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 |
|---|---|---|---|---|---|---|---|---|
// <auto-generated>
// Auto-generated by StoneAPI, do not modify.
// </auto-generated>
namespace Dropbox.Api.Sharing
{
using sys = System;
using col = System.Collections.Generic;
using re = System.Text.RegularExpressions;
using enc = Dropbox.Api.Stone;
/// <summary>
/// <para>Properties of the shared folder.</para>
/// </summary>
/// <seealso cref="SharedFolderMetadata" />
public class SharedFolderMetadataBase
{
#pragma warning disable 108
/// <summary>
/// <para>The encoder instance.</para>
/// </summary>
internal static enc.StructEncoder<SharedFolderMetadataBase> Encoder = new SharedFolderMetadataBaseEncoder();
/// <summary>
/// <para>The decoder instance.</para>
/// </summary>
internal static enc.StructDecoder<SharedFolderMetadataBase> Decoder = new SharedFolderMetadataBaseDecoder();
/// <summary>
/// <para>Initializes a new instance of the <see cref="SharedFolderMetadataBase" />
/// class.</para>
/// </summary>
/// <param name="accessType">The current user's access level for this shared
/// folder.</param>
/// <param name="isInsideTeamFolder">Whether this folder is inside of a team
/// folder.</param>
/// <param name="isTeamFolder">Whether this folder is a <a
/// href="https://www.dropbox.com/en/help/986">team folder</a>.</param>
/// <param name="ownerDisplayNames">The display names of the users that own the folder.
/// If the folder is part of a team folder, the display names of the team admins are
/// also included. Absent if the owner display names cannot be fetched.</param>
/// <param name="ownerTeam">The team that owns the folder. This field is not present if
/// the folder is not owned by a team.</param>
/// <param name="parentSharedFolderId">The ID of the parent shared folder. This field
/// is present only if the folder is contained within another shared folder.</param>
/// <param name="pathLower">The lower-cased full path of this shared folder. Absent for
/// unmounted folders.</param>
/// <param name="parentFolderName">Display name for the parent folder.</param>
public SharedFolderMetadataBase(AccessLevel accessType,
bool isInsideTeamFolder,
bool isTeamFolder,
col.IEnumerable<string> ownerDisplayNames = null,
global::Dropbox.Api.Users.Team ownerTeam = null,
string parentSharedFolderId = null,
string pathLower = null,
string parentFolderName = null)
{
if (accessType == null)
{
throw new sys.ArgumentNullException("accessType");
}
var ownerDisplayNamesList = enc.Util.ToList(ownerDisplayNames);
if (parentSharedFolderId != null)
{
if (!re.Regex.IsMatch(parentSharedFolderId, @"\A(?:[-_0-9a-zA-Z:]+)\z"))
{
throw new sys.ArgumentOutOfRangeException("parentSharedFolderId", @"Value should match pattern '\A(?:[-_0-9a-zA-Z:]+)\z'");
}
}
this.AccessType = accessType;
this.IsInsideTeamFolder = isInsideTeamFolder;
this.IsTeamFolder = isTeamFolder;
this.OwnerDisplayNames = ownerDisplayNamesList;
this.OwnerTeam = ownerTeam;
this.ParentSharedFolderId = parentSharedFolderId;
this.PathLower = pathLower;
this.ParentFolderName = parentFolderName;
}
/// <summary>
/// <para>Initializes a new instance of the <see cref="SharedFolderMetadataBase" />
/// class.</para>
/// </summary>
/// <remarks>This is to construct an instance of the object when
/// deserializing.</remarks>
[sys.ComponentModel.EditorBrowsable(sys.ComponentModel.EditorBrowsableState.Never)]
public SharedFolderMetadataBase()
{
}
/// <summary>
/// <para>The current user's access level for this shared folder.</para>
/// </summary>
public AccessLevel AccessType { get; protected set; }
/// <summary>
/// <para>Whether this folder is inside of a team folder.</para>
/// </summary>
public bool IsInsideTeamFolder { get; protected set; }
/// <summary>
/// <para>Whether this folder is a <a href="https://www.dropbox.com/en/help/986">team
/// folder</a>.</para>
/// </summary>
public bool IsTeamFolder { get; protected set; }
/// <summary>
/// <para>The display names of the users that own the folder. If the folder is part of
/// a team folder, the display names of the team admins are also included. Absent if
/// the owner display names cannot be fetched.</para>
/// </summary>
public col.IList<string> OwnerDisplayNames { get; protected set; }
/// <summary>
/// <para>The team that owns the folder. This field is not present if the folder is not
/// owned by a team.</para>
/// </summary>
public global::Dropbox.Api.Users.Team OwnerTeam { get; protected set; }
/// <summary>
/// <para>The ID of the parent shared folder. This field is present only if the folder
/// is contained within another shared folder.</para>
/// </summary>
public string ParentSharedFolderId { get; protected set; }
/// <summary>
/// <para>The lower-cased full path of this shared folder. Absent for unmounted
/// folders.</para>
/// </summary>
public string PathLower { get; protected set; }
/// <summary>
/// <para>Display name for the parent folder.</para>
/// </summary>
public string ParentFolderName { get; protected set; }
#region Encoder class
/// <summary>
/// <para>Encoder for <see cref="SharedFolderMetadataBase" />.</para>
/// </summary>
private class SharedFolderMetadataBaseEncoder : enc.StructEncoder<SharedFolderMetadataBase>
{
/// <summary>
/// <para>Encode fields of given value.</para>
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public override void EncodeFields(SharedFolderMetadataBase value, enc.IJsonWriter writer)
{
WriteProperty("access_type", value.AccessType, writer, global::Dropbox.Api.Sharing.AccessLevel.Encoder);
WriteProperty("is_inside_team_folder", value.IsInsideTeamFolder, writer, enc.BooleanEncoder.Instance);
WriteProperty("is_team_folder", value.IsTeamFolder, writer, enc.BooleanEncoder.Instance);
if (value.OwnerDisplayNames.Count > 0)
{
WriteListProperty("owner_display_names", value.OwnerDisplayNames, writer, enc.StringEncoder.Instance);
}
if (value.OwnerTeam != null)
{
WriteProperty("owner_team", value.OwnerTeam, writer, global::Dropbox.Api.Users.Team.Encoder);
}
if (value.ParentSharedFolderId != null)
{
WriteProperty("parent_shared_folder_id", value.ParentSharedFolderId, writer, enc.StringEncoder.Instance);
}
if (value.PathLower != null)
{
WriteProperty("path_lower", value.PathLower, writer, enc.StringEncoder.Instance);
}
if (value.ParentFolderName != null)
{
WriteProperty("parent_folder_name", value.ParentFolderName, writer, enc.StringEncoder.Instance);
}
}
}
#endregion
#region Decoder class
/// <summary>
/// <para>Decoder for <see cref="SharedFolderMetadataBase" />.</para>
/// </summary>
private class SharedFolderMetadataBaseDecoder : enc.StructDecoder<SharedFolderMetadataBase>
{
/// <summary>
/// <para>Create a new instance of type <see cref="SharedFolderMetadataBase"
/// />.</para>
/// </summary>
/// <returns>The struct instance.</returns>
protected override SharedFolderMetadataBase Create()
{
return new SharedFolderMetadataBase();
}
/// <summary>
/// <para>Set given field.</para>
/// </summary>
/// <param name="value">The field value.</param>
/// <param name="fieldName">The field name.</param>
/// <param name="reader">The json reader.</param>
protected override void SetField(SharedFolderMetadataBase value, string fieldName, enc.IJsonReader reader)
{
switch (fieldName)
{
case "access_type":
value.AccessType = global::Dropbox.Api.Sharing.AccessLevel.Decoder.Decode(reader);
break;
case "is_inside_team_folder":
value.IsInsideTeamFolder = enc.BooleanDecoder.Instance.Decode(reader);
break;
case "is_team_folder":
value.IsTeamFolder = enc.BooleanDecoder.Instance.Decode(reader);
break;
case "owner_display_names":
value.OwnerDisplayNames = ReadList<string>(reader, enc.StringDecoder.Instance);
break;
case "owner_team":
value.OwnerTeam = global::Dropbox.Api.Users.Team.Decoder.Decode(reader);
break;
case "parent_shared_folder_id":
value.ParentSharedFolderId = enc.StringDecoder.Instance.Decode(reader);
break;
case "path_lower":
value.PathLower = enc.StringDecoder.Instance.Decode(reader);
break;
case "parent_folder_name":
value.ParentFolderName = enc.StringDecoder.Instance.Decode(reader);
break;
default:
reader.Skip();
break;
}
}
}
#endregion
}
}
| 43.99187 | 143 | 0.55803 | [
"MIT"
] | AlirezaMaddah/dropbox-sdk-dotnet | dropbox-sdk-dotnet/Dropbox.Api/Generated/Sharing/SharedFolderMetadataBase.cs | 10,822 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Response
{
/// <summary>
/// AlipayOpenMiniDataSummaryQueryResponse.
/// </summary>
public class AlipayOpenMiniDataSummaryQueryResponse : AlipayResponse
{
/// <summary>
/// 页面访问次数
/// </summary>
[JsonPropertyName("app_pv")]
public long AppPv { get; set; }
/// <summary>
/// 当日使用人数
/// </summary>
[JsonPropertyName("app_uv")]
public long AppUv { get; set; }
/// <summary>
/// 人均停留时长
/// </summary>
[JsonPropertyName("avg_stay_time_per_user")]
public long AvgStayTimePerUser { get; set; }
/// <summary>
/// 次均停留时长
/// </summary>
[JsonPropertyName("avg_stay_time_per_visit")]
public long AvgStayTimePerVisit { get; set; }
/// <summary>
/// 累计使用次数
/// </summary>
[JsonPropertyName("launch_cnt")]
public long LaunchCnt { get; set; }
/// <summary>
/// 累计使用次数
/// </summary>
[JsonPropertyName("launch_cnt_dst")]
public long LaunchCntDst { get; set; }
/// <summary>
/// 新增用户数
/// </summary>
[JsonPropertyName("new_user_cnt")]
public long NewUserCnt { get; set; }
/// <summary>
/// 当日分享次数
/// </summary>
[JsonPropertyName("share_cnt")]
public long ShareCnt { get; set; }
/// <summary>
/// 累计分享次数
/// </summary>
[JsonPropertyName("share_cnt_dst")]
public long ShareCntDst { get; set; }
/// <summary>
/// 当日分享人数
/// </summary>
[JsonPropertyName("share_user_cnt")]
public long ShareUserCnt { get; set; }
/// <summary>
/// 累计分享人数
/// </summary>
[JsonPropertyName("share_user_cnt_dst")]
public long ShareUserCntDst { get; set; }
/// <summary>
/// 30日活跃人数
/// </summary>
[JsonPropertyName("user_cnt_30_d")]
public long UserCnt30D { get; set; }
/// <summary>
/// 7日活跃人数
/// </summary>
[JsonPropertyName("user_cnt_7_d")]
public long UserCnt7D { get; set; }
/// <summary>
/// 累计使用人数
/// </summary>
[JsonPropertyName("user_cnt_dst")]
public long UserCntDst { get; set; }
}
}
| 25.557895 | 72 | 0.515239 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Response/AlipayOpenMiniDataSummaryQueryResponse.cs | 2,592 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Sophia.Recommending.RecommendationStraregies.ChrevRecommendationStrategy
{
public class ChrevMetaCandidateInfo : IMetaCandidateInfo
{
public int GlobalTotalReviews { get; set; }
public int GlobalTotalCommits { get; set; }
public int LocalTotalReviews { get; set; }
public int LocalTotalCommits { get; set; }
public int TotalTouchedFiles { get; set; }
public int TotalNewFiles { get; set; }
public int TotalActiveMonths { get; set; }
public object TotalModifiedFiles { get; internal set; }
public object TotalReviewedFiles { get; internal set; }
}
}
| 27.615385 | 82 | 0.688022 | [
"MIT"
] | CESEL/Sofia | src/Sofia.Recommending/RecommendationStraregies/ChrevRecommendationStrategy/ChrevMetaCandidateInfo.cs | 720 | 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 lightsail-2016-11-28.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.Lightsail.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Lightsail.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for UnauthenticatedException Object
/// </summary>
public class UnauthenticatedExceptionUnmarshaller : IErrorResponseUnmarshaller<UnauthenticatedException, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public UnauthenticatedException Unmarshall(JsonUnmarshallerContext context)
{
return this.Unmarshall(context, new Amazon.Runtime.Internal.ErrorResponse());
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <param name="errorResponse"></param>
/// <returns></returns>
public UnauthenticatedException Unmarshall(JsonUnmarshallerContext context, Amazon.Runtime.Internal.ErrorResponse errorResponse)
{
context.Read();
UnauthenticatedException unmarshalledObject = new UnauthenticatedException(errorResponse.Message, errorResponse.InnerException,
errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("code", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Code = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("docs", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Docs = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("tip", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Tip = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static UnauthenticatedExceptionUnmarshaller _instance = new UnauthenticatedExceptionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static UnauthenticatedExceptionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.330097 | 139 | 0.63485 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/Lightsail/Generated/Model/Internal/MarshallTransformations/UnauthenticatedExceptionUnmarshaller.cs | 3,845 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1/schema/predict/params/image_segmentation.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.AIPlatform.V1.Schema.Predict.Params {
/// <summary>Holder for reflection information generated from google/cloud/aiplatform/v1/schema/predict/params/image_segmentation.proto</summary>
public static partial class ImageSegmentationReflection {
#region Descriptor
/// <summary>File descriptor for google/cloud/aiplatform/v1/schema/predict/params/image_segmentation.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ImageSegmentationReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cklnb29nbGUvY2xvdWQvYWlwbGF0Zm9ybS92MS9zY2hlbWEvcHJlZGljdC9w",
"YXJhbXMvaW1hZ2Vfc2VnbWVudGF0aW9uLnByb3RvEjBnb29nbGUuY2xvdWQu",
"YWlwbGF0Zm9ybS52MS5zY2hlbWEucHJlZGljdC5wYXJhbXMaHGdvb2dsZS9h",
"cGkvYW5ub3RhdGlvbnMucHJvdG8iQQohSW1hZ2VTZWdtZW50YXRpb25QcmVk",
"aWN0aW9uUGFyYW1zEhwKFGNvbmZpZGVuY2VfdGhyZXNob2xkGAEgASgCQtcC",
"CjRjb20uZ29vZ2xlLmNsb3VkLmFpcGxhdGZvcm0udjEuc2NoZW1hLnByZWRp",
"Y3QucGFyYW1zQiZJbWFnZVNlZ21lbnRhdGlvblByZWRpY3Rpb25QYXJhbXNQ",
"cm90b1ABWlZnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlz",
"L2Nsb3VkL2FpcGxhdGZvcm0vdjEvc2NoZW1hL3ByZWRpY3QvcGFyYW1zO3Bh",
"cmFtc6oCMEdvb2dsZS5DbG91ZC5BSVBsYXRmb3JtLlYxLlNjaGVtYS5QcmVk",
"aWN0LlBhcmFtc8oCMEdvb2dsZVxDbG91ZFxBSVBsYXRmb3JtXFYxXFNjaGVt",
"YVxQcmVkaWN0XFBhcmFtc+oCNkdvb2dsZTo6Q2xvdWQ6OkFJUGxhdGZvcm06",
"OlYxOjpTY2hlbWE6OlByZWRpY3Q6OlBhcmFtc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.AIPlatform.V1.Schema.Predict.Params.ImageSegmentationPredictionParams), global::Google.Cloud.AIPlatform.V1.Schema.Predict.Params.ImageSegmentationPredictionParams.Parser, new[]{ "ConfidenceThreshold" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Prediction model parameters for Image Segmentation.
/// </summary>
public sealed partial class ImageSegmentationPredictionParams : pb::IMessage<ImageSegmentationPredictionParams>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<ImageSegmentationPredictionParams> _parser = new pb::MessageParser<ImageSegmentationPredictionParams>(() => new ImageSegmentationPredictionParams());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<ImageSegmentationPredictionParams> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.AIPlatform.V1.Schema.Predict.Params.ImageSegmentationReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ImageSegmentationPredictionParams() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ImageSegmentationPredictionParams(ImageSegmentationPredictionParams other) : this() {
confidenceThreshold_ = other.confidenceThreshold_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ImageSegmentationPredictionParams Clone() {
return new ImageSegmentationPredictionParams(this);
}
/// <summary>Field number for the "confidence_threshold" field.</summary>
public const int ConfidenceThresholdFieldNumber = 1;
private float confidenceThreshold_;
/// <summary>
/// When the model predicts category of pixels of the image, it will only
/// provide predictions for pixels that it is at least this much confident
/// about. All other pixels will be classified as background. Default value is
/// 0.5.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public float ConfidenceThreshold {
get { return confidenceThreshold_; }
set {
confidenceThreshold_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as ImageSegmentationPredictionParams);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(ImageSegmentationPredictionParams other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(ConfidenceThreshold, other.ConfidenceThreshold)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (ConfidenceThreshold != 0F) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(ConfidenceThreshold);
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (ConfidenceThreshold != 0F) {
output.WriteRawTag(13);
output.WriteFloat(ConfidenceThreshold);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (ConfidenceThreshold != 0F) {
output.WriteRawTag(13);
output.WriteFloat(ConfidenceThreshold);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (ConfidenceThreshold != 0F) {
size += 1 + 4;
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(ImageSegmentationPredictionParams other) {
if (other == null) {
return;
}
if (other.ConfidenceThreshold != 0F) {
ConfidenceThreshold = other.ConfidenceThreshold;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 13: {
ConfidenceThreshold = input.ReadFloat();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 13: {
ConfidenceThreshold = input.ReadFloat();
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| 40.628458 | 296 | 0.714661 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.AIPlatform.V1/Google.Cloud.AIPlatform.V1/Schema/Predict/Params/ImageSegmentation.g.cs | 10,279 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("NLP-With-Dispatch-Bot")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("NLP-With-Dispatch-Bot")]
[assembly: System.Reflection.AssemblyTitleAttribute("NLP-With-Dispatch-Bot")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 42.208333 | 80 | 0.649556 | [
"MIT"
] | kenguil/Bot4.6 | 14.nlp-with-dispatch/obj/Debug/netcoreapp3.1/NLP-With-Dispatch-Bot.AssemblyInfo.cs | 1,013 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
namespace Microsoft.MixedReality.OpenXR
{
public abstract class Disposable : IDisposable
{
protected bool disposedValue { get; private set; }
protected virtual void DisposeManagedResources()
{
// Dispose managed state (managed objects)
}
protected virtual void DisposeNativeResources()
{
// Free unmanaged resources (unmanaged objects) and override finalizer
// Set large fields to null
}
private void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
DisposeManagedResources();
}
DisposeNativeResources();
disposedValue = true;
}
}
// Override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
~Disposable()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: false);
}
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
System.GC.SuppressFinalize(this);
}
}
} | 27.72549 | 100 | 0.557992 | [
"MIT"
] | YitingLiu97/Lifeline2022 | MSBuild/PackagesCopy/com.microsoft.mixedreality.openxr/Runtime/Utilities/Disposable.cs | 1,414 | C# |
using System;
using System.ComponentModel;
namespace Common.Enums
{
[Serializable]
public enum DayOfTheWeek : int
{
/// <summary>
/// Monday
/// </summary>
[Description("Monday")]
Monday = 0,
/// <summary>
/// Tuesday
/// </summary>
[Description("Tuesday")]
Tuesday = 1,
/// <summary>
/// Wednesday
/// </summary>
[Description("Wednesday")]
Wednesday = 2,
/// <summary>
/// Thursday
/// </summary>
[Description("Thursday")]
Thursday = 3,
/// <summary>
/// Friday
/// </summary>
[Description("Friday")]
Friday = 4,
/// <summary>
/// Saturday
/// </summary>
[Description("Saturday")]
Saturday = 5,
/// <summary>
/// Sunday
/// </summary>
[Description("Sunday")]
Sunday = 6,
}
} | 19.196078 | 34 | 0.434116 | [
"MIT"
] | salda8/Quant-Finance-Mngmt-System | CommonStandard/Enums/DayOfTheWeek.cs | 981 | C# |
using System;
#if !NETSTANDARD16
using System.Configuration;
#endif
namespace RomanticWeb.Configuration
{
/// <summary>Configuration element to set base Uri for.</summary>
#if NETSTANDARD16
public class BaseUriElement
{
private Uri _default;
/// <summary>Gets or sets the default base Uri.</summary>
public Uri Default
{
get { return _default; }
set { UriValidator.Default.Validate(_default = value); }
}
}
#else
public class BaseUriElement : ConfigurationElement
{
private const string DefaultUriAttributeName = "default";
/// <summary>Gets or sets the default base Uri.</summary>
[ConfigurationProperty(DefaultUriAttributeName)]
[UriValidator]
public Uri Default
{
get { return (Uri)this[DefaultUriAttributeName]; }
set { this[DefaultUriAttributeName] = value; }
}
}
#endif
}
| 27.444444 | 70 | 0.6083 | [
"BSD-3-Clause"
] | alien-mcl/RomanticWeb | RomanticWeb/Configuration/BaseUriElement.cs | 990 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
// Modified for Intuit's Oauth2 implementation
using Intuit.Ipp.OAuth2PlatformClient;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net;
namespace Intuit.Ipp.OAuth2PlatformClient
{
/// <summary>
/// DiscoveryResponse class to handle response from Discovery call
/// </summary>
public class DiscoveryResponse
{
/// <summary>
/// Raw
/// </summary>
public string Raw { get; }
/// <summary>
/// Json
/// </summary>
public JObject Json { get; }
/// <summary>
/// Is error
/// </summary>
public bool IsError { get; } = false;
/// <summary>
/// Http status code
/// </summary>
public HttpStatusCode StatusCode { get; }
/// <summary>
/// Error
/// </summary>
public string Error { get; }
/// <summary>
/// Error Type
/// </summary>
public ResponseErrorType ErrorType { get; set; } = ResponseErrorType.None;
/// <summary>
/// Exception
/// </summary>
public System.Exception Exception { get; }
/// <summary>
/// Key Set
/// </summary>
public JsonWebKeySet KeySet { get; set; }
/// <summary>
/// Handles success raw response from Token api call
/// </summary>
/// <param name="raw">raw</param>
/// <param name="policy">policy</param>
public DiscoveryResponse(string raw, DiscoveryPolicy policy = null)
{
if (policy == null) policy = new DiscoveryPolicy();
IsError = false;
StatusCode = HttpStatusCode.OK;
Raw = raw;
try
{
Json = JObject.Parse(raw);
//Remove validation as it impacts e2e testing
var validationError = Validate(policy);
if (!string.IsNullOrEmpty(validationError))
{
IsError = true;
Json = null;
ErrorType = ResponseErrorType.PolicyViolation;
Error = validationError;
}
}
catch (System.Exception ex)
{
IsError = true;
ErrorType = ResponseErrorType.Exception;
Error = ex.Message;
Exception = ex;
}
}
/// <summary>
/// Handles exception response from Token api call
/// </summary>
/// <param name="statusCode">statusCode</param>
/// <param name="reason">reason</param>
public DiscoveryResponse(HttpStatusCode statusCode, string reason)
{
IsError = true;
ErrorType = ResponseErrorType.Http;
StatusCode = statusCode;
Error = reason;
}
/// <summary>
/// Handles exception response from Token api call
/// </summary>
/// <param name="exception">exception</param>
/// <param name="errorMessage">errorMessage</param>
public DiscoveryResponse(System.Exception exception, string errorMessage)
{
IsError = true;
ErrorType = ResponseErrorType.Exception;
Exception = exception;
Error = $"{errorMessage}: {exception.Message}";
}
/// <summary>
/// Strongly typed getters
/// </summary>
public string Issuer => TryGetString(OidcConstants.Discovery.Issuer);
public string AuthorizeEndpoint => TryGetString(OidcConstants.Discovery.AuthorizationEndpoint);
public string TokenEndpoint => TryGetString(OidcConstants.Discovery.TokenEndpoint);
public string UserInfoEndpoint => TryGetString(OidcConstants.Discovery.UserInfoEndpoint);
public string RevocationEndpoint => TryGetString(OidcConstants.Discovery.RevocationEndpoint);
public string JwksUri => TryGetString(OidcConstants.Discovery.JwksUri);
public IEnumerable<string> ResponseTypesSupported => TryGetStringArray(OidcConstants.Discovery.ResponseTypesSupported);
public IEnumerable<string> SubjectTypesSupported => TryGetStringArray(OidcConstants.Discovery.SubjectTypesSupported);
public IEnumerable<string> ScopesSupported => TryGetStringArray(OidcConstants.Discovery.ScopesSupported);
public IEnumerable<string> IdTokenSigningAlgValuesSupported => TryGetStringArray(OidcConstants.Discovery.IdTokenSigningAlgValuesSupported);
public IEnumerable<string> TokenEndpointAuthenticationMethodsSupported => TryGetStringArray(OidcConstants.Discovery.TokenEndpointAuthenticationMethodsSupported);
public IEnumerable<string> ClaimsSupported => TryGetStringArray(OidcConstants.Discovery.ClaimsSupported);
/// <summary>
/// Generic getters
/// </summary>
public JToken TryGetValue(string name) => Json.TryGetValue(name);
public string TryGetString(string name) => Json.TryGetString(name);
public bool? TryGetBoolean(string name) => Json.TryGetBoolean(name);
public IEnumerable<string> TryGetStringArray(string name) => Json.TryGetStringArray(name);
/// <summary>
/// Validates Discovery policy
/// </summary>
/// <param name="policy">policy</param>
/// <returns>string</returns>
private string Validate(DiscoveryPolicy policy = null)
{
if (policy.ValidateIssuerName)
{
if (string.IsNullOrWhiteSpace(Issuer)) return "Issuer name is missing";
if (Issuer == OidcConstants.Discovery.IssuerUrl)//do this check only for prod/sandbox url as partners may test with e2e
{
var isValid = ValidateIssuerName(Issuer.RemoveTrailingSlash(), policy.Authority.RemoveTrailingSlash());
if (!isValid) return "Issuer name does not match authority: " + Issuer;
}
}
var error = ValidateEndpoints(Json, policy);
if (!string.IsNullOrEmpty(error)) return error;
return string.Empty;
}
/// <summary>
/// Validates Issuer Name
/// </summary>
/// <param name="issuer">issuer</param>
/// <param name="authority">authority</param>
/// <returns>bool</returns>
public bool ValidateIssuerName(string issuer, string authority)
{
return string.Equals(issuer, authority, StringComparison.Ordinal);
}
/// <summary>
/// Validates Endpoints
/// </summary>
/// <param name="json">json</param>
/// <param name="policy">policy</param>
/// <returns>bool</returns>
public string ValidateEndpoints(JObject json, DiscoveryPolicy policy)//policy for later use
{
//var authorityHost = new Uri(policy.Authority).Authority;
foreach (var element in json)
{
if (element.Key.EndsWith("Endpoint", StringComparison.OrdinalIgnoreCase) ||
element.Key.Equals(OidcConstants.Discovery.JwksUri, StringComparison.OrdinalIgnoreCase))
{
var endpoint = element.Value.ToString();
Uri uri;
var isValidUri = Uri.TryCreate(endpoint, UriKind.Absolute, out uri);
if (!isValidUri)//Uri not valid
{
return $"Malformed endpoint: {endpoint}";
}
if (!DiscoveryUrlHelper.IsValidScheme(uri))//Scheme not valid
{
return $"Malformed endpoint: {endpoint}";
}
if (!DiscoveryUrlHelper.IsSecureScheme(uri, policy))//Scheme not secure
{
return $"Endpoint does not use HTTPS: {endpoint}";
}
}
}
return string.Empty;
}
}
} | 35.815451 | 169 | 0.571959 | [
"Apache-2.0"
] | ANSIOS-X9SAN-iOS-XR/QuickBooks-V3-DotNET-SDK | IPPDotNetDevKitCSV3/Code/Intuit.Ipp.OAuth2PlatformClient/Client/DiscoveryResponse.cs | 8,347 | C# |
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using System.Linq;
// ReSharper disable InconsistentNaming
// ReSharper disable MemberHidesStaticFromOuterClass
namespace SixLabors.ImageSharp.Tests
{
/// <summary>
/// Class that contains all the relative test image paths in the TestImages/Formats directory.
/// Use with <see cref="WithFileAttribute"/>, <see cref="WithFileCollectionAttribute"/>.
/// </summary>
public static class TestImages
{
public static class Png
{
public const string P1 = "Png/pl.png";
public const string Pd = "Png/pd.png";
public const string Blur = "Png/blur.png";
public const string Indexed = "Png/indexed.png";
public const string Splash = "Png/splash.png";
public const string Cross = "Png/cross.png";
public const string Powerpoint = "Png/pp.png";
public const string SplashInterlaced = "Png/splash-interlaced.png";
public const string Interlaced = "Png/interlaced.png";
public const string Palette8Bpp = "Png/palette-8bpp.png";
public const string Bpp1 = "Png/bpp1.png";
public const string Gray4Bpp = "Png/gray_4bpp.png";
public const string L16Bit = "Png/gray-16.png";
public const string GrayA8Bit = "Png/gray-alpha-8.png";
public const string GrayA8BitInterlaced = "Png/rollsroyce.png";
public const string GrayAlpha1BitInterlaced = "Png/iftbbn0g01.png";
public const string GrayAlpha2BitInterlaced = "Png/iftbbn0g02.png";
public const string Gray4BitInterlaced = "Png/iftbbn0g04.png";
public const string GrayAlpha16Bit = "Png/gray-alpha-16.png";
public const string GrayTrns16BitInterlaced = "Png/gray-16-tRNS-interlaced.png";
public const string Rgb24BppTrans = "Png/rgb-8-tRNS.png";
public const string Rgb48Bpp = "Png/rgb-48bpp.png";
public const string Rgb48BppInterlaced = "Png/rgb-48bpp-interlaced.png";
public const string Rgb48BppTrans = "Png/rgb-16-tRNS.png";
public const string Rgba64Bpp = "Png/rgb-16-alpha.png";
public const string ColorsSaturationLightness = "Png/colors-saturation-lightness.png";
public const string CalliphoraPartial = "Png/CalliphoraPartial.png";
public const string CalliphoraPartialGrayscale = "Png/CalliphoraPartialGrayscale.png";
public const string Bike = "Png/Bike.png";
public const string BikeGrayscale = "Png/BikeGrayscale.png";
public const string SnakeGame = "Png/SnakeGame.png";
public const string Icon = "Png/icon.png";
public const string Kaboom = "Png/kaboom.png";
public const string PDSrc = "Png/pd-source.png";
public const string PDDest = "Png/pd-dest.png";
public const string Gray1BitTrans = "Png/gray-1-trns.png";
public const string Gray2BitTrans = "Png/gray-2-tRNS.png";
public const string Gray4BitTrans = "Png/gray-4-tRNS.png";
public const string L8BitTrans = "Png/gray-8-tRNS.png";
public const string LowColorVariance = "Png/low-variance.png";
public const string PngWithMetadata = "Png/PngWithMetaData.png";
public const string InvalidTextData = "Png/InvalidTextData.png";
public const string David = "Png/david.png";
// Filtered test images from http://www.schaik.com/pngsuite/pngsuite_fil_png.html
public const string Filter0 = "Png/filter0.png";
public const string Filter1 = "Png/filter1.png";
public const string Filter2 = "Png/filter2.png";
public const string Filter3 = "Png/filter3.png";
public const string Filter4 = "Png/filter4.png";
// Paletted images also from http://www.schaik.com/pngsuite/pngsuite_fil_png.html
public const string PalettedTwoColor = "Png/basn3p01.png";
public const string PalettedFourColor = "Png/basn3p02.png";
public const string PalettedSixteenColor = "Png/basn3p04.png";
public const string Paletted256Colors = "Png/basn3p08.png";
// Filter changing per scanline
public const string FilterVar = "Png/filterVar.png";
public const string VimImage1 = "Png/vim16x16_1.png";
public const string VimImage2 = "Png/vim16x16_2.png";
public const string VersioningImage1 = "Png/versioning-1_1.png";
public const string VersioningImage2 = "Png/versioning-1_2.png";
public const string Banner7Adam7InterlaceMode = "Png/banner7-adam.png";
public const string Banner8Index = "Png/banner8-index.png";
public const string Ratio1x4 = "Png/ratio-1x4.png";
public const string Ratio4x1 = "Png/ratio-4x1.png";
public const string Ducky = "Png/ducky.png";
public const string Rainbow = "Png/rainbow.png";
public const string Bradley01 = "Png/Bradley01.png";
public const string Bradley02 = "Png/Bradley02.png";
// Issue 1014: https://github.com/SixLabors/ImageSharp/issues/1014
public const string Issue1014_1 = "Png/issues/Issue_1014_1.png";
public const string Issue1014_2 = "Png/issues/Issue_1014_2.png";
public const string Issue1014_3 = "Png/issues/Issue_1014_3.png";
public const string Issue1014_4 = "Png/issues/Issue_1014_4.png";
public const string Issue1014_5 = "Png/issues/Issue_1014_5.png";
public const string Issue1014_6 = "Png/issues/Issue_1014_6.png";
// Issue 1127: https://github.com/SixLabors/ImageSharp/issues/1127
public const string Issue1127 = "Png/issues/Issue_1127.png";
// Issue 1177: https://github.com/SixLabors/ImageSharp/issues/1177
public const string Issue1177_1 = "Png/issues/Issue_1177_1.png";
public const string Issue1177_2 = "Png/issues/Issue_1177_2.png";
// Issue 935: https://github.com/SixLabors/ImageSharp/issues/935
public const string Issue935 = "Png/issues/Issue_935.png";
public static class Bad
{
public const string MissingDataChunk = "Png/xdtn0g01.png";
public const string CorruptedChunk = "Png/big-corrupted-chunk.png";
// Zlib errors.
public const string ZlibOverflow = "Png/zlib-overflow.png";
public const string ZlibOverflow2 = "Png/zlib-overflow2.png";
public const string ZlibZtxtBadHeader = "Png/zlib-ztxt-bad-header.png";
// Odd chunk lengths
public const string ChunkLength1 = "Png/chunklength1.png";
public const string ChunkLength2 = "Png/chunklength2.png";
// Issue 1047: https://github.com/SixLabors/ImageSharp/issues/1047
public const string Issue1047_BadEndChunk = "Png/issues/Issue_1047.png";
// Issue 410: https://github.com/SixLabors/ImageSharp/issues/410
public const string Issue410_MalformedApplePng = "Png/issues/Issue_410.png";
// Bad bit depth.
public const string BitDepthZero = "Png/xd0n2c08.png";
public const string BitDepthThree = "Png/xd3n2c08.png";
// Invalid color type.
public const string ColorTypeOne = "Png/xc1n0g08.png";
public const string ColorTypeNine = "Png/xc9n2c08.png";
}
public static readonly string[] All =
{
P1, Pd, Blur, Splash, Cross,
Powerpoint, SplashInterlaced, Interlaced,
Filter0, Filter1, Filter2, Filter3, Filter4,
FilterVar, VimImage1, VimImage2, VersioningImage1,
VersioningImage2, Ratio4x1, Ratio1x4
};
}
public static class Jpeg
{
public static class Progressive
{
public const string Fb = "Jpg/progressive/fb.jpg";
public const string Progress = "Jpg/progressive/progress.jpg";
public const string Festzug = "Jpg/progressive/Festzug.jpg";
public static class Bad
{
public const string BadEOF = "Jpg/progressive/BadEofProgressive.jpg";
public const string ExifUndefType = "Jpg/progressive/ExifUndefType.jpg";
}
public static readonly string[] All = { Fb, Progress, Festzug };
}
public static class Baseline
{
public static class Bad
{
public const string BadEOF = "Jpg/baseline/badeof.jpg";
public const string BadRST = "Jpg/baseline/badrst.jpg";
}
public const string Cmyk = "Jpg/baseline/cmyk.jpg";
public const string Exif = "Jpg/baseline/exif.jpg";
public const string Floorplan = "Jpg/baseline/Floorplan.jpg";
public const string Calliphora = "Jpg/baseline/Calliphora.jpg";
public const string Ycck = "Jpg/baseline/ycck.jpg";
public const string Turtle420 = "Jpg/baseline/turtle.jpg";
public const string GammaDalaiLamaGray = "Jpg/baseline/gamma_dalai_lama_gray.jpg";
public const string Hiyamugi = "Jpg/baseline/Hiyamugi.jpg";
public const string Snake = "Jpg/baseline/Snake.jpg";
public const string Lake = "Jpg/baseline/Lake.jpg";
public const string Jpeg400 = "Jpg/baseline/jpeg400jfif.jpg";
public const string Jpeg420Exif = "Jpg/baseline/jpeg420exif.jpg";
public const string Jpeg444 = "Jpg/baseline/jpeg444.jpg";
public const string Jpeg420Small = "Jpg/baseline/jpeg420small.jpg";
public const string Testorig420 = "Jpg/baseline/testorig.jpg";
public const string MultiScanBaselineCMYK = "Jpg/baseline/MultiScanBaselineCMYK.jpg";
public const string Ratio1x1 = "Jpg/baseline/ratio-1x1.jpg";
public const string LowContrast = "Jpg/baseline/AsianCarvingLowContrast.jpg";
public const string Testorig12bit = "Jpg/baseline/testorig12.jpg";
public const string YcckSubsample1222 = "Jpg/baseline/ycck-subsample-1222.jpg";
public const string Iptc = "Jpg/baseline/iptc.jpg";
public const string App13WithEmptyIptc = "Jpg/baseline/iptc-psAPP13-wIPTCempty.jpg";
public const string HistogramEqImage = "Jpg/baseline/640px-Unequalized_Hawkes_Bay_NZ.jpg";
public static readonly string[] All =
{
Cmyk, Ycck, Exif, Floorplan,
Calliphora, Turtle420, GammaDalaiLamaGray,
Hiyamugi, Jpeg400, Jpeg420Exif, Jpeg444,
Ratio1x1, Testorig12bit, YcckSubsample1222
};
}
public static class Issues
{
public const string CriticalEOF214 = "Jpg/issues/Issue214-CriticalEOF.jpg";
public const string MissingFF00ProgressiveGirl159 = "Jpg/issues/Issue159-MissingFF00-Progressive-Girl.jpg";
public const string MissingFF00ProgressiveBedroom159 = "Jpg/issues/Issue159-MissingFF00-Progressive-Bedroom.jpg";
public const string BadCoeffsProgressive178 = "Jpg/issues/Issue178-BadCoeffsProgressive-Lemon.jpg";
public const string BadZigZagProgressive385 = "Jpg/issues/Issue385-BadZigZag-Progressive.jpg";
public const string MultiHuffmanBaseline394 = "Jpg/issues/Issue394-MultiHuffmanBaseline-Speakers.jpg";
public const string NoEoiProgressive517 = "Jpg/issues/Issue517-No-EOI-Progressive.jpg";
public const string BadRstProgressive518 = "Jpg/issues/Issue518-Bad-RST-Progressive.jpg";
public const string InvalidCast520 = "Jpg/issues/Issue520-InvalidCast.jpg";
public const string DhtHasWrongLength624 = "Jpg/issues/Issue624-DhtHasWrongLength-Progressive-N.jpg";
public const string ExifDecodeOutOfRange694 = "Jpg/issues/Issue694-Decode-Exif-OutOfRange.jpg";
public const string InvalidEOI695 = "Jpg/issues/Issue695-Invalid-EOI.jpg";
public const string ExifResizeOutOfRange696 = "Jpg/issues/Issue696-Resize-Exif-OutOfRange.jpg";
public const string InvalidAPP0721 = "Jpg/issues/Issue721-InvalidAPP0.jpg";
public const string OrderedInterleavedProgressive723A = "Jpg/issues/Issue723-Ordered-Interleaved-Progressive-A.jpg";
public const string OrderedInterleavedProgressive723B = "Jpg/issues/Issue723-Ordered-Interleaved-Progressive-B.jpg";
public const string OrderedInterleavedProgressive723C = "Jpg/issues/Issue723-Ordered-Interleaved-Progressive-C.jpg";
public const string ExifGetString750Transform = "Jpg/issues/issue750-exif-tranform.jpg";
public const string ExifGetString750Load = "Jpg/issues/issue750-exif-load.jpg";
public const string IncorrectQuality845 = "Jpg/issues/Issue845-Incorrect-Quality99.jpg";
public const string IncorrectColorspace855 = "Jpg/issues/issue855-incorrect-colorspace.jpg";
public const string IncorrectResize1006 = "Jpg/issues/issue1006-incorrect-resize.jpg";
public const string ExifResize1049 = "Jpg/issues/issue1049-exif-resize.jpg";
public const string BadSubSampling1076 = "Jpg/issues/issue-1076-invalid-subsampling.jpg";
public const string IdentifyMultiFrame1211 = "Jpg/issues/issue-1221-identify-multi-frame.jpg";
public static class Fuzz
{
public const string NullReferenceException797 = "Jpg/issues/fuzz/Issue797-NullReferenceException.jpg";
public const string AccessViolationException798 = "Jpg/issues/fuzz/Issue798-AccessViolationException.jpg";
public const string DivideByZeroException821 = "Jpg/issues/fuzz/Issue821-DivideByZeroException.jpg";
public const string DivideByZeroException822 = "Jpg/issues/fuzz/Issue822-DivideByZeroException.jpg";
public const string NullReferenceException823 = "Jpg/issues/fuzz/Issue823-NullReferenceException.jpg";
public const string IndexOutOfRangeException824A = "Jpg/issues/fuzz/Issue824-IndexOutOfRangeException-A.jpg";
public const string IndexOutOfRangeException824B = "Jpg/issues/fuzz/Issue824-IndexOutOfRangeException-B.jpg";
public const string IndexOutOfRangeException824C = "Jpg/issues/fuzz/Issue824-IndexOutOfRangeException-C.jpg";
public const string IndexOutOfRangeException824D = "Jpg/issues/fuzz/Issue824-IndexOutOfRangeException-D.jpg";
public const string IndexOutOfRangeException824E = "Jpg/issues/fuzz/Issue824-IndexOutOfRangeException-E.jpg";
public const string IndexOutOfRangeException824F = "Jpg/issues/fuzz/Issue824-IndexOutOfRangeException-F.jpg";
public const string IndexOutOfRangeException824G = "Jpg/issues/fuzz/Issue824-IndexOutOfRangeException-G.jpg";
public const string IndexOutOfRangeException824H = "Jpg/issues/fuzz/Issue824-IndexOutOfRangeException-H.jpg";
public const string ArgumentOutOfRangeException825A = "Jpg/issues/fuzz/Issue825-ArgumentOutOfRangeException-A.jpg";
public const string ArgumentOutOfRangeException825B = "Jpg/issues/fuzz/Issue825-ArgumentOutOfRangeException-B.jpg";
public const string ArgumentOutOfRangeException825C = "Jpg/issues/fuzz/Issue825-ArgumentOutOfRangeException-C.jpg";
public const string ArgumentOutOfRangeException825D = "Jpg/issues/fuzz/Issue825-ArgumentOutOfRangeException-D.jpg";
public const string ArgumentException826A = "Jpg/issues/fuzz/Issue826-ArgumentException-A.jpg";
public const string ArgumentException826B = "Jpg/issues/fuzz/Issue826-ArgumentException-B.jpg";
public const string ArgumentException826C = "Jpg/issues/fuzz/Issue826-ArgumentException-C.jpg";
public const string AccessViolationException827 = "Jpg/issues/fuzz/Issue827-AccessViolationException.jpg";
public const string ExecutionEngineException839 = "Jpg/issues/fuzz/Issue839-ExecutionEngineException.jpg";
public const string AccessViolationException922 = "Jpg/issues/fuzz/Issue922-AccessViolationException.jpg";
}
}
public static readonly string[] All = Baseline.All.Concat(Progressive.All).ToArray();
public static class BenchmarkSuite
{
public const string Jpeg400_SmallMonochrome = Baseline.Jpeg400;
public const string Jpeg420Exif_MidSizeYCbCr = Baseline.Jpeg420Exif;
public const string Lake_Small444YCbCr = Baseline.Lake;
// A few large images from the "issues" set are actually very useful for benchmarking:
public const string MissingFF00ProgressiveBedroom159_MidSize420YCbCr = Issues.MissingFF00ProgressiveBedroom159;
public const string BadRstProgressive518_Large444YCbCr = Issues.BadRstProgressive518;
public const string ExifGetString750Transform_Huge420YCbCr = Issues.ExifGetString750Transform;
}
}
public static class Bmp
{
// Note: The inverted images have been generated by altering the BitmapInfoHeader using a hex editor.
// As such, the expected pixel output will be the reverse of the unaltered equivalent images.
public const string Car = "Bmp/Car.bmp";
public const string F = "Bmp/F.bmp";
public const string NegHeight = "Bmp/neg_height.bmp";
public const string CoreHeader = "Bmp/BitmapCoreHeaderQR.bmp";
public const string V5Header = "Bmp/BITMAPV5HEADER.bmp";
public const string RLE24 = "Bmp/rgb24rle24.bmp";
public const string RLE24Cut = "Bmp/rle24rlecut.bmp";
public const string RLE24Delta = "Bmp/rle24rlecut.bmp";
public const string RLE8 = "Bmp/RunLengthEncoded.bmp";
public const string RLE8Cut = "Bmp/pal8rlecut.bmp";
public const string RLE8Delta = "Bmp/pal8rletrns.bmp";
public const string Rle8Delta320240 = "Bmp/rle8-delta-320x240.bmp";
public const string Rle8Blank160120 = "Bmp/rle8-blank-160x120.bmp";
public const string RLE8Inverted = "Bmp/RunLengthEncoded-inverted.bmp";
public const string RLE4 = "Bmp/pal4rle.bmp";
public const string RLE4Cut = "Bmp/pal4rlecut.bmp";
public const string RLE4Delta = "Bmp/pal4rletrns.bmp";
public const string Rle4Delta320240 = "Bmp/rle4-delta-320x240.bmp";
public const string Bit1 = "Bmp/pal1.bmp";
public const string Bit1Pal1 = "Bmp/pal1p1.bmp";
public const string Bit4 = "Bmp/pal4.bmp";
public const string Bit8 = "Bmp/test8.bmp";
public const string Bit8Gs = "Bmp/pal8gs.bmp";
public const string Bit8Inverted = "Bmp/test8-inverted.bmp";
public const string Bit16 = "Bmp/test16.bmp";
public const string Bit16Inverted = "Bmp/test16-inverted.bmp";
public const string Bit32Rgb = "Bmp/rgb32.bmp";
public const string Bit32Rgba = "Bmp/rgba32.bmp";
public const string Rgb16 = "Bmp/rgb16.bmp";
// Note: This format can be called OS/2 BMPv1, or Windows BMPv2
public const string WinBmpv2 = "Bmp/pal8os2v1_winv2.bmp";
public const string WinBmpv3 = "Bmp/rgb24.bmp";
public const string WinBmpv4 = "Bmp/pal8v4.bmp";
public const string WinBmpv5 = "Bmp/pal8v5.bmp";
public const string Bit8Palette4 = "Bmp/pal8-0.bmp";
public const string Os2v2Short = "Bmp/pal8os2v2-16.bmp";
public const string Os2v2 = "Bmp/pal8os2v2.bmp";
public const string Os2BitmapArray = "Bmp/ba-bm.bmp";
public const string Os2BitmapArray9s = "Bmp/9S.BMP";
public const string Os2BitmapArrayDiamond = "Bmp/DIAMOND.BMP";
public const string Os2BitmapArrayMarble = "Bmp/GMARBLE.BMP";
public const string Os2BitmapArraySkater = "Bmp/SKATER.BMP";
public const string Os2BitmapArraySpade = "Bmp/SPADE.BMP";
public const string Os2BitmapArraySunflower = "Bmp/SUNFLOW.BMP";
public const string Os2BitmapArrayWarpd = "Bmp/WARPD.BMP";
public const string Os2BitmapArrayPines = "Bmp/PINES.BMP";
public const string LessThanFullSizedPalette = "Bmp/pal8os2sp.bmp";
public const string Pal8Offset = "Bmp/pal8offs.bmp";
public const string OversizedPalette = "Bmp/pal8oversizepal.bmp";
public const string Rgb24LargePalette = "Bmp/rgb24largepal.bmp";
public const string InvalidPaletteSize = "Bmp/invalidPaletteSize.bmp";
public const string Rgb24jpeg = "Bmp/rgb24jpeg.bmp";
public const string Rgb24png = "Bmp/rgb24png.bmp";
public const string Rgba32v4 = "Bmp/rgba32v4.bmp";
// Bitmap images with compression type BITFIELDS.
public const string Rgb32bfdef = "Bmp/rgb32bfdef.bmp";
public const string Rgb32bf = "Bmp/rgb32bf.bmp";
public const string Rgb16bfdef = "Bmp/rgb16bfdef.bmp";
public const string Rgb16565 = "Bmp/rgb16-565.bmp";
public const string Rgb16565pal = "Bmp/rgb16-565pal.bmp";
public const string Issue735 = "Bmp/issue735.bmp";
public const string Rgba32bf56AdobeV3 = "Bmp/rgba32h56.bmp";
public const string Rgb32h52AdobeV3 = "Bmp/rgb32h52.bmp";
public const string Rgba321010102 = "Bmp/rgba32-1010102.bmp";
public const string RgbaAlphaBitfields = "Bmp/rgba32abf.bmp";
public static readonly string[] BitFields =
{
Rgb32bfdef,
Rgb32bf,
Rgb16565,
Rgb16bfdef,
Rgb16565pal,
Issue735,
};
public static readonly string[] Miscellaneous =
{
Car,
F,
NegHeight
};
public static readonly string[] Benchmark =
{
Car,
F,
NegHeight,
CoreHeader,
V5Header,
RLE4,
RLE8,
RLE8Inverted,
Bit1,
Bit1Pal1,
Bit4,
Bit8,
Bit8Inverted,
Bit16,
Bit16Inverted,
Bit32Rgb
};
}
public static class Gif
{
public const string Rings = "Gif/rings.gif";
public const string Giphy = "Gif/giphy.gif";
public const string Cheers = "Gif/cheers.gif";
public const string Receipt = "Gif/receipt.gif";
public const string Trans = "Gif/trans.gif";
public const string Kumin = "Gif/kumin.gif";
public const string Leo = "Gif/leo.gif";
public const string Ratio4x1 = "Gif/base_4x1.gif";
public const string Ratio1x4 = "Gif/base_1x4.gif";
public const string LargeComment = "Gif/large_comment.gif";
public const string GlobalQuantizationTest = "Gif/GlobalQuantizationTest.gif";
// Test images from https://github.com/robert-ancell/pygif/tree/master/test-suite
public const string ZeroSize = "Gif/image-zero-size.gif";
public const string ZeroHeight = "Gif/image-zero-height.gif";
public const string ZeroWidth = "Gif/image-zero-width.gif";
public const string MaxWidth = "Gif/max-width.gif";
public const string MaxHeight = "Gif/max-height.gif";
public static class Issues
{
public const string BadAppExtLength = "Gif/issues/issue405_badappextlength252.gif";
public const string BadAppExtLength_2 = "Gif/issues/issue405_badappextlength252-2.gif";
public const string BadDescriptorWidth = "Gif/issues/issue403_baddescriptorwidth.gif";
public const string Issue1505 = "Gif/issues/issue1505_argumentoutofrange.png";
public const string Issue1530 = "Gif/issues/issue1530.gif";
}
public static readonly string[] All = { Rings, Giphy, Cheers, Trans, Kumin, Leo, Ratio4x1, Ratio1x4 };
}
public static class Tga
{
public const string Gray8BitTopLeft = "Tga/grayscale_UL.tga";
public const string Gray8BitTopRight = "Tga/grayscale_UR.tga";
public const string Gray8BitBottomLeft = "Tga/targa_8bit.tga";
public const string Gray8BitBottomRight = "Tga/grayscale_LR.tga";
public const string Gray8BitRleTopLeft = "Tga/grayscale_rle_UL.tga";
public const string Gray8BitRleTopRight = "Tga/grayscale_rle_UR.tga";
public const string Gray8BitRleBottomLeft = "Tga/targa_8bit_rle.tga";
public const string Gray8BitRleBottomRight = "Tga/grayscale_rle_LR.tga";
public const string Bit15 = "Tga/rgb15.tga";
public const string Bit15Rle = "Tga/rgb15rle.tga";
public const string Bit16BottomLeft = "Tga/targa_16bit.tga";
public const string Bit16PalRle = "Tga/ccm8.tga";
public const string Bit16RleBottomLeft = "Tga/targa_16bit_rle.tga";
public const string Bit16PalBottomLeft = "Tga/targa_16bit_pal.tga";
public const string Gray16BitTopLeft = "Tga/grayscale_a_UL.tga";
public const string Gray16BitBottomLeft = "Tga/grayscale_a_LL.tga";
public const string Gray16BitBottomRight = "Tga/grayscale_a_LR.tga";
public const string Gray16BitTopRight = "Tga/grayscale_a_UR.tga";
public const string Gray16BitRleTopLeft = "Tga/grayscale_a_rle_UL.tga";
public const string Gray16BitRleBottomLeft = "Tga/grayscale_a_rle_LL.tga";
public const string Gray16BitRleBottomRight = "Tga/grayscale_a_rle_LR.tga";
public const string Gray16BitRleTopRight = "Tga/grayscale_a_rle_UR.tga";
public const string Bit24TopLeft = "Tga/rgb24_top_left.tga";
public const string Bit24BottomLeft = "Tga/targa_24bit.tga";
public const string Bit24BottomRight = "Tga/rgb_LR.tga";
public const string Bit24TopRight = "Tga/rgb_UR.tga";
public const string Bit24RleTopLeft = "Tga/targa_24bit_rle_origin_topleft.tga";
public const string Bit24RleBottomLeft = "Tga/targa_24bit_rle.tga";
public const string Bit24RleTopRight = "Tga/rgb_rle_UR.tga";
public const string Bit24RleBottomRight = "Tga/rgb_rle_LR.tga";
public const string Bit24PalTopLeft = "Tga/targa_24bit_pal_origin_topleft.tga";
public const string Bit24PalTopRight = "Tga/indexed_UR.tga";
public const string Bit24PalBottomLeft = "Tga/targa_24bit_pal.tga";
public const string Bit24PalBottomRight = "Tga/indexed_LR.tga";
public const string Bit24PalRleTopLeft = "Tga/indexed_rle_UL.tga";
public const string Bit24PalRleBottomLeft = "Tga/indexed_rle_LL.tga";
public const string Bit24PalRleTopRight = "Tga/indexed_rle_UR.tga";
public const string Bit24PalRleBottomRight = "Tga/indexed_rle_LR.tga";
public const string Bit32TopLeft = "Tga/rgb_a_UL.tga";
public const string Bit32BottomLeft = "Tga/targa_32bit.tga";
public const string Bit32TopRight = "Tga/rgb_a_UR.tga";
public const string Bit32BottomRight = "Tga/rgb_a_LR.tga";
public const string Bit32PalTopLeft = "Tga/indexed_a_UL.tga";
public const string Bit32PalBottomLeft = "Tga/indexed_a_LL.tga";
public const string Bit32PalBottomRight = "Tga/indexed_a_LR.tga";
public const string Bit32PalTopRight = "Tga/indexed_a_UR.tga";
public const string Bit32RleTopLeft = "Tga/rgb_a_rle_UL.tga";
public const string Bit32RleTopRight = "Tga/rgb_a_rle_UR.tga";
public const string Bit32RleBottomRight = "Tga/rgb_a_rle_LR.tga";
public const string Bit32RleBottomLeft = "Tga/targa_32bit_rle.tga";
public const string Bit32PalRleTopLeft = "Tga/indexed_a_rle_UL.tga";
public const string Bit32PalRleBottomLeft = "Tga/indexed_a_rle_LL.tga";
public const string Bit32PalRleTopRight = "Tga/indexed_a_rle_UR.tga";
public const string Bit32PalRleBottomRight = "Tga/indexed_a_rle_LR.tga";
public const string NoAlphaBits16Bit = "Tga/16bit_noalphabits.tga";
public const string NoAlphaBits16BitRle = "Tga/16bit_rle_noalphabits.tga";
public const string NoAlphaBits32Bit = "Tga/32bit_no_alphabits.tga";
public const string NoAlphaBits32BitRle = "Tga/32bit_rle_no_alphabits.tga";
}
public static class Tiff
{
public const string Benchmark_Path = "Tiff/Benchmarks/";
public const string Benchmark_BwFax3 = "medium_bw_Fax3.tiff";
public const string Benchmark_BwFax4 = "medium_bw_Fax4.tiff";
public const string Benchmark_BwRle = "medium_bw_Rle.tiff";
public const string Benchmark_GrayscaleUncompressed = "medium_grayscale_uncompressed.tiff";
public const string Benchmark_PaletteUncompressed = "medium_palette_uncompressed.tiff";
public const string Benchmark_RgbDeflate = "medium_rgb_deflate.tiff";
public const string Benchmark_RgbLzw = "medium_rgb_lzw.tiff";
public const string Benchmark_RgbPackbits = "medium_rgb_packbits.tiff";
public const string Benchmark_RgbUncompressed = "medium_rgb_uncompressed.tiff";
public const string Calliphora_GrayscaleUncompressed = "Tiff/Calliphora_grayscale_uncompressed.tiff";
public const string Calliphora_GrayscaleDeflate_Predictor = "Tiff/Calliphora_gray_deflate_predictor.tiff";
public const string Calliphora_GrayscaleLzw_Predictor = "Tiff/Calliphora_gray_lzw_predictor.tiff";
public const string Calliphora_GrayscaleDeflate = "Tiff/Calliphora_gray_deflate.tiff";
public const string Calliphora_RgbDeflate_Predictor = "Tiff/Calliphora_rgb_deflate_predictor.tiff";
public const string Calliphora_RgbJpeg = "Tiff/Calliphora_rgb_jpeg.tiff";
public const string Calliphora_PaletteUncompressed = "Tiff/Calliphora_palette_uncompressed.tiff";
public const string Calliphora_RgbLzwPredictor = "Tiff/Calliphora_rgb_lzw_predictor.tiff";
public const string Calliphora_RgbPaletteLzw = "Tiff/Calliphora_rgb_palette_lzw.tiff";
public const string Calliphora_RgbPaletteLzw_Predictor = "Tiff/Calliphora_rgb_palette_lzw_predictor.tiff";
public const string Calliphora_RgbPackbits = "Tiff/Calliphora_rgb_packbits.tiff";
public const string Calliphora_RgbUncompressed = "Tiff/Calliphora_rgb_uncompressed.tiff";
public const string Calliphora_Fax3Compressed = "Tiff/Calliphora_ccitt_fax3.tiff";
public const string Fax3Uncompressed = "Tiff/ccitt_fax3_uncompressed.tiff";
public const string Calliphora_Fax3Compressed_WithEolPadding = "Tiff/Calliphora_ccitt_fax3_with_eol_padding.tiff";
public const string Calliphora_Fax4Compressed = "Tiff/Calliphora_ccitt_fax4.tiff";
public const string Calliphora_HuffmanCompressed = "Tiff/Calliphora_huffman_rle.tiff";
public const string Calliphora_BiColorUncompressed = "Tiff/Calliphora_bicolor_uncompressed.tiff";
public const string CcittFax3AllTermCodes = "Tiff/ccitt_fax3_all_terminating_codes.tiff";
public const string CcittFax3AllMakeupCodes = "Tiff/ccitt_fax3_all_makeup_codes.tiff";
public const string HuffmanRleAllTermCodes = "Tiff/huffman_rle_all_terminating_codes.tiff";
public const string HuffmanRleAllMakeupCodes = "Tiff/huffman_rle_all_makeup_codes.tiff";
// Test case for an issue, that the last bits in a row got ignored.
public const string HuffmanRle_basi3p02 = "Tiff/basi3p02_huffman_rle.tiff";
public const string GrayscaleDeflateMultistrip = "Tiff/grayscale_deflate_multistrip.tiff";
public const string GrayscaleUncompressed = "Tiff/grayscale_uncompressed.tiff";
public const string PaletteDeflateMultistrip = "Tiff/palette_grayscale_deflate_multistrip.tiff";
public const string PaletteUncompressed = "Tiff/palette_uncompressed.tiff";
public const string RgbDeflate = "Tiff/rgb_deflate.tiff";
public const string RgbDeflatePredictor = "Tiff/rgb_deflate_predictor.tiff";
public const string RgbDeflateMultistrip = "Tiff/rgb_deflate_multistrip.tiff";
public const string RgbJpeg = "Tiff/rgb_jpeg.tiff";
public const string RgbLzwPredictor = "Tiff/rgb_lzw_predictor.tiff";
public const string RgbLzwNoPredictor = "Tiff/rgb_lzw_no_predictor.tiff";
public const string RgbLzwNoPredictorMultistrip = "Tiff/rgb_lzw_noPredictor_multistrip.tiff";
public const string RgbLzwNoPredictorMultistripMotorola = "Tiff/rgb_lzw_noPredictor_multistrip_Motorola.tiff";
public const string RgbLzwNoPredictorSinglestripMotorola = "Tiff/rgb_lzw_noPredictor_singlestrip_Motorola.tiff";
public const string RgbLzwMultistripPredictor = "Tiff/rgb_lzw_multistrip.tiff";
public const string RgbPackbits = "Tiff/rgb_packbits.tiff";
public const string RgbPackbitsMultistrip = "Tiff/rgb_packbits_multistrip.tiff";
public const string RgbUncompressed = "Tiff/rgb_uncompressed.tiff";
public const string RgbPalette = "Tiff/rgb_palette.tiff";
public const string Rgb4BitPalette = "Tiff/bike_colorpalette_4bit.tiff";
public const string RgbPaletteDeflate = "Tiff/rgb_palette_deflate.tiff";
public const string SmallRgbDeflate = "Tiff/rgb_small_deflate.tiff";
public const string SmallRgbLzw = "Tiff/rgb_small_lzw.tiff";
public const string RgbUncompressedTiled = "Tiff/rgb_uncompressed_tiled.tiff";
public const string MultiframeDifferentSizeTiled = "Tiff/multipage_ withPreview_differentSize_tiled.tiff";
public const string MultiframeLzwPredictor = "Tiff/multipage_lzw.tiff";
public const string MultiframeDeflateWithPreview = "Tiff/multipage_deflate_withPreview.tiff";
public const string MultiframeDifferentSize = "Tiff/multipage_differentSize.tiff";
public const string MultiframeDifferentVariants = "Tiff/multipage_differentVariants.tiff";
public const string FillOrder2 = "Tiff/b0350_fillorder2.tiff";
public const string LittleEndianByteOrder = "Tiff/little_endian.tiff";
public const string Fax4_Motorola = "Tiff/moy.tiff";
public const string SampleMetadata = "Tiff/metadata_sample.tiff";
// Iptc data as long[] instead of byte[]
public const string InvalidIptcData = "Tiff/7324fcaff3aad96f27899da51c1bb5d9.tiff";
public const string IptcData = "Tiff/iptc.tiff";
public static readonly string[] Multiframes = { MultiframeDeflateWithPreview, MultiframeLzwPredictor /*, MultiFrameDifferentSize, MultiframeDifferentSizeTiled, MultiFrameDifferentVariants,*/ };
public static readonly string[] Metadata = { SampleMetadata };
public static readonly string[] NotSupported = { Calliphora_RgbJpeg, RgbJpeg, RgbUncompressedTiled, MultiframeDifferentSize, MultiframeDifferentVariants, FillOrder2, Calliphora_Fax4Compressed, Fax4_Motorola };
}
}
}
| 62.244932 | 221 | 0.660669 | [
"Apache-2.0"
] | carbon/ImageSharp | tests/ImageSharp.Tests/TestImages.cs | 36,849 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// 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("AWSSDK.Signer")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Signer. With code signing for IoT, you can sign code that you create for any IoT device that is supported by Amazon Web Services (AWS). Code signing is available through Amazon FreeRTOS and AWS IoT Device Management, and integrated with AWS Certificate Manager (ACM).")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS Signer. With code signing for IoT, you can sign code that you create for any IoT device that is supported by Amazon Web Services (AWS). Code signing is available through Amazon FreeRTOS and AWS IoT Device Management, and integrated with AWS Certificate Manager (ACM).")]
#elif PCL
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - AWS Signer. With code signing for IoT, you can sign code that you create for any IoT device that is supported by Amazon Web Services (AWS). Code signing is available through Amazon FreeRTOS and AWS IoT Device Management, and integrated with AWS Certificate Manager (ACM).")]
#elif UNITY
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - AWS Signer. With code signing for IoT, you can sign code that you create for any IoT device that is supported by Amazon Web Services (AWS). Code signing is available through Amazon FreeRTOS and AWS IoT Device Management, and integrated with AWS Certificate Manager (ACM).")]
#elif NETSTANDARD13
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- AWS Signer. With code signing for IoT, you can sign code that you create for any IoT device that is supported by Amazon Web Services (AWS). Code signing is available through Amazon FreeRTOS and AWS IoT Device Management, and integrated with AWS Certificate Manager (ACM).")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- AWS Signer. With code signing for IoT, you can sign code that you create for any IoT device that is supported by Amazon Web Services (AWS). Code signing is available through Amazon FreeRTOS and AWS IoT Device Management, and integrated with AWS Certificate Manager (ACM).")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.3.101.34")]
#if WINDOWS_PHONE || UNITY
[assembly: System.CLSCompliant(false)]
# else
[assembly: System.CLSCompliant(true)]
#endif
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 64.881356 | 362 | 0.774033 | [
"Apache-2.0"
] | dorki/aws-sdk-net | sdk/src/Services/Signer/Properties/AssemblyInfo.cs | 3,828 | C# |
using Contoso.GameNetCore.Builder;
using Contoso.GameNetCore.Hosting;
using Contoso.GameNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace Http2SampleApp
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app)
{
app.UseTimingMiddleware();
app.Run(context =>
{
return context.Response.WriteAsync("Hello World! " + context.Request.Protocol);
});
}
}
}
| 24.04 | 96 | 0.603993 | [
"Apache-2.0"
] | bclnet/GameNetCore | src/Servers/Kestrel/samples/Proto2SampleApp/Startup.cs | 601 | C# |
using System;
using System.Threading.Tasks;
using Xunit;
namespace ActualBudget.Api.FunctionalTests
{
public class ActualClientWithBudgetFacts : IClassFixture<ActualClientWithBudgetFacts.ActualClientFixture>
{
private readonly ActualClientFixture _fixture;
public IActualClient Client => _fixture.GetClient();
public ActualClientWithBudgetFacts(ActualClientFixture fixture)
{
_fixture = fixture;
}
[Fact]
public async Task Test1()
{
await using var clientWithBudget = await Client.OpenAsync("My-Finances-1-dde9556");
var list = await clientWithBudget.GetBudgetMonthsAsync();
foreach (var dateTime in list)
{
Console.WriteLine(dateTime);
}
}
public class ActualClientFixture : IDisposable
{
private IActualClient? _client;
public IActualClient GetClient()
{
return _client ??= ActualClientFactory.Create();
}
public void Dispose()
{
_client?.Dispose();
}
}
}
} | 26.772727 | 109 | 0.587436 | [
"MIT"
] | Silvenga/actualbudget-net | tests/ActualBudget.Api.FunctionalTests/ActualClientWithBudgetFacts.cs | 1,178 | C# |
// Copyright (c) Dolittle. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Linq;
using Dolittle.Runtime.Projections.Store.State;
using ContractsProjectionCurrentState = Dolittle.Runtime.Projections.Contracts.ProjectionCurrentState;
namespace Dolittle.Runtime.Events.Processing.Projections
{
/// <summary>
/// Extensions for <see cref="ProjectionCurrentState"/>.
/// </summary>
public static class ProjectionCurrentStateExtensions
{
/// <summary>
/// Convert to a protobuf representation of <see cref="ProjectionCurrentState"/>.
/// </summary>
/// <param name="state"><see cref="ProjectionCurrentState"/> to convert.</param>
/// <returns>Converted <see cref="ContractsProjectionCurrentState"/>.</returns>
public static ContractsProjectionCurrentState ToProtobuf(this ProjectionCurrentState state)
=> new()
{
Type = state.Type.ToProtobuf(),
State = state.State,
Key = state.Key
};
/// <summary>
/// Convert to an <see cref="IEnumerable{T}"/> of protobuf representations of <see cref="ProjectionCurrentState"/>.
/// </summary>
/// <param name="states">The <see cref="IEnumerable{T}"/> of type <see cref="ProjectionCurrentState"/> to convert.</param>
/// <returns>Converted <see cref="IEnumerable{T}"/> of type <see cref="ContractsProjectionCurrentState"/>.</returns>
public static IEnumerable<ContractsProjectionCurrentState> ToProtobuf(this IEnumerable<ProjectionCurrentState> states)
=> states.Select(_ => _.ToProtobuf());
}
}
| 46.5 | 130 | 0.670062 | [
"MIT"
] | dolittle/Runtime | Source/Events.Processing/Projections/ProjectionCurrentStateExtensions.cs | 1,767 | C# |
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using WebApplication1.Api;
using WebApplication1.Api.Infrastructure.Extensions;
using WebApplication1.Api.Infrastructure.Filters;
namespace WebApplication1.IntegrationTest
{
public class TestStartup
{
public TestStartup(IConfiguration configuration)
{
this.Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(configure =>
{
configure.Filters.Add(typeof(HttpGlobalExceptionFilter));
})
.AddApplicationPart(Assembly.GetAssembly(typeof(Startup)));
services.AddAppConfiguration(this.Configuration);
services.AddIocContainer(this.Configuration);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IApiVersionDescriptionProvider provider)
{
app.UseRouting();
app.UseAppConfiguration(env, provider);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 29.270833 | 120 | 0.674733 | [
"Apache-2.0"
] | dgzornoza/net-api-raiden | WebApplication1/Tests/WebApplication1.IntegrationTest/TestStartup.cs | 1,407 | C# |
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18408
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CityPlace.Domain.DAL
{
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="CityPlace")]
public partial class CityPlaceDataContext : System.Data.Linq.DataContext
{
private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
#region Extensibility Method Definitions
partial void OnCreated();
partial void InsertCity(CityPlace.Domain.Entities.City instance);
partial void UpdateCity(CityPlace.Domain.Entities.City instance);
partial void DeleteCity(CityPlace.Domain.Entities.City instance);
partial void InsertUser(CityPlace.Domain.Entities.User instance);
partial void UpdateUser(CityPlace.Domain.Entities.User instance);
partial void DeleteUser(CityPlace.Domain.Entities.User instance);
partial void InsertMailNotificationMessage(CityPlace.Domain.Entities.MailNotificationMessage instance);
partial void UpdateMailNotificationMessage(CityPlace.Domain.Entities.MailNotificationMessage instance);
partial void DeleteMailNotificationMessage(CityPlace.Domain.Entities.MailNotificationMessage instance);
partial void InsertPermission(CityPlace.Domain.Entities.Permission instance);
partial void UpdatePermission(CityPlace.Domain.Entities.Permission instance);
partial void DeletePermission(CityPlace.Domain.Entities.Permission instance);
partial void InsertRolePermission(CityPlace.Domain.Entities.RolePermission instance);
partial void UpdateRolePermission(CityPlace.Domain.Entities.RolePermission instance);
partial void DeleteRolePermission(CityPlace.Domain.Entities.RolePermission instance);
partial void InsertRole(CityPlace.Domain.Entities.Role instance);
partial void UpdateRole(CityPlace.Domain.Entities.Role instance);
partial void DeleteRole(CityPlace.Domain.Entities.Role instance);
partial void InsertSMSNotificationMessage(CityPlace.Domain.Entities.SMSNotificationMessage instance);
partial void UpdateSMSNotificationMessage(CityPlace.Domain.Entities.SMSNotificationMessage instance);
partial void DeleteSMSNotificationMessage(CityPlace.Domain.Entities.SMSNotificationMessage instance);
partial void InsertCategory(CityPlace.Domain.Entities.Category instance);
partial void UpdateCategory(CityPlace.Domain.Entities.Category instance);
partial void DeleteCategory(CityPlace.Domain.Entities.Category instance);
partial void InsertPlace(CityPlace.Domain.Entities.Place instance);
partial void UpdatePlace(CityPlace.Domain.Entities.Place instance);
partial void DeletePlace(CityPlace.Domain.Entities.Place instance);
partial void InsertEvent(CityPlace.Domain.Entities.Event instance);
partial void UpdateEvent(CityPlace.Domain.Entities.Event instance);
partial void DeleteEvent(CityPlace.Domain.Entities.Event instance);
partial void InsertProduct(CityPlace.Domain.Entities.Product instance);
partial void UpdateProduct(CityPlace.Domain.Entities.Product instance);
partial void DeleteProduct(CityPlace.Domain.Entities.Product instance);
partial void InsertPublication(CityPlace.Domain.Entities.Publication instance);
partial void UpdatePublication(CityPlace.Domain.Entities.Publication instance);
partial void DeletePublication(CityPlace.Domain.Entities.Publication instance);
partial void InsertCityUser(CityPlace.Domain.Entities.CityUser instance);
partial void UpdateCityUser(CityPlace.Domain.Entities.CityUser instance);
partial void DeleteCityUser(CityPlace.Domain.Entities.CityUser instance);
partial void InsertDevice(CityPlace.Domain.Entities.Device instance);
partial void UpdateDevice(CityPlace.Domain.Entities.Device instance);
partial void DeleteDevice(CityPlace.Domain.Entities.Device instance);
#endregion
public CityPlaceDataContext(string connection) :
base(connection, mappingSource)
{
OnCreated();
}
public CityPlaceDataContext(System.Data.IDbConnection connection) :
base(connection, mappingSource)
{
OnCreated();
}
public CityPlaceDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public CityPlaceDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public System.Data.Linq.Table<CityPlace.Domain.Entities.City> Cities
{
get
{
return this.GetTable<CityPlace.Domain.Entities.City>();
}
}
public System.Data.Linq.Table<CityPlace.Domain.Entities.User> Users
{
get
{
return this.GetTable<CityPlace.Domain.Entities.User>();
}
}
public System.Data.Linq.Table<CityPlace.Domain.Entities.MailNotificationMessage> MailNotificationMessages
{
get
{
return this.GetTable<CityPlace.Domain.Entities.MailNotificationMessage>();
}
}
public System.Data.Linq.Table<CityPlace.Domain.Entities.Permission> Permissions
{
get
{
return this.GetTable<CityPlace.Domain.Entities.Permission>();
}
}
public System.Data.Linq.Table<CityPlace.Domain.Entities.RolePermission> RolePermissions
{
get
{
return this.GetTable<CityPlace.Domain.Entities.RolePermission>();
}
}
public System.Data.Linq.Table<CityPlace.Domain.Entities.Role> Roles
{
get
{
return this.GetTable<CityPlace.Domain.Entities.Role>();
}
}
public System.Data.Linq.Table<CityPlace.Domain.Entities.SMSNotificationMessage> SMSNotificationMessages
{
get
{
return this.GetTable<CityPlace.Domain.Entities.SMSNotificationMessage>();
}
}
public System.Data.Linq.Table<CityPlace.Domain.Entities.Category> Categories
{
get
{
return this.GetTable<CityPlace.Domain.Entities.Category>();
}
}
public System.Data.Linq.Table<CityPlace.Domain.Entities.Place> Places
{
get
{
return this.GetTable<CityPlace.Domain.Entities.Place>();
}
}
public System.Data.Linq.Table<CityPlace.Domain.Entities.Event> Events
{
get
{
return this.GetTable<CityPlace.Domain.Entities.Event>();
}
}
public System.Data.Linq.Table<CityPlace.Domain.Entities.Product> Products
{
get
{
return this.GetTable<CityPlace.Domain.Entities.Product>();
}
}
public System.Data.Linq.Table<CityPlace.Domain.Entities.Publication> Publications
{
get
{
return this.GetTable<CityPlace.Domain.Entities.Publication>();
}
}
public System.Data.Linq.Table<CityPlace.Domain.Entities.CityUser> CityUsers
{
get
{
return this.GetTable<CityPlace.Domain.Entities.CityUser>();
}
}
public System.Data.Linq.Table<CityPlace.Domain.Entities.Device> Devices
{
get
{
return this.GetTable<CityPlace.Domain.Entities.Device>();
}
}
}
}
namespace CityPlace.Domain.Entities
{
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.ComponentModel;
using System;
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Cities")]
public partial class City : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private long _Id;
private string _Name;
private System.Nullable<double> _CenterLat;
private System.Nullable<double> _CenterLon;
private System.Nullable<System.DateTime> _DateCreated;
private System.Nullable<System.DateTime> _DateModified;
private EntitySet<Place> _Places;
private EntitySet<Publication> _Publications;
private EntitySet<CityUser> _CityUsers;
private EntitySet<Device> _Devices;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(long value);
partial void OnIdChanged();
partial void OnNameChanging(string value);
partial void OnNameChanged();
partial void OnCenterLatChanging(System.Nullable<double> value);
partial void OnCenterLatChanged();
partial void OnCenterLonChanging(System.Nullable<double> value);
partial void OnCenterLonChanged();
partial void OnDateCreatedChanging(System.Nullable<System.DateTime> value);
partial void OnDateCreatedChanged();
partial void OnDateModifiedChanging(System.Nullable<System.DateTime> value);
partial void OnDateModifiedChanged();
#endregion
public City()
{
this._Places = new EntitySet<Place>(new Action<Place>(this.attach_Places), new Action<Place>(this.detach_Places));
this._Publications = new EntitySet<Publication>(new Action<Publication>(this.attach_Publications), new Action<Publication>(this.detach_Publications));
this._CityUsers = new EntitySet<CityUser>(new Action<CityUser>(this.attach_CityUsers), new Action<CityUser>(this.detach_CityUsers));
this._Devices = new EntitySet<Device>(new Action<Device>(this.attach_Devices), new Action<Device>(this.detach_Devices));
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public long Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Name", DbType="NVarChar(255) NOT NULL", CanBeNull=false)]
public string Name
{
get
{
return this._Name;
}
set
{
if ((this._Name != value))
{
this.OnNameChanging(value);
this.SendPropertyChanging();
this._Name = value;
this.SendPropertyChanged("Name");
this.OnNameChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CenterLat", DbType="Float")]
public System.Nullable<double> CenterLat
{
get
{
return this._CenterLat;
}
set
{
if ((this._CenterLat != value))
{
this.OnCenterLatChanging(value);
this.SendPropertyChanging();
this._CenterLat = value;
this.SendPropertyChanged("CenterLat");
this.OnCenterLatChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CenterLon", DbType="Float")]
public System.Nullable<double> CenterLon
{
get
{
return this._CenterLon;
}
set
{
if ((this._CenterLon != value))
{
this.OnCenterLonChanging(value);
this.SendPropertyChanging();
this._CenterLon = value;
this.SendPropertyChanged("CenterLon");
this.OnCenterLonChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateCreated", DbType="DateTime")]
public System.Nullable<System.DateTime> DateCreated
{
get
{
return this._DateCreated;
}
set
{
if ((this._DateCreated != value))
{
this.OnDateCreatedChanging(value);
this.SendPropertyChanging();
this._DateCreated = value;
this.SendPropertyChanged("DateCreated");
this.OnDateCreatedChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateModified", DbType="DateTime")]
public System.Nullable<System.DateTime> DateModified
{
get
{
return this._DateModified;
}
set
{
if ((this._DateModified != value))
{
this.OnDateModifiedChanging(value);
this.SendPropertyChanging();
this._DateModified = value;
this.SendPropertyChanged("DateModified");
this.OnDateModifiedChanged();
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="City_Place", Storage="_Places", ThisKey="Id", OtherKey="CityId")]
public EntitySet<Place> Places
{
get
{
return this._Places;
}
set
{
this._Places.Assign(value);
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="City_Publication", Storage="_Publications", ThisKey="Id", OtherKey="CityId")]
public EntitySet<Publication> Publications
{
get
{
return this._Publications;
}
set
{
this._Publications.Assign(value);
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="City_CityUser", Storage="_CityUsers", ThisKey="Id", OtherKey="CityId")]
public EntitySet<CityUser> CityUsers
{
get
{
return this._CityUsers;
}
set
{
this._CityUsers.Assign(value);
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="City_Device", Storage="_Devices", ThisKey="Id", OtherKey="CityId")]
public EntitySet<Device> Devices
{
get
{
return this._Devices;
}
set
{
this._Devices.Assign(value);
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private void attach_Places(Place entity)
{
this.SendPropertyChanging();
entity.City = this;
}
private void detach_Places(Place entity)
{
this.SendPropertyChanging();
entity.City = null;
}
private void attach_Publications(Publication entity)
{
this.SendPropertyChanging();
entity.City = this;
}
private void detach_Publications(Publication entity)
{
this.SendPropertyChanging();
entity.City = null;
}
private void attach_CityUsers(CityUser entity)
{
this.SendPropertyChanging();
entity.City = this;
}
private void detach_CityUsers(CityUser entity)
{
this.SendPropertyChanging();
entity.City = null;
}
private void attach_Devices(Device entity)
{
this.SendPropertyChanging();
entity.City = this;
}
private void detach_Devices(Device entity)
{
this.SendPropertyChanging();
entity.City = null;
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Users")]
public partial class User : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private long _Id;
private string _Email;
private string _PasswordHash;
private string _Phone;
private string _FirstName;
private string _LastName;
private string _SurName;
private long _RoleId;
private short _Status;
private System.Nullable<System.DateTime> _DateRegistred;
private System.Nullable<System.DateTime> _DateModified;
private System.Nullable<System.DateTime> _LastLogin;
private EntitySet<CityUser> _CityUsers;
private EntityRef<Role> _Role;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(long value);
partial void OnIdChanged();
partial void OnEmailChanging(string value);
partial void OnEmailChanged();
partial void OnPasswordHashChanging(string value);
partial void OnPasswordHashChanged();
partial void OnPhoneChanging(string value);
partial void OnPhoneChanged();
partial void OnFirstNameChanging(string value);
partial void OnFirstNameChanged();
partial void OnLastNameChanging(string value);
partial void OnLastNameChanged();
partial void OnSurNameChanging(string value);
partial void OnSurNameChanged();
partial void OnRoleIdChanging(long value);
partial void OnRoleIdChanged();
partial void OnStatusChanging(short value);
partial void OnStatusChanged();
partial void OnDateRegistredChanging(System.Nullable<System.DateTime> value);
partial void OnDateRegistredChanged();
partial void OnDateModifiedChanging(System.Nullable<System.DateTime> value);
partial void OnDateModifiedChanged();
partial void OnLastLoginChanging(System.Nullable<System.DateTime> value);
partial void OnLastLoginChanged();
#endregion
public User()
{
this._CityUsers = new EntitySet<CityUser>(new Action<CityUser>(this.attach_CityUsers), new Action<CityUser>(this.detach_CityUsers));
this._Role = default(EntityRef<Role>);
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public long Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Email", DbType="NVarChar(255)")]
public string Email
{
get
{
return this._Email;
}
set
{
if ((this._Email != value))
{
this.OnEmailChanging(value);
this.SendPropertyChanging();
this._Email = value;
this.SendPropertyChanged("Email");
this.OnEmailChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_PasswordHash", DbType="NVarChar(MAX)")]
public string PasswordHash
{
get
{
return this._PasswordHash;
}
set
{
if ((this._PasswordHash != value))
{
this.OnPasswordHashChanging(value);
this.SendPropertyChanging();
this._PasswordHash = value;
this.SendPropertyChanged("PasswordHash");
this.OnPasswordHashChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Phone", DbType="NVarChar(255)")]
public string Phone
{
get
{
return this._Phone;
}
set
{
if ((this._Phone != value))
{
this.OnPhoneChanging(value);
this.SendPropertyChanging();
this._Phone = value;
this.SendPropertyChanged("Phone");
this.OnPhoneChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_FirstName", DbType="NVarChar(255)")]
public string FirstName
{
get
{
return this._FirstName;
}
set
{
if ((this._FirstName != value))
{
this.OnFirstNameChanging(value);
this.SendPropertyChanging();
this._FirstName = value;
this.SendPropertyChanged("FirstName");
this.OnFirstNameChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_LastName", DbType="NVarChar(255)")]
public string LastName
{
get
{
return this._LastName;
}
set
{
if ((this._LastName != value))
{
this.OnLastNameChanging(value);
this.SendPropertyChanging();
this._LastName = value;
this.SendPropertyChanged("LastName");
this.OnLastNameChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_SurName", DbType="NVarChar(255)")]
public string SurName
{
get
{
return this._SurName;
}
set
{
if ((this._SurName != value))
{
this.OnSurNameChanging(value);
this.SendPropertyChanging();
this._SurName = value;
this.SendPropertyChanged("SurName");
this.OnSurNameChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_RoleId", DbType="BigInt NOT NULL")]
public long RoleId
{
get
{
return this._RoleId;
}
set
{
if ((this._RoleId != value))
{
if (this._Role.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnRoleIdChanging(value);
this.SendPropertyChanging();
this._RoleId = value;
this.SendPropertyChanged("RoleId");
this.OnRoleIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Status", DbType="SmallInt NOT NULL")]
public short Status
{
get
{
return this._Status;
}
set
{
if ((this._Status != value))
{
this.OnStatusChanging(value);
this.SendPropertyChanging();
this._Status = value;
this.SendPropertyChanged("Status");
this.OnStatusChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateRegistred", DbType="DateTime")]
public System.Nullable<System.DateTime> DateRegistred
{
get
{
return this._DateRegistred;
}
set
{
if ((this._DateRegistred != value))
{
this.OnDateRegistredChanging(value);
this.SendPropertyChanging();
this._DateRegistred = value;
this.SendPropertyChanged("DateRegistred");
this.OnDateRegistredChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateModified", DbType="DateTime")]
public System.Nullable<System.DateTime> DateModified
{
get
{
return this._DateModified;
}
set
{
if ((this._DateModified != value))
{
this.OnDateModifiedChanging(value);
this.SendPropertyChanging();
this._DateModified = value;
this.SendPropertyChanged("DateModified");
this.OnDateModifiedChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_LastLogin", DbType="DateTime")]
public System.Nullable<System.DateTime> LastLogin
{
get
{
return this._LastLogin;
}
set
{
if ((this._LastLogin != value))
{
this.OnLastLoginChanging(value);
this.SendPropertyChanging();
this._LastLogin = value;
this.SendPropertyChanged("LastLogin");
this.OnLastLoginChanged();
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="User_CityUser", Storage="_CityUsers", ThisKey="Id", OtherKey="UserId")]
public EntitySet<CityUser> CityUsers
{
get
{
return this._CityUsers;
}
set
{
this._CityUsers.Assign(value);
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Role_User", Storage="_Role", ThisKey="RoleId", OtherKey="Id", IsForeignKey=true)]
public Role Role
{
get
{
return this._Role.Entity;
}
set
{
Role previousValue = this._Role.Entity;
if (((previousValue != value)
|| (this._Role.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._Role.Entity = null;
previousValue.Users.Remove(this);
}
this._Role.Entity = value;
if ((value != null))
{
value.Users.Add(this);
this._RoleId = value.Id;
}
else
{
this._RoleId = default(long);
}
this.SendPropertyChanged("Role");
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private void attach_CityUsers(CityUser entity)
{
this.SendPropertyChanging();
entity.User = this;
}
private void detach_CityUsers(CityUser entity)
{
this.SendPropertyChanging();
entity.User = null;
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.MailNotificationMessages")]
public partial class MailNotificationMessage : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private long _Id;
private string _Recipient;
private string _Subject;
private string _Content;
private bool _Sended;
private System.Nullable<System.DateTime> _DateEnqued;
private System.Nullable<System.DateTime> _DateSended;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(long value);
partial void OnIdChanged();
partial void OnRecipientChanging(string value);
partial void OnRecipientChanged();
partial void OnSubjectChanging(string value);
partial void OnSubjectChanged();
partial void OnContentChanging(string value);
partial void OnContentChanged();
partial void OnSendedChanging(bool value);
partial void OnSendedChanged();
partial void OnDateEnquedChanging(System.Nullable<System.DateTime> value);
partial void OnDateEnquedChanged();
partial void OnDateSendedChanging(System.Nullable<System.DateTime> value);
partial void OnDateSendedChanged();
#endregion
public MailNotificationMessage()
{
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public long Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Recipient", DbType="NVarChar(255) NOT NULL", CanBeNull=false)]
public string Recipient
{
get
{
return this._Recipient;
}
set
{
if ((this._Recipient != value))
{
this.OnRecipientChanging(value);
this.SendPropertyChanging();
this._Recipient = value;
this.SendPropertyChanged("Recipient");
this.OnRecipientChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Subject", DbType="NVarChar(255)")]
public string Subject
{
get
{
return this._Subject;
}
set
{
if ((this._Subject != value))
{
this.OnSubjectChanging(value);
this.SendPropertyChanging();
this._Subject = value;
this.SendPropertyChanged("Subject");
this.OnSubjectChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Content", DbType="NVarChar(MAX)")]
public string Content
{
get
{
return this._Content;
}
set
{
if ((this._Content != value))
{
this.OnContentChanging(value);
this.SendPropertyChanging();
this._Content = value;
this.SendPropertyChanged("Content");
this.OnContentChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Sended", DbType="Bit NOT NULL")]
public bool Sended
{
get
{
return this._Sended;
}
set
{
if ((this._Sended != value))
{
this.OnSendedChanging(value);
this.SendPropertyChanging();
this._Sended = value;
this.SendPropertyChanged("Sended");
this.OnSendedChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateEnqued", DbType="DateTime")]
public System.Nullable<System.DateTime> DateEnqued
{
get
{
return this._DateEnqued;
}
set
{
if ((this._DateEnqued != value))
{
this.OnDateEnquedChanging(value);
this.SendPropertyChanging();
this._DateEnqued = value;
this.SendPropertyChanged("DateEnqued");
this.OnDateEnquedChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateSended", DbType="DateTime")]
public System.Nullable<System.DateTime> DateSended
{
get
{
return this._DateSended;
}
set
{
if ((this._DateSended != value))
{
this.OnDateSendedChanging(value);
this.SendPropertyChanging();
this._DateSended = value;
this.SendPropertyChanged("DateSended");
this.OnDateSendedChanged();
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Permissions")]
public partial class Permission : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private long _Id;
private string _Name;
private string _PermissionGroup;
private EntitySet<RolePermission> _RolePermissions;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(long value);
partial void OnIdChanged();
partial void OnNameChanging(string value);
partial void OnNameChanged();
partial void OnPermissionGroupChanging(string value);
partial void OnPermissionGroupChanged();
#endregion
public Permission()
{
this._RolePermissions = new EntitySet<RolePermission>(new Action<RolePermission>(this.attach_RolePermissions), new Action<RolePermission>(this.detach_RolePermissions));
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public long Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Name", DbType="NVarChar(255) NOT NULL", CanBeNull=false)]
public string Name
{
get
{
return this._Name;
}
set
{
if ((this._Name != value))
{
this.OnNameChanging(value);
this.SendPropertyChanging();
this._Name = value;
this.SendPropertyChanged("Name");
this.OnNameChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_PermissionGroup", DbType="NVarChar(255)")]
public string PermissionGroup
{
get
{
return this._PermissionGroup;
}
set
{
if ((this._PermissionGroup != value))
{
this.OnPermissionGroupChanging(value);
this.SendPropertyChanging();
this._PermissionGroup = value;
this.SendPropertyChanged("PermissionGroup");
this.OnPermissionGroupChanged();
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Permission_RolePermission", Storage="_RolePermissions", ThisKey="Id", OtherKey="PermissionId")]
public EntitySet<RolePermission> RolePermissions
{
get
{
return this._RolePermissions;
}
set
{
this._RolePermissions.Assign(value);
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private void attach_RolePermissions(RolePermission entity)
{
this.SendPropertyChanging();
entity.Permission = this;
}
private void detach_RolePermissions(RolePermission entity)
{
this.SendPropertyChanging();
entity.Permission = null;
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.RolePermissions")]
public partial class RolePermission : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private long _Id;
private long _RoleId;
private long _PermissionId;
private System.Nullable<System.DateTime> _DateCreated;
private EntityRef<Permission> _Permission;
private EntityRef<Role> _Role;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(long value);
partial void OnIdChanged();
partial void OnRoleIdChanging(long value);
partial void OnRoleIdChanged();
partial void OnPermissionIdChanging(long value);
partial void OnPermissionIdChanged();
partial void OnDateCreatedChanging(System.Nullable<System.DateTime> value);
partial void OnDateCreatedChanged();
#endregion
public RolePermission()
{
this._Permission = default(EntityRef<Permission>);
this._Role = default(EntityRef<Role>);
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public long Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_RoleId", DbType="BigInt NOT NULL")]
public long RoleId
{
get
{
return this._RoleId;
}
set
{
if ((this._RoleId != value))
{
if (this._Role.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnRoleIdChanging(value);
this.SendPropertyChanging();
this._RoleId = value;
this.SendPropertyChanged("RoleId");
this.OnRoleIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_PermissionId", DbType="BigInt NOT NULL")]
public long PermissionId
{
get
{
return this._PermissionId;
}
set
{
if ((this._PermissionId != value))
{
if (this._Permission.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnPermissionIdChanging(value);
this.SendPropertyChanging();
this._PermissionId = value;
this.SendPropertyChanged("PermissionId");
this.OnPermissionIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateCreated", DbType="DateTime")]
public System.Nullable<System.DateTime> DateCreated
{
get
{
return this._DateCreated;
}
set
{
if ((this._DateCreated != value))
{
this.OnDateCreatedChanging(value);
this.SendPropertyChanging();
this._DateCreated = value;
this.SendPropertyChanged("DateCreated");
this.OnDateCreatedChanged();
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Permission_RolePermission", Storage="_Permission", ThisKey="PermissionId", OtherKey="Id", IsForeignKey=true)]
public Permission Permission
{
get
{
return this._Permission.Entity;
}
set
{
Permission previousValue = this._Permission.Entity;
if (((previousValue != value)
|| (this._Permission.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._Permission.Entity = null;
previousValue.RolePermissions.Remove(this);
}
this._Permission.Entity = value;
if ((value != null))
{
value.RolePermissions.Add(this);
this._PermissionId = value.Id;
}
else
{
this._PermissionId = default(long);
}
this.SendPropertyChanged("Permission");
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Role_RolePermission", Storage="_Role", ThisKey="RoleId", OtherKey="Id", IsForeignKey=true, DeleteOnNull=true, DeleteRule="CASCADE")]
public Role Role
{
get
{
return this._Role.Entity;
}
set
{
Role previousValue = this._Role.Entity;
if (((previousValue != value)
|| (this._Role.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._Role.Entity = null;
previousValue.RolePermissions.Remove(this);
}
this._Role.Entity = value;
if ((value != null))
{
value.RolePermissions.Add(this);
this._RoleId = value.Id;
}
else
{
this._RoleId = default(long);
}
this.SendPropertyChanged("Role");
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Roles")]
public partial class Role : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private long _Id;
private string _SystemName;
private string _DisplayName;
private string _Description;
private System.Nullable<System.DateTime> _DateCreated;
private System.Nullable<System.DateTime> _DateModified;
private EntitySet<User> _Users;
private EntitySet<RolePermission> _RolePermissions;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(long value);
partial void OnIdChanged();
partial void OnSystemNameChanging(string value);
partial void OnSystemNameChanged();
partial void OnDisplayNameChanging(string value);
partial void OnDisplayNameChanged();
partial void OnDescriptionChanging(string value);
partial void OnDescriptionChanged();
partial void OnDateCreatedChanging(System.Nullable<System.DateTime> value);
partial void OnDateCreatedChanged();
partial void OnDateModifiedChanging(System.Nullable<System.DateTime> value);
partial void OnDateModifiedChanged();
#endregion
public Role()
{
this._Users = new EntitySet<User>(new Action<User>(this.attach_Users), new Action<User>(this.detach_Users));
this._RolePermissions = new EntitySet<RolePermission>(new Action<RolePermission>(this.attach_RolePermissions), new Action<RolePermission>(this.detach_RolePermissions));
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public long Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_SystemName", DbType="NVarChar(255) NOT NULL", CanBeNull=false)]
public string SystemName
{
get
{
return this._SystemName;
}
set
{
if ((this._SystemName != value))
{
this.OnSystemNameChanging(value);
this.SendPropertyChanging();
this._SystemName = value;
this.SendPropertyChanged("SystemName");
this.OnSystemNameChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DisplayName", DbType="NVarChar(255)")]
public string DisplayName
{
get
{
return this._DisplayName;
}
set
{
if ((this._DisplayName != value))
{
this.OnDisplayNameChanging(value);
this.SendPropertyChanging();
this._DisplayName = value;
this.SendPropertyChanged("DisplayName");
this.OnDisplayNameChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Description", DbType="NVarChar(MAX)")]
public string Description
{
get
{
return this._Description;
}
set
{
if ((this._Description != value))
{
this.OnDescriptionChanging(value);
this.SendPropertyChanging();
this._Description = value;
this.SendPropertyChanged("Description");
this.OnDescriptionChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateCreated", DbType="DateTime")]
public System.Nullable<System.DateTime> DateCreated
{
get
{
return this._DateCreated;
}
set
{
if ((this._DateCreated != value))
{
this.OnDateCreatedChanging(value);
this.SendPropertyChanging();
this._DateCreated = value;
this.SendPropertyChanged("DateCreated");
this.OnDateCreatedChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateModified", DbType="DateTime")]
public System.Nullable<System.DateTime> DateModified
{
get
{
return this._DateModified;
}
set
{
if ((this._DateModified != value))
{
this.OnDateModifiedChanging(value);
this.SendPropertyChanging();
this._DateModified = value;
this.SendPropertyChanged("DateModified");
this.OnDateModifiedChanged();
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Role_User", Storage="_Users", ThisKey="Id", OtherKey="RoleId")]
public EntitySet<User> Users
{
get
{
return this._Users;
}
set
{
this._Users.Assign(value);
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Role_RolePermission", Storage="_RolePermissions", ThisKey="Id", OtherKey="RoleId")]
public EntitySet<RolePermission> RolePermissions
{
get
{
return this._RolePermissions;
}
set
{
this._RolePermissions.Assign(value);
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private void attach_Users(User entity)
{
this.SendPropertyChanging();
entity.Role = this;
}
private void detach_Users(User entity)
{
this.SendPropertyChanging();
entity.Role = null;
}
private void attach_RolePermissions(RolePermission entity)
{
this.SendPropertyChanging();
entity.Role = this;
}
private void detach_RolePermissions(RolePermission entity)
{
this.SendPropertyChanging();
entity.Role = null;
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.SMSNotificationMessages")]
public partial class SMSNotificationMessage : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private long _Id;
private string _Recipient;
private string _Message;
private bool _Sended;
private System.Nullable<System.DateTime> _DateEnqueued;
private System.Nullable<System.DateTime> _DateSended;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(long value);
partial void OnIdChanged();
partial void OnRecipientChanging(string value);
partial void OnRecipientChanged();
partial void OnMessageChanging(string value);
partial void OnMessageChanged();
partial void OnSendedChanging(bool value);
partial void OnSendedChanged();
partial void OnDateEnqueuedChanging(System.Nullable<System.DateTime> value);
partial void OnDateEnqueuedChanged();
partial void OnDateSendedChanging(System.Nullable<System.DateTime> value);
partial void OnDateSendedChanged();
#endregion
public SMSNotificationMessage()
{
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public long Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Recipient", DbType="NVarChar(255) NOT NULL", CanBeNull=false)]
public string Recipient
{
get
{
return this._Recipient;
}
set
{
if ((this._Recipient != value))
{
this.OnRecipientChanging(value);
this.SendPropertyChanging();
this._Recipient = value;
this.SendPropertyChanged("Recipient");
this.OnRecipientChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Message", DbType="NVarChar(255) NOT NULL", CanBeNull=false)]
public string Message
{
get
{
return this._Message;
}
set
{
if ((this._Message != value))
{
this.OnMessageChanging(value);
this.SendPropertyChanging();
this._Message = value;
this.SendPropertyChanged("Message");
this.OnMessageChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Sended", DbType="Bit NOT NULL")]
public bool Sended
{
get
{
return this._Sended;
}
set
{
if ((this._Sended != value))
{
this.OnSendedChanging(value);
this.SendPropertyChanging();
this._Sended = value;
this.SendPropertyChanged("Sended");
this.OnSendedChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateEnqueued", DbType="DateTime")]
public System.Nullable<System.DateTime> DateEnqueued
{
get
{
return this._DateEnqueued;
}
set
{
if ((this._DateEnqueued != value))
{
this.OnDateEnqueuedChanging(value);
this.SendPropertyChanging();
this._DateEnqueued = value;
this.SendPropertyChanged("DateEnqueued");
this.OnDateEnqueuedChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateSended", DbType="DateTime")]
public System.Nullable<System.DateTime> DateSended
{
get
{
return this._DateSended;
}
set
{
if ((this._DateSended != value))
{
this.OnDateSendedChanging(value);
this.SendPropertyChanging();
this._DateSended = value;
this.SendPropertyChanged("DateSended");
this.OnDateSendedChanged();
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Categories")]
public partial class Category : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private long _Id;
private string _Title;
private string _Description;
private string _Image;
private bool _Hidden;
private System.Nullable<System.DateTime> _DateCreated;
private System.Nullable<System.DateTime> _DateModified;
private EntitySet<Place> _Places;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(long value);
partial void OnIdChanged();
partial void OnTitleChanging(string value);
partial void OnTitleChanged();
partial void OnDescriptionChanging(string value);
partial void OnDescriptionChanged();
partial void OnImageChanging(string value);
partial void OnImageChanged();
partial void OnHiddenChanging(bool value);
partial void OnHiddenChanged();
partial void OnDateCreatedChanging(System.Nullable<System.DateTime> value);
partial void OnDateCreatedChanged();
partial void OnDateModifiedChanging(System.Nullable<System.DateTime> value);
partial void OnDateModifiedChanged();
#endregion
public Category()
{
this._Places = new EntitySet<Place>(new Action<Place>(this.attach_Places), new Action<Place>(this.detach_Places));
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public long Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Title", DbType="NVarChar(255)")]
public string Title
{
get
{
return this._Title;
}
set
{
if ((this._Title != value))
{
this.OnTitleChanging(value);
this.SendPropertyChanging();
this._Title = value;
this.SendPropertyChanged("Title");
this.OnTitleChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Description", DbType="NVarChar(MAX)")]
public string Description
{
get
{
return this._Description;
}
set
{
if ((this._Description != value))
{
this.OnDescriptionChanging(value);
this.SendPropertyChanging();
this._Description = value;
this.SendPropertyChanged("Description");
this.OnDescriptionChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Image", DbType="NVarChar(MAX)")]
public string Image
{
get
{
return this._Image;
}
set
{
if ((this._Image != value))
{
this.OnImageChanging(value);
this.SendPropertyChanging();
this._Image = value;
this.SendPropertyChanged("Image");
this.OnImageChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Hidden", DbType="Bit NOT NULL")]
public bool Hidden
{
get
{
return this._Hidden;
}
set
{
if ((this._Hidden != value))
{
this.OnHiddenChanging(value);
this.SendPropertyChanging();
this._Hidden = value;
this.SendPropertyChanged("Hidden");
this.OnHiddenChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateCreated", DbType="DateTime")]
public System.Nullable<System.DateTime> DateCreated
{
get
{
return this._DateCreated;
}
set
{
if ((this._DateCreated != value))
{
this.OnDateCreatedChanging(value);
this.SendPropertyChanging();
this._DateCreated = value;
this.SendPropertyChanged("DateCreated");
this.OnDateCreatedChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateModified", DbType="DateTime")]
public System.Nullable<System.DateTime> DateModified
{
get
{
return this._DateModified;
}
set
{
if ((this._DateModified != value))
{
this.OnDateModifiedChanging(value);
this.SendPropertyChanging();
this._DateModified = value;
this.SendPropertyChanged("DateModified");
this.OnDateModifiedChanged();
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Category_Place", Storage="_Places", ThisKey="Id", OtherKey="CategoryId")]
public EntitySet<Place> Places
{
get
{
return this._Places;
}
set
{
this._Places.Assign(value);
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private void attach_Places(Place entity)
{
this.SendPropertyChanging();
entity.Category = this;
}
private void detach_Places(Place entity)
{
this.SendPropertyChanging();
entity.Category = null;
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Places")]
public partial class Place : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private long _Id;
private long _CityId;
private long _CategoryId;
private string _Title;
private string _Description;
private string _Image;
private string _Address;
private System.Nullable<double> _Latitude;
private System.Nullable<double> _Longitude;
private string _WorkTime;
private string _Phone1;
private string _Phone2;
private string _Phone3;
private string _Fax;
private string _Email;
private string _Site;
private bool _CashPayments;
private bool _CashlessPayments;
private bool _WiFi;
private bool _Booking;
private bool _Ordering;
private System.Nullable<decimal> _AverageCheck;
private bool _VIPSection;
private bool _LiveMusic;
private bool _SmokingRoom;
private bool _BusinessLunch;
private bool _Hidden;
private System.Nullable<System.DateTime> _DateCreated;
private System.Nullable<System.DateTime> _DateModified;
private EntitySet<Event> _Events;
private EntitySet<Product> _Products;
private EntityRef<Category> _Category;
private EntityRef<City> _City;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(long value);
partial void OnIdChanged();
partial void OnCityIdChanging(long value);
partial void OnCityIdChanged();
partial void OnCategoryIdChanging(long value);
partial void OnCategoryIdChanged();
partial void OnTitleChanging(string value);
partial void OnTitleChanged();
partial void OnDescriptionChanging(string value);
partial void OnDescriptionChanged();
partial void OnImageChanging(string value);
partial void OnImageChanged();
partial void OnAddressChanging(string value);
partial void OnAddressChanged();
partial void OnLatitudeChanging(System.Nullable<double> value);
partial void OnLatitudeChanged();
partial void OnLongitudeChanging(System.Nullable<double> value);
partial void OnLongitudeChanged();
partial void OnWorkTimeChanging(string value);
partial void OnWorkTimeChanged();
partial void OnPhone1Changing(string value);
partial void OnPhone1Changed();
partial void OnPhone2Changing(string value);
partial void OnPhone2Changed();
partial void OnPhone3Changing(string value);
partial void OnPhone3Changed();
partial void OnFaxChanging(string value);
partial void OnFaxChanged();
partial void OnEmailChanging(string value);
partial void OnEmailChanged();
partial void OnSiteChanging(string value);
partial void OnSiteChanged();
partial void OnCashPaymentsChanging(bool value);
partial void OnCashPaymentsChanged();
partial void OnCashlessPaymentsChanging(bool value);
partial void OnCashlessPaymentsChanged();
partial void OnWiFiChanging(bool value);
partial void OnWiFiChanged();
partial void OnBookingChanging(bool value);
partial void OnBookingChanged();
partial void OnOrderingChanging(bool value);
partial void OnOrderingChanged();
partial void OnAverageCheckChanging(System.Nullable<decimal> value);
partial void OnAverageCheckChanged();
partial void OnVIPSectionChanging(bool value);
partial void OnVIPSectionChanged();
partial void OnLiveMusicChanging(bool value);
partial void OnLiveMusicChanged();
partial void OnSmokingRoomChanging(bool value);
partial void OnSmokingRoomChanged();
partial void OnBusinessLunchChanging(bool value);
partial void OnBusinessLunchChanged();
partial void OnHiddenChanging(bool value);
partial void OnHiddenChanged();
partial void OnDateCreatedChanging(System.Nullable<System.DateTime> value);
partial void OnDateCreatedChanged();
partial void OnDateModifiedChanging(System.Nullable<System.DateTime> value);
partial void OnDateModifiedChanged();
#endregion
public Place()
{
this._Events = new EntitySet<Event>(new Action<Event>(this.attach_Events), new Action<Event>(this.detach_Events));
this._Products = new EntitySet<Product>(new Action<Product>(this.attach_Products), new Action<Product>(this.detach_Products));
this._Category = default(EntityRef<Category>);
this._City = default(EntityRef<City>);
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public long Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CityId", DbType="BigInt NOT NULL")]
public long CityId
{
get
{
return this._CityId;
}
set
{
if ((this._CityId != value))
{
if (this._City.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnCityIdChanging(value);
this.SendPropertyChanging();
this._CityId = value;
this.SendPropertyChanged("CityId");
this.OnCityIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CategoryId", DbType="BigInt NOT NULL")]
public long CategoryId
{
get
{
return this._CategoryId;
}
set
{
if ((this._CategoryId != value))
{
if (this._Category.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnCategoryIdChanging(value);
this.SendPropertyChanging();
this._CategoryId = value;
this.SendPropertyChanged("CategoryId");
this.OnCategoryIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Title", DbType="NVarChar(255)")]
public string Title
{
get
{
return this._Title;
}
set
{
if ((this._Title != value))
{
this.OnTitleChanging(value);
this.SendPropertyChanging();
this._Title = value;
this.SendPropertyChanged("Title");
this.OnTitleChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Description", DbType="NVarChar(MAX)")]
public string Description
{
get
{
return this._Description;
}
set
{
if ((this._Description != value))
{
this.OnDescriptionChanging(value);
this.SendPropertyChanging();
this._Description = value;
this.SendPropertyChanged("Description");
this.OnDescriptionChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Image", DbType="NVarChar(MAX)")]
public string Image
{
get
{
return this._Image;
}
set
{
if ((this._Image != value))
{
this.OnImageChanging(value);
this.SendPropertyChanging();
this._Image = value;
this.SendPropertyChanged("Image");
this.OnImageChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Address", DbType="NVarChar(MAX)")]
public string Address
{
get
{
return this._Address;
}
set
{
if ((this._Address != value))
{
this.OnAddressChanging(value);
this.SendPropertyChanging();
this._Address = value;
this.SendPropertyChanged("Address");
this.OnAddressChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Latitude", DbType="Float")]
public System.Nullable<double> Latitude
{
get
{
return this._Latitude;
}
set
{
if ((this._Latitude != value))
{
this.OnLatitudeChanging(value);
this.SendPropertyChanging();
this._Latitude = value;
this.SendPropertyChanged("Latitude");
this.OnLatitudeChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Longitude", DbType="Float")]
public System.Nullable<double> Longitude
{
get
{
return this._Longitude;
}
set
{
if ((this._Longitude != value))
{
this.OnLongitudeChanging(value);
this.SendPropertyChanging();
this._Longitude = value;
this.SendPropertyChanged("Longitude");
this.OnLongitudeChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_WorkTime", DbType="NVarChar(MAX)")]
public string WorkTime
{
get
{
return this._WorkTime;
}
set
{
if ((this._WorkTime != value))
{
this.OnWorkTimeChanging(value);
this.SendPropertyChanging();
this._WorkTime = value;
this.SendPropertyChanged("WorkTime");
this.OnWorkTimeChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Phone1", DbType="NVarChar(50)")]
public string Phone1
{
get
{
return this._Phone1;
}
set
{
if ((this._Phone1 != value))
{
this.OnPhone1Changing(value);
this.SendPropertyChanging();
this._Phone1 = value;
this.SendPropertyChanged("Phone1");
this.OnPhone1Changed();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Phone2", DbType="NVarChar(50)")]
public string Phone2
{
get
{
return this._Phone2;
}
set
{
if ((this._Phone2 != value))
{
this.OnPhone2Changing(value);
this.SendPropertyChanging();
this._Phone2 = value;
this.SendPropertyChanged("Phone2");
this.OnPhone2Changed();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Phone3", DbType="NVarChar(50)")]
public string Phone3
{
get
{
return this._Phone3;
}
set
{
if ((this._Phone3 != value))
{
this.OnPhone3Changing(value);
this.SendPropertyChanging();
this._Phone3 = value;
this.SendPropertyChanged("Phone3");
this.OnPhone3Changed();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Fax", DbType="NVarChar(50)")]
public string Fax
{
get
{
return this._Fax;
}
set
{
if ((this._Fax != value))
{
this.OnFaxChanging(value);
this.SendPropertyChanging();
this._Fax = value;
this.SendPropertyChanged("Fax");
this.OnFaxChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Email", DbType="NVarChar(255)")]
public string Email
{
get
{
return this._Email;
}
set
{
if ((this._Email != value))
{
this.OnEmailChanging(value);
this.SendPropertyChanging();
this._Email = value;
this.SendPropertyChanged("Email");
this.OnEmailChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Site", DbType="NVarChar(255)")]
public string Site
{
get
{
return this._Site;
}
set
{
if ((this._Site != value))
{
this.OnSiteChanging(value);
this.SendPropertyChanging();
this._Site = value;
this.SendPropertyChanged("Site");
this.OnSiteChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CashPayments", DbType="Bit NOT NULL")]
public bool CashPayments
{
get
{
return this._CashPayments;
}
set
{
if ((this._CashPayments != value))
{
this.OnCashPaymentsChanging(value);
this.SendPropertyChanging();
this._CashPayments = value;
this.SendPropertyChanged("CashPayments");
this.OnCashPaymentsChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CashlessPayments", DbType="Bit NOT NULL")]
public bool CashlessPayments
{
get
{
return this._CashlessPayments;
}
set
{
if ((this._CashlessPayments != value))
{
this.OnCashlessPaymentsChanging(value);
this.SendPropertyChanging();
this._CashlessPayments = value;
this.SendPropertyChanged("CashlessPayments");
this.OnCashlessPaymentsChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_WiFi", DbType="Bit NOT NULL")]
public bool WiFi
{
get
{
return this._WiFi;
}
set
{
if ((this._WiFi != value))
{
this.OnWiFiChanging(value);
this.SendPropertyChanging();
this._WiFi = value;
this.SendPropertyChanged("WiFi");
this.OnWiFiChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Booking", DbType="Bit NOT NULL")]
public bool Booking
{
get
{
return this._Booking;
}
set
{
if ((this._Booking != value))
{
this.OnBookingChanging(value);
this.SendPropertyChanging();
this._Booking = value;
this.SendPropertyChanged("Booking");
this.OnBookingChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Ordering", DbType="Bit NOT NULL")]
public bool Ordering
{
get
{
return this._Ordering;
}
set
{
if ((this._Ordering != value))
{
this.OnOrderingChanging(value);
this.SendPropertyChanging();
this._Ordering = value;
this.SendPropertyChanged("Ordering");
this.OnOrderingChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_AverageCheck", DbType="Money")]
public System.Nullable<decimal> AverageCheck
{
get
{
return this._AverageCheck;
}
set
{
if ((this._AverageCheck != value))
{
this.OnAverageCheckChanging(value);
this.SendPropertyChanging();
this._AverageCheck = value;
this.SendPropertyChanged("AverageCheck");
this.OnAverageCheckChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_VIPSection", DbType="Bit NOT NULL")]
public bool VIPSection
{
get
{
return this._VIPSection;
}
set
{
if ((this._VIPSection != value))
{
this.OnVIPSectionChanging(value);
this.SendPropertyChanging();
this._VIPSection = value;
this.SendPropertyChanged("VIPSection");
this.OnVIPSectionChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_LiveMusic", DbType="Bit NOT NULL")]
public bool LiveMusic
{
get
{
return this._LiveMusic;
}
set
{
if ((this._LiveMusic != value))
{
this.OnLiveMusicChanging(value);
this.SendPropertyChanging();
this._LiveMusic = value;
this.SendPropertyChanged("LiveMusic");
this.OnLiveMusicChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_SmokingRoom", DbType="Bit NOT NULL")]
public bool SmokingRoom
{
get
{
return this._SmokingRoom;
}
set
{
if ((this._SmokingRoom != value))
{
this.OnSmokingRoomChanging(value);
this.SendPropertyChanging();
this._SmokingRoom = value;
this.SendPropertyChanged("SmokingRoom");
this.OnSmokingRoomChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_BusinessLunch", DbType="Bit NOT NULL")]
public bool BusinessLunch
{
get
{
return this._BusinessLunch;
}
set
{
if ((this._BusinessLunch != value))
{
this.OnBusinessLunchChanging(value);
this.SendPropertyChanging();
this._BusinessLunch = value;
this.SendPropertyChanged("BusinessLunch");
this.OnBusinessLunchChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Hidden", DbType="Bit NOT NULL")]
public bool Hidden
{
get
{
return this._Hidden;
}
set
{
if ((this._Hidden != value))
{
this.OnHiddenChanging(value);
this.SendPropertyChanging();
this._Hidden = value;
this.SendPropertyChanged("Hidden");
this.OnHiddenChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateCreated", DbType="DateTime")]
public System.Nullable<System.DateTime> DateCreated
{
get
{
return this._DateCreated;
}
set
{
if ((this._DateCreated != value))
{
this.OnDateCreatedChanging(value);
this.SendPropertyChanging();
this._DateCreated = value;
this.SendPropertyChanged("DateCreated");
this.OnDateCreatedChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateModified", DbType="DateTime")]
public System.Nullable<System.DateTime> DateModified
{
get
{
return this._DateModified;
}
set
{
if ((this._DateModified != value))
{
this.OnDateModifiedChanging(value);
this.SendPropertyChanging();
this._DateModified = value;
this.SendPropertyChanged("DateModified");
this.OnDateModifiedChanged();
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Place_Event", Storage="_Events", ThisKey="Id", OtherKey="PlaceId")]
public EntitySet<Event> Events
{
get
{
return this._Events;
}
set
{
this._Events.Assign(value);
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Place_Product", Storage="_Products", ThisKey="Id", OtherKey="PlaceId")]
public EntitySet<Product> Products
{
get
{
return this._Products;
}
set
{
this._Products.Assign(value);
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Category_Place", Storage="_Category", ThisKey="CategoryId", OtherKey="Id", IsForeignKey=true)]
public Category Category
{
get
{
return this._Category.Entity;
}
set
{
Category previousValue = this._Category.Entity;
if (((previousValue != value)
|| (this._Category.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._Category.Entity = null;
previousValue.Places.Remove(this);
}
this._Category.Entity = value;
if ((value != null))
{
value.Places.Add(this);
this._CategoryId = value.Id;
}
else
{
this._CategoryId = default(long);
}
this.SendPropertyChanged("Category");
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="City_Place", Storage="_City", ThisKey="CityId", OtherKey="Id", IsForeignKey=true)]
public City City
{
get
{
return this._City.Entity;
}
set
{
City previousValue = this._City.Entity;
if (((previousValue != value)
|| (this._City.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._City.Entity = null;
previousValue.Places.Remove(this);
}
this._City.Entity = value;
if ((value != null))
{
value.Places.Add(this);
this._CityId = value.Id;
}
else
{
this._CityId = default(long);
}
this.SendPropertyChanged("City");
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private void attach_Events(Event entity)
{
this.SendPropertyChanging();
entity.Place = this;
}
private void detach_Events(Event entity)
{
this.SendPropertyChanging();
entity.Place = null;
}
private void attach_Products(Product entity)
{
this.SendPropertyChanging();
entity.Place = this;
}
private void detach_Products(Product entity)
{
this.SendPropertyChanging();
entity.Place = null;
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Events")]
public partial class Event : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private long _Id;
private long _PlaceId;
private System.DateTime _StartDateTime;
private System.Nullable<System.DateTime> _EndDateTime;
private string _Title;
private string _Description;
private string _Image;
private bool _Hidden;
private string _Summary;
private System.Nullable<System.DateTime> _DateCreated;
private System.Nullable<System.DateTime> _DateModified;
private EntityRef<Place> _Place;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(long value);
partial void OnIdChanged();
partial void OnPlaceIdChanging(long value);
partial void OnPlaceIdChanged();
partial void OnStartDateTimeChanging(System.DateTime value);
partial void OnStartDateTimeChanged();
partial void OnEndDateTimeChanging(System.Nullable<System.DateTime> value);
partial void OnEndDateTimeChanged();
partial void OnTitleChanging(string value);
partial void OnTitleChanged();
partial void OnDescriptionChanging(string value);
partial void OnDescriptionChanged();
partial void OnImageChanging(string value);
partial void OnImageChanged();
partial void OnHiddenChanging(bool value);
partial void OnHiddenChanged();
partial void OnSummaryChanging(string value);
partial void OnSummaryChanged();
partial void OnDateCreatedChanging(System.Nullable<System.DateTime> value);
partial void OnDateCreatedChanged();
partial void OnDateModifiedChanging(System.Nullable<System.DateTime> value);
partial void OnDateModifiedChanged();
#endregion
public Event()
{
this._Place = default(EntityRef<Place>);
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public long Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_PlaceId", DbType="BigInt NOT NULL")]
public long PlaceId
{
get
{
return this._PlaceId;
}
set
{
if ((this._PlaceId != value))
{
if (this._Place.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnPlaceIdChanging(value);
this.SendPropertyChanging();
this._PlaceId = value;
this.SendPropertyChanged("PlaceId");
this.OnPlaceIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_StartDateTime", DbType="DateTime NOT NULL")]
public System.DateTime StartDateTime
{
get
{
return this._StartDateTime;
}
set
{
if ((this._StartDateTime != value))
{
this.OnStartDateTimeChanging(value);
this.SendPropertyChanging();
this._StartDateTime = value;
this.SendPropertyChanged("StartDateTime");
this.OnStartDateTimeChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EndDateTime", DbType="DateTime")]
public System.Nullable<System.DateTime> EndDateTime
{
get
{
return this._EndDateTime;
}
set
{
if ((this._EndDateTime != value))
{
this.OnEndDateTimeChanging(value);
this.SendPropertyChanging();
this._EndDateTime = value;
this.SendPropertyChanged("EndDateTime");
this.OnEndDateTimeChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Title", DbType="NVarChar(255) NOT NULL", CanBeNull=false)]
public string Title
{
get
{
return this._Title;
}
set
{
if ((this._Title != value))
{
this.OnTitleChanging(value);
this.SendPropertyChanging();
this._Title = value;
this.SendPropertyChanged("Title");
this.OnTitleChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Description", DbType="NVarChar(MAX)")]
public string Description
{
get
{
return this._Description;
}
set
{
if ((this._Description != value))
{
this.OnDescriptionChanging(value);
this.SendPropertyChanging();
this._Description = value;
this.SendPropertyChanged("Description");
this.OnDescriptionChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Image", DbType="NVarChar(MAX)")]
public string Image
{
get
{
return this._Image;
}
set
{
if ((this._Image != value))
{
this.OnImageChanging(value);
this.SendPropertyChanging();
this._Image = value;
this.SendPropertyChanged("Image");
this.OnImageChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Hidden", DbType="Bit NOT NULL")]
public bool Hidden
{
get
{
return this._Hidden;
}
set
{
if ((this._Hidden != value))
{
this.OnHiddenChanging(value);
this.SendPropertyChanging();
this._Hidden = value;
this.SendPropertyChanged("Hidden");
this.OnHiddenChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Summary", DbType="NVarChar(MAX)")]
public string Summary
{
get
{
return this._Summary;
}
set
{
if ((this._Summary != value))
{
this.OnSummaryChanging(value);
this.SendPropertyChanging();
this._Summary = value;
this.SendPropertyChanged("Summary");
this.OnSummaryChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateCreated", DbType="DateTime")]
public System.Nullable<System.DateTime> DateCreated
{
get
{
return this._DateCreated;
}
set
{
if ((this._DateCreated != value))
{
this.OnDateCreatedChanging(value);
this.SendPropertyChanging();
this._DateCreated = value;
this.SendPropertyChanged("DateCreated");
this.OnDateCreatedChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateModified", DbType="DateTime")]
public System.Nullable<System.DateTime> DateModified
{
get
{
return this._DateModified;
}
set
{
if ((this._DateModified != value))
{
this.OnDateModifiedChanging(value);
this.SendPropertyChanging();
this._DateModified = value;
this.SendPropertyChanged("DateModified");
this.OnDateModifiedChanged();
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Place_Event", Storage="_Place", ThisKey="PlaceId", OtherKey="Id", IsForeignKey=true, DeleteOnNull=true, DeleteRule="CASCADE")]
public Place Place
{
get
{
return this._Place.Entity;
}
set
{
Place previousValue = this._Place.Entity;
if (((previousValue != value)
|| (this._Place.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._Place.Entity = null;
previousValue.Events.Remove(this);
}
this._Place.Entity = value;
if ((value != null))
{
value.Events.Add(this);
this._PlaceId = value.Id;
}
else
{
this._PlaceId = default(long);
}
this.SendPropertyChanged("Place");
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Products")]
public partial class Product : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private long _Id;
private long _PlaceId;
private short _Type;
private string _Title;
private string _Description;
private string _Category;
private string _Image;
private string _Price;
private string _Article;
private string _Weight;
private bool _Hidden;
private System.Nullable<System.DateTime> _DateCreated;
private System.Nullable<System.DateTime> _DateModified;
private EntityRef<Place> _Place;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(long value);
partial void OnIdChanged();
partial void OnPlaceIdChanging(long value);
partial void OnPlaceIdChanged();
partial void OnTypeChanging(short value);
partial void OnTypeChanged();
partial void OnTitleChanging(string value);
partial void OnTitleChanged();
partial void OnDescriptionChanging(string value);
partial void OnDescriptionChanged();
partial void OnCategoryChanging(string value);
partial void OnCategoryChanged();
partial void OnImageChanging(string value);
partial void OnImageChanged();
partial void OnPriceChanging(string value);
partial void OnPriceChanged();
partial void OnArticleChanging(string value);
partial void OnArticleChanged();
partial void OnWeightChanging(string value);
partial void OnWeightChanged();
partial void OnHiddenChanging(bool value);
partial void OnHiddenChanged();
partial void OnDateCreatedChanging(System.Nullable<System.DateTime> value);
partial void OnDateCreatedChanged();
partial void OnDateModifiedChanging(System.Nullable<System.DateTime> value);
partial void OnDateModifiedChanged();
#endregion
public Product()
{
this._Place = default(EntityRef<Place>);
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public long Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_PlaceId", DbType="BigInt NOT NULL")]
public long PlaceId
{
get
{
return this._PlaceId;
}
set
{
if ((this._PlaceId != value))
{
if (this._Place.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnPlaceIdChanging(value);
this.SendPropertyChanging();
this._PlaceId = value;
this.SendPropertyChanged("PlaceId");
this.OnPlaceIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Type", DbType="SmallInt NOT NULL")]
public short Type
{
get
{
return this._Type;
}
set
{
if ((this._Type != value))
{
this.OnTypeChanging(value);
this.SendPropertyChanging();
this._Type = value;
this.SendPropertyChanged("Type");
this.OnTypeChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Title", DbType="NVarChar(255) NOT NULL", CanBeNull=false)]
public string Title
{
get
{
return this._Title;
}
set
{
if ((this._Title != value))
{
this.OnTitleChanging(value);
this.SendPropertyChanging();
this._Title = value;
this.SendPropertyChanged("Title");
this.OnTitleChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Description", DbType="NVarChar(MAX)")]
public string Description
{
get
{
return this._Description;
}
set
{
if ((this._Description != value))
{
this.OnDescriptionChanging(value);
this.SendPropertyChanging();
this._Description = value;
this.SendPropertyChanged("Description");
this.OnDescriptionChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Category", DbType="NVarChar(MAX)")]
public string Category
{
get
{
return this._Category;
}
set
{
if ((this._Category != value))
{
this.OnCategoryChanging(value);
this.SendPropertyChanging();
this._Category = value;
this.SendPropertyChanged("Category");
this.OnCategoryChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Image", DbType="NVarChar(MAX)")]
public string Image
{
get
{
return this._Image;
}
set
{
if ((this._Image != value))
{
this.OnImageChanging(value);
this.SendPropertyChanging();
this._Image = value;
this.SendPropertyChanged("Image");
this.OnImageChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Price", DbType="NVarChar(MAX)")]
public string Price
{
get
{
return this._Price;
}
set
{
if ((this._Price != value))
{
this.OnPriceChanging(value);
this.SendPropertyChanging();
this._Price = value;
this.SendPropertyChanged("Price");
this.OnPriceChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Article", DbType="NVarChar(MAX)")]
public string Article
{
get
{
return this._Article;
}
set
{
if ((this._Article != value))
{
this.OnArticleChanging(value);
this.SendPropertyChanging();
this._Article = value;
this.SendPropertyChanged("Article");
this.OnArticleChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Weight", DbType="NVarChar(MAX)")]
public string Weight
{
get
{
return this._Weight;
}
set
{
if ((this._Weight != value))
{
this.OnWeightChanging(value);
this.SendPropertyChanging();
this._Weight = value;
this.SendPropertyChanged("Weight");
this.OnWeightChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Hidden", DbType="Bit NOT NULL")]
public bool Hidden
{
get
{
return this._Hidden;
}
set
{
if ((this._Hidden != value))
{
this.OnHiddenChanging(value);
this.SendPropertyChanging();
this._Hidden = value;
this.SendPropertyChanged("Hidden");
this.OnHiddenChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateCreated", DbType="DateTime")]
public System.Nullable<System.DateTime> DateCreated
{
get
{
return this._DateCreated;
}
set
{
if ((this._DateCreated != value))
{
this.OnDateCreatedChanging(value);
this.SendPropertyChanging();
this._DateCreated = value;
this.SendPropertyChanged("DateCreated");
this.OnDateCreatedChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateModified", DbType="DateTime")]
public System.Nullable<System.DateTime> DateModified
{
get
{
return this._DateModified;
}
set
{
if ((this._DateModified != value))
{
this.OnDateModifiedChanging(value);
this.SendPropertyChanging();
this._DateModified = value;
this.SendPropertyChanged("DateModified");
this.OnDateModifiedChanged();
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Place_Product", Storage="_Place", ThisKey="PlaceId", OtherKey="Id", IsForeignKey=true, DeleteOnNull=true, DeleteRule="CASCADE")]
public Place Place
{
get
{
return this._Place.Entity;
}
set
{
Place previousValue = this._Place.Entity;
if (((previousValue != value)
|| (this._Place.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._Place.Entity = null;
previousValue.Products.Remove(this);
}
this._Place.Entity = value;
if ((value != null))
{
value.Products.Add(this);
this._PlaceId = value.Id;
}
else
{
this._PlaceId = default(long);
}
this.SendPropertyChanged("Place");
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Publications")]
public partial class Publication : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private long _Id;
private long _CityId;
private string _Title;
private string _Annotation;
private string _Content;
private System.DateTime _PublicationDate;
private string _Category;
private string _Image;
private bool _Hidden;
private System.Nullable<System.DateTime> _DateCreated;
private System.Nullable<System.DateTime> _DateModified;
private EntityRef<City> _City;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(long value);
partial void OnIdChanged();
partial void OnCityIdChanging(long value);
partial void OnCityIdChanged();
partial void OnTitleChanging(string value);
partial void OnTitleChanged();
partial void OnAnnotationChanging(string value);
partial void OnAnnotationChanged();
partial void OnContentChanging(string value);
partial void OnContentChanged();
partial void OnPublicationDateChanging(System.DateTime value);
partial void OnPublicationDateChanged();
partial void OnCategoryChanging(string value);
partial void OnCategoryChanged();
partial void OnImageChanging(string value);
partial void OnImageChanged();
partial void OnHiddenChanging(bool value);
partial void OnHiddenChanged();
partial void OnDateCreatedChanging(System.Nullable<System.DateTime> value);
partial void OnDateCreatedChanged();
partial void OnDateModifiedChanging(System.Nullable<System.DateTime> value);
partial void OnDateModifiedChanged();
#endregion
public Publication()
{
this._City = default(EntityRef<City>);
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public long Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CityId", DbType="BigInt NOT NULL")]
public long CityId
{
get
{
return this._CityId;
}
set
{
if ((this._CityId != value))
{
if (this._City.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnCityIdChanging(value);
this.SendPropertyChanging();
this._CityId = value;
this.SendPropertyChanged("CityId");
this.OnCityIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Title", DbType="NVarChar(255) NOT NULL", CanBeNull=false)]
public string Title
{
get
{
return this._Title;
}
set
{
if ((this._Title != value))
{
this.OnTitleChanging(value);
this.SendPropertyChanging();
this._Title = value;
this.SendPropertyChanged("Title");
this.OnTitleChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Annotation", DbType="NVarChar(255)")]
public string Annotation
{
get
{
return this._Annotation;
}
set
{
if ((this._Annotation != value))
{
this.OnAnnotationChanging(value);
this.SendPropertyChanging();
this._Annotation = value;
this.SendPropertyChanged("Annotation");
this.OnAnnotationChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Content", DbType="NVarChar(MAX)")]
public string Content
{
get
{
return this._Content;
}
set
{
if ((this._Content != value))
{
this.OnContentChanging(value);
this.SendPropertyChanging();
this._Content = value;
this.SendPropertyChanged("Content");
this.OnContentChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_PublicationDate", DbType="DateTime NOT NULL")]
public System.DateTime PublicationDate
{
get
{
return this._PublicationDate;
}
set
{
if ((this._PublicationDate != value))
{
this.OnPublicationDateChanging(value);
this.SendPropertyChanging();
this._PublicationDate = value;
this.SendPropertyChanged("PublicationDate");
this.OnPublicationDateChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Category", DbType="NVarChar(255)")]
public string Category
{
get
{
return this._Category;
}
set
{
if ((this._Category != value))
{
this.OnCategoryChanging(value);
this.SendPropertyChanging();
this._Category = value;
this.SendPropertyChanged("Category");
this.OnCategoryChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Image", DbType="NVarChar(MAX)")]
public string Image
{
get
{
return this._Image;
}
set
{
if ((this._Image != value))
{
this.OnImageChanging(value);
this.SendPropertyChanging();
this._Image = value;
this.SendPropertyChanged("Image");
this.OnImageChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Hidden", DbType="Bit NOT NULL")]
public bool Hidden
{
get
{
return this._Hidden;
}
set
{
if ((this._Hidden != value))
{
this.OnHiddenChanging(value);
this.SendPropertyChanging();
this._Hidden = value;
this.SendPropertyChanged("Hidden");
this.OnHiddenChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateCreated", DbType="DateTime")]
public System.Nullable<System.DateTime> DateCreated
{
get
{
return this._DateCreated;
}
set
{
if ((this._DateCreated != value))
{
this.OnDateCreatedChanging(value);
this.SendPropertyChanging();
this._DateCreated = value;
this.SendPropertyChanged("DateCreated");
this.OnDateCreatedChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateModified", DbType="DateTime")]
public System.Nullable<System.DateTime> DateModified
{
get
{
return this._DateModified;
}
set
{
if ((this._DateModified != value))
{
this.OnDateModifiedChanging(value);
this.SendPropertyChanging();
this._DateModified = value;
this.SendPropertyChanged("DateModified");
this.OnDateModifiedChanged();
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="City_Publication", Storage="_City", ThisKey="CityId", OtherKey="Id", IsForeignKey=true, DeleteOnNull=true, DeleteRule="CASCADE")]
public City City
{
get
{
return this._City.Entity;
}
set
{
City previousValue = this._City.Entity;
if (((previousValue != value)
|| (this._City.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._City.Entity = null;
previousValue.Publications.Remove(this);
}
this._City.Entity = value;
if ((value != null))
{
value.Publications.Add(this);
this._CityId = value.Id;
}
else
{
this._CityId = default(long);
}
this.SendPropertyChanged("City");
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.CityUsers")]
public partial class CityUser : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private long _Id;
private long _CityId;
private long _UserId;
private System.DateTime _DateCreated;
private EntityRef<City> _City;
private EntityRef<User> _User;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(long value);
partial void OnIdChanged();
partial void OnCityIdChanging(long value);
partial void OnCityIdChanged();
partial void OnUserIdChanging(long value);
partial void OnUserIdChanged();
partial void OnDateCreatedChanging(System.DateTime value);
partial void OnDateCreatedChanged();
#endregion
public CityUser()
{
this._City = default(EntityRef<City>);
this._User = default(EntityRef<User>);
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public long Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CityId", DbType="BigInt NOT NULL")]
public long CityId
{
get
{
return this._CityId;
}
set
{
if ((this._CityId != value))
{
if (this._City.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnCityIdChanging(value);
this.SendPropertyChanging();
this._CityId = value;
this.SendPropertyChanged("CityId");
this.OnCityIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_UserId", DbType="BigInt NOT NULL")]
public long UserId
{
get
{
return this._UserId;
}
set
{
if ((this._UserId != value))
{
if (this._User.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnUserIdChanging(value);
this.SendPropertyChanging();
this._UserId = value;
this.SendPropertyChanged("UserId");
this.OnUserIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateCreated", DbType="DateTime NOT NULL")]
public System.DateTime DateCreated
{
get
{
return this._DateCreated;
}
set
{
if ((this._DateCreated != value))
{
this.OnDateCreatedChanging(value);
this.SendPropertyChanging();
this._DateCreated = value;
this.SendPropertyChanged("DateCreated");
this.OnDateCreatedChanged();
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="City_CityUser", Storage="_City", ThisKey="CityId", OtherKey="Id", IsForeignKey=true)]
public City City
{
get
{
return this._City.Entity;
}
set
{
City previousValue = this._City.Entity;
if (((previousValue != value)
|| (this._City.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._City.Entity = null;
previousValue.CityUsers.Remove(this);
}
this._City.Entity = value;
if ((value != null))
{
value.CityUsers.Add(this);
this._CityId = value.Id;
}
else
{
this._CityId = default(long);
}
this.SendPropertyChanged("City");
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="User_CityUser", Storage="_User", ThisKey="UserId", OtherKey="Id", IsForeignKey=true)]
public User User
{
get
{
return this._User.Entity;
}
set
{
User previousValue = this._User.Entity;
if (((previousValue != value)
|| (this._User.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._User.Entity = null;
previousValue.CityUsers.Remove(this);
}
this._User.Entity = value;
if ((value != null))
{
value.CityUsers.Add(this);
this._UserId = value.Id;
}
else
{
this._UserId = default(long);
}
this.SendPropertyChanged("User");
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Devices")]
public partial class Device : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private long _Id;
private short _Platform;
private long _CityId;
private string _Token;
private System.Nullable<System.DateTime> _DateRegistred;
private EntityRef<City> _City;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(long value);
partial void OnIdChanged();
partial void OnPlatformChanging(short value);
partial void OnPlatformChanged();
partial void OnCityIdChanging(long value);
partial void OnCityIdChanged();
partial void OnTokenChanging(string value);
partial void OnTokenChanged();
partial void OnDateRegistredChanging(System.Nullable<System.DateTime> value);
partial void OnDateRegistredChanged();
#endregion
public Device()
{
this._City = default(EntityRef<City>);
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public long Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Platform", DbType="SmallInt NOT NULL")]
public short Platform
{
get
{
return this._Platform;
}
set
{
if ((this._Platform != value))
{
this.OnPlatformChanging(value);
this.SendPropertyChanging();
this._Platform = value;
this.SendPropertyChanged("Platform");
this.OnPlatformChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CityId", DbType="BigInt NOT NULL")]
public long CityId
{
get
{
return this._CityId;
}
set
{
if ((this._CityId != value))
{
if (this._City.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnCityIdChanging(value);
this.SendPropertyChanging();
this._CityId = value;
this.SendPropertyChanged("CityId");
this.OnCityIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Token", DbType="NVarChar(MAX)")]
public string Token
{
get
{
return this._Token;
}
set
{
if ((this._Token != value))
{
this.OnTokenChanging(value);
this.SendPropertyChanging();
this._Token = value;
this.SendPropertyChanged("Token");
this.OnTokenChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateRegistred", DbType="DateTime")]
public System.Nullable<System.DateTime> DateRegistred
{
get
{
return this._DateRegistred;
}
set
{
if ((this._DateRegistred != value))
{
this.OnDateRegistredChanging(value);
this.SendPropertyChanging();
this._DateRegistred = value;
this.SendPropertyChanged("DateRegistred");
this.OnDateRegistredChanged();
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="City_Device", Storage="_City", ThisKey="CityId", OtherKey="Id", IsForeignKey=true)]
public City City
{
get
{
return this._City.Entity;
}
set
{
City previousValue = this._City.Entity;
if (((previousValue != value)
|| (this._City.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._City.Entity = null;
previousValue.Devices.Remove(this);
}
this._City.Entity = value;
if ((value != null))
{
value.Devices.Add(this);
this._CityId = value.Id;
}
else
{
this._CityId = default(long);
}
this.SendPropertyChanged("City");
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
#pragma warning restore 1591
| 24.535873 | 195 | 0.67747 | [
"MIT"
] | softgears/CityPlace | CityPlace.Domain/DAL/CityPlace.designer.cs | 110,119 | C# |
//*********************************************************************
//xCAD
//Copyright(C) 2021 Xarial Pty Limited
//Product URL: https://www.xcad.net
//License: https://xcad.xarial.com/license/
//*********************************************************************
using System;
using System.Collections.Generic;
using System.Text;
using Xarial.XCad.Documents;
using Xarial.XCad.Documents.Enums;
using Xarial.XCad.SolidWorks.Documents;
namespace Xarial.XCad.SolidWorks.Services
{
public class LazyNewDocumentGeometryBuilderDocumentProvider : IMemoryGeometryBuilderDocumentProvider
{
protected readonly ISwApplication m_App;
private ISwDocument m_TempDoc;
public LazyNewDocumentGeometryBuilderDocumentProvider(ISwApplication app)
{
m_App = app;
}
public ISwDocument ProvideDocument(Type geomType) => GetTempDocument();
protected virtual ISwDocument CreateTempDocument()
{
var activeDoc = m_App.Documents.Active;
var doc = (SwDocument)m_App.Documents.NewPart();
doc.Title = "xCADGeometryBuilderDoc_" + Guid.NewGuid().ToString();
if (activeDoc != null)
{
m_App.Documents.Active = activeDoc;
}
var curState = doc.State;
if (!curState.HasFlag(DocumentState_e.Hidden))
{
doc.State = curState | DocumentState_e.Hidden;
}
return doc;
}
private ISwDocument GetTempDocument()
{
if (!IsTempDocAlive())
{
m_TempDoc = CreateTempDocument();
}
return m_TempDoc;
}
private bool IsTempDocAlive()
{
if (m_TempDoc != null)
{
try
{
var title = m_TempDoc.Title;
return true;
}
catch
{
return false;
}
}
else
{
return false;
}
}
}
}
| 26.024096 | 104 | 0.496296 | [
"MIT"
] | EddyAlleman/xcad | src/SolidWorks/Services/LazyNewDocumentGeometryBuilderDocumentProvider.cs | 2,162 | C# |
// ==============================================================================================================
// Microsoft patterns & practices
// CQRS Journey project
// ==============================================================================================================
// ©2012 Microsoft. All rights reserved. Certain content used with permission from contributors
// http://cqrsjourney.github.com/contributors/members
// 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 Infrastructure.Azure
{
using Infrastructure.Azure.Messaging;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
/// <summary>
/// Admin helpers for tests.
/// </summary>
public static class BusSettingsExtensions
{
public static MessageReceiver CreateMessageReceiver(this ServiceBusSettings settings, string topic, string subscription)
{
var tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
var serviceUri = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);
var messagingFactory = MessagingFactory.Create(serviceUri, tokenProvider);
return messagingFactory.CreateMessageReceiver(SubscriptionClient.FormatDeadLetterPath(topic, subscription));
}
public static SubscriptionClient CreateSubscriptionClient(this ServiceBusSettings settings, string topic, string subscription, ReceiveMode mode = ReceiveMode.PeekLock)
{
var tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
var serviceUri = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);
var messagingFactory = MessagingFactory.Create(serviceUri, tokenProvider);
return messagingFactory.CreateSubscriptionClient(topic, subscription, mode);
}
public static TopicClient CreateTopicClient(this ServiceBusSettings settings, string topic)
{
var tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
var serviceUri = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);
var messagingFactory = MessagingFactory.Create(serviceUri, tokenProvider);
return messagingFactory.CreateTopicClient(topic);
}
public static void CreateTopic(this ServiceBusSettings settings, string topic)
{
new NamespaceManager(
ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath),
TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey))
.CreateTopic(topic);
}
public static void CreateSubscription(this ServiceBusSettings settings, string topic, string subscription)
{
CreateTopic(settings, topic);
new NamespaceManager(
ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath),
TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey))
.CreateSubscription(topic, subscription);
}
public static void CreateSubscription(this ServiceBusSettings settings, SubscriptionDescription description)
{
CreateTopic(settings, description.TopicPath);
new NamespaceManager(
ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath),
TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey))
.CreateSubscription(description);
}
public static void TryDeleteSubscription(this ServiceBusSettings settings, string topic, string subscription)
{
try
{
new NamespaceManager(
ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath),
TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey))
.DeleteSubscription(topic, subscription);
}
catch { }
}
public static void TryDeleteTopic(this ServiceBusSettings settings, string topic)
{
try
{
new NamespaceManager(
ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath),
TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey))
.DeleteTopic(topic);
}
catch { }
}
}
}
| 53.801887 | 175 | 0.672804 | [
"Apache-2.0"
] | jelster/cqrs-journey-code | source/Infrastructure/Azure/Infrastructure.Azure.IntegrationTests/MessagingSettingsExtensions.cs | 5,706 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace NullDffsGrabber
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter dffs path:");
string FileDffsPath = Console.ReadLine().Replace("\"", "");
byte[] data = File.ReadAllBytes(FileDffsPath);
MemoryStream memstr = new MemoryStream(data);
BinaryReader binread = new BinaryReader(memstr);
int FileStart = 1078346825;
byte[] buffer = new byte[] { 0, 0, 0, 0 };
while (true)
{
buffer[0] = buffer[1];
buffer[1] = buffer[2];
buffer[2] = buffer[3];
buffer[3] = binread.ReadByte();
if (FileStart == BitConverter.ToInt32(buffer, 0))
{
break;
}
}
Console.WriteLine("Найден маркер начала IDF@ файла. Смещение:" + binread.BaseStream.Position);
Console.WriteLine("Размер данных файла:" + binread.ReadInt32());
int files = 0;
Console.WriteLine("Количество файлов в IDF@ архиве:" + (files = binread.ReadInt32()));
binread.ReadInt64();
for (int i = 1; i < files; i++)
{
int filesize = binread.ReadInt32();
string FileName = Encoding.UTF8.GetString(binread.ReadBytes(0x108)).Replace("/","\\");
FileName = FileName.Remove(FileName.IndexOf("\0"));
File.WriteAllText(".\\test.txt", FileName);
byte[] fileadata = new byte[] { 0 };
if (filesize > 0)
fileadata = binread.ReadBytes(filesize);
Console.WriteLine("Чтение файла " + FileName + " размер данных:" + filesize + "/" + fileadata.Length);
if (!Directory.Exists(Path.GetDirectoryName(FileName)))
Directory.CreateDirectory(Path.GetDirectoryName(FileName));
File.WriteAllBytes(FileName,fileadata);
}
Console.ReadLine();
}
}
}
| 35.177419 | 118 | 0.527281 | [
"Unlicense"
] | UnrealKaraulov/NullDffsGrabber | NullDffsGrabber/Program.cs | 2,277 | C# |
namespace Forum.Services.Contracts
{
public interface ICategoryService
{
TModel ByName<TModel>(string name);
TModel Create<TModel>(string name);
}
}
| 15.8 | 37 | 0.746835 | [
"MIT"
] | HouseBreaker/ForumConsoleApp | Forum.Services/Contracts/ICategoryService.cs | 160 | C# |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace TestSvgControl
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
| 22.238095 | 65 | 0.595289 | [
"BSD-3-Clause"
] | yavor87/sharpvectors | Main/Samples/GdiTestSvgControl/Program.cs | 469 | C# |
using CU.Application.Data.Common.Interfaces;
using CU.Application.Shared.DataRequests.SchoolItems.Queries;
using CU.Application.Shared.Models.SchoolDtos;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace CU.ApplicationIntegrationTests.ApplicationTests
{
[Collection(TestFixture.DbCollectionName)]
public class GetCoursesTests : ApplicationTestBase
{
public GetCoursesTests(ITestOutputHelper testOutputHelper, TestFixture fixture)
: base(testOutputHelper, fixture)
{
}
[Fact]
public async Task CanGetCoursesPaginated()
{
GetCourseListItemsWithPaginationQuery query = new GetCourseListItemsWithPaginationQuery
{
PageNumber = 1,
PageSize = 5,
SortOrder = CourseSortOrder.ByCourseID
};
var result = await SendAsync(query);
result.Should().NotBeNull();
result.Items.Should().NotBeNull();
result.Items.Count.Should().BePositive();
result.TotalCount.Should().BeGreaterThanOrEqualTo(result.Items.Count);
CourseListItemDto firstListItem = result.Items.First();
firstListItem.Should().NotBeNull();
_testOutputHelper.WriteLine($"First course CourseID = {firstListItem.CourseID}, Title = [{firstListItem.Title}]");
_testOutputHelper.WriteLine($"Items.Count = {result.Items.Count}, TotalCount = {result.TotalCount}");
}
[SkippableFact]
public async Task CanGetCoursesForInstructor()
{
int instructorId = 0;
const string instructorLastName = "Kapoor";
using (var scope = _fixture.GetServiceScopeFactory(_testOutputHelper).CreateScope())
{
ISchoolDbContext cuContext = scope.ServiceProvider.GetRequiredService<ISchoolDbContext>();
cuContext.Should().NotBeNull();
instructorId = cuContext.Instructors.Where(i => i.LastName == instructorLastName)
.Select(i => i.ID)
.SingleOrDefault();
Skip.If(instructorId == 0, $"Did not find Instructor with Last Name [{instructorLastName}] - test cannot be completed");
}
GetCourseListItemsQuery query = new GetCourseListItemsQuery
{
InstructorID = instructorId,
SortOrder = CourseSortOrder.ByCourseID
};
var result = await SendAsync(query);
result.Should().NotBeNull();
result.Should().NotBeNull();
result.Count.Should().BePositive();
CourseListItemDto firstListItem = result.First();
firstListItem.Should().NotBeNull();
_testOutputHelper.WriteLine($"First course for instructor [{instructorLastName}], CourseID = {firstListItem.CourseID}, Title = [{firstListItem.Title}]");
_testOutputHelper.WriteLine($"Items.Count = {result.Count}");
}
[SkippableFact]
public async Task CanGetCoursesPaginatedForInstructor()
{
int instructorId = 0;
const string instructorLastName = "Kapoor";
using (var scope = _fixture.GetServiceScopeFactory(_testOutputHelper).CreateScope())
{
ISchoolDbContext cuContext = scope.ServiceProvider.GetRequiredService<ISchoolDbContext>();
cuContext.Should().NotBeNull();
instructorId = cuContext.Instructors.Where(i => i.LastName == instructorLastName)
.Select(i => i.ID)
.SingleOrDefault();
Skip.If(instructorId == 0, $"Did not find Instructor with Last Name [{instructorLastName}] - test cannot be completed");
}
GetCourseListItemsWithPaginationQuery query = new GetCourseListItemsWithPaginationQuery
{
InstructorID = instructorId,
PageNumber = 1,
PageSize = 5,
SortOrder = CourseSortOrder.ByCourseID
};
var result = await SendAsync(query);
result.Should().NotBeNull();
result.Items.Should().NotBeNull();
result.Items.Count.Should().BePositive();
result.TotalCount.Should().BeGreaterThanOrEqualTo(result.Items.Count);
CourseListItemDto firstListItem = result.Items.First();
firstListItem.Should().NotBeNull();
_testOutputHelper.WriteLine($"First course for instructor [{instructorLastName}], CourseID = {firstListItem.CourseID}, Title = [{firstListItem.Title}]");
_testOutputHelper.WriteLine($"Items.Count = {result.Items.Count}, TotalCount = {result.TotalCount}");
}
}
}
| 44.409091 | 165 | 0.626203 | [
"MIT"
] | bgoodearl/ContosoU_dn6_MVCB_Clean | tests/CU.ApplicationIntegrationTests/ApplicationTests/GetCoursesTests.cs | 4,887 | C# |
using System;
namespace Alex.Utils
{
public static class MathUtils
{
public static float ToRadians(float deg)
{
return (float)(Math.PI* deg / 180F);
return (float)(deg * (Math.PI / 180F));
}
public static float RadianToDegree(float angle)
{
return (float)(angle * (180.0f / Math.PI));
}
}
}
| 16.736842 | 49 | 0.644654 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | TruDan/Alex | src/Alex/Utils/MathUtils.cs | 320 | C# |
using Newtonsoft.Json;
namespace CompaniesHouse.Response.Document
{
public class DocumentMetadataContentLength
{
[JsonProperty("content_length")]
public int ContentLength { get; set; }
}
} | 21.8 | 46 | 0.697248 | [
"MIT"
] | SreejithNair/CompaniesHouse.NET | src/CompaniesHouse/Response/Document/DocumentMetadataContentLength.cs | 220 | C# |
using System;
namespace SixtenLabs.SpawnOfVulkan
{
public struct Rect2D
{
internal Offset2D Offset;
internal Extent2D Extent;
}
} | 15.9 | 34 | 0.660377 | [
"Unlicense"
] | SixtenLabs/SpawnOfVulkan | src/SixtenLabs.SpawnOfVulkan/Structs/Rect2D.cs | 161 | C# |
/*
Box2DNet Copyright (c) 2009 Ihar Kalasouski http://code.google.com/p/box2dx
Box2D original C++ version Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
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 System; using System.Numerics;
using Box2DNet.Common;
using Box2DNet.Collision;
using Transform = Box2DNet.Common.Transform;
namespace Box2DNet.Dynamics
{
/// <summary>
/// A body definition holds all the data needed to construct a rigid body.
/// You can safely re-use body definitions.
/// </summary>
public struct BodyDef
{
/// <summary>
/// This constructor sets the body definition default values.
/// </summary>
public BodyDef(byte init)
{
MassData = new MassData();
MassData.Center = Vector2.Zero;
MassData.Mass = 0.0f;
MassData.I = 0.0f;
UserData = null;
Position = Vector2.Zero;
Angle = 0.0f;
LinearVelocity = Vector2.Zero;
AngularVelocity = 0.0f;
LinearDamping = 0.0f;
AngularDamping = 0.0f;
AllowSleep = true;
IsSleeping = false;
FixedRotation = false;
IsBullet = false;
}
/// <summary>
/// You can use this to initialized the mass properties of the body.
/// If you prefer, you can set the mass properties after the shapes
/// have been added using Body.SetMassFromShapes.
/// </summary>
public MassData MassData;
/// <summary>
/// Use this to store application specific body data.
/// </summary>
public object UserData;
/// <summary>
/// The world position of the body. Avoid creating bodies at the origin
/// since this can lead to many overlapping shapes.
/// </summary>
public Vector2 Position;
/// <summary>
/// The world angle of the body in radians.
/// </summary>
public float Angle;
/// The linear velocity of the body in world co-ordinates.
public Vector2 LinearVelocity;
// The angular velocity of the body.
public float AngularVelocity;
/// <summary>
/// Linear damping is use to reduce the linear velocity. The damping parameter
/// can be larger than 1.0f but the damping effect becomes sensitive to the
/// time step when the damping parameter is large.
/// </summary>
public float LinearDamping;
/// <summary>
/// Angular damping is use to reduce the angular velocity. The damping parameter
/// can be larger than 1.0f but the damping effect becomes sensitive to the
/// time step when the damping parameter is large.
/// </summary>
public float AngularDamping;
/// <summary>
/// Set this flag to false if this body should never fall asleep. Note that
/// this increases CPU usage.
/// </summary>
public bool AllowSleep;
/// <summary>
/// Is this body initially sleeping?
/// </summary>
public bool IsSleeping;
/// <summary>
/// Should this body be prevented from rotating? Useful for characters.
/// </summary>
public bool FixedRotation;
/// <summary>
/// Is this a fast moving body that should be prevented from tunneling through
/// other moving bodies? Note that all bodies are prevented from tunneling through
/// static bodies.
/// @warning You should use this flag sparingly since it increases processing time.
/// </summary>
public bool IsBullet;
}
/// <summary>
/// A rigid body. These are created via World.CreateBody.
/// </summary>
public class Body : IDisposable
{
[Flags]
public enum BodyFlags
{
Frozen = 0x0002,
Island = 0x0004,
Sleep = 0x0008,
AllowSleep = 0x0010,
Bullet = 0x0020,
FixedRotation = 0x0040
}
public enum BodyType
{
Static,
Dynamic,
MaxTypes
}
internal BodyFlags _flags;
private BodyType _type;
internal int _islandIndex;
internal Transform _xf; // the body origin Transform
internal Sweep _sweep; // the swept motion for CCD
internal Vector2 _linearVelocity;
internal float _angularVelocity;
internal Vector2 _force;
internal float _torque;
private World _world;
internal Body _prev;
internal Body _next;
internal Fixture _fixtureList;
internal int _fixtureCount;
internal JointEdge _jointList;
internal ContactEdge _contactList;
internal Controllers.ControllerEdge _controllerList;
internal float _mass;
internal float _invMass;
internal float _I;
internal float _invI;
internal float _linearDamping;
internal float _angularDamping;
internal float _sleepTime;
private object _userData;
public int bodyID;
static int bodyCount = 0;
internal Body(BodyDef bd, World world)
{
_flags = 0;
if (bd.IsBullet)
{
_flags |= BodyFlags.Bullet;
}
if (bd.FixedRotation)
{
_flags |= BodyFlags.FixedRotation;
}
if (bd.AllowSleep)
{
_flags |= BodyFlags.AllowSleep;
}
if (bd.IsSleeping)
{
_flags |= BodyFlags.Sleep;
}
_world = world;
_xf.position = bd.Position;
_xf.rotation = Box2DNet.Common.Math.AngleToRotation(bd.Angle);
//_xf.R = new Mat22(bd.Angle);
_sweep.LocalCenter = bd.MassData.Center;
_sweep.T0 = 1.0f;
_sweep.A0 = _sweep.A = bd.Angle;
_sweep.C0 = _sweep.C = _xf.TransformPoint(_sweep.LocalCenter);
//_jointList = null;
//_contactList = null;
//_controllerList = null;
//_prev = null;
//_next = null;
_linearVelocity = bd.LinearVelocity;
_angularVelocity = bd.AngularVelocity;
_linearDamping = bd.LinearDamping;
_angularDamping = bd.AngularDamping;
//_force.Set(0.0f, 0.0f);
//_torque = 0.0f;
//_linearVelocity.SetZero();
//_angularVelocity = 0.0f;
//_sleepTime = 0.0f;
//_invMass = 0.0f;
//_I = 0.0f;
//_invI = 0.0f;
_mass = bd.MassData.Mass;
if (_mass > 0.0f)
{
_invMass = 1.0f / _mass;
}
_I = bd.MassData.I;
if (_I > 0.0f && (_flags & BodyFlags.FixedRotation) == 0)
{
_invI = 1.0f / _I;
}
if (_invMass == 0.0f && _invI == 0.0f)
{
_type = BodyType.Static;
}
else
{
_type = BodyType.Dynamic;
}
_userData = bd.UserData;
//_fixtureList = null;
//_fixtureCount = 0;
bodyID = bodyCount++;
}
public void Dispose()
{
// shapes and joints are destroyed in World.Destroy
}
internal bool SynchronizeFixtures()
{
Transform xf1 = new Transform();
xf1.rotation = Box2DNet.Common.Math.AngleToRotation(_sweep.A0);
//xf1.R = new Mat22(_sweep.A0);
xf1.position = _sweep.C0 - xf1.TransformDirection(_sweep.LocalCenter);
bool inRange = true;
for (Fixture f = _fixtureList; f != null; f = f.Next)
{
inRange = f.Synchronize(_world._broadPhase, xf1, _xf);
if (inRange == false)
{
break;
}
}
if (inRange == false)
{
_flags |= BodyFlags.Frozen;
_linearVelocity = Vector2.Zero;
_angularVelocity = 0.0f;
// Failure
return false;
}
// Success
return true;
}
// This is used to prevent connected bodies from colliding.
// It may lie, depending on the collideConnected flag.
internal bool IsConnected(Body other)
{
for (JointEdge jn = _jointList; jn != null; jn = jn.Next)
{
if (jn.Other == other)
return jn.Joint._collideConnected == false;
}
return false;
}
/// <summary>
/// Creates a fixture and attach it to this body.
/// @warning This function is locked during callbacks.
/// </summary>
/// <param name="def">The fixture definition.</param>
public Fixture CreateFixture(FixtureDef def)
{
if (_world._lock == true)
{
return null;
}
BroadPhase broadPhase = _world._broadPhase;
Fixture fixture = new Fixture();
fixture.Create(broadPhase, this, _xf, def);
fixture._next = _fixtureList;
_fixtureList = fixture;
++_fixtureCount;
fixture._body = this;
return fixture;
}
/// <summary>
/// Destroy a fixture. This removes the fixture from the broad-phase and
/// therefore destroys any contacts associated with this fixture. All fixtures
/// attached to a body are implicitly destroyed when the body is destroyed.
/// @warning This function is locked during callbacks.
/// </summary>
/// <param name="fixture">The fixture to be removed.</param>
public void DestroyFixture(Fixture fixture)
{
if (_world._lock == true)
{
return;
}
// Remove the fixture from this body's singly linked list.
Fixture node = _fixtureList;
bool found = false;
while (node != null)
{
if (node == fixture)
{
//*node = fixture->m_next;
_fixtureList = fixture.Next;
found = true;
break;
}
node = node.Next;
}
// You tried to remove a shape that is not attached to this body.
BroadPhase broadPhase = _world._broadPhase;
fixture.Destroy(broadPhase);
fixture._body = null;
fixture._next = null;
--_fixtureCount;
}
// TODO_ERIN adjust linear velocity and torque to account for movement of center.
/// <summary>
/// Set the mass properties. Note that this changes the center of mass position.
/// If you are not sure how to compute mass properties, use SetMassFromShapes.
/// The inertia tensor is assumed to be relative to the center of mass.
/// </summary>
/// <param name="massData">The mass properties.</param>
public void SetMass(MassData massData)
{
if (_world._lock == true)
{
return;
}
_invMass = 0.0f;
_I = 0.0f;
_invI = 0.0f;
_mass = massData.Mass;
if (_mass > 0.0f)
{
_invMass = 1.0f / _mass;
}
_I = massData.I;
if (_I > 0.0f && (_flags & BodyFlags.FixedRotation) == 0)
{
_invI = 1.0f / _I;
}
// Move center of mass.
_sweep.LocalCenter = massData.Center;
_sweep.C0 = _sweep.C = _xf.TransformPoint(_sweep.LocalCenter);
BodyType oldType = _type;
if (_invMass == 0.0f && _invI == 0.0f)
{
_type = BodyType.Static;
}
else
{
_type = BodyType.Dynamic;
}
// If the body type changed, we need to refilter the broad-phase proxies.
if (oldType != _type)
{
for (Fixture f = _fixtureList; f != null; f = f.Next)
{
f.RefilterProxy(_world._broadPhase, _xf);
}
}
}
// TODO_ERIN adjust linear velocity and torque to account for movement of center.
/// <summary>
/// Compute the mass properties from the attached shapes. You typically call this
/// after adding all the shapes. If you add or remove shapes later, you may want
/// to call this again. Note that this changes the center of mass position.
/// </summary>
public void SetMassFromShapes()
{
if (_world._lock == true)
{
return;
}
// Compute mass data from shapes. Each shape has its own density.
_mass = 0.0f;
_invMass = 0.0f;
_I = 0.0f;
_invI = 0.0f;
Vector2 center = Vector2.Zero;
for (Fixture f = _fixtureList; f != null; f = f.Next)
{
MassData massData;
f.ComputeMass(out massData);
_mass += massData.Mass;
center += massData.Mass * massData.Center;
_I += massData.I;
}
// Compute center of mass, and shift the origin to the COM.
if (_mass > 0.0f)
{
_invMass = 1.0f / _mass;
center *= _invMass;
}
if (_I > 0.0f && (_flags & BodyFlags.FixedRotation) == 0)
{
// Center the inertia about the center of mass.
_I -= _mass * Vector2.Dot(center, center);
_invI = 1.0f / _I;
}
else
{
_I = 0.0f;
_invI = 0.0f;
}
// Move center of mass.
_sweep.LocalCenter = center;
_sweep.C0 = _sweep.C = _xf.TransformPoint(_sweep.LocalCenter);
BodyType oldType = _type;
if (_invMass == 0.0f && _invI == 0.0f)
{
_type = BodyType.Static;
}
else
{
_type = BodyType.Dynamic;
}
// If the body type changed, we need to refilter the broad-phase proxies.
if (oldType != _type)
{
for (Fixture f = _fixtureList; f != null; f = f.Next)
{
f.RefilterProxy(_world._broadPhase, _xf);
}
}
}
public bool SetTransform(Vector2 position, float angle)
{
return SetTransform(position, Box2DNet.Common.Math.AngleToRotation(angle));
}
#if USE_MATRIX_FOR_ROTATION
/// <summary>
/// Set the position of the body's origin and rotation (radians).
/// This breaks any contacts and wakes the other bodies.
/// </summary>
/// <param name="position">The new world position of the body's origin (not necessarily
/// the center of mass).</param>
/// <param name="angle">The new world rotation angle of the body in radians.</param>
/// <returns>Return false if the movement put a shape outside the world. In this case the
/// body is automatically frozen.</returns>
public bool SetTransform(Vector2 position, Mat22 rotation)
#else
public bool SetTransform(Vector2 position, Quaternion rotation)
#endif
{
if (_world._lock == true)
{
return true;
}
if (IsFrozen())
{
return false;
}
_xf.rotation = rotation;
//_xf.R = rotation;
_xf.position = position;
_sweep.C0 = _sweep.C = _xf.TransformPoint(_sweep.LocalCenter);
#if USE_MATRIX_FOR_ROTATION
_sweep.A0 = _sweep.A = rotation.GetAngle();
#else
_sweep.A0 = _sweep.A = (rotation.Z * 180 / (float)System.Math.PI) * 0.0174532924f;
#endif
bool freeze = false;
for (Fixture f = _fixtureList; f != null; f = f.Next)
{
bool inRange = f.Synchronize(_world._broadPhase, _xf, _xf);
if (inRange == false)
{
freeze = true;
break;
}
}
if (freeze == true)
{
_flags |= BodyFlags.Frozen;
_linearVelocity = Vector2.Zero;
_angularVelocity = 0.0f;
// Failure
return false;
}
// Success
_world._broadPhase.Commit();
return true;
}
/// <summary>
/// Set the position of the body's origin and rotation (radians).
/// This breaks any contacts and wakes the other bodies.
/// Note this is less efficient than the other overload - you should use that
/// if the angle is available.
/// </summary>
/// <param name="xf">The Transform of position and angle to set the body to.</param>
/// <returns>False if the movement put a shape outside the world. In this case the
/// body is automatically frozen.</returns>
public bool SetTransform(Transform xf)
{
return SetTransform(xf.position, xf.rotation);
}
/// <summary>
/// Get the body Transform for the body's origin.
/// </summary>
/// <returns>Return the world Transform of the body's origin.</returns>
public Transform GetTransform()
{
return _xf;
}
/// <summary>
/// Set the world body origin position.
/// </summary>
/// <param name="position">The new position of the body.</param>
public void SetPosition(Vector2 position)
{
#if USE_MATRIX_FOR_ROTATION
SetTransform(position, new Mat22(GetAngle()));
#else
SetTransform(position, Box2DNet.Common.Math.AngleToRotation(GetAngle()));
#endif
}
/// <summary>
/// Set the world body angle.
/// </summary>
/// <param name="angle">The new angle of the body in radians</param>
public void SetAngle(float angle)
{
#if USE_MATRIX_FOR_ROTATION
SetTransform(GetPosition(), new Mat22(angle));
#else
SetTransform(GetPosition(), Box2DNet.Common.Math.AngleToRotation(angle));
#endif
}
/// <summary>
/// Get the world body origin position.
/// </summary>
/// <returns>Return the world position of the body's origin.</returns>
public Vector2 GetPosition()
{
return _xf.position;
}
/// <summary>
/// Get the angle in radians.
/// </summary>
/// <returns>Return the current world rotation angle in radians.</returns>
public float GetAngle()
{
return _sweep.A;
}
/// <summary>
/// Get the world position of the center of mass.
/// </summary>
/// <returns></returns>
public Vector2 GetWorldCenter()
{
return _sweep.C;
}
/// <summary>
/// Get the local position of the center of mass.
/// </summary>
/// <returns></returns>
public Vector2 GetLocalCenter()
{
return _sweep.LocalCenter;
}
/// <summary>
/// Set the linear velocity of the center of mass.
/// </summary>
/// <param name="v">The new linear velocity of the center of mass.</param>
public void SetLinearVelocity(Vector2 v)
{
_linearVelocity = v;
}
/// <summary>
/// Get the linear velocity of the center of mass.
/// </summary>
/// <returns>Return the linear velocity of the center of mass.</returns>
public Vector2 GetLinearVelocity()
{
return _linearVelocity;
}
/// <summary>
/// Set the angular velocity.
/// </summary>
/// <param name="omega">The new angular velocity in radians/second.</param>
public void SetAngularVelocity(float w)
{
_angularVelocity = w;
}
/// <summary>
/// Get the angular velocity.
/// </summary>
/// <returns>Return the angular velocity in radians/second.</returns>
public float GetAngularVelocity()
{
return _angularVelocity;
}
/// <summary>
/// Apply a force at a world point. If the force is not
/// applied at the center of mass, it will generate a torque and
/// affect the angular velocity. This wakes up the body.
/// </summary>
/// <param name="force">The world force vector, usually in Newtons (N).</param>
/// <param name="point">The world position of the point of application.</param>
public void ApplyForce(Vector2 force, Vector2 point)
{
if (IsSleeping())
{
WakeUp();
}
_force += force;
_torque += (point - _sweep.C).Cross(force);
}
/// <summary>
/// Apply a torque. This affects the angular velocity
/// without affecting the linear velocity of the center of mass.
/// This wakes up the body.
/// </summary>
/// <param name="torque">Torque about the z-axis (out of the screen), usually in N-m.</param>
public void ApplyTorque(float torque)
{
if (IsSleeping())
{
WakeUp();
}
_torque += torque;
}
/// <summary>
/// Apply an impulse at a point. This immediately modifies the velocity.
/// It also modifies the angular velocity if the point of application
/// is not at the center of mass. This wakes up the body.
/// </summary>
/// <param name="impulse">The world impulse vector, usually in N-seconds or kg-m/s.</param>
/// <param name="point">The world position of the point of application.</param>
public void ApplyImpulse(Vector2 impulse, Vector2 point)
{
if (IsSleeping())
{
WakeUp();
}
_linearVelocity += _invMass * impulse;
_angularVelocity += _invI * (point - _sweep.C).Cross(impulse);
}
/// <summary>
/// Get the total mass of the body.
/// </summary>
/// <returns>Return the mass, usually in kilograms (kg).</returns>
public float GetMass()
{
return _mass;
}
/// <summary>
/// Get the central rotational inertia of the body.
/// </summary>
/// <returns>Return the rotational inertia, usually in kg-m^2.</returns>
public float GetInertia()
{
return _I;
}
/// <summary>
/// Get the mass data of the body.
/// </summary>
/// <returns>A struct containing the mass, inertia and center of the body.</returns>
public MassData GetMassData()
{
MassData massData = new MassData();
massData.Mass = _mass;
massData.I = _I;
massData.Center = GetWorldCenter();
return massData;
}
/// <summary>
/// Get the world coordinates of a point given the local coordinates.
/// </summary>
/// <param name="localPoint">A point on the body measured relative the the body's origin.</param>
/// <returns>Return the same point expressed in world coordinates.</returns>
public Vector2 GetWorldPoint(Vector2 localPoint)
{
return _xf.TransformPoint(localPoint);
}
/// <summary>
/// Get the world coordinates of a vector given the local coordinates.
/// </summary>
/// <param name="localVector">A vector fixed in the body.</param>
/// <returns>Return the same vector expressed in world coordinates.</returns>
public Vector2 GetWorldVector(Vector2 localVector)
{
return _xf.TransformDirection(localVector);
}
/// <summary>
/// Gets a local point relative to the body's origin given a world point.
/// </summary>
/// <param name="worldPoint">A point in world coordinates.</param>
/// <returns>Return the corresponding local point relative to the body's origin.</returns>
public Vector2 GetLocalPoint(Vector2 worldPoint)
{
return _xf.InverseTransformPoint(worldPoint);
}
/// <summary>
/// Gets a local vector given a world vector.
/// </summary>
/// <param name="worldVector">A vector in world coordinates.</param>
/// <returns>Return the corresponding local vector.</returns>
public Vector2 GetLocalVector(Vector2 worldVector)
{
return _xf.InverseTransformDirection(worldVector);
}
/// <summary>
/// Get the world linear velocity of a world point attached to this body.
/// </summary>
/// <param name="worldPoint">A point in world coordinates.</param>
/// <returns>The world velocity of a point.</returns>
public Vector2 GetLinearVelocityFromWorldPoint(Vector2 worldPoint)
{
return _linearVelocity + (worldPoint - _sweep.C).CrossScalarPreMultiply(_angularVelocity);
}
/// <summary>
/// Get the world velocity of a local point.
/// </summary>
/// <param name="localPoint">A point in local coordinates.</param>
/// <returns>The world velocity of a point.</returns>
public Vector2 GetLinearVelocityFromLocalPoint(Vector2 localPoint)
{
return GetLinearVelocityFromWorldPoint(GetWorldPoint(localPoint));
}
public float GetLinearDamping()
{
return _linearDamping;
}
public void SetLinearDamping(float linearDamping)
{
_linearDamping = linearDamping;
}
public float GetAngularDamping()
{
return _angularDamping;
}
public void SetAngularDamping(float angularDamping)
{
_angularDamping = angularDamping;
}
/// <summary>
/// Is this body treated like a bullet for continuous collision detection?
/// </summary>
/// <returns></returns>
public bool IsBullet()
{
return (_flags & BodyFlags.Bullet) == BodyFlags.Bullet;
}
/// <summary>
/// Should this body be treated like a bullet for continuous collision detection?
/// </summary>
/// <param name="flag"></param>
public void SetBullet(bool flag)
{
if (flag)
{
_flags |= BodyFlags.Bullet;
}
else
{
_flags &= ~BodyFlags.Bullet;
}
}
public bool IsFixedRotation()
{
return (_flags & BodyFlags.FixedRotation) == BodyFlags.FixedRotation;
}
public void SetFixedRotation(bool fixedr)
{
if (fixedr)
{
_angularVelocity = 0.0f;
_invI = 0.0f;
_flags |= BodyFlags.FixedRotation;
}
else
{
if (_I > 0.0f)
{
// Recover _invI from _I.
_invI = 1.0f / _I;
_flags &= BodyFlags.FixedRotation;
}
// TODO: Else what?
}
}
/// <summary>
/// Is this body static (immovable)?
/// </summary>
/// <returns></returns>
public bool IsStatic()
{
return _type == BodyType.Static;
}
public void SetStatic()
{
if (_type == BodyType.Static)
return;
_mass = 0.0f;
_invMass = 0.0f;
_I = 0.0f;
_invI = 0.0f;
_type = BodyType.Static;
for (Fixture f = _fixtureList; f != null; f = f.Next)
{
f.RefilterProxy(_world._broadPhase, _xf);
}
}
/// <summary>
/// Is this body dynamic (movable)?
/// </summary>
/// <returns></returns>
public bool IsDynamic()
{
return _type == BodyType.Dynamic;
}
/// <summary>
/// Is this body frozen?
/// </summary>
/// <returns></returns>
public bool IsFrozen()
{
return (_flags & BodyFlags.Frozen) == BodyFlags.Frozen;
}
/// <summary>
/// Is this body sleeping (not simulating).
/// </summary>
/// <returns></returns>
public bool IsSleeping()
{
return (_flags & BodyFlags.Sleep) == BodyFlags.Sleep;
}
public bool IsAllowSleeping()
{
return (_flags & BodyFlags.AllowSleep) == BodyFlags.AllowSleep;
}
/// <summary>
/// You can disable sleeping on this body.
/// </summary>
/// <param name="flag"></param>
public void AllowSleeping(bool flag)
{
if (flag)
{
_flags |= BodyFlags.AllowSleep;
}
else
{
_flags &= ~BodyFlags.AllowSleep;
WakeUp();
}
}
/// <summary>
/// Wake up this body so it will begin simulating.
/// </summary>
public void WakeUp()
{
_flags &= ~BodyFlags.Sleep;
_sleepTime = 0.0f;
}
/// <summary>
/// Put this body to sleep so it will stop simulating.
/// This also sets the velocity to zero.
/// </summary>
public void PutToSleep()
{
_flags |= BodyFlags.Sleep;
_sleepTime = 0.0f;
_linearVelocity = Vector2.Zero;
_angularVelocity = 0.0f;
_force = Vector2.Zero;
_torque = 0.0f;
}
/// <summary>
/// Get the list of all fixtures attached to this body.
/// </summary>
/// <returns></returns>
public Fixture GetFixtureList()
{
return _fixtureList;
}
/// <summary>
/// Get the list of all joints attached to this body.
/// </summary>
/// <returns></returns>
public JointEdge GetJointList()
{
return _jointList;
}
public Controllers.ControllerEdge GetControllerList()
{
return _controllerList;
}
/// <summary>
/// Get the next body in the world's body list.
/// </summary>
/// <returns></returns>
public Body GetNext()
{
return _next;
}
/// <summary>
/// Get the user data pointer that was provided in the body definition.
/// </summary>
/// <returns></returns>
public object GetUserData()
{
return _userData;
}
/// <summary>
/// Set the user data. Use this to store your application specific data.
/// </summary>
/// <param name="data"></param>
public void SetUserData(object data) { _userData = data; }
/// <summary>
/// Get the parent world of this body.
/// </summary>
/// <returns></returns>
public World GetWorld() { return _world; }
internal void SynchronizeTransform()
{
//_xf.R = new Mat22(_sweep.A);
_xf.rotation = Box2DNet.Common.Math.AngleToRotation(_sweep.A);
_xf.position = _sweep.C - _xf.TransformDirection(_sweep.LocalCenter);//Common.Math.Mul(_xf.R, _sweep.LocalCenter);
}
internal void Advance(float t)
{
// Advance to the new safe time.
_sweep.Advance(t);
_sweep.C = _sweep.C0;
_sweep.A = _sweep.A0;
SynchronizeTransform();
}
}
}
| 24.53516 | 117 | 0.653242 | [
"Apache-2.0"
] | NocturnalWisp/Tynted-Engine | TyntedEngine/Physics/Dynamics/Body.cs | 26,868 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma warning disable 1634, 1691
#pragma warning disable 56523
using Dbg = System.Management.Automation;
using System.IO;
using System.Management.Automation.Internal;
using System.Management.Automation.Security;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using DWORD = System.UInt32;
namespace System.Management.Automation
{
/// <summary>
/// Defines the options that control what data is embedded in the
/// signature blob.
/// </summary>
public enum SigningOption
{
/// <summary>
/// Embeds only the signer's certificate.
/// </summary>
AddOnlyCertificate,
/// <summary>
/// Embeds the entire certificate chain.
/// </summary>
AddFullCertificateChain,
/// <summary>
/// Embeds the entire certificate chain, except for the root
/// certificate.
/// </summary>
AddFullCertificateChainExceptRoot,
/// <summary>
/// Default: Embeds the entire certificate chain, except for the
/// root certificate.
/// </summary>
Default = AddFullCertificateChainExceptRoot
}
/// <summary>
/// Helper functions for signature functionality.
/// </summary>
internal static class SignatureHelper
{
/// <summary>
/// Tracer for SignatureHelper.
/// </summary>
[Dbg.TraceSource("SignatureHelper",
"tracer for SignatureHelper")]
private static readonly Dbg.PSTraceSource s_tracer =
Dbg.PSTraceSource.GetTracer("SignatureHelper",
"tracer for SignatureHelper");
/// <summary>
/// Sign a file.
/// </summary>
/// <param name="option">Option that controls what gets embedded in the signature blob.</param>
/// <param name="fileName">Name of file to sign.</param>
/// <param name="certificate">Signing cert.</param>
/// <param name="timeStampServerUrl">URL of time stamping server.</param>
/// <param name="hashAlgorithm"> The name of the hash
/// algorithm to use.</param>
/// <returns>Does not return a value.</returns>
/// <exception cref="System.ArgumentNullException">
/// Thrown if argument fileName or certificate is null.
/// </exception>
/// <exception cref="System.ArgumentException">
/// Thrown if
/// -- argument fileName is empty OR
/// -- the specified certificate is not suitable for
/// signing code
/// </exception>
/// <exception cref="System.Security.Cryptography.CryptographicException">
/// This exception can be thrown if any cryptographic error occurs.
/// It is not possible to know exactly what went wrong.
/// This is because of the way CryptographicException is designed.
/// Possible reasons:
/// -- certificate is invalid
/// -- certificate has no private key
/// -- certificate password mismatch
/// -- etc
/// </exception>
/// <exception cref="System.IO.FileNotFoundException">
/// Thrown if the file specified by argument fileName is not found
/// </exception>
[ArchitectureSensitive]
internal static Signature SignFile(SigningOption option,
string fileName,
X509Certificate2 certificate,
string timeStampServerUrl,
string hashAlgorithm)
{
bool result = false;
Signature signature = null;
IntPtr pSignInfo = IntPtr.Zero;
DWORD error = 0;
string hashOid = null;
Utils.CheckArgForNullOrEmpty(fileName, "fileName");
Utils.CheckArgForNull(certificate, "certificate");
// If given, TimeStamp server URLs must begin with http://
if (!string.IsNullOrEmpty(timeStampServerUrl))
{
if ((timeStampServerUrl.Length <= 7) ||
(timeStampServerUrl.IndexOf("http://", StringComparison.OrdinalIgnoreCase) != 0))
{
throw PSTraceSource.NewArgumentException(
"certificate",
Authenticode.TimeStampUrlRequired);
}
}
// Validate that the hash algorithm is valid
if (!string.IsNullOrEmpty(hashAlgorithm))
{
IntPtr intptrAlgorithm = Marshal.StringToHGlobalUni(hashAlgorithm);
IntPtr oidPtr = NativeMethods.CryptFindOIDInfo(NativeConstants.CRYPT_OID_INFO_NAME_KEY,
intptrAlgorithm,
0);
// If we couldn't find an OID for the hash
// algorithm, it was invalid.
if (oidPtr == IntPtr.Zero)
{
throw PSTraceSource.NewArgumentException(
"certificate",
Authenticode.InvalidHashAlgorithm);
}
else
{
NativeMethods.CRYPT_OID_INFO oidInfo =
Marshal.PtrToStructure<NativeMethods.CRYPT_OID_INFO>(oidPtr);
hashOid = oidInfo.pszOID;
}
}
if (!SecuritySupport.CertIsGoodForSigning(certificate))
{
throw PSTraceSource.NewArgumentException(
"certificate",
Authenticode.CertNotGoodForSigning);
}
SecuritySupport.CheckIfFileExists(fileName);
// SecurityUtils.CheckIfFileSmallerThan4Bytes(fileName);
try
{
// CryptUI is not documented either way, but does not
// support empty strings for the timestamp server URL.
// It expects null, only. Instead, it randomly AVs if you
// try.
string timeStampServerUrlForCryptUI = null;
if (!string.IsNullOrEmpty(timeStampServerUrl))
{
timeStampServerUrlForCryptUI = timeStampServerUrl;
}
//
// first initialize the struct to pass to
// CryptUIWizDigitalSign() function
//
NativeMethods.CRYPTUI_WIZ_DIGITAL_SIGN_INFO si = NativeMethods.InitSignInfoStruct(fileName,
certificate,
timeStampServerUrlForCryptUI,
hashOid,
option);
pSignInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(si));
Marshal.StructureToPtr(si, pSignInfo, false);
//
// sign the file
//
// The GetLastWin32Error of this is checked, but PreSharp doesn't seem to be
// able to see that.
#pragma warning disable 56523
result = NativeMethods.CryptUIWizDigitalSign(
(DWORD)NativeMethods.CryptUIFlags.CRYPTUI_WIZ_NO_UI,
IntPtr.Zero,
IntPtr.Zero,
pSignInfo,
IntPtr.Zero);
#pragma warning restore 56523
if (si.pSignExtInfo != null)
{
Marshal.DestroyStructure<NativeMethods.CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO>(si.pSignExtInfo);
Marshal.FreeCoTaskMem(si.pSignExtInfo);
}
if (!result)
{
error = GetLastWin32Error();
//
// ISSUE-2004/05/08-kumarp : there seems to be a bug
// in CryptUIWizDigitalSign().
// It returns 80004005 or 80070001
// but it signs the file correctly. Mask this error
// till we figure out this odd behavior.
//
if ((error == 0x80004005) ||
(error == 0x80070001) ||
// CryptUIWizDigitalSign introduced a breaking change in Win8 to return this
// error code (ERROR_INTERNET_NAME_NOT_RESOLVED) when you provide an invalid
// timestamp server. It used to be 0x80070001.
// Also masking this out so that we don't introduce a breaking change ourselves.
(error == 0x80072EE7)
)
{
result = true;
}
else
{
if (error == Win32Errors.NTE_BAD_ALGID)
{
throw PSTraceSource.NewArgumentException(
"certificate",
Authenticode.InvalidHashAlgorithm);
}
s_tracer.TraceError("CryptUIWizDigitalSign: failed: {0:x}",
error);
}
}
if (result)
{
signature = GetSignature(fileName, null);
}
else
{
signature = new Signature(fileName, (DWORD)error);
}
}
finally
{
Marshal.DestroyStructure<NativeMethods.CRYPTUI_WIZ_DIGITAL_SIGN_INFO>(pSignInfo);
Marshal.FreeCoTaskMem(pSignInfo);
}
return signature;
}
/// <summary>
/// Get signature on the specified file.
/// </summary>
/// <param name="fileName">Name of file to check.</param>
/// <param name="fileContent">Content of file to check.</param>
/// <returns>Signature object.</returns>
/// <exception cref="System.ArgumentException">
/// Thrown if argument fileName is empty.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown if argument fileName is null
/// </exception>
/// <exception cref="System.IO.FileNotFoundException">
/// Thrown if the file specified by argument fileName is not found.
/// </exception>
[ArchitectureSensitive]
internal static Signature GetSignature(string fileName, string fileContent)
{
Signature signature = null;
if (fileContent == null)
{
// First, try to get the signature from the catalog signature APIs.
signature = GetSignatureFromCatalog(fileName);
}
// If there is no signature or it is invalid, go by the file content
// with the older WinVerifyTrust APIs
if ((signature == null) || (signature.Status != SignatureStatus.Valid))
{
signature = GetSignatureFromWinVerifyTrust(fileName, fileContent);
}
return signature;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")]
private static Signature GetSignatureFromCatalog(string filename)
{
if (Signature.CatalogApiAvailable.HasValue && !Signature.CatalogApiAvailable.Value)
{
// Signature.CatalogApiAvailable would be set to false the first time it is detected that
// WTGetSignatureInfo API does not exist on the platform, or if the API is not functional on the target platform.
// Just return from the function instead of revalidating.
return null;
}
Signature signature = null;
Utils.CheckArgForNullOrEmpty(filename, "fileName");
SecuritySupport.CheckIfFileExists(filename);
try
{
using (FileStream stream = File.OpenRead(filename))
{
NativeMethods.SIGNATURE_INFO sigInfo = new NativeMethods.SIGNATURE_INFO();
sigInfo.cbSize = (uint)Marshal.SizeOf(sigInfo);
IntPtr ppCertContext = IntPtr.Zero;
IntPtr phStateData = IntPtr.Zero;
try
{
int hresult = NativeMethods.WTGetSignatureInfo(filename, stream.SafeFileHandle.DangerousGetHandle(),
NativeMethods.SIGNATURE_INFO_FLAGS.SIF_CATALOG_SIGNED |
NativeMethods.SIGNATURE_INFO_FLAGS.SIF_CATALOG_FIRST |
NativeMethods.SIGNATURE_INFO_FLAGS.SIF_AUTHENTICODE_SIGNED |
NativeMethods.SIGNATURE_INFO_FLAGS.SIF_BASE_VERIFICATION |
NativeMethods.SIGNATURE_INFO_FLAGS.SIF_CHECK_OS_BINARY,
ref sigInfo, ref ppCertContext, ref phStateData);
if (Utils.Succeeded(hresult))
{
DWORD error = GetErrorFromSignatureState(sigInfo.nSignatureState);
X509Certificate2 cert = null;
if (ppCertContext != IntPtr.Zero)
{
cert = new X509Certificate2(ppCertContext);
// Get the time stamper certificate if available
TryGetProviderSigner(phStateData, out IntPtr pProvSigner, out X509Certificate2 timestamperCert);
if (timestamperCert != null)
{
signature = new Signature(filename, error, cert, timestamperCert);
}
else
{
signature = new Signature(filename, error, cert);
}
switch (sigInfo.nSignatureType)
{
case NativeMethods.SIGNATURE_INFO_TYPE.SIT_AUTHENTICODE: signature.SignatureType = SignatureType.Authenticode; break;
case NativeMethods.SIGNATURE_INFO_TYPE.SIT_CATALOG: signature.SignatureType = SignatureType.Catalog; break;
}
if (sigInfo.fOSBinary == 1)
{
signature.IsOSBinary = true;
}
}
else
{
signature = new Signature(filename, error);
}
if (!Signature.CatalogApiAvailable.HasValue)
{
string productFile = Path.Combine(Utils.DefaultPowerShellAppBase, "Modules\\PSDiagnostics\\PSDiagnostics.psm1");
if (signature.Status != SignatureStatus.Valid)
{
if (string.Equals(filename, productFile, StringComparison.OrdinalIgnoreCase))
{
Signature.CatalogApiAvailable = false;
}
else
{
// ProductFile has to be Catalog signed. Hence validating
// to see if the Catalog API is functional using the ProductFile.
Signature productFileSignature = GetSignatureFromCatalog(productFile);
Signature.CatalogApiAvailable = (productFileSignature != null && productFileSignature.Status == SignatureStatus.Valid);
}
}
}
}
else
{
// If calling NativeMethods.WTGetSignatureInfo failed (returned a non-zero value), we still want to set Signature.CatalogApiAvailable to false.
Signature.CatalogApiAvailable = false;
}
}
finally
{
if (phStateData != IntPtr.Zero)
{
NativeMethods.FreeWVTStateData(phStateData);
}
if (ppCertContext != IntPtr.Zero)
{
NativeMethods.CertFreeCertificateContext(ppCertContext);
}
}
}
}
catch (TypeLoadException)
{
// If we don't have WTGetSignatureInfo, don't return a Signature.
Signature.CatalogApiAvailable = false;
return null;
}
return signature;
}
private static DWORD GetErrorFromSignatureState(NativeMethods.SIGNATURE_STATE state)
{
switch (state)
{
case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_UNSIGNED_MISSING: return Win32Errors.TRUST_E_NOSIGNATURE;
case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_UNSIGNED_UNSUPPORTED: return Win32Errors.TRUST_E_NOSIGNATURE;
case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_UNSIGNED_POLICY: return Win32Errors.TRUST_E_NOSIGNATURE;
case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_INVALID_CORRUPT: return Win32Errors.TRUST_E_BAD_DIGEST;
case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_INVALID_POLICY: return Win32Errors.CRYPT_E_BAD_MSG;
case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_VALID: return Win32Errors.NO_ERROR;
case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_TRUSTED: return Win32Errors.NO_ERROR;
case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_UNTRUSTED: return Win32Errors.TRUST_E_EXPLICIT_DISTRUST;
// Should not happen
default:
System.Diagnostics.Debug.Fail("Should not get here - could not map SIGNATURE_STATE");
return Win32Errors.TRUST_E_NOSIGNATURE;
}
}
private static Signature GetSignatureFromWinVerifyTrust(string fileName, string fileContent)
{
Signature signature = null;
NativeMethods.WINTRUST_DATA wtd;
DWORD error = Win32Errors.E_FAIL;
if (fileContent == null)
{
Utils.CheckArgForNullOrEmpty(fileName, "fileName");
SecuritySupport.CheckIfFileExists(fileName);
// SecurityUtils.CheckIfFileSmallerThan4Bytes(fileName);
}
try
{
error = GetWinTrustData(fileName, fileContent, out wtd);
if (error != Win32Errors.NO_ERROR)
{
s_tracer.WriteLine("GetWinTrustData failed: {0:x}", error);
}
signature = GetSignatureFromWintrustData(fileName, error, wtd);
error = NativeMethods.DestroyWintrustDataStruct(wtd);
if (error != Win32Errors.NO_ERROR)
{
s_tracer.WriteLine("DestroyWinTrustDataStruct failed: {0:x}", error);
}
}
catch (AccessViolationException)
{
signature = new Signature(fileName, Win32Errors.TRUST_E_NOSIGNATURE);
}
return signature;
}
[ArchitectureSensitive]
private static DWORD GetWinTrustData(string fileName, string fileContent,
out NativeMethods.WINTRUST_DATA wtData)
{
DWORD dwResult = Win32Errors.E_FAIL;
IntPtr WINTRUST_ACTION_GENERIC_VERIFY_V2 = IntPtr.Zero;
IntPtr wtdBuffer = IntPtr.Zero;
Guid actionVerify =
new Guid("00AAC56B-CD44-11d0-8CC2-00C04FC295EE");
try
{
WINTRUST_ACTION_GENERIC_VERIFY_V2 =
Marshal.AllocCoTaskMem(Marshal.SizeOf(actionVerify));
Marshal.StructureToPtr(actionVerify,
WINTRUST_ACTION_GENERIC_VERIFY_V2,
false);
NativeMethods.WINTRUST_DATA wtd;
if (fileContent == null)
{
NativeMethods.WINTRUST_FILE_INFO wfi = NativeMethods.InitWintrustFileInfoStruct(fileName);
wtd = NativeMethods.InitWintrustDataStructFromFile(wfi);
}
else
{
NativeMethods.WINTRUST_BLOB_INFO wbi = NativeMethods.InitWintrustBlobInfoStruct(fileName, fileContent);
wtd = NativeMethods.InitWintrustDataStructFromBlob(wbi);
}
wtdBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(wtd));
Marshal.StructureToPtr(wtd, wtdBuffer, false);
// The result is returned to the caller, and handled generically.
// Disable the PreFast check for Win32 error codes, as we don't care.
#pragma warning disable 56523
dwResult = NativeMethods.WinVerifyTrust(
IntPtr.Zero,
WINTRUST_ACTION_GENERIC_VERIFY_V2,
wtdBuffer);
#pragma warning restore 56523
wtData = Marshal.PtrToStructure<NativeMethods.WINTRUST_DATA>(wtdBuffer);
}
finally
{
Marshal.DestroyStructure<Guid>(WINTRUST_ACTION_GENERIC_VERIFY_V2);
Marshal.FreeCoTaskMem(WINTRUST_ACTION_GENERIC_VERIFY_V2);
Marshal.DestroyStructure<NativeMethods.WINTRUST_DATA>(wtdBuffer);
Marshal.FreeCoTaskMem(wtdBuffer);
}
return dwResult;
}
[ArchitectureSensitive]
private static X509Certificate2 GetCertFromChain(IntPtr pSigner)
{
X509Certificate2 signerCert = null;
// We don't care about the Win32 error code here, so disable
// the PreFast complaint that we're not retrieving it.
#pragma warning disable 56523
IntPtr pCert =
NativeMethods.WTHelperGetProvCertFromChain(pSigner, 0);
#pragma warning restore 56523
if (pCert != IntPtr.Zero)
{
NativeMethods.CRYPT_PROVIDER_CERT provCert =
(NativeMethods.CRYPT_PROVIDER_CERT)
Marshal.PtrToStructure<NativeMethods.CRYPT_PROVIDER_CERT>(pCert);
signerCert = new X509Certificate2(provCert.pCert);
}
return signerCert;
}
[ArchitectureSensitive]
private static Signature GetSignatureFromWintrustData(
string filePath,
DWORD error,
NativeMethods.WINTRUST_DATA wtd)
{
s_tracer.WriteLine("GetSignatureFromWintrustData: error: {0}", error);
Signature signature = null;
if (TryGetProviderSigner(wtd.hWVTStateData, out IntPtr pProvSigner, out X509Certificate2 timestamperCert))
{
//
// get cert of the signer
//
X509Certificate2 signerCert = GetCertFromChain(pProvSigner);
if (signerCert != null)
{
if (timestamperCert != null)
{
signature = new Signature(filePath,
error,
signerCert,
timestamperCert);
}
else
{
signature = new Signature(filePath,
error,
signerCert);
}
signature.SignatureType = SignatureType.Authenticode;
}
}
Diagnostics.Assert(error != 0 || signature != null, "GetSignatureFromWintrustData: general crypto failure");
if ((signature == null) && (error != 0))
{
signature = new Signature(filePath, error);
}
return signature;
}
[ArchitectureSensitive]
private static bool TryGetProviderSigner(IntPtr wvtStateData, out IntPtr pProvSigner, out X509Certificate2 timestamperCert)
{
pProvSigner = IntPtr.Zero;
timestamperCert = null;
// The GetLastWin32Error of this is checked, but PreSharp doesn't seem to be
// able to see that.
#pragma warning disable 56523
IntPtr pProvData =
NativeMethods.WTHelperProvDataFromStateData(wvtStateData);
#pragma warning restore 56523
if (pProvData != IntPtr.Zero)
{
pProvSigner =
NativeMethods.WTHelperGetProvSignerFromChain(pProvData, 0, 0, 0);
if (pProvSigner != IntPtr.Zero)
{
NativeMethods.CRYPT_PROVIDER_SGNR provSigner =
(NativeMethods.CRYPT_PROVIDER_SGNR)
Marshal.PtrToStructure<NativeMethods.CRYPT_PROVIDER_SGNR>(pProvSigner);
if (provSigner.csCounterSigners == 1)
{
//
// time stamper cert available
//
timestamperCert = GetCertFromChain(provSigner.pasCounterSigners);
}
return true;
}
}
return false;
}
[ArchitectureSensitive]
private static DWORD GetLastWin32Error()
{
int error = Marshal.GetLastWin32Error();
return SecuritySupport.GetDWORDFromInt(error);
}
}
}
#pragma warning restore 56523
| 41.485362 | 171 | 0.517791 | [
"MIT"
] | 3pe2/PowerShell | src/System.Management.Automation/security/Authenticode.cs | 26,924 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace OnLine.Pages.Popups.Sale
{
public partial class AllLead_Specification_Show_Feat
{
/// <summary>
/// form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
}
}
| 28.703704 | 84 | 0.487742 | [
"Apache-2.0"
] | shibathethinker/ChimeraCRM | OnLine/OnLine/Pages/Popups/Sale/AllLead_Specification_Show_Feat.aspx.designer.cs | 777 | 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.ComponentModel.Composition;
namespace Dagent.RemoteAgent
{
[Export(typeof(IBusDispacher))]
public class BusDispacher : IBusDispacher
{
public void Send(string agent, object message)
{
}
}
}
| 26.75 | 112 | 0.675234 | [
"MIT"
] | dagent2/dagent | DagentExtensions/RemoteAgent/BusDispach.cs | 430 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class BrokenGemInfo
{
public GemModel gemModel;
public List<GemModel> gemModels;
public void Clear()
{
gemModel = null;
gemModels.Clear();
}
}
public class BlockedGemInfo
{
public GemModel gemModel;
public List<GemModel> gemModels;
public bool isNextBreakable;
public bool isNextMovable;
public void Clear()
{
gemModel = null;
gemModels.Clear();
isNextBreakable = false;
isNextMovable = false;
}
}
public class ReplacedGemInfo
{
public GemModel blockedGemModel;
public List<GemModel> gemModels;
public void Clear()
{
blockedGemModel = null;
gemModels.Clear();
}
}
public class MergedGemInfo
{
public GemModel mergee;
public GemModel merger;
public void Clear()
{
mergee = null;
merger = null;
}
}
public class MatchableGemInfo
{
public GemModel sourceGemModel;
public GemModel nearGemModel;
}
public class MatchableTypeInfo
{
public Position sourcePosition;
public GemModel sourceGemModel;
public List<WhereCanMatch> wheresCanMatch;
public GemType matchingType;
public bool isSpecialType;
}
public class GameController<M>: BaseController<M>
where M: GameModel
{
readonly int[][] SET_OF_RANDOM_DIRECTIONS;
readonly Random RANDOM;
List<MatchedLineInfo> matchedLineInfos;
List<GemModel> feedingGemModels;
List<GemModel> fallingGemModels;
Stack<GemModel> blockedGemModels;
List<GemModel> swappingGemModels;
BrokenGemInfo brokenGemInfo;
BlockedGemInfo blockedGemInfo;
List<GemModel> matchedGemModels;
ReplacedGemInfo replacedGemInfo;
MergedGemInfo mergedGemInfo;
List<MatchableGemInfo> matchableGemInfos;
List<WhereCanMatch> wheresCanMatch;
List<MatchableTypeInfo> matchableTypeInfos;
public GameController()
{
SET_OF_RANDOM_DIRECTIONS = new int[][]{ new int[]{ -1, 1 }, new int[]{ 1, -1 } };
RANDOM = new Random();
matchedLineInfos = new List<MatchedLineInfo>();
feedingGemModels = new List<GemModel>();
fallingGemModels = new List<GemModel>();
blockedGemModels = new Stack<GemModel>();
matchedGemModels = new List<GemModel>();
swappingGemModels = new List<GemModel>();
brokenGemInfo = new BrokenGemInfo() {
gemModels = new List<GemModel>()
};
blockedGemInfo = new BlockedGemInfo {
gemModels = new List<GemModel>()
};
replacedGemInfo = new ReplacedGemInfo {
gemModels = new List<GemModel>()
};
mergedGemInfo = new MergedGemInfo();
matchableGemInfos = new List<MatchableGemInfo>();
wheresCanMatch = new List<WhereCanMatch>();
matchableTypeInfos = new List<MatchableTypeInfo>();
}
public override void Kill()
{
base.Kill();
matchedLineInfos = null;
feedingGemModels = null;
fallingGemModels = null;
blockedGemModels = null;
matchedGemModels = null;
swappingGemModels = null;
brokenGemInfo = null;
blockedGemInfo = null;
replacedGemInfo = null;
mergedGemInfo = null;
matchableGemInfos = null;
wheresCanMatch = null;
matchableTypeInfos = null;
}
public void TakeSnapshot()
{
Model.HistoryOfGemModels.Add((GemModel[,])Model.GemModels.Clone());
}
public bool HasAnyChange()
{
var gemModelsCurrent = Model.GemModels;
var gemModelsBefore = Model.HistoryOfGemModels[Model.HistoryOfGemModels.Count - 1];
return !gemModelsCurrent.ContentEquals<GemModel>(gemModelsBefore);
}
public bool HasAnySpecialGems()
{
var specialGemModels =
from GemModel gemModel in Model.GemModels
where IsMovableTile(gemModel.Position)
&& gemModel.IsSpecialType()
select gemModel;
return specialGemModels.Any();
}
public void PutGems()
{
var matchLineModels = Model.allwayMatchLineModels;
var matchingTypes = Model.MatchingTypes;
var emptyGemModels =
from GemModel gemModel in Model.GemModels
where gemModel is EmptyGemModel && gemModel.Type == GemType.EmptyGem
select gemModel;
foreach (var emptyGemModel in emptyGemModels)
{
var gemsCantPutIn = new List<GemType>();
foreach (var matchLineModel in matchLineModels) {
foreach(var matchingType in matchingTypes) {
if (GetWheresCanMatch(emptyGemModel.Position, matchLineModel, matchingType).Count == 0) { continue; }
gemsCantPutIn.Add(matchingType);
}
}
if (gemsCantPutIn.Count == matchingTypes.Count) {
throw new InvalidOperationException("That should not happen.");
}
var gemsCanPutIn = matchingTypes.Except(gemsCantPutIn).ToList();
emptyGemModel.Type = gemsCanPutIn[RANDOM.Next(gemsCanPutIn.Count)];
}
}
public IEnumerable<GemModel> GetAll()
{
var allGemModels =
from GemModel gemModel in Model.GemModels
where gemModel is IMovable && gemModel.Type != GemType.EmptyGem && IsMovableTile(gemModel.Position)
select gemModel;
return allGemModels;
}
public void TurnNext()
{
Model.currentTurn += 1;
}
public List<WhereCanMatch> GetWheresCanMatch(Position sourcePosition, MatchLineModel matchLineModel, GemType matchingType)
{
wheresCanMatch.Clear();
foreach(var whereCanMatch in matchLineModel.wheresCanMatch)
{
var matchCount = 0;
foreach(var matchOffset in whereCanMatch.MatchOffsets) {
if (!IsAcceptableIndex(sourcePosition, matchOffset[0], matchOffset[1])) { break; }
var matchPosition = Position.Get(sourcePosition, matchOffset[0], matchOffset[1]);
if (IsMovableTile(matchPosition)
&& (sourcePosition.index == matchPosition.index || GetGemModel(matchPosition).CanMatch(matchingType))) {
matchCount++;
} else {
break;
}
}
if (matchCount == whereCanMatch.MatchOffsets.Count) {
wheresCanMatch.Add(whereCanMatch);
}
}
return wheresCanMatch;
}
public List<MatchableGemInfo> GetMatchableGems()
{
matchableGemInfos.Clear();
matchableTypeInfos.Clear();
foreach (var gemModel in GetAll())
{
var sourcePosition = gemModel.Position;
var sourceGemModel = GetGemModel(sourcePosition);
// Add to targets either if it is special gem
if (sourceGemModel.IsSpecialType()) {
matchableTypeInfos.Add(new MatchableTypeInfo {
sourcePosition = sourcePosition,
sourceGemModel = sourceGemModel,
wheresCanMatch = new List<WhereCanMatch> {
new WhereCanMatch(new List<int[]>{ new int[] {0, 0} })
},
matchingType = sourceGemModel.Type,
isSpecialType = true
});
}
// Or if it has a matchable line.
foreach (var matchLineModel in Model.allwayMatchLineModels) {
foreach(var matchingType in Model.MatchingTypes) {
var wheresCanMatch = GetWheresCanMatch(sourcePosition, matchLineModel, matchingType);
if (wheresCanMatch.Count == 0) { continue; }
matchableTypeInfos.Add(new MatchableTypeInfo {
sourcePosition = sourcePosition,
wheresCanMatch = wheresCanMatch.ToList(),
matchingType = matchingType
});
}
}
}
foreach (var matchableTypeInfo in matchableTypeInfos)
{
var sourcePosition = matchableTypeInfo.sourcePosition;
if (matchableTypeInfo.isSpecialType) {
var sourceGemModel = matchableTypeInfo.sourceGemModel;
if (sourceGemModel.Type == GemType.ChocoGem || sourceGemModel.Type == GemType.SuperGem) {
matchableGemInfos.Add(new MatchableGemInfo {
sourceGemModel = GetGemModel(sourcePosition)
});
}
foreach (var offsetCanSwap in Model.offsetsCanSwap) {
if (!IsAcceptableIndex(sourcePosition, offsetCanSwap[0], offsetCanSwap[1])) { continue; }
var nearPosition = Position.Get(sourcePosition, offsetCanSwap[0], offsetCanSwap[1]);
if (!IsMovableTile(nearPosition)
|| !GetGemModel(nearPosition).IsSpecialType()) { continue; }
matchableGemInfos.Add(new MatchableGemInfo {
sourceGemModel = GetGemModel(sourcePosition), nearGemModel = GetGemModel(nearPosition)
});
// UnityEngine.Debug.Log("Possible Match Found : " + sourcePosition + " <=> " + nearPosition);
}
continue;
}
foreach(var whereCanMatch in matchableTypeInfo.wheresCanMatch) {
foreach (var offsetCanSwap in Model.offsetsCanSwap) {
if (!IsAcceptableIndex(sourcePosition, offsetCanSwap[0], offsetCanSwap[1])) { continue; }
var nearPosition = Position.Get(sourcePosition, offsetCanSwap[0], offsetCanSwap[1]);
if (!IsMovableTile(nearPosition)
|| GetGemModel(nearPosition).Type != matchableTypeInfo.matchingType
|| IsNearPositionOnMatchLine(nearPosition, sourcePosition, whereCanMatch)) { continue; }
matchableGemInfos.Add(new MatchableGemInfo {
sourceGemModel = GetGemModel(sourcePosition), nearGemModel = GetGemModel(nearPosition)
});
// UnityEngine.Debug.Log("Possible Match Found : " + sourcePosition + " <=> " + nearPosition);
}
}
}
return matchableGemInfos;
}
bool IsNearPositionOnMatchLine(Position nearPosition, Position sourcePosition, WhereCanMatch whereCanMatch)
{
var result = false;
foreach(var matchOffset in whereCanMatch.MatchOffsets)
{
var matchPosition = Position.Get(sourcePosition, matchOffset[0], matchOffset[1]);
if (matchPosition.index == nearPosition.index) { result = true; break; }
}
return result;
}
public IEnumerable<GemModel> Shuffle(Int64 preservedFromMatch)
{
var allGems = GetAll().ToList();
var random = new Random();
for (int i = 0; i < allGems.Count; i++)
{
int randomIndex = random.Next(i, allGems.Count);
var randomPosition = allGems[randomIndex].Position;
allGems[randomIndex].Position = allGems[i].Position;
allGems[i].Position = randomPosition;
}
foreach (var gemModel in allGems)
{
gemModel.preservedFromMatch = preservedFromMatch;
SetGemModel(gemModel);
}
return GetAll();
}
public List<GemModel> Swap(Position sourcePosition, Position nearPosition)
{
swappingGemModels.Clear();
var sourceGemModel = GetGemModel(sourcePosition);
var nearGemModel = GetGemModel(nearPosition);
nearGemModel.Position = sourcePosition;
sourceGemModel.Position = nearPosition;
SetGemModel(nearGemModel);
SetGemModel(sourceGemModel);
sourceGemModel.preservedFromMatch = nearGemModel.preservedFromMatch
= Model.currentTurn + 5;
swappingGemModels.Add(sourceGemModel);
swappingGemModels.Add(nearGemModel);
return swappingGemModels;
}
public MergedGemInfo Merge(Position sourcePosition, Position nearPosition)
{
mergedGemInfo.Clear();
var sourceGemModel = GetGemModel(sourcePosition);
var nearGemModel = GetGemModel(nearPosition);
nearGemModel.specialKey = MergeSpecialKey(nearGemModel, sourceGemModel);
nearGemModel.endurance = MergeEndurance(nearGemModel, sourceGemModel);
nearGemModel.positionBefore = sourcePosition;
sourceGemModel.preservedFromMatch = nearGemModel.preservedFromMatch = Model.currentTurn + 5;
mergedGemInfo.merger = nearGemModel;
mergedGemInfo.mergee = sourceGemModel;
return mergedGemInfo;
}
public List<MatchedLineInfo> Match()
{
matchedLineInfos.Clear();
var matchLineModels = Model.positiveMatchLineModels;
var matchableGemModels =
from GemModel gemModel in Model.GemModels
where gemModel is IMovable
&& gemModel.Type != GemType.EmptyGem
&& IsMovableTile(gemModel.Position)
&& Model.currentTurn > gemModel.preservedFromMatch
&& !IsFalling(gemModel)
select gemModel;
foreach (var matchableGemModel in matchableGemModels)
{
foreach (var matchLineModel in matchLineModels)
{
var matchedGemModels = GetAnyMatches(matchableGemModel, matchLineModel);
if (matchedGemModels.Count == 0) { continue; }
var newMatchLineInfo = new MatchedLineInfo() {
gemModels = matchedGemModels.ToList(),
matchLineModels = new List<MatchLineModel>(){ matchLineModel }
};
// Merge if the matched line has intersection.
foreach (var matchedLineInfo in matchedLineInfos) {
if (matchedLineInfo.gemModels.Intersect(newMatchLineInfo.gemModels).Any()) {
matchedLineInfo.Merge(newMatchLineInfo);
break;
}
}
if (!newMatchLineInfo.isMerged) {
matchedLineInfos.Add(newMatchLineInfo);
}
}
}
foreach (var matchedLineInfo in matchedLineInfos)
{
// foreach (var matchLineModel in matchedLineInfo.matchLineModels)
// {
// UnityEngine.Debug.Log(matchLineModel.ToString());
// }
var latestGemModel = matchedLineInfo.gemModels.OrderByDescending(gemModel => gemModel.sequence).FirstOrDefault();
foreach (var matchedGemModel in matchedLineInfo.gemModels)
{
var newGemType = GemType.EmptyGem;
if (matchedGemModel == latestGemModel) {
newGemType = ReadGemType(
latestGemModel.Type,
ReadSpecialKey(matchedLineInfo.matchLineModels, latestGemModel.PositionVector)
);
}
// Create a new gem model either empty or merged.
var newGemModel = GemModelFactory.Get(newGemType, matchedGemModel.Position);
SetGemModel(newGemModel);
if (newGemType != GemType.EmptyGem) {
// UnityEngine.Debug.Log("newGemModel : " + newGemModel.ToString());
matchedLineInfo.newAdded = newGemModel;
newGemModel.preservedFromBreak = Model.currentTurn + 1;
}
newGemModel.preservedFromFall = Model.currentTurn;
}
}
return matchedLineInfos;
}
public List<GemModel> GetAnyMatches(GemModel sourceGemModel, MatchLineModel matchLineModel)
{
matchedGemModels.Clear();
foreach (var whereCanMatch in matchLineModel.wheresCanMatch)
{
foreach (var matchOffset in whereCanMatch.MatchOffsets) {
if (!IsAcceptableIndex(sourceGemModel.Position, matchOffset[0], matchOffset[1])) { continue; }
var matchingPosition = Position.Get(sourceGemModel.Position, matchOffset[0], matchOffset[1]);
if (!IsMovableTile(matchingPosition)) { continue; }
var matchingGemModel = GetGemModel(matchingPosition);
if (sourceGemModel.CanMatch(matchingGemModel.Type)
&& Model.currentTurn > matchingGemModel.preservedFromMatch
&& !IsFalling(matchingGemModel)
) {
matchedGemModels.Add(matchingGemModel);
} else {
// Need to match about all offsets.
break;
}
}
if (matchedGemModels.Count == whereCanMatch.MatchOffsets.Count) {
// Finally found!
break;
} else {
matchedGemModels.Clear();
}
}
return matchedGemModels;
}
public GemType ReadGemType(GemType baseGemType, string specialKey)
{
GemType gemType = GemType.EmptyGem;
int specialGemType = 0;
switch (specialKey)
{
case Literals.SP:
gemType = GemType.SuperGem;
break;
case Literals.SQ:
gemType = GemType.ChocoGem;
break;
case Literals.C:
specialGemType = 1;
break;
case Literals.H:
specialGemType = 2;
break;
case Literals.V:
specialGemType = 3;
break;
}
if (specialGemType != 0)
{
gemType = (GemType)((int)baseGemType + specialGemType);
}
return gemType;
}
string MergeSpecialKey(GemModel merger, GemModel mergee)
{
var mergerType = merger.Type;
var mergerKey = merger.specialKey;
var mergeeType = mergee.Type;
var mergeeKey = mergee.specialKey;
var maxOfGemtype = Math.Max((int)merger.Type, (int)mergee.Type);
merger.Type = (maxOfGemtype >= 10) ? (GemType)maxOfGemtype : GemType.Nil;
mergee.Type = GemType.Nil;
merger.specialKey = mergee.specialKey = Literals.Nil;
var sb = new StringBuilder();
sb.Append(ReadMergingKey(mergerType, mergerKey));
sb.Append(ReadMergingKey(mergeeType, mergeeKey));
return sb.ToString();
}
int MergeEndurance(GemModel merger, GemModel mergee)
{
if (merger.specialKey == Literals.CC) { return 2; }
if (merger.specialKey == Literals.HSQ || merger.specialKey == Literals.SQH) { return 5; }
return Math.Max(merger.endurance, mergee.endurance);
}
string ReadMergingKey(GemType gemType, string specialKey)
{
if (gemType == GemType.SuperGem) { return Literals.SP; }
else if (gemType == GemType.ChocoGem) { return Literals.SQ; }
return specialKey;
}
public string ReadSpecialKey(IEnumerable<MatchLineModel> matchLineModels, PositionVector positionVector)
{
var specialKey = Literals.Nil;
var hasVerticalMatch = false;
var hasHorizontalMatch = false;
var hasSquareMatch = false;
var maxMagnitude = 0;
foreach (var matchLineModel in matchLineModels)
{
hasVerticalMatch = hasVerticalMatch || matchLineModel.type == MatchLineType.V;
hasHorizontalMatch = hasHorizontalMatch || matchLineModel.type == MatchLineType.H;
hasSquareMatch = hasSquareMatch || matchLineModel.type == MatchLineType.S;
maxMagnitude = Math.Max(matchLineModel.magnitude, maxMagnitude);
}
if (maxMagnitude == 5)
{
specialKey = Literals.SP;
}
else if (hasVerticalMatch && hasHorizontalMatch)
{
specialKey = Literals.C;
}
else if (maxMagnitude == 4)
{
specialKey = positionVector.colOffset != 0 ? Literals.H: Literals.V;
}
else if (hasSquareMatch)
{
specialKey = Literals.SQ;
}
return specialKey;
}
bool IsFalling(GemModel gemModel)
{
bool result = false;
var sourcePosition = gemModel.Position;
while (true)
{
var gravity = GetGravityModel(sourcePosition).vector;
if (!IsAcceptableIndex(sourcePosition, gravity[0], gravity[1])) { break; }
var nearPosition = Position.Get(sourcePosition, gravity[0], gravity[1]);
if (!IsMovableTile(nearPosition)) {
break;
}
if (GetGemModel(nearPosition).Type == GemType.EmptyGem) {
result = true;
break;
}
sourcePosition = nearPosition;
}
return result;
}
public List<GemInfo> Fall()
{
fallingGemModels.Clear();
blockedGemModels.Clear();
var emptyGemModels =
from GemModel gemModel in Model.GemModels
where IsMovableTile(gemModel.Position)
&& gemModel is IMovable
&& gemModel.Type == GemType.EmptyGem
&& Model.currentTurn > gemModel.preservedFromFall
select gemModel;
// Only one of them will be executed between a and b.
// A: Vertical comparing as bottom up
foreach (var emptyGemModel in emptyGemModels)
{
var emptyGemPosition = emptyGemModel.Position;
var gravity = GetGravityModel(emptyGemPosition).vector;
if (!IsAcceptableIndex(emptyGemPosition, gravity[0], -gravity[1])) { continue; }
var nearPosition = Position.Get(emptyGemPosition, gravity[0], -gravity[1]);
var nearGemModel = GetGemModel(nearPosition);
if (Model.currentTurn <= nearGemModel.preservedFromMatch) { continue; }
if (nearGemModel.markedBy != 0) { continue; }
if (nearGemModel is IMovable) {
fallingGemModels.AddRange(Swap(emptyGemPosition, nearPosition));
} else {
blockedGemModels.Push(emptyGemModel);
}
}
// B: Diagonal comparing as bottom up
foreach (var blockedGemModel in blockedGemModels)
{
var blockedGemPosition = blockedGemModel.Position;
var gravity = GetGravityModel(blockedGemPosition).vector;
var randomDirections = SET_OF_RANDOM_DIRECTIONS[RANDOM.Next(SET_OF_RANDOM_DIRECTIONS.Length)];
foreach (var randomDirection in randomDirections)
{
int directionX = 0;
int directionY = 0;
if (gravity[0] != 0) {
directionX = -gravity[0];
directionY = randomDirection;
} else if (gravity[1] != 0) {
directionX = randomDirection;
directionY = -gravity[1];
}
if (!IsAcceptableIndex(blockedGemPosition, directionX, directionY)) { continue; }
Position nearPosition = Position.Get(blockedGemPosition, directionX, directionY);
var nearGemModel = GetGemModel(nearPosition);
if (Model.currentTurn <= nearGemModel.preservedFromMatch) { continue; }
if (IsMovableTile(nearPosition)
&& !fallingGemModels.Contains(nearGemModel)
&& nearGemModel is IMovable) {
fallingGemModels.AddRange(Swap(blockedGemPosition, nearPosition));
break;
}
}
}
return fallingGemModels
.Where(gemModel => gemModel.Type != GemType.EmptyGem)
.Select(fallingGemModel => {
return new GemInfo {
position = fallingGemModel.Position,
id = fallingGemModel.id,
endOfFall = !IsFalling(fallingGemModel)
};
})
.ToList();
}
public List<GemModel> Feed()
{
feedingGemModels.Clear();
var matchingTypes = Model.MatchingTypes;
var spawnerGemModels =
from GemModel gemModel in Model.GemModels
where gemModel is SpawnerGemModel
select gemModel;
foreach (SpawnerGemModel spawnerGemModel in spawnerGemModels)
{
var gravity = GetGravityModel(spawnerGemModel.Position).vector;
var spawneePosition = Position.Get(spawnerGemModel.Position, gravity[0], gravity[1]);
if (GetGemModel(spawneePosition).Type == GemType.EmptyGem) {
var spawneeGemModel = GemModelFactory.Get(GemType.EmptyGem, spawneePosition);
SetGemModel(spawneeGemModel);
spawneeGemModel.Type = matchingTypes[RANDOM.Next(matchingTypes.Count)];
feedingGemModels.Add(spawneeGemModel);
}
}
return feedingGemModels;
}
public BlockedGemInfo MarkAsBlock(Position sourcePosition, Int64 markerID)
{
blockedGemInfo.Clear();
var sourceGemModel = GetGemModel(sourcePosition);
var isMovable = IsMovableTile(sourcePosition);
if (isMovable
&& sourceGemModel is IMovable
&& sourceGemModel.Type != GemType.EmptyGem
&& Model.currentTurn >= sourceGemModel.preservedFromBreak)
{
blockedGemInfo.gemModel = CopyAsBlock(markerID, sourceGemModel);
}
return blockedGemInfo;
}
public ReplacedGemInfo ReplaceSameTypeAsSpecial(
Position sourcePosition,
GemType gemType,
Int64 replacerID,
string[] specialKeys,
int endurance
) {
replacedGemInfo.Clear();
replacedGemInfo.blockedGemModel = CopyAsBlock(replacerID, GetGemModel(sourcePosition));
var sameGemModels =
from GemModel gemModel in Model.GemModels
where IsMovableTile(gemModel.Position)
&& gemModel is IMovable
&& gemModel.CanMatch(gemType)
&& Model.currentTurn >= gemModel.preservedFromBreak
select gemModel;
foreach (var gemModel in sameGemModels)
{
replacedGemInfo.gemModels.Add(
CopyAsSpecial(replacerID, gemModel, specialKeys[RANDOM.Next(specialKeys.Length)], endurance)
);
}
return replacedGemInfo;
}
public ReplacedGemInfo ReplaceAnyTypeAsSpecial(
Int64 replacerID,
string[] specialKeys,
int endurance
) {
replacedGemInfo.Clear();
var chosenGemModels =
from GemModel gemModel in Model.GemModels
where IsMovableTile(gemModel.Position)
&& gemModel is IMovable
&& gemModel.IsPrimitiveType()
&& Model.currentTurn >= gemModel.preservedFromBreak
select gemModel;
chosenGemModels = chosenGemModels.OrderBy(s => Guid.NewGuid()).Take(endurance);
foreach (var gemModel in chosenGemModels)
{
replacedGemInfo.gemModels.Add(
CopyAsSpecial(replacerID, gemModel, specialKeys[RANDOM.Next(specialKeys.Length)], int.MaxValue)
);
}
return replacedGemInfo;
}
public BlockedGemInfo MarkSameTypeAsBlock(Position sourcePosition, GemType gemType, Int64 markerID)
{
blockedGemInfo.Clear();
blockedGemInfo.gemModels.Add(CopyAsBlock(markerID, GetGemModel(sourcePosition)));
var sameGemModels =
from GemModel gemModel in Model.GemModels
where IsMovableTile(gemModel.Position)
&& gemModel is IMovable
&& gemModel.CanMatch(gemType)
&& Model.currentTurn >= gemModel.preservedFromBreak
// && Model.currentTurn >= gemModel.preservedFromMatch
select gemModel;
foreach (var gemModel in sameGemModels)
{
blockedGemInfo.gemModels.Add(CopyAsBlock(markerID, gemModel));
}
return blockedGemInfo;
}
public BlockedGemInfo MarkSpecialTypeAsBlock(Int64 markerID)
{
blockedGemInfo.Clear();
var specialGemModels =
from GemModel gemModel in Model.GemModels
where IsMovableTile(gemModel.Position)
&& gemModel.IsSpecialType()
select gemModel;
foreach (var gemModel in specialGemModels)
{
blockedGemInfo.gemModels.Add(CopyAsBlock(markerID, gemModel));
}
return blockedGemInfo;
}
public BlockedGemInfo MarkAllGemsAsBlock(Position sourcePosition, Int64 markerID)
{
blockedGemInfo.Clear();
var sameGemModels =
from GemModel gemModel in Model.GemModels
where IsMovableTile(gemModel.Position)
&& gemModel is IMovable
&& Model.currentTurn >= gemModel.preservedFromBreak
select gemModel;
foreach (var gemModel in sameGemModels)
{
blockedGemInfo.gemModels.Add(CopyAsBlock(markerID, gemModel));
}
return blockedGemInfo;
}
GemModel CopyAsBlock(Int64 markerID, GemModel targetGemModel)
{
var copiedGemModel = GemModelFactory.Get(GemType.BlockedGem, targetGemModel.Position);
copiedGemModel.id = targetGemModel.id;
copiedGemModel.markedBy = markerID;
copiedGemModel.Type = targetGemModel.Type;
copiedGemModel.specialKey = targetGemModel.specialKey;
copiedGemModel.endurance = targetGemModel.endurance;
copiedGemModel.Position = targetGemModel.Position;
copiedGemModel.positionBefore = targetGemModel.positionBefore;
SetGemModel(copiedGemModel);
return copiedGemModel;
}
GemModel CopyAsSpecial(Int64 replacerID, GemModel targetGemModel, string specialKey, int endurance)
{
var copiedGemModel = GemModelFactory.Get(
ReadGemType(targetGemModel.Type, specialKey),
targetGemModel.Position
);
copiedGemModel.id = targetGemModel.id;
copiedGemModel.replacedBy = replacerID;
SetGemModel(copiedGemModel);
return copiedGemModel;
}
public BrokenGemInfo Break(Position targetPosition, Int64 markerID)
{
brokenGemInfo.Clear();
if (IsMovableTile(targetPosition))
{
var targetGemModel = GetGemModel(targetPosition);
if (targetGemModel.markedBy == markerID || targetGemModel.replacedBy == markerID) {
var newGemModel = GemModelFactory.Get(GemType.EmptyGem, targetGemModel.Position);
newGemModel.preservedFromFall = Model.currentTurn + 1;
SetGemModel(newGemModel);
brokenGemInfo.gemModel = targetGemModel;
}
}
return brokenGemInfo;
}
public BrokenGemInfo BreakEmptyBlocks(Int64 markerID)
{
brokenGemInfo.Clear();
var emptyBlockGemModels =
from GemModel gemModel in Model.GemModels
where gemModel is IBlockable
&& (gemModel.Type == GemType.EmptyGem || gemModel.Type == GemType.Nil)
&& gemModel.markedBy == markerID
select gemModel;
foreach (var gemModel in emptyBlockGemModels)
{
var newGemModel = GemModelFactory.Get(GemType.EmptyGem, gemModel.Position);
newGemModel.preservedFromFall = Model.currentTurn;
SetGemModel(newGemModel);
brokenGemInfo.gemModels.Add(gemModel);
}
return brokenGemInfo;
}
public GemModel GetGemModel(Position position)
{
return Model.GemModels[position.row, position.col];
}
public GravityModel GetGravityModel(Position position)
{
return Model.GravityModels[position.row, position.col];
}
public bool IsAcceptableIndex(Position position, int colOffset, int rowOffset)
{
return (position.col + colOffset) >= 0
&& (position.col + colOffset) < Model.Cols
&& (position.row + rowOffset) >= 0
&& (position.row + rowOffset) < Model.Rows;
}
public void SetGemModel(GemModel gemModel)
{
Model.GemModels[gemModel.Position.row, gemModel.Position.col] = gemModel;
}
public bool IsMovableTile(Position position)
{
return Model.TileModels[position.row, position.col].Type == TileType.Movable;
}
public bool IsBreakableTile(Position position)
{
return Model.TileModels[position.row, position.col].Type != TileType.Immovable;
}
}
| 28.415193 | 127 | 0.726151 | [
"MIT"
] | gemfile/Match3 | Assets/Scripts/Controller/GameController.cs | 27,309 | C# |
using GovUk.Education.SearchAndCompare.Domain.Client;
using GovUk.Education.SearchAndCompare.UI.Services;
using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GovUk.Education.SearchAndCompare.UI.Controllers
{
public class DynamicController : Controller
{
private readonly ISearchAndCompareApi _api;
private readonly IGeocoder _geocoder;
private readonly TelemetryClient _telemetryClient;
public DynamicController(ISearchAndCompareApi api, IGeocoder geocoder, TelemetryClient telemetryClient)
{
_api = api;
_geocoder = geocoder;
_telemetryClient = telemetryClient;
}
[HttpGet("/dynamic/providersuggest")]
public JsonResult ProviderSuggest(string query)
{
var res = _api.GetProviderSuggestions(query);
return Json(res.Select(x => new { name = x.Name, providerCode = x.ProviderCode }).ToList());
}
[HttpGet("/dynamic/locationsuggest")]
public async Task<JsonResult> LocationSuggest(string query)
{
IEnumerable<string> res = new List<string>();
try
{
res = await _geocoder.SuggestLocationsAsync(query);
}
catch (Exception ex)
{
_telemetryClient.TrackException(ex);
}
return Json(res.Count() > 5 ? res.Take(5) : res);
}
}
}
| 29.490566 | 111 | 0.637236 | [
"MIT"
] | DFE-Digital/search-and-compare-language-prototype | src/Controllers/DynamicController.cs | 1,563 | C# |
using System;
namespace Models
{
[Serializable]
public class KCHF555 : IModel
{
public int KCHF555Id { get; set; }
public int ModuleTreeId { get; set; }
//基本尺寸
public decimal Length { get; set; }
public decimal Deepth { get; set; }
public decimal ExRightDis { get; set; }
public int ExNo { get; set; }
public decimal ExDis { get; set; }
public decimal ExLength { get; set; }
public decimal ExWidth { get; set; }
public decimal ExHeight { get; set; }
public string SidePanel { get; set; }
//配置
public string Outlet { get; set; }
public string LEDlogo { get; set; }
public string BackToBack { get; set; }
public int LEDSpotNo { get; set; }
public decimal LEDSpotDis { get; set; }
public string LightType { get; set; }
//ANSUL
public string ANSUL { get; set; }
public string ANSide { get; set; }
public string ANDetector { get; set; }
public decimal ANYDis { get; set; }
public int ANDropNo { get; set; }
public decimal ANDropDis1 { get; set; }
public decimal ANDropDis2 { get; set; }
public decimal ANDropDis3 { get; set; }
public decimal ANDropDis4 { get; set; }
public decimal ANDropDis5 { get; set; }
//MARVEL
public string MARVEL { get; set; }
public int IRNo { get; set; }
public decimal IRDis1 { get; set; }
public decimal IRDis2 { get; set; }
public decimal IRDis3 { get; set; }
//F型新风
public int SuNo { get; set; }
public decimal SuDis { get; set; }
}
}
| 34.489796 | 47 | 0.561538 | [
"MIT"
] | felixzhu1989/Compass | Models/Hood/KCHF555.cs | 1,710 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\mmeapi.h(991,9)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct midihdr_tag
{
[MarshalAs(UnmanagedType.LPStr)]
public string lpData;
public uint dwBufferLength;
public uint dwBytesRecorded;
public IntPtr dwUser;
public uint dwFlags;
public IntPtr lpNext;
public IntPtr reserved;
public uint dwOffset;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public IntPtr[] dwReserved;
}
}
| 28.956522 | 83 | 0.644144 | [
"MIT"
] | Steph55/DirectN | DirectN/DirectN/Generated/midihdr_tag.cs | 668 | C# |
//! \file ImageGRC.cs
//! \date 2019 Mar 09
//! \brief Sudio
//
// Copyright (C) 2019 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace GameRes.Formats.Jikkenshitsu
{
internal class GrcMetaData : ImageMetaData
{
public int BitsOffset;
public int BitsLength;
public int DataOffset;
public int DataLength;
public int AlphaOffset;
public int AlphaLength;
}
[Export(typeof(ImageFormat))]
public class GrcFormat : ImageFormat
{
public override string Tag { get { return "GRC"; } }
public override string Description { get { return "Studio Jikkenshitsu image format"; } }
public override uint Signature { get { return 0x08; } }
public override ImageMetaData ReadMetaData (IBinaryStream file)
{
if (!file.Name.HasExtension (".grc"))
return null;
var header = file.ReadHeader (0x20);
int bpp = header.ToInt32 (0);
if (bpp != 8)
return null;
return new GrcMetaData {
Width = header.ToUInt16 (4),
Height = header.ToUInt16 (6),
BPP = bpp,
BitsOffset = header.ToInt32 (8),
BitsLength = header.ToInt32 (12),
DataOffset = header.ToInt32 (16),
DataLength = header.ToInt32 (20),
AlphaOffset = header.ToInt32 (24),
AlphaLength = header.ToInt32 (28),
};
}
public override ImageData Read (IBinaryStream file, ImageMetaData info)
{
var reader = new GrcReader (file, (GrcMetaData)info);
return reader.Unpack();
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("GrcFormat.Write not implemented");
}
public override ImageData ReadAndExport(IBinaryStream file, ImageMetaData info, Stream exportFile)
{
throw new System.NotImplementedException();
}
public override void Pack(Stream file, IBinaryStream inputFile, ImageData bitmap)
{
throw new System.NotImplementedException();
}
}
internal class GrcReader
{
IBinaryStream m_input;
GrcMetaData m_info;
int m_stride;
byte[] m_output;
public BitmapPalette Palette { get; private set; }
public PixelFormat Format { get; private set; }
public GrcReader (IBinaryStream input, GrcMetaData info)
{
m_input = input;
m_info = info;
m_stride = m_info.iWidth * m_info.BPP / 8;
m_output = new byte[m_stride * m_info.iHeight];
}
public ImageData Unpack ()
{
m_input.Position = 0x20;
Format = PixelFormats.Indexed8;
if (8 == m_info.BPP)
Palette = ImageFormat.ReadPalette (m_input.AsStream);
var rowsCtl = m_input.ReadBytes (m_info.iHeight);
m_input.Position = m_info.BitsOffset;
var ctlBits = m_input.ReadBytes (m_info.BitsLength);
m_input.Position = m_info.DataOffset;
int src1 = 0;
int dst = 0;
var coord = new int[4,4] {
{ 0, -1, -m_stride, -m_stride - 1 },
{ 0, -1, -2, -3 },
{ 0, -m_stride, -2 * m_stride, -3 * m_stride },
{ 0, -m_stride - 1, -m_stride, -m_stride + 1 }
};
int blocks = m_info.iWidth / 4;
for (int y = 0; y < m_info.iHeight; ++y)
{
int ctl = rowsCtl[y];
if (ctl > 3)
throw new InvalidFormatException();
for (int x = 0; x < blocks; ++x)
{
int bits = ctlBits[src1++];
for (int i = 6; i >= 0; i -= 2)
{
int p = (bits >> i) & 3;
byte px;
if (p != 0)
px = m_output[dst + coord[ctl,p]];
else
px = m_input.ReadUInt8();
m_output[dst++] = px;
}
}
}
return ImageData.CreateFlipped (m_info, Format, Palette, m_output, m_stride);
}
}
}
| 36.229299 | 106 | 0.553973 | [
"MIT"
] | Sagilio/GARbro | ArcFormats/StudioJikkenshitsu/ImageGRC.cs | 5,688 | C# |
// Copyright 2016 Michael Mairegger
//
// 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 Mairegger.Printing.Definition
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// Defines on which pages the specific <see cref="PrintAppendixes" /> should not be printed.
/// </summary>
/// <remarks>
/// <see cref="ExcludeFromPageAttribute" /> is prioritized against <see cref="PrintOnPageAttribute" />
/// </remarks>
[SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes", Justification = "Inheriting should be allowed")]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[DebuggerDisplay("Exclude on page: {" + nameof(PrintAppendixes) + "}")]
public class ExcludeFromPageAttribute : PrintPartDefinitionAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="ExcludeFromPageAttribute" /> class regarding the specified range and
/// print parts
/// </summary>
/// <param name="printAppendixes">The print parts that are defined by this attribute.</param>
/// <param name="pages">The page range where the print parts are not defined</param>
public ExcludeFromPageAttribute(PrintAppendixes printAppendixes, Range<int> pages)
: base(printAppendixes, pages)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ExcludeFromPageAttribute" /> class regarding the specified single page
/// and print parts
/// </summary>
/// <param name="printAppendixes">The print parts that are defined by this attribute.</param>
/// <param name="singlePage">The page where the print parts is not defined.</param>
public ExcludeFromPageAttribute(PrintAppendixes printAppendixes, int singlePage)
: base(printAppendixes, singlePage)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ExcludeFromPageAttribute" /> class regarding the specified pages and
/// print parts
/// </summary>
/// <param name="printAppendixes">The print parts that are defined by this attribute.</param>
/// <param name="definedPages">The pages where the print parts are not defined.</param>
public ExcludeFromPageAttribute(PrintAppendixes printAppendixes, params int[] definedPages)
: base(printAppendixes, definedPages)
{
}
public sealed override PrintPartStatus GetPrintDefinition(int page)
{
if (IsPageInAnyRange(page))
{
return PrintPartStatus.Exclude;
}
return PrintPartStatus.NotDefined;
}
}
} | 44.306667 | 131 | 0.661751 | [
"Apache-2.0"
] | johnmbaughman/Mairegger.Printing | src/Mairegger.Printing/Definition/ExcludeFromPageAttribute.cs | 3,323 | C# |
/* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.Runtime.Serialization;
using OpenSearch.Net;
namespace OpenSearch.Client
{
/// <summary>
/// Determines how the terms aggregation is executed
/// </summary>
[StringEnum]
public enum TermsAggregationCollectMode
{
/// <summary>
/// Order by using field values directly in order to aggregate data per-bucket
/// </summary>
[EnumMember(Value = "depth_first")]
DepthFirst,
/// <summary>
/// Order by using ordinals of the field values instead of the values themselves
/// </summary>
[EnumMember(Value = "breadth_first")]
BreadthFirst
}
}
| 31.692308 | 82 | 0.745752 | [
"Apache-2.0"
] | opensearch-project/opensearch-net | src/OpenSearch.Client/Aggregations/Bucket/Terms/TermsAggregationCollectMode.cs | 1,648 | C# |
using System;
namespace P15_ThreeEqualNumbers
{
class ThreeEqualNumbers
{
static void Main(string[] args)
{
double num1 = double.Parse(Console.ReadLine());
double num2 = double.Parse(Console.ReadLine());
double num3 = double.Parse(Console.ReadLine());
if (num1 == num2 && num2 == num3)
{
Console.WriteLine("yes");
}
else
{
Console.WriteLine("no");
}
}
}
}
| 22.291667 | 59 | 0.474766 | [
"MIT"
] | stStoyanov93/SoftUni-Programming-Basics | PS03_SimpleConditionalStatements/P15_ThreeEqualNumbers/ThreeEqualNumbers.cs | 537 | C# |
namespace Nager.Country.CountryInfo
{
/// <summary>
/// Barbados
/// </summary>
public class BarbadosInfo : ICountryInfo
{
public string CommonName => "Barbados";
public string OfficialName => "Barbados";
public Translation[] Translations => new []
{
new Translation(LanguageCode.AR, "باربادوس"),
new Translation(LanguageCode.AZ, "Barbados"),
new Translation(LanguageCode.BE, "Барбадас"),
new Translation(LanguageCode.BG, "Барбадос"),
new Translation(LanguageCode.BS, "Barbados"),
new Translation(LanguageCode.CA, "Barbados"),
new Translation(LanguageCode.CS, "Barbados"),
new Translation(LanguageCode.DA, "Barbados"),
new Translation(LanguageCode.DE, "Barbados"),
new Translation(LanguageCode.EL, "Μπαρμπάντος"),
new Translation(LanguageCode.EN, "Barbados"),
new Translation(LanguageCode.ES, "Barbados"),
new Translation(LanguageCode.ET, "Barbados"),
new Translation(LanguageCode.FA, "باربادوس"),
new Translation(LanguageCode.FI, "Barbados"),
new Translation(LanguageCode.FR, "Barbade"),
new Translation(LanguageCode.HE, "ברבדוס"),
new Translation(LanguageCode.HR, "Barbados"),
new Translation(LanguageCode.HU, "Barbados"),
new Translation(LanguageCode.HY, "Բարբադոս"),
new Translation(LanguageCode.ID, "Barbados"),
new Translation(LanguageCode.IT, "Barbados"),
new Translation(LanguageCode.JA, "バルバドス"),
new Translation(LanguageCode.KA, "ბარბადოსი"),
new Translation(LanguageCode.KK, "Барбадос"),
new Translation(LanguageCode.KO, "바베이도스"),
new Translation(LanguageCode.KY, "Барбадос"),
new Translation(LanguageCode.LT, "Barbadosas"),
new Translation(LanguageCode.LV, "Barbadosa"),
new Translation(LanguageCode.MK, "Барбадос"),
new Translation(LanguageCode.MN, "Барбадос"),
new Translation(LanguageCode.NB, "Barbados"),
new Translation(LanguageCode.NL, "Barbados"),
new Translation(LanguageCode.NN, "Barbados"),
new Translation(LanguageCode.PL, "Barbados"),
new Translation(LanguageCode.PT, "Barbados"),
new Translation(LanguageCode.RO, "Barbados"),
new Translation(LanguageCode.RU, "Барбадос"),
new Translation(LanguageCode.SK, "Barbados"),
new Translation(LanguageCode.SL, "Barbados"),
new Translation(LanguageCode.SR, "Барбадос"),
new Translation(LanguageCode.SV, "Barbados"),
new Translation(LanguageCode.TR, "Barbados"),
new Translation(LanguageCode.UK, "Барбадос"),
new Translation(LanguageCode.UZ, "Barbados"),
new Translation(LanguageCode.ZH, "巴巴多斯"),
};
public Alpha2Code Alpha2Code => Alpha2Code.BB;
public Alpha3Code Alpha3Code => Alpha3Code.BRB;
public int NumericCode => 052;
public string[] TLD => new [] { ".bb" };
public Region Region => Region.Americas;
public SubRegion SubRegion => SubRegion.Caribbean;
public Alpha2Code[] BorderCountrys => new Alpha2Code[]
{
};
public string[] Currencies => new [] { "BBD" };
public string[] CallingCodes => new [] { "1246" };
}
}
| 45.973684 | 62 | 0.60933 | [
"MIT"
] | MrGrabazu/Nager.Country | src/Nager.Country/CountryInfo/BarbadosInfo.cs | 3,653 | C# |
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LoadConfiguration {
public static ApiConfig ApiConfig;
/// <summary>
/// Load API config from json file
/// </summary>
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
public static void LoadAPIConfig()
{
Debug.Log("Loading api config");
var Result = (TextAsset)Resources.Load("Configuration/configuration_api");
ApiConfig = JsonUtility.FromJson<ApiConfig>(Result.text);
API.Initialize();
// TESTING
Debug.Log(API.GetProduct("120267000000").nutrition_facts.standard.nutrients[0].name);
Debug.Log(API.GetProduct("120267000000").origins.producing_country);
}
}
[System.Serializable]
public class ApiConfig
{
public string username;
public string password;
public string base_url;
public string product_url;
public string discount_url;
}
| 24.97619 | 93 | 0.71306 | [
"MIT"
] | vithu92/hackzurich2020_viroda | Assets/Resources/Scripts/LoadConfiguration.cs | 1,051 | C# |
/*
* MightyLittleGeodesy
* RT90, SWEREF99 and WGS84 coordinate transformation library
*
* Read my blog @ http://blog.sallarp.com
*
*
* Copyright (C) 2009 Björn Sållarp
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace SwedishCoordinates.Positions
{
using SwedishCoordinates.Classes;
public class SWEREF99Position : Position
{
public enum SWEREFProjection
{
sweref_99_tm = 0,
sweref_99_12_00 = 1,
sweref_99_13_30 = 2,
sweref_99_15_00 = 3,
sweref_99_16_30 = 4,
sweref_99_18_00 = 5,
sweref_99_14_15 = 6,
sweref_99_15_45 = 7,
sweref_99_17_15 = 8,
sweref_99_18_45 = 9,
sweref_99_20_15 = 10,
sweref_99_21_45 = 11,
sweref_99_23_15 = 12
}
/// <summary>
/// Create a Sweref99 position from double values with
/// Sweref 99 TM as default projection.
/// </summary>
/// <param name="n"></param>
/// <param name="e"></param>
public SWEREF99Position(double n, double e)
: base(n, e, Grid.SWEREF99)
{
this.Projection = SWEREFProjection.sweref_99_tm;
}
/// <summary>
/// Create a Sweref99 position from double values. Supply the projection
/// for values other than Sweref 99 TM
/// </summary>
/// <param name="n"></param>
/// <param name="e"></param>
/// <param name="projection"></param>
public SWEREF99Position(double n, double e, SWEREFProjection projection)
: base(n, e, Grid.SWEREF99)
{
this.Projection = projection;
}
/// <summary>
/// Create a RT90 position by converting a WGS84 position
/// </summary>
/// <param name="position">WGS84 position to convert</param>
/// <param name="rt90projection">Projection to convert to</param>
public SWEREF99Position(WGS84Position position, SWEREFProjection projection)
: base(Grid.SWEREF99)
{
GaussKreuger gkProjection = new GaussKreuger();
gkProjection.swedish_params(this.GetProjectionString(projection));
var lat_lon = gkProjection.geodetic_to_grid(position.Latitude, position.Longitude);
this.Latitude = lat_lon[0];
this.Longitude = lat_lon[1];
this.Projection = projection;
}
/// <summary>
/// Convert the position to WGS84 format
/// </summary>
/// <returns></returns>
public WGS84Position ToWGS84()
{
GaussKreuger gkProjection = new GaussKreuger();
gkProjection.swedish_params(this.ProjectionString);
var lat_lon = gkProjection.grid_to_geodetic(this.Latitude, this.Longitude);
WGS84Position newPos = new WGS84Position()
{
Latitude = lat_lon[0],
Longitude = lat_lon[1]
};
return newPos;
}
private string GetProjectionString(SWEREFProjection projection)
{
string retVal = string.Empty;
switch (projection)
{
case SWEREFProjection.sweref_99_tm:
retVal = "sweref_99_tm";
break;
case SWEREFProjection.sweref_99_12_00:
retVal = "sweref_99_1200";
break;
case SWEREFProjection.sweref_99_13_30:
retVal = "sweref_99_1330";
break;
case SWEREFProjection.sweref_99_14_15:
retVal = "sweref_99_1415";
break;
case SWEREFProjection.sweref_99_15_00:
retVal = "sweref_99_1500";
break;
case SWEREFProjection.sweref_99_15_45:
retVal = "sweref_99_1545";
break;
case SWEREFProjection.sweref_99_16_30:
retVal = "sweref_99_1630";
break;
case SWEREFProjection.sweref_99_17_15:
retVal = "sweref_99_1715";
break;
case SWEREFProjection.sweref_99_18_00:
retVal = "sweref_99_1800";
break;
case SWEREFProjection.sweref_99_18_45:
retVal = "sweref_99_1845";
break;
case SWEREFProjection.sweref_99_20_15:
retVal = "sweref_99_2015";
break;
case SWEREFProjection.sweref_99_21_45:
retVal = "sweref_99_2145";
break;
case SWEREFProjection.sweref_99_23_15:
retVal = "sweref_99_2315";
break;
default:
retVal = "sweref_99_tm";
break;
}
return retVal;
}
public SWEREFProjection Projection { get; set; }
public string ProjectionString
{
get
{
return this.GetProjectionString(this.Projection);
}
}
public override string ToString()
{
return string.Format("N: {0} E: {1} Projection: {2}", this.Latitude, this.Longitude, this.ProjectionString);
}
}
}
| 37.051136 | 120 | 0.56295 | [
"MIT"
] | unger/SwedishCoordinates | SwedishCoordinates/Positions/SWEREF99Position.cs | 6,525 | C# |
// *** WARNING: this file was generated by pulumigen. ***
// *** 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.Kubernetes.Certificates.V1Beta1
{
/// <summary>
/// Describes a certificate signing request
/// </summary>
[KubernetesResourceType("kubernetes:certificates.k8s.io/v1beta1:CertificateSigningRequest")]
public partial class CertificateSigningRequest : KubernetesResource
{
/// <summary>
/// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
/// </summary>
[Output("apiVersion")]
public Output<string> ApiVersion { get; private set; } = null!;
/// <summary>
/// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
/// </summary>
[Output("kind")]
public Output<string> Kind { get; private set; } = null!;
[Output("metadata")]
public Output<Pulumi.Kubernetes.Types.Outputs.Meta.V1.ObjectMeta> Metadata { get; private set; } = null!;
/// <summary>
/// The certificate request itself and any additional information.
/// </summary>
[Output("spec")]
public Output<Pulumi.Kubernetes.Types.Outputs.Certificates.V1Beta1.CertificateSigningRequestSpec> Spec { get; private set; } = null!;
/// <summary>
/// Derived information about the request.
/// </summary>
[Output("status")]
public Output<Pulumi.Kubernetes.Types.Outputs.Certificates.V1Beta1.CertificateSigningRequestStatus> Status { get; private set; } = null!;
/// <summary>
/// Create a CertificateSigningRequest 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 CertificateSigningRequest(string name, Pulumi.Kubernetes.Types.Inputs.Certificates.V1Beta1.CertificateSigningRequestArgs? args = null, CustomResourceOptions? options = null)
: base("kubernetes:certificates.k8s.io/v1beta1:CertificateSigningRequest", name, MakeArgs(args), MakeResourceOptions(options, ""))
{
}
internal CertificateSigningRequest(string name, ImmutableDictionary<string, object?> dictionary, CustomResourceOptions? options = null)
: base("kubernetes:certificates.k8s.io/v1beta1:CertificateSigningRequest", name, new DictionaryResourceArgs(dictionary), MakeResourceOptions(options, ""))
{
}
private CertificateSigningRequest(string name, Input<string> id, CustomResourceOptions? options = null)
: base("kubernetes:certificates.k8s.io/v1beta1:CertificateSigningRequest", name, null, MakeResourceOptions(options, id))
{
}
private static Pulumi.Kubernetes.Types.Inputs.Certificates.V1Beta1.CertificateSigningRequestArgs? MakeArgs(Pulumi.Kubernetes.Types.Inputs.Certificates.V1Beta1.CertificateSigningRequestArgs? args)
{
args ??= new Pulumi.Kubernetes.Types.Inputs.Certificates.V1Beta1.CertificateSigningRequestArgs();
args.ApiVersion = "certificates.k8s.io/v1beta1";
args.Kind = "CertificateSigningRequest";
return args;
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "kubernetes:certificates.k8s.io/v1:CertificateSigningRequest"},
},
};
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 CertificateSigningRequest 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 CertificateSigningRequest Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new CertificateSigningRequest(name, id, options);
}
}
}
namespace Pulumi.Kubernetes.Types.Inputs.Certificates.V1Beta1
{
public class CertificateSigningRequestArgs : Pulumi.ResourceArgs
{
/// <summary>
/// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
/// </summary>
[Input("apiVersion")]
public Input<string>? ApiVersion { get; set; }
/// <summary>
/// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
/// </summary>
[Input("kind")]
public Input<string>? Kind { get; set; }
[Input("metadata")]
public Input<Pulumi.Kubernetes.Types.Inputs.Meta.V1.ObjectMetaArgs>? Metadata { get; set; }
/// <summary>
/// The certificate request itself and any additional information.
/// </summary>
[Input("spec")]
public Input<Pulumi.Kubernetes.Types.Inputs.Certificates.V1Beta1.CertificateSigningRequestSpecArgs>? Spec { get; set; }
public CertificateSigningRequestArgs()
{
}
}
}
| 51.155556 | 302 | 0.675355 | [
"Apache-2.0"
] | AaronFriel/pulumi-kubernetes | sdk/dotnet/Certificates/V1Beta1/CertificateSigningRequest.cs | 6,906 | C# |
namespace MyClinicalCourse.ClinicalCourse
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
/// <summary>
/// 看護経過表の軸目盛り コントロールです。
/// このコントロールを利用者が直接作成することはありません。
/// </summary>
internal class AxisTick : Control
{
static AxisTick()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(AxisTick), new FrameworkPropertyMetadata(typeof(AxisTick)));
}
internal AxisTick()
{
}
#region 依存関係プロパティ
/// <summary>
/// 軸の配置場所を表す値を を取得します。
/// </summary>
/// <remarks>このプロパティは読み取り専用です。</remarks>
[Category("看護経過表")]
[Description("軸の配置場所を表す値を を取得します。このプロパティは読み取り専用です。")]
public AxisPosition Position
{
get { return (AxisPosition)GetValue(PositionProperty); }
private set { SetValue(PositionPropertyKey, value); }
}
// Using a DependencyProperty as the backing store for Position. This enables animation, styling, binding, etc...
private static readonly DependencyPropertyKey PositionPropertyKey =
DependencyProperty.RegisterReadOnly("Position", typeof(AxisPosition), typeof(AxisTick),
new FrameworkPropertyMetadata(AxisPosition.Left, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsParentMeasure,
(oo, ee) =>
{
var sender = oo as AxisTick;
sender?.OnPositionPropertyChanged(sender.Position);
}, null, false, UpdateSourceTrigger.PropertyChanged));
public static readonly DependencyProperty PositionProperty = PositionPropertyKey.DependencyProperty;
/// <summary>
/// 軸目盛り領域の幅 を取得します。
/// </summary>
/// <remarks>このプロパティは読み取り専用です。</remarks>
[Category("看護経過表")]
[Description("軸目盛り領域の幅 を取得します。このプロパティは読み取り専用です。")]
public double TickAreaWidth
{
get { return (double)GetValue(TickAreaWidthProperty); }
private set { SetValue(TickAreaWidthPropertyKey, value); }
}
// Using a DependencyProperty as the backing store for TickAreaWidth. This enables animation, styling, binding, etc...
private static readonly DependencyPropertyKey TickAreaWidthPropertyKey =
DependencyProperty.RegisterReadOnly("TickAreaWidth", typeof(double), typeof(AxisTick),
new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.AffectsMeasure,
null, null, false, UpdateSourceTrigger.PropertyChanged));
public static readonly DependencyProperty TickAreaWidthProperty = TickAreaWidthPropertyKey.DependencyProperty;
/// <summary>
/// 軸目盛り領域の高さ を取得します。
/// </summary>
/// <remarks>このプロパティは読み取り専用です。</remarks>
[Category("看護経過表")]
[Description("軸目盛り領域の高さ を取得します。このプロパティは読み取り専用です。")]
public double TickAreaHeight
{
get { return (double)GetValue(TickAreaHeightProperty); }
private set { SetValue(TickAreaHeightPropertyKey, value); }
}
// Using a DependencyProperty as the backing store for TickAreaHeight. This enables animation, styling, binding, etc...
private static readonly DependencyPropertyKey TickAreaHeightPropertyKey =
DependencyProperty.RegisterReadOnly("TickAreaHeight", typeof(double), typeof(AxisTick),
new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.AffectsMeasure,
null, null, false, UpdateSourceTrigger.PropertyChanged));
public static readonly DependencyProperty TickAreaHeightProperty = TickAreaHeightPropertyKey.DependencyProperty;
/// <summary>
/// 軸目盛りのコレクション を取得します。
/// </summary>
/// <remarks>このプロパティは読み取り専用です。</remarks>
[Category("看護経過表")]
[Description("軸目盛りのコレクション を取得します。このプロパティは読み取り専用です。")]
public IEnumerable<AxisTickModel> TickItems
{
get { return (IEnumerable<AxisTickModel>)GetValue(TickItemsProperty); }
private set { SetValue(TickItemsPropertyKey, value); }
}
// Using a DependencyProperty as the backing store for TickItems. This enables animation, styling, binding, etc...
private static readonly DependencyPropertyKey TickItemsPropertyKey =
DependencyProperty.RegisterReadOnly("TickItems", typeof(IEnumerable<AxisTickModel>), typeof(AxisTick),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsArrange, null, null, false, UpdateSourceTrigger.PropertyChanged));
public static readonly DependencyProperty TickItemsProperty = TickItemsPropertyKey.DependencyProperty;
#endregion
/// <summary>
/// 軸目盛りの変更イベントハンドラー
/// </summary>
/// <param name="sender">イベントの発生元オブジェクト</param>
/// <param name="e">イベント引数</param>
internal void OnAxisTickChanged(object sender, AxisTickChangedEventArgs e)
{
this.Position = e.Position;
this.TickItems = e.Ticks.ToList();
this.TickAreaWidth = e.Position.IsSideAxis() ? e.TickAreaSize : double.NaN;
this.TickAreaHeight = e.Position.IsSideAxis() ? double.NaN : e.TickAreaSize;
this.Visibility = e.IsShowTick ? Visibility.Visible : Visibility.Collapsed;
VisualStateManager.GoToState(this, this.Position.ToString(), false);
}
/// <summary>
/// 軸の配置変更時の処理
/// </summary>
/// <param name="position">軸の配置</param>
private void OnPositionPropertyChanged(AxisPosition position)
{
VisualStateManager.GoToState(this, position.ToString(), false);
}
}
}
| 43.686131 | 169 | 0.654971 | [
"MIT"
] | mizuku/MyClinicalCourse | MyClinicalCourse/ClinicalCourse/AxisTick.cs | 6,779 | C# |
using Newtonsoft.Json;
namespace Nest
{
[JsonObject]
public class EmailActionResult
{
[JsonProperty("reason")]
public string Reason { get; set; }
[JsonProperty("account")]
public string Account { get; set; }
[JsonProperty("message")]
public EmailResult Message { get; set; }
}
}
| 16.611111 | 42 | 0.685619 | [
"Apache-2.0"
] | BedeGaming/elasticsearch-net | src/Nest/XPack/Watcher/Execution/Email/EmailActionResult.cs | 301 | C# |
using FluentAssertions;
using NToolbox.Extensions.Strings;
using Xunit;
namespace NToolbox.Tests.Extensions.Strings
{
public class IsNotNullOrWhiteSpaceTests
{
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
[InlineData("abc")]
public void IsNotNullOrEmpty_StringValue_True(string value)
{
// Arrange
var expectedResult = !string.IsNullOrWhiteSpace(value);
// Act
var result = value.IsNotNullOrWhiteSpace();
// Assert
result.Should().Be(expectedResult);
}
}
}
| 21.689655 | 67 | 0.586645 | [
"MIT"
] | lmorelato/n-toolbox | tests/NToolbox.Tests/Extensions/Strings/IsNotNullOrWhiteSpaceTests.cs | 631 | C# |
using System;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Crmf;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Operators;
namespace Org.BouncyCastle.Crmf
{
public class ProofOfPossessionSigningKeyBuilder
{
private CertRequest _certRequest;
private SubjectPublicKeyInfo _pubKeyInfo;
private GeneralName _name;
private PKMacValue _publicKeyMAC;
public ProofOfPossessionSigningKeyBuilder(CertRequest certRequest)
{
this._certRequest = certRequest;
}
public ProofOfPossessionSigningKeyBuilder(SubjectPublicKeyInfo pubKeyInfo)
{
this._pubKeyInfo = pubKeyInfo;
}
public ProofOfPossessionSigningKeyBuilder SetSender(GeneralName name)
{
this._name = name;
return this;
}
public ProofOfPossessionSigningKeyBuilder SetPublicKeyMac(PKMacBuilder generator, char[] password)
{
IMacFactory fact = generator.Build(password);
IStreamCalculator calc = fact.CreateCalculator();
byte[] d = _pubKeyInfo.GetDerEncoded();
calc.Stream.Write(d, 0, d.Length);
calc.Stream.Flush();
calc.Stream.Close();
this._publicKeyMAC = new PKMacValue(
(AlgorithmIdentifier)fact.AlgorithmDetails,
new DerBitString(((IBlockResult)calc.GetResult()).Collect()));
return this;
}
public PopoSigningKey Build(ISignatureFactory signer)
{
if (_name != null && _publicKeyMAC != null)
{
throw new InvalidOperationException("name and publicKeyMAC cannot both be set.");
}
PopoSigningKeyInput popo;
byte[] b;
IStreamCalculator calc = signer.CreateCalculator();
if (_certRequest != null)
{
popo = null;
b = _certRequest.GetDerEncoded();
calc.Stream.Write(b, 0, b.Length);
}
else if (_name != null)
{
popo = new PopoSigningKeyInput(_name, _pubKeyInfo);
b = popo.GetDerEncoded();
calc.Stream.Write(b, 0, b.Length);
}
else
{
popo = new PopoSigningKeyInput(_publicKeyMAC, _pubKeyInfo);
b = popo.GetDerEncoded();
calc.Stream.Write(b, 0, b.Length);
}
calc.Stream.Flush();
calc.Stream.Close();
DefaultSignatureResult res = (DefaultSignatureResult)calc.GetResult();
return new PopoSigningKey(popo, (AlgorithmIdentifier)signer.AlgorithmDetails, new DerBitString(res.Collect()));
}
}
}
| 31.775281 | 123 | 0.586987 | [
"MIT"
] | SeppPenner/bc-csharp | crypto/src/crmf/ProofOfPossessionSigningKeyBuilder.cs | 2,830 | C# |
// -----------------------------------------------------------------------
// <copyright file="ProjectLineParser.cs" company="Brad Marshall">
// Copyright © 2019 Brad Marshall. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace CodeGenerator.SolutionFile
{
/// <summary>
/// Parse Project section. It is of the following format:
/// Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items",
/// "{BCE760BF-2F2F-4CDE-965D-A125430CE1FD}"
/// ProjectSection(SolutionItems) = preProject
/// dirs.proj = dirs.proj
/// EndProjectSection
/// EndProject
/// 'ProjectSection' optional element
/// </summary>
internal sealed class ProjectLineParser : ILineParser
{
private readonly SectionDefinitionLineParser sectionParser;
private ProjectDefinition project;
private State currentState;
public ProjectLineParser()
{
sectionParser = new SectionDefinitionLineParser("ProjectSection");
}
public bool TryParseLine(string line, SolutionFileBuilder sfb, out bool needMoreLines)
{
needMoreLines = false;
if (currentState == State.NotStarted)
{
if (line.StartsWith("Project(\""))
{
if (!TryParseProjectDefinitionFirstLine(line))
{
sfb.SetIsValid(false);
return false;
}
currentState = State.WaitForProjectSectionOrEnd;
needMoreLines = true;
return true;
}
}
else if (currentState == State.WaitForProjectSectionOrEnd)
{
if (line == "EndProject")
{
sfb.AddProjectDefinition(project);
Clear();
return true;
}
if (sectionParser.TryParseFirstLine(line))
{
currentState = State.InsideProjectSection;
needMoreLines = true;
return true;
}
sfb.SetIsValid(false);
}
else if (currentState == State.InsideProjectSection)
{
if (!sectionParser.ParseNextLine(line))
{
if (sectionParser.LastProcessingStatus == SectionDefinitionLineParser.State.Succeeded)
{
project.InnerProjectSections[sectionParser.LastSuccessfullyProcessedSection.SectionType] =
sectionParser.LastSuccessfullyProcessedSection;
currentState = State.WaitForProjectSectionOrEnd;
needMoreLines = true;
return true;
}
sfb.SetIsValid(false);
}
else
{
needMoreLines = true;
return true;
}
}
return false;
}
private bool TryParseProjectDefinitionFirstLine(string line)
{
KeyValuePair<string, string> result1;
if (!LineParserHelper.TryParseKeyValuePair(line, out result1))
{
return false;
}
string[] arrayOfStrings = LineParserHelper.ParseArrayOfStrings(result1.Value);
if (arrayOfStrings.Length != 3)
{
return false;
}
int num1 = result1.Key.IndexOf('{');
int num2 = result1.Key.IndexOf('}');
Guid result2;
if (num1 == -1 ||
num2 == -1 ||
num1 + 1 > num2 ||
!Guid.TryParse(result1.Key.Substring(num1 + 1, num2 - num1 - 1), out result2))
{
return false;
}
string name = arrayOfStrings[0];
string moniker = arrayOfStrings[1];
Guid result3;
if (!Guid.TryParse(arrayOfStrings[2].Trim('{', '}'), out result3))
{
return false;
}
project = new ProjectDefinition(result2, name, moniker, result3);
return true;
}
private void Clear()
{
project = null;
currentState = State.NotStarted;
}
private enum State
{
NotStarted,
WaitForProjectSectionOrEnd,
InsideProjectSection
}
}
}
| 33.827586 | 115 | 0.468502 | [
"MIT"
] | sped-mobi/repogen | tools/CodeGenerator/SolutionFile/ProjectLineParser.cs | 4,908 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace SpreadsheetLight
{
/// <summary>
/// The type of data fields to be imported, whether by delimiters/separators or in fixed width.
/// </summary>
public enum SLTextImportDataFieldTypeValues
{
/// <summary>
/// Data is separated by character delimiters.
/// </summary>
Delimited = 0,
/// <summary>
/// Data is separated by fixed width columns.
/// </summary>
FixedWidth
}
/// <summary>
/// The type of column data format.
/// </summary>
public enum SLTextImportColumnFormatValues
{
/// <summary>
/// Numeric values will be converted to numbers, date values to dates and remaining values to text.
/// </summary>
General = 0,
/// <summary>
/// Text format.
/// </summary>
Text,
/// <summary>
/// The value will be parsed as a date in the order of month, day, year.
/// Failing that, any given custom date formats will be used to parse the value.
/// Failing that, the value is parse generically as a date.
/// And failing that, the value is set as text.
/// </summary>
DateMDY,
/// <summary>
/// The value will be parsed as a date in the order of day, month, year.
/// Failing that, any given custom date formats will be used to parse the value.
/// Failing that, the value is parse generically as a date.
/// And failing that, the value is set as text.
/// </summary>
DateDMY,
/// <summary>
/// The value will be parsed as a date in the order of year, month, day.
/// Failing that, any given custom date formats will be used to parse the value.
/// Failing that, the value is parse generically as a date.
/// And failing that, the value is set as text.
/// </summary>
DateYMD,
/// <summary>
/// The value will be parsed as a date in the order of month, year, day.
/// Failing that, any given custom date formats will be used to parse the value.
/// Failing that, the value is parse generically as a date.
/// And failing that, the value is set as text.
/// </summary>
DateMYD,
/// <summary>
/// The value will be parsed as a date in the order of day, year, month.
/// Failing that, any given custom date formats will be used to parse the value.
/// Failing that, the value is parse generically as a date.
/// And failing that, the value is set as text.
/// </summary>
DateDYM,
/// <summary>
/// The value will be parsed as a date in the order of year, day, month.
/// Failing that, any given custom date formats will be used to parse the value.
/// Failing that, the value is parse generically as a date.
/// And failing that, the value is set as text.
/// </summary>
DateYDM,
/// <summary>
/// This column will be skipped.
/// </summary>
Skip
}
/// <summary>
/// Text import options for importing text data.
/// </summary>
public class SLTextImportOptions
{
/// <summary>
/// Indicates if fields are separated by character delimiters or are of fixed width.
/// The default is Delimited.
/// </summary>
public SLTextImportDataFieldTypeValues DataFieldType { get; set; }
// Excel by default only has the tab delimiter turned on.
// LibreOffice Calc by default has the tab, comma and semicolon delimiters turned on.
// I'm gonna follow Excel. Having the comma delimiter makes sense. Because you know,
// the C in CSV stands for "comma". But if the data contains something like
// "1,234,567.89" then the comma is a hindrance. We want the 1.234 million.
private int iDefaultFixedWidth;
/// <summary>
/// The default number of characters when columns are of fixed width.
/// If no width is set for a column, this will be used. By default, this is 8 characters.
/// </summary>
public int DefaultFixedWidth
{
get { return iDefaultFixedWidth; }
set
{
if (value >= 1) iDefaultFixedWidth = value;
}
}
/// <summary>
/// Indicates if a tab character is a delimiter. By default, this is true.
/// </summary>
public bool UseTabDelimiter { get; set; }
/// <summary>
/// Indicates if a semicolon is a delimiter. By default, this is false.
/// </summary>
public bool UseSemicolonDelimiter { get; set; }
/// <summary>
/// Indicates if a comma is a delimiter. By default, this is false.
/// </summary>
public bool UseCommaDelimiter { get; set; }
/// <summary>
/// Indicates if a space character is a delimiter. By default, this is false.
/// </summary>
public bool UseSpaceDelimiter { get; set; }
/// <summary>
/// Indicates if a custom character is used as a delimiter. By default, this is false. Use the CustomDelimiter property to set the custom delimiter character.
/// </summary>
public bool UseCustomDelimiter { get; set; }
/// <summary>
/// The custom delimiter character. This is used only when UseCustomDelimiter is true.
/// </summary>
public char CustomDelimiter { get; set; }
/// <summary>
/// Indicates if consecutive delimiters are treated as one.
/// </summary>
public bool MergeDelimiters { get; set; }
/// <summary>
/// Indicates if data enclosed within text qualifiers is taken as text.
/// The default is true.
/// </summary>
public bool HasTextQualifier { get; set; }
/// <summary>
/// Data enclosed within this qualifier will automatically be taken as text. The text qualifier
/// will be removed. The default is the double quote character.
/// </summary>
public char TextQualifier { get; set; }
private int iImportStartRowIndex;
/// <summary>
/// The row in the text data source to begin importing.
/// </summary>
public int ImportStartRowIndex
{
get { return iImportStartRowIndex; }
set
{
// because 0 and negative numbers don't make sense
if (value >= 1) iImportStartRowIndex = value;
}
}
/// <summary>
/// The culture used for parsing numbers and dates. The default is the InvariantCulture.
/// </summary>
public CultureInfo Culture { get; set; }
/// <summary>
/// The number styles used for parsing numeric data. The default is NumberStyles.Any.
/// </summary>
public NumberStyles NumberStyles { get; set; }
/// <summary>
/// The encoding used to read the data source. The default is Encoding.Default.
/// </summary>
public Encoding Encoding { get; set; }
/// <summary>
/// Indicates if space characters in the data source are preserved (after data column separation by delimiters). By default, this is true.
/// </summary>
public bool PreserveSpace { get; set; }
internal Dictionary<int, SLTextImportColumnFormatValues> dictColumnFormat;
internal List<string> listCustomDateFormats;
internal Dictionary<int, int> dictFixedWidth;
/// <summary>
/// Initializes an instance of SLTextImportOptions, and assuming that the data source is character delimited.
/// </summary>
public SLTextImportOptions()
{
this.SetAllNull(SLTextImportDataFieldTypeValues.Delimited);
}
/// <summary>
/// Initializes an instance of SLTextImportOptions.
/// </summary>
/// <param name="DataFieldType">Whether the data source is character delimited or of fixed width.</param>
public SLTextImportOptions(SLTextImportDataFieldTypeValues DataFieldType)
{
this.SetAllNull(DataFieldType);
}
private void SetAllNull(SLTextImportDataFieldTypeValues DataFieldType)
{
this.DataFieldType = DataFieldType;
this.iDefaultFixedWidth = 8;
this.UseTabDelimiter = true;
this.UseSemicolonDelimiter = false;
this.UseCommaDelimiter = false;
this.UseSpaceDelimiter = false;
this.UseCustomDelimiter = false;
this.CustomDelimiter = ' ';
this.MergeDelimiters = false;
this.HasTextQualifier = true;
this.TextQualifier = '"';
this.iImportStartRowIndex = 1;
this.Culture = CultureInfo.InvariantCulture;
this.NumberStyles = System.Globalization.NumberStyles.Any;
this.Encoding = Encoding.Default;
this.PreserveSpace = true;
this.dictColumnFormat = new Dictionary<int, SLTextImportColumnFormatValues>();
this.listCustomDateFormats = new List<string>();
this.dictFixedWidth = new Dictionary<int, int>();
}
/// <summary>
/// Set the column data format type.
/// </summary>
/// <param name="ColumnIndex">The column index in the data source. This is 1-based indexing, so it's 1 for the 1st data source column, 2 for the 2nd data source column and so on.</param>
/// <param name="ColumnFormat">The column data format type.</param>
public void SetColumnFormat(int ColumnIndex, SLTextImportColumnFormatValues ColumnFormat)
{
if (ColumnIndex >= 1)
{
this.dictColumnFormat[ColumnIndex] = ColumnFormat;
}
}
/// <summary>
/// Skip a particular data source column. This is equivalent to using the SetColumnFormat() function with a Skip data format type.
/// </summary>
/// <param name="ColumnIndex">The data source column to skip. This is 1-based indexing, so it's 1 for the 1st data source column, 2 for the 2nd data source column and so on.</param>
public void SkipColumn(int ColumnIndex)
{
if (ColumnIndex >= 1)
{
this.dictColumnFormat[ColumnIndex] = SLTextImportColumnFormatValues.Skip;
}
}
/// <summary>
/// Clear all column data formats. This is effectively making all columns to be of General type.
/// </summary>
public void ClearColumnFormats()
{
this.dictColumnFormat.Clear();
}
/// <summary>
/// Add custom date formats (this is the .NET date format code, not Excel's format code).
/// This is used to parse any date data into a date, and is done first before trying other
/// generic date parsing operations.
/// </summary>
/// <param name="Format"></param>
public void AddCustomDateFormat(string Format)
{
this.listCustomDateFormats.Add(Format);
}
/// <summary>
/// Clear all custom date formats.
/// </summary>
public void ClearCustomDateFormats()
{
this.listCustomDateFormats.Clear();
}
/// <summary>
/// Set the width of a column in number of characters for separating data columns.
/// This is used when the data source is specified as of fixed width.
/// If no width is specified, the DefaultFixedWidth is used.
/// </summary>
/// <param name="ColumnIndex">The column index of the data source. This is 1-based indexing, so it's 1 for the 1st data source column, 2 for the 2nd data source column and so on.</param>
/// <param name="ColumnWidth">The column width in number of characters.</param>
public void SetFixedWidth(int ColumnIndex, int ColumnWidth)
{
if (ColumnIndex >= 1 && ColumnWidth >= 1)
{
this.dictFixedWidth[ColumnIndex] = ColumnWidth;
}
}
/// <summary>
/// Clone an instance of SLTextImportOptions.
/// </summary>
/// <returns>An SLTextImportOptions object.</returns>
public SLTextImportOptions Clone()
{
SLTextImportOptions tio = new SLTextImportOptions();
tio.DataFieldType = this.DataFieldType;
tio.iDefaultFixedWidth = this.iDefaultFixedWidth;
tio.UseTabDelimiter = this.UseTabDelimiter;
tio.UseSemicolonDelimiter = this.UseSemicolonDelimiter;
tio.UseCommaDelimiter = this.UseCommaDelimiter;
tio.UseSpaceDelimiter = this.UseSpaceDelimiter;
tio.UseCustomDelimiter = this.UseCustomDelimiter;
tio.CustomDelimiter = this.CustomDelimiter;
tio.MergeDelimiters = this.MergeDelimiters;
tio.HasTextQualifier = this.HasTextQualifier;
tio.TextQualifier = this.TextQualifier;
tio.iImportStartRowIndex = this.iImportStartRowIndex;
tio.Culture = this.Culture;
tio.NumberStyles = this.NumberStyles;
tio.Encoding = this.Encoding;
tio.PreserveSpace = this.PreserveSpace;
foreach (int key in this.dictColumnFormat.Keys)
{
tio.dictColumnFormat[key] = this.dictColumnFormat[key];
}
foreach (string format in this.listCustomDateFormats)
{
tio.listCustomDateFormats.Add(format);
}
foreach (int key in this.dictFixedWidth.Keys)
{
tio.dictFixedWidth[key] = this.dictFixedWidth[key];
}
return tio;
}
}
}
| 40.994302 | 195 | 0.579331 | [
"MIT"
] | bjornharrtell/SpreadsheetLight | misc/SLTextImportOptions.cs | 14,391 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.Azure.Commands.Storage.Table.Cmdlet
{
using Microsoft.Azure.Commands.Storage.Common;
using Microsoft.Azure.Commands.Storage.Model.Contract;
using Microsoft.Azure.Commands.Storage.Table;
using Microsoft.Azure.Cosmos.Table;
using System;
using System.Globalization;
using System.Management.Automation;
using System.Security.Permissions;
[Microsoft.Azure.PowerShell.Cmdlets.Storage.Profile("latest-2019-04-30")]
[Cmdlet("Set", Azure.Commands.ResourceManager.Common.AzureRMConstants.AzurePrefix + "StorageTableStoredAccessPolicy!V2", SupportsShouldProcess = true), OutputType(typeof(String))]
public class SetAzureStorageTableStoredAccessPolicyCommand : StorageCloudTableCmdletBase
{
[Alias("N", "Name")]
[Parameter(Position = 0, Mandatory = true,
HelpMessage = "Table Name",
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public string Table { get; set; }
[Parameter(Position = 1, Mandatory = true,
HelpMessage = "Policy Identifier")]
[ValidateNotNullOrEmpty]
public string Policy { get; set; }
[Parameter(HelpMessage = "Permissions for a table. Permissions can be any not-empty subset of \"audqr\".")]
public string Permission { get; set; }
[Parameter(HelpMessage = "Start Time")]
public DateTime? StartTime { get; set; }
[Parameter(HelpMessage = "Expirty Time")]
public DateTime? ExpiryTime { get; set; }
[Parameter(HelpMessage = "Set StartTime as null for the policy")]
public SwitchParameter NoStartTime { get; set; }
[Parameter(HelpMessage = "Set ExpiryTime as null for the policy")]
public SwitchParameter NoExpiryTime { get; set; }
/// <summary>
/// Initializes a new instance of the SetAzureStorageTableStoredAccessPolicyCommand class.
/// </summary>
public SetAzureStorageTableStoredAccessPolicyCommand()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the SetAzureStorageTableStoredAccessPolicyCommand class.
/// </summary>
/// <param name="channel">IStorageTableManagement channel</param>
public SetAzureStorageTableStoredAccessPolicyCommand(IStorageTableManagement channel)
{
Channel = channel;
EnableMultiThread = false;
}
internal string SetAzureTableStoredAccessPolicy(IStorageTableManagement localChannel, string tableName, string policyName, DateTime? startTime, DateTime? expiryTime, string permission, bool noStartTime, bool noExpiryTime)
{
DateTime? startTimeToSet = startTime;
DateTime? expiryTimetoSet = expiryTime;
//Get existing permissions
CloudTable table = localChannel.GetTableReference(Table);
TablePermissions tablePermissions = localChannel.GetTablePermissions(table);
//Set the policy with new value
if (!tablePermissions.SharedAccessPolicies.Keys.Contains(policyName))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, ResourceV2.PolicyNotFound, policyName));
}
SharedAccessTablePolicy policy = tablePermissions.SharedAccessPolicies[policyName];
AccessPolicyHelper.SetupAccessPolicy<SharedAccessTablePolicy>(policy, startTime, expiryTime, permission, noStartTime, noExpiryTime);
tablePermissions.SharedAccessPolicies[policyName] = policy;
//Set permission back to table
localChannel.SetTablePermissions(table, tablePermissions);
WriteObject(AccessPolicyHelper.ConstructPolicyOutputPSObject<SharedAccessTablePolicy>(tablePermissions.SharedAccessPolicies, policyName));
return policyName;
}
/// <summary>
/// Execute command
/// </summary>
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public override void ExecuteCmdlet()
{
if (String.IsNullOrEmpty(Table) || String.IsNullOrEmpty(Policy)) return;
if (NoStartTime && StartTime != null)
{
throw new ArgumentException(ResourceV2.StartTimeParameterConflict);
}
if (NoExpiryTime && ExpiryTime != null)
{
throw new ArgumentException(ResourceV2.ExpiryTimeParameterConflict);
}
if (ShouldProcess(Policy, "Set"))
{
SetAzureTableStoredAccessPolicy(Channel, Table, Policy, StartTime, ExpiryTime, Permission, NoStartTime, NoExpiryTime);
}
}
}
}
| 44.590551 | 230 | 0.639414 | [
"MIT"
] | bganapa/azure-powershell | src/Storage/custom/Dataplane.v2/Table/Cmdlet/SetAzureStorageTableStoredAccessPolicy.cs | 5,539 | C# |
using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using InSituVisualization.Annotations;
using InSituVisualization.Filter;
namespace InSituVisualization.ViewModels
{
public class FilterWindowControlViewModel : ViewModelBase
{
private readonly IFilterController _filterController;
public ObservableCollection<FilterControlViewModel> EnabledFilters { get; } = new ObservableCollection<FilterControlViewModel> { new FilterControlViewModel() };
public FilterWindowControlViewModel([NotNull] IFilterController filterController)
{
_filterController = filterController ?? throw new ArgumentNullException(nameof(filterController));
ApplyFiltersCommand = new RelayCommand<object>(obj => OnApplyFiltersCommand());
AddFilterCommand = new RelayCommand<FilterControlViewModel>(OnAddFilterCommand);
RemoveFilterCommand = new RelayCommand<FilterControlViewModel>(OnRemoveFilterCommand);
}
/// <summary>
/// TODO RR: Insert and remove at clicked index...
/// </summary>
private void OnRemoveFilterCommand(FilterControlViewModel filterControlViewModel)
{
EnabledFilters.Remove(filterControlViewModel);
if (EnabledFilters.Count <= 0)
{
EnabledFilters.Add(new FilterControlViewModel());
}
}
private void OnAddFilterCommand(FilterControlViewModel filterControlViewModel)
{
EnabledFilters.Insert(EnabledFilters.IndexOf(filterControlViewModel) + 1, new FilterControlViewModel());
}
public ICommand ApplyFiltersCommand { get; }
public ICommand AddFilterCommand { get; }
public ICommand RemoveFilterCommand { get; }
private void OnApplyFiltersCommand()
{
// TODO RR Rework:
_filterController.Filters.Clear();
foreach (var filterControlViewModel in EnabledFilters)
{
var filter = filterControlViewModel.GetFilter();
if (filter != null)
{
_filterController.Filters.Add(filter);
}
}
}
}
}
| 36.177419 | 168 | 0.659831 | [
"Apache-2.0"
] | sealuzh/visual-studio-perfviz | InSituVisualization/ViewModels/FilterWindowControlViewModel.cs | 2,245 | C# |
namespace AngleSharp.Dom.Svg
{
using AngleSharp.Html;
using System;
/// <summary>
/// Represents the circle element of the SVG DOM.
/// </summary>
sealed class SvgCircleElement : SvgElement, ISvgCircleElement
{
public SvgCircleElement(Document owner, String prefix = null)
: base(owner, TagNames.Circle, prefix)
{
}
}
}
| 22.941176 | 69 | 0.615385 | [
"MIT"
] | ArmyMedalMei/AngleSharp | src/AngleSharp/Dom/Svg/SvgCircleElement.cs | 392 | C# |
using System;
namespace Orleans.Runtime
{
[Serializable]
internal class PreferLocalPlacement : PlacementStrategy
{
internal static PreferLocalPlacement Singleton { get; } = new PreferLocalPlacement();
private PreferLocalPlacement()
{ }
public override bool Equals(object obj)
{
return obj is PreferLocalPlacement;
}
public override int GetHashCode()
{
return GetType().GetHashCode();
}
}
}
| 21.416667 | 93 | 0.599222 | [
"MIT"
] | Invertironline/orleans | src/Orleans/Placement/PreferLocalPlacement.cs | 514 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace WalletWasabi.Gui.Rpc
{
///<summary>
/// Represents the collection of metadata needed to execute the remote procedure.
///</summary>
public class JsonRpcMethodMetadata
{
// The name of the remote procedure. This is NOT the name of the method to be invoked.
public string Name { get; }
public MethodInfo MethodInfo { get; }
public List<(string name, Type type)> Parameters { get; }
public JsonRpcMethodMetadata(string name, MethodInfo mi, List<(string name, Type type)> parameters)
{
Name = name;
MethodInfo = mi;
Parameters = parameters;
}
}
} | 27.192308 | 101 | 0.731259 | [
"MIT"
] | lontivero/Wasabito | WalletWasabi.Gui/Rpc/JsonRpcMethodMetadata.cs | 707 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.AppService.Models;
using Azure.ResourceManager.Core;
namespace Azure.ResourceManager.AppService
{
/// <summary> A class representing collection of VnetInfoResource and their operations over its parent. </summary>
public partial class SiteVirtualNetworkConnectionCollection : ArmCollection, IEnumerable<SiteVirtualNetworkConnection>
{
private readonly ClientDiagnostics _clientDiagnostics;
private readonly WebAppsRestOperations _webAppsRestClient;
/// <summary> Initializes a new instance of the <see cref="SiteVirtualNetworkConnectionCollection"/> class for mocking. </summary>
protected SiteVirtualNetworkConnectionCollection()
{
}
/// <summary> Initializes a new instance of SiteVirtualNetworkConnectionCollection class. </summary>
/// <param name="parent"> The resource representing the parent resource. </param>
internal SiteVirtualNetworkConnectionCollection(ArmResource parent) : base(parent)
{
_clientDiagnostics = new ClientDiagnostics(ClientOptions);
_webAppsRestClient = new WebAppsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri);
}
/// <summary> Gets the valid resource type for this object. </summary>
protected override ResourceType ValidResourceType => WebSite.ResourceType;
// Collection level operations.
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/virtualNetworkConnections/{vnetName}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}
/// OperationId: WebApps_CreateOrUpdateVnetConnection
/// <summary> Description for Adds a Virtual Network connection to an app or slot (PUT) or updates the connection properties (PATCH). </summary>
/// <param name="vnetName"> Name of an existing Virtual Network. </param>
/// <param name="connectionEnvelope"> Properties of the Virtual Network connection. See example. </param>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="vnetName"/> or <paramref name="connectionEnvelope"/> is null. </exception>
public virtual WebAppCreateOrUpdateVnetConnectionOperation CreateOrUpdate(string vnetName, VnetInfoResourceData connectionEnvelope, bool waitForCompletion = true, CancellationToken cancellationToken = default)
{
if (vnetName == null)
{
throw new ArgumentNullException(nameof(vnetName));
}
if (connectionEnvelope == null)
{
throw new ArgumentNullException(nameof(connectionEnvelope));
}
using var scope = _clientDiagnostics.CreateScope("SiteVirtualNetworkConnectionCollection.CreateOrUpdate");
scope.Start();
try
{
var response = _webAppsRestClient.CreateOrUpdateVnetConnection(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, vnetName, connectionEnvelope, cancellationToken);
var operation = new WebAppCreateOrUpdateVnetConnectionOperation(Parent, response);
if (waitForCompletion)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/virtualNetworkConnections/{vnetName}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}
/// OperationId: WebApps_CreateOrUpdateVnetConnection
/// <summary> Description for Adds a Virtual Network connection to an app or slot (PUT) or updates the connection properties (PATCH). </summary>
/// <param name="vnetName"> Name of an existing Virtual Network. </param>
/// <param name="connectionEnvelope"> Properties of the Virtual Network connection. See example. </param>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="vnetName"/> or <paramref name="connectionEnvelope"/> is null. </exception>
public async virtual Task<WebAppCreateOrUpdateVnetConnectionOperation> CreateOrUpdateAsync(string vnetName, VnetInfoResourceData connectionEnvelope, bool waitForCompletion = true, CancellationToken cancellationToken = default)
{
if (vnetName == null)
{
throw new ArgumentNullException(nameof(vnetName));
}
if (connectionEnvelope == null)
{
throw new ArgumentNullException(nameof(connectionEnvelope));
}
using var scope = _clientDiagnostics.CreateScope("SiteVirtualNetworkConnectionCollection.CreateOrUpdate");
scope.Start();
try
{
var response = await _webAppsRestClient.CreateOrUpdateVnetConnectionAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, vnetName, connectionEnvelope, cancellationToken).ConfigureAwait(false);
var operation = new WebAppCreateOrUpdateVnetConnectionOperation(Parent, response);
if (waitForCompletion)
await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/virtualNetworkConnections/{vnetName}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}
/// OperationId: WebApps_GetVnetConnection
/// <summary> Description for Gets a virtual network the app (or deployment slot) is connected to by name. </summary>
/// <param name="vnetName"> Name of the virtual network. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="vnetName"/> is null. </exception>
public virtual Response<SiteVirtualNetworkConnection> Get(string vnetName, CancellationToken cancellationToken = default)
{
if (vnetName == null)
{
throw new ArgumentNullException(nameof(vnetName));
}
using var scope = _clientDiagnostics.CreateScope("SiteVirtualNetworkConnectionCollection.Get");
scope.Start();
try
{
var response = _webAppsRestClient.GetVnetConnection(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, vnetName, cancellationToken);
if (response.Value == null)
throw _clientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new SiteVirtualNetworkConnection(Parent, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/virtualNetworkConnections/{vnetName}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}
/// OperationId: WebApps_GetVnetConnection
/// <summary> Description for Gets a virtual network the app (or deployment slot) is connected to by name. </summary>
/// <param name="vnetName"> Name of the virtual network. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="vnetName"/> is null. </exception>
public async virtual Task<Response<SiteVirtualNetworkConnection>> GetAsync(string vnetName, CancellationToken cancellationToken = default)
{
if (vnetName == null)
{
throw new ArgumentNullException(nameof(vnetName));
}
using var scope = _clientDiagnostics.CreateScope("SiteVirtualNetworkConnectionCollection.Get");
scope.Start();
try
{
var response = await _webAppsRestClient.GetVnetConnectionAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, vnetName, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new SiteVirtualNetworkConnection(Parent, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="vnetName"> Name of the virtual network. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="vnetName"/> is null. </exception>
public virtual Response<SiteVirtualNetworkConnection> GetIfExists(string vnetName, CancellationToken cancellationToken = default)
{
if (vnetName == null)
{
throw new ArgumentNullException(nameof(vnetName));
}
using var scope = _clientDiagnostics.CreateScope("SiteVirtualNetworkConnectionCollection.GetIfExists");
scope.Start();
try
{
var response = _webAppsRestClient.GetVnetConnection(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, vnetName, cancellationToken: cancellationToken);
return response.Value == null
? Response.FromValue<SiteVirtualNetworkConnection>(null, response.GetRawResponse())
: Response.FromValue(new SiteVirtualNetworkConnection(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="vnetName"> Name of the virtual network. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="vnetName"/> is null. </exception>
public async virtual Task<Response<SiteVirtualNetworkConnection>> GetIfExistsAsync(string vnetName, CancellationToken cancellationToken = default)
{
if (vnetName == null)
{
throw new ArgumentNullException(nameof(vnetName));
}
using var scope = _clientDiagnostics.CreateScope("SiteVirtualNetworkConnectionCollection.GetIfExistsAsync");
scope.Start();
try
{
var response = await _webAppsRestClient.GetVnetConnectionAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, vnetName, cancellationToken: cancellationToken).ConfigureAwait(false);
return response.Value == null
? Response.FromValue<SiteVirtualNetworkConnection>(null, response.GetRawResponse())
: Response.FromValue(new SiteVirtualNetworkConnection(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="vnetName"> Name of the virtual network. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="vnetName"/> is null. </exception>
public virtual Response<bool> Exists(string vnetName, CancellationToken cancellationToken = default)
{
if (vnetName == null)
{
throw new ArgumentNullException(nameof(vnetName));
}
using var scope = _clientDiagnostics.CreateScope("SiteVirtualNetworkConnectionCollection.Exists");
scope.Start();
try
{
var response = GetIfExists(vnetName, cancellationToken: cancellationToken);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="vnetName"> Name of the virtual network. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="vnetName"/> is null. </exception>
public async virtual Task<Response<bool>> ExistsAsync(string vnetName, CancellationToken cancellationToken = default)
{
if (vnetName == null)
{
throw new ArgumentNullException(nameof(vnetName));
}
using var scope = _clientDiagnostics.CreateScope("SiteVirtualNetworkConnectionCollection.ExistsAsync");
scope.Start();
try
{
var response = await GetIfExistsAsync(vnetName, cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/virtualNetworkConnections
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}
/// OperationId: WebApps_ListVnetConnections
/// <summary> Description for Gets the virtual networks the app (or deployment slot) is connected to. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<IReadOnlyList<SiteVirtualNetworkConnection>> GetAll(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("SiteVirtualNetworkConnectionCollection.GetAll");
scope.Start();
try
{
var response = _webAppsRestClient.ListVnetConnections(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
return Response.FromValue(response.Value.Select(value => new SiteVirtualNetworkConnection(Parent, value)).ToArray() as IReadOnlyList<SiteVirtualNetworkConnection>, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/virtualNetworkConnections
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}
/// OperationId: WebApps_ListVnetConnections
/// <summary> Description for Gets the virtual networks the app (or deployment slot) is connected to. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<Response<IReadOnlyList<SiteVirtualNetworkConnection>>> GetAllAsync(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("SiteVirtualNetworkConnectionCollection.GetAll");
scope.Start();
try
{
var response = await _webAppsRestClient.ListVnetConnectionsAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value.Select(value => new SiteVirtualNetworkConnection(Parent, value)).ToArray() as IReadOnlyList<SiteVirtualNetworkConnection>, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
IEnumerator<SiteVirtualNetworkConnection> IEnumerable<SiteVirtualNetworkConnection>.GetEnumerator()
{
return GetAll().Value.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetAll().Value.GetEnumerator();
}
// Builders.
// public ArmBuilder<Azure.Core.ResourceIdentifier, SiteVirtualNetworkConnection, VnetInfoResourceData> Construct() { }
}
}
| 53.697059 | 234 | 0.653996 | [
"MIT"
] | Manny27nyc/azure-sdk-for-net | sdk/websites/Azure.ResourceManager.AppService/src/Generated/SiteVirtualNetworkConnectionCollection.cs | 18,257 | C# |
using Abp.Dependency;
namespace YiHan.Cms
{
public class AppFolders : IAppFolders, ISingletonDependency
{
public string TempFileDownloadFolder { get; set; }
public string SampleProfileImagesFolder { get; set; }
public string WebLogsFolder { get; set; }
}
} | 22.769231 | 63 | 0.679054 | [
"MIT"
] | Letheloney/YiHanCms | src/YiHan.Cms.Core/AppFolders.cs | 298 | C# |
using ComputeSharp;
namespace adrilight.Shaders
{
/// <summary>
/// Fully procedural 3D animated volume with three evaluations per step (for shading).
/// Ported from <see href="https://www.shadertoy.com/view/3l23Rh"/>.
/// <para>Created by nimitz (twitter: @stormoid).</para>
/// <para>License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.</para>
/// </summary>
[AutoConstructor]
internal readonly partial struct ProteanClouds : IPixelShader<Float4>
{
/// <summary>
/// The current time Hlsl.Since the start of the application.
/// </summary>
public readonly float time;
private static readonly Float3x3 m3 = new Float3x3(0.33338f, 0.56034f, -0.71817f, -0.87887f, 0.32651f, -0.15323f, 0.15162f, 0.69596f, 0.61339f) * 1.93f;
private static Float2x2 Rotate(in float a)
{
float c = Hlsl.Cos(a), s = Hlsl.Sin(a);
return new(c, s, -s, c);
}
private static float LinStep(in float mn, in float mx, in float x)
{
return Hlsl.Clamp((x - mn) / (mx - mn), 0.0f, 1.0f);
}
private static Float2 Disp(float t)
{
return new Float2(Hlsl.Sin(t * 0.22f) * 1.0f, Hlsl.Cos(t * 0.175f) * 1.0f) * 2.0f;
}
private Float2 Map(Float3 p, float prm1, Float2 bsMo)
{
Float3 p2 = p;
p2.XY -= Disp(p.Z).XY;
p.XY = Hlsl.Mul(p.XY, Rotate(Hlsl.Sin(p.Z + time) * (0.1f + prm1 * 0.05f) + time * 0.09f));
float cl = Hlsl.Dot(p2.XY, p2.XY);
float d = 0.0f;
p *= 0.61f;
float z = 1.0f;
float trk = 1.0f;
float dspAmp = 0.1f + prm1 * 0.2f;
for (int i = 0; i < 5; i++)
{
p += Hlsl.Sin(p.ZXY * 0.75f * trk + time * trk * 0.8f) * dspAmp;
d -= Hlsl.Abs(Hlsl.Dot(Hlsl.Cos(p), Hlsl.Sin(p.YZX)) * z);
z *= 0.57f;
trk *= 1.4f;
p = Hlsl.Mul(p, m3);
}
d = Hlsl.Abs(d + prm1 * 3.0f) + prm1 * 0.3f - 2.5f + bsMo.Y;
return new Float2(d + cl * 0.2f + 0.25f, cl);
}
private Float4 Render(Float3 ro, Float3 rd, float time, float prm1, Float2 bsMo)
{
Float4 rez = 0;
float t = 1.5f;
float fogT = 0;
for (int i = 0; i < 130; i++)
{
if (rez.A > 0.99f) break;
Float3 pos = ro + t * rd;
Float2 mpv = Map(pos, prm1, bsMo);
float den = Hlsl.Clamp(mpv.X - 0.3f, 0.0f, 1.0f) * 1.12f;
float dn = Hlsl.Clamp((mpv.X + 2.0f), 0.0f, 3.0f);
Float4 col = 0f;
if (mpv.X > 0.6f)
{
col = new Float4(Hlsl.Sin(new Float3(5.0f, 0.4f, 0.2f) + mpv.Y * 0.1f + Hlsl.Sin(pos.Z * 0.4f) * 0.5f + 1.8f) * 0.5f + 0.5f, 0.08f);
col *= den * den * den;
col.RGB *= LinStep(4.0f, -2.5f, mpv.X) * 2.3f;
float dif = Hlsl.Clamp((den - Map(pos + 0.8f, prm1, bsMo).X) / 9.0f, 0.001f, 1.0f);
dif += Hlsl.Clamp((den - Map(pos + 0.35f, prm1, bsMo).X) / 2.5f, 0.001f, 1.0f);
col.XYZ *= den * (new Float3(0.005f, 0.045f, 0.075f) + 1.5f * new Float3(0.033f, 0.07f, 0.03f) * dif);
}
float fogC = Hlsl.Exp(t * 0.2f - 2.2f);
col += new Float4(0.06f, 0.11f, 0.11f, 0.1f) * Hlsl.Clamp(fogC - fogT, 0.0f, 1.0f);
fogT = fogC;
rez += col * (1.0f - rez.A);
t += Hlsl.Clamp(0.5f - dn * dn * 0.05f, 0.09f, 0.3f);
}
return Hlsl.Clamp(rez, 0.0f, 1.0f);
}
private static float GetSaturation(Float3 c)
{
float mi = Hlsl.Min(Hlsl.Min(c.X, c.Y), c.Z);
float ma = Hlsl.Max(Hlsl.Max(c.X, c.Y), c.Z);
return (ma - mi) / (ma + (float)1e-7);
}
private static Float3 ILerp(in Float3 a, in Float3 b, in float x)
{
Float3 ic = Hlsl.Lerp(a, b, x) + new Float3((float)1e-6, 0.0f, 0.0f);
float sd = Hlsl.Abs(GetSaturation(ic) - Hlsl.Lerp(GetSaturation(a), GetSaturation(b), x));
Float3 dir = Hlsl.Normalize(new Float3(2.0f * ic.X - ic.Y - ic.Z, 2.0f * ic.Y - ic.X - ic.Z, 2.0f * ic.Z - ic.Y - ic.X));
float lgt = Hlsl.Dot(1.0f, ic);
float ff = Hlsl.Dot(dir, Hlsl.Normalize(ic));
ic += 1.5f * dir * sd * ff * lgt;
return Hlsl.Clamp(ic, 0.0f, 1.0f);
}
/// <inheritdoc/>
public Float4 Execute()
{
Float2 q = (Float2)ThreadIds.XY / DispatchSize.XY;
Float2 p = (ThreadIds.XY - 0.5f * (Float2)DispatchSize.XY) / DispatchSize.Y;
Float2 bsMo = -0.5f * (Float2)DispatchSize.XY / DispatchSize.Y;
float scaledTime = time * 3.0f;
Float3 ro = new(0, 0, scaledTime);
ro += new Float3(Hlsl.Sin(time) * 0.5f, Hlsl.Sin(time * 1.0f) * 0.0f, 0);
float dspAmp = 0.85f;
ro.XY += Disp(ro.Z) * dspAmp;
float tgtDst = 3.5f;
Float3 target = Hlsl.Normalize(ro - new Float3(Disp(scaledTime + tgtDst) * dspAmp, scaledTime + tgtDst));
ro.X -= bsMo.X * 2.0f;
Float3 rightdir = Hlsl.Normalize(Hlsl.Cross(target, new Float3(0, 1, 0)));
Float3 updir = Hlsl.Normalize(Hlsl.Cross(rightdir, target));
rightdir = Hlsl.Normalize(Hlsl.Cross(updir, target));
Float3 rd = Hlsl.Normalize((p.X * rightdir + p.Y * updir) * 1.0f - target);
rd.XY = Hlsl.Mul(rd.XY, Rotate(-Disp(scaledTime + 3.5f).X * 0.2f + bsMo.X));
float prm1 = Hlsl.SmoothStep(-0.4f, 0.4f, Hlsl.Sin(time * 0.3f));
Float4 scn = Render(ro, rd, scaledTime, prm1, bsMo);
Float3 col = scn.RGB;
col = ILerp(col.BGR, col.RGB, Hlsl.Clamp(1.0f - prm1, 0.05f, 1.0f));
col = Hlsl.Pow(col, new Float3(0.55f, 0.65f, 0.6f)) * new Float3(1.0f, 0.97f, 0.9f);
col *= Hlsl.Pow(16.0f * q.X * q.Y * (1.0f - q.X) * (1.0f - q.Y), 0.12f) * 0.7f + 0.3f;
return new(col, 1.0f);
}
}
}
| 36.802326 | 160 | 0.487678 | [
"MIT"
] | Kaitoukid93/Ambinity | adrilight/Shaders/ProteanClouds.cs | 6,332 | C# |
using System.Reactive.Subjects;
using akarnokd.reactive_extensions;
using NUnit.Framework;
using Shouldly;
using Xpand.Extensions.Reactive.Transform;
using Xpand.Extensions.Reactive.Utility;
using Xpand.TestsLib.Common;
using Xpand.TestsLib.Common.Attributes;
namespace Xpand.XAF.Modules.Reactive.Tests{
[NonParallelizable]
public class CommonExtensionsTests:CommonTest{
[Test]
[XpandTest]
public void CountSubSequent(){
var subject = new ReplaySubject<int>();
subject.OnNext(0);
subject.OnNext(0);
subject.OnNext(1);
subject.OnNext(0);
var count = subject.CountSubsequent(i => i).SubscribeReplay();
var items = count.Test().Items;
items.Count.ShouldBe(2);
items[0].length.ShouldBe(2);
items[0].item.ShouldBe(0);
items[1].length.ShouldBe(1);
items[1].item.ShouldBe(1);
}
}
} | 27.685714 | 74 | 0.627451 | [
"Apache-2.0"
] | aois-dev/Reactive.XAF | src/Tests/Reactive/CommonExtensionsTests.cs | 971 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XTool
{
public static class ListProvider
{
public static IEnumerable<Display> GetCountLimits()
{
List<Display> list = new List<Display>()
{
{new Display("Twenty-Five",25)},
{new Display("Fifty",50)},
{new Display("One-Hundred",100)},
{new Display("Two-Hundred-Fifty",250)},
{new Display("Five-Hundred",500)},
{new Display("One-Thousand",1000)},
{new Display("100K",100000)},
{new Display("All",Int32.MaxValue)},
};
return list;
}
}
}
| 26.724138 | 59 | 0.523871 | [
"MIT"
] | eXtensoft/xtool | XTool/code/ListProvider.cs | 777 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercicio1
{
class ApelidoNome
{
private string nome, apelido;
public ApelidoNome(string N, string A)
{
nome = N;
apelido = A;
}
}
}
| 17.315789 | 46 | 0.601824 | [
"MIT"
] | EduardaSRBastos/CSharp.NET-Console-2017 | Ficha15/Exercicio1/ApelidoNome.cs | 331 | C# |
using DuinoCoin.Net.Converters;
using DuinoCoin.Net.Models;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace DuinoCoin.Net
{
public class ServerApi
{
public string BaseUrl { get; set; }
private HttpClient _client { get; set; }
private JsonSerializerOptions _options { get; set; }
public ServerApi(string baseUrl = "https://server.duinocoin.com")
{
BaseUrl = baseUrl;
_client = new HttpClient { BaseAddress = new Uri(BaseUrl) };
_options = new JsonSerializerOptions();
_options.Converters.Add(new JsonCustomDateTimeConverter());
}
/// <summary>
/// Get a specific user's details including: Balance, Miners and Transactions.
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
public async Task<UserInfoResult> GetUserInfo(string username)
{
var res = await _client.GetFromJsonAsync<ResponseBase<UserInfoResult>>($"users/{username}", _options);
return res.Result;
}
/// <summary>
/// Get the most recent transactions on the blockchain.
/// </summary>
/// <returns></returns>
public async Task<Dictionary<string, Transaction>> GetTransactions()
{
var res = await _client.GetFromJsonAsync<ResponseBase<Dictionary<string, Transaction>>>($"transactions", _options);
return res.Result;
}
/// <summary>
/// Get a specific transaction from the blockchain for a specific hash value.
/// </summary>
/// <param name="hash"></param>
/// <returns></returns>
public async Task<Transaction> GetTransaction(string hash)
{
var res = await _client.GetFromJsonAsync<ResponseBase<Transaction>>($"transactions/{hash}", _options);
return res.Result;
}
/// <summary>
/// Get a dictionary of usernames and their corresponding balances.
/// </summary>
/// <returns></returns>
public async Task<Dictionary<string, decimal>> GetBalances()
{
var res = await _client.GetFromJsonAsync<ResponseBase<Dictionary<string, decimal>>>($"balances");
return res.Result;
}
/// <summary>
/// Get the current balance for a specific user.
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
public async Task<UserBalance> GetBalance(string username)
{
var res = await _client.GetFromJsonAsync<ResponseBase<UserBalance>>($"balances/{username}");
return res.Result;
}
/// <summary>
/// Get a dictionary of users and their corresponding miners.
/// </summary>
/// <returns></returns>
public async Task<Dictionary<string, List<Miner>>> GetMiners()
{
var res = await _client.GetFromJsonAsync<ResponseBase<Dictionary<string, List<Miner>>>>("miners");
return res.Result;
}
}
}
| 35.791209 | 127 | 0.59871 | [
"MIT"
] | Augmensis/DuinoCoin.Net | DuinoCoin.Net/ServerApi.cs | 3,259 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu( fileName = "New Conversation", menuName = "Dialogue/Conversation")]
public class Conversation : ScriptableObject {
public List<Sentence> sentences;
}
[System.Serializable]
public struct Sentence{
public string characterName;
public Sprite characterImage;
[TextAreaAttribute]
public string text;
public bool appearRight;
public bool hasChoice;
public List<Choice> choices;
}
| 15.903226 | 85 | 0.778905 | [
"MIT"
] | DrikoArgon/Into-The-Wild | Assets/Scripts/UI/Dialogue/Conversation.cs | 495 | C# |
namespace IFramework.EventStore
{
public interface IEventSerializer
{
/// <summary>
/// Serialize the key or value of a <see cref="T:Confluent.Kafka.Message`2" />
/// instance.
/// </summary>
/// <param name="data">The value to serialize.</param>
/// <returns>The serialized value.</returns>
byte[] Serialize(object data);
}
}
| 28.857143 | 90 | 0.566832 | [
"MIT"
] | IvanZheng/IFramework | Src/iFramework/EventStore/IEventSerializer.cs | 406 | C# |
using System;
using ArenaLS.Model;
using SkiaSharp;
namespace ArenaLS.UI.Views.Combat.Renderers
{
class HUDRenderer
{
CharacterStyleInfo StyleInfo;
TilesetLoader StatusIconLoader;
public HUDRenderer (CharacterStyleInfo styleInfo)
{
StyleInfo = styleInfo;
StatusIconLoader = new TilesetLoader ("data/tf_icon_32.png", 32);
}
public void Render (SKCanvas canvas, Character c, int x, int y, long frame)
{
DrawHUD (canvas, c, x, y);
DrawCastbar (canvas, x, y, frame);
}
void DrawHUD (SKCanvas canvas, Character c, int x, int y)
{
const int BackgroundOffsetX = 5;
const int BackgroundOffsetY = 15;
const int HUDWidth = 85;
const int HUDHeight = 60;
const int LineHeight = 18;
const int StatusIconHeightGap = 4;
const int StatusIconWidthGap = 20;
canvas.DrawRect (SKRect.Create (x + StyleInfo.TextXOffset - BackgroundOffsetX, y + StyleInfo.TextYOffset - BackgroundOffsetY, HUDWidth, HUDHeight), Styles.TextBackground);
canvas.DrawText (c.Name, new SKPoint (x + StyleInfo.TextXOffset, y + StyleInfo.TextYOffset), Styles.TextPaint);
canvas.DrawText ($"HP {c.Health.Current}/{c.Health.Maximum}", new SKPoint (x + StyleInfo.TextXOffset, LineHeight + y + StyleInfo.TextYOffset), Styles.TextPaint);
// TestData - Status Icons
int iconOffset = 0;
foreach (int i in new int [] { 33, 42, 148, 36 })
{
var bitmapRect = SKRect.Create (x + StyleInfo.TextXOffset + (iconOffset * StatusIconWidthGap), LineHeight + StatusIconHeightGap + y + StyleInfo.TextYOffset, 16, 16);
canvas.DrawBitmap (StatusIconLoader.Tileset, StatusIconLoader.GetRect (i), bitmapRect, Styles.AntialiasPaint);
iconOffset++;
}
}
readonly SKPaint CastBarOutlinePaint = new SKPaint () { StrokeWidth = 2, Color = new SKColor (238, 238, 238), IsStroke = true };
readonly SKPaint CastBarInsidePaint = new SKPaint () { StrokeWidth = 2, Color = new SKColor (44, 82, 178) };
void DrawCastbar (SKCanvas canvas, int x, int y, long frame)
{
const int TinyTextBackgroundOffsetX = 1;
const int TinyTextBackgroundOffsetY = 8;
const int CastbarHeight = 8;
const int CastbarLength = 60;
const int CastbarTextOffsetX = -12;
const int CastbarTextOffsetY = 5;
// TestData - CastBar
int percentCast = (int)((frame * 2) % 100);
var castBarOutlineRect = SKRect.Create (x + StyleInfo.CastXOffset, y + StyleInfo.CastYOffset, CastbarLength, CastbarHeight);
canvas.DrawRect (castBarOutlineRect, CastBarOutlinePaint);
int filledLength = (int)Math.Round (((CastbarLength - 2.0) * percentCast) / 100);
var castBarFilledRect = SKRect.Create (x + StyleInfo.CastXOffset + 1, y + StyleInfo.CastYOffset + 1, filledLength, CastbarHeight - 2);
canvas.DrawRect (castBarFilledRect, CastBarInsidePaint);
var castBarTextBackgroundRect = SKRect.Create (x + StyleInfo.CastXOffset - TinyTextBackgroundOffsetX - CastbarTextOffsetX, y + StyleInfo.CastYOffset - CastbarTextOffsetY - 1 - TinyTextBackgroundOffsetY, 42, 12);
canvas.DrawRect (castBarTextBackgroundRect, Styles.TextBackground);
var castBarTextRect = new SKPoint (x + StyleInfo.CastXOffset - CastbarTextOffsetX, y + StyleInfo.CastYOffset - CastbarTextOffsetY);
canvas.DrawText ("Fire Strike", castBarTextRect, Styles.SmallTextPaint);
}
}
}
| 43.64 | 214 | 0.729911 | [
"MIT"
] | chamons/ArenaLS | src/ArenaLS.UI/Views/Combat/Renderers/HUDRenderer.cs | 3,275 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SageFrame.Web.Utilities;
namespace AspxCommerce.Core
{
public class AspxInvoiceMgntProvider
{
public AspxInvoiceMgntProvider()
{
}
public static List<InvoiceDetailsInfo> GetInvoiceDetailsList(int offset, System.Nullable<int> limit, InvoiceBasicInfo invoiceObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<KeyValuePair<string, object>> parameter = CommonParmBuilder.GetParamSPUC(aspxCommonObj);
parameter.Add(new KeyValuePair<string, object>("@offset", offset));
parameter.Add(new KeyValuePair<string, object>("@limit", limit));
parameter.Add(new KeyValuePair<string, object>("@InvoiceNumber", invoiceObj.InvoiceNumber));
parameter.Add(new KeyValuePair<string, object>("@BillToName", invoiceObj.BillToName));
parameter.Add(new KeyValuePair<string, object>("@OrderStatusID", invoiceObj.OrderStatusName));
SQLHandler sqlH = new SQLHandler();
List<InvoiceDetailsInfo> lstInvoiceDetail = sqlH.ExecuteAsList<InvoiceDetailsInfo>("usp_Aspx_GetInvoiceDetails", parameter);
return lstInvoiceDetail;
}
catch (Exception e)
{
throw e;
}
}
public static List<InvoiceDetailByorderIDInfo> GetInvoiceDetailsByOrderID(int orderID, AspxCommonInfo aspxCommonObj)
{
try
{
List<KeyValuePair<string, object>> parameter = CommonParmBuilder.GetParamSPUC(aspxCommonObj);
parameter.Add(new KeyValuePair<string, object>("@OrderID", orderID));
SQLHandler sqlh = new SQLHandler();
List<InvoiceDetailByorderIDInfo> info = sqlh.ExecuteAsList<InvoiceDetailByorderIDInfo>("usp_Aspx_GetInvoiceDetailsByOrderID", parameter);
return info;
}
catch (Exception e)
{
throw e;
}
}
}
}
| 40.339623 | 167 | 0.618803 | [
"MIT"
] | AspxCommerce/AspxCommerce2.7 | AspxCommerce.Core/AspxServices/Provider/AspxInvoiceMgntProvider.cs | 2,140 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.XPath;
// Disable warning for missing XML comments
#pragma warning disable CS1591
namespace LoxSmoke.DocXml
{
/// <summary>
/// Helper class that reads XML documentation generated by C# compiler from code comments.
/// </summary>
public class DocXmlReader
{
/// <summary>
/// XML navigator object in case of only one XML file.
/// Null if more than one XML file and assemblyNavigators dictionary is in use.
/// </summary>
protected readonly XPathNavigator navigator;
/// <summary>
/// Dictionary of XML navigators for multiple assemblies.
/// </summary>
protected readonly Dictionary<Assembly, XPathNavigator> assemblyNavigators;
/// <summary>
/// Function that returns path to XML documentation file for specified assembly.
/// </summary>
protected readonly Func<Assembly, string> assemblyXmlPathFunction;
/// <summary>
/// Default value is true.
/// When it is set to true DocXmlReader removes leading spaces and an empty
/// lines at the end of the comment.
/// By default XML comments are indented for human readability but it adds
/// leading spaces that are not present in source code.
/// For example here is compiler generated XML documentation with '-'
/// showing spaces for readability.
/// ----<summary>
/// ----Text
/// ----</summary>
/// With UnIndentText set to true returned summary text is just "Text"
/// With UnIndentText set to false returned summary text contains leading spaces
/// and the trailing empty line "\n----Text\n----"
/// </summary>
public bool UnIndentText { get; set; } = true;
/// <summary>
/// Create reader and use specified XML documentation file
/// </summary>
/// <param name="fileName">The name of the XML documentation file.</param>
/// <param name="unindentText">True if extra leading spaces should be removed from comments</param>
public DocXmlReader(string fileName, bool unindentText = true)
{
var document = new XPathDocument(fileName);
navigator = document.CreateNavigator();
UnIndentText = unindentText;
}
/// <summary>
/// Create reader for specified xpath document.
/// </summary>
/// <param name="xPathDocument">XML documentation</param>
/// <param name="unindentText">True if extra leading spaces should be removed from comments</param>
public DocXmlReader(XPathDocument xPathDocument, bool unindentText = true)
{
var document = xPathDocument ?? throw new ArgumentException(nameof(xPathDocument));
navigator = document.CreateNavigator();
UnIndentText = unindentText;
}
/// <summary>
/// Open XML documentation files based on assemblies of types. Comment file names
/// are generated based on assembly names by replacing assembly location with .xml.
/// </summary>
/// <param name="assemblyXmlPathFunction">Function that returns path to the assembly XML comment file.
/// If function is null then comments file is assumed to have the same file name as assembly.
/// If function returns null or if comments file does not exist then all comments for types from that
/// assembly would remain empty. </param>
/// <param name="unindentText">True if extra leading spaces should be removed from comments</param>
public DocXmlReader(Func<Assembly, string> assemblyXmlPathFunction = null, bool unindentText = true)
{
assemblyNavigators = new Dictionary<Assembly, XPathNavigator>();
UnIndentText = unindentText;
this.assemblyXmlPathFunction = assemblyXmlPathFunction;
}
/// <summary>
/// Open XML documentation files based on assemblies of types. Comment file names
/// are generated based on assembly names by replacing assembly location with .xml.
/// </summary>
/// <param name="assemblies">The list of assemblies for XML documentation</param>
/// <param name="assemblyXmlPathFunction">Function that returns path to the assembly XML comment file.
/// If function is null then comments file is assumed to have the same file name as assembly.
/// If function returns null or if comments file does not exist then all comments for types from that
/// assembly would remain empty. </param>
/// <param name="unindentText">True if extra leading spaces should be removed from comments</param>
public DocXmlReader(IEnumerable<Assembly> assemblies,
Func<Assembly, string> assemblyXmlPathFunction = null, bool unindentText = true)
{
assemblyNavigators = new Dictionary<Assembly, XPathNavigator>();
UnIndentText = unindentText;
this.assemblyXmlPathFunction = assemblyXmlPathFunction;
foreach (var assembly in assemblies)
{
GetNavigatorForAssembly(assembly);
}
}
#region Public methods
/// <summary>
/// Returns comments for the method or constructor. Returns empty comments object
/// if comments for method are missing in XML documentation file.
/// Returned comments tags:
/// Summary, Remarks, Parameters (if present), Responses (if present), Returns
/// </summary>
/// <returns></returns>
public MethodComments GetMethodComments(MethodBase methodInfo)
{
return GetMethodComments(methodInfo, false);
}
/// <summary>
/// Returns comments for the class method. May return null object is comments for method
/// are missing in XML documentation file.
/// Returned comments tags:
/// Summary, Remarks, Parameters (if present), Responses (if present), Returns
/// </summary>
/// <param name="methodInfo"></param>
/// <param name="nullIfNoComment">Return null if comment for method is not available</param>
/// <returns></returns>
public MethodComments GetMethodComments(MethodBase methodInfo, bool nullIfNoComment)
{
var methodNode = GetXmlMemberNode(methodInfo.MethodId(), methodInfo?.ReflectedType);
if (nullIfNoComment && methodNode == null) return null;
var comments = new MethodComments();
return GetComments(methodInfo, comments, methodNode);
}
protected MethodComments GetComments(MethodBase methodInfo, MethodComments comments, XPathNavigator node)
{
if (node == null) return comments;
GetCommonComments(comments, node);
comments.Parameters = GetParametersComments(node);
comments.TypeParameters = GetNamedComments(node, TypeParamXPath, NameAttribute);
comments.Returns = GetReturnsComment(node);
comments.Responses = GetNamedComments(node, ResponsesXPath, CodeAttribute);
comments = ResolveInheritdocComments(comments, methodInfo);
return comments;
}
/// <summary>
/// Return Summary comments for specified type.
/// For Delegate types Parameters field may be returned as well.
/// </summary>
/// <param name="type"></param>
/// <returns>TypeComment</returns>
public TypeComments GetTypeComments(Type type)
{
var comments = new TypeComments();
var node = GetXmlMemberNode(type.TypeId(), type);
return GetComments(type, comments, node);
}
protected TypeComments GetComments(Type type, TypeComments comments, XPathNavigator node)
{
if (node == null) return comments;
if (type.IsSubclassOf(typeof(Delegate)))
{
comments.Parameters = GetParametersComments(node);
}
GetCommonComments(comments, node);
comments = ResolveInheritdocComments(comments, type);
return comments;
}
/// <summary>
/// Returns Summary comment for specified class member.
/// </summary>
/// <param name="memberInfo"></param>
/// <returns></returns>
public string GetMemberComment(MemberInfo memberInfo)
{
return GetSummaryComment(GetXmlMemberNode(memberInfo.MemberId(), memberInfo?.ReflectedType));
}
/// <summary>
/// Returns comments for specified class member.
/// </summary>
/// <param name="memberInfo"></param>
/// <returns></returns>
public CommonComments GetMemberComments(MemberInfo memberInfo)
{
var comments = new CommonComments();
var node = GetXmlMemberNode(memberInfo.MemberId(), memberInfo?.ReflectedType);
return GetComments(memberInfo, comments, node);
}
protected CommonComments GetComments(MemberInfo memberInfo, CommonComments comments, XPathNavigator node)
{
if (node == null) return comments;
GetCommonComments(comments, node);
comments = ResolveInheritdocComments(comments, memberInfo);
return comments;
}
/// <summary>
/// Get enum type description and comments for enum values. If <paramref name="fillValues"/>
/// is false and no comments exist for any value then ValueComments list is empty.
/// </summary>
/// <param name="enumType">For non-enum types ArgumentException would be throws</param>
/// <param name="fillValues">True if ValueComments list should be filled even if
/// non of the enum values have any summary comments</param>
/// <returns>EnumComment</returns>
public EnumComments GetEnumComments(Type enumType, bool fillValues = false)
{
if (!enumType.IsEnum) throw new ArgumentException(nameof(enumType));
var comments = new EnumComments();
var typeNode = GetXmlMemberNode(enumType.TypeId(), enumType?.ReflectedType);
if (typeNode != null)
{
GetCommonComments(comments, typeNode);
};
bool valueCommentsExist = false;
foreach (var enumName in enumType.GetEnumNames())
{
var valueNode = GetXmlMemberNode(enumType.EnumValueId(enumName), enumType?.ReflectedType);
valueCommentsExist |= (valueNode != null);
var valueComment = new EnumValueComment()
{
Name = enumName,
Value = (int) Enum.Parse(enumType, enumName)
};
comments.ValueComments.Add(valueComment);
GetCommonComments(valueComment, valueNode);
}
if (!valueCommentsExist && !fillValues) comments.ValueComments.Clear();
return comments;
}
#endregion
#region XML items and atribute names
// XPath strings and XML attribute names
private const string MemberXPath = "/doc/members/member[@name='{0}']";
private const string SummaryXPath = "summary";
private const string RemarksXPath = "remarks";
private const string ExampleXPath = "example";
private const string ParamXPath = "param";
private const string TypeParamXPath = "typeparam";
private const string ResponsesXPath = "response";
private const string ReturnsXPath = "returns";
private const string InheritdocXPath = "inheritdoc";
// XML attribute names
private const string NameAttribute = "name";
private const string CodeAttribute = "code";
private const string CrefAttribute = "cref";
#endregion
#region XML helper functions
private void GetCommonComments(CommonComments comments, XPathNavigator rootNode)
{
comments.Summary = GetSummaryComment(rootNode);
comments.Remarks = GetRemarksComment(rootNode);
comments.Example = GetExampleComment(rootNode);
comments.Inheritdoc = GetInheritdocTag(rootNode);
}
private XPathNavigator GetXmlMemberNode(string name, Type typeForAssembly, bool searchAllCurrentFiles = false)
{
if (navigator != null)
{
return navigator.SelectSingleNode(string.Format(MemberXPath, name));
}
var node = GetXmlMemberNodeFromDictionary(name, typeForAssembly);
if (node != null ||
!searchAllCurrentFiles ||
assemblyNavigators.Count <= 1 && typeForAssembly != null) return node;
foreach (var docNavigator in assemblyNavigators.Values)
{
node = docNavigator.SelectSingleNode(string.Format(MemberXPath, name));
if (node != null) break;
}
return node;
}
private XPathNavigator GetXmlMemberNodeFromDictionary(string name, Type typeForAssembly)
{
var typeNavigator = GetNavigatorForAssembly(typeForAssembly?.Assembly);
return typeNavigator?.SelectSingleNode(string.Format(MemberXPath, name));
}
private XPathNavigator GetNavigatorForAssembly(Assembly assembly)
{
if (assembly == null) return null;
if (assemblyNavigators.TryGetValue(assembly, out var typeNavigator))
{
return typeNavigator;
}
var commentFileName = assemblyXmlPathFunction == null
? Path.ChangeExtension(assembly.Location, ".xml")
: assemblyXmlPathFunction(assembly);
if (commentFileName == null || !File.Exists(commentFileName))
{
assemblyNavigators.Add(assembly, null);
return null;
}
var document = new XPathDocument(commentFileName);
var docNavigator = document.CreateNavigator();
assemblyNavigators.Add(assembly, docNavigator);
return docNavigator;
}
private string GetXmlText(XPathNavigator node)
{
var innerText = node?.InnerXml ?? "";
if (!UnIndentText || string.IsNullOrEmpty(innerText)) return innerText;
var outerText = node?.OuterXml ?? "";
var indentText = FindIndent(outerText);
if (string.IsNullOrEmpty(indentText)) return innerText;
return innerText.Replace(indentText, indentText[0].ToString()).Trim('\r', '\n');
}
private string FindIndent(string outerText)
{
if (string.IsNullOrEmpty(outerText)) return "";
var end = outerText.LastIndexOf("</");
if (end < 0) return "";
var start = end - 1;
for (; start >= 0 && outerText[start] != '\r' && outerText[start] != '\n'; start--) ;
if (start < 0 || end <= start) return "";
return outerText.Substring(start, end - start);
}
private string GetSummaryComment(XPathNavigator rootNode)
{
return GetXmlText(rootNode?.SelectSingleNode(SummaryXPath));
}
private string GetRemarksComment(XPathNavigator rootNode)
{
return GetXmlText(rootNode?.SelectSingleNode(RemarksXPath));
}
private string GetExampleComment(XPathNavigator rootNode)
{
return GetXmlText(rootNode?.SelectSingleNode(ExampleXPath));
}
private string GetReturnsComment(XPathNavigator methodNode)
{
var responseNodes = methodNode?.Select(ReturnsXPath);
if (responseNodes?.MoveNext() == true)
return GetXmlText(responseNodes.Current);
return "";
}
private List<(string Name, string Text)> GetParametersComments(XPathNavigator rootNode)
{
return GetNamedComments(rootNode, ParamXPath, NameAttribute);
}
private List<(string Name, string Text)> GetNamedComments(XPathNavigator rootNode, string path, string attributeName)
{
var list = new List<(string Name, string Text)>();
var childNodes = rootNode?.Select(path);
if (childNodes == null) return list;
while (childNodes.MoveNext())
{
var code = childNodes.Current.GetAttribute(attributeName, "");
list.Add((code, GetXmlText(childNodes.Current)));
}
return list;
}
private InheritdocTag GetInheritdocTag(XPathNavigator rootNode)
{
if (rootNode == null) return null;
var inheritdoc = GetNamedComments(rootNode, InheritdocXPath, CrefAttribute);
if (inheritdoc.Count == 0) return null;
return new InheritdocTag() {Cref = inheritdoc.First().Item1};
}
private bool NeedsResolving(CommonComments comments)
{
return comments?.Inheritdoc != null &&
string.IsNullOrEmpty(comments.Summary) &&
string.IsNullOrEmpty(comments.Remarks) &&
string.IsNullOrEmpty(comments.Example);
}
private bool GetCrefComments(string cref, Type typeForAssembly, CommonComments comments,
Action<XPathNavigator> getCommentAction)
{
if (string.IsNullOrEmpty(cref)) return false;
var typeNode = GetXmlMemberNode(cref, typeForAssembly, true);
var inheritdoc = comments.Inheritdoc;
comments.Inheritdoc = null;
getCommentAction(typeNode);
comments.Inheritdoc = inheritdoc;
return true;
}
private MethodComments ResolveInheritdocComments(MethodComments comments, MethodBase methodInfo)
{
if (!NeedsResolving(comments) ||
comments?.Parameters?.Count > 0 ||
!string.IsNullOrEmpty(comments?.Returns) ||
comments?.Responses?.Count > 0 ||
comments?.TypeParameters?.Count > 0) return comments;
// If an explicit cref attribute is specified, the documentation from
// the specified namespace/type/member is inherited.
if (GetCrefComments(comments.Inheritdoc.Cref, methodInfo.ReflectedType, comments,
(node) => GetComments(methodInfo, comments, node))) return comments;
// For constructors:
// - Search backwards up the type inheritance chain for a constructor
// with a matching signature.
// - If a match is found, its documentation is inherited.
if (methodInfo.IsConstructor)
{
var baseClass = methodInfo.ReflectedType.BaseType;
var constructorSignature = methodInfo.GetParameters()
.Select(p => p.ParameterType).ToArray();
while (baseClass != null)
{
var baseConstructor = baseClass.GetConstructor(
BindingFlags.Public| BindingFlags.NonPublic| BindingFlags.Instance,
null, CallingConventions.Any, constructorSignature, null);
if (baseConstructor != null)
{
var newComments = GetMethodComments(baseConstructor);
if (newComments == null) return comments;
newComments.Inheritdoc = comments.Inheritdoc;
return newComments;
}
baseClass = baseClass.BaseType;
}
return comments;
}
// For virtual members and interface implementations:
// - If the member is an override, documentation is inherited from the
// member it overrides.
// - If the member is part of an interface, documentation is inherited
// from the interface member being implemented.
var interfaceDeclaration = methodInfo.ReflectedType
.GetTypeInfo()
.ImplementedInterfaces
.Select(ii => methodInfo.ReflectedType.GetInterfaceMap(ii))
.SelectMany(map => Enumerable.Range(0, map.TargetMethods.Length)
.Where(n => map.TargetMethods[n] == methodInfo)
.Select(n => map.InterfaceMethods[n]))
.FirstOrDefault();
if (interfaceDeclaration != null)
{
var newComments = GetMethodComments(interfaceDeclaration);
if (newComments == null) return comments;
newComments.Inheritdoc = comments.Inheritdoc;
return newComments;
}
if (methodInfo.IsVirtual)
{
var baseMethod = (methodInfo as MethodInfo)?.GetBaseDefinition();
if (baseMethod != null)
{
var newComments = GetMethodComments(baseMethod);
if (newComments == null) return comments;
newComments.Inheritdoc = comments.Inheritdoc;
return newComments;
}
return comments;
}
return comments;
}
private TypeComments ResolveInheritdocComments(TypeComments comments, Type type)
{
if (!NeedsResolving(comments) ||
comments?.Parameters?.Count > 0) return comments;
// If an explicit cref attribute is specified, the documentation from
// the specified namespace/type/member is inherited.
if (GetCrefComments(comments.Inheritdoc.Cref, type, comments,
(node) => GetComments(type, comments, node))) return comments;
// For types and interfaces:
// - Inherit documentation from all base classes working backwards up
// the inheritance chain.
// - Inherit documentation from all interface implementations (if any)
// working through them in the order listed in the reflection information file (usually alphabetically).
if (type.BaseType != null && type.BaseType != typeof(object))
{
var newComments = GetTypeComments(type.BaseType);
if (newComments != null)
{
newComments.Parameters = comments.Parameters;
newComments.Inheritdoc = comments.Inheritdoc;
return newComments;
}
}
var interfaces = type.GetInterfaces();
if (interfaces?.Length > 0)
{
foreach (var intf in interfaces.OrderBy(i => i.FullName))
{
var newComments = GetTypeComments(intf);
if (newComments != null)
{
newComments.Parameters = comments.Parameters;
newComments.Inheritdoc = comments.Inheritdoc;
return newComments;
}
}
}
return comments;
}
private CommonComments ResolveInheritdocComments(CommonComments comments, MemberInfo memberInfo)
{
if (!NeedsResolving(comments)) return comments;
// If an explicit cref attribute is specified, the documentation from
// the specified namespace/type/member is inherited.
GetCrefComments(comments.Inheritdoc.Cref, memberInfo.DeclaringType, comments,
(node) => GetComments(memberInfo, comments, node));
return comments;
}
#endregion
}
}
| 44.932727 | 126 | 0.587019 | [
"MIT"
] | egil/DocXml | src/DocXml/DocXmlReader.cs | 24,715 | C# |
using System.Net.NetworkInformation;
namespace Thinktecture.Net.NetworkInformation
{
/// <summary>
/// Provides information about network interfaces that support Internet Protocol version 4 (IPv4) or Internet Protocol version 6 (IPv6).
/// </summary>
// ReSharper disable once InconsistentNaming
public interface IIPInterfaceProperties : IAbstraction<IPInterfaceProperties>
{
/// <summary>
/// Gets the anycast IP addresses assigned to this interface.
/// </summary>
IIPAddressInformationCollection AnycastAddresses { get; }
/// <summary>
/// Gets the addresses of Dynamic Host Configuration Protocol (DHCP) servers for this interface.
/// </summary>
IIPAddressCollection DhcpServerAddresses { get; }
/// <summary>
/// Gets the addresses of Domain Name System (DNS) servers for this interface.
/// </summary>
IIPAddressCollection DnsAddresses { get; }
/// <summary>
/// Gets the Domain Name System (DNS) suffix associated with this interface.
/// </summary>
string DnsSuffix { get; }
/// <summary>
/// Gets the IPv4 network gateway addresses for this interface.
/// </summary>
IGatewayIPAddressInformationCollection GatewayAddresses { get; }
/// <summary>
/// Gets a Boolean value that indicates whether NetBt is configured to use DNS name resolution on this interface.
/// </summary>
bool IsDnsEnabled { get; }
/// <summary>
/// Gets a Boolean value that indicates whether this interface is configured to automatically register its IP address information with the Domain Name System (DNS).
/// </summary>
bool IsDynamicDnsEnabled { get; }
/// <summary>
/// Gets the multicast addresses assigned to this interface.
/// </summary>
IMulticastIPAddressInformationCollection MulticastAddresses { get; }
/// <summary>
/// Gets the unicast addresses assigned to this interface.
/// </summary>
IUnicastIPAddressInformationCollection UnicastAddresses { get; }
/// <summary>
/// Gets the addresses of Windows Internet Name Service (WINS) servers.
/// </summary>
IIPAddressCollection WinsServersAddresses { get; }
/// <summary>
/// Provides Internet Protocol version 4 (IPv4) configuration data for this network interface.
/// </summary>
/// <returns>An IPv4InterfaceProperties object that contains IPv4 configuration data, or null if no data is available for the interface.</returns>
IIPv4InterfaceProperties GetIPv4Properties();
/// <summary>
/// Provides Internet Protocol version 6 (IPv6) configuration data for this network interface.
/// </summary>
/// <returns>An IPv6InterfaceProperties object that contains IPv6 configuration data.</returns>
IIPv6InterfaceProperties GetIPv6Properties();
}
}
| 38.09589 | 167 | 0.711974 | [
"BSD-3-Clause"
] | PawelGerr/Thinktecture.Abstractions | src/Thinktecture.Net.NetworkInformation.Abstractions/Net/NetworkInformation/IIPInterfaceProperties.cs | 2,781 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// 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("AutoNM C#")]
[assembly: AssemblyDescription("AutoNM i ny og forbedret utgave")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Praetox Technologies")]
[assembly: AssemblyProduct("AutoNM C#")]
[assembly: AssemblyCopyright("Praetox Technologies 2007")]
[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("2a9abb25-0757-40db-b43b-0c59dadbda77")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.1.2")]
[assembly: AssemblyFileVersion("1.0.1.2")]
[assembly: NeutralResourcesLanguageAttribute("nb-NO")]
| 38.972222 | 85 | 0.739843 | [
"Unlicense"
] | Praetox/NordicMafia | AutoNM_C#/AutoNM/Properties/AssemblyInfo.cs | 1,405 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RadioLog.Common
{
public class BooleanAveragingBuffer
{
private bool[] mBuffer;
private int mBufferPointer;
public BooleanAveragingBuffer(int length)
{
mBuffer = new bool[length];
//Preload the array with false values
Common.ArrayUtils.Fill(mBuffer, false);
}
public bool get(bool newValue)
{
//Fetch current boolean value
bool retVal = mBuffer[mBufferPointer];
//Load the new value into the buffer
put(newValue);
return retVal;
}
/**
* Loads the newValue into this buffer and adjusts the buffer pointer
* to prepare for the next get/put cycle
*/
private void put(bool newValue)
{
//Store the new value to the buffer
mBuffer[mBufferPointer] = newValue;
//Increment the buffer pointer
mBufferPointer++;
//Wrap the buffer pointer around to 0 when necessary
if (mBufferPointer >= mBuffer.Length)
{
mBufferPointer = 0;
}
}
/**
* Loads the newValue into the buffer, calculates the average
* and returns that average from this method
*
* This effectively performs low-pass filtering
*/
public bool getAverage(bool newValue)
{
//Load the new value into the buffer
put(newValue);
int trueCount = 0;
for (int x = 0; x < mBuffer.Length; x++)
{
if (mBuffer[x])
{
trueCount++;
}
}
/**
* If the number of true values in the buffer is
* more than half, return true, otherwise, false
*/
if (trueCount > (int)(mBuffer.Length / 2))
{
return true;
}
else
{
return false;
}
}
}
}
| 24.875 | 77 | 0.49566 | [
"MIT"
] | JoeGilkey/RadioLog | RadioLog/RadioLog.Common/BooleanAveragingBuffer.cs | 2,191 | C# |
using System.Collections;
using System.Collections.Generic;
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
using NetOffice.CollectionsGeneric;
namespace NetOffice.ExcelApi
{
/// <summary>
/// DispatchInterface SheetViews
/// SupportByVersion Excel, 12,14,15,16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff836204.aspx </remarks>
[SupportByVersion("Excel", 12,14,15,16)]
[EntityType(EntityType.IsDispatchInterface), Enumerator(Enumerator.Reference, EnumeratorInvoke.Method, "Excel", 12, 14, 15, 16), HasIndexProperty(IndexInvoke.Property, "_Default")]
[TypeId("0002448C-0000-0000-C000-000000000046")]
public interface SheetViews : ICOMObject, IEnumerableProvider<object>
{
#region Properties
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff838179.aspx </remarks>
[SupportByVersion("Excel", 12,14,15,16)]
NetOffice.ExcelApi.Application Application { get; }
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff195051.aspx </remarks>
[SupportByVersion("Excel", 12,14,15,16)]
NetOffice.ExcelApi.Enums.XlCreator Creator { get; }
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff839612.aspx </remarks>
[SupportByVersion("Excel", 12,14,15,16), ProxyResult]
object Parent { get; }
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff821833.aspx </remarks>
[SupportByVersion("Excel", 12,14,15,16)]
Int32 Count { get; }
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
/// <param name="index">object index</param>
[SupportByVersion("Excel", 12,14,15,16), ProxyResult]
[NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item"), IndexProperty]
object this[object index] { get; }
#endregion
#region IEnumerable<object>
/// <summary>
/// SupportByVersion Excel, 12,14,15,16
/// </summary>
[SupportByVersion("Excel", 12, 14, 15, 16)]
new IEnumerator<object> GetEnumerator();
#endregion
}
}
| 32.56962 | 181 | 0.678197 | [
"MIT"
] | igoreksiz/NetOffice | Source/Excel/DispatchInterfaces/SheetViews.cs | 2,575 | C# |
namespace Shop
{
partial class CustomersForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CustomersForm));
this.lbBack = new System.Windows.Forms.Label();
this.groupCustomer = new System.Windows.Forms.GroupBox();
this.tbEmail = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.btnAddCustomer = new System.Windows.Forms.Button();
this.tbName = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.Id = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.FullName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Email = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.btnDelete = new System.Windows.Forms.Button();
this.btnUser = new System.Windows.Forms.Button();
this.btnBack = new System.Windows.Forms.PictureBox();
this.btnExit = new System.Windows.Forms.PictureBox();
this.groupCustomer.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.btnBack)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.btnExit)).BeginInit();
this.SuspendLayout();
//
// lbBack
//
this.lbBack.AutoSize = true;
this.lbBack.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbBack.Location = new System.Drawing.Point(57, 25);
this.lbBack.Name = "lbBack";
this.lbBack.Size = new System.Drawing.Size(42, 18);
this.lbBack.TabIndex = 28;
this.lbBack.Text = "Back";
//
// groupCustomer
//
this.groupCustomer.Controls.Add(this.tbEmail);
this.groupCustomer.Controls.Add(this.label6);
this.groupCustomer.Controls.Add(this.btnAddCustomer);
this.groupCustomer.Controls.Add(this.tbName);
this.groupCustomer.Controls.Add(this.label1);
this.groupCustomer.Font = new System.Drawing.Font("Calibri", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.groupCustomer.Location = new System.Drawing.Point(50, 99);
this.groupCustomer.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupCustomer.Name = "groupCustomer";
this.groupCustomer.Padding = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupCustomer.Size = new System.Drawing.Size(273, 258);
this.groupCustomer.TabIndex = 24;
this.groupCustomer.TabStop = false;
this.groupCustomer.Text = "Customer";
//
// tbEmail
//
this.tbEmail.Location = new System.Drawing.Point(19, 136);
this.tbEmail.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.tbEmail.Name = "tbEmail";
this.tbEmail.Size = new System.Drawing.Size(237, 26);
this.tbEmail.TabIndex = 6;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Font = new System.Drawing.Font("Calibri", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label6.Location = new System.Drawing.Point(19, 116);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(42, 18);
this.label6.TabIndex = 5;
this.label6.Text = "Email";
//
// btnAddCustomer
//
this.btnAddCustomer.BackColor = System.Drawing.SystemColors.GrayText;
this.btnAddCustomer.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnAddCustomer.Font = new System.Drawing.Font("Calibri Light", 10F);
this.btnAddCustomer.ForeColor = System.Drawing.Color.White;
this.btnAddCustomer.Location = new System.Drawing.Point(48, 200);
this.btnAddCustomer.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.btnAddCustomer.Name = "btnAddCustomer";
this.btnAddCustomer.Size = new System.Drawing.Size(175, 37);
this.btnAddCustomer.TabIndex = 4;
this.btnAddCustomer.Text = "Add Customer";
this.btnAddCustomer.UseVisualStyleBackColor = false;
this.btnAddCustomer.Click += new System.EventHandler(this.btAddCustomer_Click);
this.btnAddCustomer.MouseEnter += new System.EventHandler(this.btnAddCustomer_MouseEnter);
this.btnAddCustomer.MouseLeave += new System.EventHandler(this.btnAddCustomer_MouseLeave);
//
// tbName
//
this.tbName.Location = new System.Drawing.Point(19, 66);
this.tbName.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.tbName.Name = "tbName";
this.tbName.Size = new System.Drawing.Size(237, 26);
this.tbName.TabIndex = 2;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Calibri", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(19, 46);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(45, 18);
this.label1.TabIndex = 0;
this.label1.Text = "Name";
//
// dataGridView
//
this.dataGridView.AllowUserToAddRows = false;
this.dataGridView.BackgroundColor = System.Drawing.Color.WhiteSmoke;
this.dataGridView.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.dataGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Id,
this.FullName,
this.Email});
this.dataGridView.Location = new System.Drawing.Point(384, 99);
this.dataGridView.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 30;
this.dataGridView.Size = new System.Drawing.Size(564, 441);
this.dataGridView.TabIndex = 26;
//
// Id
//
this.Id.HeaderText = "Id";
this.Id.MinimumWidth = 6;
this.Id.Name = "Id";
this.Id.ReadOnly = true;
this.Id.Width = 125;
//
// FullName
//
this.FullName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.FullName.HeaderText = "Full name";
this.FullName.MinimumWidth = 6;
this.FullName.Name = "FullName";
this.FullName.ReadOnly = true;
//
// Email
//
this.Email.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.Email.HeaderText = "Email";
this.Email.MinimumWidth = 6;
this.Email.Name = "Email";
this.Email.ReadOnly = true;
//
// btnDelete
//
this.btnDelete.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnDelete.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnDelete.Location = new System.Drawing.Point(857, 555);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(91, 38);
this.btnDelete.TabIndex = 29;
this.btnDelete.Text = "Delete";
this.btnDelete.UseVisualStyleBackColor = true;
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
this.btnDelete.MouseEnter += new System.EventHandler(this.btnDelete_MouseEnter);
this.btnDelete.MouseLeave += new System.EventHandler(this.btnDelete_MouseLeave);
//
// btnUser
//
this.btnUser.BackColor = System.Drawing.SystemColors.GrayText;
this.btnUser.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnUser.Font = new System.Drawing.Font("Calibri Light", 10F);
this.btnUser.ForeColor = System.Drawing.Color.White;
this.btnUser.Location = new System.Drawing.Point(384, 556);
this.btnUser.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.btnUser.Name = "btnUser";
this.btnUser.Size = new System.Drawing.Size(175, 37);
this.btnUser.TabIndex = 7;
this.btnUser.Text = "Select User ";
this.btnUser.UseVisualStyleBackColor = false;
this.btnUser.Click += new System.EventHandler(this.btnUser_Click);
this.btnUser.MouseEnter += new System.EventHandler(this.btnAddSelect_MouseEnter);
this.btnUser.MouseLeave += new System.EventHandler(this.btnAddSelect_MouseLeave);
//
// btnBack
//
this.btnBack.ErrorImage = ((System.Drawing.Image)(resources.GetObject("btnBack.ErrorImage")));
this.btnBack.Image = ((System.Drawing.Image)(resources.GetObject("btnBack.Image")));
this.btnBack.InitialImage = ((System.Drawing.Image)(resources.GetObject("btnBack.InitialImage")));
this.btnBack.Location = new System.Drawing.Point(13, 11);
this.btnBack.Margin = new System.Windows.Forms.Padding(4);
this.btnBack.Name = "btnBack";
this.btnBack.Size = new System.Drawing.Size(37, 32);
this.btnBack.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.btnBack.TabIndex = 27;
this.btnBack.TabStop = false;
this.btnBack.Click += new System.EventHandler(this.btBack_Click);
this.btnBack.MouseEnter += new System.EventHandler(this.btnBack_MouseEnter);
this.btnBack.MouseLeave += new System.EventHandler(this.btnBack_MouseLeave);
//
// btnExit
//
this.btnExit.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnExit.ErrorImage = ((System.Drawing.Image)(resources.GetObject("btnExit.ErrorImage")));
this.btnExit.Image = ((System.Drawing.Image)(resources.GetObject("btnExit.Image")));
this.btnExit.InitialImage = ((System.Drawing.Image)(resources.GetObject("btnExit.InitialImage")));
this.btnExit.Location = new System.Drawing.Point(953, 11);
this.btnExit.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.btnExit.Name = "btnExit";
this.btnExit.Size = new System.Drawing.Size(35, 35);
this.btnExit.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.btnExit.TabIndex = 25;
this.btnExit.TabStop = false;
this.btnExit.Visible = false;
this.btnExit.Click += new System.EventHandler(this.btExit_Click);
this.btnExit.MouseEnter += new System.EventHandler(this.btnExit_MouseEnter);
this.btnExit.MouseLeave += new System.EventHandler(this.btnExit_MouseLeave);
//
// CustomersForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(1000, 650);
this.Controls.Add(this.btnUser);
this.Controls.Add(this.btnDelete);
this.Controls.Add(this.lbBack);
this.Controls.Add(this.btnBack);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.btnExit);
this.Controls.Add(this.groupCustomer);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "CustomersForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "Customers";
this.groupCustomer.ResumeLayout(false);
this.groupCustomer.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.btnBack)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.btnExit)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lbBack;
private System.Windows.Forms.PictureBox btnBack;
private System.Windows.Forms.PictureBox btnExit;
private System.Windows.Forms.GroupBox groupCustomer;
private System.Windows.Forms.TextBox tbEmail;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Button btnAddCustomer;
private System.Windows.Forms.TextBox tbName;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.DataGridView dataGridView;
private System.Windows.Forms.DataGridViewTextBoxColumn Id;
private System.Windows.Forms.DataGridViewTextBoxColumn FullName;
private System.Windows.Forms.DataGridViewTextBoxColumn Email;
private System.Windows.Forms.Button btnDelete;
private System.Windows.Forms.Button btnUser;
}
} | 53.198606 | 168 | 0.616387 | [
"MIT"
] | constantimi/Object-Oriented-Programming | csharp/2020-04-20-csharp-files-binary/Shop/CustomersForm.Designer.cs | 15,270 | 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.Gcp.BigQuery.Outputs
{
[OutputType]
public sealed class JobQueryDestinationEncryptionConfiguration
{
/// <summary>
/// Describes the Cloud KMS encryption key that will be used to protect destination BigQuery table.
/// The BigQuery Service Account associated with your project requires access to this encryption key.
/// </summary>
public readonly string KmsKeyName;
[OutputConstructor]
private JobQueryDestinationEncryptionConfiguration(string kmsKeyName)
{
KmsKeyName = kmsKeyName;
}
}
}
| 31.862069 | 109 | 0.701299 | [
"ECL-2.0",
"Apache-2.0"
] | dimpu47/pulumi-gcp | sdk/dotnet/BigQuery/Outputs/JobQueryDestinationEncryptionConfiguration.cs | 924 | C# |
using Academy.Core.Contracts;
using Academy.Ninject;
using Ninject;
namespace Academy
{
public class Startup
{
public static void Main(string[] args)
{
var kernel = new StandardKernel(new AcademyModule());
var engine = kernel.Get<IEngine>();
engine.Start();
}
}
}
| 19.882353 | 65 | 0.585799 | [
"MIT"
] | SvetozarMateev/Exercises | Academy/Academy/Startup.cs | 340 | 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.WafV2.Outputs
{
[OutputType]
public sealed class RuleGroupRuleStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchAllQueryArguments
{
[OutputConstructor]
private RuleGroupRuleStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchAllQueryArguments()
{
}
}
}
| 31.636364 | 134 | 0.772989 | [
"ECL-2.0",
"Apache-2.0"
] | Otanikotani/pulumi-aws | sdk/dotnet/WafV2/Outputs/RuleGroupRuleStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchAllQueryArguments.cs | 696 | C# |
using System;
using System.ComponentModel.DataAnnotations;
namespace IntroEFCore
{
public class Todo
{
public Guid Id { get; set; }
public string Description { get; set; }
[Required]
public bool IsCompleted { get; set; }
}
} | 18.066667 | 46 | 0.619926 | [
"Apache-2.0"
] | ioanabirsan/Introduction-to-.Net | labs/IntroEFCore-ver2/IntroEFCore/IntroEFCore/Todo.cs | 273 | C# |
namespace DragonSpark.Application.Runtime;
public interface IOrderAware
{
public uint? Order { get; set; }
} | 18.5 | 43 | 0.765766 | [
"MIT"
] | DragonSpark/Framework | DragonSpark.Application/Runtime/IOrderAware.cs | 113 | C# |
using System.Collections.Generic;
using CompanySearch.Models;
using CompanySearch.Services;
using CompanySearch.ViewModels;
using Xamarin.Forms;
using CompanySearch.Instrumentation;
using CompanySearch.Instrumentation.Metrics;
using Microsoft.Azure.Mobile.Analytics;
namespace CompanySearch.Pages
{
public partial class SearchPage : ContentPage
{
public SearchPage()
{
InitializeComponent();
BindingContext = new SearchViewModel(new SearchService());
Query.Keyboard = Keyboard.Create(0);
NavigationPage.SetBackButtonTitle(this, "");
}
private async void onCompanySelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null)
return;
var company = e.SelectedItem as Company;
MetricService.Instance.Log(new CountedMetric("viewcompany", tags: new List<string> { $"name:{company.Name}" }));
Analytics.TrackEvent("Company Viewed", new Dictionary<string, string> { ["name"] = company.Name });
await Navigation.PushAsync(new CompanyPage(company));
Companies.SelectedItem = null;
}
}
} | 27.615385 | 124 | 0.742804 | [
"MIT"
] | gshackles/xamarin-monitoring-sample | CompanySearch/CompanySearch/Pages/SearchPage.xaml.cs | 1,079 | C# |
using System.Web.Mvc;
namespace ASF.UI.WbSite.Areas.Carts
{
public class CartsAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Carts";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Carts_default",
"Carts/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
} | 23.666667 | 75 | 0.5 | [
"MIT"
] | MagninM/MCGA2017 | Presentation/ASF.UI.WbSite/Areas/Carts/CartsAreaRegistration.cs | 570 | C# |
// *************************************************************
// project: graphql-aspnet
// --
// repo: https://github.com/graphql-aspnet
// docs: https://graphql-aspnet.github.io
// --
// License: MIT
// *************************************************************
namespace GraphQL.AspNet.Defaults
{
using System.Threading.Tasks;
using GraphQL.AspNet.Common;
using GraphQL.AspNet.Execution;
using GraphQL.AspNet.Interfaces.Engine;
using GraphQL.AspNet.Interfaces.Execution;
using GraphQL.AspNet.Interfaces.TypeSystem;
using GraphQL.AspNet.Internal.Interfaces;
using GraphQL.AspNet.Parsing.Lexing.Exceptions;
using GraphQL.AspNet.PlanGeneration;
/// <summary>
/// A plan generator capable of converting a syntax tree into an actionable
/// query plan executable by a the query pipeline.
/// </summary>
/// <typeparam name="TSchema">The type of the schema this plan generator is registered for.</typeparam>
public class DefaultGraphQueryPlanGenerator<TSchema> : IGraphQueryPlanGenerator<TSchema>
where TSchema : class, ISchema
{
private readonly ISchema _schema;
private readonly IQueryOperationComplexityCalculator<TSchema> _complexityCalculator;
private readonly IGraphQueryDocumentGenerator<TSchema> _documentGenerator;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultGraphQueryPlanGenerator{TSchema}" /> class.
/// </summary>
/// <param name="schema">The schema.</param>
/// <param name="documentGenerator">The document generator that will generate query documents, a precursor
/// to a query plan.</param>
/// <param name="complexityCalculator">The complexity calculator for this plan generator to use
/// when computing complexity scores.</param>
public DefaultGraphQueryPlanGenerator(
TSchema schema,
IGraphQueryDocumentGenerator<TSchema> documentGenerator,
IQueryOperationComplexityCalculator<TSchema> complexityCalculator)
{
_schema = Validation.ThrowIfNullOrReturn(schema, nameof(schema));
_complexityCalculator = Validation.ThrowIfNullOrReturn(complexityCalculator, nameof(complexityCalculator));
_documentGenerator = Validation.ThrowIfNullOrReturn(documentGenerator, nameof(documentGenerator));
}
/// <summary>
/// Creates a qualified exeuction plan that can be executed to fulfill a user's request.
/// </summary>
/// <param name="syntaxTree">The syntax tree that was lexed from the original source supplied by a user.</param>
/// <returns>Task<IGraphQueryPlan>.</returns>
public async Task<IGraphQueryPlan> CreatePlan(ISyntaxTree syntaxTree)
{
Validation.ThrowIfNull(syntaxTree, nameof(syntaxTree));
var queryPlan = this.CreatePlanInstance();
// ------------------------------------------
// Step 1: Parse the document.
// ------------------------------------------
// Validate that the lexed syntax tree is internally consistant and
// is valid in context to the schema it is to be processed against
// at the same time build up the query document in anticipation that it will be correct
// as in production this should mostly be the case. Should it fail return the messages
// on an empty query plan.
// ------------------------------------------
var document = _documentGenerator.CreateDocument(syntaxTree);
this.InspectSyntaxDepth(document);
queryPlan.MaxDepth = document.MaxDepth;
queryPlan.Messages.AddRange(document.Messages);
if (!queryPlan.IsValid)
return queryPlan;
// ------------------------------------------
// Step 2: Plan Construction
// ------------------------------------------
// The document is garunteed to be syntactically correct and, barring anything user related (variable data, custom code etc.),
// will resolve to produce a result. Using the correct operation (or the anon operation), extract the resolvers for all possible concrete
// types needed to fulfill the user's request and generate a query plan that can be executed to fulfill the request.
// ------------------------------------------
var generator = new ExecutableOperationGenerator(_schema);
foreach (var operation in document.Operations.Values)
{
var executableOperation = await generator.Create(operation).ConfigureAwait(false);
queryPlan.AddOperation(executableOperation);
// estimate the complexity for any successfully parsed operations
if (executableOperation.Messages.IsSucessful)
{
var complexity = _complexityCalculator.Calculate(executableOperation);
if (complexity > queryPlan.EstimatedComplexity)
queryPlan.EstimatedComplexity = complexity;
}
}
this.InspectQueryPlanComplexity(queryPlan);
return queryPlan;
}
/// <summary>
/// Creates a new instance of the <see cref="IGraphQueryPlan"/>
/// this generator manages. Overload this method in a child class to inject
/// your own plan type.
/// </summary>
/// <returns>IGraphQueryPlan.</returns>
protected virtual IGraphQueryPlan CreatePlanInstance()
{
return new GraphQueryExecutionPlan<TSchema>();
}
/// <summary>
/// Inspects the syntax tree against the required metric values for the target schema and should a violation occur a
/// <see cref="GraphQLSyntaxException" /> is thrown aborting the query.
/// </summary>
/// <param name="document">The document to inspect.</param>
protected void InspectSyntaxDepth(IGraphQueryDocument document)
{
var maxAllowedDepth = _schema.Configuration?.ExecutionOptions?.MaxQueryDepth;
if (maxAllowedDepth.HasValue && document.MaxDepth > maxAllowedDepth.Value)
{
document.Messages.Critical(
$"The query has a max field depth of {document.MaxDepth} but " +
$"this schema has been configured to only accept queries with a max depth of {maxAllowedDepth.Value}. " +
"Adjust your query and try again.",
Constants.ErrorCodes.REQUEST_ABORTED);
}
}
/// <summary>
/// Inspects the query plan's estimated execution metrics against the configured values for the target schema and should a violation
/// occur, a message is recorded to the plan and it is abandoned.
/// </summary>
/// <param name="plan">The plan.</param>
protected void InspectQueryPlanComplexity(IGraphQueryPlan plan)
{
var maxComplexity = _schema.Configuration?.ExecutionOptions?.MaxQueryComplexity;
if (maxComplexity.HasValue && plan.EstimatedComplexity > maxComplexity.Value)
{
plan.Messages.Critical(
$"The generated query plan has an estimated complexity score of {plan.EstimatedComplexity} but this schema has been configured to only accept " +
$"queries with a maximum estimated complexity of {maxComplexity.Value}. A high complexity value " +
"usually indicates a large number of data store operations and compounding field executions such as fields that yield lists with child fields that also yield lists. " +
"Adjust your query and try again.",
Constants.ErrorCodes.REQUEST_ABORTED);
}
}
}
} | 52.150327 | 188 | 0.614739 | [
"MIT"
] | NET1211/aspnet-archive-tools | src/graphql-aspnet/Defaults/DefaultGraphQueryPlanGenerator{TSchema}.cs | 7,981 | C# |
using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using Pro.Utils;
using Pro.Dal;
using Platinium.Entidade;
using Negocio;
namespace Platinium.Negocio
{
public class ManterTipoTransferencia : IManter
{
#region Variáveis e Propriedades
private TipoTransferencia oTipoTransferencia;
private Dao oDao;
#endregion
#region Construtores
public ManterTipoTransferencia()
{
oDao = new Dao();
}
public ManterTipoTransferencia(string connectionString, DataBaseTypes dataBaseType)
{
oDao = new Dao(connectionString, dataBaseType);
}
#endregion
#region Métodos
public DataTable Consultar(Dictionary<string, object> filtros, string direcao, string colunaSort)
{
Dictionary<string, string> dicionario = ClassFunctions.GetMap(typeof(TipoTransferencia));
List<Parameter> lstParametros = new List<Parameter>();
foreach (KeyValuePair<string, object> item in filtros)
{
if (item.Value != null)
{
if (item.Value.GetType() == typeof(Int32))
lstParametros.Add(new Parameter(item.Key, item.Value, OperationTypes.EqualsTo));
else
lstParametros.Add(new Parameter(item.Key, item.Value, OperationTypes.Like));
}
}
lstParametros.Add(new Parameter(colunaSort, null, OperationTypes.Null, direcao));
return this.oDao.Select(lstParametros, "platinium", "TB_TIPO_TRANSFERENCIA_TITR", dicionario);
}
public DataTable Consultar(Dictionary<string, object> filtros, string direcao)
{
Dictionary<string, string> dicionario = ClassFunctions.GetMap(typeof(TipoTransferencia));
List<Parameter> lstParametros = new List<Parameter>();
foreach (KeyValuePair<string, object> item in filtros)
{
if (item.Value != null)
{
if (item.Value.GetType() == typeof(Int32))
lstParametros.Add(new Parameter(item.Key, item.Value, OperationTypes.EqualsTo));
else
lstParametros.Add(new Parameter(item.Key, item.Value, OperationTypes.Like));
}
}
return this.oDao.Select(lstParametros, "platinium", "TB_TIPO_TRANSFERENCIA_TITR", dicionario);
}
public void PrepararInclusao()
{
oTipoTransferencia = new TipoTransferencia(oDao);
}
public Dictionary<string, object> Selecionar(int id)
{
oTipoTransferencia = new TipoTransferencia(id, oDao);
return ClassFunctions.GetProperties(oTipoTransferencia);
}
public CrudActionTypes Salvar(Dictionary<string, object> valores)
{
ClassFunctions.SetProperties(oTipoTransferencia, valores);
return oTipoTransferencia.Salvar();
}
public CrudActionTypes Excluir()
{
return oTipoTransferencia.Excluir();
}
#endregion
}
}
| 31.699029 | 106 | 0.593262 | [
"MIT"
] | CesarRabelo/eGovernos.Corporativo | src/Negocio/Controladoras/ManterTipoTransferencia.cs | 3,269 | C# |
using UnityEngine;
using System.Collections;
public class LevelManager : MonoBehaviour {
public string LevelName;
public int beaten = 0;
public int unlocked = 0;
public int BestScore = 999;
public int NumberOfPlays = 0;
public int ParScore;
// Use this for initialization
void Start () {
//retrieves level data from playerprefs
LevelName = Application.loadedLevelName;
if(PlayerPrefs.HasKey(LevelName + "beaten"))
beaten = PlayerPrefs.GetInt(LevelName + "beaten");
else beaten = 0;
if(PlayerPrefs.HasKey(LevelName + "unlocked"))
unlocked = PlayerPrefs.GetInt(LevelName + "unlocked");
else unlocked = 0;
if(PlayerPrefs.HasKey(LevelName + "BestScore"))
BestScore = PlayerPrefs.GetInt(LevelName + "BestScore");
else BestScore = 999;
if(PlayerPrefs.HasKey(LevelName + "NumberOfPlays"))
NumberOfPlays = PlayerPrefs.GetInt(LevelName + "NumberOfPlays");
else NumberOfPlays = 0;
GameManager.instance.LastLevelName = LevelName;
// if(!PlayerPrefs.HasKey(LevelName + "ParScore"))
// PlayerPrefs.SetInt(LevelName + "ParScore", Mathf.Min(BestScore, ParScore));
// else
// ParScore = PlayerPrefs.GetInt(LevelName + "ParScore", ParScore);
NumberOfPlays++;
}
// Update is called once per frame
void Update () {
}
//when level is beaten, optionally send data to GA and update some data
public void LevelBeaten(int Steps){
if (Steps < BestScore) {
BestScore = Steps;
}
beaten++;
int LevelNum = int.Parse (LevelName);
// GA.API.Design.NewEvent ("UserBeatLevel " + LevelName, Time.timeSinceLevelLoad);
// GA.API.Design.NewEvent ("NumberOfStepsLevel " + LevelName, Steps);
}
void OnDestroy(){
//save all the data
PlayerPrefs.SetInt(LevelName + "beaten", beaten);
PlayerPrefs.SetInt(LevelName + "unlocked", unlocked);
PlayerPrefs.SetInt(LevelName + "BestScore", BestScore);
PlayerPrefs.SetInt(LevelName + "NumberOfPlays", NumberOfPlays);
PlayerPrefs.SetInt(LevelName + "ParScore", ParScore);
PlayerPrefs.Save ();
}
}
| 27.27027 | 85 | 0.7111 | [
"MIT"
] | edd34/Awale | Unity_Game_Awale/Assets/Scripts/LevelManager.cs | 2,018 | C# |
// Project: Aguafrommars/TheIdServer
// Copyright (c) 2021 @Olivier Lefebvre
using System.Threading;
using System.Threading.Tasks;
namespace Aguacongas.IdentityServer.Abstractions
{
public interface IProviderClient
{
Task ProviderAddedAsync(string scheme, CancellationToken cancellationToken = default);
Task ProviderUpdatedAsync(string scheme, CancellationToken cancellationToken = default);
Task ProviderRemovedAsync(string scheme, CancellationToken cancellationToken = default);
Task KeyRevokedAsync(string kind, string id, CancellationToken cancellationToken = default);
}
}
| 34 | 101 | 0.752322 | [
"Apache-2.0"
] | Aguafrommars/TheIdServer | src/IdentityServer/Aguacongas.IdentityServer/Abstractions/IProviderClient.cs | 648 | C# |
namespace Fluxera.Enumeration.JsonNet.UnitTests
{
using System;
using FluentAssertions;
using Fluxera.Enumeration.UnitTests.Enums;
using Newtonsoft.Json;
using NUnit.Framework;
[TestFixture]
public class EnumerationNameConverterTests
{
public class TestClass
{
[JsonConverter(typeof(EnumerationNameConverter<Color, int>))]
public Color Color { get; set; }
}
private static readonly TestClass TestInstance = new TestClass
{
Color = Color.Red,
};
private static readonly string JsonString = @"{""Color"":""Red""}";
[Test]
public void ShouldDeserializeFromName()
{
TestClass obj = JsonConvert.DeserializeObject<TestClass>(JsonString);
obj.Color.Should().BeSameAs(Color.Red);
}
[Test]
public void ShouldDeserializeNullProperty()
{
string json = @"{}";
TestClass obj = JsonConvert.DeserializeObject<TestClass>(json);
obj.Color.Should().BeNull();
}
[Test]
public void ShouldDeserializeNullValue()
{
string json = @"{ ""Color"": null }";
TestClass obj = JsonConvert.DeserializeObject<TestClass>(json);
obj.Color.Should().BeNull();
}
[Test]
public void ShouldSerializeForName()
{
string json = JsonConvert.SerializeObject(TestInstance, Formatting.None);
json.Should().Be(JsonString);
}
[Test]
public void ShouldThrowWhenNotFound()
{
string json = @"{ ""Color"": ""Not Found"" }";
Action act = () => JsonConvert.DeserializeObject<TestClass>(json);
act.Should()
.Throw<JsonSerializationException>();
}
}
}
| 20.917808 | 76 | 0.695481 | [
"MIT"
] | fluxera/Fluxera.Enumeration | tests/Fluxera.Common.Enumeration.JsonNet.UnitTests/EnumerationNameConverterTests.cs | 1,527 | C# |
using System.Reflection;
using Hellang.Middleware.ProblemDetails;
using Microsoft.OpenApi.Models;
using Rocket.Surgery.LaunchPad.AspNetCore;
using Rocket.Surgery.LaunchPad.AspNetCore.AppMetrics;
using Serilog;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace Sample.Restful;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddControllersAsServices();
services
.Configure<SwaggerGenOptions>(
c => c.SwaggerDoc(
"v1",
new OpenApiInfo
{
Version = typeof(Startup).GetCustomAttribute<AssemblyVersionAttribute>()?.Version
?? typeof(Startup).GetCustomAttribute<AssemblyFileVersionAttribute>()?.Version ?? "0.1.0",
Title = "Test Application",
}
)
);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseProblemDetails();
app.UseHttpsRedirection();
// Should this move into an extension method?
app.UseSerilogRequestLogging(
x =>
{
x.GetLevel = LaunchPadLogHelpers.DefaultGetLevel;
x.EnrichDiagnosticContext = LaunchPadLogHelpers.DefaultEnrichDiagnosticContext;
}
);
app.UseMetricsAllMiddleware();
app.UseRouting();
app
.UseSwaggerUI()
.UseReDoc();
app.UseAuthorization();
app.UseEndpoints(
endpoints =>
{
endpoints.MapControllers();
// Should this move into an extension method?
endpoints.MapSwagger();
endpoints.MapAppMetrics();
}
);
}
}
| 29.959459 | 121 | 0.593144 | [
"MIT"
] | RocketSurgeonsGuild/SpaceShuttle | sample/Sample.Restful/Startup.cs | 2,217 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/directmanipulation.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using static TerraFX.Interop.Windows.IID;
namespace TerraFX.Interop.DirectX.UnitTests;
/// <summary>Provides validation of the <see cref="IDirectManipulationViewport" /> struct.</summary>
[SupportedOSPlatform("windows8.0")]
public static unsafe partial class IDirectManipulationViewportTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="IDirectManipulationViewport" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(IDirectManipulationViewport).GUID, Is.EqualTo(IID_IDirectManipulationViewport));
}
/// <summary>Validates that the <see cref="IDirectManipulationViewport" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IDirectManipulationViewport>(), Is.EqualTo(sizeof(IDirectManipulationViewport)));
}
/// <summary>Validates that the <see cref="IDirectManipulationViewport" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IDirectManipulationViewport).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IDirectManipulationViewport" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IDirectManipulationViewport), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(IDirectManipulationViewport), Is.EqualTo(4));
}
}
}
| 38.056604 | 145 | 0.715915 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | tests/Interop/Windows/DirectX/um/directmanipulation/IDirectManipulationViewportTests.cs | 2,019 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using NADD.Models;
namespace NADD.Controllers
{
public class DisciplinasController : Controller
{
private readonly Contexto _context;
public DisciplinasController(Contexto context)
{
_context = context;
}
// GET: Disciplinas
public async Task<IActionResult> Index()
{
var contexto = _context.Disciplina.Include(d => d.Curso);
return View(await contexto.ToListAsync());
}
// GET: Disciplinas/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var disciplina = await _context.Disciplina
.Include(d => d.Curso)
.FirstOrDefaultAsync(m => m.DisciplinaId == id);
if (disciplina == null)
{
return NotFound();
}
return View(disciplina);
}
// GET: Disciplinas/Create
public IActionResult Create()
{
ViewData["CursoId"] = new SelectList(_context.Curso, "CursoId", "NomeCurso");
return View();
}
// POST: Disciplinas/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("DisciplinaId,NomeDisciplina,CursoId,DtCriacao,Status")] Disciplina disciplina)
{
if (ModelState.IsValid)
{
_context.Add(disciplina);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["CursoId"] = new SelectList(_context.Curso, "CursoId", "NomeCurso", disciplina.CursoId);
return View(disciplina);
}
// GET: Disciplinas/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var disciplina = await _context.Disciplina.FindAsync(id);
if (disciplina == null)
{
return NotFound();
}
ViewData["CursoId"] = new SelectList(_context.Curso, "CursoId", "NomeCurso", disciplina.CursoId);
return View(disciplina);
}
// POST: Disciplinas/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("DisciplinaId,NomeDisciplina,CursoId,DtCriacao,Status")] Disciplina disciplina)
{
if (id != disciplina.DisciplinaId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(disciplina);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!DisciplinaExists(disciplina.DisciplinaId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["CursoId"] = new SelectList(_context.Curso, "CursoId", "NomeCurso", disciplina.CursoId);
return View(disciplina);
}
// GET: Disciplinas/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var disciplina = await _context.Disciplina
.Include(d => d.Curso)
.FirstOrDefaultAsync(m => m.DisciplinaId == id);
if (disciplina == null)
{
return NotFound();
}
return View(disciplina);
}
// POST: Disciplinas/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var disciplina = await _context.Disciplina.FindAsync(id);
_context.Disciplina.Remove(disciplina);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool DisciplinaExists(int id)
{
return _context.Disciplina.Any(e => e.DisciplinaId == id);
}
}
}
| 31.925 | 139 | 0.532498 | [
"Apache-2.0"
] | caiodomingues/Projeto-NADD | NADD/NADD/Controllers/DisciplinasController.cs | 5,110 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace _01.Ranking
{
class Program
{
static void Main(string[] args)
{
var townNameTimePassengersCount = new Dictionary<string, Dictionary<int, long>>();
while (true)
{
string[] commands = Console.ReadLine().Split(":");
if (commands[0] == "Slide rule")
{
foreach (var kvp in townNameTimePassengersCount
.Where(a => a.Value.Keys.Min() > 0)
.Where(a => a.Value.Values.Max() > 0)
.OrderBy(a => a.Value.Keys.Min())
.ThenBy(a => a.Key))
{
Console.WriteLine($"{kvp.Key} -> Time: {kvp.Value.Keys.Min()} -> Passengers: {kvp.Value.Values.Max()}");
}
break;
}
string[] commandsSplitted1 = commands[1].Split("->");
string town = commands[0];
string timeOrAmbush = commandsSplitted1[0];
long passengersCount = long.Parse(commandsSplitted1[1]);
int currentTime = 0;
if (timeOrAmbush != "ambush")
{
currentTime = int.Parse(timeOrAmbush);
}
if (townNameTimePassengersCount.ContainsKey(town) == false)
{
if (timeOrAmbush == "ambush")
{
continue;
}
townNameTimePassengersCount.Add(town, new Dictionary<int, long>());
townNameTimePassengersCount[town].Add(currentTime, passengersCount);
}
else
{
var key = townNameTimePassengersCount[town].Keys.Max();
var value = townNameTimePassengersCount[town][key];
if (timeOrAmbush == "ambush")
{
townNameTimePassengersCount[town][key] -= passengersCount;
townNameTimePassengersCount[town].Remove(key);
townNameTimePassengersCount[town].Add(0, value);
}
else
{
townNameTimePassengersCount[town][key] += passengersCount;
if (key > currentTime || key == 0)
{
townNameTimePassengersCount[town].Remove(key);
townNameTimePassengersCount[town].Add(currentTime, value);
}
}
}
}
}
}
} | 36.539474 | 128 | 0.441124 | [
"MIT"
] | grekssi/Softuni-Courses | SoftUni/01. .NET Courses/02. Technology Fundamentals - C#/11. Dictionaries, Lambda and LINQ/More Exercises/01.Ranking/01.cs | 2,779 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using Android.Content;
using Android.Util;
using Android.Views;
using Android.Widget;
namespace MonoDroid.TimesSquare
{
public class MonthView : LinearLayout
{
private TextView _title;
private CalendarGridView _grid;
private ClickHandler _clickHandler;
public MonthView(Context context, IAttributeSet attrs)
: base(context, attrs)
{
}
public static MonthView Create(ViewGroup parent, LayoutInflater inflater, string weekdayNameFormat,
DateTime today, ClickHandler handler, int dividerColor, int dayBackgroundResId,
int dayTextColorResId, int titleTextColor, int headerTextColor)
{
var view = (MonthView) inflater.Inflate(Resource.Layout.month, parent, false);
view.setDividerColor(dividerColor);
view.setDayTextColor(dayTextColorResId);
view.setTitleTextColor(titleTextColor);
view.setHeaderTextColor(headerTextColor);
if (dayBackgroundResId != 0) {
view.setDayBackground(dayBackgroundResId);
}
var originalDay = today;
var firstDayOfWeek = (int) CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
var headerRow = (CalendarRowView) view._grid.GetChildAt(0);
for (int i = 0; i < 7; i++) {
var offset = firstDayOfWeek - (int) today.DayOfWeek + i;
today = today.AddDays(offset);
var textView = (TextView) headerRow.GetChildAt(i);
textView.Text = today.ToString(weekdayNameFormat);
today = originalDay;
}
view._clickHandler = handler;
return view;
}
public void Init(MonthDescriptor month, List<List<MonthCellDescriptor>> cells)
{
Logr.D("Initializing MonthView ({0:d}) for {1}", GetHashCode(), month);
var stopWatch = new Stopwatch();
stopWatch.Start();
_title.Text = month.Label;
int numOfRows = cells.Count;
_grid.NumRows = numOfRows;
for (int i = 0; i < 6; i++) {
var weekRow = (CalendarRowView)_grid.GetChildAt(i + 1);
weekRow.ClickHandler = _clickHandler;
if (i < numOfRows) {
weekRow.Visibility = ViewStates.Visible;
var week = cells[i];
for (int c = 0; c < week.Count; c++) {
var cell = week[c];
var cellView = (CalendarCellView)weekRow.GetChildAt(c);
cellView.Text = cell.Value.ToString();
cellView.Enabled = cell.IsCurrentMonth;
cellView.Selectable = cell.IsSelectable;
cellView.Selected = cell.IsSelected;
cellView.IsCurrentMonth = cell.IsCurrentMonth;
cellView.IsToday = cell.IsToday;
cellView.IsHighlighted = cell.IsHighlighted;
cellView.RangeState = cell.RangeState;
cellView.Tag = cell;
}
}
else {
weekRow.Visibility = ViewStates.Gone;
}
}
stopWatch.Stop();
Logr.D("MonthView.Init took {0} ms", stopWatch.ElapsedMilliseconds);
}
public void setDividerColor(int color)
{
_grid.SetDividerColor(color);
}
public void setDayBackground(int resId)
{
_grid.SetDayBackground(resId);
}
public void setDayTextColor(int resId)
{
_grid.SetDayTextColor(resId);
}
public void setTitleTextColor(int color)
{
_title.SetTextColor(base.Resources.GetColor(color));
}
public void setHeaderTextColor(int color)
{
_grid.SetHeaderTextColor(color);
}
protected override void OnFinishInflate()
{
base.OnFinishInflate();
_title = FindViewById<TextView>(Resource.Id.title);
_grid = FindViewById<CalendarGridView>(Resource.Id.calendar_grid);
}
}
} | 35.354839 | 107 | 0.560903 | [
"Apache-2.0"
] | aaronhe42/MonoDroid.TimesSquare | MonoDroid.TimesSquare/MonthView.cs | 4,384 | C# |
using System;
using System.Collections.Generic;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.RenderGraphModule
{
/// <summary>
/// The mode that determines the size of a Texture.
/// </summary>
#region Resource Descriptors
public enum TextureSizeMode
{
///<summary>Explicit size.</summary>
Explicit,
///<summary>Size automatically scaled by a Vector.</summary>
Scale,
///<summary>Size automatically scaled by a Functor.</summary>
Functor
}
/// <summary>
/// Descriptor used to create texture resources
/// </summary>
public struct TextureDesc
{
///<summary>Texture sizing mode.</summary>
public TextureSizeMode sizeMode;
///<summary>Texture width.</summary>
public int width;
///<summary>Texture height.</summary>
public int height;
///<summary>Number of texture slices..</summary>
public int slices;
///<summary>Texture scale.</summary>
public Vector2 scale;
///<summary>Texture scale function.</summary>
public ScaleFunc func;
///<summary>Depth buffer bit depth.</summary>
public DepthBits depthBufferBits;
///<summary>Color format.</summary>
public GraphicsFormat colorFormat;
///<summary>Filtering mode.</summary>
public FilterMode filterMode;
///<summary>Addressing mode.</summary>
public TextureWrapMode wrapMode;
///<summary>Texture dimension.</summary>
public TextureDimension dimension;
///<summary>Enable random UAV read/write on the texture.</summary>
public bool enableRandomWrite;
///<summary>Texture needs mip maps.</summary>
public bool useMipMap;
///<summary>Automatically generate mip maps.</summary>
public bool autoGenerateMips;
///<summary>Texture is a shadow map.</summary>
public bool isShadowMap;
///<summary>Anisotropic filtering level.</summary>
public int anisoLevel;
///<summary>Mip map bias.</summary>
public float mipMapBias;
///<summary>Textre is multisampled. Only supported for Scale and Functor size mode.</summary>
public bool enableMSAA;
///<summary>Number of MSAA samples. Only supported for Explicit size mode.</summary>
public MSAASamples msaaSamples;
///<summary>Bind texture multi sampled.</summary>
public bool bindTextureMS;
///<summary>Texture uses dynamic scaling.</summary>
public bool useDynamicScale;
///<summary>Memory less flag.</summary>
public RenderTextureMemoryless memoryless;
///<summary>Texture name.</summary>
public string name;
// Initial state. Those should not be used in the hash
///<summary>Texture needs to be cleared on first use.</summary>
public bool clearBuffer;
///<summary>Clear color.</summary>
public Color clearColor;
void InitDefaultValues(bool dynamicResolution, bool xrReady)
{
useDynamicScale = dynamicResolution;
// XR Ready
if (xrReady)
{
slices = TextureXR.slices;
dimension = TextureXR.dimension;
}
else
{
slices = 1;
dimension = TextureDimension.Tex2D;
}
}
/// <summary>
/// TextureDesc constructor for a texture using explicit size
/// </summary>
/// <param name="width">Texture width</param>
/// <param name="height">Texture height</param>
/// <param name="dynamicResolution">Use dynamic resolution</param>
/// <param name="xrReady">Set this to true if the Texture is a render texture in an XR setting.</param>
public TextureDesc(int width, int height, bool dynamicResolution = false, bool xrReady = false)
: this()
{
// Size related init
sizeMode = TextureSizeMode.Explicit;
this.width = width;
this.height = height;
// Important default values not handled by zero construction in this()
msaaSamples = MSAASamples.None;
InitDefaultValues(dynamicResolution, xrReady);
}
/// <summary>
/// TextureDesc constructor for a texture using a fixed scaling
/// </summary>
/// <param name="scale">RTHandle scale used for this texture</param>
/// <param name="dynamicResolution">Use dynamic resolution</param>
/// <param name="xrReady">Set this to true if the Texture is a render texture in an XR setting.</param>
public TextureDesc(Vector2 scale, bool dynamicResolution = false, bool xrReady = false)
: this()
{
// Size related init
sizeMode = TextureSizeMode.Scale;
this.scale = scale;
// Important default values not handled by zero construction in this()
msaaSamples = MSAASamples.None;
dimension = TextureDimension.Tex2D;
InitDefaultValues(dynamicResolution, xrReady);
}
/// <summary>
/// TextureDesc constructor for a texture using a functor for scaling
/// </summary>
/// <param name="func">Function used to determnine the texture size</param>
/// <param name="dynamicResolution">Use dynamic resolution</param>
/// <param name="xrReady">Set this to true if the Texture is a render texture in an XR setting.</param>
public TextureDesc(ScaleFunc func, bool dynamicResolution = false, bool xrReady = false)
: this()
{
// Size related init
sizeMode = TextureSizeMode.Functor;
this.func = func;
// Important default values not handled by zero construction in this()
msaaSamples = MSAASamples.None;
dimension = TextureDimension.Tex2D;
InitDefaultValues(dynamicResolution, xrReady);
}
/// <summary>
/// Copy constructor
/// </summary>
/// <param name="input"></param>
public TextureDesc(TextureDesc input)
{
this = input;
}
/// <summary>
/// Hash function
/// </summary>
/// <returns>The texture descriptor hash.</returns>
public override int GetHashCode()
{
int hashCode = 17;
unchecked
{
switch (sizeMode)
{
case TextureSizeMode.Explicit:
hashCode = hashCode * 23 + width;
hashCode = hashCode * 23 + height;
hashCode = hashCode * 23 + (int)msaaSamples;
break;
case TextureSizeMode.Functor:
if (func != null)
hashCode = hashCode * 23 + func.GetHashCode();
hashCode = hashCode * 23 + (enableMSAA ? 1 : 0);
break;
case TextureSizeMode.Scale:
hashCode = hashCode * 23 + scale.x.GetHashCode();
hashCode = hashCode * 23 + scale.y.GetHashCode();
hashCode = hashCode * 23 + (enableMSAA ? 1 : 0);
break;
}
hashCode = hashCode * 23 + mipMapBias.GetHashCode();
hashCode = hashCode * 23 + slices;
hashCode = hashCode * 23 + (int)depthBufferBits;
hashCode = hashCode * 23 + (int)colorFormat;
hashCode = hashCode * 23 + (int)filterMode;
hashCode = hashCode * 23 + (int)wrapMode;
hashCode = hashCode * 23 + (int)dimension;
hashCode = hashCode * 23 + (int)memoryless;
hashCode = hashCode * 23 + anisoLevel;
hashCode = hashCode * 23 + (enableRandomWrite ? 1 : 0);
hashCode = hashCode * 23 + (useMipMap ? 1 : 0);
hashCode = hashCode * 23 + (autoGenerateMips ? 1 : 0);
hashCode = hashCode * 23 + (isShadowMap ? 1 : 0);
hashCode = hashCode * 23 + (bindTextureMS ? 1 : 0);
hashCode = hashCode * 23 + (useDynamicScale ? 1 : 0);
}
return hashCode;
}
}
#endregion
/// <summary>
/// The RenderGraphResourceRegistry holds all resource allocated during Render Graph execution.
/// </summary>
public class RenderGraphResourceRegistry
{
static readonly ShaderTagId s_EmptyName = new ShaderTagId("");
#region Resources
internal struct TextureResource
{
public TextureDesc desc;
public bool imported;
public RTHandle rt;
public int cachedHash;
public int firstWritePassIndex;
public int lastReadPassIndex;
public int shaderProperty;
public bool wasReleased;
internal TextureResource(RTHandle rt, int shaderProperty)
: this()
{
Reset();
this.rt = rt;
imported = true;
this.shaderProperty = shaderProperty;
}
internal TextureResource(in TextureDesc desc, int shaderProperty)
: this()
{
Reset();
this.desc = desc;
this.shaderProperty = shaderProperty;
}
void Reset()
{
imported = false;
rt = null;
cachedHash = -1;
firstWritePassIndex = int.MaxValue;
lastReadPassIndex = -1;
wasReleased = false;
}
}
internal struct RendererListResource
{
public RendererListDesc desc;
public RendererList rendererList;
internal RendererListResource(in RendererListDesc desc)
{
this.desc = desc;
this.rendererList = new RendererList(); // Invalid by default
}
}
#endregion
DynamicArray<TextureResource> m_TextureResources = new DynamicArray<TextureResource>();
Dictionary<int, Stack<RTHandle>> m_TexturePool = new Dictionary<int, Stack<RTHandle>>();
DynamicArray<RendererListResource> m_RendererListResources = new DynamicArray<RendererListResource>();
RTHandleSystem m_RTHandleSystem = new RTHandleSystem();
RenderGraphDebugParams m_RenderGraphDebug;
RenderGraphLogger m_Logger;
// Diagnostic only
List<(int, RTHandle)> m_AllocatedTextures = new List<(int, RTHandle)>();
#region Public Interface
/// <summary>
/// Returns the RTHandle associated with the provided resource handle.
/// </summary>
/// <param name="handle">Handle to a texture resource.</param>
/// <returns>The RTHandle associated with the provided resource handle.</returns>
public RTHandle GetTexture(in RenderGraphResource handle)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (handle.type != RenderGraphResourceType.Texture)
throw new InvalidOperationException("Trying to access a RenderGraphResource that is not a texture.");
var res = m_TextureResources[handle.handle];
if (res.rt == null && !res.wasReleased)
throw new InvalidOperationException(string.Format("Trying to access texture \"{0}\" that was never created. Check that it was written at least once before trying to get it.", res.desc.name));
if (res.rt == null && res.wasReleased)
throw new InvalidOperationException(string.Format("Trying to access texture \"{0}\" that was already released. Check that the last pass where it's read is after this one.", res.desc.name));
#endif
return m_TextureResources[handle.handle].rt;
}
/// <summary>
/// Returns the RendererList associated with the provided resource handle.
/// </summary>
/// <param name="handle">Handle to a Renderer List resource.</param>
/// <returns>The Renderer List associated with the provided resource handle.</returns>
public RendererList GetRendererList(in RenderGraphResource handle)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (handle.type != RenderGraphResourceType.RendererList)
throw new InvalidOperationException("Trying to access a RenderGraphResource that is not a RendererList.");
#endif
return m_RendererListResources[handle.handle].rendererList;
}
#endregion
#region Internal Interface
private RenderGraphResourceRegistry()
{
}
internal RenderGraphResourceRegistry(bool supportMSAA, MSAASamples initialSampleCount, RenderGraphDebugParams renderGraphDebug, RenderGraphLogger logger)
{
m_RTHandleSystem.Initialize(1, 1, supportMSAA, initialSampleCount);
m_RenderGraphDebug = renderGraphDebug;
m_Logger = logger;
}
internal void SetRTHandleReferenceSize(int width, int height, MSAASamples msaaSamples)
{
m_RTHandleSystem.SetReferenceSize(width, height, msaaSamples);
}
internal RTHandleProperties GetRTHandleProperties() { return m_RTHandleSystem.rtHandleProperties; }
// Texture Creation/Import APIs are internal because creation should only go through RenderGraph
internal RenderGraphMutableResource ImportTexture(RTHandle rt, int shaderProperty = 0)
{
int newHandle = m_TextureResources.Add(new TextureResource(rt, shaderProperty));
return new RenderGraphMutableResource(newHandle, RenderGraphResourceType.Texture);
}
internal RenderGraphMutableResource CreateTexture(in TextureDesc desc, int shaderProperty = 0)
{
ValidateTextureDesc(desc);
int newHandle = m_TextureResources.Add(new TextureResource(desc, shaderProperty));
return new RenderGraphMutableResource(newHandle, RenderGraphResourceType.Texture);
}
internal void UpdateTextureFirstWrite(RenderGraphResource tex, int passIndex)
{
ref var res = ref GetTextureResource(tex);
res.firstWritePassIndex = Math.Min(passIndex, res.firstWritePassIndex);
//// We increment lastRead index here so that a resource used only for a single pass can be released at the end of said pass.
//// This will also keep the resource alive as long as it is written to.
//// Typical example is a depth buffer that may never be explicitly read from but is necessary all along
///
// PROBLEM: Increasing last read on write operation will keep the target alive even if it's not used at all so it's not good.
// If we don't do it though, it means that client code cannot write "by default" into a target as it will try to write to an already released target.
// Example:
// DepthPrepass: Writes to Depth and Normal buffers (pass will create normal buffer)
// ObjectMotion: Writes to MotionVectors and Normal => Exception because NormalBuffer is already released as it not used.
// => Solution includes : Shader Combination (without MRT for example) / Dummy Targets
//res.lastReadPassIndex = Math.Max(passIndex, res.lastReadPassIndex);
}
internal void UpdateTextureLastRead(RenderGraphResource tex, int passIndex)
{
ref var res = ref GetTextureResource(tex);
res.lastReadPassIndex = Math.Max(passIndex, res.lastReadPassIndex);
}
ref TextureResource GetTextureResource(RenderGraphResource res)
{
return ref m_TextureResources[res.handle];
}
internal TextureDesc GetTextureResourceDesc(RenderGraphResource res)
{
return m_TextureResources[res.handle].desc;
}
internal RenderGraphResource CreateRendererList(in RendererListDesc desc)
{
ValidateRendererListDesc(desc);
int newHandle = m_RendererListResources.Add(new RendererListResource(desc));
return new RenderGraphResource(newHandle, RenderGraphResourceType.RendererList);
}
internal void CreateAndClearTexturesForPass(RenderGraphContext rgContext, int passIndex, List<RenderGraphMutableResource> textures)
{
foreach (var rgResource in textures)
{
ref var resource = ref GetTextureResource(rgResource);
if (!resource.imported && resource.firstWritePassIndex == passIndex)
{
CreateTextureForPass(ref resource);
if (resource.desc.clearBuffer || m_RenderGraphDebug.clearRenderTargetsAtCreation)
{
// Commented because string.Format causes garbage
//using (new ProfilingSample(rgContext.cmd, string.Format("RenderGraph: Clear Buffer {0}", resourceDescMoved.desc.name)))
bool debugClear = m_RenderGraphDebug.clearRenderTargetsAtCreation && !resource.desc.clearBuffer;
var name = debugClear ? "RenderGraph: Clear Buffer (Debug)" : "RenderGraph: Clear Buffer";
using (new ProfilingSample(rgContext.cmd, name))
{
var clearFlag = resource.desc.depthBufferBits != DepthBits.None ? ClearFlag.Depth : ClearFlag.Color;
var clearColor = debugClear ? Color.magenta : resource.desc.clearColor;
CoreUtils.SetRenderTarget(rgContext.cmd, resource.rt, clearFlag, clearColor);
}
}
LogTextureCreation(resource.rt, resource.desc.clearBuffer || m_RenderGraphDebug.clearRenderTargetsAtCreation);
}
}
}
void CreateTextureForPass(ref TextureResource resource)
{
var desc = resource.desc;
int hashCode = desc.GetHashCode();
if(resource.rt != null)
throw new InvalidOperationException(string.Format("Trying to create an already created texture ({0}). Texture was probably declared for writing more than once.", resource.desc.name));
resource.rt = null;
if (!TryGetRenderTarget(hashCode, out resource.rt))
{
// Note: Name used here will be the one visible in the memory profiler so it means that whatever is the first pass that actually allocate the texture will set the name.
// TODO: Find a way to display name by pass.
switch (desc.sizeMode)
{
case TextureSizeMode.Explicit:
resource.rt = m_RTHandleSystem.Alloc(desc.width, desc.height, desc.slices, desc.depthBufferBits, desc.colorFormat, desc.filterMode, desc.wrapMode, desc.dimension, desc.enableRandomWrite,
desc.useMipMap, desc.autoGenerateMips, desc.isShadowMap, desc.anisoLevel, desc.mipMapBias, desc.msaaSamples, desc.bindTextureMS, desc.useDynamicScale, desc.memoryless, desc.name);
break;
case TextureSizeMode.Scale:
resource.rt = m_RTHandleSystem.Alloc(desc.scale, desc.slices, desc.depthBufferBits, desc.colorFormat, desc.filterMode, desc.wrapMode, desc.dimension, desc.enableRandomWrite,
desc.useMipMap, desc.autoGenerateMips, desc.isShadowMap, desc.anisoLevel, desc.mipMapBias, desc.enableMSAA, desc.bindTextureMS, desc.useDynamicScale, desc.memoryless, desc.name);
break;
case TextureSizeMode.Functor:
resource.rt = m_RTHandleSystem.Alloc(desc.func, desc.slices, desc.depthBufferBits, desc.colorFormat, desc.filterMode, desc.wrapMode, desc.dimension, desc.enableRandomWrite,
desc.useMipMap, desc.autoGenerateMips, desc.isShadowMap, desc.anisoLevel, desc.mipMapBias, desc.enableMSAA, desc.bindTextureMS, desc.useDynamicScale, desc.memoryless, desc.name);
break;
}
}
//// Try to update name when re-using a texture.
//// TODO: Check if that actually works.
//resource.rt.name = desc.name;
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (hashCode != -1)
{
m_AllocatedTextures.Add((hashCode, resource.rt));
}
#endif
resource.cachedHash = hashCode;
}
void SetGlobalTextures(RenderGraphContext rgContext, List<RenderGraphResource> textures, bool bindDummyTexture)
{
foreach (var resource in textures)
{
var resourceDesc = GetTextureResource(resource);
if (resourceDesc.shaderProperty != 0)
{
if (resourceDesc.rt == null)
{
throw new InvalidOperationException(string.Format("Trying to set Global Texture parameter for \"{0}\" which was never created.\nCheck that at least one write operation happens before reading it.", resourceDesc.desc.name));
}
rgContext.cmd.SetGlobalTexture(resourceDesc.shaderProperty, bindDummyTexture ? TextureXR.GetMagentaTexture() : resourceDesc.rt);
}
}
}
internal void PreRenderPassSetGlobalTextures(RenderGraphContext rgContext, List<RenderGraphResource> textures)
{
SetGlobalTextures(rgContext, textures, false);
}
internal void PostRenderPassUnbindGlobalTextures(RenderGraphContext rgContext, List<RenderGraphResource> textures)
{
SetGlobalTextures(rgContext, textures, true);
}
internal void ReleaseTexturesForPass(RenderGraphContext rgContext, int passIndex, List<RenderGraphResource> readTextures, List<RenderGraphMutableResource> writtenTextures)
{
foreach (var resource in readTextures)
{
ref var resourceDesc = ref GetTextureResource(resource);
if (!resourceDesc.imported && resourceDesc.lastReadPassIndex == passIndex)
{
if (m_RenderGraphDebug.clearRenderTargetsAtRelease)
{
using (new ProfilingSample(rgContext.cmd, "RenderGraph: Clear Buffer (Debug)"))
{
var clearFlag = resourceDesc.desc.depthBufferBits != DepthBits.None ? ClearFlag.Depth : ClearFlag.Color;
CoreUtils.SetRenderTarget(rgContext.cmd, GetTexture(resource), clearFlag, Color.magenta);
}
}
ReleaseTextureForPass(resource);
}
}
// If a resource was created for only a single pass, we don't want users to have to declare explicitly the read operation.
// So to do that, we also update lastReadIndex on resource writes.
// This means that we need to check written resources for destruction too
foreach (var resource in writtenTextures)
{
ref var resourceDesc = ref GetTextureResource(resource);
// <= because a texture that is only declared as written in a single pass (and read implicitly in the same pass) will have the default lastReadPassIndex at -1
if (!resourceDesc.imported && resourceDesc.lastReadPassIndex <= passIndex)
{
ReleaseTextureForPass(resource);
}
}
}
void ReleaseTextureForPass(RenderGraphResource res)
{
Debug.Assert(res.type == RenderGraphResourceType.Texture);
ref var resource = ref m_TextureResources[res.handle];
// This can happen because we release texture in two passes (see ReleaseTexturesForPass) and texture can be present in both passes
if (resource.rt != null)
{
LogTextureRelease(resource.rt);
ReleaseTextureResource(resource.cachedHash, resource.rt);
resource.cachedHash = -1;
resource.rt = null;
resource.wasReleased = true;
}
}
void ReleaseTextureResource(int hash, RTHandle rt)
{
if (!m_TexturePool.TryGetValue(hash, out var stack))
{
stack = new Stack<RTHandle>();
m_TexturePool.Add(hash, stack);
}
stack.Push(rt);
#if DEVELOPMENT_BUILD || UNITY_EDITOR
m_AllocatedTextures.Remove((hash, rt));
#endif
}
void ValidateTextureDesc(in TextureDesc desc)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (desc.colorFormat == GraphicsFormat.None && desc.depthBufferBits == DepthBits.None)
{
throw new ArgumentException("Texture was created with an invalid color format.");
}
if (desc.dimension == TextureDimension.None)
{
throw new ArgumentException("Texture was created with an invalid texture dimension.");
}
if (desc.slices == 0)
{
throw new ArgumentException("Texture was created with a slices parameter value of zero.");
}
if (desc.sizeMode == TextureSizeMode.Explicit)
{
if (desc.width == 0 || desc.height == 0)
throw new ArgumentException("Texture using Explicit size mode was create with either width or height at zero.");
if (desc.enableMSAA)
throw new ArgumentException("enableMSAA TextureDesc parameter is not supported for textures using Explicit size mode.");
}
if (desc.sizeMode == TextureSizeMode.Scale || desc.sizeMode == TextureSizeMode.Functor)
{
if (desc.msaaSamples != MSAASamples.None)
throw new ArgumentException("msaaSamples TextureDesc parameter is not supported for textures using Scale or Functor size mode.");
}
#endif
}
void ValidateRendererListDesc(in RendererListDesc desc)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (desc.passName != ShaderTagId.none && desc.passNames != null
|| desc.passName == ShaderTagId.none && desc.passNames == null)
{
throw new ArgumentException("Renderer List creation descriptor must contain either a single passName or an array of passNames.");
}
if (desc.renderQueueRange.lowerBound == 0 && desc.renderQueueRange.upperBound == 0)
{
throw new ArgumentException("Renderer List creation descriptor must have a valid RenderQueueRange.");
}
if (desc.camera == null)
{
throw new ArgumentException("Renderer List creation descriptor must have a valid Camera.");
}
#endif
}
bool TryGetRenderTarget(int hashCode, out RTHandle rt)
{
if (m_TexturePool.TryGetValue(hashCode, out var stack) && stack.Count > 0)
{
rt = stack.Pop();
return true;
}
rt = null;
return false;
}
internal void CreateRendererLists(List<RenderGraphResource> rendererLists)
{
// For now we just create a simple structure
// but when the proper API is available in trunk we'll kick off renderer lists creation jobs here.
foreach (var rendererList in rendererLists)
{
Debug.Assert(rendererList.type == RenderGraphResourceType.RendererList);
ref var rendererListResource = ref m_RendererListResources[rendererList.handle];
ref var desc = ref rendererListResource.desc;
RendererList newRendererList = RendererList.Create(desc);
rendererListResource.rendererList = newRendererList;
}
}
internal void Clear()
{
LogResources();
m_TextureResources.Clear();
m_RendererListResources.Clear();
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (m_AllocatedTextures.Count != 0)
{
Debug.LogWarning("RenderGraph: Not all textures were released.");
List<(int, RTHandle)> tempList = new List<(int, RTHandle)>(m_AllocatedTextures);
foreach (var value in tempList)
{
ReleaseTextureResource(value.Item1, value.Item2);
}
}
#endif
}
internal void Cleanup()
{
foreach (var value in m_TexturePool)
{
foreach (var rt in value.Value)
{
m_RTHandleSystem.Release(rt);
}
}
}
void LogTextureCreation(RTHandle rt, bool cleared)
{
if (m_RenderGraphDebug.logFrameInformation)
{
m_Logger.LogLine("Created Texture: {0} (Cleared: {1})", rt.rt.name, cleared);
}
}
void LogTextureRelease(RTHandle rt)
{
if (m_RenderGraphDebug.logFrameInformation)
{
m_Logger.LogLine("Released Texture: {0}", rt.rt.name);
}
}
void LogResources()
{
if (m_RenderGraphDebug.logResources)
{
m_Logger.LogLine("==== Allocated Resources ====\n");
List<string> allocationList = new List<string>();
foreach (var stack in m_TexturePool)
{
foreach (var rt in stack.Value)
{
allocationList.Add(rt.rt.name);
}
}
allocationList.Sort();
int index = 0;
foreach (var element in allocationList)
m_Logger.LogLine("[{0}] {1}", index++, element);
}
}
#endregion
}
}
| 44.030726 | 247 | 0.573907 | [
"MIT"
] | MusouCrow/CustomShaderGraph | Packages/com.unity.render-pipelines.core@7.1.8/Runtime/RenderGraph/RenderGraphResourceRegistry.cs | 31,526 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using mrHelper.Common.Constants;
using mrHelper.Common.Interfaces;
using mrHelper.Common.Tools;
namespace mrHelper.App.Helpers
{
public struct ParsedNewMergeRequestUrl
{
public ParsedNewMergeRequestUrl(ProjectKey projectKey, string sourceBranch,
IEnumerable<string> targetBranchCandidates)
{
ProjectKey = projectKey;
SourceBranch = sourceBranch;
TargetBranchCandidates = targetBranchCandidates;
}
public ProjectKey ProjectKey { get; }
public string SourceBranch { get; }
public IEnumerable<string> TargetBranchCandidates { get; }
}
/// <summary>
/// <summary>
public static class NewMergeRequestUrlParser
{
public static readonly string RegEx =
@"create\/mr" +
@"\?(?:Repository\=(?'Repository'.*))" +
@"\&(?:SourceBranch\=(?'SourceBranch'[\w_\-\/]+))";
static readonly int MaxUrlLength = 512;
private static readonly Regex url_re = new Regex(RegEx, RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// Splits passed url in parts and stores in object properties
/// <summary>
public static ParsedNewMergeRequestUrl Parse(string url)
{
if (url.Length > MaxUrlLength)
{
throw new UriFormatException("Too long URL");
}
Match m = url_re.Match(url);
if (!m.Success)
{
throw new UriFormatException("Failed to parse URL");
}
Group path = m.Groups["Repository"];
Group sourceBranch = m.Groups["SourceBranch"];
if (!path.Success || !sourceBranch.Success)
{
throw new UriFormatException("Unsupported URL format");
}
ProjectKey? projectKey = GitTools.GetRepositoryProjectKey(path.Value);
if (!projectKey.HasValue)
{
throw new UriFormatException(String.Format("\"{0}\" is not a git repository", path.Value));
}
// sourceBranch can be one of the following:
// - br_foo
// - origin/br_foo
// - 53ff02a
// Resolve all these cases to origin/br_foo here.
string remoteSourceBranch = getRemoteSourceBranch(path.Value, sourceBranch.Value);
if (String.IsNullOrEmpty(remoteSourceBranch))
{
throw new UriFormatException(String.Format("\"{0}\" does not point to a remote branch", sourceBranch.Value));
}
string sourceBranchName = trimRemoteOrigin(remoteSourceBranch);
IEnumerable<string> targetBranchName = findTargetBranch(path.Value, remoteSourceBranch)
.Select(fullName => trimRemoteOrigin(fullName));
return new ParsedNewMergeRequestUrl(projectKey.Value, sourceBranchName, targetBranchName);
}
private static string getRemoteSourceBranch(string path, string sourceBranch)
{
IEnumerable<string> refs = GitTools.GetRemotePointsAt(path, sourceBranch);
return refs?.FirstOrDefault();
}
private static IEnumerable<string> findTargetBranch(string path, string remoteSourceBranch)
{
for (int iDepth = 0; iDepth < Constants.MaxCommitDepth; ++iDepth)
{
string sha = String.Format("{0}{1}", remoteSourceBranch, new string('^', iDepth));
IEnumerable<string> refs = GitTools.GetRemotePointsAt(path, sha)
.Where(x => x != remoteSourceBranch)
.Where(x => x != String.Format("{0}HEAD", RemoteOrigin));
if (refs.Any())
{
return refs;
}
}
return new string[] { String.Format("{0}master", RemoteOrigin) };
}
private static string trimRemoteOrigin(string name)
{
Debug.Assert(name.StartsWith(RemoteOrigin));
return name.Substring(RemoteOrigin.Length);
}
private static readonly string RemoteOrigin = "origin/";
}
}
| 34.846154 | 121 | 0.628894 | [
"MIT"
] | denis-adamchuk/mrHelper | src/App/src/Helpers/Url/NewMergeRequestUrlParser.cs | 4,079 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Nest
{
/// <summary>
/// The Allocate action allows you to specify which nodes are allowed to host the shards of the index and set the number of
/// replicas. Behind the scenes, it is modifying the index settings for shard filtering and/or replica counts. When
/// updating the number of replicas, configuring allocation rules is optional. When configuring allocation rules, setting
/// number of replicas is optional. Although this action can be treated as two separate index settings updates, both can be
/// configured at once.
/// </summary>
public interface IAllocateLifecycleAction : ILifecycleAction
{
/// <summary>
/// Assigns an index to nodes having none of the attributes
/// </summary>
[DataMember(Name = "exclude")]
IDictionary<string, string> Exclude { get; set; }
/// <summary>
/// Assigns an index to nodes having at least one of the attributes
/// </summary>
[DataMember(Name = "include")]
IDictionary<string, string> Include { get; set; }
/// <summary>
/// The number of replicas to assign to the index
/// </summary>
[DataMember(Name = "number_of_replicas")]
int? NumberOfReplicas { get; set; }
/// <summary>
/// Assigns an index to nodes having all of the attributes
/// </summary>
[DataMember(Name = "require")]
IDictionary<string, string> Require { get; set; }
}
public class AllocateLifecycleAction : IAllocateLifecycleAction
{
/// <inheritdoc />
public IDictionary<string, string> Exclude { get; set; }
/// <inheritdoc />
public IDictionary<string, string> Include { get; set; }
/// <inheritdoc />
public int? NumberOfReplicas { get; set; }
/// <inheritdoc />
public IDictionary<string, string> Require { get; set; }
}
public class AllocateLifecycleActionDescriptor
: DescriptorBase<AllocateLifecycleActionDescriptor, IAllocateLifecycleAction>, IAllocateLifecycleAction
{
/// <inheritdoc cref="IAllocateLifecycleAction.Exclude" />
IDictionary<string, string> IAllocateLifecycleAction.Exclude { get; set; }
/// <inheritdoc cref="IAllocateLifecycleAction.Include" />
IDictionary<string, string> IAllocateLifecycleAction.Include { get; set; }
/// <inheritdoc cref="IAllocateLifecycleAction.NumberOfReplicas" />
int? IAllocateLifecycleAction.NumberOfReplicas { get; set; }
/// <inheritdoc cref="IAllocateLifecycleAction.Require" />
IDictionary<string, string> IAllocateLifecycleAction.Require { get; set; }
/// <inheritdoc cref="IAllocateLifecycleAction.NumberOfReplicas" />
public AllocateLifecycleActionDescriptor NumberOfReplicas(int? numberOfReplicas)
=> Assign(numberOfReplicas, (a, v) => a.NumberOfReplicas = numberOfReplicas);
/// <inheritdoc cref="IAllocateLifecycleAction.Include" />
public AllocateLifecycleActionDescriptor Include(Func<FluentDictionary<string, string>, FluentDictionary<string, string>> includeSelector) =>
Assign(includeSelector(new FluentDictionary<string, string>()), (a, v) => a.Include = v);
/// <inheritdoc cref="IAllocateLifecycleAction.Exclude" />
public AllocateLifecycleActionDescriptor Exclude(Func<FluentDictionary<string, string>, FluentDictionary<string, string>> excludeSelector) =>
Assign(excludeSelector(new FluentDictionary<string, string>()), (a, v) => a.Exclude = v);
/// <inheritdoc cref="IAllocateLifecycleAction.Require" />
public AllocateLifecycleActionDescriptor Require(Func<FluentDictionary<string, string>, FluentDictionary<string, string>> requireSelector) =>
Assign(requireSelector(new FluentDictionary<string, string>()), (a, v) => a.Require = v);
}
}
| 42.01087 | 143 | 0.740492 | [
"Apache-2.0"
] | Atharvpatel21/elasticsearch-net | src/Nest/XPack/Ilm/Actions/AllocateAction.cs | 3,865 | C# |
using System;
using ashley.Utils;
namespace ashley.Core
{
public class ComponentOperationHandler
{
private IBooleanInformer _delayedInformer;
private Pool<ComponentOperation> _operationPool = new Pool<ComponentOperation>(() => new ComponentOperation());
private Bag<ComponentOperation> _operations = new Bag<ComponentOperation>();
public ComponentOperationHandler(IBooleanInformer delayedInformer)
{
_delayedInformer = delayedInformer;
}
public void Add(Entity entity)
{
if (_delayedInformer.Value)
{
var operation = _operationPool.Obtain();
operation.MakeAdd(entity);
_operations.Add(operation);
}
else
{
entity.OnComponentAdded();
}
}
public void Remove(Entity entity)
{
if (_delayedInformer.Value)
{
var operation = _operationPool.Obtain();
operation.MakeRemove(entity);
_operations.Add(operation);
}
else
{
entity.OnComponentRemoved();
}
}
public bool HasOperationsToProcess => _operations.Size > 0;
public void ProcessOperations()
{
foreach (var operation in _operations)
{
switch (operation.Type)
{
case ComponentOperationType.Add:
operation.Entity.OnComponentAdded();
break;
case ComponentOperationType.Remove:
operation.Entity.OnComponentRemoved();
break;
default:
throw new ArgumentOutOfRangeException();
}
_operationPool.Free(operation);
}
_operations.Clear();
}
}
} | 29 | 119 | 0.510745 | [
"Apache-2.0"
] | dresswithpockets/ashley | ashley/Core/ComponentOperationHandler.cs | 2,003 | C# |
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace DurandalAuth.Domain.Models.Mapping
{
public class otMap : EntityTypeConfiguration<ot>
{
public otMap()
{
// Primary Key
this.HasKey(t => t.ot_id);
// Properties
this.Property(t => t.bl_id)
.IsFixedLength()
.HasMaxLength(8);
this.Property(t => t.comments)
.HasMaxLength(2000);
this.Property(t => t.description)
.IsFixedLength()
.HasMaxLength(64);
this.Property(t => t.option1)
.IsFixedLength()
.HasMaxLength(16);
this.Property(t => t.option2)
.IsFixedLength()
.HasMaxLength(16);
this.Property(t => t.pr_id)
.IsFixedLength()
.HasMaxLength(16);
this.Property(t => t.status)
.IsFixedLength()
.HasMaxLength(8);
// Table & Column Mappings
this.ToTable("ot", "afm");
this.Property(t => t.bl_id).HasColumnName("bl_id");
this.Property(t => t.comments).HasColumnName("comments");
this.Property(t => t.cost_purchase).HasColumnName("cost_purchase");
this.Property(t => t.cost_selling).HasColumnName("cost_selling");
this.Property(t => t.date_purchase).HasColumnName("date_purchase");
this.Property(t => t.date_sold).HasColumnName("date_sold");
this.Property(t => t.description).HasColumnName("description");
this.Property(t => t.option1).HasColumnName("option1");
this.Property(t => t.option2).HasColumnName("option2");
this.Property(t => t.pr_id).HasColumnName("pr_id");
this.Property(t => t.status).HasColumnName("status");
this.Property(t => t.ot_id).HasColumnName("ot_id");
// Relationships
this.HasOptional(t => t.bl)
.WithMany(t => t.ots)
.HasForeignKey(d => d.bl_id);
this.HasOptional(t => t.property)
.WithMany(t => t.ots)
.HasForeignKey(d => d.pr_id);
}
}
}
| 34.402985 | 79 | 0.529718 | [
"MIT"
] | benitazz/AlcmSolutions | DurandalAuth.Domain/Models/Mapping/otMap.cs | 2,305 | C# |
using System.Collections.Generic;
namespace Kata.CustomTypes.MenuFactory
{
public abstract class MenuBase
{
// 1. backing store for the list of items
private List<MenuItemBase> items = new List<MenuItemBase>();
// 2. readonly property to access the backing store
public List<MenuItemBase> Items { get { return items; } }
// 3. constructor to call the Factory Method
public MenuBase()
{
this.CreateMenuItems();
}
// 4. definition of the factory method which all children must implement.
protected abstract void CreateMenuItems();
}
}
| 27.458333 | 81 | 0.622155 | [
"MIT"
] | contino/dotnet-training-course | Kata/CustomTypes/AdHoc/MenuFactory/MenuBase.cs | 661 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Domain
{
/// <summary>
/// KoubeiMarketingCampaignMemberRelationCreateModel Data Structure.
/// </summary>
public class KoubeiMarketingCampaignMemberRelationCreateModel : AlipayObject
{
/// <summary>
/// 会员开通时间
/// </summary>
[JsonPropertyName("activate_time")]
public string ActivateTime { get; set; }
/// <summary>
/// token
/// </summary>
[JsonPropertyName("auth_token")]
public string AuthToken { get; set; }
/// <summary>
/// 余额
/// </summary>
[JsonPropertyName("balance")]
public string Balance { get; set; }
/// <summary>
/// 生日
/// </summary>
[JsonPropertyName("birth")]
public string Birth { get; set; }
/// <summary>
/// 手机号
/// </summary>
[JsonPropertyName("cell")]
public string Cell { get; set; }
/// <summary>
/// 会员过期时间
/// </summary>
[JsonPropertyName("end_time")]
public string EndTime { get; set; }
/// <summary>
/// 性别
/// </summary>
[JsonPropertyName("gender")]
public string Gender { get; set; }
/// <summary>
/// 会员等级
/// </summary>
[JsonPropertyName("level")]
public long Level { get; set; }
/// <summary>
/// 会员模版id
/// </summary>
[JsonPropertyName("member_template_id")]
public string MemberTemplateId { get; set; }
/// <summary>
/// 商户外部会员号
/// </summary>
[JsonPropertyName("out_member_no")]
public string OutMemberNo { get; set; }
/// <summary>
/// 积分
/// </summary>
[JsonPropertyName("point")]
public string Point { get; set; }
/// <summary>
/// 外部请求幂等号
/// </summary>
[JsonPropertyName("request_id")]
public string RequestId { get; set; }
/// <summary>
/// 会员开始时间
/// </summary>
[JsonPropertyName("start_time")]
public string StartTime { get; set; }
/// <summary>
/// 用户id
/// </summary>
[JsonPropertyName("user_id")]
public string UserId { get; set; }
/// <summary>
/// 姓名
/// </summary>
[JsonPropertyName("user_name")]
public string UserName { get; set; }
}
}
| 24.792079 | 80 | 0.497604 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Domain/KoubeiMarketingCampaignMemberRelationCreateModel.cs | 2,616 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace WebAppExample.Migrations
{
public partial class Intial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Categories",
columns: table => new
{
CategoryId = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Categories", x => x.CategoryId);
});
migrationBuilder.CreateTable(
name: "Suppliers",
columns: table => new
{
SupplierId = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
City = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Suppliers", x => x.SupplierId);
});
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
ProductId = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
Price = table.Column<decimal>(type: "decimal(8,2)", nullable: false),
CategoryId = table.Column<long>(type: "bigint", nullable: false),
SupplierId = table.Column<long>(type: "bigint", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.ProductId);
table.ForeignKey(
name: "FK_Products_Categories_CategoryId",
column: x => x.CategoryId,
principalTable: "Categories",
principalColumn: "CategoryId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Products_Suppliers_SupplierId",
column: x => x.SupplierId,
principalTable: "Suppliers",
principalColumn: "SupplierId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Products_CategoryId",
table: "Products",
column: "CategoryId");
migrationBuilder.CreateIndex(
name: "IX_Products_SupplierId",
table: "Products",
column: "SupplierId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Products");
migrationBuilder.DropTable(
name: "Categories");
migrationBuilder.DropTable(
name: "Suppliers");
}
}
}
| 39.886364 | 89 | 0.482621 | [
"MIT"
] | Deftextra/WebAppExample | Migrations/20201117223637_Intial.cs | 3,512 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BasicallyMe.RobinhoodNet
{
public class MarginBalance : Balance
{
internal MarginBalance(Newtonsoft.Json.Linq.JToken json)
{
this.CreatedAt = (DateTime)json["created_at"];
this.UpdatedAt = (DateTime)json["updated_at"];
this.CashHeldForOrders = (decimal)json["cash_held_for_orders"];
this.Cash = (decimal)json["cash"];
this.BuyingPower = (decimal)json["day_trade_buying_power"];
this.CashAvailableForWithdrawal = (decimal)json["cash_available_for_withdrawal"];
this.UnclearedDeposits = (decimal)json["uncleared_deposits"];
//this.UnsettledFunds = (decimal)json["unsettled_funds"];
}
}
}
| 27.777778 | 84 | 0.752 | [
"MIT"
] | MeetHassan/Stocks4All | RobinhoodNet/MarginBalance.cs | 752 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Core.Models.Chats
{
public class Chat
{
[Key]
public string Id { get; set; }
public bool IsNewMessage { get; set; }
public DateTime CreatedAt { get; set; }
public int SupplierCompanyId { get; set; }
public virtual SupplierCompany SupplierCompany { get; set; }
public int RequestId { get; set; }
public virtual Request Request { get; set; }
public virtual ICollection<Message> Messages { get; set; }
}
}
| 25.571429 | 68 | 0.674581 | [
"MIT"
] | behluluysal/fibu-app-demo | WebAPICore/Core/Models/Chats/Chat.cs | 718 | 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.DataFactory.Inputs
{
/// <summary>
/// A copy activity Salesforce sink.
/// </summary>
public sealed class SalesforceSinkArgs : Pulumi.ResourceArgs
{
/// <summary>
/// If true, disable data store metrics collection. Default is false. Type: boolean (or Expression with resultType boolean).
/// </summary>
[Input("disableMetricsCollection")]
public Input<object>? DisableMetricsCollection { get; set; }
/// <summary>
/// The name of the external ID field for upsert operation. Default value is 'Id' column. Type: string (or Expression with resultType string).
/// </summary>
[Input("externalIdFieldName")]
public Input<object>? ExternalIdFieldName { get; set; }
/// <summary>
/// The flag indicating whether or not to ignore null values from input dataset (except key fields) during write operation. Default value is false. If set it to true, it means ADF will leave the data in the destination object unchanged when doing upsert/update operation and insert defined default value when doing insert operation, versus ADF will update the data in the destination object to NULL when doing upsert/update operation and insert NULL value when doing insert operation. Type: boolean (or Expression with resultType boolean).
/// </summary>
[Input("ignoreNullValues")]
public Input<object>? IgnoreNullValues { get; set; }
/// <summary>
/// The maximum concurrent connection count for the sink data store. Type: integer (or Expression with resultType integer).
/// </summary>
[Input("maxConcurrentConnections")]
public Input<object>? MaxConcurrentConnections { get; set; }
/// <summary>
/// Sink retry count. Type: integer (or Expression with resultType integer).
/// </summary>
[Input("sinkRetryCount")]
public Input<object>? SinkRetryCount { get; set; }
/// <summary>
/// Sink retry wait. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
/// </summary>
[Input("sinkRetryWait")]
public Input<object>? SinkRetryWait { get; set; }
/// <summary>
/// Copy sink type.
/// Expected value is 'SalesforceSink'.
/// </summary>
[Input("type", required: true)]
public Input<string> Type { get; set; } = null!;
/// <summary>
/// Write batch size. Type: integer (or Expression with resultType integer), minimum: 0.
/// </summary>
[Input("writeBatchSize")]
public Input<object>? WriteBatchSize { get; set; }
/// <summary>
/// Write batch timeout. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
/// </summary>
[Input("writeBatchTimeout")]
public Input<object>? WriteBatchTimeout { get; set; }
/// <summary>
/// The write behavior for the operation. Default is Insert.
/// </summary>
[Input("writeBehavior")]
public InputUnion<string, Pulumi.AzureNative.DataFactory.SalesforceSinkWriteBehavior>? WriteBehavior { get; set; }
public SalesforceSinkArgs()
{
}
}
}
| 43.607143 | 547 | 0.630631 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/DataFactory/Inputs/SalesforceSinkArgs.cs | 3,663 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
#if HAVE_REFLECTION_EMIT
using System;
using System.Collections.Generic;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#endif
using System.Reflection;
using System.Reflection.Emit;
using Newtonsoft.Json.Serialization;
using System.Globalization;
namespace Newtonsoft.Json.Utilities
{
internal class DynamicReflectionDelegateFactory : ReflectionDelegateFactory
{
internal static DynamicReflectionDelegateFactory Instance { get; } =
new DynamicReflectionDelegateFactory();
private static DynamicMethod CreateDynamicMethod(
string name,
Type? returnType,
Type[] parameterTypes,
Type owner
)
{
DynamicMethod dynamicMethod = !owner.IsInterface()
? new DynamicMethod(name, returnType, parameterTypes, owner, true)
: new DynamicMethod(name, returnType, parameterTypes, owner.Module, true);
return dynamicMethod;
}
public override ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method)
{
DynamicMethod dynamicMethod = CreateDynamicMethod(
method.ToString(),
typeof(object),
new[] { typeof(object[]) },
method.DeclaringType
);
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateMethodCallIL(method, generator, 0);
return (ObjectConstructor<object>)dynamicMethod.CreateDelegate(
typeof(ObjectConstructor<object>)
);
}
public override MethodCall<T, object?> CreateMethodCall<T>(MethodBase method)
{
DynamicMethod dynamicMethod = CreateDynamicMethod(
method.ToString(),
typeof(object),
new[] { typeof(object), typeof(object[]) },
method.DeclaringType
);
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateMethodCallIL(method, generator, 1);
return (MethodCall<T, object?>)dynamicMethod.CreateDelegate(
typeof(MethodCall<T, object?>)
);
}
private void GenerateCreateMethodCallIL(
MethodBase method,
ILGenerator generator,
int argsIndex
)
{
ParameterInfo[] args = method.GetParameters();
Label argsOk = generator.DefineLabel();
// throw an error if the number of argument values doesn't match method parameters
generator.Emit(OpCodes.Ldarg, argsIndex);
generator.Emit(OpCodes.Ldlen);
generator.Emit(OpCodes.Ldc_I4, args.Length);
generator.Emit(OpCodes.Beq, argsOk);
generator.Emit(
OpCodes.Newobj,
typeof(TargetParameterCountException).GetConstructor(ReflectionUtils.EmptyTypes)
);
generator.Emit(OpCodes.Throw);
generator.MarkLabel(argsOk);
if (!method.IsConstructor && !method.IsStatic)
{
generator.PushInstance(method.DeclaringType);
}
LocalBuilder localConvertible = generator.DeclareLocal(typeof(IConvertible));
LocalBuilder localObject = generator.DeclareLocal(typeof(object));
OpCode variableAddressOpCode = args.Length < 256 ? OpCodes.Ldloca_S : OpCodes.Ldloca;
OpCode variableLoadOpCode = args.Length < 256 ? OpCodes.Ldloc_S : OpCodes.Ldloc;
for (int i = 0; i < args.Length; i++)
{
ParameterInfo parameter = args[i];
Type parameterType = parameter.ParameterType;
if (parameterType.IsByRef)
{
parameterType = parameterType.GetElementType();
LocalBuilder localVariable = generator.DeclareLocal(parameterType);
// don't need to set variable for 'out' parameter
if (!parameter.IsOut)
{
generator.PushArrayInstance(argsIndex, i);
if (parameterType.IsValueType())
{
Label skipSettingDefault = generator.DefineLabel();
Label finishedProcessingParameter = generator.DefineLabel();
// check if parameter is not null
generator.Emit(OpCodes.Brtrue_S, skipSettingDefault);
// parameter has no value, initialize to default
generator.Emit(variableAddressOpCode, localVariable);
generator.Emit(OpCodes.Initobj, parameterType);
generator.Emit(OpCodes.Br_S, finishedProcessingParameter);
// parameter has value, get value from array again and unbox and set to variable
generator.MarkLabel(skipSettingDefault);
generator.PushArrayInstance(argsIndex, i);
generator.UnboxIfNeeded(parameterType);
generator.Emit(OpCodes.Stloc_S, localVariable);
// parameter finished, we out!
generator.MarkLabel(finishedProcessingParameter);
}
else
{
generator.UnboxIfNeeded(parameterType);
generator.Emit(OpCodes.Stloc_S, localVariable);
}
}
generator.Emit(variableAddressOpCode, localVariable);
}
else if (parameterType.IsValueType())
{
generator.PushArrayInstance(argsIndex, i);
generator.Emit(OpCodes.Stloc_S, localObject);
// have to check that value type parameters aren't null
// otherwise they will error when unboxed
Label skipSettingDefault = generator.DefineLabel();
Label finishedProcessingParameter = generator.DefineLabel();
// check if parameter is not null
generator.Emit(OpCodes.Ldloc_S, localObject);
generator.Emit(OpCodes.Brtrue_S, skipSettingDefault);
// parameter has no value, initialize to default
LocalBuilder localVariable = generator.DeclareLocal(parameterType);
generator.Emit(variableAddressOpCode, localVariable);
generator.Emit(OpCodes.Initobj, parameterType);
generator.Emit(variableLoadOpCode, localVariable);
generator.Emit(OpCodes.Br_S, finishedProcessingParameter);
// argument has value, try to convert it to parameter type
generator.MarkLabel(skipSettingDefault);
if (parameterType.IsPrimitive())
{
// for primitive types we need to handle type widening (e.g. short -> int)
MethodInfo toParameterTypeMethod = typeof(IConvertible).GetMethod(
"To" + parameterType.Name,
new[] { typeof(IFormatProvider) }
);
if (toParameterTypeMethod != null)
{
Label skipConvertible = generator.DefineLabel();
// check if argument type is an exact match for parameter type
// in this case we may use cheap unboxing instead
generator.Emit(OpCodes.Ldloc_S, localObject);
generator.Emit(OpCodes.Isinst, parameterType);
generator.Emit(OpCodes.Brtrue_S, skipConvertible);
// types don't match, check if argument implements IConvertible
generator.Emit(OpCodes.Ldloc_S, localObject);
generator.Emit(OpCodes.Isinst, typeof(IConvertible));
generator.Emit(OpCodes.Stloc_S, localConvertible);
generator.Emit(OpCodes.Ldloc_S, localConvertible);
generator.Emit(OpCodes.Brfalse_S, skipConvertible);
// convert argument to parameter type
generator.Emit(OpCodes.Ldloc_S, localConvertible);
generator.Emit(OpCodes.Ldnull);
generator.Emit(OpCodes.Callvirt, toParameterTypeMethod);
generator.Emit(OpCodes.Br_S, finishedProcessingParameter);
generator.MarkLabel(skipConvertible);
}
}
// we got here because either argument type matches parameter (conversion will succeed),
// or argument type doesn't match parameter, but we're out of options (conversion will fail)
generator.Emit(OpCodes.Ldloc_S, localObject);
generator.UnboxIfNeeded(parameterType);
// parameter finished, we out!
generator.MarkLabel(finishedProcessingParameter);
}
else
{
generator.PushArrayInstance(argsIndex, i);
generator.UnboxIfNeeded(parameterType);
}
}
if (method.IsConstructor)
{
generator.Emit(OpCodes.Newobj, (ConstructorInfo)method);
}
else
{
generator.CallMethod((MethodInfo)method);
}
Type returnType = method.IsConstructor
? method.DeclaringType
: ((MethodInfo)method).ReturnType;
if (returnType != typeof(void))
{
generator.BoxIfNeeded(returnType);
}
else
{
generator.Emit(OpCodes.Ldnull);
}
generator.Return();
}
public override Func<T> CreateDefaultConstructor<T>(Type type)
{
DynamicMethod dynamicMethod = CreateDynamicMethod(
"Create" + type.FullName,
typeof(T),
ReflectionUtils.EmptyTypes,
type
);
dynamicMethod.InitLocals = true;
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateDefaultConstructorIL(type, generator, typeof(T));
return (Func<T>)dynamicMethod.CreateDelegate(typeof(Func<T>));
}
private void GenerateCreateDefaultConstructorIL(
Type type,
ILGenerator generator,
Type delegateType
)
{
if (type.IsValueType())
{
generator.DeclareLocal(type);
generator.Emit(OpCodes.Ldloc_0);
// only need to box if the delegate isn't returning the value type
if (type != delegateType)
{
generator.Emit(OpCodes.Box, type);
}
}
else
{
ConstructorInfo constructorInfo = type.GetConstructor(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
null,
ReflectionUtils.EmptyTypes,
null
);
if (constructorInfo == null)
{
throw new ArgumentException(
"Could not get constructor for {0}.".FormatWith(
CultureInfo.InvariantCulture,
type
)
);
}
generator.Emit(OpCodes.Newobj, constructorInfo);
}
generator.Return();
}
public override Func<T, object?> CreateGet<T>(PropertyInfo propertyInfo)
{
DynamicMethod dynamicMethod = CreateDynamicMethod(
"Get" + propertyInfo.Name,
typeof(object),
new[] { typeof(T) },
propertyInfo.DeclaringType
);
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateGetPropertyIL(propertyInfo, generator);
return (Func<T, object?>)dynamicMethod.CreateDelegate(typeof(Func<T, object?>));
}
private void GenerateCreateGetPropertyIL(PropertyInfo propertyInfo, ILGenerator generator)
{
MethodInfo getMethod = propertyInfo.GetGetMethod(true);
if (getMethod == null)
{
throw new ArgumentException(
"Property '{0}' does not have a getter.".FormatWith(
CultureInfo.InvariantCulture,
propertyInfo.Name
)
);
}
if (!getMethod.IsStatic)
{
generator.PushInstance(propertyInfo.DeclaringType);
}
generator.CallMethod(getMethod);
generator.BoxIfNeeded(propertyInfo.PropertyType);
generator.Return();
}
public override Func<T, object?> CreateGet<T>(FieldInfo fieldInfo)
{
if (fieldInfo.IsLiteral)
{
object constantValue = fieldInfo.GetValue(null);
Func<T, object?> getter = o => constantValue;
return getter;
}
DynamicMethod dynamicMethod = CreateDynamicMethod(
"Get" + fieldInfo.Name,
typeof(T),
new[] { typeof(object) },
fieldInfo.DeclaringType
);
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateGetFieldIL(fieldInfo, generator);
return (Func<T, object?>)dynamicMethod.CreateDelegate(typeof(Func<T, object?>));
}
private void GenerateCreateGetFieldIL(FieldInfo fieldInfo, ILGenerator generator)
{
if (!fieldInfo.IsStatic)
{
generator.PushInstance(fieldInfo.DeclaringType);
generator.Emit(OpCodes.Ldfld, fieldInfo);
}
else
{
generator.Emit(OpCodes.Ldsfld, fieldInfo);
}
generator.BoxIfNeeded(fieldInfo.FieldType);
generator.Return();
}
public override Action<T, object?> CreateSet<T>(FieldInfo fieldInfo)
{
DynamicMethod dynamicMethod = CreateDynamicMethod(
"Set" + fieldInfo.Name,
null,
new[] { typeof(T), typeof(object) },
fieldInfo.DeclaringType
);
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateSetFieldIL(fieldInfo, generator);
return (Action<T, object?>)dynamicMethod.CreateDelegate(typeof(Action<T, object?>));
}
internal static void GenerateCreateSetFieldIL(FieldInfo fieldInfo, ILGenerator generator)
{
if (!fieldInfo.IsStatic)
{
generator.PushInstance(fieldInfo.DeclaringType);
}
generator.Emit(OpCodes.Ldarg_1);
generator.UnboxIfNeeded(fieldInfo.FieldType);
if (!fieldInfo.IsStatic)
{
generator.Emit(OpCodes.Stfld, fieldInfo);
}
else
{
generator.Emit(OpCodes.Stsfld, fieldInfo);
}
generator.Return();
}
public override Action<T, object?> CreateSet<T>(PropertyInfo propertyInfo)
{
DynamicMethod dynamicMethod = CreateDynamicMethod(
"Set" + propertyInfo.Name,
null,
new[] { typeof(T), typeof(object) },
propertyInfo.DeclaringType
);
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateSetPropertyIL(propertyInfo, generator);
return (Action<T, object?>)dynamicMethod.CreateDelegate(typeof(Action<T, object>));
}
internal static void GenerateCreateSetPropertyIL(
PropertyInfo propertyInfo,
ILGenerator generator
)
{
MethodInfo setMethod = propertyInfo.GetSetMethod(true);
if (!setMethod.IsStatic)
{
generator.PushInstance(propertyInfo.DeclaringType);
}
generator.Emit(OpCodes.Ldarg_1);
generator.UnboxIfNeeded(propertyInfo.PropertyType);
generator.CallMethod(setMethod);
generator.Return();
}
}
}
#endif
| 38.210856 | 112 | 0.550019 | [
"MIT"
] | belav/Newtonsoft.Json | Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs | 18,305 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// NullableDecimalAverageAggregationOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// An inlined average aggregation operator and its enumerator, for Nullable decimals.
/// </summary>
internal sealed class NullableDecimalAverageAggregationOperator : InlinedAggregationOperator<decimal?, Pair<decimal, long>, decimal?>
{
//---------------------------------------------------------------------------------------
// Constructs a new instance of an average associative operator.
//
internal NullableDecimalAverageAggregationOperator(IEnumerable<decimal?> child) : base(child)
{
}
//---------------------------------------------------------------------------------------
// Executes the entire query tree, and aggregates the intermediate results into the
// final result based on the binary operators and final reduction.
//
// Return Value:
// The single result of aggregation.
//
protected override decimal? InternalAggregate(ref Exception singularExceptionToThrow)
{
// Because the final reduction is typically much cheaper than the intermediate
// reductions over the individual partitions, and because each parallel partition
// will do a lot of work to produce a single output element, we prefer to turn off
// pipelining, and process the final reductions serially.
using (IEnumerator<Pair<decimal, long>> enumerator = GetEnumerator(ParallelMergeOptions.FullyBuffered, true))
{
// If the sequence was empty, return null right away.
if (!enumerator.MoveNext())
{
return null;
}
Pair<decimal, long> result = enumerator.Current;
// Simply add together the sums and totals.
while (enumerator.MoveNext())
{
checked
{
result.First += enumerator.Current.First;
result.Second += enumerator.Current.Second;
}
}
// And divide the sum by the total to obtain the final result.
return result.First / result.Second;
}
}
//---------------------------------------------------------------------------------------
// Creates an enumerator that is used internally for the final aggregation step.
//
protected override QueryOperatorEnumerator<Pair<decimal, long>, int> CreateEnumerator<TKey>(
int index, int count, QueryOperatorEnumerator<decimal?, TKey> source, object sharedData, CancellationToken cancellationToken)
{
return new NullableDecimalAverageAggregationOperatorEnumerator<TKey>(source, index, cancellationToken);
}
//---------------------------------------------------------------------------------------
// This enumerator type encapsulates the intermediary aggregation over the underlying
// (possibly partitioned) data source.
//
private class NullableDecimalAverageAggregationOperatorEnumerator<TKey> : InlinedAggregationOperatorEnumerator<Pair<decimal, long>>
{
private QueryOperatorEnumerator<decimal?, TKey> _source; // The source data.
//---------------------------------------------------------------------------------------
// Instantiates a new aggregation operator.
//
internal NullableDecimalAverageAggregationOperatorEnumerator(QueryOperatorEnumerator<decimal?, TKey> source, int partitionIndex,
CancellationToken cancellationToken) :
base(partitionIndex, cancellationToken)
{
Debug.Assert(source != null);
_source = source;
}
//---------------------------------------------------------------------------------------
// Tallies up the average of the underlying data source, walking the entire thing the first
// time MoveNext is called on this object.
//
protected override bool MoveNextCore(ref Pair<decimal, long> currentElement)
{
// The temporary result contains the running sum and count, respectively.
decimal sum = 0.0m;
long count = 0;
QueryOperatorEnumerator<decimal?, TKey> source = _source;
decimal? current = default(decimal?);
TKey currentKey = default(TKey);
int i = 0;
while (source.MoveNext(ref current, ref currentKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
if (current.HasValue)
{
checked
{
sum += current.GetValueOrDefault();
count++;
}
}
}
currentElement = new Pair<decimal, long>(sum, count);
return count > 0;
}
//---------------------------------------------------------------------------------------
// Dispose of resources associated with the underlying enumerator.
//
protected override void Dispose(bool disposing)
{
Debug.Assert(_source != null);
_source.Dispose();
}
}
}
} | 42.819444 | 140 | 0.498378 | [
"MIT"
] | 690486439/corefx | src/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Inlined/NullableDecimalAverageAggregationOperator.cs | 6,166 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.