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 |
|---|---|---|---|---|---|---|---|---|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Conventions;
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
{
internal static class HttpContextDatabaseContextDetailsExtensions
{
public static async ValueTask<DatabaseContextDetails?> GetContextDetailsAsync(this HttpContext httpContext, Type dbcontextType, ILogger logger)
{
var context = (DbContext?)httpContext.RequestServices.GetService(dbcontextType);
if (context == null)
{
logger.ContextNotRegisteredDatabaseErrorPageMiddleware(dbcontextType.FullName!);
return null;
}
var relationalDatabaseCreator = context.GetService<IDatabaseCreator>() as IRelationalDatabaseCreator;
if (relationalDatabaseCreator == null)
{
logger.NotRelationalDatabase();
return null;
}
var databaseExists = await relationalDatabaseCreator.ExistsAsync();
if (databaseExists)
{
databaseExists = await relationalDatabaseCreator.HasTablesAsync();
}
var migrationsAssembly = context.GetService<IMigrationsAssembly>();
var modelDiffer = context.GetService<IMigrationsModelDiffer>();
var snapshotModel = migrationsAssembly.ModelSnapshot?.Model;
if (snapshotModel is IMutableModel mutableModel)
{
snapshotModel = mutableModel.FinalizeModel();
}
if (snapshotModel != null)
{
snapshotModel = context.GetService<IModelRuntimeInitializer>().Initialize(snapshotModel);
}
// HasDifferences will return true if there is no model snapshot, but if there is an existing database
// and no model snapshot then we don't want to show the error page since they are most likely targeting
// and existing database and have just misconfigured their model
return new DatabaseContextDetails(
type: dbcontextType,
databaseExists: databaseExists,
pendingModelChanges: (!databaseExists || migrationsAssembly.ModelSnapshot != null)
&& modelDiffer.HasDifferences(
snapshotModel?.GetRelationalModel(),
context.GetService<IDesignTimeModel>().Model.GetRelationalModel()),
pendingMigrations: databaseExists
? await context.Database.GetPendingMigrationsAsync()
: context.Database.GetMigrations());
}
}
}
| 42.153846 | 151 | 0.67427 | [
"Apache-2.0"
] | 1175169074/aspnetcore | src/Middleware/Diagnostics.EntityFrameworkCore/src/HttpContextDatabaseContextDetailsExtensions.cs | 3,288 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace System.IO
{
/// <summary>
/// Extensions for the stream class
/// </summary>
public static class StreamExtensions
{
public static Stream ToStream(this byte[] bytes)
{
var asStream = new MemoryStream(bytes.Length);
asStream.Write(bytes, 0, bytes.Length);
asStream.Position = 0;
return asStream;
}
/// <summary>
/// Reads the bytes of 2 streams, computing a hash along the way, in order to determin if they are equal
/// at a byte level.
/// </summary>
/// <param name="source">A stream to compare</param>
/// <param name="destination">A stream to compare</param>
/// <returns>If the streams bytes are equivalent</returns>
public static bool IsEquaTo(this Stream source, Stream destination)
{
return source.ComputeHash() == destination.ComputeHash();
}
/// <summary>
/// Computes an MD5 has on the source stream
/// </summary>
/// <param name="source">The stream to hash</param>
/// <returns>The hash</returns>
public static string ComputeHash(this Stream source)
{
var hash = source.ComputeMd5AsBytes();
return hash.ToHash();
}
public static string ToHash(this byte[] bytesToHash)
{
return BitConverter.ToString(bytesToHash); //.Replace("-", string.Empty).ToLower();
}
public static byte[] FromHash(this string hashedBytes)
{
//if(hashedBytes.IsNullOrWhitespace())
// hashedBytes = hashedBytes.Replace("-", string.Empty).ToLower();
var length = (hashedBytes.Length + 1) / 3;
var asBytes = new byte[length];
for (var i = 0; i < length; i++)
asBytes[i] = Convert.ToByte(hashedBytes.Substring(3 * i, 2), 16);
return asBytes;
}
public static byte[] ComputeMd5AsBytes(this Stream source)
{
HashAlgorithm ha = new MD5CryptoServiceProvider();
using (var buffered = new BufferedStream(source, 1200000))
{
var hash = ha.ComputeHash(buffered);
return hash;
}
}
public static byte[] ComputeMd5AsBytes(this byte[] source)
{
HashAlgorithm ha = new MD5CryptoServiceProvider();
var hash = ha.ComputeHash(source);
return hash;
}
public static string ComputeHash(this byte[] toHash)
{
var hash = toHash.ComputeMd5AsBytes();
return hash.ToHash();
}
public static string ComputeMd5(this byte[] toHash)
{
return toHash.ComputeHash();
}
public static string AsBase64(this string source)
{
if (source == null) return null;
return Convert.ToBase64String(Encoding.UTF8.GetBytes(source));
}
public static string AsBase64(this byte[] source)
{
if (source == null) return null;
return Convert.ToBase64String(source);
}
public static byte[] FromBase64(this string source)
{
return Convert.FromBase64String(source);
}
public static string FromBase64AsString(this string source)
{
return Encoding.UTF8.GetString(Convert.FromBase64String(source));
}
public static string ComputeMd5(this Stream source)
{
return source.ComputeHash();
}
public static string ComputeHash(this string source)
{
return ComputeHash(Encoding.UTF8.GetBytes(source));
}
}
}
| 30.007634 | 112 | 0.572119 | [
"MIT"
] | captainjono/rxns | src/Rxns/StreamExtensions.cs | 3,933 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace Engine
{
class ImageHelper
{
//Supports the resizing of an image with no smoothing and nearest neighbor interpolation.
public static Image ResizeImage(Image Image, int Width, int Height)
{
Bitmap DestImage = new Bitmap(Width, Height);
Rectangle DestRect = new Rectangle(0, 0, Width, Height);
Graphics G = Graphics.FromImage(DestImage);
G.InterpolationMode = InterpolationMode.NearestNeighbor;
G.SmoothingMode = SmoothingMode.None;
G.DrawImage(Image, DestRect, 0, 0, Image.Width, Image.Height, GraphicsUnit.Pixel);
return DestImage;
}
public static Image ChangeOpacity(Image original, float opacity)
{
return AlterImageChannel(original, 3, opacity);
}
public static Image AdjustLuminosity(Image original, float change)
{
return AlterImageChannel(original, 2, change);
}
public static Image AlterImageChannel(Image original, int channel, float value)
{
if ((original.PixelFormat & PixelFormat.Indexed) == PixelFormat.Indexed)
return original;
Bitmap bmp = original.Clone() as Bitmap;
BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
IntPtr ptr = data.Scan0;
byte[] bytes = new byte[bmp.Width * bmp.Height * 4];
System.Runtime.InteropServices.Marshal.Copy(ptr, bytes, 0, bytes.Length);
for (int i = 0; i < bytes.Length; i += 4)
{
if (channel == 3)
{
if (bytes[i + 3] == 0)
continue;
bytes[i + 3] = (byte)(value * 255);
}
if (channel == 2)// L*(value +1) L+0.25*(1-L)
{
for (var j = 0; j < 3; j++)
{
bytes[i + j] = value < 0 ? (byte)(bytes[i + j] * (value + 1)) : (byte)(bytes[i + j] + value * (255 - bytes[i + j]));
}
}
}
System.Runtime.InteropServices.Marshal.Copy(bytes, 0, ptr, bytes.Length);
bmp.UnlockBits(data);
return bmp;
}
}
}
| 37.838235 | 141 | 0.548776 | [
"Unlicense"
] | save-buffer/Engine | Source/ImageHelper.cs | 2,575 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Unmanaged.Jni
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
/// <summary>
/// Dynamically loads unmanaged DLLs with respect to current platform.
/// </summary>
internal static class DllLoader
{
/** Lazy symbol binding. */
private const int RtldLazy = 1;
/** Global symbol access. */
private const int RtldGlobal = 8;
/// <summary>
/// ERROR_BAD_EXE_FORMAT constant.
/// </summary>
// ReSharper disable once InconsistentNaming
private const int ERROR_BAD_EXE_FORMAT = 193;
/// <summary>
/// ERROR_MOD_NOT_FOUND constant.
/// </summary>
// ReSharper disable once InconsistentNaming
private const int ERROR_MOD_NOT_FOUND = 126;
/// <summary>
/// Initializes the <see cref="DllLoader"/> class.
/// </summary>
static DllLoader()
{
NativeLibraryUtils.SetDllImportResolvers();
}
/// <summary>
/// Loads specified DLL.
/// </summary>
/// <returns>Library handle and error message.</returns>
public static KeyValuePair<IntPtr, string> Load(string dllPath)
{
if (Os.IsWindows)
{
var ptr = NativeMethodsWindows.LoadLibrary(dllPath);
return new KeyValuePair<IntPtr, string>(ptr, ptr == IntPtr.Zero
? FormatWin32Error(Marshal.GetLastWin32Error()) ?? "Unknown error"
: null);
}
if (Os.IsMacOs)
{
var ptr = NativeMethodsMacOs.dlopen(dllPath, RtldGlobal | RtldLazy);
return new KeyValuePair<IntPtr, string>(ptr, ptr == IntPtr.Zero
? GetErrorText(NativeMethodsMacOs.dlerror())
: null);
}
if (Os.IsLinux)
{
if (Os.IsMono)
{
var ptr = NativeMethodsMono.dlopen(dllPath, RtldGlobal | RtldLazy);
return new KeyValuePair<IntPtr, string>(ptr, ptr == IntPtr.Zero
? GetErrorText(NativeMethodsMono.dlerror())
: null);
}
// Depending on the Linux distro, dlopen is either present in libdl or in libcoreclr.
try
{
var ptr = NativeMethodsLinuxLibcoreclr.dlopen(dllPath, RtldGlobal | RtldLazy);
return new KeyValuePair<IntPtr, string>(ptr, ptr == IntPtr.Zero
? GetErrorText(NativeMethodsLinuxLibcoreclr.dlerror())
: null);
}
catch (EntryPointNotFoundException)
{
var ptr = NativeMethodsLinuxLibdl.dlopen(dllPath, RtldGlobal | RtldLazy);
return new KeyValuePair<IntPtr, string>(ptr, ptr == IntPtr.Zero
? GetErrorText(NativeMethodsLinuxLibdl.dlerror())
: null);
}
}
throw new InvalidOperationException("Unsupported OS: " + Environment.OSVersion);
}
/// <summary>
/// Gets the error text.
/// </summary>
private static string GetErrorText(IntPtr charPtr)
{
return Marshal.PtrToStringAnsi(charPtr) ?? "Unknown error";
}
/// <summary>
/// Formats the Win32 error.
/// </summary>
[ExcludeFromCodeCoverage]
private static string FormatWin32Error(int errorCode)
{
if (errorCode == ERROR_BAD_EXE_FORMAT)
{
var mode = Environment.Is64BitProcess ? "x64" : "x86";
return string.Format("DLL could not be loaded (193: ERROR_BAD_EXE_FORMAT). " +
"This is often caused by x64/x86 mismatch. " +
"Current process runs in {0} mode, and DLL is not {0}.", mode);
}
if (errorCode == ERROR_MOD_NOT_FOUND)
{
return "DLL could not be loaded (126: ERROR_MOD_NOT_FOUND). " +
"This can be caused by missing dependencies. ";
}
return string.Format("{0}: {1}", errorCode, new Win32Exception(errorCode).Message);
}
/// <summary>
/// Windows.
/// </summary>
private static class NativeMethodsWindows
{
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi, BestFitMapping = false,
ThrowOnUnmappableChar = true)]
internal static extern IntPtr LoadLibrary(string filename);
}
/// <summary>
/// Linux.
/// </summary>
private static class NativeMethodsLinuxLibdl
{
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("libdl.so", SetLastError = true, CharSet = CharSet.Ansi, BestFitMapping = false,
ThrowOnUnmappableChar = true)]
internal static extern IntPtr dlopen(string filename, int flags);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("libdl.so", SetLastError = true, CharSet = CharSet.Ansi, BestFitMapping = false,
ThrowOnUnmappableChar = true)]
internal static extern IntPtr dlerror();
}
/// <summary>
/// libdl.so depends on libc6-dev on Linux, use Mono instead.
/// </summary>
private static class NativeMethodsMono
{
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("__Internal", SetLastError = true, CharSet = CharSet.Ansi, BestFitMapping = false,
ThrowOnUnmappableChar = true)]
internal static extern IntPtr dlopen(string filename, int flags);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("__Internal", SetLastError = true, CharSet = CharSet.Ansi, BestFitMapping = false,
ThrowOnUnmappableChar = true)]
internal static extern IntPtr dlerror();
}
/// <summary>
/// libdl.so depends on libc6-dev on Linux, use libcoreclr instead.
/// </summary>
private static class NativeMethodsLinuxLibcoreclr
{
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("libcoreclr.so", SetLastError = true, CharSet = CharSet.Ansi, BestFitMapping = false,
ThrowOnUnmappableChar = true)]
internal static extern IntPtr dlopen(string filename, int flags);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("libcoreclr.so", SetLastError = true, CharSet = CharSet.Ansi, BestFitMapping = false,
ThrowOnUnmappableChar = true)]
internal static extern IntPtr dlerror();
}
/// <summary>
/// macOs uses "libSystem.dylib".
/// </summary>
internal static class NativeMethodsMacOs
{
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("libSystem.dylib", CharSet = CharSet.Ansi, BestFitMapping = false,
ThrowOnUnmappableChar = true)]
internal static extern IntPtr dlopen(string filename, int flags);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("libSystem.dylib", CharSet = CharSet.Ansi, BestFitMapping = false,
ThrowOnUnmappableChar = true)]
internal static extern IntPtr dlerror();
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("libSystem.dylib", CharSet = CharSet.Ansi, BestFitMapping = false,
ThrowOnUnmappableChar = true)]
internal static extern IntPtr dlsym(IntPtr handle, string symbol);
}
}
}
| 41.608108 | 108 | 0.591642 | [
"Apache-2.0"
] | BrentShikoski/ignite | modules/platforms/dotnet/Apache.Ignite.Core/Impl/Unmanaged/Jni/DllLoader.cs | 9,239 | C# |
namespace Shopify.Unity.SDK {
using System.Collections.Generic;
using System.Collections;
using System;
[Serializable]
public class SummaryItem : Serializable {
protected const string LABEL = "Label";
protected const string AMOUNT = "Amount";
#pragma warning disable 0414
public string Label;
public string Amount;
#pragma warning restore 0414
public SummaryItem(string label, string amount) {
Label = label;
Amount = amount;
}
public override object ToJson() {
var dict = new Dictionary<string, object>();
dict[LABEL] = Label;
dict[AMOUNT] = Amount;
return dict;
}
}
} | 26.178571 | 57 | 0.59618 | [
"MIT"
] | fresh-eggs/unity-buy-sdk | Assets/Shopify/Unity/SDK/SummaryItem.cs | 733 | C# |
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace AnimeTask.Sample
{
public class SampleMenu : MonoBehaviour
{
public Sample Sample;
public Dropdown Dropdown;
private readonly List<Dropdown.OptionData> list = new List<Dropdown.OptionData>
{
new Dropdown.OptionData("Sample01"),
new Dropdown.OptionData("Sample02"),
new Dropdown.OptionData("Sample03"),
new Dropdown.OptionData("Sample04"),
new Dropdown.OptionData("Sample05"),
new Dropdown.OptionData("Sample06"),
new Dropdown.OptionData("Sample07"),
new Dropdown.OptionData("Sample08"),
new Dropdown.OptionData("Sample09"),
new Dropdown.OptionData("Sample10"),
new Dropdown.OptionData("Sample11"),
};
public void Start()
{
Dropdown.options = list;
Dropdown.onValueChanged.AddListener(Play);
Play(0);
}
private void Play(int index)
{
Debug.Log($"Play {list[index].text}");
Sample.Invoke(list[index].text, 0.0f);
}
}
}
| 29.243902 | 87 | 0.582152 | [
"MIT"
] | toddlerer/AnimeTask | Assets/Sample/SampleMenu.cs | 1,201 | C# |
/*
* OANDA v20 REST API
*
* The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more.
*
* OpenAPI spec version: 3.0.15
* Contact: api@oanda.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace Oanda.RestV20.Model
{
/// <summary>
/// Representation of how many units of an Instrument are available to be traded by an Order depending on its postionFill option.
/// </summary>
[DataContract]
public partial class UnitsAvailable : IEquatable<UnitsAvailable>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="UnitsAvailable" /> class.
/// </summary>
/// <param name="_Default">_Default.</param>
/// <param name="ReduceFirst">ReduceFirst.</param>
/// <param name="ReduceOnly">ReduceOnly.</param>
/// <param name="OpenOnly">OpenOnly.</param>
public UnitsAvailable(UnitsAvailableDetails _Default = default(UnitsAvailableDetails), UnitsAvailableDetails ReduceFirst = default(UnitsAvailableDetails), UnitsAvailableDetails ReduceOnly = default(UnitsAvailableDetails), UnitsAvailableDetails OpenOnly = default(UnitsAvailableDetails))
{
this._Default = _Default;
this.ReduceFirst = ReduceFirst;
this.ReduceOnly = ReduceOnly;
this.OpenOnly = OpenOnly;
}
/// <summary>
/// Gets or Sets _Default
/// </summary>
[DataMember(Name="default", EmitDefaultValue=false)]
public UnitsAvailableDetails _Default { get; set; }
/// <summary>
/// Gets or Sets ReduceFirst
/// </summary>
[DataMember(Name="reduceFirst", EmitDefaultValue=false)]
public UnitsAvailableDetails ReduceFirst { get; set; }
/// <summary>
/// Gets or Sets ReduceOnly
/// </summary>
[DataMember(Name="reduceOnly", EmitDefaultValue=false)]
public UnitsAvailableDetails ReduceOnly { get; set; }
/// <summary>
/// Gets or Sets OpenOnly
/// </summary>
[DataMember(Name="openOnly", EmitDefaultValue=false)]
public UnitsAvailableDetails OpenOnly { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class UnitsAvailable {\n");
sb.Append(" _Default: ").Append(_Default).Append("\n");
sb.Append(" ReduceFirst: ").Append(ReduceFirst).Append("\n");
sb.Append(" ReduceOnly: ").Append(ReduceOnly).Append("\n");
sb.Append(" OpenOnly: ").Append(OpenOnly).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as UnitsAvailable);
}
/// <summary>
/// Returns true if UnitsAvailable instances are equal
/// </summary>
/// <param name="other">Instance of UnitsAvailable to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(UnitsAvailable other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this._Default == other._Default ||
this._Default != null &&
this._Default.Equals(other._Default)
) &&
(
this.ReduceFirst == other.ReduceFirst ||
this.ReduceFirst != null &&
this.ReduceFirst.Equals(other.ReduceFirst)
) &&
(
this.ReduceOnly == other.ReduceOnly ||
this.ReduceOnly != null &&
this.ReduceOnly.Equals(other.ReduceOnly)
) &&
(
this.OpenOnly == other.OpenOnly ||
this.OpenOnly != null &&
this.OpenOnly.Equals(other.OpenOnly)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this._Default != null)
hash = hash * 59 + this._Default.GetHashCode();
if (this.ReduceFirst != null)
hash = hash * 59 + this.ReduceFirst.GetHashCode();
if (this.ReduceOnly != null)
hash = hash * 59 + this.ReduceOnly.GetHashCode();
if (this.OpenOnly != null)
hash = hash * 59 + this.OpenOnly.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 38.110465 | 294 | 0.567963 | [
"Apache-2.0"
] | 3ai-co/Lean | Brokerages/Oanda/RestV20/Model/UnitsAvailable.cs | 6,555 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReliefAnalyze.Logic.ColorDetect
{
public class MapObjectsColors
{
private static MapObjectsColors instance;
public IDictionary<string, List<ColorInfo>> ColorsDict;
public List<string> Tight;
public List<string> Relief;
protected MapObjectsColors()
{
ColorsDict = new Dictionary<string, List<ColorInfo>>();
Tight = new List<string>();
Relief = new List<string>();
ColorsDict.Add("Ponds", new List<ColorInfo>());
ColorsDict.Add("Rivers", new List<ColorInfo>());
ColorsDict.Add("Forests", new List<ColorInfo>());
ColorsDict.Add("Roads", new List<ColorInfo>());
ColorsDict.Add("Sand", new List<ColorInfo>());
ColorsDict.Add("Hills", new List<ColorInfo>());
ColorsDict.Add("Plain", new List<ColorInfo>());
ColorsDict.Add("Mountains", new List<ColorInfo>());
ColorsDict.Add("Swamp", new List<ColorInfo>());
ColorsDict.Add("Ice", new List<ColorInfo>());
ColorsDict.Add("Culture", new List<ColorInfo>());
Tight.AddRange(new string[] { "Rivers", "Roads" });
Relief.AddRange(new string[] { "Mountains", "Plain", "Hills" });
}
public static MapObjectsColors GetInstance()
{
if (instance == null)
instance = new MapObjectsColors();
return instance;
}
/*
* "DarkGreen"
* "SeaGreen"
* "MediumSeaGreen"
* "DarkSlateGray"
* "Gray"
* "DimGray"
* "CornflowerBlue"
* "Navy"
* "LightSteelBlue"
* "Khaki"
* "SandyBrown"
* "SaddleBrown"
* "DarkOliveGreen"
* "OrangeRed"
* "Khaki"
* "Maroon"
* "Peru"
* "Gold"
* "Goldenrod"
* "Tomato"
* "LightPink"
* "Red"
* "Lavender"
* "Azure"
* "White"
* "MintCream"
* "Sienna"
* "LightCyan"
*/
public void SetDefaultColors()
{
foreach (var elem in ColorsDict)
{
ColorsDict[elem.Key].Clear();
}
ColorsDict["Ponds"].AddRange(new ColorInfo[] {
new ColorInfo {NearColor="LightSteelBlue", Color= Color.LightSteelBlue },
new ColorInfo {NearColor="CornflowerBlue", Color=Color.CornflowerBlue }
});
ColorsDict["Rivers"].AddRange(new ColorInfo[] {
new ColorInfo { Color = Color.Navy, NearColor = "Navy" }
});
ColorsDict["Hills"].AddRange(new ColorInfo[] {
new ColorInfo {NearColor="DimGray", Color = Color.DimGray },
new ColorInfo {NearColor="Gray", Color = Color.Gray },
//new ColorInfo {NearColor="Khaki", Color = Color.Khaki }
});
ColorsDict["Forests"].Add(new ColorInfo { NearColor = "DarkGreen", Color = Color.DarkGreen });
ColorsDict["Plain"].AddRange(new ColorInfo[] {
new ColorInfo {NearColor="DarkSlateGray",Color = Color.DarkSlateGray },
new ColorInfo {NearColor="SeaGreen",Color = Color.SeaGreen },
new ColorInfo {NearColor="MediumSeaGreen",Color = Color.MediumSeaGreen },
new ColorInfo {NearColor="Khaki", Color = Color.Khaki },
new ColorInfo {NearColor="Yellow", Color = Color.Yellow},
new ColorInfo {NearColor="GreenYellow", Color = Color.GreenYellow},
new ColorInfo {NearColor="YellowGreen", Color = Color.YellowGreen},
new ColorInfo {NearColor="LightGreen", Color = Color.LightGreen},
new ColorInfo {NearColor="OliveDrab", Color = Color.OliveDrab},
new ColorInfo {NearColor = "DarkOliveGreen", Color=Color.DarkOliveGreen }
});
ColorsDict["Roads"].AddRange(new ColorInfo[] {
new ColorInfo {NearColor="Tomato",Color=Color.Tomato },
new ColorInfo {NearColor="LightPink",Color=Color.LightPink },
new ColorInfo {NearColor="Red",Color=Color.Red}
});
ColorsDict["Sand"].AddRange(new ColorInfo[] {
new ColorInfo {NearColor="Gold",Color=Color.Gold },
new ColorInfo {NearColor="Peru",Color=Color.Peru }
});
ColorsDict["Mountains"].AddRange(new ColorInfo[] {
new ColorInfo {NearColor = "DarkOliveGreen", Color=Color.DarkOliveGreen },
new ColorInfo {NearColor = "Maroon", Color=Color.Maroon},
new ColorInfo {NearColor = "SandyBrown", Color=Color.SandyBrown},
new ColorInfo {NearColor = "SaddleBrown", Color=Color.SaddleBrown},
new ColorInfo {NearColor = "OrangeRed", Color=Color.OrangeRed},
new ColorInfo {NearColor = "Khaki", Color=Color.Khaki},
new ColorInfo {NearColor = "Sienna", Color=Color.Sienna},
new ColorInfo {NearColor = "LightCyan", Color=Color.LightCyan},
new ColorInfo {NearColor = "MintCream", Color=Color.MintCream},
new ColorInfo {NearColor = "Azure", Color=Color.Azure }
});
ColorsDict["Culture"].Add(new ColorInfo() { NearColor = "Goldenrod", Color = Color.Goldenrod });
ColorsDict["Ice"].Add(new ColorInfo { NearColor = "Lavender", Color = Color.Lavender });
ColorsDict["Swamp"].Add(new ColorInfo { NearColor = "Sienna", Color = Color.Sienna });
}
}
}
| 43.103704 | 108 | 0.557656 | [
"MIT"
] | ArtemNazarov/ReliefAnalyze | ReliefAnalyze/Logic/ColorDetect/MapObjectsColors.cs | 5,821 | C# |
using System.Threading.Tasks;
using Fux.Example.Config.Model;
namespace Fux.Example.Config
{
/// <summary>
/// This class is responsible for executing a Fux.Config.Docker example
/// </summary>
public class Docker : Runner
{
/// <summary>
/// This property is for testing outside of a Docker environment only
/// in the library, this defaults to /run/secrets
/// </summary>
private static string DockerSecretDirectory = "/home/tbrown/.secrets";
/// <summary>
/// This method retrieves a Docker secret value as a boolean
/// </summary>
private void Boolean()
{
// Localize the Docker secret object
bool boolean = Fux.Config.Docker.Get<bool>("fux-example-config-docker-boolean");
// Log the message
LogMessage(Helper.Message.New("[DockerSecretBoolean] => ${boolean}")
.WithDataObject("boolean", boolean));
}
/// <summary>
/// This method asynchronously retrieves a Docker secret value as a boolean
/// </summary>
/// <returns></returns>
private async Task BooleanAsync()
{
// Localize the Docker secret object
bool boolean = await Fux.Config.Docker.GetAsync<bool>("fux-example-config-docker-boolean");
// Log the message
LogMessage(Helper.Message.New("[DockerSecretBoolean] => ${boolean}")
.WithDataObject("boolean", boolean));
}
/// <summary>
/// This method retrieves a Docker secret value as a double
/// </summary>
private void Double()
{
// Localize the Docker secret object
double dbl = Fux.Config.Docker.Get<double>("fux-example-config-docker-double");
// Log the message
LogMessage(Helper.Message.New("[DockerSecretDouble] => ${double}")
.WithDataObject("double", dbl));
}
/// <summary>
/// This method asynchronously retrieves a Docker secret value as a double
/// </summary>
/// <returns></returns>
private async Task DoubleAsync()
{
// Localize the Docker secret object
double dbl = await Fux.Config.Docker.GetAsync<double>("fux-example-config-docker-double");
// Log the message
LogMessage(Helper.Message.New("[DockerSecretDouble] => ${double}")
.WithDataObject("double", dbl));
}
/// <summary>
/// This method retrieves a Docker secret value as an integer
/// </summary>
private void Integer()
{
// Localize the Docker secret object
int integer = Fux.Config.Docker.Get<int>("fux-example-config-docker-integer");
// Log the message
LogMessage(Helper.Message.New("[DockerSecretInteger] => ${integer}")
.WithDataObject("integer", integer));
}
/// <summary>
/// This method asynchronously retrieves a Docker secret value as an integer
/// </summary>
private async Task IntegerAsync()
{
// Localize the Docker secret object
int integer = await Fux.Config.Docker.GetAsync<int>("fux-example-config-docker-integer");
// Log the message
LogMessage(Helper.Message.New("[DockerSecretInteger] => ${integer}")
.WithDataObject("integer", integer));
}
/// <summary>
/// This method retrieves a Docker secret and deserializes it into a POCO
/// </summary>
/// <returns></returns>
private void KeyObject()
{
// Localize the Docker secret object
KeyObject keyObject = Fux.Config.Docker.Get<KeyObject>();
// Log the message
LogMessage(Helper.Message.New("[DockerSecretKeyObject] => ${keyObject}")
.WithDataObject("keyObject", keyObject));
}
/// <summary>
/// This method asynchronously retrieves a Docker secret and deserializes it into a POCO
/// </summary>
/// <returns></returns>
private async Task KeyObjectAsync()
{
// Localize the Docker secret object
KeyObject keyObject = await Fux.Config.Docker.GetAsync<KeyObject>();
// Log the message
LogMessage(Helper.Message.New("[DockerSecretKeyObject] => ${keyObject}")
.WithDataObject("keyObject", keyObject));
}
/// <summary>
/// This method retrieves keys from a Docker secret defined as attributes in a POCO
/// and then populates and returns the POCO
/// </summary>
/// <returns></returns>
private void Object()
{
// Localize the Docker secret object
Object obj = Fux.Config.Docker.GetObject<Object>();
// Log the message
LogMessage(Helper.Message.New("[DockerSecretObject] => ${object}").WithDataObject("object", obj));
}
/// <summary>
/// This method asynchronously retrieves keys from a Docker secret defined as
/// attributes in a POCO and then populates and returns the POCO
/// </summary>
/// <returns></returns>
private async Task ObjectAsync()
{
// Localize the Docker secret object
Object obj = await Fux.Config.Docker.GetObjectAsync<Object>();
// Log the message
LogMessage(Helper.Message.New("[DockerSecretObject] => ${object}").WithDataObject("object", obj));
}
/// <summary>
/// This task retrieves a string from a Docker secret
/// </summary>
/// <returns></returns>
private void String()
{
// Localize the Docker secret
string str = Fux.Config.Docker.Get("fux-example-config-docker-string");
// Log the message
LogMessage(
Helper.Message
.New("[DockerSecretString] => ${string}")
.WithDataObject("string", str));
}
/// <summary>
/// This task asynchronously retrieves a string from a Docker secret
/// </summary>
/// <returns></returns>
private async Task StringAsync()
{
// Localize the Docker secret
string str = await Fux.Config.Docker.GetAsync("fux-example-config-docker-key");
// Log the message
LogMessage(Helper.Message.New("[DockerSecretString] => ${string}").WithDataObject("string", str));
}
/// <summary>
/// This method runs the Docker secret example
/// </summary>
/// <param name="ticker"></param>
/// <returns></returns>
protected override void Task(Core.Ticker ticker)
{
// Reset the Docker secret path
Fux.Config.Docker.SetSecretsDirectory(DockerSecretDirectory);
// Run the Docker secret boolean task
Boolean();
// Run the Docker secret double task
Double();
// Run the Docker secret integer task
Integer();
// Run the Docker secret key object task
KeyObject();
// Run the Docker secret object task
Object();
// Run the Docker secret string task
String();
}
/// <summary>
/// This method runs the Docker secret example asynchronously
/// </summary>
/// <param name="ticker"></param>
/// <returns></returns>
protected override async Task TaskAsync(Core.Ticker ticker)
{
// Reset the Docker secret path
Fux.Config.Docker.SetSecretsDirectory(DockerSecretDirectory);
// Run the Docker secret boolean task
await BooleanAsync();
// Run the Docker secret double task
await DoubleAsync();
// Run the Docker secret integer task
await IntegerAsync();
// Run the Docker secret key object task
await KeyObjectAsync();
// Run the Docker secret object task
await ObjectAsync();
// Run the Docker secret string task
await StringAsync();
}
}
}
| 38.552995 | 110 | 0.5612 | [
"MIT"
] | bolvarak/aspnetcore-fux-examples | Config/Docker.cs | 8,366 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Structure;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal class IndexerDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<IndexerDeclarationSyntax>
{
protected override void CollectBlockSpans(
IndexerDeclarationSyntax indexerDeclaration,
ArrayBuilder<BlockSpan> spans,
BlockStructureOptionProvider optionProvider,
CancellationToken cancellationToken)
{
CSharpStructureHelpers.CollectCommentBlockSpans(indexerDeclaration, spans, optionProvider);
// fault tolerance
if (indexerDeclaration.AccessorList == null ||
indexerDeclaration.AccessorList.IsMissing ||
indexerDeclaration.AccessorList.OpenBraceToken.IsMissing ||
indexerDeclaration.AccessorList.CloseBraceToken.IsMissing)
{
return;
}
SyntaxNodeOrToken current = indexerDeclaration;
var nextSibling = current.GetNextSibling();
// Check IsNode to compress blank lines after this node if it is the last child of the parent.
//
// Indexers are grouped together with properties in Metadata as Source.
var compressEmptyLines = optionProvider.IsMetadataAsSource
&& (!nextSibling.IsNode || nextSibling.IsKind(SyntaxKind.IndexerDeclaration) || nextSibling.IsKind(SyntaxKind.PropertyDeclaration));
spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan(
indexerDeclaration,
indexerDeclaration.ParameterList.GetLastToken(includeZeroWidth: true),
compressEmptyLines: compressEmptyLines,
autoCollapse: true,
type: BlockTypes.Member,
isCollapsible: true));
}
}
}
| 42.480769 | 148 | 0.685831 | [
"MIT"
] | KirillOsenkov/roslyn | src/Features/CSharp/Portable/Structure/Providers/IndexerDeclarationStructureProvider.cs | 2,211 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SF.Space
{
public static class MathUtils
{
public const double Epsilon = 1E-12;
public static readonly double Ln10 = Math.Log(10);
public static string NumberToText(double value, string unit)
{
return value.ToString("N0") + (string.IsNullOrEmpty(unit) ? string.Empty : (" " + unit));
}
public static int Gold(int n)
{
return n * 618 / 1000;
}
public static int Round(double a)
{
return (int)Math.Round(a);
}
public static double ToDegrees(double a)
{
return 180 * a / Math.PI;
}
public static double ToRadians(double d)
{
return d * Math.PI / 180;
}
public static int ToDegreesInt(double a)
{
return Round(ToDegrees(a));
}
public static bool NearlyEqual(double a, double b)
{
return NearlyEqual(a, b, Epsilon);
}
public static bool NearlyEqual(double a, double b, double epsilon)
{
if (a == b)
return true;
var diff = Math.Abs(a - b);
var sum = Math.Abs(a) + Math.Abs(b);
return diff <= sum * epsilon;
}
public static double Linear(double min, double max, double lambda)
{
return min * (1 - lambda) + max * lambda;
}
public static double LimitedLinear(double min, double max, double lambda)
{
if (lambda < 0)
lambda = 0;
if (lambda > 1)
lambda = 1;
return Linear(min, max, lambda);
}
public static double NextAngle(this Random random)
{
return 2 * Math.PI * random.NextDouble();
}
public static Vector NextDirection(this Random random)
{
return Vector.Direction(random.NextAngle());
}
public static T RandomOf<T>(this ICollection<T> that, Random random)
{
var list = that.ToList();
var index = random.Next(list.Count);
return list[index];
}
}
}
| 25.662921 | 101 | 0.518389 | [
"Apache-2.0"
] | lncubus/SpaceFight | Space/MathUtils.cs | 2,286 | C# |
using System;
using System.Collections.Generic;
namespace FutureState.Flow.Enrich
{
/// <summary>
/// Enriches the content of a given entity type.
/// </summary>
public interface IEnricher
{
/// <summary>
/// Gets the entity type used to enrich a given target.
/// </summary>
FlowEntity SourceEntityType { get; }
/// <summary>
/// Gets the unique network address of the data source.
/// </summary>
string AddressId { get; }
}
/// <summary>
/// Enriches the content of a well known entity type.
/// </summary>
/// <typeparam name="TTarget">The data type to enrich.</typeparam>
public interface IEnricher<TTarget> : IEnricher
{
/// <summary>
/// Gets the data structures used to enrich the target type.
/// </summary>
/// <returns></returns>
IEnumerable<IEquatable<TTarget>> Get();
/// <summary>
/// Enriches the 'whole' data type from the 'part' data type.
/// </summary>
/// <returns></returns>
TTarget Enrich(IEquatable<TTarget> part, TTarget whole);
/// <summary>
/// Gets all parts that can be used to enrich a given target instance.
/// </summary>
/// <returns></returns>
IEnumerable<IEquatable<TTarget>> Find(TTarget target);
}
} | 30.521739 | 82 | 0.564103 | [
"Apache-2.0"
] | arisanikolaou/futurestate | src/FutureState.Flow/Enrich/IEnricher.cs | 1,406 | C# |
using Microsoft.AspNetCore.Identity;
using RimmuTraining.WebApp.Data;
using RimmuTraining.WebApp.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RimmuTraining.WebApp.Domain.Members
{
public class MakeTrainer
{
public Guid MemberId { get; set; }
public DateTime Date { get; set; }
public string Type { get; set; }
}
public class MakeTrainerCommandHandler : ICommandHandler<MakeTrainer>
{
private readonly RimmuDbContext dbContext;
private readonly UserManager<RimmuUser> userManager;
public MakeTrainerCommandHandler(RimmuDbContext dbContext, UserManager<RimmuUser> userManager)
{
this.dbContext = dbContext;
this.userManager = userManager;
}
public async Task<Result> HandleAsync(MakeTrainer command)
{
if (!TrainingTypes.Get().Contains(command.Type))
{
return new Result("Invalid training type.");
}
var member = await dbContext.Members.FindAsync(command.MemberId);
if (member != null)
{
if (member.User != null)
{
member.Events.Add(new MemberEvents
{
Date = command.Date,
Title = string.Format("Became {0} Trainer", command.Type)
});
var roleResult = await userManager.AddToRoleAsync(member.User, string.Format("{0} Trainer", command.Type));
if (roleResult.Succeeded)
{
await dbContext.SaveChangesAsync();
return new Result();
}
return new Result(roleResult.Errors.Select(e => e.Description).ToString());
}
else
{
return new Result("Member does not have a user. Register a user before making him/her a trainer.");
}
}
return new Result("Member not found.");
}
}
}
| 35.491803 | 127 | 0.552887 | [
"MIT"
] | gudnig/RimmuTraining | RimmuTraining.WebApp/Domain/Members/MakeTrainer.cs | 2,167 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using FDK;
namespace DTXMania
{
internal class CAct演奏レーンフラッシュGB共通 : CActivity
{
// プロパティ
// コンストラクタ
public CAct演奏レーンフラッシュGB共通()
{
base.b活性化してない = true;
}
// メソッド
// CActivity 実装
public override void On活性化()
{
base.On活性化();
}
public override void On非活性化()
{
base.On非活性化();
}
public override void OnManagedリソースの作成()
{
if( !base.b活性化してない )
{
base.OnManagedリソースの作成();
}
}
public override void OnManagedリソースの解放()
{
if( !base.b活性化してない )
{
base.OnManagedリソースの解放();
}
}
}
}
| 12.38 | 46 | 0.628433 | [
"MIT"
] | NSU4zYPZKjMS/apo-3-Release | DTXManiaプロジェクト/コード/ステージ/07.演奏/CAct演奏レーンフラッシュGB共通.cs | 831 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using Microsoft.OpenApi.Properties;
namespace Microsoft.OpenApi.Exceptions
{
/// <summary>
/// Exception type representing exceptions in the OpenAPI writer.
/// </summary>
public class OpenApiWriterException : OpenApiException
{
/// <summary>
/// Creates a new instance of the <see cref="OpenApiWriterException"/> class with default values.
/// </summary>
public OpenApiWriterException()
: this(SRResource.OpenApiWriterExceptionGenericError)
{
}
/// <summary>
/// Creates a new instance of the <see cref="OpenApiWriterException"/> class with an error message.
/// </summary>
/// <param name="message">The plain text error message for this exception.</param>
public OpenApiWriterException(string message)
: this(message, null)
{
}
/// <summary>
/// Creates a new instance of the <see cref="OpenApiWriterException"/> class with an error message and an inner exception.
/// </summary>
/// <param name="message">The plain text error message for this exception.</param>
/// <param name="innerException">The inner exception that is the cause of this exception to be thrown.</param>
public OpenApiWriterException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
| 36.47619 | 130 | 0.640339 | [
"MIT"
] | CenterEdge/OpenAPI.NET | src/Microsoft.OpenApi/Exceptions/OpenApiWriterException.cs | 1,534 | C# |
/* Copyright 2020-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Bson.TestHelpers.JsonDrivenTests;
using MongoDB.Driver.Core;
using MongoDB.Driver.Core.Bindings;
using MongoDB.Driver.Core.Clusters;
using MongoDB.Driver.Core.Events;
using MongoDB.Driver.Core.Servers;
using MongoDB.Driver.Core.TestHelpers;
using MongoDB.Driver.Tests.JsonDrivenTests;
using MongoDB.Driver.Tests.Specifications.Runner;
using Xunit;
namespace MongoDB.Driver.Tests.Specifications.server_discovery_and_monitoring
{
public class ServerDiscoveryAndMonitoringIntegrationTestRunner : DisposableJsonDrivenTestRunner, IJsonDrivenTestRunner
{
public ICluster FailPointCluster => DriverTestConfiguration.Client.Cluster;
public IServer FailPointServer => _failPointServer;
protected override string[] ExpectedTestColumns => new[] { "description", "failPoint", "clientOptions", "operations", "expectations", "outcome", "async" };
// public methods
public void ConfigureFailPoint(IServer server, ICoreSessionHandle session, BsonDocument failCommand)
{
ConfigureFailPointCommand(failCommand);
var failPoint = FailPoint.Configure(server, session, failCommand);
AddDisposable(failPoint);
}
public async Task ConfigureFailPointAsync(IServer server, ICoreSessionHandle session, BsonDocument failCommand)
{
ConfigureFailPointCommand(failCommand);
var failPoint = await Task.Run(() => FailPoint.Configure(server, session, failCommand)).ConfigureAwait(false);
AddDisposable(failPoint);
}
[SkippableTheory]
[ClassData(typeof(TestCaseFactory))]
public void Run(JsonDrivenTestCase testCase)
{
SetupAndRunTest(testCase);
}
// protected methods
protected override JsonDrivenTestFactory CreateJsonDrivenTestFactory(IMongoClient mongoClient, string databaseName, string collectionName, Dictionary<string, object> objectMap, EventCapturer eventCapturer)
{
return new JsonDrivenTestFactory(this, mongoClient, databaseName, collectionName, bucketName: null, objectMap, eventCapturer);
}
protected override List<object> ExtractEventsForAsserting(EventCapturer eventCapturer)
{
return base
.ExtractEventsForAsserting(eventCapturer)
.Where(@event => @event is CommandStartedEvent) // apply events asserting only for this event
.ToList();
}
protected override EventCapturer InitializeEventCapturer(EventCapturer eventCapturer)
{
var doNotCaptureEvents = DefaultCommandsToNotCapture;
doNotCaptureEvents.Add("configureFailPoint");
doNotCaptureEvents.Add("replSetStepDown");
return eventCapturer.Capture<CommandStartedEvent>(e => !doNotCaptureEvents.Contains(e.CommandName))
.Capture<ServerDescriptionChangedEvent>()
.Capture<ConnectionPoolClearedEvent>()
.Capture<ConnectionPoolReadyEvent>();
}
// nested types
private class TestCaseFactory : JsonDrivenTestCaseFactory
{
// protected properties
protected override string PathPrefix => "MongoDB.Driver.Tests.Specifications.server_discovery_and_monitoring.tests.integration.";
// protected methods
protected override IEnumerable<JsonDrivenTestCase> CreateTestCases(BsonDocument document)
{
var testCases = base.CreateTestCases(document);
foreach (var testCase in testCases)
{
foreach (var async in new[] { false, true })
{
var name = $"{testCase.Name}:async={async}";
var test = testCase.Test.DeepClone().AsBsonDocument.Add("async", async);
yield return new JsonDrivenTestCase(name, testCase.Shared, test);
}
}
}
}
}
}
| 42.927273 | 213 | 0.683185 | [
"Apache-2.0"
] | LaudateCorpus1/mongo-csharp-driver | tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/ServerDiscoveryAndMonitoringIntegrationTestRunner.cs | 4,724 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using StoreProject.Api.Data;
using StoreProject.Commands;
using StoreProject.Models.Shopping;
namespace StoreProject.Api.Controllers {
[Route("api/[controller]")]
[ApiController]
public class ProdutoController : ControllerBase {
private readonly StoreProjectDbContext _context;
public ProdutoController(StoreProjectDbContext context) {
_context = context;
}
[HttpGet]
[Route("seedProducts")]
public async Task<IActionResult> SeedProducts() {
try {
var prodList = new List<Produto> {
new Produto("Jaqueta de pele de Chinchila", "Jaqueta de pele de chinchila e vison marrom tosquiada EM-EL feminino", "https://images-na.ssl-images-amazon.com/images/I/61iEsBFNfuL._AC_UL1200_.jpg", 4350),
new Produto("Jaqueta de pele de Zibelina", "Sable suntuosa! Esta linda jaqueta de pele apresenta uma gola de pele de marta canadense com lapidação cruzada e punhos virados para trás em uma jaqueta clássica de pele de vison tingida de preto", "https://images-na.ssl-images-amazon.com/images/I/51m0WNQm8fL._AC_UL1200_.jpg", 6420),
new Produto("Casaco de pele sintética Remelon", "Casaco de pele sintética Remelon feminino de manga longa inverno quente lapela raposa casaco de pele falsa sobretudo com bolsos", "https://images-na.ssl-images-amazon.com/images/I/61tib8HwyRL._AC_UL1000_.jpg", 840),
new Produto("Casaco de pele sintética Remelon Amarelo", "Casaco de pele sintética Remelon feminino de manga longa inverno quente lapela raposa casaco de pele falsa sobretudo com bolsos", "https://m.media-amazon.com/images/I/71pLLeGu0YL._AC_UL1292_.jpg", 890),
//new
new Produto("Mr/s Camisa", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut in aenean.", "https://images3.pricecheck.co.za/images/objects/hash/product/90d/05a/6af/image_big_168671010.jpg?1564052074", 154),
new Produto("Cringe. T-shirt", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut in aenean.", "https://designslots.com/wp-content/uploads/2015/06/Cover6-250x150.jpg", 140),
new Produto("Baby Toon", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut in aenean.", "https://lh3.googleusercontent.com/proxy/QwhgzaYM6bfSypXwwqjGuPAvSaKUrFkNhBtyfEdd1wKp2c003PPdyjzaGUUdClKcFLgw55bFEaY3yAQ6GAUK8pboKDkoaPeq3NtsAU72zVUTLEqGpzE_YmETgNQoLzsm7OIgEK21dW--htK2YSFVkYpnvLp2Mmj0pA", 200),
new Produto("OPL T-Shirt series", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut in aenean.", "https://opl.lib.in.us/wp-content/uploads/2020/04/shirt-a-250x150.png", decimal.Parse("241,50"))
};
var finalList = new List<Produto>();
foreach(var item in prodList) {
if (!_context.Produtos.AnyAsync(x => x.Nome == item.Nome).Result) finalList.Add(item);
}
if(finalList.Count > 1)
await _context.Produtos.AddRangeAsync(finalList);
await _context.SaveChangesAsync();
return Ok("Finalizado");
}
catch (Exception ex) {
return BadRequest(ex.Message);
}
}
[HttpGet]
[Route("getallproducts")]
public async Task<IActionResult> GetAllProductsAsync() {
try {
var list = await _context.Produtos.ToListAsync();
if (list.Count > 0)
return Ok(list);
else
return StatusCode(204, "Sem dados registrados");
}
catch(Exception ex) {
return BadRequest(ex.Message);
}
}
[HttpPost]
[Route("realizarcompra")]
public async Task<IActionResult> RealizarCompraAsync([FromBody]RealizarCompraCommand model) {
try {
decimal total = 0;
foreach (var item in model.Compras) {
total += (item.Produto.Preco * item.Quantidade);
}
var novaCompra = new HistoricoCompras(Guid.Parse(model.UserId), model.Compras, total);
await _context.HistoricoCompras.AddAsync(novaCompra);
await _context.SaveChangesAsync();
return Ok("Compra realizada com sucesso.");
}
catch (Exception ex) {
return BadRequest(ex.Message);
}
}
}
}
| 45.093458 | 348 | 0.629845 | [
"MIT"
] | danncarloss/store-project | StoreProject.Api/StoreProject.Api/Controllers/ProdutoController.cs | 4,835 | C# |
// Screen WebAPI by Mozilla Contributors is licensed under CC-BY-SA 2.5.
// https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList
using System;
using Bridge;
namespace Bridge.Html5
{
/// <summary>
/// A MediaQueryList object maintains a list of media queries on a document, and handles sending notifications to listeners when the media queries on the document change.
/// This makes it possible to observe a document to detect when its media queries change, instead of polling the values periodically, if you need to programmatically detect changes to the values of media queries on a document.
/// </summary>
[Ignore]
[Name("MediaQueryList")]
public class MediaQueryList
{
private MediaQueryList()
{
}
/// <summary>
/// Adds a new listener to the media query list. If the specified listener is already in the list, this method has no effect.
/// </summary>
/// <param name="listener">The MediaQueryListListener to invoke when the media query's evaluated result changes.</param>
public virtual void AddListener(Delegate listener)
{
}
/// <summary>
/// Adds a new listener to the media query list. If the specified listener is already in the list, this method has no effect.
/// </summary>
/// <param name="listener">The MediaQueryListListener to invoke when the media query's evaluated result changes.</param>
public virtual void AddListener(Action<MediaQueryList> listener)
{
}
/// <summary>
/// Removes a listener from the media query list. Does nothing if the specified listener isn't already in the list.
/// </summary>
/// <param name="listener">The MediaQueryListListener to stop calling on changes to the media query's evaluated result.</param>
public virtual void RemoveListener(Delegate listener)
{
}
/// <summary>
/// Removes a listener from the media query list. Does nothing if the specified listener isn't already in the list.
/// </summary>
/// <param name="listener">The MediaQueryListListener to stop calling on changes to the media query's evaluated result.</param>
public virtual void RemoveListener(Action<MediaQueryList> listener)
{
}
/// <summary>
/// true if the document currently matches the media query list; otherwise false. Read only.
/// </summary>
public readonly bool Matches;
/// <summary>
/// The serialized media query list.
/// </summary>
public readonly string Media;
}
}
| 41.153846 | 230 | 0.656822 | [
"Apache-2.0"
] | BenitoJedai/Bridge | Html5/MediaQueryList.cs | 2,677 | C# |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2021 Ingo Herbote
* https://www.yetanotherforum.net/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace YAF.Web.BBCodes
{
using System.Web.UI;
using YAF.Configuration;
using YAF.Core.BBCode;
using YAF.Core.Extensions;
using YAF.Core.Helpers;
using YAF.Core.Model;
using YAF.Types.Constants;
using YAF.Types.Extensions;
using YAF.Types.Interfaces;
using YAF.Types.Models;
/// <summary>
/// The Attachment BB Code Module.
/// </summary>
public class Attach : BBCodeControl
{
/// <summary>
/// Render The Album Image as Link with Image
/// </summary>
/// <param name="writer">The writer.</param>
protected override void Render(HtmlTextWriter writer)
{
if (!ValidationHelper.IsNumeric(this.Parameters["inner"]))
{
return;
}
var attachment = this.GetRepository<Attachment>().GetSingleById(this.Parameters["inner"].ToType<int>());
if (attachment == null)
{
return;
}
if (this.PageContext.ForumPageType is ForumPages.UserProfile or ForumPages.Board)
{
writer.Write(@"<i class=""fa fa-file fa-fw""></i> {0}", attachment.FileName);
return;
}
var filename = attachment.FileName.ToLower();
var showImage = false;
// verify it's not too large to display
// Ederon : 02/17/2009 - made it board setting
if (attachment.Bytes.ToType<int>() <= this.PageContext.BoardSettings.PictureAttachmentDisplayTreshold)
{
// is it an image file?
showImage = filename.IsImageName();
}
// user doesn't have rights to download, don't show the image
if (!this.UserHasDownloadAccess())
{
writer.Write(
@"<i class=""fa fa-file fa-fw""></i> {0} <span class=""badge bg-warning text-dark"" role=""alert"">{1}</span>",
attachment.FileName,
this.GetText("ATTACH_NO"));
return;
}
if (showImage)
{
// user has rights to download, show him image
if (this.PageContext.BoardSettings.EnableImageAttachmentResize)
{
writer.Write(
@"<div class=""card bg-dark text-white"" style=""max-width:{0}px"">",
this.PageContext.BoardSettings.ImageThumbnailMaxWidth);
writer.Write(
@"<a href=""{0}resource.ashx?i={1}&b={3}"" title=""{2}"" data-gallery=""#blueimp-gallery-{4}"">",
BoardInfo.ForumClientFileRoot,
attachment.ID,
this.HtmlEncode(attachment.FileName),
this.PageContext.PageBoardID,
this.MessageID.Value);
writer.Write(
@"<img src=""{0}resource.ashx?p={1}&b={3}"" alt=""{2}"" class=""img-user-posted card-img-top"" style=""max-height:{4}px"">",
BoardInfo.ForumClientFileRoot,
attachment.ID,
this.HtmlEncode(attachment.FileName),
this.PageContext.PageBoardID,
this.PageContext.BoardSettings.ImageThumbnailMaxHeight);
writer.Write(@"</a>");
writer.Write(
@"<div class=""card-body py-1""><p class=""card-text small"">{0}",
this.GetText("IMAGE_RESIZE_ENLARGE"));
writer.Write(
@"<span class=""text-muted float-end"">{0}</span></p>",
this.GetTextFormatted("IMAGE_RESIZE_VIEWS", attachment.Downloads));
writer.Write(@"</div></div>");
}
else
{
writer.Write(
@"<img src=""{0}resource.ashx?a={1}&b={3}"" alt=""{2}"" class=""img-user-posted img-thumbnail"" style=""max-height:{4}px"">",
BoardInfo.ForumClientFileRoot,
attachment.ID,
this.HtmlEncode(attachment.FileName),
this.PageContext.PageBoardID,
this.PageContext.BoardSettings.ImageThumbnailMaxHeight);
}
}
else
{
// regular file attachment
var kb = (1023 + attachment.Bytes.ToType<int>()) / 1024;
writer.Write(
@"<i class=""fa fa-file fa-fw""></i>
<a href=""{0}resource.ashx?a={1}&b={4}"">{2}</a>
<span>{3}</span>",
BoardInfo.ForumClientFileRoot,
attachment.ID,
attachment.FileName,
this.GetTextFormatted("ATTACHMENTINFO", kb, attachment.Downloads),
this.PageContext.PageBoardID);
}
}
/// <summary>
/// Checks if the user has download access.
/// </summary>
/// <returns>
/// The <see cref="bool"/>.
/// </returns>
private bool UserHasDownloadAccess()
{
return this.PageContext.ForumPageType is ForumPages.PrivateMessage or ForumPages.PostPrivateMessage ||
this.PageContext.ForumDownloadAccess;
}
}
} | 40.095808 | 150 | 0.514785 | [
"Apache-2.0"
] | Spinks90/YAFNET | yafsrc/YAF.Web/BBCodes/Attach.cs | 6,533 | C# |
namespace PhotoShare.Models.Enums
{
public enum Color
{
White,
Green,
Blue,
Pink,
Yellow,
Black,
Cyan,
Magenta,
Red,
Purple,
WhiteBlackGradient
}
}
| 14.777778 | 35 | 0.421053 | [
"MIT"
] | morskibg/CS_TrainingAtHome | Photoshare/PhotoShare.Models/Enums/Color.cs | 268 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EmbedExcelIntoWordDoc")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EmbedExcelIntoWordDoc")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("91c88525-c6bf-46aa-857b-072643bf6a58")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.243243 | 84 | 0.74841 | [
"MIT"
] | Ranin26/msdn-code-gallery-microsoft | OneCodeTeam/How to embed Excel sheet into Word Document by using Open XML SDK/[C#]-How to embed Excel sheet into Word Document by using Open XML SDK/C#/Properties/AssemblyInfo.cs | 1,418 | C# |
using ZimaHrm.Data.Entity;
using ZimaHrm.Data.Repository.Base;
namespace ZimaHrm.Data.Repository.PaySlip
{
public class EmployeePaySlipRepository : BaseRepository<EmployeePaySlip>, IEmployeePaySlipRepository
{
public EmployeePaySlipRepository(AppDbContext context) : base(context)
{
}
}
}
| 25.153846 | 104 | 0.737003 | [
"Apache-2.0"
] | Dakicksoft/ZimaHrm | ZimaHrm.Data/Repository/PaySlip/EmployeePaySlipRepository.cs | 329 | C# |
using System;
using System.Text;
using System.Collections.Generic;
namespace Pyro.Language.Impl
{
/// <inheritdoc cref="LexerBase" />
/// <summary>
/// Common to all Lexers
/// </summary>
/// <typeparam name="TEnum">The enumeration type for tokens in the language</typeparam>
/// <typeparam name="TToken">The token type to use</typeparam>
/// <typeparam name="TTokenFactory">How to make Tokens</typeparam>
public abstract class LexerCommon<TEnum, TToken, TTokenFactory>
: LexerBase
, ILexerCommon<TToken>
where TToken : class, ITokenBase<TEnum>, new()
where TTokenFactory : class, ITokenFactory<TEnum, TToken>, new()
{
public IList<TToken> Tokens => _Tokens;
protected List<TToken> _Tokens = new List<TToken>();
protected Dictionary<string, TEnum> _KeyWords = new Dictionary<string, TEnum>();
protected Dictionary<TEnum, string> _KeyWordsInvert = new Dictionary<TEnum, string>();
protected TTokenFactory _Factory = new TTokenFactory();
public TToken ErrorToken;
protected LexerCommon(string input)
: base(input)
=> _Factory.SetLexer(this);
protected override void LexError(string fmt, params object[] args) => Error = string.Format(fmt, args);
protected override void AddStringToken(Slice slice) => _Tokens.Add(_Factory.NewTokenString(slice));
protected virtual bool NextToken() => false;
protected virtual void Terminate() { }
protected virtual void AddKeyWords() { }
public TEnum StringToEnum(string str)
=> _KeyWords.TryGetValue(str, out var e) ? e : default;
public string EnumToString(TEnum e)
=> _KeyWordsInvert.TryGetValue(e, out var str) ? str : e.ToString();
public bool Process()
{
AddKeyWords();
CreateLines();
return Run();
}
public override string ToString()
{
var str = new StringBuilder();
foreach (var tok in _Tokens)
str.Append($"{tok}, ");
return str.ToString();
}
protected bool Run()
{
_offset = 0;
_lineNumber = 0;
while (!Failed && NextToken())
;
Terminate();
return !Failed;
}
protected TToken LexAlpha()
{
var tok = _Factory.NewTokenIdent(Gather(char.IsLetter));
if (_KeyWords.TryGetValue(tok.ToString(), out var en))
tok.Type = en;
return tok;
}
protected bool AddSlice(TEnum type, Slice slice)
{
_Tokens.Add(_Factory.NewToken(type, slice));
return true;
}
protected bool Add(TEnum type, int len = 1)
{
AddSlice(type, new Slice(this, _offset, _offset + len));
while (len-- > 0)
Next();
return true;
}
protected bool AddIfNext(char ch, TEnum thenType, TEnum elseType)
{
if (Peek() != ch)
return Add(elseType, 1);
Add(thenType, 2);
Next();
return true;
}
protected bool AddTwoCharOp(TEnum ty)
{
Add(ty, 2);
return true;
}
protected bool AddThreeCharOp(TEnum ty)
{
Add(ty, 3);
Next();
return true;
}
protected bool LexError(string text)
=> Fail(CreateErrorMessage(_Factory.NewEmptyToken(new Slice(this, _offset, _offset)), text, Current()));
public string CreateErrorMessage(TToken tok, string fmt, params object[] args)
{
ErrorToken = tok;
var buff = $"({tok.LineNumber}):[{tok.Slice.Start}]: {string.Format(fmt, args)}";
const int beforeContext = 2;
const int afterContext = 2;
var lex = tok.Lexer;
var start = Math.Max(0, tok.LineNumber - beforeContext);
var end = Math.Min(lex.Lines.Count - 1, tok.LineNumber + afterContext);
var str = new StringBuilder();
str.AppendLine(buff);
for (var n = start; n <= end; ++n)
{
foreach (var ch in lex.GetLine(n))
{
if (ch == '\t')
str.Append(" ");
else
str.Append(ch);
}
if (n != tok.LineNumber)
continue;
for (var ch = 0; ch < lex.GetLine(n).Length; ++ch)
{
if (ch == tok.Slice.Start)
{
str.Append('^');
break;
}
var c = lex.GetLine(tok.LineNumber)[ch];
if (c == '\t')
str.Append(" ");
else
str.Append(' ');
}
}
return str.ToString();
}
}
}
| 29.918605 | 116 | 0.503692 | [
"MIT"
] | cschladetsch/Diver | Library/Language/Common/Impl/LexerCommon.cs | 5,148 | C# |
using Tesseract.Core.Graphics.Accelerated;
using Tesseract.Vulkan.Graphics.Impl;
namespace Tesseract.Vulkan.Graphics {
public class VulkanGraphicsLimits : IGraphicsLimits {
public VulkanPhysicalDeviceInfo DeviceInfo { get; }
public uint MaxTextureDimension1D => DeviceInfo.Limits.MaxImageDimension1D;
public uint MaxImageDimension2D => DeviceInfo.Limits.MaxImageDimension2D;
public uint MaxTextureDimension3D => DeviceInfo.Limits.MaxImageDimension3D;
public uint MaxTextureDimensionCube => DeviceInfo.Limits.MaxImageDimensionCube;
public uint MaxTextureArrayLayers => DeviceInfo.Limits.MaxImageArrayLayers;
public uint MaxTexelBufferElements => DeviceInfo.Limits.MaxTexelBufferElements;
public uint MaxUniformBufferRange => DeviceInfo.Limits.MaxUniformBufferRange;
public uint MaxStorageBufferRange => DeviceInfo.Limits.MaxStorageBufferRange;
public uint MaxPushConstantSize => DeviceInfo.Limits.MaxPushConstantsSize;
public uint MaxSamplerObjects => DeviceInfo.Limits.MaxSamplerAllocationCount;
public ulong SparseAddressSpaceSize => DeviceInfo.Limits.SparseAddressSpaceSize;
public uint MaxBoundSets => DeviceInfo.Limits.MaxBoundDescriptorSets;
public uint MaxPerStageSamplers => DeviceInfo.Limits.MaxPerStageDescriptorSamplers;
public uint MaxPerStageUniformBuffers => DeviceInfo.Limits.MaxPerStageDescriptorUniformBuffers;
public uint MaxPerStageStorageBuffers => DeviceInfo.Limits.MaxPerStageDescriptorSamplers;
public uint MaxPerStageSampledImages => DeviceInfo.Limits.MaxPerStageDescriptorSampledImages;
public uint MaxPerStageStorageImages => DeviceInfo.Limits.MaxPerStageDescriptorStorageImages;
public uint MaxPerStageInputAttachments => DeviceInfo.Limits.MaxPerStageDescriptorInputAttachments;
public uint MaxPerStageResources => DeviceInfo.Limits.MaxPerStageResources;
public uint MaxPerLayoutSamplers => DeviceInfo.Limits.MaxDescriptorSetSamplers;
public uint MaxPerLayoutUniformBuffers => DeviceInfo.Limits.MaxDescriptorSetUniformBuffers;
public uint MaxPerLayoutDynamicUniformBuffers => DeviceInfo.Limits.MaxDescriptorSetUniformBuffersDynamic;
public uint MaxPerLayoutStorageBuffers => DeviceInfo.Limits.MaxDescriptorSetStorageBuffers;
public uint MaxPerLayoutDynamicStorageBuffers => DeviceInfo.Limits.MaxDescriptorSetStorageBuffersDynamic;
public uint MaxPerLayoutSampledImages => DeviceInfo.Limits.MaxDescriptorSetSampledImages;
public uint MaxPerLayoutStorageImages => DeviceInfo.Limits.MaxDescriptorSetStorageImages;
public uint MaxPerLayoutInputAttachments => DeviceInfo.Limits.MaxDescriptorSetInputAttachments;
public uint MaxVertexAttribs => DeviceInfo.Limits.MaxVertexInputAttributes;
public uint MaxVertexBindings => DeviceInfo.Limits.MaxVertexInputBindings;
public uint MaxVertexAttribOffset => DeviceInfo.Limits.MaxVertexInputAttributeOffset;
public uint MaxVertexBindingStride => DeviceInfo.Limits.MaxVertexInputBindingStride;
public uint MaxVertexStageOutputComponents => DeviceInfo.Limits.MaxVertexOutputComponents;
public uint MaxTessellationGenerationLevel => DeviceInfo.Limits.MaxTessellationGenerationLevel;
public uint MaxTessellationPatchSize => DeviceInfo.Limits.MaxTessellationPatchSize;
public uint MaxTessellationControlInputComponents => DeviceInfo.Limits.MaxTessellationControlPerVertexInputComponents;
public uint MaxTessellationControlPerVertexOutputComponents => DeviceInfo.Limits.MaxTessellationControlPerVertexOutputComponents;
public uint MaxTessellationControlPerPatchOutputComponents => DeviceInfo.Limits.MaxTessellationControlPerPatchOutputComponents;
public uint MaxTessellationControlTotalOutputComponents => DeviceInfo.Limits.MaxTessellationControlTotalOutputComponents;
public uint MaxTessellationEvaluationInputComponents => DeviceInfo.Limits.MaxTessellationEvaluationInputComponents;
public uint MaxTessellationEvaluationOutputComponents => DeviceInfo.Limits.MaxTessellationEvaluationOutputComponents;
public uint MaxGeometryShaderInvocations => DeviceInfo.Limits.MaxGeometryShaderInvocations;
public uint MaxGeometryInputComponents => DeviceInfo.Limits.MaxGeometryInputComponents;
public uint MaxGeometryOutputComponents => DeviceInfo.Limits.MaxGeometryOutputComponents;
public uint MaxGeometryOutputVertices => DeviceInfo.Limits.MaxGeometryOutputVertices;
public uint MaxGeometryTotalOutputComponents => DeviceInfo.Limits.MaxGeometryTotalOutputComponents;
public (float, float) PointSizeRange {
get {
var range = DeviceInfo.Limits.PointSizeRange;
return (range.X, range.Y);
}
}
public (float, float) LineWidthRange {
get {
var range = DeviceInfo.Limits.LineWidthRange;
return (range.X, range.Y);
}
}
public float PointSizeGranularity => DeviceInfo.Limits.PointSizeGranularity;
public float LineWidthGranularity => DeviceInfo.Limits.LineWidthGranularity;
public VulkanGraphicsLimits(VulkanPhysicalDeviceInfo info) {
DeviceInfo = info;
}
}
}
| 61.8875 | 131 | 0.850333 | [
"Apache-2.0"
] | Zekrom64/TesseractEngine | TesseractEngine-Vulkan/Vulkan/Graphics/GraphicsLimits.cs | 4,953 | C# |
using Moonbyte.MaterialFramework.Events;
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
#region Legal Stuff
/*
MIT License
Copyright (c) 2015 - 2016 Vortex Studio (Inactive), 2015 - 2017 Indie Goat (Current Holder)
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.
Support us! https://www.patreon.com/vortexstudio
our website : https://vortexstudio.us
*/
#endregion
namespace Moonbyte.MaterialFramework.Controls
{
/// <summary>
/// Custom tab page, used to handle the Icon for the tab.
/// </summary>
[System.ComponentModel.ToolboxItem(false)]
[DesignTimeVisible(true)]
public class MaterialTabPage : TabPage
{
//Private local icon
public Image icon;
#region Custom Events
public event EventHandler<TabIconChangeArgs> TabIconChange;
public event EventHandler<EventArgs> TabTextChanged;
#endregion
#region Custom Method's
/// <summary>
/// Used to trigger the text changed event.
/// </summary>
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
//Trigger the TextChanged event
TabTextChanged?.Invoke(this, new EventArgs());
}
/// <summary>
/// Used to change the private var icon
/// </summary>
/// <param name="ico">Image var, used to chage the private var icon</param>
public void ChangeTabIcon(Image ico)
{
//Invoke the TabIconChangeArgs if not null with the attached icon
TabIconChange?.Invoke(this, new TabIconChangeArgs { icon = ico });
//Change the local Icon to the image
icon = ico;
}
#endregion
}
}
| 31.078652 | 91 | 0.69342 | [
"MIT"
] | OfficialIndieGoat/Material-Framework | MaterialFramework/MaterialFramework/Controls/Tab Control/MaterialTabPage.cs | 2,768 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RestaurantUI
{
public class MainMenu : IMenu
{
public void Display()
{
Console.WriteLine("Welcome to this Restuarant Application.");
Console.WriteLine("Please choose an option.");
Console.WriteLine("Press <1> Create Restaurant");
Console.WriteLine("Press <2> Create User");
Console.WriteLine("Press <3> Create Review");
Console.WriteLine("Press <4> Filter Search");
Console.WriteLine("Press <5> Display Restaurant");
Console.WriteLine("Press <6> Display User");
Console.WriteLine("Press <7> Display Review");
Console.WriteLine("Press <0> Exit");
}
/// <summary>
/// Goes to the correct menu
/// </summary>
/// <returns></returns>
public string UserChoice()
{
string otherinpute = Console.ReadLine();
switch (otherinpute)
{
case "0":
return "Exit";
case "1":
return "Create Restaurant";
case "2":
return "Create User";
case "3":
return "Create Review";
case "4":
return "Filtered Search";
case "5":
return "Display Restaurant";
case "6":
return "Display User";
case "7":
return "Display Review";
default:
Console.WriteLine("View does not exist");
Console.WriteLine("Please press <enter> to continue");
Console.ReadLine();
return "MainMenu";
}
}
}
}
| 29.939394 | 74 | 0.469636 | [
"MIT"
] | 220328-uta-sh-net-ext/Daniel-Oszczapinski | Project 1/RestaurantApp/RestaurantUI/MainMenu.cs | 1,978 | C# |
//
// Copyright (c) 2019-2021 Angouri.
// AngouriMath is licensed under MIT.
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
// Website: https://am.angouri.org.
//
using AngouriMath.Extensions;
using Xunit;
namespace UnitTests.PatternsTest
{
public sealed class SortSimplifyTest
{
[Theory]
[InlineData("a + x + e + d + sin(x) + c + 1 + 2 + 2a", "3 * a")]
[InlineData("x + a + b + c + arcsin(x2) + d + e + 1/2 - 23 * sqrt(3) + arccos(x * x)", "pi / 2")]
[InlineData("x + a + b + c + arctan(x2) + d + e + 1/2 - 23 * sqrt(3) + arccot(x * x)", "pi / 2")]
[InlineData("a / b + c + d + e + f + sin(x) + arcsin(x) + 1 + 0 - a * (b ^ -1)", "a / b", false)]
// Skipped
// [InlineData("sin(arcsin(c x) + arccos(x c) + c)2 + a + b + sin(x) + 0 + cos(c - -arcsin(c x) - -arccos(-c x * (-1)))2", "1")]
// [InlineData("sin(arcsin(c x) + arccos(x c) + c)2 + a + b + sin(x) + 0 + cos(c - -arcsin(c x) - -arccos(-c x * (-1)))2", ") ^ 2", false)]
[InlineData("sec(x) + a + sin(x) + c + 1 + 0 + 3 + sec(x)", "2 * sec(x)")]
[InlineData("tan(x) * a * b / c / sin(h + 0.1) * cotan(x)", "tan", false)]
[InlineData("sin(x) * a * b / c / sin(h + 0.1) * cosec(x)", "cosec", false)]
[InlineData("cos(x) * a * b / c / sin(h + 0.1) * sec(x)", "cos", false)]
[InlineData("sec(x) * a * b / c / sin(h + 0.1) * cos(x)", "sec", false)]
[InlineData("cosec(x) * a * b / c / sin(h + 0.1) * sin(x)", "cosec", false)]
public void TestStringIn(string exprRaw, string toBeIn, bool ifToBeIn = true)
{
var entity = exprRaw.ToEntity();
var actual = entity.Simplify(5);
if (ifToBeIn)
Assert.Contains(toBeIn, actual.Stringize());
else
Assert.DoesNotContain(toBeIn, actual.Stringize());
}
}
}
| 47.75 | 147 | 0.497382 | [
"MIT"
] | asc-community/AngouriMath | Sources/Tests/UnitTests/PatternsTest/SortSimplifyTest.cs | 1,912 | C# |
namespace SirJoshSpeedyComputer.Forms {
partial class Form1 {
/// <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(Form1));
this.button1 = new System.Windows.Forms.Button();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.updateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// button1
//
this.button1.Dock = System.Windows.Forms.DockStyle.Fill;
this.button1.Location = new System.Drawing.Point(0, 24);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(213, 28);
this.button1.TabIndex = 1;
this.button1.Text = "Kill not required processes";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.updateToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(213, 24);
this.menuStrip1.TabIndex = 2;
this.menuStrip1.Text = "menuStrip1";
//
// updateToolStripMenuItem
//
this.updateToolStripMenuItem.Name = "updateToolStripMenuItem";
this.updateToolStripMenuItem.Size = new System.Drawing.Size(57, 20);
this.updateToolStripMenuItem.Text = "Update";
this.updateToolStripMenuItem.Click += new System.EventHandler(this.updateToolStripMenuItem_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(213, 52);
this.Controls.Add(this.button1);
this.Controls.Add(this.menuStrip1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip1;
this.Name = "Form1";
this.Text = "Speed Computer";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem updateToolStripMenuItem;
}
}
| 36.586207 | 129 | 0.699026 | [
"MIT"
] | SirJosh3917/SirJoshSpeedyComputer | SirJosh Speedy Computer/SirJosh Speedy Computer/Form1.Designer.cs | 3,185 | C# |
using OpenRPA.Interfaces;
using OpenRPA.Interfaces.entity;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace OpenRPA.FileWatcher.Views
{
public partial class FileWatcherView : UserControl, INotifyPropertyChanged
{
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
public FileWatcherView(FileWatcherDetectorPlugin plugin)
{
InitializeComponent();
this.plugin = plugin;
DataContext = this;
}
private FileWatcherDetectorPlugin plugin;
public IDetector Entity
{
get
{
return plugin.Entity;
}
}
public string EntityName
{
get
{
if (Entity == null) return string.Empty;
return Entity.name;
}
set
{
Entity.name = value;
NotifyPropertyChanged("Entity");
}
}
public string EntityPath
{
get
{
return plugin.Watchpath;
}
set
{
plugin.Watchpath = value;
plugin.Stop();
plugin.Start();
NotifyPropertyChanged("Entity");
}
}
public string EntityFilter
{
get
{
return plugin.WatchFilter;
}
set
{
plugin.WatchFilter = value;
plugin.Stop();
plugin.Start();
NotifyPropertyChanged("Entity");
}
}
public bool IncludeSubdirectories
{
get
{
return plugin.IncludeSubdirectories;
}
set
{
plugin.IncludeSubdirectories = value;
plugin.Stop();
plugin.Start();
NotifyPropertyChanged("Entity");
}
}
private void Open_Selector_Click(object sender, RoutedEventArgs e)
{
}
private void Highlight_Click(object sender, RoutedEventArgs e)
{
}
private void Select_Click(object sender, RoutedEventArgs e)
{
}
private void StartRecordPlugins()
{
}
private void StopRecordPlugins()
{
}
public void OnUserAction(Interfaces.IRecordPlugin sender, Interfaces.IRecordEvent e)
{
}
}
}
| 26.820513 | 108 | 0.534098 | [
"MPL-2.0"
] | accabral/openrpa | OpenRPA.FileWatcher/Views/FileWatcherView.xaml.cs | 3,140 | C# |
////////////////////////////////////////////////////////////////////////////////
//EF Core Provider for LCPI OLE DB.
// IBProvider and Contributors. 02.04.2019.
using System;
using System.Diagnostics;
using System.Linq.Expressions;
namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Root.Query.Local.Expressions.Methods.Translators{
////////////////////////////////////////////////////////////////////////////////
//using
using Structure_TypeCache
=Structure.Structure_TypeCache;
using Structure_MethodIdCache
=Structure.Structure_MethodIdCache;
////////////////////////////////////////////////////////////////////////////////
//class ETranslator__Math__vrt__Round__NullableDouble
sealed class ETranslator__Math__vrt__Round__NullableDouble
:Root.Query.Local.LcpiOleDb__LocalEval_MethodCallTranslator
{
public static readonly Root.Query.Local.LcpiOleDb__LocalEval_MethodCallTranslator
Instance
=new ETranslator__Math__vrt__Round__NullableDouble();
//-----------------------------------------------------------------------
private ETranslator__Math__vrt__Round__NullableDouble()
:base(Structure_MethodIdCache.MethodIdOf__Math__vrt__Round__NullableDouble)
{
}//ETranslator__Math__vrt__Round__NullableDouble
//interface -------------------------------------------------------------
public override Expression Translate(in tagOpData opData)
{
Debug.Assert(!Object.ReferenceEquals(opData.MethodId,null));
Debug.Assert(opData.MethodId==Structure_MethodIdCache.MethodIdOf__Math__vrt__Round__NullableDouble);
//----------------------------------------
Debug.Assert(Object.ReferenceEquals(opData.CallObject,null));
Debug.Assert(!Object.ReferenceEquals(opData.Arguments,null));
Debug.Assert(opData.Arguments.Count==1);
Debug.Assert(!Object.ReferenceEquals(opData.Arguments[0],null));
Debug.Assert(opData.Arguments[0].Type==Structure_TypeCache.TypeOf__System_NullableDouble);
//----------------------------------------
var node_Arg0
=opData.Arguments[0];
Debug.Assert(!Object.ReferenceEquals(node_Arg0,null));
Debug.Assert(!Object.ReferenceEquals(node_Arg0.Type,null));
Debug.Assert(node_Arg0.Type==Structure_TypeCache.TypeOf__System_NullableDouble);
//----------------------------------------
var r
=Code.Method_Code__Math__Round__NullableDouble.CreateCallExpression
(node_Arg0);
Debug.Assert(!Object.ReferenceEquals(r,null));
return r;
}//Translate
};//class ETranslator__Math__vrt__Round__NullableDouble
////////////////////////////////////////////////////////////////////////////////
}//namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Root.Query.Local.Expressions.Methods.Translators
| 38.013889 | 121 | 0.638655 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Code/Provider/Source/Basement/EF/Root/Query/Local/Expressions/Methods/Translators/Math/ETranslator__Math__vrt__Round__nullableDouble.cs | 2,739 | C# |
using Core.Dtos.CategoryDtos;
using Core.Dtos.CommonDtos;
using Core.Dtos.Settings;
using Core.FilterAttributes;
using Core.Helpers;
using Core.Interfaces.CategoryProviders;
using Core.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
namespace Infrastructure.Services.CategoryProviders
{
public class CategoryManager : ICategoryManager
{
private readonly ApplicationDbContext _dbContext;
private readonly PanelAppSettings _appSettings;
public CategoryManager(
ApplicationDbContext dbContext,
IOptions<PanelAppSettings> appSettings)
{
_dbContext = dbContext;
_appSettings = appSettings.Value;
}
public async Task<(List<CategoryGridDto> Items, int TotalCount)> GetAllAsync(CategoryGridDto dto)
{
var query = _dbContext.Categories.Where(c => !c.Deleted);
if (dto.PageOrder != null)
{
query = query.OrderByField(dto.PageOrderBy, dto.PageOrder.ToLower() == "asc");
}
query = query.WhereIf(dto.Id.HasValue, c => c.Id == dto.Id);
query = query.WhereIf(!string.IsNullOrWhiteSpace(dto.Name), c => c.Translations.Any(t=>t.Name.Contains(dto.Name.Trim())));
query = query.WhereIf(!string.IsNullOrWhiteSpace(dto.ParentName), c => c.ParentId.HasValue && c.Parent.Translations.Any(t => t.Name.Contains(dto.ParentName.Trim())));
query = query.WhereIf(dto.IsActive.HasValue, c => c.IsActive == dto.IsActive);
if (!string.IsNullOrWhiteSpace(dto.CreatedOn))
{
var createdOnDateTime = DateTime.Parse(dto.CreatedOn);
query = query.Where(c => c.CreatedOn > createdOnDateTime.Date && c.CreatedOn < createdOnDateTime.Date.AddDays(1));
}
var totalCount = query.Count();
var take = _appSettings.PageSize;
var skip = (dto.ThisPageIndex - 1) * take;
query = query.Skip(skip).Take(take);
var items = await query.Select(category => new CategoryGridDto
{
Id = category.Id,
IsActive = category.IsActive,
Name = category.Translations.First(t=> t.Language == "fa").Name,
ParentName = category.ParentId.HasValue? category.Parent.Translations.First(t => t.Language == "fa").Name : "---",
CreatedOn = PersianDateHelper.ConvertToLocalDateTime(category.CreatedOn)
}).ToListAsync();
return (items, totalCount);
}
public Task<List<Select2ItemDto>> GetSelectListAsync(int? toExclude = null)
{
return _dbContext.Categories
.Where(c => !c.Deleted && c.ParentId == null && c.Id != toExclude)
.OrderByDescending(c => c.Id)
.Select(c => new Select2ItemDto
{
Id = c.Id.ToString(),
Text = c.Translations.First(t=>t.Language == "fa").Name
})
.ToListAsync();
}
public Task<List<JsTreeNode>> GetTreeAsync()
{
return _dbContext.Categories
.Where(c => !c.Deleted && c.IsActive)
.OrderByDescending(c => c.Id)
.Select(c => new JsTreeNode
{
Id = c.Id.ToString(),
Text = c.Translations.First(t => t.Language == "fa").Name,
Parent = c.ParentId.HasValue ? c.ParentId.ToString() : "#"
})
.ToListAsync();
}
public async Task<CategoryUpdateDto> GetAsync(int id)
{
var category = await _dbContext.Categories.Include(c=>c.Translations).Include(c=>c.Parent.Translations).FirstOrDefaultAsync(c => c.Id == id && !c.Deleted);
if(category == null)
{
return null;
}
return new CategoryUpdateDto
{
Id = category.Id,
IsActive = category.IsActive,
ParentId = category.ParentId,
ParentName = (category.ParentId.HasValue ? category.Parent.Translations.First(t => t.Language == "fa").Name : null),
Translations = category.Translations.Select(t => new CategoryTranslationDto { Language = t.Language, Name = t.Name })
};
}
public async Task<DeleteResultDto> DeleteAsync(int id)
{
var category = await _dbContext.Categories
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == id && !c.Deleted);
if (category == null)
{
return DeleteResultDto.NotFound(id.ToString());
}
using var transaction = _dbContext.Database.BeginTransaction();
try
{
category.Deleted = true;
category.DeletedOn = DateTime.Now;
_dbContext.Update(category);
_dbContext.Content2Categories.RemoveRange(_dbContext.Content2Categories.Where(t => t.CategoryId == id));
await _dbContext.SaveChangesAsync();
transaction.Commit();
return DeleteResultDto.Successful(id.ToString());
}
catch
{
return DeleteResultDto.UnknownError(id.ToString());
}
}
public async Task<ChangeStatusResultDto> ChangeStatusAsync(int id)
{
var propertyInfo = typeof(CategoryGridDto).GetProperty(nameof(CategoryGridDto.IsActive));
if (!propertyInfo.IsDefined(typeof(BooleanAttribute), false))
{
return ChangeStatusResultDto.NotPossible(id.ToString());
}
var booleanAttribute = propertyInfo.GetCustomAttributes(typeof(BooleanAttribute), false).Cast<BooleanAttribute>().SingleOrDefault();
var category = await _dbContext.Categories
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == id && !c.Deleted);
if (category == null)
{
return ChangeStatusResultDto.NotFound(id.ToString());
}
try
{
category.IsActive = !category.IsActive;
category.UpdatedOn = DateTime.Now;
_dbContext.Update(category);
await _dbContext.SaveChangesAsync();
if (category.IsActive)
{
return ChangeStatusResultDto.Successful(id.ToString(), booleanAttribute.TrueBadge, booleanAttribute.TrueText);
}
return ChangeStatusResultDto.Successful(id.ToString(), booleanAttribute.FalseBadge, booleanAttribute.FalseText);
}
catch
{
return ChangeStatusResultDto.UnknownError(id.ToString());
}
}
public async Task<CommandResultDto> CreateAsync(CategoryCreateDto dto)
{
var translations = JsonSerializer.Deserialize<List<CategoryTranslation>>(dto.Names, options: new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if(translations.Any(t=> string.IsNullOrWhiteSpace(t.Name)))
{
return CommandResultDto.InvalidModelState(new List<string> { "برای همه زبانها نام مشخص کنید." });
}
var category = new Category
{
ParentId = dto.ParentId,
IsActive = dto.IsActive,
CreatedOn = DateTime.Now,
Translations = translations
};
_dbContext.Categories.Add(category);
await _dbContext.SaveChangesAsync();
return CommandResultDto.Successful();
}
public async Task<CommandResultDto> UpdateAsync(CategoryUpdateDto dto)
{
var translations = JsonSerializer.Deserialize<List<CategoryTranslation>>(dto.Names, options: new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if (translations.Any(t => string.IsNullOrWhiteSpace(t.Name)))
{
return CommandResultDto.InvalidModelState(new List<string> { "برای همه زبانها نام مشخص کنید." });
}
var category = await _dbContext.Categories
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == dto.Id && !c.Deleted);
if (category == null)
{
return CommandResultDto.NotFound();
}
category.IsActive = dto.IsActive;
category.ParentId = dto.ParentId;
category.UpdatedOn = DateTime.Now;
_dbContext.Update(category);
var prevTranslations = _dbContext.CategoryTranslations.Where(t => t.CategoryId == category.Id);
_dbContext.CategoryTranslations.RemoveRange(prevTranslations);
translations = translations.Select(t => { t.CategoryId = category.Id; return t; }).ToList();
await _dbContext.CategoryTranslations.AddRangeAsync(translations);
await _dbContext.SaveChangesAsync();
return CommandResultDto.Successful();
}
}
}
| 39.84322 | 178 | 0.576624 | [
"MIT"
] | Smahdie/Blog | src/Infrastructure/Services/CategoryProviders/CategoryManager.cs | 9,453 | C# |
// Copyright (c) 1995-2009 held by the author(s). All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1995
{
/// <summary>
/// Section 5.3.3. Common superclass for EntityState and Collision PDUs. This should be abstract.
/// </summary>
[Serializable]
[XmlRoot]
public partial class EntityInformationPdu : Pdu, IEquatable<EntityInformationPdu>
{
/// <summary>
/// Initializes a new instance of the <see cref="EntityInformationPdu"/> class.
/// </summary>
public EntityInformationPdu()
{
ProtocolFamily = (byte)1;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(EntityInformationPdu left, EntityInformationPdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(EntityInformationPdu left, EntityInformationPdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
return marshalSize;
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public virtual void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<EntityInformationPdu>");
base.Reflection(sb);
try
{
sb.AppendLine("</EntityInformationPdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as EntityInformationPdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(EntityInformationPdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
return result;
}
}
}
| 36.180147 | 143 | 0.563865 | [
"BSD-2-Clause"
] | mastertnt/open-dis-csharp | Libs/CsharpDis6/Dis1995/Generated/EntityInformationPdu.cs | 9,841 | 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/msxml.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 static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="IXMLElement2" /> struct.</summary>
public static unsafe partial class IXMLElement2Tests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="IXMLElement2" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(IXMLElement2).GUID, Is.EqualTo(IID_IXMLElement2));
}
/// <summary>Validates that the <see cref="IXMLElement2" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IXMLElement2>(), Is.EqualTo(sizeof(IXMLElement2)));
}
/// <summary>Validates that the <see cref="IXMLElement2" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IXMLElement2).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IXMLElement2" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IXMLElement2), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(IXMLElement2), Is.EqualTo(4));
}
}
}
}
| 35.961538 | 145 | 0.625668 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | tests/Interop/Windows/um/msxml/IXMLElement2Tests.cs | 1,872 | C# |
using System.Net.Http;
using WebAnchor.RequestFactory;
using WebAnchor.RequestFactory.Serialization;
namespace SlackbotAnchor
{
public class RawContentSerializer : IContentSerializer
{
public HttpContent Serialize(object value, Parameter content)
{
return new StringContent(value.ToString());
}
}
} | 23.266667 | 69 | 0.707736 | [
"MIT"
] | mattiasnordqvist/SlackbotAnchor | SlackbotAnchor.Standard/RawContentSerializer.cs | 351 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace _03.Camera_View
{
class Program
{
static void Main(string[] args)
{
int[] elements = Console.ReadLine().Split().Select(int.Parse).ToArray();
Console.WriteLine(string.Join(", ", Regex.Matches(Console.ReadLine(),
@"\|<(.*?)(?=\||$)").Cast<Match>()
.Select(e => string.Concat(e.Groups[1].ToString().Skip(elements[0])
.Take(elements[1]).ToArray()))));
}
}
}
| 27.666667 | 84 | 0.566265 | [
"MIT"
] | Daniel-Takev/SoftUni-Programming-Fundamentals-course | Regular Expressions (RegEx) - Exercises/03. Camera View/Program.cs | 583 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveBase : MonoBehaviour
{
protected bool _canMove = false;
protected IMoveData _moveData = new MoveData();
protected Rigidbody2D _rb;
void Start()
{
GetRigidBody2D();
}
public void StartMove()
{
StopMovement();
_canMove = true;
}
public void StopMove()
{
_canMove = false;
StopMovement();
}
protected Rigidbody2D GetRigidBody2D()
{
if( this.gameObject.GetComponent<Rigidbody2D>() != null)
{
_rb = this.gameObject.GetComponent<Rigidbody2D>();
return _rb;
}
return null;
}
protected void StopMovement()
{
if (_rb != null)
{
_rb.velocity = Vector2.zero;
_rb.angularVelocity = 0.0f;
}
}
protected bool CanMove()
{
if (_canMove == false || _rb == null || _moveData == null)
return false;
else
return true;
}
}
| 19.527273 | 66 | 0.547486 | [
"MIT"
] | oviebd/Gravity-Warrior | Assets/Scripts/Move/MoveBase.cs | 1,076 | 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.ContainerRegistry.V20180901.Outputs
{
/// <summary>
/// The properties that determine the run agent configuration.
/// </summary>
[OutputType]
public sealed class AgentPropertiesResponse
{
/// <summary>
/// The CPU configuration in terms of number of cores required for the run.
/// </summary>
public readonly int? Cpu;
[OutputConstructor]
private AgentPropertiesResponse(int? cpu)
{
Cpu = cpu;
}
}
}
| 26.935484 | 83 | 0.657485 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/ContainerRegistry/V20180901/Outputs/AgentPropertiesResponse.cs | 835 | C# |
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org)
// Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net)
// Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// See the LICENSE.md file in the project root for full license information.
using System;
using System.ComponentModel;
using Stride.Core;
using Stride.Core.Annotations;
using Stride.Core.Mathematics;
using Stride.Engine;
using Stride.Graphics;
namespace Stride.Rendering.Lights
{
/// <summary>
/// A spot light.
/// </summary>
[DataContract("LightSpot")]
[Display("Spot")]
public class LightSpot : DirectLightBase
{
// These values have to match the ones defined in "TextureProjectionReceiverBase.sdsl".
public enum FlipModeEnum
{
None = 0,
FlipX = 1,
FlipY = 2,
FlipXY = 3,
}
/// <summary>
/// Initializes a new instance of the <see cref="LightSpot"/> class.
/// </summary>
public LightSpot()
{
Range = 3.0f;
AngleInner = 30.0f;
AngleOuter = 35.0f;
UVOffset = Vector2.Zero;
UVScale = Vector2.One;
Shadow = new LightStandardShadowMap()
{
Size = LightShadowMapSize.Medium,
BiasParameters =
{
DepthBias = 0.001f,
},
};
}
/// <summary>
/// Gets or sets the range distance the light is affecting.
/// </summary>
/// <value>The range.</value>
/// <userdoc>The range of the spot light in scene units</userdoc>
[DataMember(10)]
[DefaultValue(3.0f)]
public float Range { get; set; }
/// <summary>
/// Gets or sets the spot angle in degrees.
/// </summary>
/// <value>The spot angle in degrees.</value>
/// <userdoc>The angle of the main beam of the light spot.</userdoc>
[DataMember(20)]
[DataMemberRange(0.01, 90, 1, 10, 1)]
[DefaultValue(30.0f)]
public float AngleInner { get; set; }
/// <summary>
/// Gets or sets the spot angle in degrees.
/// </summary>
/// <value>The spot angle in degrees.</value>
/// <userdoc>The angle of secondary beam of the light spot</userdoc>
[DataMember(30)]
[DataMemberRange(0.01, 90, 1, 10, 1)]
[DefaultValue(35.0f)]
public float AngleOuter { get; set; }
/// <summary>The texture that is multiplied on top of the lighting result like a mask. Can be used like a cinema projector.</summary>
/// <userdoc>The texture that is multiplied on top of the lighting result like a mask. Can be used like a cinema projector.</userdoc>
[DataMember(40)]
[DefaultValue(null)]
public Texture ProjectiveTexture { get; set; }
/// <summary>
/// The scale of the texture coordinates.
/// </summary>
/// <userdoc>
/// The scale to apply to the texture coordinates. Values lower than 1 zoom the texture in; values greater than 1 tile it.
/// </userdoc>
[DataMember(43)]
[Display("UV scale")]
public Vector2 UVScale { get; set; }
/// <summary>
/// The offset in the texture coordinates.
/// </summary>
/// <userdoc>
/// The offset to apply to the model's texture coordinates
/// </userdoc>
[DataMember(45)]
[Display("UV offset")]
public Vector2 UVOffset { get; set; }
/// <summary>Scales the mip map level in the shader. 0 = biggest mip map, 1 = smallest mip map.</summary>
/// <userdoc>Used to set how blurry the projected texture should be. 0 = full resolution, 1 = 1x1 pixel</userdoc>
[DataMember(50)]
[DataMemberRange(0.0, 1.0, 0.01, 0.1, 3)]
[DefaultValue(0.0f)]
public float MipMapScale { get; set; } = 0.0f;
[DataMember(60)]
[DefaultValue(1.0f)]
public float AspectRatio { get; set; } = 1.0f;
[DataMember(70)]
[DefaultValue(0.2f)]
[DataMemberRange(0.0, 1.0, 0.01, 0.1, 3)]
public float TransitionArea { get; set; } = 0.2f;
[DataMember(75)]
[DefaultValue(1.0f)]
public float ProjectionPlaneDistance { get; set; } = 1.0f;
[DataMember(80)]
[DefaultValue(FlipModeEnum.None)]
public FlipModeEnum FlipMode { get; set; } = FlipModeEnum.None;
[DataMemberIgnore]
internal float InvSquareRange;
[DataMemberIgnore]
internal float LightAngleScale;
[DataMemberIgnore]
internal float AngleOuterInRadians;
[DataMemberIgnore]
internal float LightAngleOffset;
internal float LightRadiusAtTarget;
public override bool Update(RenderLight light)
{
var range = Math.Max(0.001f, Range);
InvSquareRange = 1.0f / (range * range);
var innerAngle = Math.Min(AngleInner, AngleOuter);
var outerAngle = Math.Max(AngleInner, AngleOuter);
AngleOuterInRadians = MathUtil.DegreesToRadians(outerAngle);
var cosInner = (float)Math.Cos(MathUtil.DegreesToRadians(innerAngle / 2));
var cosOuter = (float)Math.Cos(AngleOuterInRadians * 0.5f);
LightAngleScale = 1.0f / Math.Max(0.001f, cosInner - cosOuter);
LightAngleOffset = -cosOuter * LightAngleScale;
LightRadiusAtTarget = (float)Math.Abs(Range * Math.Sin(AngleOuterInRadians * 0.5f));
return true;
}
public override bool HasBoundingBox
{
get
{
return true;
}
}
public override BoundingBox ComputeBounds(Vector3 position, Vector3 direction)
{
// Calculates the bouding box of the spot target
var spotTarget = position + direction * Range;
var r = LightRadiusAtTarget * 1.73205080f; // * length(vector3(r,r,r))
var box = new BoundingBox(spotTarget - r, spotTarget + r);
// Merge it with the start of the bounding box
BoundingBox.Merge(ref box, ref position, out box);
return box;
}
public override float ComputeScreenCoverage(RenderView renderView, Vector3 position, Vector3 direction)
{
// TODO: We could improve this by calculating a screen-aligned triangle and a sphere at the end of the cone.
// With the screen-aligned triangle we would cover the entire spotlight, not just its end.
// http://stackoverflow.com/questions/21648630/radius-of-projected-sphere-in-screen-space
// Use a sphere at target point to compute the screen coverage. This is a very rough approximation.
// We compute the sphere at target point where the size of light is the largest
// TODO: Check if we can improve this calculation with a better model
var targetPosition = new Vector4(position + direction * Range, 1.0f);
Vector4 projectedTarget;
Vector4.Transform(ref targetPosition, ref renderView.ViewProjection, out projectedTarget);
var d = Math.Abs(projectedTarget.W) + 0.00001f;
var r = Range * Math.Sin(MathUtil.DegreesToRadians(AngleOuter / 2.0f));
// Handle correctly the case where the eye is inside the sphere
if (d < r)
return Math.Max(renderView.ViewSize.X, renderView.ViewSize.Y);
var coTanFovBy2 = renderView.Projection.M22;
var pr = r * coTanFovBy2 / (Math.Sqrt(d * d - r * r) + 0.00001f);
// Size on screen
return (float)pr * Math.Max(renderView.ViewSize.X, renderView.ViewSize.Y);
}
}
}
| 37.563981 | 141 | 0.589579 | [
"MIT"
] | Ethereal77/stride | sources/engine/Stride.Rendering/Rendering/Lights/LightSpot.cs | 7,926 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Settings : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
} | 10.653846 | 56 | 0.711191 | [
"MIT"
] | GridProtectionAlliance/DashAdmin | src/DashAdminSite/Settings.aspx.cs | 279 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace CameraControl.Visca.Demo
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 18.777778 | 42 | 0.710059 | [
"Apache-2.0"
] | DMXControl/DemoCode | CameraControl/CameraControl.Visca.Demo/App.xaml.cs | 340 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using McMaster.Extensions.CommandLineUtils;
namespace NeoExpress.Commands
{
[Command("run", Description = "Run Neo-Express instance node")]
class RunCommand
{
readonly ExpressChainManagerFactory chainManagerFactory;
public RunCommand(ExpressChainManagerFactory chainManagerFactory)
{
this.chainManagerFactory = chainManagerFactory;
}
[Argument(0, Description = "Index of node to run")]
internal int NodeIndex { get; init; } = 0;
[Option(Description = "Path to neo-express data file")]
internal string Input { get; init; } = string.Empty;
[Option(Description = "Time between blocks")]
internal uint? SecondsPerBlock { get; }
[Option(Description = "Discard blockchain changes on shutdown")]
internal bool Discard { get; init; } = false;
[Option(Description = "Enable contract execution tracing")]
internal bool Trace { get; init; } = false;
internal async Task ExecuteAsync(IConsole console, CancellationToken token)
{
var (chainManager, _) = chainManagerFactory.LoadChain(Input, SecondsPerBlock);
var chain = chainManager.Chain;
if (NodeIndex < 0 || NodeIndex >= chain.ConsensusNodes.Count) throw new Exception("Invalid node index");
var node = chain.ConsensusNodes[NodeIndex];
var storageProvider = chainManager.GetNodeStorageProvider(node, Discard);
using var disposable = storageProvider as IDisposable ?? Nito.Disposables.NoopDisposable.Instance;
await chainManager.RunAsync(storageProvider, node, Trace, console.Out, token);
}
internal async Task<int> OnExecuteAsync(CommandLineApplication app, IConsole console, CancellationToken token)
{
try
{
await ExecuteAsync(console, token);
return 0;
}
catch (Exception ex)
{
app.WriteException(ex);
return 1;
}
}
}
}
| 35.245902 | 118 | 0.631628 | [
"MIT"
] | ixje/neo-express | src/neoxp/Commands/RunCommand.cs | 2,150 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
namespace System.IO.Compression
{
// This class can be used to read bits from an byte array quickly.
// Normally we get bits from 'bitBuffer' field and bitsInBuffer stores
// the number of bits available in 'BitBuffer'.
// When we used up the bits in bitBuffer, we will try to get byte from
// the byte array and copy the byte to appropiate position in bitBuffer.
//
// The byte array is not reused. We will go from 'start' to 'end'.
// When we reach the end, most read operations will return -1,
// which means we are running out of input.
internal class InputBuffer
{
private byte[] _buffer; // byte array to store input
private int _start; // start poisition of the buffer
private int _end; // end position of the buffer
private uint _bitBuffer = 0; // store the bits here, we can quickly shift in this buffer
private int _bitsInBuffer = 0; // number of bits available in bitBuffer
// Total bits available in the input buffer
public int AvailableBits
{
get
{
return _bitsInBuffer;
}
}
// Total bytes available in the input buffer
public int AvailableBytes
{
get
{
return (_end - _start) + (_bitsInBuffer / 8);
}
}
// Ensure that count bits are in the bit buffer.
// Returns false if input is not sufficient to make this true.
// Count can be up to 16.
public bool EnsureBitsAvailable(int count)
{
Debug.Assert(0 < count && count <= 16, "count is invalid.");
// manual inlining to improve perf
if (_bitsInBuffer < count)
{
if (NeedsInput())
{
return false;
}
// insert a byte to bitbuffer
_bitBuffer |= (uint)_buffer[_start++] << _bitsInBuffer;
_bitsInBuffer += 8;
if (_bitsInBuffer < count)
{
if (NeedsInput())
{
return false;
}
// insert a byte to bitbuffer
_bitBuffer |= (uint)_buffer[_start++] << _bitsInBuffer;
_bitsInBuffer += 8;
}
}
return true;
}
// This function will try to load 16 or more bits into bitBuffer.
// It returns whatever is contained in bitBuffer after loading.
// The main difference between this and GetBits is that this will
// never return -1. So the caller needs to check AvailableBits to
// see how many bits are available.
public uint TryLoad16Bits()
{
if (_bitsInBuffer < 8)
{
if (_start < _end)
{
_bitBuffer |= (uint)_buffer[_start++] << _bitsInBuffer;
_bitsInBuffer += 8;
}
if (_start < _end)
{
_bitBuffer |= (uint)_buffer[_start++] << _bitsInBuffer;
_bitsInBuffer += 8;
}
}
else if (_bitsInBuffer < 16)
{
if (_start < _end)
{
_bitBuffer |= (uint)_buffer[_start++] << _bitsInBuffer;
_bitsInBuffer += 8;
}
}
return _bitBuffer;
}
private uint GetBitMask(int count)
{
return ((uint)1 << count) - 1;
}
// Gets count bits from the input buffer. Returns -1 if not enough bits available.
public int GetBits(int count)
{
Debug.Assert(0 < count && count <= 16, "count is invalid.");
if (!EnsureBitsAvailable(count))
{
return -1;
}
int result = (int)(_bitBuffer & GetBitMask(count));
_bitBuffer >>= count;
_bitsInBuffer -= count;
return result;
}
/// Copies length bytes from input buffer to output buffer starting
/// at output[offset]. You have to make sure, that the buffer is
/// byte aligned. If not enough bytes are available, copies fewer
/// bytes.
/// Returns the number of bytes copied, 0 if no byte is available.
public int CopyTo(byte[] output, int offset, int length)
{
Debug.Assert(output != null, "");
Debug.Assert(offset >= 0, "");
Debug.Assert(length >= 0, "");
Debug.Assert(offset <= output.Length - length, "");
Debug.Assert((_bitsInBuffer % 8) == 0, "");
// Copy the bytes in bitBuffer first.
int bytesFromBitBuffer = 0;
while (_bitsInBuffer > 0 && length > 0)
{
output[offset++] = (byte)_bitBuffer;
_bitBuffer >>= 8;
_bitsInBuffer -= 8;
length--;
bytesFromBitBuffer++;
}
if (length == 0)
{
return bytesFromBitBuffer;
}
int avail = _end - _start;
if (length > avail)
{
length = avail;
}
Array.Copy(_buffer, _start, output, offset, length);
_start += length;
return bytesFromBitBuffer + length;
}
// Return true is all input bytes are used.
// This means the caller can call SetInput to add more input.
public bool NeedsInput()
{
return _start == _end;
}
// Set the byte array to be processed.
// All the bits remained in bitBuffer will be processed before the new bytes.
// We don't clone the byte array here since it is expensive.
// The caller should make sure after a buffer is passed in.
// It will not be changed before calling this function again.
public void SetInput(byte[] buffer, int offset, int length)
{
Debug.Assert(buffer != null, "");
Debug.Assert(offset >= 0, "");
Debug.Assert(length >= 0, "");
Debug.Assert(offset <= buffer.Length - length, "");
Debug.Assert(_start == _end, "");
_buffer = buffer;
_start = offset;
_end = offset + length;
}
// Skip n bits in the buffer
public void SkipBits(int n)
{
Debug.Assert(_bitsInBuffer >= n, "No enough bits in the buffer, Did you call EnsureBitsAvailable?");
_bitBuffer >>= n;
_bitsInBuffer -= n;
}
// Skips to the next byte boundary.
public void SkipToByteBoundary()
{
_bitBuffer >>= (_bitsInBuffer % 8);
_bitsInBuffer = _bitsInBuffer - (_bitsInBuffer % 8);
}
}
}
| 34.102326 | 112 | 0.50982 | [
"MIT"
] | FrancisFYK/corefx | src/System.IO.Compression/src/System/IO/Compression/DeflateManaged/InputBuffer.cs | 7,332 | C# |
using Pentibox.Engine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Pentibox
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private Game game;
DispatcherTimer timer;
public MainPage()
{
this.InitializeComponent();
this.game = new Game();
this.timer = new DispatcherTimer();
this.timer.Tick += this.OnTimerTick;
this.timer.Interval = TimeSpan.FromMilliseconds(500);
this.Loaded += this.OnLoaded;
}
void OnLoaded(object sender, RoutedEventArgs e)
{
this.game.Start();
this.timer.Start();
}
void OnTimerTick(object sender, object e)
{
this.game.OnTick();
}
void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args)
{
switch (args.VirtualKey)
{
case VirtualKey.Left:
this.game.MoveLeft();
break;
case VirtualKey.Right:
this.game.MoveRight();
break;
case VirtualKey.Down:
this.game.MoveDown();
break;
case VirtualKey.Up:
this.game.Rotate(true);
break;
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
this.board.Attach(this.game);
}
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
base.OnNavigatingFrom(e);
Window.Current.CoreWindow.KeyDown -= CoreWindow_KeyDown;
this.timer.Stop();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.game.OnTick();
}
private void Button_Rotate(object sender, RoutedEventArgs e)
{
this.game.Rotate(false);
}
}
}
| 27.37 | 101 | 0.579467 | [
"MIT"
] | atanasovg/Pentibox | Pentibox/MainPage.xaml.cs | 2,739 | 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.CodeDeploy
{
/// <summary>
/// Provides a CodeDeploy deployment config for an application
///
/// ## Example Usage
///
/// ### Server Usage
///
/// ```csharp
/// using Pulumi;
/// using Aws = Pulumi.Aws;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var fooDeploymentConfig = new Aws.CodeDeploy.DeploymentConfig("fooDeploymentConfig", new Aws.CodeDeploy.DeploymentConfigArgs
/// {
/// DeploymentConfigName = "test-deployment-config",
/// MinimumHealthyHosts = new Aws.CodeDeploy.Inputs.DeploymentConfigMinimumHealthyHostsArgs
/// {
/// Type = "HOST_COUNT",
/// Value = 2,
/// },
/// });
/// var fooDeploymentGroup = new Aws.CodeDeploy.DeploymentGroup("fooDeploymentGroup", new Aws.CodeDeploy.DeploymentGroupArgs
/// {
/// AlarmConfiguration = new Aws.CodeDeploy.Inputs.DeploymentGroupAlarmConfigurationArgs
/// {
/// Alarms =
/// {
/// "my-alarm-name",
/// },
/// Enabled = true,
/// },
/// AppName = aws_codedeploy_app.Foo_app.Name,
/// AutoRollbackConfiguration = new Aws.CodeDeploy.Inputs.DeploymentGroupAutoRollbackConfigurationArgs
/// {
/// Enabled = true,
/// Events =
/// {
/// "DEPLOYMENT_FAILURE",
/// },
/// },
/// DeploymentConfigName = fooDeploymentConfig.Id,
/// DeploymentGroupName = "bar",
/// Ec2TagFilters =
/// {
/// new Aws.CodeDeploy.Inputs.DeploymentGroupEc2TagFilterArgs
/// {
/// Key = "filterkey",
/// Type = "KEY_AND_VALUE",
/// Value = "filtervalue",
/// },
/// },
/// ServiceRoleArn = aws_iam_role.Foo_role.Arn,
/// TriggerConfigurations =
/// {
/// new Aws.CodeDeploy.Inputs.DeploymentGroupTriggerConfigurationArgs
/// {
/// TriggerEvents =
/// {
/// "DeploymentFailure",
/// },
/// TriggerName = "foo-trigger",
/// TriggerTargetArn = "foo-topic-arn",
/// },
/// },
/// });
/// }
///
/// }
/// ```
///
/// ### Lambda Usage
///
/// ```csharp
/// using Pulumi;
/// using Aws = Pulumi.Aws;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var fooDeploymentConfig = new Aws.CodeDeploy.DeploymentConfig("fooDeploymentConfig", new Aws.CodeDeploy.DeploymentConfigArgs
/// {
/// ComputePlatform = "Lambda",
/// DeploymentConfigName = "test-deployment-config",
/// TrafficRoutingConfig = new Aws.CodeDeploy.Inputs.DeploymentConfigTrafficRoutingConfigArgs
/// {
/// TimeBasedLinear = new Aws.CodeDeploy.Inputs.DeploymentConfigTrafficRoutingConfigTimeBasedLinearArgs
/// {
/// Interval = 10,
/// Percentage = 10,
/// },
/// Type = "TimeBasedLinear",
/// },
/// });
/// var fooDeploymentGroup = new Aws.CodeDeploy.DeploymentGroup("fooDeploymentGroup", new Aws.CodeDeploy.DeploymentGroupArgs
/// {
/// AlarmConfiguration = new Aws.CodeDeploy.Inputs.DeploymentGroupAlarmConfigurationArgs
/// {
/// Alarms =
/// {
/// "my-alarm-name",
/// },
/// Enabled = true,
/// },
/// AppName = aws_codedeploy_app.Foo_app.Name,
/// AutoRollbackConfiguration = new Aws.CodeDeploy.Inputs.DeploymentGroupAutoRollbackConfigurationArgs
/// {
/// Enabled = true,
/// Events =
/// {
/// "DEPLOYMENT_STOP_ON_ALARM",
/// },
/// },
/// DeploymentConfigName = fooDeploymentConfig.Id,
/// DeploymentGroupName = "bar",
/// ServiceRoleArn = aws_iam_role.Foo_role.Arn,
/// });
/// }
///
/// }
/// ```
/// </summary>
public partial class DeploymentConfig : Pulumi.CustomResource
{
/// <summary>
/// The compute platform can be `Server`, `Lambda`, or `ECS`. Default is `Server`.
/// </summary>
[Output("computePlatform")]
public Output<string?> ComputePlatform { get; private set; } = null!;
/// <summary>
/// The AWS Assigned deployment config id
/// </summary>
[Output("deploymentConfigId")]
public Output<string> DeploymentConfigId { get; private set; } = null!;
/// <summary>
/// The name of the deployment config.
/// </summary>
[Output("deploymentConfigName")]
public Output<string> DeploymentConfigName { get; private set; } = null!;
/// <summary>
/// A minimum_healthy_hosts block. Required for `Server` compute platform. Minimum Healthy Hosts are documented below.
/// </summary>
[Output("minimumHealthyHosts")]
public Output<Outputs.DeploymentConfigMinimumHealthyHosts?> MinimumHealthyHosts { get; private set; } = null!;
/// <summary>
/// A traffic_routing_config block. Traffic Routing Config is documented below.
/// </summary>
[Output("trafficRoutingConfig")]
public Output<Outputs.DeploymentConfigTrafficRoutingConfig?> TrafficRoutingConfig { get; private set; } = null!;
/// <summary>
/// Create a DeploymentConfig 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 DeploymentConfig(string name, DeploymentConfigArgs args, CustomResourceOptions? options = null)
: base("aws:codedeploy/deploymentConfig:DeploymentConfig", name, args ?? new DeploymentConfigArgs(), MakeResourceOptions(options, ""))
{
}
private DeploymentConfig(string name, Input<string> id, DeploymentConfigState? state = null, CustomResourceOptions? options = null)
: base("aws:codedeploy/deploymentConfig:DeploymentConfig", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing DeploymentConfig resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static DeploymentConfig Get(string name, Input<string> id, DeploymentConfigState? state = null, CustomResourceOptions? options = null)
{
return new DeploymentConfig(name, id, state, options);
}
}
public sealed class DeploymentConfigArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The compute platform can be `Server`, `Lambda`, or `ECS`. Default is `Server`.
/// </summary>
[Input("computePlatform")]
public Input<string>? ComputePlatform { get; set; }
/// <summary>
/// The name of the deployment config.
/// </summary>
[Input("deploymentConfigName", required: true)]
public Input<string> DeploymentConfigName { get; set; } = null!;
/// <summary>
/// A minimum_healthy_hosts block. Required for `Server` compute platform. Minimum Healthy Hosts are documented below.
/// </summary>
[Input("minimumHealthyHosts")]
public Input<Inputs.DeploymentConfigMinimumHealthyHostsArgs>? MinimumHealthyHosts { get; set; }
/// <summary>
/// A traffic_routing_config block. Traffic Routing Config is documented below.
/// </summary>
[Input("trafficRoutingConfig")]
public Input<Inputs.DeploymentConfigTrafficRoutingConfigArgs>? TrafficRoutingConfig { get; set; }
public DeploymentConfigArgs()
{
}
}
public sealed class DeploymentConfigState : Pulumi.ResourceArgs
{
/// <summary>
/// The compute platform can be `Server`, `Lambda`, or `ECS`. Default is `Server`.
/// </summary>
[Input("computePlatform")]
public Input<string>? ComputePlatform { get; set; }
/// <summary>
/// The AWS Assigned deployment config id
/// </summary>
[Input("deploymentConfigId")]
public Input<string>? DeploymentConfigId { get; set; }
/// <summary>
/// The name of the deployment config.
/// </summary>
[Input("deploymentConfigName")]
public Input<string>? DeploymentConfigName { get; set; }
/// <summary>
/// A minimum_healthy_hosts block. Required for `Server` compute platform. Minimum Healthy Hosts are documented below.
/// </summary>
[Input("minimumHealthyHosts")]
public Input<Inputs.DeploymentConfigMinimumHealthyHostsGetArgs>? MinimumHealthyHosts { get; set; }
/// <summary>
/// A traffic_routing_config block. Traffic Routing Config is documented below.
/// </summary>
[Input("trafficRoutingConfig")]
public Input<Inputs.DeploymentConfigTrafficRoutingConfigGetArgs>? TrafficRoutingConfig { get; set; }
public DeploymentConfigState()
{
}
}
}
| 41.010676 | 149 | 0.54278 | [
"ECL-2.0",
"Apache-2.0"
] | JakeGinnivan/pulumi-aws | sdk/dotnet/CodeDeploy/DeploymentConfig.cs | 11,524 | C# |
using System;
using System.Globalization;
using System.Windows.Data;
namespace TestApp.Android.Converters
{
public class StringToUpperConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string str = value as string;
if (string.IsNullOrEmpty(str))
{
return "";
}
return str.ToUpper(culture);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| 21.84 | 97 | 0.736264 | [
"MIT"
] | Julien-Mialon/StormXamarin | StormXamarin/TestApp.Android/Converters/StringToUpperConverter.cs | 548 | C# |
using UnityEngine;
using System.Collections;
public class ObserveState : IEnemyState
{
StatePatternEnemy statePatternEnemy;
public ObserveState(StatePatternEnemy spe)
{
statePatternEnemy = spe;
statePatternEnemy.anim.SetBool("Walking", false);
}
public void EnterState()
{
Debug.Log("observe");
}
public void ExitState()
{
statePatternEnemy.lastAttackTime = Time.time - 1;
Debug.Log("observe exit");
}
public void UpdateState()
{
Movement player = statePatternEnemy.GetPlayer();
if (player != null)
{
if (Vector2.Distance(statePatternEnemy.transform.position, statePatternEnemy.player.transform.position) < statePatternEnemy.minObserveDistance)
{
statePatternEnemy.ChangeState(new ChaseState(statePatternEnemy));
}
}
}
}
| 23.205128 | 155 | 0.634254 | [
"MIT"
] | brandio/spellLike | dungeons of spell/Assets/Scripts/Ai/AiStates/ObserveState.cs | 907 | C# |
using DMCIT.Core.Entities.Core;
using DMCIT.Core.Entities.Messaging;
using DMCIT.Core.Services;
using DMCIT.Infrastructure.Events.SendMessageEvent;
using Hangfire.Server;
using MediatR;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace DMCIT.Infrastructure.Services
{
public class SendMessageService : ISendMessageService
{
private readonly IMediator _mediator;
public SendMessageService(IMediator mediator)
{
_mediator = mediator;
}
public async Task BeginSendMessageBatch(MessageBatch batch, IEnumerable<SentMessage> messages, AppUser actor, PerformContext context)
{
await _mediator.Publish(new BeginSendMessageBatchEvent
{
Batch = batch,
Actor = actor,
Context = context,
Mesasges = messages
});
}
public async Task EndSendMessageBatch(MessageBatch batch, AppUser actor, PerformContext context)
{
await _mediator.Publish(new EndSendMessageBatchEvent
{
Batch = batch,
Actor = actor,
Context = context
});
}
public async Task InitializeSendMessageBatch(int batchId, PerformContext context)
{
await _mediator.Publish(new InitializeMessageBatchEvent
{
BatchId = batchId,
Context = context
});
}
public async Task SendMessageBatchFailed(int batchId, string reason, AppUser actor, PerformContext context)
{
await _mediator.Publish(new SendMessageBatchFaildEvent
{
BatchId = batchId,
Reason = reason,
Context = context
});
}
public async Task SendMessageFailed(SentMessage msg, string reason, PerformContext context)
{
await _mediator.Publish(new SendMessageFailedEvent
{
Message = msg,
Reason = reason,
Context = context
});
}
public async Task SendMessageSuccess(SentMessage msg, PerformContext context)
{
await _mediator.Publish(new SendMessageSuccessEvent
{
Message = msg,
Context = context
});
}
}
}
| 30.275 | 141 | 0.578035 | [
"MIT"
] | thanhtuan260593/dmcit-netcore | src/DMCIT.Infrastructure/Services/SendMessageService.cs | 2,424 | C# |
namespace HighPerformance.Miscellaneous;
/// <summary>
/// Defining a capacity of a list when allocating that list will increase performance.
/// </summary>
public class DefineListCapacity
{
[Params(10, 10000, 100000)]
public int Capacity { get; set; }
[Benchmark(Baseline = true)]
public void AllocWithoutDefiningCapacity_FillList()
{
List<int> testList = new List<int>();
for (int i = 0; i < Capacity; i++)
{
testList.Add(i);
}
}
[Benchmark]
public void AllocDefineCapacity_FillList()
{
List<int> testList = new List<int>(Capacity);
for (int i = 0; i < Capacity; i++)
{
testList.Add(i);
}
}
}
/*
| Method | Capacity | Mean | Error | StdDev | Median | Ratio | RatioSD |
|-------------------------------------- |--------- |--------------:|--------------:|--------------:|--------------:|------:|--------:|
| AllocWithoutDefiningCapacity_FillList | 10 | 71.45 ns | 1.471 ns | 4.124 ns | 70.84 ns | 1.00 | 0.00 |
| AllocDefineCapacity_FillList | 10 | 31.82 ns | 0.792 ns | 2.298 ns | 31.59 ns | 0.44 | 0.04 |
| | | | | | | | |
| AllocWithoutDefiningCapacity_FillList | 10000 | 30,164.67 ns | 597.011 ns | 1,703.306 ns | 29,519.48 ns | 1.00 | 0.00 |
| AllocDefineCapacity_FillList | 10000 | 20,878.67 ns | 174.069 ns | 162.824 ns | 20,968.55 ns | 0.67 | 0.04 |
| | | | | | | | |
| AllocWithoutDefiningCapacity_FillList | 100000 | 561,780.08 ns | 21,082.435 ns | 62,162.036 ns | 538,123.68 ns | 1.00 | 0.00 |
| AllocDefineCapacity_FillList | 100000 | 344,258.14 ns | 2,702.511 ns | 2,109.943 ns | 344,899.85 ns | 0.64 | 0.01 |
*/ | 45.347826 | 134 | 0.442474 | [
"MIT"
] | marko-lohert/High-Performance-CSharp-Samples-With-Benchmarks | HighPerformance/HighPerformance/Miscellaneous/DefineListCapacity.cs | 2,088 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IAM.WebAPI;
using System.Data;
using System.Data.SqlClient;
using SafeTrend.Json;
using IAM.GlobalDefs.WebApi;
using IAM.GlobalDefs;
using IAM.Filters;
using System.Globalization;
using System.Threading;
namespace IAMWebServer._admin.content
{
public partial class container : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.HttpMethod != "POST")
return;
String area = "";
if (!String.IsNullOrWhiteSpace((String)RouteData.Values["area"]))
area = (String)RouteData.Values["area"];
Int64 enterpriseId = 0;
if ((Session["enterprise_data"]) != null && (Session["enterprise_data"] is EnterpriseData))
enterpriseId = ((EnterpriseData)Session["enterprise_data"]).Id;
Boolean newItem = false;
if ((RouteData.Values["new"] != null) && (RouteData.Values["new"] == "1"))
newItem = true;
String ApplicationVirtualPath = Session["ApplicationVirtualPath"].ToString();
LMenu menu1 = new LMenu("Dashboard", ApplicationVirtualPath + "admin/");
LMenu menu2 = new LMenu("Pastas", ApplicationVirtualPath + "admin/container/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
LMenu menu3 = new LMenu("Pastas", ApplicationVirtualPath + "admin/container/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
WebJsonResponse contentRet = null;
String html = "";
String eHtml = "";
String js = null;
String errorTemplate = "<span class=\"empty-results\">{0}</span>";
//Verifica se está sendo selecionada uma role
Int64 containerId = 0;
try
{
containerId = Int64.Parse((String)RouteData.Values["id"]);
if (containerId < 0)
containerId = 0;
}
catch { }
String error = "";
ContainerGetResult selectedContainer = null;
String filter = "";
HashData hashData = new HashData(this);
String rData = null;
//SqlConnection conn = null;
String jData = "";
Int32 page = 1;
Int32 pageSize = 20;
Boolean hasNext = true;
if (!String.IsNullOrWhiteSpace((String)RouteData.Values["filter"]))
filter = (String)RouteData.Values["filter"];
if ((containerId > 0) && (area.ToLower() != "search"))
{
try
{
rData = SafeTrend.Json.JSON.Serialize2(new
{
jsonrpc = "1.0",
method = "container.get",
parameters = new
{
containerid = containerId
},
id = 1
});
jData = "";
using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
jData = WebPageAPI.ExecuteLocal(database, this, rData);
if (String.IsNullOrWhiteSpace(jData))
throw new Exception("");
selectedContainer = JSON.Deserialize<ContainerGetResult>(jData);
if (selectedContainer == null)
{
error = MessageResource.GetMessage("container_not_found");
//ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
}
else if (selectedContainer.error != null)
{
error = selectedContainer.error.data;
selectedContainer = null;
}
else if (selectedContainer.result == null || selectedContainer.result.info == null)
{
error = MessageResource.GetMessage("container_not_found");
selectedContainer = null;
}
else
{
menu3.Name = selectedContainer.result.info.name;
}
}
catch (Exception ex)
{
error = MessageResource.GetMessage("api_error");
Tools.Tool.notifyException(ex, this);
selectedContainer = null;
//ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
}
}
String infoTemplate = "<tr><td class=\"col1\">{0}</td><td class=\"col2\"><span class=\"no-edit\">{1}</span></td></tr>";
switch (area)
{
case "":
case "search":
case "content":
if (newItem)
{
error = "";
rData = SafeTrend.Json.JSON.Serialize2(new
{
jsonrpc = "1.0",
method = "context.list",
parameters = new { },
id = 1
});
jData = "";
using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
jData = WebPageAPI.ExecuteLocal(database, this, rData);
if (String.IsNullOrWhiteSpace(jData))
throw new Exception("");
ContextListResult contextList = JSON.Deserialize<ContextListResult>(jData);
if (contextList == null)
{
error = MessageResource.GetMessage("context_not_found");
//ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
}
else if (contextList.error != null)
{
error = contextList.error.data;
}
else if (contextList.result == null)
{
error = MessageResource.GetMessage("context_not_found");
}
else
{
rData = SafeTrend.Json.JSON.Serialize2(new
{
jsonrpc = "1.0",
method = "container.list",
parameters = new
{
page_size = Int32.MaxValue,
page = 1
},
id = 1
});
jData = "";
using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
jData = WebPageAPI.ExecuteLocal(database, this, rData);
List<ContainerData> conteinerList = new List<ContainerData>();
ContainerListResult cl = JSON.Deserialize<ContainerListResult>(jData);
if ((cl != null) && (cl.error == null) && (cl.result != null) && (cl.result.Count > 0))
conteinerList.AddRange(cl.result);
html = "<h3>Adição de pasta</h3>";
html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/container/action/add_container/\">";
html += "<div class=\"no-tabs fields\"><table><tbody>";
html += String.Format(infoTemplate, "Nome", "<input id=\"container_name\" name=\"container_name\" placeholder=\"Digite o nome da pasta\" type=\"text\"\">");
String select = "<select id=\"container_context\" name=\"container_context\" ><option value=\"\"></option>";
foreach (ContextData c in contextList.result)
select += "<option value=\"" + c.context_id + "\" " + (hashData.GetValue("context") == c.context_id.ToString() ? "selected" : "") + ">" + c.name + "</option>";
select += "</select>";
html += String.Format(infoTemplate, "Contexto", select);
Func<String, Int64, Int64, String> chields = null;
chields = new Func<String, long, long, string>(delegate(String padding, Int64 root, Int64 ctx)
{
String h = "";
foreach (ContainerData c in conteinerList)
if ((c.parent_id == root) && (c.context_id == ctx))
{
h += "<option value=\"" + c.container_id + "\" " + (hashData.GetValue("container") == c.container_id.ToString() ? "selected" : "") + ">" + padding + " " + c.name + "</option>";
h += chields(padding + "---", c.container_id, ctx);
}
return h;
});
select = "<select id=\"parent_container\" name=\"parent_container\" >";
foreach (ContextData ctx in contextList.result)
{
select += "<option value=\"0\">Raiz no contexto " + ctx.name +"</option>";
select += chields("|", 0, ctx.context_id);
}
select += "</select>";
html += String.Format(infoTemplate, "Pasta pai", select);
html += "</tbody></table><div class=\"clear-block\"></div></div>";
html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button> <a href=\"" + ApplicationVirtualPath + "admin/container/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";
contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
}
}
else
{
if (selectedContainer == null)
{
Int32.TryParse(Request.Form["page"], out page);
if (page < 1)
page = 1;
String containerTemplate = "<div id=\"proxy-list-{0}\" data-id=\"{0}\" data-name=\"{1}\" data-total=\"{2}\" class=\"app-list-item\">";
containerTemplate += "<table>";
containerTemplate += " <tbody>";
containerTemplate += " <tr>";
containerTemplate += " <td class=\"col1\">";
containerTemplate += " <span id=\"total_{0}\" class=\"total \">{2}</span>";
containerTemplate += " <a href=\"" + ApplicationVirtualPath + "admin/users/#container/{0}\">";
containerTemplate += " <div class=\"app-btn a-btn\"><span class=\"a-btn-inner\">Ver usuários</span></div>";
containerTemplate += " </a>";
containerTemplate += " </td>";
containerTemplate += " <td class=\"col2\">";
containerTemplate += " <div class=\"title\"><span class=\"name field-editor\" id=\"container_name_{0}\" data-id=\"{0}\" data-function=\"iamadmin.editTextField('#container_name_{0}',null,containerNameEdit);\">{1}</span><span class=\"date\">{3}</span><div class=\"clear-block\"></div></div>";
containerTemplate += " <div class=\"description\">";
containerTemplate += " <div class=\"first\">{4}</div>";
containerTemplate += " </div>";
containerTemplate += " <div class=\"links\">";
containerTemplate += " <div class=\"line\">{5}</div><div class=\"clear-block\"></div>";
containerTemplate += " </div>";
containerTemplate += " </td>";
containerTemplate += " </tr>";
containerTemplate += " </tbody>";
containerTemplate += "</table></div>";
js += "containerNameEdit = function(thisId, changedText) { iamadmin.changeName(thisId,changedText); };";
html += "<div id=\"box-container\" class=\"box-container\">";
String query = "";
try
{
rData = "";
if (!String.IsNullOrWhiteSpace((String)RouteData.Values["query"]))
query = (String)RouteData.Values["query"];
if (String.IsNullOrWhiteSpace(query) && !String.IsNullOrWhiteSpace(hashData.GetValue("query")))
query = hashData.GetValue("query");
if (String.IsNullOrWhiteSpace(query))
{
rData = SafeTrend.Json.JSON.Serialize2(new
{
jsonrpc = "1.0",
method = "container.list",
parameters = new
{
page_size = pageSize,
page = page
},
id = 1
});
}
else
{
rData = SafeTrend.Json.JSON.Serialize2(new
{
jsonrpc = "1.0",
method = "container.search",
parameters = new
{
text = query,
page_size = pageSize,
page = page
},
id = 1
});
}
jData = "";
using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
jData = WebPageAPI.ExecuteLocal(database, this, rData);
if (String.IsNullOrWhiteSpace(jData))
throw new Exception("");
ContainerListResult ret2 = JSON.Deserialize<ContainerListResult>(jData);
if (ret2 == null)
{
eHtml += String.Format(errorTemplate, MessageResource.GetMessage("container_not_found"));
hasNext = false;
}
else if (ret2.error != null)
{
#if DEBUG
eHtml += String.Format(errorTemplate, ret2.error.data + ret2.error.debug);
#else
eHtml += String.Format(errorTemplate, ret2.error.data);
#endif
hasNext = false;
}
else if (ret2.result == null || (ret2.result.Count == 0 && page == 1))
{
eHtml += String.Format(errorTemplate, MessageResource.GetMessage("container_not_found"));
hasNext = false;
}
else
{
foreach (ContainerData c in ret2.result)
{
String text = "";
if (c.path != null)
text += "<span>Path: " + c.path + "</span><br />";
if (c.context_name != null)
text += "<span>Contexto: " + c.context_name + "</span>";
String links = "";
links += "<a href=\"" + ApplicationVirtualPath + "admin/container/" + c.container_id + "/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-change\">Editar</div></a>";
links += "<a href=\"" + ApplicationVirtualPath + "admin/container/" + c.container_id + "/add_user/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-user-add\">Adicionar usuário</div></a>";
links += "<a href=\"" + ApplicationVirtualPath + "admin/container/" + c.container_id + "/action/delete_all_users/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"confirm-action\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente todos os usuários da pasta '" + c.name + "'?\" ok=\"Excluir\" cancel=\"Cancelar\"><div class=\"ico icon-close\">Excluir usuários</div></a>";
links += (c.entity_qty > 0 ? "" : "<a class=\"confirm-action\" href=\"" + ApplicationVirtualPath + "admin/container/" + c.container_id + "/action/delete/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente a pasta '" + c.name + "'?\" ok=\"Excluir\" cancel=\"Cancelar\"><div class=\"ico icon-close\">Apagar</div></a>");
html += String.Format(containerTemplate, c.container_id, c.name, c.entity_qty, (c.create_date > 0 ? "Criado em " + MessageResource.FormatDate(new DateTime(1970, 1, 1).AddSeconds(c.create_date), true) : ""), text, links);
}
if (ret2.result.Count < pageSize)
hasNext = false;
}
}
catch (Exception ex)
{
eHtml += String.Format(errorTemplate, MessageResource.GetMessage("api_error"));
}
if (page == 1)
{
html += "</div>";
html += "<span class=\"empty-results content-loading proxy-list-loader hide\"></span>";
contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
}
else
{
contentRet = new WebJsonResponse("#content-wrapper #box-container", (eHtml != "" ? eHtml : html), true);
}
contentRet.js = js + "$( document ).unbind('end_of_scroll');";
if (hasNext)
contentRet.js += "$( document ).bind( 'end_of_scroll.loader_role', function() { $( document ).unbind('end_of_scroll.loader_role'); $('.proxy-list-loader').removeClass('hide'); iamadmin.getPageContent2( { page: " + ++page + ", search:'" + (!String.IsNullOrWhiteSpace(query) ? query : "") + "' }, function(){ $('.proxy-list-loader').addClass('hide'); } ); });";
}
else//Esta sendo selecionado o content
{
if (error != "")
{
contentRet = new WebJsonResponse("#content-wrapper", String.Format(errorTemplate, error));
}
else
{
switch (filter)
{
case "":
rData = SafeTrend.Json.JSON.Serialize2(new
{
jsonrpc = "1.0",
method = "container.list",
parameters = new
{
page_size = Int32.MaxValue,
page = 1
},
id = 1
});
jData = "";
using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
jData = WebPageAPI.ExecuteLocal(database, this, rData);
List<ContainerData> conteinerList = new List<ContainerData>();
ContainerListResult cl = JSON.Deserialize<ContainerListResult>(jData);
if ((cl != null) && (cl.error == null) && (cl.result != null) && (cl.result.Count > 0))
conteinerList.AddRange(cl.result);
html = "<h3>Edição da pasta</h3>";
html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/container/" + selectedContainer.result.info.container_id + "/action/change/\">";
html += "<div class=\"no-tabs fields\"><table><tbody>";
html += String.Format(infoTemplate, "Nome", "<input id=\"container_name\" name=\"container_name\" placeholder=\"Digite o nome da pasta\" type=\"text\"\" value=\""+ selectedContainer.result.info.name +"\">");
html += String.Format(infoTemplate, "Contexto", selectedContainer.result.info.context_name);
Func<String, Int64, Int64, String> chields = null;
chields = new Func<String, long, long, string>(delegate(String padding, Int64 root, Int64 ctx)
{
String h = "";
foreach (ContainerData c in conteinerList)
if ((c.parent_id == root) && (c.context_id == ctx))
{
h += "<option value=\"" + c.container_id + "\" " + (selectedContainer.result.info.parent_id.ToString() == c.container_id.ToString() ? "selected" : "") + ">" + padding + " " + c.name + "</option>";
h += chields(padding + "---", c.container_id, ctx);
}
return h;
});
String select = "<select id=\"parent_container\" name=\"parent_container\" >";
select += "<option value=\"0\">Raiz no contexto " + selectedContainer.result.info.context_name + "</option>";
select += chields("|", 0, selectedContainer.result.info.context_id);
select += "</select>";
html += String.Format(infoTemplate, "Pasta pai", select);
html += "</tbody></table><div class=\"clear-block\"></div></div>";
html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button> <a href=\"" + ApplicationVirtualPath + "admin/container/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";
contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
break;
case "add_user":
html = "<h3>Adição de usuário</h3>";
html += "<form id=\"form_add_user\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/container/" + containerId + "/action/add_user/\"><div class=\"no-tabs pb10\">";
html += "<div class=\"form-group\" id=\"add_user\"><label>Usuário</label><input id=\"add_user_text\" placeholder=\"Digite o nome do usuário\" type=\"text\"\"></div>";
html += "<div class=\"clear-block\"></div></div>";
html += "<h3>Usuários selecionados</h3>";
html += "<div id=\"box-container\" class=\"box-container\"><div class=\"no-tabs pb10 none\">";
html += "Nenhum usuário selecionado";
html += "</div></div>";
html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Cadastrar</button> <a href=\"" + ApplicationVirtualPath + "admin/container/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";
contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
contentRet.js = "iamadmin.autoCompleteText('#add_user_text', '" + ApplicationVirtualPath + "admin/users/content/search_user/', {context_id: '" + selectedContainer.result.info.context_id + "'} , function(thisId, selectedItem){ $(thisId).val(''); $('.none').remove(); $('.box-container').append(selectedItem.html); } )";
break;
}
}
}
}
break;
case "sidebar":
if (menu1 != null)
{
html += "<div class=\"sep\"><div class=\"section-nav-header\">";
html += " <div class=\"crumbs\">";
html += " <div class=\"subject subject-color\">";
html += " <a href=\"" + menu1.HRef + "\">" + menu1.Name + "</a>";
html += " </div>";
if (menu2 != null)
{
html += " <div class=\"topic topic-color\">";
html += " <a href=\"" + menu2.HRef + "\">" + menu2.Name + "</a>";
html += " </div>";
}
html += " </div>";
if (menu3 != null)
{
html += " <div class=\"crumbs tutorial-title\">";
html += " <h2 class=\"title tutorial-color\">" + menu3.Name + "</h2>";
html += " </div>";
}
html += "</div></div>";
}
if (!newItem)
{
html += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "admin/container/new/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "'\">Nova pasta</button></div>";
}
contentRet = new WebJsonResponse("#main aside", html);
break;
case "mobilebar":
break;
case "buttonbox":
break;
}
if (contentRet != null)
{
if (!String.IsNullOrWhiteSpace((String)Request["cid"]))
contentRet.callId = (String)Request["cid"];
Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
}
}
}
} | 55.336347 | 483 | 0.403287 | [
"Apache-2.0"
] | helviojunior/safeid | IAMWebServer/IAMWebServer/_admin/content/container.aspx.cs | 30,621 | C# |
using System;
using Util.Datas.Dapper.SqlServer;
using Util.Datas.Queries;
using Util.Datas.Sql;
using Util.Datas.Tests.XUnitHelpers;
using Util.Properties;
using Xunit;
using Xunit.Abstractions;
using String = Util.Helpers.String;
namespace Util.Datas.Tests.Sql.Builders.SqlServer {
/// <summary>
/// Sql Server Sql生成器测试
/// </summary>
public partial class SqlServerBuilderTest {
/// <summary>
/// 输出工具
/// </summary>
private readonly ITestOutputHelper _output;
/// <summary>
/// Sql Server Sql生成器
/// </summary>
private readonly SqlServerBuilder _builder;
/// <summary>
/// 测试初始化
/// </summary>
public SqlServerBuilderTest( ITestOutputHelper output ) {
_output = output;
_builder = new SqlServerBuilder();
}
/// <summary>
/// 验证表名为空
/// </summary>
[Fact]
public void Test_Validate_1() {
_builder.Select( "a" );
AssertHelper.Throws<InvalidOperationException>( () => _builder.ToSql() );
}
/// <summary>
/// 设置查询条件 - 验证列名为空
/// </summary>
[Fact]
public void Test_Validate_2() {
AssertHelper.Throws<ArgumentNullException>( () => _builder.Where( "", "a" ) );
}
/// <summary>
/// 验证分页时未设置排序字段,抛出异常
/// </summary>
[Fact]
public void TestPage_1() {
var pager = new QueryParameter();
_builder.From( "a" ).Page( pager );
AssertHelper.Throws<ArgumentException>( () => _builder.ToSql(), LibraryResource.OrderIsEmptyForPage );
}
/// <summary>
/// 分页时设置了排序字段
/// </summary>
[Fact]
public void TestPage_2() {
//结果
var result = new String();
result.AppendLine( "Select * " );
result.AppendLine( "From [Test] " );
result.AppendLine( "Order By [a] " );
result.Append( "Offset @_p_0 Rows Fetch Next @_p_1 Rows Only" );
//执行
var pager = new QueryParameter { Order = "a" };
_builder.From( "Test" ).Page( pager );
//验证
Assert.Equal( result.ToString(), _builder.ToSql() );
Assert.Equal( 0, _builder.GetParams()["@_p_0"] );
Assert.Equal( 20, _builder.GetParams()["@_p_1"] );
}
/// <summary>
/// 测试联合操作
/// </summary>
[Fact]
public void TestUnion_1() {
//结果
var result = new String();
result.AppendLine( "(Select [a],[b] " );
result.AppendLine( "From [Test] " );
result.AppendLine( "Where [c]=@_p_1 " );
result.AppendLine( ") " );
result.AppendLine( "Union " );
result.AppendLine( "(Select [a],[b] " );
result.AppendLine( "From [Test2] " );
result.AppendLine( "Where [c]=@_p_0 " );
result.Append( ")" );
//执行
var builder2 = _builder.New().Select( "a,b" ).From( "Test2" ).Where( "c", 1 );
_builder.Select( "a,b" ).From( "Test" ).Where( "c", 2 ).Union( builder2 );
//验证
Assert.Equal( result.ToString(), _builder.ToSql() );
Assert.Equal( 1, _builder.GetParams()["@_p_0"] );
Assert.Equal( 2, _builder.GetParams()["@_p_1"] );
}
/// <summary>
/// 测试联合操作 - 排序
/// </summary>
[Fact]
public void TestUnion_2() {
//结果
var result = new String();
result.AppendLine( "(Select [a],[b] " );
result.AppendLine( "From [Test] " );
result.AppendLine( "Where [c]=@_p_1 " );
result.AppendLine( ") " );
result.AppendLine( "Union " );
result.AppendLine( "(Select [a],[b] " );
result.AppendLine( "From [Test2] " );
result.AppendLine( "Where [c]=@_p_0 " );
result.AppendLine( ") " );
result.Append( "Order By [a]" );
//执行
var builder2 = _builder.New().Select( "a,b" ).From( "Test2" ).Where( "c", 1 );
_builder.Select( "a,b" ).From( "Test" ).Where( "c", 2 ).OrderBy( "a" ).Union( builder2 );
//验证
Assert.Equal( result.ToString(), _builder.ToSql() );
Assert.Equal( 1, _builder.GetParams()["@_p_0"] );
Assert.Equal( 2, _builder.GetParams()["@_p_1"] );
}
/// <summary>
/// 测试联合操作 - 排序 - 联合查询中带排序被过滤
/// </summary>
[Fact]
public void TestUnion_3() {
//结果
var result = new String();
result.AppendLine( "(Select [a],[b] " );
result.AppendLine( "From [Test] " );
result.AppendLine( "Where [c]=@_p_1 " );
result.AppendLine( ") " );
result.AppendLine( "Union " );
result.AppendLine( "(Select [a],[b] " );
result.AppendLine( "From [Test2] " );
result.AppendLine( "Where [c]=@_p_0 " );
result.AppendLine( ") " );
result.Append( "Order By [a]" );
//执行
var builder2 = _builder.New().Select( "a,b" ).From( "Test2" ).Where( "c", 1 ).OrderBy( "b" );
_builder.Select( "a,b" ).From( "Test" ).Where( "c", 2 ).OrderBy( "a" ).Union( builder2 );
//验证
Assert.Equal( result.ToString(), _builder.ToSql() );
Assert.Equal( 1, _builder.GetParams()["@_p_0"] );
Assert.Equal( 2, _builder.GetParams()["@_p_1"] );
}
/// <summary>
/// 测试CTE
/// </summary>
[Fact]
public void TestWith_1() {
//结果
var result = new String();
result.AppendLine( "With [Test] " );
result.AppendLine( "As (Select [a],[b] " );
result.AppendLine( "From [Test2])" );
result.AppendLine( "Select [a],[b] " );
result.Append( "From [Test]" );
//执行
var builder2 = _builder.New().Select( "a,b" ).From( "Test2" );
_builder.Select( "a,b" ).From( "Test" ).With( "Test", builder2 );
//验证
Assert.Equal( result.ToString(), _builder.ToSql() );
}
/// <summary>
/// 测试CTE - 两个CTE
/// </summary>
[Fact]
public void TestWith_2() {
//结果
var result = new String();
result.AppendLine( "With [Test] " );
result.AppendLine( "As (Select [a],[b] " );
result.AppendLine( "From [Test2])," );
result.AppendLine( "[Test3] " );
result.AppendLine( "As (Select [a],[b] " );
result.AppendLine( "From [Test3])" );
result.AppendLine( "Select [a],[b] " );
result.Append( "From [Test]" );
//执行
var builder2 = _builder.New().Select( "a,b" ).From( "Test2" );
var builder3 = _builder.New().Select( "a,b" ).From( "Test3" );
_builder.Select( "a,b" ).From( "Test" ).With( "Test", builder2 ).With( "Test3", builder3 );
//验证
Assert.Equal( result.ToString(), _builder.ToSql() );
}
}
}
| 34.301887 | 114 | 0.481711 | [
"MIT"
] | LuciferJun1227/Util | test/Util.Datas.Tests.Integration/Sql/Builders/SqlServer/SqlServerBuilderTest.cs | 7,548 | C# |
using ESFA.DC.ESF.Database.EF;
using ESFA.DC.ESF.Interfaces.DataAccessLayer;
using ESFA.DC.ESF.Models;
namespace ESFA.DC.ESF.DataAccessLayer.Mappers
{
public class SourceFileModelMapper : ISourceFileModelMapper
{
public SourceFileModel GetModelFromEntity(SourceFile entity)
{
return new SourceFileModel
{
SourceFileId = entity.SourceFileId,
ConRefNumber = entity.ConRefNumber,
UKPRN = entity.UKPRN,
FileName = entity.FileName,
PreparationDate = entity.FilePreparationDate,
SuppliedDate = entity.DateTime
};
}
}
} | 31 | 68 | 0.615836 | [
"MIT"
] | SkillsFundingAgency/DC-ESF | src/ESFA.DC.ESF.DataAccessLayer/Mappers/SourceFileModelMapper.cs | 684 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Store.Tests.Commands
{
[TestClass]
public class CreateOrderCommandTests
{
[TestMethod]
[TestCategory("Handlers")]
public void DadoUmComandInvalidOPedidoNaoDeveSerGerado()
{
// FailFastValidation
var command = new Domain.Commands.CreateOrderCommand();
command.Customer = "";
command.ZipCode = "13454424";
command.PromoCode = "123456";
command.Items.Add(new Domain.Commands.CreateOrderItemCommand(Guid.NewGuid(), 1));
command.Items.Add(new Domain.Commands.CreateOrderItemCommand(Guid.NewGuid(), 1));
command.Validate();
Assert.AreEqual(false, command.Valid);
}
}
} | 32.16 | 93 | 0.633085 | [
"MIT"
] | JoaoNascSilva/RefatorandoParaTestesDeUnidade | Store.Tests/Commands/CreateOrderCommandTests.cs | 804 | C# |
namespace SharpBucket.V1.Pocos
{
public class SrcFile
{
public string node { get; set; }
public string path { get; set; }
public string data { get; set; }
public long size { get; set; }
}
} | 24.3 | 41 | 0.539095 | [
"MIT"
] | shannonphillipl/SharpBucket | SharpBucket/V1/Pocos/SrcFile.cs | 245 | C# |
using System;
using System.IO;
namespace Microsoft.Xna.Framework.Utilities
{
public class SubStream : Stream
{
Stream _host;
long _length;
long _start;
public SubStream(Stream host, long start, long len, long curPos)
{
_host = host;
_length = len;
_start = start;
if (host.CanSeek)
host.Seek(_start, SeekOrigin.Begin);
else
{
long skip = _start - curPos;
SkipBytes((int)skip);
_position = 0;
}
}
public override bool CanRead => _host.CanRead;
public override bool CanSeek => true;
public override bool CanWrite => _host.CanWrite;
public override long Length => _length;
private long _position = 0;
public override long Position
{
get
{
if (_host.CanSeek)
return _host.Position - _start;
else
return _position;
}
set
{
if (_host.CanSeek)
_host.Position = value + _start;
else
_position = value;
}
}
public override void Flush()
{
_host.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
long len = count;
if (_host.CanSeek)
{
if ((Position + len) > _length) len = _length - Position;
if (len < 1) return 0;
return _host.Read(buffer, offset, (int)len);
}
if (_position + len > Length) len = _length - _position;
if (len < 1) throw new EndOfStreamException();
int rlen = _host.Read(buffer, offset, (int)len);
_position += rlen;
return rlen;
}
public override long Seek(long offset, SeekOrigin origin)
{
if (_host.CanSeek)
{
switch (origin)
{
case SeekOrigin.Begin:
return _host.Seek(offset + _start, origin) - _start;
case SeekOrigin.Current:
return _host.Seek(offset, SeekOrigin.Current) - _start;
case SeekOrigin.End:
_host.Seek(_start + Length, SeekOrigin.Begin);
return _host.Seek(offset, SeekOrigin.Current) - _start;
}
return _host.Position - _start;
}
else
{
// Read forward if we are seeking forward
switch (origin)
{
case SeekOrigin.Begin:
if (offset > _position)
{
SkipBytes((int)(offset - _position));
}
if (offset < _position) throw new InvalidOperationException();
return offset;
case SeekOrigin.Current:
if (offset < 0) throw new InvalidOperationException();
_position += offset;
return _position;
case SeekOrigin.End:
if (offset > 0) throw new EndOfStreamException();
long _npos = Length + offset;
if (_npos < _position) throw new InvalidOperationException();
if (_npos > _position) SkipBytes((int)(_npos - _position));
return _position;
}
return _host.Position - _start;
}
}
private void SkipBytes(int cnt)
{
byte[] buffer = new byte[10240];
long skip = cnt;
long slen = Math.Min(skip, 10240L);
while (skip > 0)
{
var rlen = _host.Read(buffer, 0, (int)slen);
if (rlen != slen)
{
_position = Length;
throw new EndOfStreamException();
}
skip -= rlen;
slen = Math.Min(skip, 10240L);
}
_position += cnt;
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
_host.Write(buffer, offset, count);
}
}
}
| 29.757962 | 86 | 0.443279 | [
"MIT"
] | NebulaSleuth/MonoGame.XamarinForms | MonoGame.Framework/MonoGame.Framework.AndroidForms/Utilities/SubStream.cs | 4,674 | C# |
namespace Cake.Issues.Terraform.Tests
{
using System.Linq;
using Cake.Issues.Testing;
using Cake.Testing;
using Shouldly;
using Xunit;
public sealed class TerraformProviderTests
{
public sealed class TheCtor
{
[Fact]
public void Should_Throw_If_Log_Is_Null()
{
// Given / When
var result = Record.Exception(() =>
new TerraformIssuesProvider(
null,
new TerraformIssuesSettings("Foo".ToByteArray(), @"c:\Source\Cake.Issues")));
// Then
result.IsArgumentNullException("log");
}
[Fact]
public void Should_Throw_If_IssueProviderSettings_Are_Null()
{
var result = Record.Exception(() =>
new TerraformIssuesProvider(
new FakeLog(),
null));
// Then
result.IsArgumentNullException("issueProviderSettings");
}
}
// Test cases based on https://github.com/hashicorp/terraform-json/blob/master/validate_test.go
public sealed class TheReadIssuesMethod
{
[Fact]
public void Should_Read_Basic_Issues_Correct()
{
// Given
var fixture = new TerraformProviderFixture("basic.json", @"./");
// When
var issues = fixture.ReadIssues().ToList();
// Then
issues.Count.ShouldBe(2);
IssueChecker.Check(
issues[0],
IssueBuilder.NewIssue(
"\"anonymous\": [DEPRECATED] For versions later than 3.0.0, absence of a token enables this mode",
"Cake.Issues.Terraform.TerraformIssuesProvider",
"Terraform")
.WithPriority(IssuePriority.Warning));
IssueChecker.Check(
issues[1],
IssueBuilder.NewIssue(
"The argument \"name\" is required, but no definition was found.",
"Cake.Issues.Terraform.TerraformIssuesProvider",
"Terraform")
.InFile("main.tf", 14, 14, 37, 37)
.OfRule("Missing required argument")
.WithPriority(IssuePriority.Error));
}
[Fact]
public void Should_Read_Error_Correct()
{
// Given
var fixture = new TerraformProviderFixture("error.json", @"./");
// When
var issues = fixture.ReadIssues().ToList();
// Then
issues.Count.ShouldBe(1);
IssueChecker.Check(
issues[0],
IssueBuilder.NewIssue(
"\nPlugin reinitialization required...",
"Cake.Issues.Terraform.TerraformIssuesProvider",
"Terraform")
.OfRule("Could not load plugin")
.WithPriority(IssuePriority.Error));
}
}
}
}
| 35.180851 | 122 | 0.474146 | [
"MIT"
] | cake-contrib/Cake.Issues.Terraform | src/Cake.Issues.Terraform.Tests/TerraformProviderTests.cs | 3,309 | C# |
using LogShark.Containers;
using LogShark.Plugins.Shared;
using LogShark.Writers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
namespace LogShark.Plugins.Apache
{
public class ApachePlugin : IPlugin
{
private const bool DefaultIncludeGatewayHealthChecksValue = false;
private static readonly DataSetInfo OutputInfo = new DataSetInfo("Apache", "ApacheRequests");
private static readonly List<LogType> ConsumedLogTypesStatic = new List<LogType> { LogType.Apache };
public IList<LogType> ConsumedLogTypes => ConsumedLogTypesStatic;
public string Name => "Apache";
private IWriter<ApacheEvent> _writer;
private IProcessingNotificationsCollector _processingNotificationsCollector;
private bool _includeGatewayHealthChecks;
public void Configure(IWriterFactory writerFactory, IConfiguration pluginConfig, IProcessingNotificationsCollector processingNotificationsCollector, ILoggerFactory loggerFactory)
{
_writer = writerFactory.GetWriter<ApacheEvent>(OutputInfo);
var section = pluginConfig?.GetSection("IncludeGatewayChecks");
var sectionExists = section != null && section.Exists();
if (!sectionExists)
{
var logger = loggerFactory.CreateLogger<ApachePlugin>();
logger.LogWarning("{pluginName} config was missing from Plugins Configuration. Using default value of {defaultValue} for {missingParameterName} parameter", nameof(ApachePlugin), DefaultIncludeGatewayHealthChecksValue, "IncludeGatewayChecks");
}
_includeGatewayHealthChecks = sectionExists ? section.Get<bool>() : DefaultIncludeGatewayHealthChecksValue;
_processingNotificationsCollector = processingNotificationsCollector;
}
public void ProcessLogLine(LogLine logLine, LogType logType)
{
var @event = ApacheEventParser.ParseEvent(logLine);
if (@event == null)
{
_processingNotificationsCollector.ReportError("Failed to parse Apache event from log line", logLine, nameof(ApachePlugin));
return;
}
if (_includeGatewayHealthChecks || !IsHealthCheckRequest(@event))
{
_writer.AddLine(@event);
}
}
public SinglePluginExecutionResults CompleteProcessing()
{
var writerStatistics = _writer.Close();
return new SinglePluginExecutionResults(writerStatistics);
}
public void Dispose()
{
_writer.Dispose();
}
private static bool IsHealthCheckRequest(ApacheEvent ev)
{
return ev?.RequestBody == "/favicon.ico";
}
}
} | 40.084507 | 258 | 0.676739 | [
"MIT"
] | isabella232/Logshark | LogShark/Plugins/Apache/ApachePlugin.cs | 2,846 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using MagicChunks.Helpers;
namespace MagicChunks.Core
{
public class Transformer : ITransformer
{
private static readonly Regex RemoveEndingRegex = new Regex(@"\`\d+$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly Regex RemoveArrayEndingRegex = new Regex(@"\[\]$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly IEnumerable<Type> _documentTypes;
static Transformer()
{
_documentTypes = typeof(Transformer)
.GetTypeInfo()
.Assembly
.GetAllTypes(p => !p.IsAbstract && p.ImplementedInterfaces.Contains(typeof(IDocument)));
}
public IEnumerable<Type> DocumentTypes => _documentTypes;
public string Transform(string source, TransformationCollection transformations)
{
foreach (var documentType in DocumentTypes)
{
IDocument document;
try
{
document = (IDocument)Activator.CreateInstance(documentType, source);
}
catch (TargetInvocationException ex)
{
if (ex.InnerException.GetType() == typeof(ArgumentException))
continue;
throw;
}
return Transform(document, transformations);
}
throw new ArgumentException("Unknown document type.", nameof(source));
}
public string Transform<TDocument>(string source, TransformationCollection transformations) where TDocument : IDocument
{
var document = (TDocument)Activator.CreateInstance(typeof(TDocument), source);
return Transform(document, transformations);
}
public string Transform(Type documentType, string source, TransformationCollection transformations)
{
IDocument document;
try
{
document = (IDocument)Activator.CreateInstance(documentType, source);
}
catch (TargetInvocationException ex)
{
if (ex.InnerException.GetType() == typeof(ArgumentException))
throw new ArgumentException("Unknown document type.", nameof(source), ex);
throw;
}
return Transform(document, transformations);
}
public string Transform(IDocument source, TransformationCollection transformations)
{
if (transformations.KeysToRemove != null)
{
foreach (var key in transformations.KeysToRemove)
{
if (String.IsNullOrWhiteSpace(key))
throw new ArgumentNullException(nameof(transformations), "Transformation key is empty.");
source.RemoveKey(SplitKey(key));
}
}
foreach (var transformation in transformations)
{
if (String.IsNullOrWhiteSpace(transformation.Key))
throw new ArgumentException("Transformation key is empty.", nameof(transformations));
if (transformation.Key.StartsWith("#"))
{
source.RemoveKey(SplitKey(transformation.Key.TrimStart('#')));
}
else if (RemoveEndingRegex.Replace(transformation.Key, String.Empty).EndsWith("[]"))
{
source.AddElementToArray(SplitKey(transformation.Key), transformation.Value);
}
else
{
source.ReplaceKey(SplitKey(transformation.Key), transformation.Value);
}
}
return source.ToString();
}
private static string[] SplitKey(string key)
{
return RemoveArrayEndingRegex.Replace(RemoveEndingRegex.Replace(key.Trim(), String.Empty), String.Empty).Split('/').Select(x => x.Trim()).ToArray();
}
public void Dispose()
{
}
}
} | 35.764706 | 160 | 0.574953 | [
"MIT"
] | 3choBoomer/magic-chunks | src/MagicChunks/Core/Transformer.cs | 4,256 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Cmdlets
{
using static Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Extensions;
using System;
/// <summary>Creates or Updates a classification rule</summary>
/// <remarks>
/// [OpenAPI] CreateOrUpdate=>PUT:"/classificationrules/{classificationRuleName}"
/// </remarks>
[global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzPurviewClassificationRule_Create", SupportsShouldProcess = true)]
[global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IClassificationRule))]
[global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Description(@"Creates or Updates a classification rule")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Generated]
public partial class NewAzPurviewClassificationRule_Create : global::System.Management.Automation.PSCmdlet,
Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener
{
/// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary>
private string __correlationId = System.Guid.NewGuid().ToString();
/// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary>
private global::System.Management.Automation.InvocationInfo __invocationInfo;
/// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary>
private string __processRecordId;
/// <summary>
/// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation.
/// </summary>
private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource();
/// <summary>Backing field for <see cref="Body" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IClassificationRule _body;
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = ".", ValueFromPipeline = true)]
[Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"",
SerializedName = @"body",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IClassificationRule) })]
public Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IClassificationRule Body { get => this._body; set => this._body = value; }
/// <summary>Wait for .NET debugger to attach</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter Break { get; set; }
/// <summary>The reference to the client API class.</summary>
public Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Purviewdata Client => Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Module.Instance.ClientAPI;
/// <summary>
/// The credentials, account, tenant, and subscription used for communication with Azure
/// </summary>
[global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")]
[global::System.Management.Automation.ValidateNotNull]
[global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.ParameterCategory.Azure)]
public global::System.Management.Automation.PSObject DefaultProfile { get; set; }
/// <summary>Backing field for <see cref="Endpoint" /> property.</summary>
private string _endpoint;
/// <summary>
/// The scanning endpoint of your purview account. Example: https://{accountName}.purview.azure.com
/// </summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The scanning endpoint of your purview account. Example: https://{accountName}.purview.azure.com")]
[Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"The scanning endpoint of your purview account. Example: https://{accountName}.purview.azure.com",
SerializedName = @"Endpoint",
PossibleTypes = new [] { typeof(string) })]
[global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.ParameterCategory.Uri)]
public string Endpoint { get => this._endpoint; set => this._endpoint = value; }
/// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.ParameterCategory.Runtime)]
public Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; }
/// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.ParameterCategory.Runtime)]
public Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; }
/// <summary>Accessor for our copy of the InvocationInfo.</summary>
public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } }
/// <summary>
/// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called.
/// </summary>
global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel;
/// <summary><see cref="IEventListener" /> cancellation token.</summary>
global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener.Token => _cancellationTokenSource.Token;
/// <summary>Backing field for <see cref="Name" /> property.</summary>
private string _name;
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = ".")]
[Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"",
SerializedName = @"classificationRuleName",
PossibleTypes = new [] { typeof(string) })]
[global::System.Management.Automation.Alias("ClassificationRuleName")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.ParameterCategory.Path)]
public string Name { get => this._name; set => this._name = value; }
/// <summary>
/// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.HttpPipeline" /> that the remote call will use.
/// </summary>
private Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.HttpPipeline Pipeline { get; set; }
/// <summary>The URI for the proxy server to use</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.ParameterCategory.Runtime)]
public global::System.Uri Proxy { get; set; }
/// <summary>Credentials for a proxy server to use for the remote call</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.ParameterCategory.Runtime)]
public global::System.Management.Automation.PSCredential ProxyCredential { get; set; }
/// <summary>Use the default credentials for the proxy</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; }
/// <summary>
/// <c>overrideOnCreated</c> will be called before the regular onCreated has been processed, allowing customization of what
/// happens on that response. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IClassificationRule"
/// /> from the remote call</param>
/// <param name="returnNow">/// Determines if the rest of the onCreated method should be processed, or if the method should
/// return immediately (set to true to skip further processing )</param>
partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IClassificationRule> response, ref global::System.Threading.Tasks.Task<bool> returnNow);
/// <summary>
/// <c>overrideOnDefault</c> will be called before the regular onDefault has been processed, allowing customization of what
/// happens on that response. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IErrorResponseModel"
/// /> from the remote call</param>
/// <param name="returnNow">/// Determines if the rest of the onDefault method should be processed, or if the method should
/// return immediately (set to true to skip further processing )</param>
partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IErrorResponseModel> response, ref global::System.Threading.Tasks.Task<bool> returnNow);
/// <summary>
/// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens
/// on that response. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IClassificationRule"
/// /> from the remote call</param>
/// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return
/// immediately (set to true to skip further processing )</param>
partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IClassificationRule> response, ref global::System.Threading.Tasks.Task<bool> returnNow);
/// <summary>
/// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet)
/// </summary>
protected override void BeginProcessing()
{
Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials);
if (Break)
{
Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.AttachDebugger.Break();
}
((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
/// <summary>Performs clean-up after the command execution</summary>
protected override void EndProcessing()
{
((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
/// <summary>Handles/Dispatches events during the call to the REST service.</summary>
/// <param name="id">The message id</param>
/// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param>
/// <param name="messageData">Detailed message data for the message event.</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed.
/// </returns>
async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.EventData> messageData)
{
using( NoSynchronizationContext )
{
if (token.IsCancellationRequested)
{
return ;
}
switch ( id )
{
case Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Events.Verbose:
{
WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Events.Warning:
{
WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Events.Information:
{
var data = messageData();
WriteInformation(data.Message, new string[]{});
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Events.Debug:
{
WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Events.Error:
{
WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) );
return ;
}
}
await Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null );
if (token.IsCancellationRequested)
{
return ;
}
WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}");
}
}
/// <summary>
/// Intializes a new instance of the <see cref="NewAzPurviewClassificationRule_Create" /> cmdlet class.
/// </summary>
public NewAzPurviewClassificationRule_Create()
{
}
/// <summary>Performs execution of the command.</summary>
protected override void ProcessRecord()
{
((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
__processRecordId = System.Guid.NewGuid().ToString();
try
{
// work
if (ShouldProcess($"Call remote 'ClassificationRulesCreateOrUpdate' operation"))
{
using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Token) )
{
asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Token);
}
}
}
catch (global::System.AggregateException aggregateException)
{
// unroll the inner exceptions to get the root cause
foreach( var innerException in aggregateException.Flatten().InnerExceptions )
{
((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
// Write exception out to error channel.
WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) );
}
}
catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null)
{
((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
// Write exception out to error channel.
WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) );
}
finally
{
((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Events.CmdletProcessRecordEnd).Wait();
}
}
/// <summary>Performs execution of the command, working asynchronously if required.</summary>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
protected async global::System.Threading.Tasks.Task ProcessRecordAsync()
{
using( NoSynchronizationContext )
{
await ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
await ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName);
if (null != HttpPipelinePrepend)
{
Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend);
}
if (null != HttpPipelineAppend)
{
Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend);
}
// get the client instance
try
{
await ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
await this.Client.ClassificationRulesCreateOrUpdate(Endpoint, Name, Body, onOk, onCreated, onDefault, this, Pipeline);
await ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
catch (Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.UndeclaredResponseException urexception)
{
WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Endpoint=Endpoint,Name=Name,body=Body})
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action }
});
}
finally
{
await ((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Events.CmdletProcessRecordAsyncEnd);
}
}
}
/// <summary>Interrupts currently running code within the command.</summary>
protected override void StopProcessing()
{
((Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.IEventListener)this).Cancel();
base.StopProcessing();
}
/// <summary>a delegate that is called when the remote service returns 201 (Created).</summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IClassificationRule"
/// /> from the remote call</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
private async global::System.Threading.Tasks.Task onCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IClassificationRule> response)
{
using( NoSynchronizationContext )
{
var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false);
overrideOnCreated(responseMessage, response, ref _returnNow);
// if overrideOnCreated has returned true, then return right away.
if ((null != _returnNow && await _returnNow))
{
return ;
}
// onCreated - response for 201 / application/json
// (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IClassificationRule
WriteObject((await response));
}
}
/// <summary>
/// a delegate that is called when the remote service returns default (any response code not handled elsewhere).
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IErrorResponseModel"
/// /> from the remote call</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IErrorResponseModel> response)
{
using( NoSynchronizationContext )
{
var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false);
overrideOnDefault(responseMessage, response, ref _returnNow);
// if overrideOnDefault has returned true, then return right away.
if ((null != _returnNow && await _returnNow))
{
return ;
}
// Error Response : default
var code = (await response)?.Code;
var message = (await response)?.Message;
if ((null == code || null == message))
{
// Unrecognized Response. Create an error record based on what we have.
var ex = new Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.RestException<Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IErrorResponseModel>(responseMessage, await response);
WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Endpoint=Endpoint, Name=Name, body=Body })
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action }
});
}
else
{
WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Endpoint=Endpoint, Name=Name, body=Body })
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty }
});
}
}
}
/// <summary>a delegate that is called when the remote service returns 200 (OK).</summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IClassificationRule"
/// /> from the remote call</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IClassificationRule> response)
{
using( NoSynchronizationContext )
{
var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false);
overrideOnOk(responseMessage, response, ref _returnNow);
// if overrideOnOk has returned true, then return right away.
if ((null != _returnNow && await _returnNow))
{
return ;
}
// onOk - response for 200 / application/json
// (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IClassificationRule
WriteObject((await response));
}
}
}
} | 73.902552 | 475 | 0.673741 | [
"MIT"
] | Agazoth/azure-powershell | src/Purview/Purviewdata.Autorest/generated/cmdlets/NewAzPurviewClassificationRule_Create.cs | 31,422 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using ILRuntime.Mono.Cecil;
using ILRuntime.Runtime.Intepreter;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.CLR.TypeSystem;
using ILRuntime.Runtime.Stack;
using ILRuntime.CLR.Utils;
namespace ILRuntime.CLR.Method
{
public class CLRMethod : IMethod
{
MethodInfo def;
ConstructorInfo cDef;
List<IType> parameters;
ParameterInfo[] parametersCLR;
ILRuntime.Runtime.Enviorment.AppDomain appdomain;
CLRType declaringType;
ParameterInfo[] param;
bool isConstructor;
CLRRedirectionDelegate redirect;
IType[] genericArguments;
Type[] genericArgumentsCLR;
object[] invocationParam;
bool isDelegateInvoke;
int hashCode = -1;
static int instance_id = 0x20000000;
public IType DeclearingType
{
get
{
return declaringType;
}
}
public string Name
{
get
{
return def.Name;
}
}
public bool HasThis
{
get
{
return isConstructor ? !cDef.IsStatic : !def.IsStatic;
}
}
public int GenericParameterCount
{
get
{
if (def.ContainsGenericParameters && def.IsGenericMethodDefinition)
{
return def.GetGenericArguments().Length;
}
return 0;
}
}
public bool IsGenericInstance
{
get
{
return genericArguments != null;
}
}
public bool IsDelegateInvoke
{
get
{
return isDelegateInvoke;
}
}
public bool IsStatic
{
get
{
if (cDef != null)
return cDef.IsStatic;
else
return def.IsStatic;
}
}
public CLRRedirectionDelegate Redirection { get { return redirect; } }
public MethodInfo MethodInfo { get { return def; } }
public ConstructorInfo ConstructorInfo { get { return cDef; } }
public IType[] GenericArguments { get { return genericArguments; } }
public Type[] GenericArgumentsCLR
{
get
{
if(genericArgumentsCLR == null)
{
if (cDef != null)
genericArgumentsCLR = cDef.GetGenericArguments();
else
genericArgumentsCLR = def.GetGenericArguments();
}
return genericArgumentsCLR;
}
}
internal CLRMethod(MethodInfo def, CLRType type, ILRuntime.Runtime.Enviorment.AppDomain domain)
{
this.def = def;
declaringType = type;
this.appdomain = domain;
param = def.GetParameters();
if (!def.ContainsGenericParameters)
{
ReturnType = domain.GetType(def.ReturnType.FullName);
if (ReturnType == null)
{
ReturnType = domain.GetType(def.ReturnType.AssemblyQualifiedName);
}
}
if (type.IsDelegate && def.Name == "Invoke")
isDelegateInvoke = true;
isConstructor = false;
if (def != null)
{
if (def.IsGenericMethod && !def.IsGenericMethodDefinition)
{
//Redirection of Generic method Definition will be prioritized
if(!appdomain.RedirectMap.TryGetValue(def.GetGenericMethodDefinition(), out redirect))
appdomain.RedirectMap.TryGetValue(def, out redirect);
}
else
appdomain.RedirectMap.TryGetValue(def, out redirect);
}
}
internal CLRMethod(ConstructorInfo def, CLRType type, ILRuntime.Runtime.Enviorment.AppDomain domain)
{
this.cDef = def;
declaringType = type;
this.appdomain = domain;
param = def.GetParameters();
if (!def.ContainsGenericParameters)
{
ReturnType = type;
}
isConstructor = true;
if (def != null)
{
appdomain.RedirectMap.TryGetValue(cDef, out redirect);
}
}
public int ParameterCount
{
get
{
return param != null ? param.Length : 0;
}
}
public List<IType> Parameters
{
get
{
if (parameters == null)
{
InitParameters();
}
return parameters;
}
}
public ParameterInfo[] ParametersCLR
{
get
{
if(parametersCLR == null)
{
if (cDef != null)
parametersCLR = cDef.GetParameters();
else
parametersCLR = def.GetParameters();
}
return parametersCLR;
}
}
public IType ReturnType
{
get;
private set;
}
public bool IsConstructor
{
get
{
return cDef != null;
}
}
void InitParameters()
{
parameters = new List<IType>();
foreach (var i in param)
{
IType type = appdomain.GetType(i.ParameterType.FullName);
if (type == null)
type = appdomain.GetType(i.ParameterType.AssemblyQualifiedName);
if (i.ParameterType.IsGenericTypeDefinition)
{
if (type == null)
type = appdomain.GetType(i.ParameterType.GetGenericTypeDefinition().FullName);
if (type == null)
type = appdomain.GetType(i.ParameterType.GetGenericTypeDefinition().AssemblyQualifiedName);
}
if (i.ParameterType.ContainsGenericParameters)
{
var t = i.ParameterType;
if (t.HasElementType)
t = i.ParameterType.GetElementType();
else if (t.GetGenericArguments().Length > 0)
{
t = t.GetGenericArguments()[0];
}
type = new ILGenericParameterType(t.Name);
}
if (type == null)
throw new TypeLoadException();
parameters.Add(type);
}
}
unsafe StackObject* Minus(StackObject* a, int b)
{
return (StackObject*)((long)a - sizeof(StackObject) * b);
}
public unsafe object Invoke(Runtime.Intepreter.ILIntepreter intepreter, StackObject* esp, IList<object> mStack, bool isNewObj = false)
{
if (parameters == null)
{
InitParameters();
}
int paramCount = ParameterCount;
if (invocationParam == null)
invocationParam = new object[paramCount];
object[] param = invocationParam;
for (int i = paramCount; i >= 1; i--)
{
var p = Minus(esp, i);
var pt = this.param[paramCount - i].ParameterType;
var obj = pt.CheckCLRTypes(StackObject.ToObject(p, appdomain, mStack));
obj = ILIntepreter.CheckAndCloneValueType(obj, appdomain);
param[paramCount - i] = obj;
}
if (isConstructor)
{
if (!isNewObj)
{
if (!cDef.IsStatic)
{
object instance = declaringType.TypeForCLR.CheckCLRTypes(StackObject.ToObject((Minus(esp, paramCount + 1)), appdomain, mStack));
if (instance == null)
throw new NullReferenceException();
if (instance is CrossBindingAdaptorType && paramCount == 0)//It makes no sense to call the Adaptor's default constructor
return null;
cDef.Invoke(instance, param);
Array.Clear(invocationParam, 0, invocationParam.Length);
return null;
}
else
{
throw new NotImplementedException();
}
}
else
{
var res = cDef.Invoke(param);
FixReference(paramCount, esp, param, mStack, null, false);
Array.Clear(invocationParam, 0, invocationParam.Length);
return res;
}
}
else
{
object instance = null;
if (!def.IsStatic)
{
instance = StackObject.ToObject((Minus(esp, paramCount + 1)), appdomain, mStack);
if (!(instance is Reflection.ILRuntimeWrapperType))
instance = declaringType.TypeForCLR.CheckCLRTypes(instance);
//if (declaringType.IsValueType)
// instance = ILIntepreter.CheckAndCloneValueType(instance, appdomain);
if (instance == null)
throw new NullReferenceException();
}
object res = null;
/*if (redirect != null)
res = redirect(new ILContext(appdomain, intepreter, esp, mStack, this), instance, param, genericArguments);
else*/
{
res = def.Invoke(instance, param);
}
FixReference(paramCount, esp, param, mStack, instance, !def.IsStatic);
Array.Clear(invocationParam, 0, invocationParam.Length);
return res;
}
}
unsafe void FixReference(int paramCount, StackObject* esp, object[] param, IList<object> mStack,object instance, bool hasThis)
{
var cnt = hasThis ? paramCount + 1 : paramCount;
for (int i = cnt; i >= 1; i--)
{
var p = Minus(esp, i);
var val = i <= paramCount ? param[paramCount - i] : instance;
switch (p->ObjectType)
{
case ObjectTypes.StackObjectReference:
{
var addr = *(long*)&p->Value;
var dst = (StackObject*)addr;
if (dst->ObjectType >= ObjectTypes.Object)
{
var obj = val;
if (obj is CrossBindingAdaptorType)
obj = ((CrossBindingAdaptorType)obj).ILInstance;
mStack[dst->Value] = obj;
}
else
{
ILIntepreter.UnboxObject(dst, val, mStack, appdomain);
}
}
break;
case ObjectTypes.FieldReference:
{
var obj = mStack[p->Value];
if(obj is ILTypeInstance)
{
((ILTypeInstance)obj)[p->ValueLow] = val;
}
else
{
var t = appdomain.GetType(obj.GetType()) as CLRType;
t.GetField(p->ValueLow).SetValue(obj, val);
}
}
break;
case ObjectTypes.StaticFieldReference:
{
var t = appdomain.GetType(p->Value);
if(t is ILType)
{
((ILType)t).StaticInstance[p->ValueLow] = val;
}
else
{
((CLRType)t).SetStaticFieldValue(p->ValueLow, val);
}
}
break;
case ObjectTypes.ArrayReference:
{
var arr = mStack[p->Value] as Array;
arr.SetValue(val, p->ValueLow);
}
break;
}
}
}
public IMethod MakeGenericMethod(IType[] genericArguments)
{
Type[] p = new Type[genericArguments.Length];
for (int i = 0; i < genericArguments.Length; i++)
{
p[i] = genericArguments[i].TypeForCLR;
}
MethodInfo t = null;
#if UNITY_EDITOR || (DEBUG && !DISABLE_ILRUNTIME_DEBUG)
try
{
#endif
t = def.MakeGenericMethod(p);
#if UNITY_EDITOR || (DEBUG && !DISABLE_ILRUNTIME_DEBUG)
}
catch (Exception e)
{
string argString = "";
for (int i = 0; i < genericArguments.Length; i++)
{
argString += genericArguments[i].TypeForCLR.FullName + ", ";
}
argString = argString.Substring(0, argString.Length - 2);
throw new Exception($"MakeGenericMethod failed : {def.DeclaringType.FullName}.{def.Name}<{argString}>");
}
#endif
var res = new CLRMethod(t, declaringType, appdomain);
res.genericArguments = genericArguments;
return res;
}
public override string ToString()
{
if (def != null)
return def.ToString();
else
return cDef.ToString();
}
public override int GetHashCode()
{
if (hashCode == -1)
hashCode = System.Threading.Interlocked.Add(ref instance_id, 1);
return hashCode;
}
}
}
| 33.869863 | 152 | 0.446579 | [
"MIT"
] | yomunsam/ILRuntime | ILRuntime/CLR/Method/CLRMethod.cs | 14,837 | C# |
using System;
using UnityEngine;
using UnityEngine.SceneManagement;
/// <summary>
/// Provides singleton pattern functionality to MonoBehaviours
/// </summary>
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
private static bool destroyed = false;
/// <summary>
/// The singleton instance.
/// </summary>
public static T Instance
{
get
{
if (destroyed)
{
return null;
}
if (instance == null)
{
GameObject prefab = FindResource();
GameObject go;
if(prefab != null)
{
go = Instantiate(prefab);
go.name = prefab.name + " Instance";
instance = go.GetComponent<T>();
if(instance == null)
{
Debug.LogError("Loaded singleton instance is null");
}
}
else
{
go = new GameObject();
go.name = typeof(T).ToString() + " Instance";
instance = go.AddComponent<T>();
}
DontDestroyOnLoad(go);
}
return instance;
}
}
/// <summary>
/// Initialize
/// </summary>
protected virtual void Awake()
{
SceneManager.sceneLoaded += SceneLoadedHandler;
OnSceneLoaded(SceneManager.GetActiveScene(), LoadSceneMode.Single);
}
/// <summary>
/// Initialize
/// </summary>
protected virtual void Start()
{
}
/// <summary>
/// Called when a scene is loaded and when the singleton is first initialized.
/// </summary>
protected virtual void OnSceneLoaded(Scene scene, LoadSceneMode mode) { }
/// <summary>
/// Called when the singleton is destroyed.
/// </summary>
protected virtual void OnDestroy()
{
SceneManager.sceneLoaded -= SceneLoadedHandler;
destroyed = true;
}
/// <summary>
/// Search for the predefined instance in the resources folder
/// </summary>
/// <returns></returns>
private static GameObject FindResource()
{
GameObject go = (GameObject)Resources.Load(typeof(T).Name, typeof(GameObject));
if(go != null && go.GetComponent<T>() != null)
{
return go;
}
return null;
}
/// <summary>
/// Handles the scene loaded event.
/// </summary>
private void SceneLoadedHandler(Scene scene, LoadSceneMode mode)
{
OnSceneLoaded(scene, mode);
}
}
| 20.158879 | 81 | 0.649977 | [
"Unlicense",
"MIT"
] | LjutaPapricica/LockPick_Unity | Assets/Source/Singleton.cs | 2,159 | C# |
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Mapping.ByCode.Conformist;
using NHibernate.Mapping.ByCode;
using Sample.CustomerService.Domain;
namespace Sample.CustomerService.Maps {
public class VstorewithcontactsMap : ClassMapping<Vstorewithcontacts> {
public VstorewithcontactsMap() {
Schema("Sales");
Lazy(true);
Property(x => x.Businessentityid, map => { map.NotNullable(true); map.Precision(10); });
Property(x => x.Name, map => { map.NotNullable(true); map.Length(50); });
Property(x => x.Contacttype, map => { map.NotNullable(true); map.Length(50); });
Property(x => x.Title, map => map.Length(8));
Property(x => x.Firstname, map => { map.NotNullable(true); map.Length(50); });
Property(x => x.Middlename, map => map.Length(50));
Property(x => x.Lastname, map => { map.NotNullable(true); map.Length(50); });
Property(x => x.Suffix, map => map.Length(10));
Property(x => x.Phonenumber, map => map.Length(25));
Property(x => x.Phonenumbertype, map => map.Length(50));
Property(x => x.Emailaddress, map => map.Length(50));
Property(x => x.Emailpromotion, map => { map.NotNullable(true); map.Precision(10); });
}
}
}
| 38.333333 | 91 | 0.657708 | [
"MIT"
] | antosilva/Easy.NHibernate.Samples | SQLServer/AdventureWorks2012/Mapping/VstorewithcontactsMap.cs | 1,265 | C# |
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace Roki.Web.Models
{
public class DiscordGuild
{
public string Id { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
}
public class Guild
{
public ulong Id { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
public ulong OwnerId { get; set; }
public List<long> Moderators { get; } = new();
public bool Available { get; set; } = true;
public virtual GuildConfig GuildConfig { get; set; }
// public virtual ICollection<Event> Events { get; set; } = new List<Event>();
// public virtual ICollection<StoreItem> Items { get; set; } = new List<StoreItem>();
// public virtual ICollection<Quote> Quotes { get; set; } = new List<Quote>();
// public virtual ICollection<XpReward> XpRewards { get; set; } = new List<XpReward>();
public Guild(ulong id, string name, string icon, ulong ownerId)
{
Id = id;
Name = name;
Icon = icon;
OwnerId = ownerId;
}
}
public class GuildConfig
{
public ulong GuildId { get; set; }
#region Core
public string Prefix { get; set; } = ".";
public bool Logging { get; set; } = false;
public bool CurrencyGen { get; set; } = true;
public bool XpGain { get; set; } = true;
public bool ShowHelpOnError { get; set; } = true;
#endregion
#region Currency
public string CurrencyIcon { get; set; } = "<:stone:269130892100763649>";
public string CurrencyName { get; set; } = "Stone";
public string CurrencyNamePlural { get; set; } = "Stones";
public double CurrencyGenerationChance { get; set; } = 0.02;
public int CurrencyGenerationCooldown { get; set; } = 60;
public int CurrencyDropAmount { get; set; } = 1;
public int CurrencyDropAmountMax { get; set; } = 5;
public int CurrencyDropAmountRare { get; set; } = 100;
public long CurrencyDefault { get; set; } = 1000;
public decimal InvestingDefault { get; set; } = 5000;
#endregion
#region Xp
public int XpPerMessage { get; set; } = 5;
public int XpCooldown { get; set; } = 300;
public int XpFastCooldown { get; set; } = 150;
public int NotificationLocation { get; set; } = 1;
#endregion
#region BetFlip
public int BetFlipMin { get; set; } = 2;
public double BetFlipMultiplier { get; set; } = 1.95;
#endregion
#region BetFlipMulti
public double BetFlipMMinMultiplier { get; set; } = 2;
public int BetFlipMMinGuesses { get; set; } = 5;
public double BetFlipMMinCorrect { get; set; } = 0.75;
public double BetFlipMMultiplier { get; set; } = 1.1;
#endregion
#region BetDice
public int BetDiceMin { get; set; } = 10;
#endregion
#region BetRoll
public int BetRollMin { get; set; } = 1;
public double BetRoll71Multiplier { get; set; } = 2.5;
public double BetRoll92Multiplier { get; set; } = 4;
public double BetRoll100Multiplier { get; set; } = 10;
#endregion
#region Trivia
public double TriviaMinCorrect { get; set; } = 0.6;
public int TriviaEasy { get; set; } = 100;
public int TriviaMedium { get; set; } = 300;
public int TriviaHard { get; set; } = 500;
#endregion
#region Jeopardy
public double JeopardyWinMultiplier { get; set; } = 1;
#endregion
[JsonIgnore]
public virtual Guild Guild { get; set; }
}
public class GuildConfigUpdate
{
public string Prefix { get; set; }
[JsonPropertyName("guild_logging")]
public string Logging { get; set; }
[JsonPropertyName("guild_curr")]
public string CurrencyGen { get; set; }
[JsonPropertyName("guild_xp")]
public string XpGain { get; set; }
[JsonPropertyName("guild_show_help")]
public string ShowHelpOnError { get; set; }
[JsonPropertyName("guild_curr_icon")]
public string CurrencyIcon { get; set; }
[JsonPropertyName("guild_curr_name")]
public string CurrencyName { get; set; }
[JsonPropertyName("guild_curr_name_p")]
public string CurrencyNamePlural { get; set; }
[JsonPropertyName("guild_curr_prob")]
public string CurrencyGenerationChance { get; set; }
[JsonPropertyName("guild_curr_cd")]
public string CurrencyGenerationCooldown { get; set; }
[JsonPropertyName("guild_curr_drop")]
public string CurrencyDropAmount { get; set; }
[JsonPropertyName("guild_curr_drop_max")]
public string CurrencyDropAmountMax { get; set; }
[JsonPropertyName("guild_curr_drop_rare")]
public string CurrencyDropAmountRare { get; set; }
[JsonPropertyName("guild_curr_default")]
public string CurrencyDefault { get; set; }
[JsonPropertyName("guild_inv_default")]
public string InvestingDefault { get; set; }
[JsonPropertyName("guild_xp_pm")]
public string XpPerMessage { get; set; }
[JsonPropertyName("guild_xp_cd")]
public string XpCooldown { get; set; }
[JsonPropertyName("guild_xp_cd_fast")]
public string XpFastCooldown { get; set; }
[JsonPropertyName("guild_xp_notif")]
public string NotificationLocation { get; set; }
[JsonPropertyName("guild_bf_min")]
public string BetFlipMin { get; set; }
[JsonPropertyName("guild_bf_mult")]
public string BetFlipMultiplier { get; set; }
[JsonPropertyName("guild_bfm_min")]
public string BetFlipMMinMultiplier { get; set; }
[JsonPropertyName("guild_bfm_min_guess")]
public string BetFlipMMinGuesses { get; set; }
[JsonPropertyName("guild_bfm_min_correct")]
public string BetFlipMMinCorrect { get; set; }
[JsonPropertyName("guild_bfm_mult")]
public string BetFlipMMultiplier { get; set; }
[JsonPropertyName("guild_bd_min")]
public string BetDiceMin { get; set; }
[JsonPropertyName("guild_br_min")]
public string BetRollMin { get; set; }
[JsonPropertyName("guild_br_71")]
public string BetRoll71Multiplier { get; set; }
[JsonPropertyName("guild_br_92")]
public string BetRoll92Multiplier { get; set; }
[JsonPropertyName("guild_br_100")]
public string BetRoll100Multiplier { get; set; }
[JsonPropertyName("guild_trivia_min")]
public string TriviaMinCorrect { get; set; }
[JsonPropertyName("guild_trivia_easy")]
public string TriviaEasy { get; set; }
[JsonPropertyName("guild_trivia_med")]
public string TriviaMedium { get; set; }
[JsonPropertyName("guild_trivia_hard")]
public string TriviaHard { get; set; }
[JsonPropertyName("guild_jeopardy_mult")]
public string JeopardyWinMultiplier { get; set; }
}
} | 36.452261 | 95 | 0.610422 | [
"MIT"
] | louzhang/roki | Roki.Web/Models/GuildModel.cs | 7,254 | C# |
namespace OggVorbisEncoder.Setup.Templates.Stereo44.BookBlocks.Chapter4
{
public class Page8_1 : IStaticCodeBook
{
public int AllocedP = 0;
public int Dimensions = 2;
public byte[] LengthList = {
2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
5, 5, 5, 5, 6, 6, 6, 5, 5
};
public CodeBookMapType MapType = CodeBookMapType.Implicit;
public int QuantMin = -533725184;
public int QuantDelta = 1611661312;
public int Quant = 3;
public int QuantSequenceP = 0;
public int[] QuantList = {
2,
1,
3,
0,
4
};
}
} | 25.555556 | 72 | 0.505797 | [
"Apache-2.0",
"MIT"
] | BenRQ/valkyrie | libraries/FFGAppImport/AssetImport/oggencoder/Setup/Templates/Stereo44/BookBlocks/Chapter4/Page8_1.cs | 692 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace PolyPerfect
{
public class Common_AnimSpeed : MonoBehaviour
{
Animator anim;
float Speed;
// Use this for initialization
void Start()
{
Speed = Random.Range(0.85f, 1.25f);
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
anim.speed = Speed;
}
}
} | 18.740741 | 49 | 0.55336 | [
"MIT"
] | Bidrizi/Discrimination | Assets/Animation/polyperfect/Common/Common_AnimSpeed.cs | 508 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.ResourceManager.Compute.Models
{
public partial class VirtualMachineUpdate : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (Optional.IsDefined(Plan))
{
writer.WritePropertyName("plan");
writer.WriteObjectValue(Plan);
}
if (Optional.IsDefined(Identity))
{
writer.WritePropertyName("identity");
JsonSerializer.Serialize(writer, Identity);
}
if (Optional.IsCollectionDefined(Zones))
{
writer.WritePropertyName("zones");
writer.WriteStartArray();
foreach (var item in Zones)
{
writer.WriteStringValue(item);
}
writer.WriteEndArray();
}
if (Optional.IsCollectionDefined(Tags))
{
writer.WritePropertyName("tags");
writer.WriteStartObject();
foreach (var item in Tags)
{
writer.WritePropertyName(item.Key);
writer.WriteStringValue(item.Value);
}
writer.WriteEndObject();
}
writer.WritePropertyName("properties");
writer.WriteStartObject();
if (Optional.IsDefined(HardwareProfile))
{
writer.WritePropertyName("hardwareProfile");
writer.WriteObjectValue(HardwareProfile);
}
if (Optional.IsDefined(StorageProfile))
{
writer.WritePropertyName("storageProfile");
writer.WriteObjectValue(StorageProfile);
}
if (Optional.IsDefined(AdditionalCapabilities))
{
writer.WritePropertyName("additionalCapabilities");
writer.WriteObjectValue(AdditionalCapabilities);
}
if (Optional.IsDefined(OsProfile))
{
writer.WritePropertyName("osProfile");
writer.WriteObjectValue(OsProfile);
}
if (Optional.IsDefined(NetworkProfile))
{
writer.WritePropertyName("networkProfile");
writer.WriteObjectValue(NetworkProfile);
}
if (Optional.IsDefined(SecurityProfile))
{
writer.WritePropertyName("securityProfile");
writer.WriteObjectValue(SecurityProfile);
}
if (Optional.IsDefined(DiagnosticsProfile))
{
writer.WritePropertyName("diagnosticsProfile");
writer.WriteObjectValue(DiagnosticsProfile);
}
if (Optional.IsDefined(AvailabilitySet))
{
writer.WritePropertyName("availabilitySet");
JsonSerializer.Serialize(writer, AvailabilitySet);
}
if (Optional.IsDefined(VirtualMachineScaleSet))
{
writer.WritePropertyName("virtualMachineScaleSet");
JsonSerializer.Serialize(writer, VirtualMachineScaleSet);
}
if (Optional.IsDefined(ProximityPlacementGroup))
{
writer.WritePropertyName("proximityPlacementGroup");
JsonSerializer.Serialize(writer, ProximityPlacementGroup);
}
if (Optional.IsDefined(Priority))
{
writer.WritePropertyName("priority");
writer.WriteStringValue(Priority.Value.ToString());
}
if (Optional.IsDefined(EvictionPolicy))
{
writer.WritePropertyName("evictionPolicy");
writer.WriteStringValue(EvictionPolicy.Value.ToString());
}
if (Optional.IsDefined(BillingProfile))
{
writer.WritePropertyName("billingProfile");
writer.WriteObjectValue(BillingProfile);
}
if (Optional.IsDefined(Host))
{
writer.WritePropertyName("host");
JsonSerializer.Serialize(writer, Host);
}
if (Optional.IsDefined(HostGroup))
{
writer.WritePropertyName("hostGroup");
JsonSerializer.Serialize(writer, HostGroup);
}
if (Optional.IsDefined(LicenseType))
{
writer.WritePropertyName("licenseType");
writer.WriteStringValue(LicenseType);
}
if (Optional.IsDefined(ExtensionsTimeBudget))
{
writer.WritePropertyName("extensionsTimeBudget");
writer.WriteStringValue(ExtensionsTimeBudget);
}
if (Optional.IsDefined(PlatformFaultDomain))
{
writer.WritePropertyName("platformFaultDomain");
writer.WriteNumberValue(PlatformFaultDomain.Value);
}
if (Optional.IsDefined(ScheduledEventsProfile))
{
writer.WritePropertyName("scheduledEventsProfile");
writer.WriteObjectValue(ScheduledEventsProfile);
}
if (Optional.IsDefined(UserData))
{
writer.WritePropertyName("userData");
writer.WriteStringValue(UserData);
}
if (Optional.IsDefined(CapacityReservation))
{
writer.WritePropertyName("capacityReservation");
writer.WriteObjectValue(CapacityReservation);
}
if (Optional.IsDefined(ApplicationProfile))
{
writer.WritePropertyName("applicationProfile");
writer.WriteObjectValue(ApplicationProfile);
}
writer.WriteEndObject();
writer.WriteEndObject();
}
}
}
| 37.361446 | 74 | 0.544663 | [
"MIT"
] | BaherAbdullah/azure-sdk-for-net | sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/VirtualMachineUpdate.Serialization.cs | 6,202 | C# |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Cassandra.Collections;
using Cassandra.Connections;
using Cassandra.Connections.Control;
using Cassandra.MetadataHelpers;
using Cassandra.Requests;
using Cassandra.Tasks;
namespace Cassandra
{
/// <summary>
/// Keeps metadata on the connected cluster, including known nodes and schema
/// definitions.
/// </summary>
public class Metadata : IDisposable
{
private const string SelectSchemaVersionPeers = "SELECT schema_version FROM system.peers";
private const string SelectSchemaVersionLocal = "SELECT schema_version FROM system.local";
private static readonly Logger Logger = new Logger(typeof(ControlConnection));
private volatile TokenMap _tokenMap;
private volatile ConcurrentDictionary<string, KeyspaceMetadata> _keyspaces = new ConcurrentDictionary<string, KeyspaceMetadata>();
private volatile ISchemaParser _schemaParser;
private readonly int _queryAbortTimeout;
private volatile CopyOnWriteDictionary<IContactPoint, IEnumerable<IConnectionEndPoint>> _resolvedContactPoints =
new CopyOnWriteDictionary<IContactPoint, IEnumerable<IConnectionEndPoint>>();
public event HostsEventHandler HostsEvent;
public event SchemaChangedEventHandler SchemaChangedEvent;
/// <summary>
/// Returns the name of currently connected cluster.
/// </summary>
/// <returns>the Cassandra name of currently connected cluster.</returns>
public String ClusterName { get; internal set; }
/// <summary>
/// Determines whether the cluster is provided as a service (DataStax Astra).
/// </summary>
public bool IsDbaas { get; private set; } = false;
/// <summary>
/// Gets the configuration associated with this instance.
/// </summary>
internal Configuration Configuration { get; private set; }
/// <summary>
/// Control connection to be used to execute the queries to retrieve the metadata
/// </summary>
internal IControlConnection ControlConnection { get; set; }
internal ISchemaParser SchemaParser { get { return _schemaParser; } }
internal string Partitioner { get; set; }
internal Hosts Hosts { get; private set; }
internal IReadOnlyDictionary<IContactPoint, IEnumerable<IConnectionEndPoint>> ResolvedContactPoints => _resolvedContactPoints;
internal IReadOnlyTokenMap TokenToReplicasMap => _tokenMap;
internal Metadata(Configuration configuration)
{
_queryAbortTimeout = configuration.DefaultRequestOptions.QueryAbortTimeout;
Configuration = configuration;
Hosts = new Hosts();
Hosts.Down += OnHostDown;
Hosts.Up += OnHostUp;
}
internal Metadata(Configuration configuration, SchemaParser schemaParser) : this(configuration)
{
_schemaParser = schemaParser;
}
public void Dispose()
{
ShutDown();
}
internal KeyspaceMetadata GetKeyspaceFromCache(string keyspace)
{
_keyspaces.TryGetValue(keyspace, out var ks);
return ks;
}
internal void SetResolvedContactPoints(IDictionary<IContactPoint, IEnumerable<IConnectionEndPoint>> resolvedContactPoints)
{
_resolvedContactPoints = new CopyOnWriteDictionary<IContactPoint, IEnumerable<IConnectionEndPoint>>(resolvedContactPoints);
}
public Host GetHost(IPEndPoint address)
{
if (Hosts.TryGet(address, out var host))
return host;
return null;
}
internal Host AddHost(IPEndPoint address)
{
return Hosts.Add(address);
}
internal Host AddHost(IPEndPoint address, IContactPoint contactPoint)
{
return Hosts.Add(address, contactPoint);
}
internal void RemoveHost(IPEndPoint address)
{
Hosts.RemoveIfExists(address);
}
internal void FireSchemaChangedEvent(SchemaChangedEventArgs.Kind what, string keyspace, string table, object sender = null)
{
SchemaChangedEvent?.Invoke(sender ?? this, new SchemaChangedEventArgs { Keyspace = keyspace, What = what, Table = table });
}
private void OnHostDown(Host h)
{
HostsEvent?.Invoke(this, new HostsEventArgs { Address = h.Address, What = HostsEventArgs.Kind.Down });
}
private void OnHostUp(Host h)
{
HostsEvent?.Invoke(h, new HostsEventArgs { Address = h.Address, What = HostsEventArgs.Kind.Up });
}
/// <summary>
/// Returns all known hosts of this cluster.
/// </summary>
/// <returns>collection of all known hosts of this cluster.</returns>
public ICollection<Host> AllHosts()
{
return Hosts.ToCollection();
}
public IEnumerable<IPEndPoint> AllReplicas()
{
return Hosts.AllEndPointsToCollection();
}
// for tests
internal KeyValuePair<string, KeyspaceMetadata>[] KeyspacesSnapshot => _keyspaces.ToArray();
internal async Task RebuildTokenMapAsync(bool retry, bool fetchKeyspaces)
{
IEnumerable<KeyspaceMetadata> ksList = null;
if (fetchKeyspaces)
{
Metadata.Logger.Info("Retrieving keyspaces metadata");
ksList = await _schemaParser.GetKeyspacesAsync(retry).ConfigureAwait(false);
}
ConcurrentDictionary<string, KeyspaceMetadata> keyspaces;
if (ksList != null)
{
Metadata.Logger.Info("Updating keyspaces metadata");
var ksMap = ksList.Select(ks => new KeyValuePair<string, KeyspaceMetadata>(ks.Name, ks));
keyspaces = new ConcurrentDictionary<string, KeyspaceMetadata>(ksMap);
}
else
{
keyspaces = _keyspaces;
}
Metadata.Logger.Info("Rebuilding token map");
if (Partitioner == null)
{
throw new DriverInternalError("Partitioner can not be null");
}
var tokenMap = TokenMap.Build(Partitioner, Hosts.ToCollection(), keyspaces.Values);
_keyspaces = keyspaces;
_tokenMap = tokenMap;
}
/// <summary>
/// this method should be called by the event debouncer
/// </summary>
internal bool RemoveKeyspaceFromTokenMap(string name)
{
Metadata.Logger.Verbose("Removing keyspace metadata: " + name);
var dropped = _keyspaces.TryRemove(name, out _);
_tokenMap?.RemoveKeyspace(name);
return dropped;
}
internal async Task<KeyspaceMetadata> UpdateTokenMapForKeyspace(string name)
{
var keyspaceMetadata = await _schemaParser.GetKeyspaceAsync(name).ConfigureAwait(false);
var dropped = false;
var updated = false;
if (_tokenMap == null)
{
await RebuildTokenMapAsync(false, false).ConfigureAwait(false);
}
if (keyspaceMetadata == null)
{
Metadata.Logger.Verbose("Removing keyspace metadata: " + name);
dropped = _keyspaces.TryRemove(name, out _);
_tokenMap?.RemoveKeyspace(name);
}
else
{
Metadata.Logger.Verbose("Updating keyspace metadata: " + name);
_keyspaces.AddOrUpdate(keyspaceMetadata.Name, keyspaceMetadata, (k, v) =>
{
updated = true;
return keyspaceMetadata;
});
Metadata.Logger.Info("Rebuilding token map for keyspace {0}", keyspaceMetadata.Name);
if (Partitioner == null)
{
throw new DriverInternalError("Partitioner can not be null");
}
_tokenMap.UpdateKeyspace(keyspaceMetadata);
}
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
if (dropped)
{
FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Dropped, name, null, this);
}
else if (updated)
{
FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Updated, name, null, this);
}
else
{
FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Created, name, null, this);
}
}
return keyspaceMetadata;
}
/// <summary>
/// Get the replicas for a given partition key and keyspace
/// </summary>
public ICollection<Host> GetReplicas(string keyspaceName, byte[] partitionKey)
{
if (_tokenMap == null)
{
Metadata.Logger.Warning("Metadata.GetReplicas was called but there was no token map.");
return new Host[0];
}
return _tokenMap.GetReplicas(keyspaceName, _tokenMap.Factory.Hash(partitionKey));
}
public ICollection<Host> GetReplicas(byte[] partitionKey)
{
return GetReplicas(null, partitionKey);
}
/// <summary>
/// Returns metadata of specified keyspace.
/// </summary>
/// <param name="keyspace"> the name of the keyspace for which metadata should be
/// returned. </param>
/// <returns>the metadata of the requested keyspace or <c>null</c> if
/// <c>* keyspace</c> is not a known keyspace.</returns>
public KeyspaceMetadata GetKeyspace(string keyspace)
{
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
//Use local cache
_keyspaces.TryGetValue(keyspace, out var ksInfo);
return ksInfo;
}
return TaskHelper.WaitToComplete(SchemaParser.GetKeyspaceAsync(keyspace), _queryAbortTimeout);
}
/// <summary>
/// Returns a collection of all defined keyspaces names.
/// </summary>
/// <returns>a collection of all defined keyspaces names.</returns>
public ICollection<string> GetKeyspaces()
{
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
//Use local cache
return _keyspaces.Keys;
}
return TaskHelper.WaitToComplete(SchemaParser.GetKeyspacesNamesAsync(), _queryAbortTimeout);
}
/// <summary>
/// Returns names of all tables which are defined within specified keyspace.
/// </summary>
/// <param name="keyspace">the name of the keyspace for which all tables metadata should be
/// returned.</param>
/// <returns>an ICollection of the metadata for the tables defined in this
/// keyspace.</returns>
public ICollection<string> GetTables(string keyspace)
{
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
return !_keyspaces.TryGetValue(keyspace, out var ksMetadata)
? new string[0]
: ksMetadata.GetTablesNames();
}
return TaskHelper.WaitToComplete(SchemaParser.GetTableNamesAsync(keyspace), _queryAbortTimeout);
}
/// <summary>
/// Returns TableMetadata for specified table in specified keyspace.
/// </summary>
/// <param name="keyspace">name of the keyspace within specified table is defined.</param>
/// <param name="tableName">name of table for which metadata should be returned.</param>
/// <returns>a TableMetadata for the specified table in the specified keyspace.</returns>
public TableMetadata GetTable(string keyspace, string tableName)
{
return TaskHelper.WaitToComplete(GetTableAsync(keyspace, tableName), _queryAbortTimeout * 2);
}
internal Task<TableMetadata> GetTableAsync(string keyspace, string tableName)
{
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
return !_keyspaces.TryGetValue(keyspace, out var ksMetadata)
? Task.FromResult<TableMetadata>(null)
: ksMetadata.GetTableMetadataAsync(tableName);
}
return SchemaParser.GetTableAsync(keyspace, tableName);
}
/// <summary>
/// Returns the view metadata for the provided view name in the keyspace.
/// </summary>
/// <param name="keyspace">name of the keyspace within specified view is defined.</param>
/// <param name="name">name of view.</param>
/// <returns>a MaterializedViewMetadata for the view in the specified keyspace.</returns>
public MaterializedViewMetadata GetMaterializedView(string keyspace, string name)
{
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
return !_keyspaces.TryGetValue(keyspace, out var ksMetadata)
? null
: ksMetadata.GetMaterializedViewMetadata(name);
}
return TaskHelper.WaitToComplete(SchemaParser.GetViewAsync(keyspace, name), _queryAbortTimeout * 2);
}
/// <summary>
/// Gets the definition associated with a User Defined Type from Cassandra
/// </summary>
public UdtColumnInfo GetUdtDefinition(string keyspace, string typeName)
{
return TaskHelper.WaitToComplete(GetUdtDefinitionAsync(keyspace, typeName), _queryAbortTimeout);
}
/// <summary>
/// Gets the definition associated with a User Defined Type from Cassandra
/// </summary>
public Task<UdtColumnInfo> GetUdtDefinitionAsync(string keyspace, string typeName)
{
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
return !_keyspaces.TryGetValue(keyspace, out var ksMetadata)
? Task.FromResult<UdtColumnInfo>(null)
: ksMetadata.GetUdtDefinitionAsync(typeName);
}
return SchemaParser.GetUdtDefinitionAsync(keyspace, typeName);
}
/// <summary>
/// Gets the definition associated with a User Defined Function from Cassandra
/// </summary>
/// <returns>The function metadata or null if not found.</returns>
public FunctionMetadata GetFunction(string keyspace, string name, string[] signature)
{
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
return !_keyspaces.TryGetValue(keyspace, out var ksMetadata)
? null
: ksMetadata.GetFunction(name, signature);
}
var signatureString = SchemaParser.ComputeFunctionSignatureString(signature);
return TaskHelper.WaitToComplete(SchemaParser.GetFunctionAsync(keyspace, name, signatureString), _queryAbortTimeout);
}
/// <summary>
/// Gets the definition associated with a aggregate from Cassandra
/// </summary>
/// <returns>The aggregate metadata or null if not found.</returns>
public AggregateMetadata GetAggregate(string keyspace, string name, string[] signature)
{
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
return !_keyspaces.TryGetValue(keyspace, out var ksMetadata)
? null
: ksMetadata.GetAggregate(name, signature);
}
var signatureString = SchemaParser.ComputeFunctionSignatureString(signature);
return TaskHelper.WaitToComplete(SchemaParser.GetAggregateAsync(keyspace, name, signatureString), _queryAbortTimeout);
}
/// <summary>
/// Gets the query trace.
/// </summary>
/// <param name="trace">The query trace that contains the id, which properties are going to be populated.</param>
/// <returns></returns>
internal Task<QueryTrace> GetQueryTraceAsync(QueryTrace trace)
{
return _schemaParser.GetQueryTraceAsync(trace, Configuration.Timer);
}
/// <summary>
/// Updates the keyspace and token information
/// </summary>
public bool RefreshSchema(string keyspace = null, string table = null)
{
return TaskHelper.WaitToComplete(RefreshSchemaAsync(keyspace, table), Configuration.DefaultRequestOptions.QueryAbortTimeout * 2);
}
/// <summary>
/// Updates the keyspace and token information
/// </summary>
public async Task<bool> RefreshSchemaAsync(string keyspace = null, string table = null)
{
if (keyspace == null)
{
await ControlConnection.ScheduleAllKeyspacesRefreshAsync(true).ConfigureAwait(false);
return true;
}
await ControlConnection.ScheduleKeyspaceRefreshAsync(keyspace, true).ConfigureAwait(false);
_keyspaces.TryGetValue(keyspace, out var ks);
if (ks == null)
{
return false;
}
if (table != null)
{
ks.ClearTableMetadata(table);
}
return true;
}
public void ShutDown(int timeoutMs = Timeout.Infinite)
{
//it is really not required to be called, left as it is part of the public API
//dereference the control connection
ControlConnection = null;
}
/// <summary>
/// this method should be called by the event debouncer
/// </summary>
internal bool RemoveKeyspace(string name)
{
var existed = RemoveKeyspaceFromTokenMap(name);
if (!existed)
{
return false;
}
FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Dropped, name, null, this);
return true;
}
/// <summary>
/// this method should be called by the event debouncer
/// </summary>
internal Task<KeyspaceMetadata> RefreshSingleKeyspace(string name)
{
return UpdateTokenMapForKeyspace(name);
}
internal void ClearTable(string keyspaceName, string tableName)
{
if (_keyspaces.TryGetValue(keyspaceName, out var ksMetadata))
{
ksMetadata.ClearTableMetadata(tableName);
}
}
internal void ClearView(string keyspaceName, string name)
{
if (_keyspaces.TryGetValue(keyspaceName, out var ksMetadata))
{
ksMetadata.ClearViewMetadata(name);
}
}
internal void ClearFunction(string keyspaceName, string functionName, string[] signature)
{
if (_keyspaces.TryGetValue(keyspaceName, out var ksMetadata))
{
ksMetadata.ClearFunction(functionName, signature);
}
}
internal void ClearAggregate(string keyspaceName, string aggregateName, string[] signature)
{
if (_keyspaces.TryGetValue(keyspaceName, out var ksMetadata))
{
ksMetadata.ClearAggregate(aggregateName, signature);
}
}
/// <summary>
/// Initiates a schema agreement check.
/// <para/>
/// Schema changes need to be propagated to all nodes in the cluster.
/// Once they have settled on a common version, we say that they are in agreement.
/// <para/>
/// This method does not perform retries so
/// <see cref="ProtocolOptions.MaxSchemaAgreementWaitSeconds"/> does not apply.
/// </summary>
/// <returns>True if schema agreement was successful and false if it was not successful.</returns>
public async Task<bool> CheckSchemaAgreementAsync()
{
if (Hosts.Count == 1)
{
// If there is just one node, the schema is up to date in all nodes :)
return true;
}
try
{
var queries = new[]
{
ControlConnection.QueryAsync(SelectSchemaVersionLocal),
ControlConnection.QueryAsync(SelectSchemaVersionPeers)
};
await Task.WhenAll(queries).ConfigureAwait(false);
return CheckSchemaVersionResults(queries[0].Result, queries[1].Result);
}
catch (Exception ex)
{
Logger.Error("Error while checking schema agreement.", ex);
}
return false;
}
/// <summary>
/// Checks if there is only one schema version between the provided query results.
/// </summary>
/// <param name="localVersionQuery">
/// Results obtained from a query to <code>system.local</code> table.
/// Must contain the <code>schema_version</code> column.
/// </param>
/// <param name="peerVersionsQuery">
/// Results obtained from a query to <code>system.peers</code> table.
/// Must contain the <code>schema_version</code> column.
/// </param>
/// <returns><code>True</code> if there is a schema agreement (only 1 schema version). <code>False</code> otherwise.</returns>
private static bool CheckSchemaVersionResults(
IEnumerable<IRow> localVersionQuery, IEnumerable<IRow> peerVersionsQuery)
{
return new HashSet<Guid>(
peerVersionsQuery
.Concat(localVersionQuery)
.Select(r => r.GetValue<Guid>("schema_version"))).Count == 1;
}
/// <summary>
/// Waits until that the schema version in all nodes is the same or the waiting time passed.
/// This method blocks the calling thread.
/// </summary>
internal bool WaitForSchemaAgreement(IConnection connection)
{
if (Hosts.Count == 1)
{
//If there is just one node, the schema is up to date in all nodes :)
return true;
}
var start = DateTime.Now;
var waitSeconds = Configuration.ProtocolOptions.MaxSchemaAgreementWaitSeconds;
Metadata.Logger.Info("Waiting for schema agreement");
try
{
var totalVersions = 0;
while (DateTime.Now.Subtract(start).TotalSeconds < waitSeconds)
{
var serializer = ControlConnection.Serializer.GetCurrentSerializer();
var schemaVersionLocalQuery =
new QueryRequest(
serializer,
Metadata.SelectSchemaVersionLocal,
QueryProtocolOptions.Default,
false,
null);
var schemaVersionPeersQuery =
new QueryRequest(
serializer,
Metadata.SelectSchemaVersionPeers,
QueryProtocolOptions.Default,
false,
null);
var queries = new[] { connection.Send(schemaVersionLocalQuery), connection.Send(schemaVersionPeersQuery) };
// ReSharper disable once CoVariantArrayConversion
Task.WaitAll(queries, Configuration.DefaultRequestOptions.QueryAbortTimeout);
if (Metadata.CheckSchemaVersionResults(
Configuration.MetadataRequestHandler.GetRowSet(queries[0].Result),
Configuration.MetadataRequestHandler.GetRowSet(queries[1].Result)))
{
return true;
}
Thread.Sleep(500);
}
Metadata.Logger.Info($"Waited for schema agreement, still {totalVersions} schema versions in the cluster.");
}
catch (Exception ex)
{
//Exceptions are not fatal
Metadata.Logger.Error("There was an exception while trying to retrieve schema versions", ex);
}
return false;
}
/// <summary>
/// Sets the Cassandra version in order to identify how to parse the metadata information
/// </summary>
/// <param name="version"></param>
internal void SetCassandraVersion(Version version)
{
_schemaParser = Configuration.SchemaParserFactory.Create(version, this, GetUdtDefinitionAsync, _schemaParser);
}
internal void SetProductTypeAsDbaas()
{
IsDbaas = true;
}
internal IEnumerable<IConnectionEndPoint> UpdateResolvedContactPoint(IContactPoint contactPoint, IEnumerable<IConnectionEndPoint> endpoints)
{
return _resolvedContactPoints.AddOrUpdate(contactPoint, _ => endpoints, (_, __) => endpoints);
}
}
} | 39.152819 | 148 | 0.592595 | [
"Apache-2.0"
] | CassOnMars/csharp-driver | src/Cassandra/Metadata.cs | 26,389 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Vod.V20180717.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class TEHDConfig : AbstractModel
{
/// <summary>
/// TESHD type. Valid values:
/// <li>TEHD-100: TESHD-100.</li>
/// If this parameter is left blank, TESHD will not be enabled.
/// </summary>
[JsonProperty("Type")]
public string Type{ get; set; }
/// <summary>
/// Maximum bitrate, which is valid when `Type` is `TESHD`.
/// If this parameter is left blank or 0 is entered, there will be no upper limit for bitrate.
/// </summary>
[JsonProperty("MaxVideoBitrate")]
public ulong? MaxVideoBitrate{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "Type", this.Type);
this.SetParamSimple(map, prefix + "MaxVideoBitrate", this.MaxVideoBitrate);
}
}
}
| 33.203704 | 102 | 0.639152 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet-intl-en | TencentCloud/Vod/V20180717/Models/TEHDConfig.cs | 1,793 | C# |
using System;
using Newtonsoft.Json;
namespace Patreon.Net.Models
{
/// <summary>
/// An OAuth2 token used for authentication with the Patreon API.
/// </summary>
public class OAuthToken
{
/// <summary>
/// The access token. Use this in construction of a new <see cref="PatreonClient"/> in the future.
/// </summary>
[JsonProperty("access_token")]
public string AccessToken { get; set; }
/// <summary>
/// The time in seconds in which this token will expire. Use this to calculate a <see cref="DateTimeOffset"/> for construction of a new <see cref="PatreonClient"/> in the future.
/// </summary>
[JsonProperty("expires_in")]
public long ExpiresIn { get; set; }
/// <summary>
/// The type of this token.
/// </summary>
[JsonProperty("token_type")]
public string TokenType { get; set; }
/// <summary>
/// The scope of this token.
/// </summary>
[JsonProperty("scope")]
public string Scope { get; set; }
/// <summary>
/// The refresh token. Use this in construction of a new <see cref="PatreonClient"/> in the future.
/// </summary>
[JsonProperty("refresh_token")]
public string RefreshToken { get; set; }
/// <summary>
/// The version of this token.
/// </summary>
[JsonProperty("version")]
public string Version { get; set; }
}
}
| 34.767442 | 186 | 0.568562 | [
"MIT"
] | sawch/Patreon.Net | src/Patreon.Net/Models/OAuthToken.cs | 1,497 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneTransition : MonoBehaviour
{
public void GoToScene(string scene)
{
SceneManager.LoadScene(scene);
}
}
| 19.615385 | 44 | 0.756863 | [
"MIT"
] | IlchKhailtuud/GAME3011_A1 | Assets/Scripts/SceneTransition.cs | 255 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class CrouchLowGravityEvents : LocomotionGroundEvents
{
public CrouchLowGravityEvents(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 22.2 | 109 | 0.741742 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/CrouchLowGravityEvents.cs | 319 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CVGS.Models;
using CVGS.ViewModels;
namespace CVGS.Controllers
{
public class EventsController : Controller
{
private CVGSEntities db = new CVGSEntities();
// GET: Events
public ActionResult Index(string sort, string order)
{
// Redirect unauthenticated members
var memberId = this.Session["MemberId"];
if (memberId == null)
{
return RedirectToAction("Index", "Login"); ;
}
// Display all events in a sorted list
var eventList = db.EVENTs.ToList();
bool asc = true;
ViewBag.listSortAsc = "asc";
if (order != null && order.Equals("asc"))
{
ViewBag.listSortAsc = "desc";
asc = true;
}
else if(order != null && order.Equals("desc"))
{
ViewBag.listSortAsc = "asc";
asc = false;
}
if (sort == null) return View(EventAssociationsViewModel.CreateEventAssociationsListFromModels(eventList, (int)memberId));
// Events can be sorted by several model properties
switch (sort)
{
case "title":
eventList = asc
? eventList.OrderBy(e => e.EventTitle).ToList()
: eventList.OrderByDescending(e => e.EventTitle).ToList();
break;
case "location":
eventList = asc
? eventList.OrderBy(e => e.Location).ToList()
: eventList.OrderByDescending(e => e.Location).ToList();
break;
case "date":
eventList = asc
? eventList.OrderBy(e => e.EventDate).ToList()
: eventList.OrderByDescending(e => e.EventDate).ToList();
break;
}
return View(EventAssociationsViewModel.CreateEventAssociationsListFromModels(eventList, (int)memberId));
}
// GET: Events/Details/5
public ActionResult Details(int? id)
{
// Redirect unauthenticated members
var memberId = this.Session["MemberId"];
if (memberId == null)
{
return RedirectToAction("Index", "Login"); ;
}
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// Find and display event details
EVENT @event = db.EVENTs.Find(id);
if (@event == null)
{
return HttpNotFound();
}
// Create extended view model with basic associations
EventAssociationsViewModel eventWithAssociations = EventAssociationsViewModel.CreateEventAssociationsFromModel(@event, (int)memberId);
return View(eventWithAssociations);
}
// GET: Events/Create
public ActionResult Create()
{
// Redirect unauthenticated members
var memberId = this.Session["MemberId"];
if (memberId == null)
{
return RedirectToAction("Index", "Login"); ;
}
// Only admins and employees can manage events
string memberRole = this.Session["MemberRole"].ToString();
if (memberRole != "Admin" && memberRole != "Employee")
{
return new HttpUnauthorizedResult("You are not authorized to manage Events");
}
return View();
}
// POST: Events/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "EventId,EventTitle,Description,EventDate,Location,ActiveStatus,DateCreated")] EVENT @event)
{
// Redirect unauthenticated members
var memberId = this.Session["MemberId"];
if (memberId == null)
{
return RedirectToAction("Index", "Login"); ;
}
// Only admins and employees can manage events
string memberRole = this.Session["MemberRole"].ToString();
if (memberRole != "Admin" && memberRole != "Employee")
{
return new HttpUnauthorizedResult("You are not authorized to manage Events");
}
// Validate and add event
if (!ModelState.IsValid)
{
return View(@event);
}
db.EVENTs.Add(@event);
db.SaveChanges();
return RedirectToAction("Index");
}
// GET: Events/Edit/5
public ActionResult Edit(int? id)
{
// Redirect unauthenticated members
var memberId = this.Session["MemberId"];
if (memberId == null)
{
return RedirectToAction("Index", "Login"); ;
}
// Only admins and employees can manage events
string memberRole = this.Session["MemberRole"].ToString();
if (memberRole != "Admin" && memberRole != "Employee")
{
return new HttpUnauthorizedResult("You are not authorized to manage Events");
}
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// Find and display event for editing
EVENT @event = db.EVENTs.Find(id);
if (@event == null)
{
return HttpNotFound();
}
return View(@event);
}
// POST: Events/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "EventId,EventTitle,Description,EventDate,Location,ActiveStatus,DateCreated")] EVENT @event)
{
// Redirect unauthenticated members
var memberId = this.Session["MemberId"];
if (memberId == null)
{
return RedirectToAction("Index", "Login"); ;
}
// Only admins and employees can manage events
string memberRole = this.Session["MemberRole"].ToString();
if (memberRole != "Admin" && memberRole != "Employee")
{
return new HttpUnauthorizedResult("You are not authorized to manage Events");
}
// Validate and update event
if (!ModelState.IsValid)
{
return View(@event);
}
db.Entry(@event).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details", new { id = @event.EventId });
}
// GET: Events/Delete/5
public ActionResult Delete(int? id)
{
// Redirect unauthenticated members
var memberId = this.Session["MemberId"];
if (memberId == null)
{
return RedirectToAction("Index", "Login"); ;
}
// Only admins and employees can manage events
string memberRole = this.Session["MemberRole"].ToString();
if (memberRole != "Admin" && memberRole != "Employee")
{
return new HttpUnauthorizedResult("You are not authorized to manage Events");
}
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// Find and display event details for deletion confirmation
EVENT @event = db.EVENTs.Find(id);
if (@event == null)
{
return HttpNotFound();
}
return View(@event);
}
// POST: Events/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
// Redirect unauthenticated members
var memberId = this.Session["MemberId"];
if (memberId == null)
{
return RedirectToAction("Index", "Login"); ;
}
// Only admins and employees can manage events
string memberRole = this.Session["MemberRole"].ToString();
if (memberRole != "Admin" && memberRole != "Employee")
{
return new HttpUnauthorizedResult("You are not authorized to manage Events");
}
// Remove event and display list of events
EVENT @event = db.EVENTs.Find(id);
if (@event == null)
{
return HttpNotFound();
}
db.EVENTs.Remove(@event);
db.SaveChanges();
return RedirectToAction("Index");
}
// POST: Events/Register/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(int id, string isRegistered)
{
// Redirect unauthenticated members
var memberId = this.Session["MemberId"];
if (memberId == null)
{
return RedirectToAction("Index", "Login"); ;
}
// Validate and update member/event registration
if (!ModelState.IsValid) return RedirectToAction("Details", new {id = id});
// Find the event
EVENT @event = db.EVENTs.ToList().Find(x => x.EventId == id);
// Cancelled events cannot be registered/unregistered while unactive
if (@event == null)
{
return HttpNotFound();
}
else if (@event.ActiveStatus == false)
{
return RedirectToAction("Details", new { id = id });
}
// Remove registration if it exists
if (isRegistered == "true")
{
MEMBER_EVENT memberEvent = db.MEMBER_EVENT.ToList().Find(x => x.EventId == id && x.MemberId == (int)memberId);
if (memberEvent == null)
{
return HttpNotFound();
}
db.MEMBER_EVENT.Remove(memberEvent);
db.SaveChanges();
return RedirectToAction("Details", new { id = id });
}
// Create new member/event registration
MEMBER_EVENT memberRegister = new MEMBER_EVENT();
memberRegister.EventId = id;
memberRegister.MemberId = (int)this.Session["MemberId"];
memberRegister.DateRegistered = System.DateTime.Now;
if (memberRegister.ToString() != "")
{
try
{
db.MEMBER_EVENT.Add(memberRegister);
db.SaveChanges();
}
catch (Exception)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest); // sad path
}
}
return RedirectToAction("Details", new { id = id });
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
| 33.437681 | 146 | 0.509622 | [
"MIT"
] | 4-of-3/cvgs | CVGS/Controllers/EventsController.cs | 11,538 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the pinpoint-2016-12-01.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.Pinpoint.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Pinpoint.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for EndpointMessageResult Object
/// </summary>
public class EndpointMessageResultUnmarshaller : IUnmarshaller<EndpointMessageResult, XmlUnmarshallerContext>, IUnmarshaller<EndpointMessageResult, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
EndpointMessageResult IUnmarshaller<EndpointMessageResult, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public EndpointMessageResult Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
EndpointMessageResult unmarshalledObject = new EndpointMessageResult();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("Address", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Address = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("DeliveryStatus", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.DeliveryStatus = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("MessageId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.MessageId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("StatusCode", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.StatusCode = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("StatusMessage", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.StatusMessage = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("UpdatedToken", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.UpdatedToken = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static EndpointMessageResultUnmarshaller _instance = new EndpointMessageResultUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static EndpointMessageResultUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.967213 | 176 | 0.608377 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/Pinpoint/Generated/Model/Internal/MarshallTransformations/EndpointMessageResultUnmarshaller.cs | 4,632 | 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.Latest.Inputs
{
/// <summary>
/// Presto server linked service.
/// </summary>
public sealed class PrestoLinkedServiceArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Specifies whether to require a CA-issued SSL certificate name to match the host name of the server when connecting over SSL. The default value is false.
/// </summary>
[Input("allowHostNameCNMismatch")]
public Input<object>? AllowHostNameCNMismatch { get; set; }
/// <summary>
/// Specifies whether to allow self-signed certificates from the server. The default value is false.
/// </summary>
[Input("allowSelfSignedServerCert")]
public Input<object>? AllowSelfSignedServerCert { get; set; }
[Input("annotations")]
private InputList<object>? _annotations;
/// <summary>
/// List of tags that can be used for describing the linked service.
/// </summary>
public InputList<object> Annotations
{
get => _annotations ?? (_annotations = new InputList<object>());
set => _annotations = value;
}
/// <summary>
/// The authentication mechanism used to connect to the Presto server.
/// </summary>
[Input("authenticationType", required: true)]
public InputUnion<string, Pulumi.AzureNative.DataFactory.Latest.PrestoAuthenticationType> AuthenticationType { get; set; } = null!;
/// <summary>
/// The catalog context for all request against the server.
/// </summary>
[Input("catalog", required: true)]
public Input<object> Catalog { get; set; } = null!;
/// <summary>
/// The integration runtime reference.
/// </summary>
[Input("connectVia")]
public Input<Inputs.IntegrationRuntimeReferenceArgs>? ConnectVia { get; set; }
/// <summary>
/// Linked service description.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// Specifies whether the connections to the server are encrypted using SSL. The default value is false.
/// </summary>
[Input("enableSsl")]
public Input<object>? EnableSsl { get; set; }
/// <summary>
/// The encrypted credential used for authentication. Credentials are encrypted using the integration runtime credential manager. Type: string (or Expression with resultType string).
/// </summary>
[Input("encryptedCredential")]
public Input<object>? EncryptedCredential { get; set; }
/// <summary>
/// The IP address or host name of the Presto server. (i.e. 192.168.222.160)
/// </summary>
[Input("host", required: true)]
public Input<object> Host { get; set; } = null!;
[Input("parameters")]
private InputMap<Inputs.ParameterSpecificationArgs>? _parameters;
/// <summary>
/// Parameters for linked service.
/// </summary>
public InputMap<Inputs.ParameterSpecificationArgs> Parameters
{
get => _parameters ?? (_parameters = new InputMap<Inputs.ParameterSpecificationArgs>());
set => _parameters = value;
}
/// <summary>
/// The password corresponding to the user name.
/// </summary>
[Input("password")]
public InputUnion<Inputs.AzureKeyVaultSecretReferenceArgs, Inputs.SecureStringArgs>? Password { get; set; }
/// <summary>
/// The TCP port that the Presto server uses to listen for client connections. The default value is 8080.
/// </summary>
[Input("port")]
public Input<object>? Port { get; set; }
/// <summary>
/// The version of the Presto server. (i.e. 0.148-t)
/// </summary>
[Input("serverVersion", required: true)]
public Input<object> ServerVersion { get; set; } = null!;
/// <summary>
/// The local time zone used by the connection. Valid values for this option are specified in the IANA Time Zone Database. The default value is the system time zone.
/// </summary>
[Input("timeZoneID")]
public Input<object>? TimeZoneID { get; set; }
/// <summary>
/// The full path of the .pem file containing trusted CA certificates for verifying the server when connecting over SSL. This property can only be set when using SSL on self-hosted IR. The default value is the cacerts.pem file installed with the IR.
/// </summary>
[Input("trustedCertPath")]
public Input<object>? TrustedCertPath { get; set; }
/// <summary>
/// Type of linked service.
/// Expected value is 'Presto'.
/// </summary>
[Input("type", required: true)]
public Input<string> Type { get; set; } = null!;
/// <summary>
/// Specifies whether to use a CA certificate from the system trust store or from a specified PEM file. The default value is false.
/// </summary>
[Input("useSystemTrustStore")]
public Input<object>? UseSystemTrustStore { get; set; }
/// <summary>
/// The user name used to connect to the Presto server.
/// </summary>
[Input("username")]
public Input<object>? Username { get; set; }
public PrestoLinkedServiceArgs()
{
}
}
}
| 38.766667 | 257 | 0.609114 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/DataFactory/Latest/Inputs/PrestoLinkedServiceArgs.cs | 5,815 | C# |
#region Copyright notice and license
// Copyright 2019 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using Grpc.Core;
using Grpc.Core.Interceptors;
using Grpc.Net.Client;
namespace Grpc.Net.ClientFactory
{
/// <summary>
/// Options used to configure a gRPC client.
/// </summary>
public class GrpcClientFactoryOptions
{
/// <summary>
/// The address to use when making gRPC calls.
/// </summary>
public Uri? Address { get; set; }
/// <summary>
/// Gets a list of operations used to configure a <see cref="GrpcChannelOptions"/>.
/// </summary>
public IList<Action<GrpcChannelOptions>> ChannelOptionsActions { get; } = new List<Action<GrpcChannelOptions>>();
/// <summary>
/// Gets a list of operations used to configure a <see cref="CallOptions"/>.
/// </summary>
public IList<Action<CallOptionsContext>> CallOptionsActions { get; } = new List<Action<CallOptionsContext>>();
/// <summary>
/// Gets a list of <see cref="Interceptor"/> instances used to configure a gRPC client pipeline.
/// </summary>
[Obsolete("Interceptors collection is obsolete and will be removed in a future release. Use InterceptorRegistrations collection instead.")]
public IList<Interceptor> Interceptors { get; } = new List<Interceptor>();
/// <summary>
/// Gets a list of <see cref="InterceptorRegistration"/> instances used to configure a gRPC client pipeline.
/// </summary>
public IList<InterceptorRegistration> InterceptorRegistrations { get; } = new List<InterceptorRegistration>();
/// <summary>
/// Gets or sets a delegate that will override how a client is created.
/// </summary>
public Func<CallInvoker, object>? Creator { get; set; }
internal bool HasCallCredentials { get; set; }
internal static CallInvoker BuildInterceptors(
CallInvoker callInvoker,
IServiceProvider serviceProvider,
GrpcClientFactoryOptions clientFactoryOptions,
InterceptorScope scope)
{
CallInvoker resolvedCallInvoker;
if (clientFactoryOptions.InterceptorRegistrations.Count == 0)
{
resolvedCallInvoker = callInvoker;
}
else
{
List<Interceptor>? channelInterceptors = null;
for (var i = 0; i < clientFactoryOptions.InterceptorRegistrations.Count; i++)
{
var registration = clientFactoryOptions.InterceptorRegistrations[i];
if (registration.Scope == scope)
{
channelInterceptors ??= new List<Interceptor>();
channelInterceptors.Add(registration.Creator(serviceProvider));
}
}
resolvedCallInvoker = channelInterceptors != null
? callInvoker.Intercept(channelInterceptors.ToArray())
: callInvoker;
}
return resolvedCallInvoker;
}
}
}
| 38.645833 | 147 | 0.621563 | [
"Apache-2.0"
] | ehtick/grpc-dotnet | src/Grpc.Net.ClientFactory/GrpcClientFactoryOptions.cs | 3,712 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Internals;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Net.Sockets
{
// The Sockets.Socket class implements the Berkeley sockets interface.
public partial class Socket : IDisposable
{
internal const int DefaultCloseTimeout = -1; // NOTE: changing this default is a breaking change.
private SafeSocketHandle _handle;
// _rightEndPoint is null if the socket has not been bound. Otherwise, it is any EndPoint of the
// correct type (IPEndPoint, etc).
internal EndPoint _rightEndPoint;
internal EndPoint _remoteEndPoint;
// These flags monitor if the socket was ever connected at any time and if it still is.
private bool _isConnected;
private bool _isDisconnected;
// When the socket is created it will be in blocking mode. We'll only be able to Accept or Connect,
// so we need to handle one of these cases at a time.
private bool _willBlock = true; // Desired state of the socket from the user.
private bool _willBlockInternal = true; // Actual win32 state of the socket.
private bool _isListening = false;
// Our internal state doesn't automatically get updated after a non-blocking connect
// completes. Keep track of whether we're doing a non-blocking connect, and make sure
// to poll for the real state until we're done connecting.
private bool _nonBlockingConnectInProgress;
// Keep track of the kind of endpoint used to do a non-blocking connect, so we can set
// it to _rightEndPoint when we discover we're connected.
private EndPoint _nonBlockingConnectRightEndPoint;
// These are constants initialized by constructor.
private AddressFamily _addressFamily;
private SocketType _socketType;
private ProtocolType _protocolType;
// These caches are one degree off of Socket since they're not used in the sync case/when disabled in config.
private CacheSet _caches;
private class CacheSet
{
internal CallbackClosure ConnectClosureCache;
internal CallbackClosure AcceptClosureCache;
internal CallbackClosure SendClosureCache;
internal CallbackClosure ReceiveClosureCache;
}
// Bool marked true if the native socket option IP_PKTINFO or IPV6_PKTINFO has been set.
private bool _receivingPacketInformation;
private static object s_internalSyncObject;
private int _closeTimeout = Socket.DefaultCloseTimeout;
private int _intCleanedUp; // 0 if not completed, > 0 otherwise.
internal static volatile bool s_initialized;
#region Constructors
public Socket(SocketType socketType, ProtocolType protocolType)
: this(OSSupportsIPv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, socketType, protocolType)
{
if (OSSupportsIPv6)
{
DualMode = true;
}
}
// Initializes a new instance of the Sockets.Socket class.
public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, addressFamily);
InitializeSockets();
SocketError errorCode = SocketPal.CreateSocket(addressFamily, socketType, protocolType, out _handle);
if (errorCode != SocketError.Success)
{
Debug.Assert(_handle.IsInvalid);
// Failed to create the socket, throw.
throw new SocketException((int)errorCode);
}
Debug.Assert(!_handle.IsInvalid);
_addressFamily = addressFamily;
_socketType = socketType;
_protocolType = protocolType;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
public Socket(SocketInformation socketInformation)
{
//
// This constructor works in conjunction with DuplicateAndClose, which is not supported.
// See comments in DuplicateAndClose.
//
throw new PlatformNotSupportedException(SR.net_sockets_duplicateandclose_notsupported);
}
// Called by the class to create a socket to accept an incoming request.
private Socket(SafeSocketHandle fd)
{
// NOTE: If this ctor is ever made public/protected, this check will need
// to be converted into a runtime exception.
Debug.Assert(fd != null && !fd.IsInvalid);
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
InitializeSockets();
_handle = fd;
_addressFamily = Sockets.AddressFamily.Unknown;
_socketType = Sockets.SocketType.Unknown;
_protocolType = Sockets.ProtocolType.Unknown;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
#endregion
#region Properties
// The CLR allows configuration of these properties, separately from whether the OS supports IPv4/6. We
// do not provide these config options, so SupportsIPvX === OSSupportsIPvX.
[Obsolete("SupportsIPv4 is obsoleted for this type, please use OSSupportsIPv4 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public static bool SupportsIPv4 => OSSupportsIPv4;
[Obsolete("SupportsIPv6 is obsoleted for this type, please use OSSupportsIPv6 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public static bool SupportsIPv6 => OSSupportsIPv6;
public static bool OSSupportsIPv4
{
get
{
InitializeSockets();
return SocketProtocolSupportPal.OSSupportsIPv4;
}
}
public static bool OSSupportsIPv6
{
get
{
InitializeSockets();
return SocketProtocolSupportPal.OSSupportsIPv6;
}
}
// Gets the amount of data pending in the network's input buffer that can be
// read from the socket.
public int Available
{
get
{
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
int argp;
// This may throw ObjectDisposedException.
SocketError errorCode = SocketPal.GetAvailable(_handle, out argp);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.ioctlsocket returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
return argp;
}
}
// Gets the local end point.
public EndPoint LocalEndPoint
{
get
{
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (_nonBlockingConnectInProgress && Poll(0, SelectMode.SelectWrite))
{
// Update the state if we've become connected after a non-blocking connect.
_isConnected = true;
_rightEndPoint = _nonBlockingConnectRightEndPoint;
_nonBlockingConnectInProgress = false;
}
if (_rightEndPoint == null)
{
return null;
}
Internals.SocketAddress socketAddress = IPEndPointExtensions.Serialize(_rightEndPoint);
// This may throw ObjectDisposedException.
SocketError errorCode = SocketPal.GetSockName(
_handle,
socketAddress.Buffer,
ref socketAddress.InternalSize);
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
return _rightEndPoint.Create(socketAddress);
}
}
// Gets the remote end point.
public EndPoint RemoteEndPoint
{
get
{
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (_remoteEndPoint == null)
{
if (_nonBlockingConnectInProgress && Poll(0, SelectMode.SelectWrite))
{
// Update the state if we've become connected after a non-blocking connect.
_isConnected = true;
_rightEndPoint = _nonBlockingConnectRightEndPoint;
_nonBlockingConnectInProgress = false;
}
if (_rightEndPoint == null)
{
return null;
}
Internals.SocketAddress socketAddress = IPEndPointExtensions.Serialize(_rightEndPoint);
// This may throw ObjectDisposedException.
SocketError errorCode = SocketPal.GetPeerName(
_handle,
socketAddress.Buffer,
ref socketAddress.InternalSize);
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
try
{
_remoteEndPoint = _rightEndPoint.Create(socketAddress);
}
catch
{
}
}
return _remoteEndPoint;
}
}
public IntPtr Handle
{
get
{
_handle.SetExposed();
return _handle.DangerousGetHandle();
}
}
public SafeSocketHandle SafeHandle
{
get
{
return _handle;
}
}
// Gets and sets the blocking mode of a socket.
public bool Blocking
{
get
{
// Return the user's desired blocking behaviour (not the actual win32 state).
return _willBlock;
}
set
{
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"value:{value} willBlock:{_willBlock} willBlockInternal:{_willBlockInternal}");
bool current;
SocketError errorCode = InternalSetBlocking(value, out current);
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
// The native call succeeded, update the user's desired state.
_willBlock = current;
}
}
public bool UseOnlyOverlappedIO
{
get
{
return false;
}
set
{
//
// This implementation does not support non-IOCP-based async I/O on Windows, and this concept is
// not even meaningful on other platforms. This option is really only functionally meaningful
// if the user calls DuplicateAndClose. Since we also don't support DuplicateAndClose,
// we can safely ignore the caller's choice here, rather than breaking compat further with something
// like PlatformNotSupportedException.
//
}
}
// Gets the connection state of the Socket. This property will return the latest
// known state of the Socket. When it returns false, the Socket was either never connected
// or it is not connected anymore. When it returns true, though, there's no guarantee that the Socket
// is still connected, but only that it was connected at the time of the last IO operation.
public bool Connected
{
get
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_isConnected:{_isConnected}");
if (_nonBlockingConnectInProgress && Poll(0, SelectMode.SelectWrite))
{
// Update the state if we've become connected after a non-blocking connect.
_isConnected = true;
_rightEndPoint = _nonBlockingConnectRightEndPoint;
_nonBlockingConnectInProgress = false;
}
return _isConnected;
}
}
// Gets the socket's address family.
public AddressFamily AddressFamily
{
get
{
return _addressFamily;
}
}
// Gets the socket's socketType.
public SocketType SocketType
{
get
{
return _socketType;
}
}
// Gets the socket's protocol socketType.
public ProtocolType ProtocolType
{
get
{
return _protocolType;
}
}
public bool IsBound
{
get
{
return (_rightEndPoint != null);
}
}
public bool ExclusiveAddressUse
{
get
{
return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse) != 0 ? true : false;
}
set
{
if (IsBound)
{
throw new InvalidOperationException(SR.net_sockets_mustnotbebound);
}
SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, value ? 1 : 0);
}
}
public int ReceiveBufferSize
{
get
{
return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer);
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value);
}
}
public int SendBufferSize
{
get
{
return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer);
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value);
}
}
public int ReceiveTimeout
{
get
{
return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
}
set
{
if (value < -1)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
if (value == -1)
{
value = 0;
}
SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value);
}
}
public int SendTimeout
{
get
{
return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
}
set
{
if (value < -1)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
if (value == -1)
{
value = 0;
}
SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value);
}
}
public LingerOption LingerState
{
get
{
return (LingerOption)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger);
}
set
{
SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, value);
}
}
public bool NoDelay
{
get
{
return (int)GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay) != 0 ? true : false;
}
set
{
SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, value ? 1 : 0);
}
}
public short Ttl
{
get
{
if (_addressFamily == AddressFamily.InterNetwork)
{
return (short)(int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive);
}
else if (_addressFamily == AddressFamily.InterNetworkV6)
{
return (short)(int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IpTimeToLive);
}
else
{
throw new NotSupportedException(SR.net_invalidversion);
}
}
set
{
// Valid values are from 0 to 255 since TTL is really just a byte value on the wire.
if (value < 0 || value > 255)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
if (_addressFamily == AddressFamily.InterNetwork)
{
SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, value);
}
else if (_addressFamily == AddressFamily.InterNetworkV6)
{
SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IpTimeToLive, value);
}
else
{
throw new NotSupportedException(SR.net_invalidversion);
}
}
}
public bool DontFragment
{
get
{
if (_addressFamily == AddressFamily.InterNetwork)
{
return (int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment) != 0 ? true : false;
}
else
{
throw new NotSupportedException(SR.net_invalidversion);
}
}
set
{
if (_addressFamily == AddressFamily.InterNetwork)
{
SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment, value ? 1 : 0);
}
else
{
throw new NotSupportedException(SR.net_invalidversion);
}
}
}
public bool MulticastLoopback
{
get
{
if (_addressFamily == AddressFamily.InterNetwork)
{
return (int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback) != 0 ? true : false;
}
else if (_addressFamily == AddressFamily.InterNetworkV6)
{
return (int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback) != 0 ? true : false;
}
else
{
throw new NotSupportedException(SR.net_invalidversion);
}
}
set
{
if (_addressFamily == AddressFamily.InterNetwork)
{
SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, value ? 1 : 0);
}
else if (_addressFamily == AddressFamily.InterNetworkV6)
{
SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback, value ? 1 : 0);
}
else
{
throw new NotSupportedException(SR.net_invalidversion);
}
}
}
public bool EnableBroadcast
{
get
{
return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast) != 0 ? true : false;
}
set
{
SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, value ? 1 : 0);
}
}
// NOTE: on *nix, the OS IP stack changes a dual-mode socket back to a
// normal IPv6 socket once the socket is bound to an IPv6-specific
// address. This can cause behavioral differences in code that checks
// the value of DualMode (e.g. the checks in CanTryAddressFamily).
public bool DualMode
{
get
{
if (AddressFamily != AddressFamily.InterNetworkV6)
{
throw new NotSupportedException(SR.net_invalidversion);
}
return ((int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only) == 0);
}
set
{
if (AddressFamily != AddressFamily.InterNetworkV6)
{
throw new NotSupportedException(SR.net_invalidversion);
}
SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, value ? 0 : 1);
}
}
private bool IsDualMode
{
get
{
return AddressFamily == AddressFamily.InterNetworkV6 && DualMode;
}
}
internal bool CanTryAddressFamily(AddressFamily family)
{
return (family == _addressFamily) || (family == AddressFamily.InterNetwork && IsDualMode);
}
#endregion
#region Public Methods
// Associates a socket with an end point.
public void Bind(EndPoint localEP)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, localEP);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (localEP == null)
{
throw new ArgumentNullException(nameof(localEP));
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"localEP:{localEP}");
// Ask the EndPoint to generate a SocketAddress that we can pass down to native code.
EndPoint endPointSnapshot = localEP;
Internals.SocketAddress socketAddress = SnapshotAndSerialize(ref endPointSnapshot);
DoBind(endPointSnapshot, socketAddress);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
internal void InternalBind(EndPoint localEP)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, localEP);
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"localEP:{localEP}");
if (localEP is DnsEndPoint)
{
NetEventSource.Fail(this, "Calling InternalBind with a DnsEndPoint, about to get NotImplementedException");
}
// Ask the EndPoint to generate a SocketAddress that we can pass down to native code.
EndPoint endPointSnapshot = localEP;
Internals.SocketAddress socketAddress = SnapshotAndSerialize(ref endPointSnapshot);
DoBind(endPointSnapshot, socketAddress);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
private void DoBind(EndPoint endPointSnapshot, Internals.SocketAddress socketAddress)
{
// Mitigation for Blue Screen of Death (Win7, maybe others).
IPEndPoint ipEndPoint = endPointSnapshot as IPEndPoint;
if (!OSSupportsIPv4 && ipEndPoint != null && ipEndPoint.Address.IsIPv4MappedToIPv6)
{
UpdateStatusAfterSocketErrorAndThrowException(SocketError.InvalidArgument);
}
// This may throw ObjectDisposedException.
SocketError errorCode = SocketPal.Bind(
_handle,
_protocolType,
socketAddress.Buffer,
socketAddress.Size);
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled)
{
try
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} Interop.Winsock.bind returns errorCode:{errorCode}");
}
catch (ObjectDisposedException) { }
}
#endif
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
if (_rightEndPoint == null)
{
// Save a copy of the EndPoint so we can use it for Create().
_rightEndPoint = endPointSnapshot;
}
}
// Establishes a connection to a remote system.
public void Connect(EndPoint remoteEP)
{
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (remoteEP == null)
{
throw new ArgumentNullException(nameof(remoteEP));
}
if (_isDisconnected)
{
throw new InvalidOperationException(SR.net_sockets_disconnectedConnect);
}
if (_isListening)
{
throw new InvalidOperationException(SR.net_sockets_mustnotlisten);
}
if (_isConnected)
{
throw new SocketException((int)SocketError.IsConnected);
}
ValidateBlockingMode();
if (NetEventSource.IsEnabled)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"DST:{remoteEP}");
}
DnsEndPoint dnsEP = remoteEP as DnsEndPoint;
if (dnsEP != null)
{
ValidateForMultiConnect(isMultiEndpoint: true); // needs to come before CanTryAddressFamily call
if (dnsEP.AddressFamily != AddressFamily.Unspecified && !CanTryAddressFamily(dnsEP.AddressFamily))
{
throw new NotSupportedException(SR.net_invalidversion);
}
Connect(dnsEP.Host, dnsEP.Port);
return;
}
ValidateForMultiConnect(isMultiEndpoint: false);
EndPoint endPointSnapshot = remoteEP;
Internals.SocketAddress socketAddress = SnapshotAndSerialize(ref endPointSnapshot);
if (!Blocking)
{
_nonBlockingConnectRightEndPoint = endPointSnapshot;
_nonBlockingConnectInProgress = true;
}
DoConnect(endPointSnapshot, socketAddress);
}
public void Connect(IPAddress address, int port)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, address);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
if (_isConnected)
{
throw new SocketException((int)SocketError.IsConnected);
}
ValidateForMultiConnect(isMultiEndpoint: false); // needs to come before CanTryAddressFamily call
if (!CanTryAddressFamily(address.AddressFamily))
{
throw new NotSupportedException(SR.net_invalidversion);
}
IPEndPoint remoteEP = new IPEndPoint(address, port);
Connect(remoteEP);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
public void Connect(string host, int port)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, host);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
if (_addressFamily != AddressFamily.InterNetwork && _addressFamily != AddressFamily.InterNetworkV6)
{
throw new NotSupportedException(SR.net_invalidversion);
}
// No need to call ValidateForMultiConnect(), as the validation
// will be handled by the delegated Connect overloads.
IPAddress parsedAddress;
if (IPAddress.TryParse(host, out parsedAddress))
{
Connect(parsedAddress, port);
}
else
{
IPAddress[] addresses = Dns.GetHostAddressesAsync(host).GetAwaiter().GetResult();
Connect(addresses, port);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
public void Connect(IPAddress[] addresses, int port)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, addresses);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (addresses == null)
{
throw new ArgumentNullException(nameof(addresses));
}
if (addresses.Length == 0)
{
throw new ArgumentException(SR.net_sockets_invalid_ipaddress_length, nameof(addresses));
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
if (_addressFamily != AddressFamily.InterNetwork && _addressFamily != AddressFamily.InterNetworkV6)
{
throw new NotSupportedException(SR.net_invalidversion);
}
if (_isConnected)
{
throw new SocketException((int)SocketError.IsConnected);
}
ValidateForMultiConnect(isMultiEndpoint: true); // needs to come before CanTryAddressFamily call
ExceptionDispatchInfo lastex = null;
foreach (IPAddress address in addresses)
{
if (CanTryAddressFamily(address.AddressFamily))
{
try
{
Connect(new IPEndPoint(address, port));
lastex = null;
break;
}
catch (Exception ex) when (!ExceptionCheck.IsFatal(ex))
{
lastex = ExceptionDispatchInfo.Capture(ex);
}
}
}
lastex?.Throw();
// If we're not connected, then we didn't get a valid ipaddress in the list.
if (!Connected)
{
throw new ArgumentException(SR.net_invalidAddressList, nameof(addresses));
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
public void Close()
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
NetEventSource.Info(this, $"timeout = {_closeTimeout}");
}
Dispose();
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
public void Close(int timeout)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, timeout);
if (timeout < -1)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
_closeTimeout = timeout;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"timeout = {_closeTimeout}");
Dispose();
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, timeout);
}
// Places a socket in a listening state.
public void Listen(int backlog)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, backlog);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"backlog:{backlog}");
// This may throw ObjectDisposedException.
SocketError errorCode = SocketPal.Listen(_handle, backlog);
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled)
{
try
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} Interop.Winsock.listen returns errorCode:{errorCode}");
}
catch (ObjectDisposedException) { }
}
#endif
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
_isListening = true;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
// Creates a new Sockets.Socket instance to handle an incoming connection.
public Socket Accept()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
// Validate input parameters.
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (_rightEndPoint == null)
{
throw new InvalidOperationException(SR.net_sockets_mustbind);
}
if (!_isListening)
{
throw new InvalidOperationException(SR.net_sockets_mustlisten);
}
if (_isDisconnected)
{
throw new InvalidOperationException(SR.net_sockets_disconnectedAccept);
}
ValidateBlockingMode();
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint}");
Internals.SocketAddress socketAddress = IPEndPointExtensions.Serialize(_rightEndPoint);
// This may throw ObjectDisposedException.
SafeSocketHandle acceptedSocketHandle;
SocketError errorCode = SocketPal.Accept(
_handle,
socketAddress.Buffer,
ref socketAddress.InternalSize,
out acceptedSocketHandle);
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
Debug.Assert(acceptedSocketHandle.IsInvalid);
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
Debug.Assert(!acceptedSocketHandle.IsInvalid);
Socket socket = CreateAcceptSocket(acceptedSocketHandle, _rightEndPoint.Create(socketAddress));
if (NetEventSource.IsEnabled)
{
NetEventSource.Accepted(socket, socket.RemoteEndPoint, socket.LocalEndPoint);
NetEventSource.Exit(this, socket);
}
return socket;
}
// Sends a data buffer to a connected socket.
public int Send(byte[] buffer, int size, SocketFlags socketFlags)
{
return Send(buffer, 0, size, socketFlags);
}
public int Send(byte[] buffer, SocketFlags socketFlags)
{
return Send(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags);
}
public int Send(byte[] buffer)
{
return Send(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None);
}
public int Send(IList<ArraySegment<byte>> buffers)
{
return Send(buffers, SocketFlags.None);
}
public int Send(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
{
SocketError errorCode;
int bytesTransferred = Send(buffers, socketFlags, out errorCode);
if (errorCode != SocketError.Success)
{
throw new SocketException((int)errorCode);
}
return bytesTransferred;
}
public int Send(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (buffers == null)
{
throw new ArgumentNullException(nameof(buffers));
}
if (buffers.Count == 0)
{
throw new ArgumentException(SR.Format(SR.net_sockets_zerolist, nameof(buffers)), nameof(buffers));
}
ValidateBlockingMode();
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint}");
int bytesTransferred;
errorCode = SocketPal.Send(_handle, buffers, socketFlags, out bytesTransferred);
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled)
{
try
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} Interop.Winsock.send returns errorCode:{errorCode} bytesTransferred:{bytesTransferred}");
}
catch (ObjectDisposedException) { }
}
#endif
if (errorCode != SocketError.Success)
{
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
if (NetEventSource.IsEnabled)
{
NetEventSource.Error(this, new SocketException((int)errorCode));
NetEventSource.Exit(this, 0);
}
return 0;
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
// Sends data to a connected socket, starting at the indicated location in the buffer.
public int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags)
{
SocketError errorCode;
int bytesTransferred = Send(buffer, offset, size, socketFlags, out errorCode);
if (errorCode != SocketError.Success)
{
throw new SocketException((int)errorCode);
}
return bytesTransferred;
}
public int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (size < 0 || size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
errorCode = SocketError.Success;
ValidateBlockingMode();
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} size:{size}");
int bytesTransferred;
errorCode = SocketPal.Send(_handle, buffer, offset, size, socketFlags, out bytesTransferred);
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
if (NetEventSource.IsEnabled)
{
NetEventSource.Error(this, new SocketException((int)errorCode));
NetEventSource.Exit(this, 0);
}
return 0;
}
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(this, $"Interop.Winsock.send returns:{bytesTransferred}");
NetEventSource.DumpBuffer(this, buffer, offset, bytesTransferred);
NetEventSource.Exit(this, bytesTransferred);
}
return bytesTransferred;
}
public int Send(ReadOnlySpan<byte> buffer) => Send(buffer, SocketFlags.None);
public int Send(ReadOnlySpan<byte> buffer, SocketFlags socketFlags)
{
int bytesTransferred = Send(buffer, socketFlags, out SocketError errorCode);
return errorCode == SocketError.Success ?
bytesTransferred :
throw new SocketException((int)errorCode);
}
public int Send(ReadOnlySpan<byte> buffer, SocketFlags socketFlags, out SocketError errorCode)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp) throw new ObjectDisposedException(GetType().FullName);
ValidateBlockingMode();
int bytesTransferred;
errorCode = SocketPal.Send(_handle, buffer, socketFlags, out bytesTransferred);
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketError(errorCode);
if (NetEventSource.IsEnabled) NetEventSource.Error(this, new SocketException((int)errorCode));
bytesTransferred = 0;
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
public void SendFile(string fileName)
{
SendFile(fileName, null, null, TransmitFileOptions.UseDefaultWorkerThread);
}
public void SendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (!Connected)
{
throw new NotSupportedException(SR.net_notconnected);
}
ValidateBlockingMode();
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"::SendFile() SRC:{LocalEndPoint} DST:{RemoteEndPoint} fileName:{fileName}");
SendFileInternal(fileName, preBuffer, postBuffer, flags);
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled)
{
try
{
NetEventSource.Info(this, $"::SendFile() SRC:{LocalEndPoint} DST:{RemoteEndPoint} UnsafeNclNativeMethods.OSSOCK.TransmitFile returns errorCode:{errorCode}");
}
catch (ObjectDisposedException) { }
}
#endif
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
// Sends data to a specific end point, starting at the indicated location in the buffer.
public int SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (remoteEP == null)
{
throw new ArgumentNullException(nameof(remoteEP));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (size < 0 || size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
ValidateBlockingMode();
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} size:{size} remoteEP:{remoteEP}");
EndPoint endPointSnapshot = remoteEP;
Internals.SocketAddress socketAddress = SnapshotAndSerialize(ref endPointSnapshot);
int bytesTransferred;
SocketError errorCode = SocketPal.SendTo(_handle, buffer, offset, size, socketFlags, socketAddress.Buffer, socketAddress.Size, out bytesTransferred);
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
if (_rightEndPoint == null)
{
// Save a copy of the EndPoint so we can use it for Create().
_rightEndPoint = endPointSnapshot;
}
if (NetEventSource.IsEnabled)
{
NetEventSource.DumpBuffer(this, buffer, offset, size);
NetEventSource.Exit(this, bytesTransferred);
}
return bytesTransferred;
}
// Sends data to a specific end point, starting at the indicated location in the data.
public int SendTo(byte[] buffer, int size, SocketFlags socketFlags, EndPoint remoteEP)
{
return SendTo(buffer, 0, size, socketFlags, remoteEP);
}
public int SendTo(byte[] buffer, SocketFlags socketFlags, EndPoint remoteEP)
{
return SendTo(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags, remoteEP);
}
public int SendTo(byte[] buffer, EndPoint remoteEP)
{
return SendTo(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None, remoteEP);
}
// Receives data from a connected socket.
public int Receive(byte[] buffer, int size, SocketFlags socketFlags)
{
return Receive(buffer, 0, size, socketFlags);
}
public int Receive(byte[] buffer, SocketFlags socketFlags)
{
return Receive(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags);
}
public int Receive(byte[] buffer)
{
return Receive(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None);
}
// Receives data from a connected socket into a specific location of the receive buffer.
public int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags)
{
SocketError errorCode;
int bytesTransferred = Receive(buffer, offset, size, socketFlags, out errorCode);
if (errorCode != SocketError.Success)
{
throw new SocketException((int)errorCode);
}
return bytesTransferred;
}
public int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (size < 0 || size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
ValidateBlockingMode();
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} size:{size}");
int bytesTransferred;
errorCode = SocketPal.Receive(_handle, buffer, offset, size, socketFlags, out bytesTransferred);
if (errorCode != SocketError.Success)
{
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
if (NetEventSource.IsEnabled)
{
NetEventSource.Error(this, new SocketException((int)errorCode));
NetEventSource.Exit(this, 0);
}
return 0;
}
if (NetEventSource.IsEnabled)
{
#if TRACE_VERBOSE
try
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} bytesTransferred:{bytesTransferred}");
}
catch (ObjectDisposedException) { }
#endif
NetEventSource.DumpBuffer(this, buffer, offset, bytesTransferred);
NetEventSource.Exit(this, bytesTransferred);
}
return bytesTransferred;
}
public int Receive(Span<byte> buffer) => Receive(buffer, SocketFlags.None);
public int Receive(Span<byte> buffer, SocketFlags socketFlags)
{
int bytesTransferred = Receive(buffer, socketFlags, out SocketError errorCode);
return errorCode == SocketError.Success ?
bytesTransferred :
throw new SocketException((int)errorCode);
}
public int Receive(Span<byte> buffer, SocketFlags socketFlags, out SocketError errorCode)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp) throw new ObjectDisposedException(GetType().FullName);
ValidateBlockingMode();
int bytesTransferred;
errorCode = SocketPal.Receive(_handle, buffer, socketFlags, out bytesTransferred);
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketError(errorCode);
if (NetEventSource.IsEnabled) NetEventSource.Error(this, new SocketException((int)errorCode));
bytesTransferred = 0;
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
public int Receive(IList<ArraySegment<byte>> buffers)
{
return Receive(buffers, SocketFlags.None);
}
public int Receive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
{
SocketError errorCode;
int bytesTransferred = Receive(buffers, socketFlags, out errorCode);
if (errorCode != SocketError.Success)
{
throw new SocketException((int)errorCode);
}
return bytesTransferred;
}
public int Receive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (buffers == null)
{
throw new ArgumentNullException(nameof(buffers));
}
if (buffers.Count == 0)
{
throw new ArgumentException(SR.Format(SR.net_sockets_zerolist, nameof(buffers)), nameof(buffers));
}
ValidateBlockingMode();
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint}");
int bytesTransferred;
errorCode = SocketPal.Receive(_handle, buffers, ref socketFlags, out bytesTransferred);
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled)
{
try
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} Interop.Winsock.send returns errorCode:{errorCode} bytesTransferred:{bytesTransferred}");
}
catch (ObjectDisposedException) { }
}
#endif
if (errorCode != SocketError.Success)
{
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
if (NetEventSource.IsEnabled)
{
NetEventSource.Error(this, new SocketException((int)errorCode));
NetEventSource.Exit(this, 0);
}
return 0;
}
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled)
{
try
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} bytesTransferred:{bytesTransferred}");
}
catch (ObjectDisposedException) { }
}
#endif
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
// Receives a datagram into a specific location in the data buffer and stores
// the end point.
public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (remoteEP == null)
{
throw new ArgumentNullException(nameof(remoteEP));
}
if (!CanTryAddressFamily(remoteEP.AddressFamily))
{
throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, remoteEP.AddressFamily, _addressFamily), nameof(remoteEP));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (size < 0 || size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
if (_rightEndPoint == null)
{
throw new InvalidOperationException(SR.net_sockets_mustbind);
}
SocketPal.CheckDualModeReceiveSupport(this);
ValidateBlockingMode();
// We don't do a CAS demand here because the contents of remoteEP aren't used by
// WSARecvMsg; all that matters is that we generate a unique-to-this-call SocketAddress
// with the right address family.
EndPoint endPointSnapshot = remoteEP;
Internals.SocketAddress socketAddress = SnapshotAndSerialize(ref endPointSnapshot);
// Save a copy of the original EndPoint.
Internals.SocketAddress socketAddressOriginal = IPEndPointExtensions.Serialize(endPointSnapshot);
SetReceivingPacketInformation();
Internals.SocketAddress receiveAddress;
int bytesTransferred;
SocketError errorCode = SocketPal.ReceiveMessageFrom(this, _handle, buffer, offset, size, ref socketFlags, socketAddress, out receiveAddress, out ipPacketInformation, out bytesTransferred);
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success && errorCode != SocketError.MessageSize)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
if (!socketAddressOriginal.Equals(receiveAddress))
{
try
{
remoteEP = endPointSnapshot.Create(receiveAddress);
}
catch
{
}
if (_rightEndPoint == null)
{
// Save a copy of the EndPoint so we can use it for Create().
_rightEndPoint = endPointSnapshot;
}
}
if (NetEventSource.IsEnabled) NetEventSource.Error(this, errorCode);
return bytesTransferred;
}
// Receives a datagram into a specific location in the data buffer and stores
// the end point.
public int ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (remoteEP == null)
{
throw new ArgumentNullException(nameof(remoteEP));
}
if (!CanTryAddressFamily(remoteEP.AddressFamily))
{
throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily,
remoteEP.AddressFamily, _addressFamily), nameof(remoteEP));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (size < 0 || size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
if (_rightEndPoint == null)
{
throw new InvalidOperationException(SR.net_sockets_mustbind);
}
SocketPal.CheckDualModeReceiveSupport(this);
ValidateBlockingMode();
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC{LocalEndPoint} size:{size} remoteEP:{remoteEP}");
// We don't do a CAS demand here because the contents of remoteEP aren't used by
// WSARecvFrom; all that matters is that we generate a unique-to-this-call SocketAddress
// with the right address family.
EndPoint endPointSnapshot = remoteEP;
Internals.SocketAddress socketAddress = SnapshotAndSerialize(ref endPointSnapshot);
Internals.SocketAddress socketAddressOriginal = IPEndPointExtensions.Serialize(endPointSnapshot);
int bytesTransferred;
SocketError errorCode = SocketPal.ReceiveFrom(_handle, buffer, offset, size, socketFlags, socketAddress.Buffer, ref socketAddress.InternalSize, out bytesTransferred);
// If the native call fails we'll throw a SocketException.
SocketException socketException = null;
if (errorCode != SocketError.Success)
{
socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
if (NetEventSource.IsEnabled) NetEventSource.Error(this, socketException);
if (socketException.SocketErrorCode != SocketError.MessageSize)
{
throw socketException;
}
}
if (!socketAddressOriginal.Equals(socketAddress))
{
try
{
remoteEP = endPointSnapshot.Create(socketAddress);
}
catch
{
}
if (_rightEndPoint == null)
{
// Save a copy of the EndPoint so we can use it for Create().
_rightEndPoint = endPointSnapshot;
}
}
if (socketException != null)
{
throw socketException;
}
if (NetEventSource.IsEnabled)
{
NetEventSource.DumpBuffer(this, buffer, offset, size);
NetEventSource.Exit(this, bytesTransferred);
}
return bytesTransferred;
}
// Receives a datagram and stores the source end point.
public int ReceiveFrom(byte[] buffer, int size, SocketFlags socketFlags, ref EndPoint remoteEP)
{
return ReceiveFrom(buffer, 0, size, socketFlags, ref remoteEP);
}
public int ReceiveFrom(byte[] buffer, SocketFlags socketFlags, ref EndPoint remoteEP)
{
return ReceiveFrom(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags, ref remoteEP);
}
public int ReceiveFrom(byte[] buffer, ref EndPoint remoteEP)
{
return ReceiveFrom(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None, ref remoteEP);
}
public int IOControl(int ioControlCode, byte[] optionInValue, byte[] optionOutValue)
{
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
int realOptionLength = 0;
// IOControl is used for Windows-specific IOCTL operations. If we need to add support for IOCTLs specific
// to other platforms, we will likely need to add a new API, as the control codes may overlap with those
// from Windows. Generally it would be preferable to add new methods/properties to abstract these across
// platforms, however.
SocketError errorCode = SocketPal.WindowsIoctl(_handle, ioControlCode, optionInValue, optionOutValue, out realOptionLength);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.WSAIoctl returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
return realOptionLength;
}
public int IOControl(IOControlCode ioControlCode, byte[] optionInValue, byte[] optionOutValue)
{
return IOControl(unchecked((int)ioControlCode), optionInValue, optionOutValue);
}
// Sets the specified option to the specified value.
public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
{
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"optionLevel:{optionLevel} optionName:{optionName} optionValue:{optionValue}");
SetSocketOption(optionLevel, optionName, optionValue, false);
}
public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
{
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"optionLevel:{optionLevel} optionName:{optionName} optionValue:{optionValue}");
// This can throw ObjectDisposedException.
SocketError errorCode = SocketPal.SetSockOpt(_handle, optionLevel, optionName, optionValue);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.setsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
}
// Sets the specified option to the specified value.
public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue)
{
SetSocketOption(optionLevel, optionName, (optionValue ? 1 : 0));
}
// Sets the specified option to the specified value.
public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue)
{
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (optionValue == null)
{
throw new ArgumentNullException(nameof(optionValue));
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"optionLevel:{optionLevel} optionName:{optionName} optionValue:{optionValue}");
if (optionLevel == SocketOptionLevel.Socket && optionName == SocketOptionName.Linger)
{
LingerOption lingerOption = optionValue as LingerOption;
if (lingerOption == null)
{
throw new ArgumentException(SR.Format(SR.net_sockets_invalid_optionValue, "LingerOption"), nameof(optionValue));
}
if (lingerOption.LingerTime < 0 || lingerOption.LingerTime > (int)ushort.MaxValue)
{
throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 0, (int)ushort.MaxValue), "optionValue.LingerTime");
}
SetLingerOption(lingerOption);
}
else if (optionLevel == SocketOptionLevel.IP && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership))
{
MulticastOption multicastOption = optionValue as MulticastOption;
if (multicastOption == null)
{
throw new ArgumentException(SR.Format(SR.net_sockets_invalid_optionValue, "MulticastOption"), nameof(optionValue));
}
SetMulticastOption(optionName, multicastOption);
}
else if (optionLevel == SocketOptionLevel.IPv6 && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership))
{
// IPv6 Changes: Handle IPv6 Multicast Add / Drop
IPv6MulticastOption multicastOption = optionValue as IPv6MulticastOption;
if (multicastOption == null)
{
throw new ArgumentException(SR.Format(SR.net_sockets_invalid_optionValue, "IPv6MulticastOption"), nameof(optionValue));
}
SetIPv6MulticastOption(optionName, multicastOption);
}
else
{
throw new ArgumentException(SR.net_sockets_invalid_optionValue_all, nameof(optionValue));
}
}
// Gets the value of a socket option.
public object GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName)
{
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (optionLevel == SocketOptionLevel.Socket && optionName == SocketOptionName.Linger)
{
return GetLingerOpt();
}
else if (optionLevel == SocketOptionLevel.IP && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership))
{
return GetMulticastOpt(optionName);
}
else if (optionLevel == SocketOptionLevel.IPv6 && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership))
{
// Handle IPv6 case
return GetIPv6MulticastOpt(optionName);
}
int optionValue = 0;
// This can throw ObjectDisposedException.
SocketError errorCode = SocketPal.GetSockOpt(
_handle,
optionLevel,
optionName,
out optionValue);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
return optionValue;
}
public void GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
{
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
int optionLength = optionValue != null ? optionValue.Length : 0;
// This can throw ObjectDisposedException.
SocketError errorCode = SocketPal.GetSockOpt(
_handle,
optionLevel,
optionName,
optionValue,
ref optionLength);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
}
public byte[] GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionLength)
{
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
byte[] optionValue = new byte[optionLength];
int realOptionLength = optionLength;
// This can throw ObjectDisposedException.
SocketError errorCode = SocketPal.GetSockOpt(
_handle,
optionLevel,
optionName,
optionValue,
ref realOptionLength);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
if (optionLength != realOptionLength)
{
byte[] newOptionValue = new byte[realOptionLength];
Buffer.BlockCopy(optionValue, 0, newOptionValue, 0, realOptionLength);
optionValue = newOptionValue;
}
return optionValue;
}
public void SetIPProtectionLevel(IPProtectionLevel level)
{
if (level == IPProtectionLevel.Unspecified)
{
throw new ArgumentException(SR.net_sockets_invalid_optionValue_all, nameof(level));
}
if (_addressFamily == AddressFamily.InterNetworkV6)
{
SocketPal.SetIPProtectionLevel(this, SocketOptionLevel.IPv6, (int)level);
}
else if (_addressFamily == AddressFamily.InterNetwork)
{
SocketPal.SetIPProtectionLevel(this, SocketOptionLevel.IP, (int)level);
}
else
{
throw new NotSupportedException(SR.net_invalidversion);
}
}
// Determines the status of the socket.
public bool Poll(int microSeconds, SelectMode mode)
{
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
bool status;
SocketError errorCode = SocketPal.Poll(_handle, microSeconds, mode, out status);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.select returns socketCount:{(int)errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
return status;
}
// Determines the status of a socket.
public static void Select(IList checkRead, IList checkWrite, IList checkError, int microSeconds)
{
// Validate input parameters.
if ((checkRead == null || checkRead.Count == 0) && (checkWrite == null || checkWrite.Count == 0) && (checkError == null || checkError.Count == 0))
{
throw new ArgumentNullException(null, SR.net_sockets_empty_select);
}
const int MaxSelect = 65536;
if (checkRead != null && checkRead.Count > MaxSelect)
{
throw new ArgumentOutOfRangeException(nameof(checkRead), SR.Format(SR.net_sockets_toolarge_select, nameof(checkRead), MaxSelect.ToString()));
}
if (checkWrite != null && checkWrite.Count > MaxSelect)
{
throw new ArgumentOutOfRangeException(nameof(checkWrite), SR.Format(SR.net_sockets_toolarge_select, nameof(checkWrite), MaxSelect.ToString()));
}
if (checkError != null && checkError.Count > MaxSelect)
{
throw new ArgumentOutOfRangeException(nameof(checkError), SR.Format(SR.net_sockets_toolarge_select, nameof(checkError), MaxSelect.ToString()));
}
SocketError errorCode = SocketPal.Select(checkRead, checkWrite, checkError, microSeconds);
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
throw new SocketException((int)errorCode);
}
}
// Routine Description:
//
// BeginConnect - Does an async connect.
//
// Arguments:
//
// remoteEP - status line that we wish to parse
// Callback - Async Callback Delegate that is called upon Async Completion
// State - State used to track callback, set by caller, not required
//
// Return Value:
//
// IAsyncResult - Async result used to retrieve result
public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
{
// Validate input parameters.
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, remoteEP);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (remoteEP == null)
{
throw new ArgumentNullException(nameof(remoteEP));
}
if (_isListening)
{
throw new InvalidOperationException(SR.net_sockets_mustnotlisten);
}
if (_isConnected)
{
throw new SocketException((int)SocketError.IsConnected);
}
DnsEndPoint dnsEP = remoteEP as DnsEndPoint;
if (dnsEP != null)
{
ValidateForMultiConnect(isMultiEndpoint: true); // needs to come before CanTryAddressFamily call
if (dnsEP.AddressFamily != AddressFamily.Unspecified && !CanTryAddressFamily(dnsEP.AddressFamily))
{
throw new NotSupportedException(SR.net_invalidversion);
}
return BeginConnect(dnsEP.Host, dnsEP.Port, callback, state);
}
ValidateForMultiConnect(isMultiEndpoint: false);
return UnsafeBeginConnect(remoteEP, callback, state, flowContext:true);
}
private bool CanUseConnectEx(EndPoint remoteEP)
{
return (_socketType == SocketType.Stream) &&
(_rightEndPoint != null || remoteEP.GetType() == typeof(IPEndPoint));
}
public SocketInformation DuplicateAndClose(int targetProcessId)
{
//
// On Windows, we cannot duplicate a socket that is bound to an IOCP. In this implementation, we *only*
// support IOCPs, so this will not work.
//
// On Unix, duplication of a socket into an arbitrary process is not supported at all.
//
throw new PlatformNotSupportedException(SR.net_sockets_duplicateandclose_notsupported);
}
internal IAsyncResult UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback callback, object state, bool flowContext = false)
{
if (CanUseConnectEx(remoteEP))
{
return BeginConnectEx(remoteEP, flowContext, callback, state);
}
EndPoint endPointSnapshot = remoteEP;
var asyncResult = new ConnectAsyncResult(this, endPointSnapshot, state, callback);
// For connectionless protocols, Connect is not an I/O call.
Connect(remoteEP);
asyncResult.FinishPostingAsyncOp();
// Synchronously complete the I/O and call the user's callback.
asyncResult.InvokeCallback();
return asyncResult;
}
public IAsyncResult BeginConnect(string host, int port, AsyncCallback requestCallback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, host);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
if (_addressFamily != AddressFamily.InterNetwork && _addressFamily != AddressFamily.InterNetworkV6)
{
throw new NotSupportedException(SR.net_invalidversion);
}
if (_isListening)
{
throw new InvalidOperationException(SR.net_sockets_mustnotlisten);
}
if (_isConnected)
{
throw new SocketException((int)SocketError.IsConnected);
}
IPAddress parsedAddress;
if (IPAddress.TryParse(host, out parsedAddress))
{
IAsyncResult r = BeginConnect(parsedAddress, port, requestCallback, state);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, r);
return r;
}
ValidateForMultiConnect(isMultiEndpoint: true);
// Here, want to flow the context. No need to lock.
MultipleAddressConnectAsyncResult result = new MultipleAddressConnectAsyncResult(null, port, this, state, requestCallback);
result.StartPostingAsyncOp(false);
IAsyncResult dnsResult = Dns.BeginGetHostAddresses(host, new AsyncCallback(DnsCallback), result);
if (dnsResult.CompletedSynchronously)
{
if (DoDnsCallback(dnsResult, result))
{
result.InvokeCallback();
}
}
// Done posting.
result.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, result);
return result;
}
public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, address);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
if (_isConnected)
{
throw new SocketException((int)SocketError.IsConnected);
}
ValidateForMultiConnect(isMultiEndpoint: false); // needs to be called before CanTryAddressFamily
if (!CanTryAddressFamily(address.AddressFamily))
{
throw new NotSupportedException(SR.net_invalidversion);
}
IAsyncResult result = BeginConnect(new IPEndPoint(address, port), requestCallback, state);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, result);
return result;
}
public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, addresses);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (addresses == null)
{
throw new ArgumentNullException(nameof(addresses));
}
if (addresses.Length == 0)
{
throw new ArgumentException(SR.net_invalidAddressList, nameof(addresses));
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
if (_addressFamily != AddressFamily.InterNetwork && _addressFamily != AddressFamily.InterNetworkV6)
{
throw new NotSupportedException(SR.net_invalidversion);
}
if (_isListening)
{
throw new InvalidOperationException(SR.net_sockets_mustnotlisten);
}
if (_isConnected)
{
throw new SocketException((int)SocketError.IsConnected);
}
ValidateForMultiConnect(isMultiEndpoint: true);
// Set up the result to capture the context. No need for a lock.
MultipleAddressConnectAsyncResult result = new MultipleAddressConnectAsyncResult(addresses, port, this, state, requestCallback);
result.StartPostingAsyncOp(false);
if (DoMultipleAddressConnectCallback(PostOneBeginConnect(result), result))
{
// If the call completes synchronously, invoke the callback from here.
result.InvokeCallback();
}
// Finished posting async op. Possibly will call callback.
result.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, result);
return result;
}
public IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback callback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Start context-flowing op. No need to lock - we don't use the context till the callback.
DisconnectOverlappedAsyncResult asyncResult = new DisconnectOverlappedAsyncResult(this, state, callback);
asyncResult.StartPostingAsyncOp(false);
// Post the disconnect.
DoBeginDisconnect(reuseSocket, asyncResult);
// Finish flowing (or call the callback), and return.
asyncResult.FinishPostingAsyncOp();
return asyncResult;
}
private void DoBeginDisconnect(bool reuseSocket, DisconnectOverlappedAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
SocketError errorCode = SocketError.Success;
errorCode = SocketPal.DisconnectAsync(this, _handle, reuseSocket, asyncResult);
if (errorCode == SocketError.Success)
{
SetToDisconnected();
_remoteEndPoint = null;
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"UnsafeNclNativeMethods.OSSOCK.DisConnectEx returns:{errorCode}");
// If the call failed, update our status and throw
if (!CheckErrorAndUpdateStatus(errorCode))
{
throw new SocketException((int)errorCode);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, asyncResult);
}
public void Disconnect(bool reuseSocket)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
SocketError errorCode = SocketError.Success;
// This can throw ObjectDisposedException (handle, and retrieving the delegate).
errorCode = SocketPal.Disconnect(this, _handle, reuseSocket);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"UnsafeNclNativeMethods.OSSOCK.DisConnectEx returns:{errorCode}");
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
SetToDisconnected();
_remoteEndPoint = null;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
// Routine Description:
//
// EndConnect - Called after receiving callback from BeginConnect,
// in order to retrieve the result of async call
//
// Arguments:
//
// AsyncResult - the AsyncResult Returned from BeginConnect call
//
// Return Value:
//
// int - Return code from async Connect, 0 for success, SocketError.NotConnected otherwise
public void EndConnect(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, asyncResult);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
ContextAwareResult castedAsyncResult =
asyncResult as ConnectOverlappedAsyncResult ??
asyncResult as MultipleAddressConnectAsyncResult ??
(ContextAwareResult)(asyncResult as ConnectAsyncResult);
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (castedAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndConnect"));
}
castedAsyncResult.InternalWaitForCompletion();
castedAsyncResult.EndCalled = true;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"asyncResult:{asyncResult}");
Exception ex = castedAsyncResult.Result as Exception;
if (ex != null || (SocketError)castedAsyncResult.ErrorCode != SocketError.Success)
{
if (ex == null)
{
// Update the internal state of this socket according to the error before throwing.
SocketException se = SocketExceptionFactory.CreateSocketException(castedAsyncResult.ErrorCode, castedAsyncResult.RemoteEndPoint);
UpdateStatusAfterSocketError(se);
ex = se;
}
if (NetEventSource.IsEnabled) NetEventSource.Error(this, ex);
ExceptionDispatchInfo.Throw(ex);
}
if (NetEventSource.IsEnabled)
{
NetEventSource.Connected(this, LocalEndPoint, RemoteEndPoint);
NetEventSource.Exit(this, "");
}
}
public void EndDisconnect(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, asyncResult);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
//get async result and check for errors
LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (castedAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndDisconnect)));
}
//wait for completion if it hasn't occurred
castedAsyncResult.InternalWaitForCompletion();
castedAsyncResult.EndCalled = true;
if (NetEventSource.IsEnabled) NetEventSource.Info(this);
//
// if the asynchronous native call failed asynchronously
// we'll throw a SocketException
//
if ((SocketError)castedAsyncResult.ErrorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException((SocketError)castedAsyncResult.ErrorCode);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
// Routine Description:
//
// BeginSend - Async implementation of Send call, mirrored after BeginReceive
// This routine may go pending at which time,
// but any case the callback Delegate will be called upon completion
//
// Arguments:
//
// WriteBuffer - status line that we wish to parse
// Index - Offset into WriteBuffer to begin sending from
// Size - Size of Buffer to transmit
// Callback - Delegate function that holds callback, called on completion of I/O
// State - State used to track callback, set by caller, not required
//
// Return Value:
//
// IAsyncResult - Async result used to retrieve result
public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state)
{
SocketError errorCode;
IAsyncResult result = BeginSend(buffer, offset, size, socketFlags, out errorCode, callback, state);
if (errorCode != SocketError.Success && errorCode != SocketError.IOPending)
{
throw new SocketException((int)errorCode);
}
return result;
}
public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (size < 0 || size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
// We need to flow the context here. But we don't need to lock the context - we don't use it until the callback.
OverlappedAsyncResult asyncResult = new OverlappedAsyncResult(this, state, callback);
asyncResult.StartPostingAsyncOp(false);
// Run the send with this asyncResult.
errorCode = DoBeginSend(buffer, offset, size, socketFlags, asyncResult);
if (errorCode != SocketError.Success && errorCode != SocketError.IOPending)
{
asyncResult = null;
}
else
{
// We're not throwing, so finish the async op posting code so we can return to the user.
// If the operation already finished, the callback will be called from here.
asyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
private SocketError DoBeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} size:{size}");
// Get the Send going.
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"asyncResult:{asyncResult} size:{size}");
SocketError errorCode = SocketPal.SendAsync(_handle, buffer, offset, size, socketFlags, asyncResult);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.WSASend returns:{errorCode} size:{size} returning AsyncResult:{asyncResult}");
// If the call failed, update our status
CheckErrorAndUpdateStatus(errorCode);
return errorCode;
}
public IAsyncResult BeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
{
SocketError errorCode;
IAsyncResult result = BeginSend(buffers, socketFlags, out errorCode, callback, state);
if (errorCode != SocketError.Success && errorCode != SocketError.IOPending)
{
throw new SocketException((int)errorCode);
}
return result;
}
public IAsyncResult BeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (buffers == null)
{
throw new ArgumentNullException(nameof(buffers));
}
if (buffers.Count == 0)
{
throw new ArgumentException(SR.Format(SR.net_sockets_zerolist, nameof(buffers)), nameof(buffers));
}
// We need to flow the context here. But we don't need to lock the context - we don't use it until the callback.
OverlappedAsyncResult asyncResult = new OverlappedAsyncResult(this, state, callback);
asyncResult.StartPostingAsyncOp(false);
// Run the send with this asyncResult.
errorCode = DoBeginSend(buffers, socketFlags, asyncResult);
// We're not throwing, so finish the async op posting code so we can return to the user.
// If the operation already finished, the callback will be called from here.
asyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);
if (errorCode != SocketError.Success && errorCode != SocketError.IOPending)
{
asyncResult = null;
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
private SocketError DoBeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} buffers:{buffers}");
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"asyncResult:{asyncResult}");
SocketError errorCode = SocketPal.SendAsync(_handle, buffers, socketFlags, asyncResult);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.WSASend returns:{errorCode} returning AsyncResult:{asyncResult}");
// If the call failed, update our status
CheckErrorAndUpdateStatus(errorCode);
return errorCode;
}
// Routine Description:
//
// EndSend - Called by user code after I/O is done or the user wants to wait.
// until Async completion, needed to retrieve error result from call
//
// Arguments:
//
// AsyncResult - the AsyncResult Returned from BeginSend call
//
// Return Value:
//
// int - Number of bytes transferred
public int EndSend(IAsyncResult asyncResult)
{
SocketError errorCode;
int bytesTransferred = EndSend(asyncResult, out errorCode);
if (errorCode != SocketError.Success)
{
throw new SocketException((int)errorCode);
}
return bytesTransferred;
}
public int EndSend(IAsyncResult asyncResult, out SocketError errorCode)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, asyncResult);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
OverlappedAsyncResult castedAsyncResult = asyncResult as OverlappedAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (castedAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndSend"));
}
int bytesTransferred = castedAsyncResult.InternalWaitForCompletionInt32Result();
castedAsyncResult.EndCalled = true;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"bytesTransffered:{bytesTransferred}");
// Throw an appropriate SocketException if the native call failed asynchronously.
errorCode = (SocketError)castedAsyncResult.ErrorCode;
if (errorCode != SocketError.Success)
{
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
if (NetEventSource.IsEnabled)
{
NetEventSource.Error(this, new SocketException((int)errorCode));
NetEventSource.Exit(this, 0);
}
return 0;
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
public IAsyncResult BeginSendFile(string fileName, AsyncCallback callback, object state)
{
return BeginSendFile(fileName, null, null, TransmitFileOptions.UseDefaultWorkerThread, callback, state);
}
public IAsyncResult BeginSendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (!Connected)
{
throw new NotSupportedException(SR.net_notconnected);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"::DoBeginSendFile() SRC:{LocalEndPoint} DST:{RemoteEndPoint} fileName:{fileName}");
IAsyncResult asyncResult = BeginSendFileInternal(fileName, preBuffer, postBuffer, flags, callback, state);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
public void EndSendFile(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, asyncResult);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
EndSendFileInternal(asyncResult);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
// Routine Description:
//
// BeginSendTo - Async implementation of SendTo,
//
// This routine may go pending at which time,
// but any case the callback Delegate will be called upon completion
//
// Arguments:
//
// WriteBuffer - Buffer to transmit
// Index - Offset into WriteBuffer to begin sending from
// Size - Size of Buffer to transmit
// Flags - Specific Socket flags to pass to winsock
// remoteEP - EndPoint to transmit To
// Callback - Delegate function that holds callback, called on completion of I/O
// State - State used to track callback, set by caller, not required
//
// Return Value:
//
// IAsyncResult - Async result used to retrieve result
public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback callback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (remoteEP == null)
{
throw new ArgumentNullException(nameof(remoteEP));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (size < 0 || size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
EndPoint endPointSnapshot = remoteEP;
Internals.SocketAddress socketAddress = SnapshotAndSerialize(ref endPointSnapshot);
// Set up the async result and indicate to flow the context.
OverlappedAsyncResult asyncResult = new OverlappedAsyncResult(this, state, callback);
asyncResult.StartPostingAsyncOp(false);
// Post the send.
DoBeginSendTo(buffer, offset, size, socketFlags, endPointSnapshot, socketAddress, asyncResult);
// Finish, possibly posting the callback. The callback won't be posted before this point is reached.
asyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
private void DoBeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint endPointSnapshot, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"size:{size}");
EndPoint oldEndPoint = _rightEndPoint;
// Guarantee to call CheckAsyncCallOverlappedResult if we call SetUnamangedStructures with a cache in order to
// avoid a Socket leak in case of error.
SocketError errorCode = SocketError.SocketError;
try
{
if (_rightEndPoint == null)
{
_rightEndPoint = endPointSnapshot;
}
errorCode = SocketPal.SendToAsync(_handle, buffer, offset, size, socketFlags, socketAddress, asyncResult);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.WSASend returns:{errorCode} size:{size} returning AsyncResult:{asyncResult}");
}
catch (ObjectDisposedException)
{
_rightEndPoint = oldEndPoint;
throw;
}
// Throw an appropriate SocketException if the native call fails synchronously.
if (!CheckErrorAndUpdateStatus(errorCode))
{
// Update the internal state of this socket according to the error before throwing.
_rightEndPoint = oldEndPoint;
throw new SocketException((int)errorCode);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"size:{size} returning AsyncResult:{asyncResult}");
}
// Routine Description:
//
// EndSendTo - Called by user code after I/O is done or the user wants to wait.
// until Async completion, needed to retrieve error result from call
//
// Arguments:
//
// AsyncResult - the AsyncResult Returned from BeginSend call
//
// Return Value:
//
// int - Number of bytes transferred
public int EndSendTo(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, asyncResult);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
OverlappedAsyncResult castedAsyncResult = asyncResult as OverlappedAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (castedAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndSendTo"));
}
int bytesTransferred = castedAsyncResult.InternalWaitForCompletionInt32Result();
castedAsyncResult.EndCalled = true;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"bytesTransferred:{bytesTransferred}");
// Throw an appropriate SocketException if the native call failed asynchronously.
if ((SocketError)castedAsyncResult.ErrorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException((SocketError)castedAsyncResult.ErrorCode);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
// Routine Description:
//
// BeginReceive - Async implementation of Recv call,
//
// Called when we want to start an async receive.
// We kick off the receive, and if it completes synchronously we'll
// call the callback. Otherwise we'll return an IASyncResult, which
// the caller can use to wait on or retrieve the final status, as needed.
//
// Uses Winsock 2 overlapped I/O.
//
// Arguments:
//
// ReadBuffer - status line that we wish to parse
// Index - Offset into ReadBuffer to begin reading from
// Size - Size of Buffer to recv
// Callback - Delegate function that holds callback, called on completion of I/O
// State - State used to track callback, set by caller, not required
//
// Return Value:
//
// IAsyncResult - Async result used to retrieve result
public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state)
{
SocketError errorCode;
IAsyncResult result = BeginReceive(buffer, offset, size, socketFlags, out errorCode, callback, state);
if (errorCode != SocketError.Success && errorCode != SocketError.IOPending)
{
throw new SocketException((int)errorCode);
}
return result;
}
public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (size < 0 || size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
// We need to flow the context here. But we don't need to lock the context - we don't use it until the callback.
OverlappedAsyncResult asyncResult = new OverlappedAsyncResult(this, state, callback);
asyncResult.StartPostingAsyncOp(false);
// Run the receive with this asyncResult.
errorCode = DoBeginReceive(buffer, offset, size, socketFlags, asyncResult);
if (errorCode != SocketError.Success && errorCode != SocketError.IOPending)
{
asyncResult = null;
}
else
{
// We're not throwing, so finish the async op posting code so we can return to the user.
// If the operation already finished, the callback will be called from here.
asyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
private SocketError DoBeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"size:{size}");
#if DEBUG
IntPtr lastHandle = _handle.DangerousGetHandle();
#endif
SocketError errorCode = SocketPal.ReceiveAsync(_handle, buffer, offset, size, socketFlags, asyncResult);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.WSARecv returns:{errorCode} returning AsyncResult:{asyncResult}");
if (CheckErrorAndUpdateStatus(errorCode))
{
#if DEBUG
_lastReceiveHandle = lastHandle;
_lastReceiveThread = Environment.CurrentManagedThreadId;
_lastReceiveTick = Environment.TickCount;
#endif
}
return errorCode;
}
public IAsyncResult BeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
{
SocketError errorCode;
IAsyncResult result = BeginReceive(buffers, socketFlags, out errorCode, callback, state);
if (errorCode != SocketError.Success && errorCode != SocketError.IOPending)
{
throw new SocketException((int)errorCode);
}
return result;
}
public IAsyncResult BeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (buffers == null)
{
throw new ArgumentNullException(nameof(buffers));
}
if (buffers.Count == 0)
{
throw new ArgumentException(SR.Format(SR.net_sockets_zerolist, nameof(buffers)), nameof(buffers));
}
// We need to flow the context here. But we don't need to lock the context - we don't use it until the callback.
OverlappedAsyncResult asyncResult = new OverlappedAsyncResult(this, state, callback);
asyncResult.StartPostingAsyncOp(false);
// Run the receive with this asyncResult.
errorCode = DoBeginReceive(buffers, socketFlags, asyncResult);
if (errorCode != SocketError.Success && errorCode != SocketError.IOPending)
{
asyncResult = null;
}
else
{
// We're not throwing, so finish the async op posting code so we can return to the user.
// If the operation already finished, the callback will be called from here.
asyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
private SocketError DoBeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
#if DEBUG
IntPtr lastHandle = _handle.DangerousGetHandle();
#endif
SocketError errorCode = SocketPal.ReceiveAsync(_handle, buffers, socketFlags, asyncResult);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.WSARecv returns:{errorCode} returning AsyncResult:{asyncResult}");
if (!CheckErrorAndUpdateStatus(errorCode))
{
}
#if DEBUG
else
{
_lastReceiveHandle = lastHandle;
_lastReceiveThread = Environment.CurrentManagedThreadId;
_lastReceiveTick = Environment.TickCount;
}
#endif
return errorCode;
}
#if DEBUG
private IntPtr _lastReceiveHandle;
private int _lastReceiveThread;
private int _lastReceiveTick;
#endif
// Routine Description:
//
// EndReceive - Called when I/O is done or the user wants to wait. If
// the I/O isn't done, we'll wait for it to complete, and then we'll return
// the bytes of I/O done.
//
// Arguments:
//
// AsyncResult - the AsyncResult Returned from BeginSend call
//
// Return Value:
//
// int - Number of bytes transferred
public int EndReceive(IAsyncResult asyncResult)
{
SocketError errorCode;
int bytesTransferred = EndReceive(asyncResult, out errorCode);
if (errorCode != SocketError.Success)
{
throw new SocketException((int)errorCode);
}
return bytesTransferred;
}
public int EndReceive(IAsyncResult asyncResult, out SocketError errorCode)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, asyncResult);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
OverlappedAsyncResult castedAsyncResult = asyncResult as OverlappedAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (castedAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndReceive"));
}
int bytesTransferred = castedAsyncResult.InternalWaitForCompletionInt32Result();
castedAsyncResult.EndCalled = true;
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled)
{
try
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} bytesTransferred:{bytesTransferred}");
}
catch (ObjectDisposedException) { }
}
#endif
// Throw an appropriate SocketException if the native call failed asynchronously.
errorCode = (SocketError)castedAsyncResult.ErrorCode;
if (errorCode != SocketError.Success)
{
// Update the internal state of this socket according to the error before throwing.
UpdateStatusAfterSocketError(errorCode);
if (NetEventSource.IsEnabled)
{
NetEventSource.Error(this, new SocketException((int)errorCode));
NetEventSource.Exit(this, 0);
}
return 0;
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
NetEventSource.Info(this, $"size:{size}");
}
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (remoteEP == null)
{
throw new ArgumentNullException(nameof(remoteEP));
}
if (!CanTryAddressFamily(remoteEP.AddressFamily))
{
throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, remoteEP.AddressFamily, _addressFamily), nameof(remoteEP));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (size < 0 || size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
if (_rightEndPoint == null)
{
throw new InvalidOperationException(SR.net_sockets_mustbind);
}
SocketPal.CheckDualModeReceiveSupport(this);
// Set up the result and set it to collect the context.
ReceiveMessageOverlappedAsyncResult asyncResult = new ReceiveMessageOverlappedAsyncResult(this, state, callback);
asyncResult.StartPostingAsyncOp(false);
// Start the ReceiveFrom.
EndPoint oldEndPoint = _rightEndPoint;
// We don't do a CAS demand here because the contents of remoteEP aren't used by
// WSARecvMsg; all that matters is that we generate a unique-to-this-call SocketAddress
// with the right address family
Internals.SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP);
// Guarantee to call CheckAsyncCallOverlappedResult if we call SetUnamangedStructures with a cache in order to
// avoid a Socket leak in case of error.
SocketError errorCode = SocketError.SocketError;
try
{
// Save a copy of the original EndPoint in the asyncResult.
asyncResult.SocketAddressOriginal = IPEndPointExtensions.Serialize(remoteEP);
SetReceivingPacketInformation();
if (_rightEndPoint == null)
{
_rightEndPoint = remoteEP;
}
errorCode = SocketPal.ReceiveMessageFromAsync(this, _handle, buffer, offset, size, socketFlags, socketAddress, asyncResult);
if (errorCode != SocketError.Success)
{
// WSARecvMsg() will never return WSAEMSGSIZE directly, since a completion is queued in this case. We wouldn't be able
// to handle this easily because of assumptions OverlappedAsyncResult makes about whether there would be a completion
// or not depending on the error code. If WSAEMSGSIZE would have been normally returned, it returns WSA_IO_PENDING instead.
// That same map is implemented here just in case.
if (errorCode == SocketError.MessageSize)
{
NetEventSource.Fail(this, "Returned WSAEMSGSIZE!");
errorCode = SocketError.IOPending;
}
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.WSARecvMsg returns:{errorCode} size:{size} returning AsyncResult:{asyncResult}");
}
catch (ObjectDisposedException)
{
_rightEndPoint = oldEndPoint;
throw;
}
// Throw an appropriate SocketException if the native call fails synchronously.
if (!CheckErrorAndUpdateStatus(errorCode))
{
// Update the internal state of this socket according to the error before throwing.
_rightEndPoint = oldEndPoint;
throw new SocketException((int)errorCode);
}
// Capture the context, maybe call the callback, and return.
asyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
if (asyncResult.CompletedSynchronously && !asyncResult.SocketAddressOriginal.Equals(asyncResult.SocketAddress))
{
try
{
remoteEP = remoteEP.Create(asyncResult.SocketAddress);
}
catch
{
}
}
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(this, $"size:{size} returning AsyncResult:{asyncResult}");
NetEventSource.Exit(this, asyncResult);
}
return asyncResult;
}
public int EndReceiveMessageFrom(IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, asyncResult);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (endPoint == null)
{
throw new ArgumentNullException(nameof(endPoint));
}
if (!CanTryAddressFamily(endPoint.AddressFamily))
{
throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, endPoint.AddressFamily, _addressFamily), nameof(endPoint));
}
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
ReceiveMessageOverlappedAsyncResult castedAsyncResult = asyncResult as ReceiveMessageOverlappedAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (castedAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndReceiveMessageFrom"));
}
Internals.SocketAddress socketAddressOriginal = SnapshotAndSerialize(ref endPoint);
int bytesTransferred = castedAsyncResult.InternalWaitForCompletionInt32Result();
castedAsyncResult.EndCalled = true;
// Update socket address size.
castedAsyncResult.SocketAddress.InternalSize = castedAsyncResult.GetSocketAddressSize();
if (!socketAddressOriginal.Equals(castedAsyncResult.SocketAddress))
{
try
{
endPoint = endPoint.Create(castedAsyncResult.SocketAddress);
}
catch
{
}
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"bytesTransferred:{bytesTransferred}");
// Throw an appropriate SocketException if the native call failed asynchronously.
if ((SocketError)castedAsyncResult.ErrorCode != SocketError.Success && (SocketError)castedAsyncResult.ErrorCode != SocketError.MessageSize)
{
UpdateStatusAfterSocketErrorAndThrowException((SocketError)castedAsyncResult.ErrorCode);
}
socketFlags = castedAsyncResult.SocketFlags;
ipPacketInformation = castedAsyncResult.IPPacketInformation;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
// Routine Description:
//
// BeginReceiveFrom - Async implementation of RecvFrom call,
//
// Called when we want to start an async receive.
// We kick off the receive, and if it completes synchronously we'll
// call the callback. Otherwise we'll return an IASyncResult, which
// the caller can use to wait on or retrieve the final status, as needed.
//
// Uses Winsock 2 overlapped I/O.
//
// Arguments:
//
// ReadBuffer - status line that we wish to parse
// Index - Offset into ReadBuffer to begin reading from
// Request - Size of Buffer to recv
// Flags - Additional Flags that may be passed to the underlying winsock call
// remoteEP - EndPoint that are to receive from
// Callback - Delegate function that holds callback, called on completion of I/O
// State - State used to track callback, set by caller, not required
//
// Return Value:
//
// IAsyncResult - Async result used to retrieve result
public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (remoteEP == null)
{
throw new ArgumentNullException(nameof(remoteEP));
}
if (!CanTryAddressFamily(remoteEP.AddressFamily))
{
throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, remoteEP.AddressFamily, _addressFamily), nameof(remoteEP));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (size < 0 || size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
if (_rightEndPoint == null)
{
throw new InvalidOperationException(SR.net_sockets_mustbind);
}
SocketPal.CheckDualModeReceiveSupport(this);
// We don't do a CAS demand here because the contents of remoteEP aren't used by
// WSARecvFrom; all that matters is that we generate a unique-to-this-call SocketAddress
// with the right address family
Internals.SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP);
// Set up the result and set it to collect the context.
var asyncResult = new OriginalAddressOverlappedAsyncResult(this, state, callback);
asyncResult.StartPostingAsyncOp(false);
// Start the ReceiveFrom.
DoBeginReceiveFrom(buffer, offset, size, socketFlags, remoteEP, socketAddress, asyncResult);
// Capture the context, maybe call the callback, and return.
asyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
if (asyncResult.CompletedSynchronously && !asyncResult.SocketAddressOriginal.Equals(asyncResult.SocketAddress))
{
try
{
remoteEP = remoteEP.Create(asyncResult.SocketAddress);
}
catch
{
}
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
private void DoBeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint endPointSnapshot, Internals.SocketAddress socketAddress, OriginalAddressOverlappedAsyncResult asyncResult)
{
EndPoint oldEndPoint = _rightEndPoint;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"size:{size}");
// Guarantee to call CheckAsyncCallOverlappedResult if we call SetUnamangedStructures with a cache in order to
// avoid a Socket leak in case of error.
SocketError errorCode = SocketError.SocketError;
try
{
// Save a copy of the original EndPoint in the asyncResult.
asyncResult.SocketAddressOriginal = IPEndPointExtensions.Serialize(endPointSnapshot);
if (_rightEndPoint == null)
{
_rightEndPoint = endPointSnapshot;
}
errorCode = SocketPal.ReceiveFromAsync(_handle, buffer, offset, size, socketFlags, socketAddress, asyncResult);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.WSARecvFrom returns:{errorCode} size:{size} returning AsyncResult:{asyncResult}");
}
catch (ObjectDisposedException)
{
_rightEndPoint = oldEndPoint;
throw;
}
// Throw an appropriate SocketException if the native call fails synchronously.
if (!CheckErrorAndUpdateStatus(errorCode))
{
// Update the internal state of this socket according to the error before throwing.
_rightEndPoint = oldEndPoint;
throw new SocketException((int)errorCode);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"size:{size} return AsyncResult:{asyncResult}");
}
// Routine Description:
//
// EndReceiveFrom - Called when I/O is done or the user wants to wait. If
// the I/O isn't done, we'll wait for it to complete, and then we'll return
// the bytes of I/O done.
//
// Arguments:
//
// AsyncResult - the AsyncResult Returned from BeginReceiveFrom call
//
// Return Value:
//
// int - Number of bytes transferred
public int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, asyncResult);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (endPoint == null)
{
throw new ArgumentNullException(nameof(endPoint));
}
if (!CanTryAddressFamily(endPoint.AddressFamily))
{
throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, endPoint.AddressFamily, _addressFamily), nameof(endPoint));
}
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
OverlappedAsyncResult castedAsyncResult = asyncResult as OverlappedAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (castedAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndReceiveFrom"));
}
Internals.SocketAddress socketAddressOriginal = SnapshotAndSerialize(ref endPoint);
int bytesTransferred = castedAsyncResult.InternalWaitForCompletionInt32Result();
castedAsyncResult.EndCalled = true;
// Update socket address size.
castedAsyncResult.SocketAddress.InternalSize = castedAsyncResult.GetSocketAddressSize();
if (!socketAddressOriginal.Equals(castedAsyncResult.SocketAddress))
{
try
{
endPoint = endPoint.Create(castedAsyncResult.SocketAddress);
}
catch
{
}
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"bytesTransferred:{bytesTransferred}");
// Throw an appropriate SocketException if the native call failed asynchronously.
if ((SocketError)castedAsyncResult.ErrorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException((SocketError)castedAsyncResult.ErrorCode);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, bytesTransferred);
return bytesTransferred;
}
// Routine Description:
//
// BeginAccept - Does an async winsock accept, creating a new socket on success
//
// Works by creating a pending accept request the first time,
// and subsequent calls are queued so that when the first accept completes,
// the next accept can be resubmitted in the callback.
// this routine may go pending at which time,
// but any case the callback Delegate will be called upon completion
//
// Arguments:
//
// Callback - Async Callback Delegate that is called upon Async Completion
// State - State used to track callback, set by caller, not required
//
// Return Value:
//
// IAsyncResult - Async result used to retrieve resultant new socket
public IAsyncResult BeginAccept(AsyncCallback callback, object state)
{
if (!_isDisconnected)
{
return BeginAccept(0, callback, state);
}
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
Debug.Assert(CleanedUp);
throw new ObjectDisposedException(this.GetType().FullName);
}
public IAsyncResult BeginAccept(int receiveSize, AsyncCallback callback, object state)
{
return BeginAccept(null, receiveSize, callback, state);
}
// This is the truly async version that uses AcceptEx.
public IAsyncResult BeginAccept(Socket acceptSocket, int receiveSize, AsyncCallback callback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (receiveSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(receiveSize));
}
// Set up the async result with flowing.
AcceptOverlappedAsyncResult asyncResult = new AcceptOverlappedAsyncResult(this, state, callback);
asyncResult.StartPostingAsyncOp(false);
// Start the accept.
DoBeginAccept(acceptSocket, receiveSize, asyncResult);
// Finish the flow capture, maybe complete here.
asyncResult.FinishPostingAsyncOp(ref Caches.AcceptClosureCache);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, asyncResult);
return asyncResult;
}
private void DoBeginAccept(Socket acceptSocket, int receiveSize, AcceptOverlappedAsyncResult asyncResult)
{
if (_rightEndPoint == null)
{
throw new InvalidOperationException(SR.net_sockets_mustbind);
}
if (!_isListening)
{
throw new InvalidOperationException(SR.net_sockets_mustlisten);
}
SafeSocketHandle acceptHandle;
asyncResult.AcceptSocket = GetOrCreateAcceptSocket(acceptSocket, false, nameof(acceptSocket), out acceptHandle);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"AcceptSocket:{acceptSocket}");
int socketAddressSize = GetAddressSize(_rightEndPoint);
SocketError errorCode = SocketPal.AcceptAsync(this, _handle, acceptHandle, receiveSize, socketAddressSize, asyncResult);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.AcceptEx returns:{errorCode} {asyncResult}");
// Throw an appropriate SocketException if the native call fails synchronously.
if (!CheckErrorAndUpdateStatus(errorCode))
{
throw new SocketException((int)errorCode);
}
}
// Routine Description:
//
// EndAccept - Called by user code after I/O is done or the user wants to wait.
// until Async completion, so it provides End handling for async Accept calls,
// and retrieves new Socket object
//
// Arguments:
//
// AsyncResult - the AsyncResult Returned from BeginAccept call
//
// Return Value:
//
// Socket - a valid socket if successful
public Socket EndAccept(IAsyncResult asyncResult)
{
int bytesTransferred;
byte[] buffer;
return EndAccept(out buffer, out bytesTransferred, asyncResult);
}
public Socket EndAccept(out byte[] buffer, IAsyncResult asyncResult)
{
int bytesTransferred;
byte[] innerBuffer;
Socket socket = EndAccept(out innerBuffer, out bytesTransferred, asyncResult);
buffer = new byte[bytesTransferred];
Buffer.BlockCopy(innerBuffer, 0, buffer, 0, bytesTransferred);
return socket;
}
public Socket EndAccept(out byte[] buffer, out int bytesTransferred, IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, asyncResult);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Validate input parameters.
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
AcceptOverlappedAsyncResult castedAsyncResult = asyncResult as AcceptOverlappedAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (castedAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndAccept"));
}
Socket socket = (Socket)castedAsyncResult.InternalWaitForCompletion();
bytesTransferred = (int)castedAsyncResult.BytesTransferred;
buffer = castedAsyncResult.Buffer;
castedAsyncResult.EndCalled = true;
// Throw an appropriate SocketException if the native call failed asynchronously.
if ((SocketError)castedAsyncResult.ErrorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException((SocketError)castedAsyncResult.ErrorCode);
}
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled)
{
try
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} acceptedSocket:{socket} acceptedSocket.SRC:{socket.LocalEndPoint} acceptSocket.DST:{socket.RemoteEndPoint} bytesTransferred:{bytesTransferred}");
}
catch (ObjectDisposedException) { }
}
#endif
if (NetEventSource.IsEnabled)
{
NetEventSource.Accepted(socket, socket.RemoteEndPoint, socket.LocalEndPoint);
NetEventSource.Exit(this, socket);
}
return socket;
}
// Disables sends and receives on a socket.
public void Shutdown(SocketShutdown how)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, how);
if (CleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"how:{how}");
// This can throw ObjectDisposedException.
SocketError errorCode = SocketPal.Shutdown(_handle, _isConnected, _isDisconnected, how);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.shutdown returns errorCode:{errorCode}");
// Skip good cases: success, socket already closed.
if (errorCode != SocketError.Success && errorCode != SocketError.NotSocket)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
SetToDisconnected();
InternalSetBlocking(_willBlockInternal);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
#region Async methods
public bool AcceptAsync(SocketAsyncEventArgs e)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, e);
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (e == null)
{
throw new ArgumentNullException(nameof(e));
}
if (e.HasMultipleBuffers)
{
throw new ArgumentException(SR.net_multibuffernotsupported, "BufferList");
}
if (_rightEndPoint == null)
{
throw new InvalidOperationException(SR.net_sockets_mustbind);
}
if (!_isListening)
{
throw new InvalidOperationException(SR.net_sockets_mustlisten);
}
// Handle AcceptSocket property.
SafeSocketHandle acceptHandle;
e.AcceptSocket = GetOrCreateAcceptSocket(e.AcceptSocket, true, "AcceptSocket", out acceptHandle);
// Prepare for and make the native call.
e.StartOperationCommon(this, SocketAsyncOperation.Accept);
e.StartOperationAccept();
SocketError socketError = SocketError.Success;
try
{
socketError = e.DoOperationAccept(this, _handle, acceptHandle);
}
catch
{
// Clear in-use flag on event args object.
e.Complete();
throw;
}
bool pending = (socketError == SocketError.IOPending);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, pending);
return pending;
}
public bool ConnectAsync(SocketAsyncEventArgs e) =>
ConnectAsync(e, userSocket: true);
private bool ConnectAsync(SocketAsyncEventArgs e, bool userSocket)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, e);
bool pending;
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (e == null)
{
throw new ArgumentNullException(nameof(e));
}
if (e.HasMultipleBuffers)
{
throw new ArgumentException(SR.net_multibuffernotsupported, "BufferList");
}
if (e.RemoteEndPoint == null)
{
throw new ArgumentNullException("remoteEP");
}
if (_isListening)
{
throw new InvalidOperationException(SR.net_sockets_mustnotlisten);
}
if (_isConnected)
{
throw new SocketException((int)SocketError.IsConnected);
}
// Prepare SocketAddress.
EndPoint endPointSnapshot = e.RemoteEndPoint;
DnsEndPoint dnsEP = endPointSnapshot as DnsEndPoint;
if (dnsEP != null)
{
if (NetEventSource.IsEnabled) NetEventSource.ConnectedAsyncDns(this);
ValidateForMultiConnect(isMultiEndpoint: true); // needs to come before CanTryAddressFamily call
if (dnsEP.AddressFamily != AddressFamily.Unspecified && !CanTryAddressFamily(dnsEP.AddressFamily))
{
throw new NotSupportedException(SR.net_invalidversion);
}
MultipleConnectAsync multipleConnectAsync = new SingleSocketMultipleConnectAsync(this, userSocket: true);
e.StartOperationCommon(this, SocketAsyncOperation.Connect);
e.StartOperationConnect(multipleConnectAsync, userSocket: true);
try
{
pending = multipleConnectAsync.StartConnectAsync(e, dnsEP);
}
catch
{
e.Complete(); // Clear in-use flag on event args object.
throw;
}
}
else
{
ValidateForMultiConnect(isMultiEndpoint: false); // needs to come before CanTryAddressFamily call
// Throw if remote address family doesn't match socket.
if (!CanTryAddressFamily(e.RemoteEndPoint.AddressFamily))
{
throw new NotSupportedException(SR.net_invalidversion);
}
e._socketAddress = SnapshotAndSerialize(ref endPointSnapshot);
// Do wildcard bind if socket not bound.
if (_rightEndPoint == null)
{
if (endPointSnapshot.AddressFamily == AddressFamily.InterNetwork)
{
InternalBind(new IPEndPoint(IPAddress.Any, 0));
}
else if (endPointSnapshot.AddressFamily != AddressFamily.Unix)
{
InternalBind(new IPEndPoint(IPAddress.IPv6Any, 0));
}
}
// Save the old RightEndPoint and prep new RightEndPoint.
EndPoint oldEndPoint = _rightEndPoint;
if (_rightEndPoint == null)
{
_rightEndPoint = endPointSnapshot;
}
// Prepare for the native call.
e.StartOperationCommon(this, SocketAsyncOperation.Connect);
e.StartOperationConnect(multipleConnect: null, userSocket);
// Make the native call.
SocketError socketError = SocketError.Success;
try
{
socketError = e.DoOperationConnect(this, _handle);
}
catch
{
_rightEndPoint = oldEndPoint;
// Clear in-use flag on event args object.
e.Complete();
throw;
}
pending = (socketError == SocketError.IOPending);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, pending);
return pending;
}
public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null);
bool pending;
if (e == null)
{
throw new ArgumentNullException(nameof(e));
}
if (e.HasMultipleBuffers)
{
throw new ArgumentException(SR.net_multibuffernotsupported, "BufferList");
}
if (e.RemoteEndPoint == null)
{
throw new ArgumentNullException("remoteEP");
}
EndPoint endPointSnapshot = e.RemoteEndPoint;
DnsEndPoint dnsEP = endPointSnapshot as DnsEndPoint;
if (dnsEP != null)
{
Socket attemptSocket = null;
MultipleConnectAsync multipleConnectAsync = null;
if (dnsEP.AddressFamily == AddressFamily.Unspecified)
{
// This is the only *Connect* API that fully supports multiple endpoint attempts, as it's responsible
// for creating each Socket instance and can create one per attempt.
multipleConnectAsync = new DualSocketMultipleConnectAsync(socketType, protocolType);
#pragma warning restore
}
else
{
attemptSocket = new Socket(dnsEP.AddressFamily, socketType, protocolType);
multipleConnectAsync = new SingleSocketMultipleConnectAsync(attemptSocket, userSocket: false);
}
e.StartOperationCommon(attemptSocket, SocketAsyncOperation.Connect);
e.StartOperationConnect(multipleConnectAsync, userSocket: false);
try
{
pending = multipleConnectAsync.StartConnectAsync(e, dnsEP);
}
catch
{
e.Complete(); // Clear in-use flag on event args object.
throw;
}
}
else
{
Socket attemptSocket = new Socket(endPointSnapshot.AddressFamily, socketType, protocolType);
pending = attemptSocket.ConnectAsync(e, userSocket: false);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, pending);
return pending;
}
public static void CancelConnectAsync(SocketAsyncEventArgs e)
{
if (e == null)
{
throw new ArgumentNullException(nameof(e));
}
e.CancelConnectAsync();
}
public bool DisconnectAsync(SocketAsyncEventArgs e)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
// Throw if socket disposed
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
}
// Prepare for and make the native call.
e.StartOperationCommon(this, SocketAsyncOperation.Disconnect);
SocketError socketError = SocketError.Success;
try
{
socketError = e.DoOperationDisconnect(this, _handle);
}
catch
{
// clear in-use on event arg object
e.Complete();
throw;
}
bool retval = (socketError == SocketError.IOPending);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, retval);
return retval;
}
public bool ReceiveAsync(SocketAsyncEventArgs e)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, e);
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (e == null)
{
throw new ArgumentNullException(nameof(e));
}
// Prepare for and make the native call.
e.StartOperationCommon(this, SocketAsyncOperation.Receive);
SocketError socketError;
try
{
socketError = e.DoOperationReceive(_handle);
}
catch
{
// Clear in-use flag on event args object.
e.Complete();
throw;
}
bool pending = (socketError == SocketError.IOPending);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, pending);
return pending;
}
public bool ReceiveFromAsync(SocketAsyncEventArgs e)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, e);
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (e == null)
{
throw new ArgumentNullException(nameof(e));
}
if (e.RemoteEndPoint == null)
{
throw new ArgumentNullException(nameof(e.RemoteEndPoint));
}
if (!CanTryAddressFamily(e.RemoteEndPoint.AddressFamily))
{
throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, e.RemoteEndPoint.AddressFamily, _addressFamily), "RemoteEndPoint");
}
SocketPal.CheckDualModeReceiveSupport(this);
// We don't do a CAS demand here because the contents of remoteEP aren't used by
// WSARecvFrom; all that matters is that we generate a unique-to-this-call SocketAddress
// with the right address family.
EndPoint endPointSnapshot = e.RemoteEndPoint;
e._socketAddress = SnapshotAndSerialize(ref endPointSnapshot);
// DualMode sockets may have updated the endPointSnapshot, and it has to have the same AddressFamily as
// e.m_SocketAddres for Create to work later.
e.RemoteEndPoint = endPointSnapshot;
// Prepare for and make the native call.
e.StartOperationCommon(this, SocketAsyncOperation.ReceiveFrom);
SocketError socketError;
try
{
socketError = e.DoOperationReceiveFrom(_handle);
}
catch
{
// Clear in-use flag on event args object.
e.Complete();
throw;
}
bool pending = (socketError == SocketError.IOPending);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, pending);
return pending;
}
public bool ReceiveMessageFromAsync(SocketAsyncEventArgs e)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, e);
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (e == null)
{
throw new ArgumentNullException(nameof(e));
}
if (e.RemoteEndPoint == null)
{
throw new ArgumentNullException(nameof(e.RemoteEndPoint));
}
if (!CanTryAddressFamily(e.RemoteEndPoint.AddressFamily))
{
throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, e.RemoteEndPoint.AddressFamily, _addressFamily), "RemoteEndPoint");
}
SocketPal.CheckDualModeReceiveSupport(this);
// We don't do a CAS demand here because the contents of remoteEP aren't used by
// WSARecvMsg; all that matters is that we generate a unique-to-this-call SocketAddress
// with the right address family.
EndPoint endPointSnapshot = e.RemoteEndPoint;
e._socketAddress = SnapshotAndSerialize(ref endPointSnapshot);
// DualMode may have updated the endPointSnapshot, and it has to have the same AddressFamily as
// e.m_SocketAddres for Create to work later.
e.RemoteEndPoint = endPointSnapshot;
SetReceivingPacketInformation();
// Prepare for and make the native call.
e.StartOperationCommon(this, SocketAsyncOperation.ReceiveMessageFrom);
SocketError socketError;
try
{
socketError = e.DoOperationReceiveMessageFrom(this, _handle);
}
catch
{
// Clear in-use flag on event args object.
e.Complete();
throw;
}
bool pending = (socketError == SocketError.IOPending);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, pending);
return pending;
}
public bool SendAsync(SocketAsyncEventArgs e)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, e);
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (e == null)
{
throw new ArgumentNullException(nameof(e));
}
// Prepare for and make the native call.
e.StartOperationCommon(this, SocketAsyncOperation.Send);
SocketError socketError;
try
{
socketError = e.DoOperationSend(_handle);
}
catch
{
// Clear in-use flag on event args object.
e.Complete();
throw;
}
bool pending = (socketError == SocketError.IOPending);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, pending);
return pending;
}
public bool SendPacketsAsync(SocketAsyncEventArgs e)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, e);
// Throw if socket disposed
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (e == null)
{
throw new ArgumentNullException(nameof(e));
}
if (e.SendPacketsElements == null)
{
throw new ArgumentNullException("e.SendPacketsElements");
}
if (!Connected)
{
throw new NotSupportedException(SR.net_notconnected);
}
// Prepare for and make the native call.
e.StartOperationCommon(this, SocketAsyncOperation.SendPackets);
SocketError socketError;
try
{
socketError = e.DoOperationSendPackets(this, _handle);
}
catch (Exception)
{
// Clear in-use flag on event args object.
e.Complete();
throw;
}
bool pending = (socketError == SocketError.IOPending);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, pending);
return pending;
}
public bool SendToAsync(SocketAsyncEventArgs e)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, e);
if (CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (e == null)
{
throw new ArgumentNullException(nameof(e));
}
if (e.RemoteEndPoint == null)
{
throw new ArgumentNullException(nameof(RemoteEndPoint));
}
// Prepare SocketAddress
EndPoint endPointSnapshot = e.RemoteEndPoint;
e._socketAddress = SnapshotAndSerialize(ref endPointSnapshot);
// Prepare for and make the native call.
e.StartOperationCommon(this, SocketAsyncOperation.SendTo);
SocketError socketError;
try
{
socketError = e.DoOperationSendTo(_handle);
}
catch
{
// Clear in-use flag on event args object.
e.Complete();
throw;
}
bool retval = (socketError == SocketError.IOPending);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, retval);
return retval;
}
#endregion
#endregion
#region Internal and private properties
private static object InternalSyncObject
{
get
{
if (s_internalSyncObject == null)
{
object o = new object();
Interlocked.CompareExchange(ref s_internalSyncObject, o, null);
}
return s_internalSyncObject;
}
}
private CacheSet Caches
{
get
{
if (_caches == null)
{
// It's not too bad if extra of these are created and lost.
_caches = new CacheSet();
}
return _caches;
}
}
internal bool CleanedUp
{
get
{
return (_intCleanedUp == 1);
}
}
internal TransportType Transport
{
get
{
return
_protocolType == Sockets.ProtocolType.Tcp ?
TransportType.Tcp :
_protocolType == Sockets.ProtocolType.Udp ?
TransportType.Udp :
TransportType.All;
}
}
#endregion
#region Internal and private methods
internal static void GetIPProtocolInformation(AddressFamily addressFamily, Internals.SocketAddress socketAddress, out bool isIPv4, out bool isIPv6)
{
bool isIPv4MappedToIPv6 = socketAddress.Family == AddressFamily.InterNetworkV6 && socketAddress.GetIPAddress().IsIPv4MappedToIPv6;
isIPv4 = addressFamily == AddressFamily.InterNetwork || isIPv4MappedToIPv6; // DualMode
isIPv6 = addressFamily == AddressFamily.InterNetworkV6;
}
internal static int GetAddressSize(EndPoint endPoint)
{
AddressFamily fam = endPoint.AddressFamily;
return
fam == AddressFamily.InterNetwork ? SocketAddressPal.IPv4AddressSize :
fam == AddressFamily.InterNetworkV6 ? SocketAddressPal.IPv6AddressSize :
endPoint.Serialize().Size;
}
private Internals.SocketAddress SnapshotAndSerialize(ref EndPoint remoteEP)
{
if (remoteEP is IPEndPoint ipSnapshot)
{
// Snapshot to avoid external tampering and malicious derivations if IPEndPoint.
ipSnapshot = ipSnapshot.Snapshot();
// DualMode: return an IPEndPoint mapped to an IPv6 address.
remoteEP = RemapIPEndPoint(ipSnapshot);
}
else if (remoteEP is DnsEndPoint)
{
throw new ArgumentException(SR.Format(SR.net_sockets_invalid_dnsendpoint, nameof(remoteEP)), nameof(remoteEP));
}
return IPEndPointExtensions.Serialize(remoteEP);
}
// DualMode: automatically re-map IPv4 addresses to IPv6 addresses.
private IPEndPoint RemapIPEndPoint(IPEndPoint input)
{
if (input.AddressFamily == AddressFamily.InterNetwork && IsDualMode)
{
return new IPEndPoint(input.Address.MapToIPv6(), input.Port);
}
return input;
}
internal static void InitializeSockets()
{
if (!s_initialized)
{
InitializeSocketsCore();
}
void InitializeSocketsCore()
{
lock (InternalSyncObject)
{
if (!s_initialized)
{
SocketPal.Initialize();
s_initialized = true;
}
}
}
}
private void DoConnect(EndPoint endPointSnapshot, Internals.SocketAddress socketAddress)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, endPointSnapshot);
SocketError errorCode = SocketPal.Connect(_handle, socketAddress.Buffer, socketAddress.Size);
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled)
{
try
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} Interop.Winsock.WSAConnect returns errorCode:{errorCode}");
}
catch (ObjectDisposedException) { }
}
#endif
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
// Update the internal state of this socket according to the error before throwing.
SocketException socketException = SocketExceptionFactory.CreateSocketException((int)errorCode, endPointSnapshot);
UpdateStatusAfterSocketError(socketException);
if (NetEventSource.IsEnabled) NetEventSource.Error(this, socketException);
throw socketException;
}
if (_rightEndPoint == null)
{
// Save a copy of the EndPoint so we can use it for Create().
_rightEndPoint = endPointSnapshot;
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"connection to:{endPointSnapshot}");
// Update state and performance counters.
SetToConnected();
if (NetEventSource.IsEnabled)
{
NetEventSource.Connected(this, LocalEndPoint, RemoteEndPoint);
NetEventSource.Exit(this);
}
}
protected virtual void Dispose(bool disposing)
{
if (!disposing)
{
return;
}
if (NetEventSource.IsEnabled)
{
try
{
NetEventSource.Info(this, $"disposing:true CleanedUp:{CleanedUp}");
NetEventSource.Enter(this);
}
catch (Exception exception) when (!ExceptionCheck.IsFatal(exception)) { }
}
// Make sure we're the first call to Dispose
if (Interlocked.CompareExchange(ref _intCleanedUp, 1, 0) == 1)
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
return;
}
SetToDisconnected();
// Close the handle in one of several ways depending on the timeout.
// Ignore ObjectDisposedException just in case the handle somehow gets disposed elsewhere.
try
{
int timeout = _closeTimeout;
if (timeout == 0)
{
// Abortive.
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling _handle.Dispose()");
_handle.Dispose();
}
else
{
SocketError errorCode;
// Go to blocking mode.
if (!_willBlock || !_willBlockInternal)
{
bool willBlock;
errorCode = SocketPal.SetBlocking(_handle, false, out willBlock);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{_handle} ioctlsocket(FIONBIO):{errorCode}");
}
if (timeout < 0)
{
// Close with existing user-specified linger option.
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling _handle.CloseAsIs()");
_handle.CloseAsIs();
}
else
{
// Since our timeout is in ms and linger is in seconds, implement our own sortof linger here.
errorCode = SocketPal.Shutdown(_handle, _isConnected, _isDisconnected, SocketShutdown.Send);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{_handle} shutdown():{errorCode}");
// This should give us a timeout in milliseconds.
errorCode = SocketPal.SetSockOpt(
_handle,
SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout,
timeout);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{_handle} setsockopt():{errorCode}");
if (errorCode != SocketError.Success)
{
_handle.Dispose();
}
else
{
int unused;
errorCode = SocketPal.Receive(_handle, Array.Empty<byte>(), 0, 0, SocketFlags.None, out unused);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{_handle} recv():{errorCode}");
if (errorCode != (SocketError)0)
{
// We got a timeout - abort.
_handle.Dispose();
}
else
{
// We got a FIN or data. Use ioctlsocket to find out which.
int dataAvailable = 0;
errorCode = SocketPal.GetAvailable(_handle, out dataAvailable);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{_handle} ioctlsocket(FIONREAD):{errorCode}");
if (errorCode != SocketError.Success || dataAvailable != 0)
{
// If we have data or don't know, safest thing is to reset.
_handle.Dispose();
}
else
{
// We got a FIN. It'd be nice to block for the remainder of the timeout for the handshake to finish.
// Since there's no real way to do that, close the socket with the user's preferences. This lets
// the user decide how best to handle this case via the linger options.
_handle.CloseAsIs();
}
}
}
}
}
}
catch (ObjectDisposedException)
{
NetEventSource.Fail(this, $"handle:{_handle}, Closing the handle threw ObjectDisposedException.");
}
// Clean up any cached data
DisposeCachedTaskSocketAsyncEventArgs();
}
public void Dispose()
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(this, $"timeout = {_closeTimeout}");
NetEventSource.Enter(this);
}
Dispose(true);
GC.SuppressFinalize(this);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
~Socket()
{
Dispose(false);
}
// This version does not throw.
internal void InternalShutdown(SocketShutdown how)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"how:{how}");
if (CleanedUp || _handle.IsInvalid)
{
return;
}
try
{
SocketPal.Shutdown(_handle, _isConnected, _isDisconnected, how);
}
catch (ObjectDisposedException) { }
}
// Set the socket option to begin receiving packet information if it has not been
// set for this socket previously.
internal void SetReceivingPacketInformation()
{
if (!_receivingPacketInformation)
{
// DualMode: When bound to IPv6Any you must enable both socket options.
// When bound to an IPv4 mapped IPv6 address you must enable the IPv4 socket option.
IPEndPoint ipEndPoint = _rightEndPoint as IPEndPoint;
IPAddress boundAddress = (ipEndPoint != null ? ipEndPoint.Address : null);
Debug.Assert(boundAddress != null, "Not Bound");
if (_addressFamily == AddressFamily.InterNetwork)
{
SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
}
if ((boundAddress != null && IsDualMode && (boundAddress.IsIPv4MappedToIPv6 || boundAddress.Equals(IPAddress.IPv6Any))))
{
SocketPal.SetReceivingDualModeIPv4PacketInformation(this);
}
if (_addressFamily == AddressFamily.InterNetworkV6
&& (boundAddress == null || !boundAddress.IsIPv4MappedToIPv6))
{
SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.PacketInformation, true);
}
_receivingPacketInformation = true;
}
}
internal unsafe void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue, bool silent)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"optionLevel:{optionLevel} optionName:{optionName} optionValue:{optionValue} silent:{silent}");
if (silent && (CleanedUp || _handle.IsInvalid))
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "skipping the call");
return;
}
SocketError errorCode = SocketError.Success;
try
{
errorCode = SocketPal.SetSockOpt(_handle, optionLevel, optionName, optionValue);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.setsockopt returns errorCode:{errorCode}");
}
catch
{
if (silent && _handle.IsInvalid)
{
return;
}
throw;
}
// Keep the internal state in sync if the user manually resets this.
if (optionName == SocketOptionName.PacketInformation && optionValue == 0 &&
errorCode == SocketError.Success)
{
_receivingPacketInformation = false;
}
if (silent)
{
return;
}
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
}
private void SetMulticastOption(SocketOptionName optionName, MulticastOption MR)
{
SocketError errorCode = SocketPal.SetMulticastOption(_handle, optionName, MR);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.setsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
}
// IPv6 setsockopt for JOIN / LEAVE multicast group.
private void SetIPv6MulticastOption(SocketOptionName optionName, IPv6MulticastOption MR)
{
SocketError errorCode = SocketPal.SetIPv6MulticastOption(_handle, optionName, MR);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.setsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
}
private void SetLingerOption(LingerOption lref)
{
SocketError errorCode = SocketPal.SetLingerOption(_handle, lref);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.setsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
}
private LingerOption GetLingerOpt()
{
LingerOption lingerOption;
SocketError errorCode = SocketPal.GetLingerOption(_handle, out lingerOption);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
return lingerOption;
}
private MulticastOption GetMulticastOpt(SocketOptionName optionName)
{
MulticastOption multicastOption;
SocketError errorCode = SocketPal.GetMulticastOption(_handle, optionName, out multicastOption);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
return multicastOption;
}
// IPv6 getsockopt for JOIN / LEAVE multicast group.
private IPv6MulticastOption GetIPv6MulticastOpt(SocketOptionName optionName)
{
IPv6MulticastOption multicastOption;
SocketError errorCode = SocketPal.GetIPv6MulticastOption(_handle, optionName, out multicastOption);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
// Throw an appropriate SocketException if the native call fails.
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
return multicastOption;
}
// This method will ignore failures, but returns the win32
// error code, and will update internal state on success.
private SocketError InternalSetBlocking(bool desired, out bool current)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"desired:{desired} willBlock:{_willBlock} willBlockInternal:{_willBlockInternal}");
if (CleanedUp)
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, "ObjectDisposed");
current = _willBlock;
return SocketError.Success;
}
// Can we avoid this call if willBlockInternal is already correct?
bool willBlock = false;
SocketError errorCode;
try
{
errorCode = SocketPal.SetBlocking(_handle, desired, out willBlock);
}
catch (ObjectDisposedException)
{
errorCode = SocketError.NotSocket;
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.ioctlsocket returns errorCode:{errorCode}");
// We will update only internal state but only on successfull win32 call
// so if the native call fails, the state will remain the same.
if (errorCode == SocketError.Success)
{
_willBlockInternal = willBlock;
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"errorCode:{errorCode} willBlock:{_willBlock} willBlockInternal:{_willBlockInternal}");
current = _willBlockInternal;
return errorCode;
}
// This method ignores all failures.
internal void InternalSetBlocking(bool desired)
{
bool current;
InternalSetBlocking(desired, out current);
}
// Implements ConnectEx - this provides completion port IO and support for disconnect and reconnects.
// Since this is private, the unsafe mode is specified with a flag instead of an overload.
private IAsyncResult BeginConnectEx(EndPoint remoteEP, bool flowContext, AsyncCallback callback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
EndPoint endPointSnapshot = remoteEP;
Internals.SocketAddress socketAddress = SnapshotAndSerialize(ref endPointSnapshot);
// The socket must be bound first.
// The calling method--BeginConnect--will ensure that this method is only
// called if _rightEndPoint is not null, of that the endpoint is an IPEndPoint.
if (_rightEndPoint == null)
{
if (endPointSnapshot.AddressFamily == AddressFamily.InterNetwork)
{
InternalBind(new IPEndPoint(IPAddress.Any, 0));
}
else if (endPointSnapshot.AddressFamily != AddressFamily.Unix)
{
InternalBind(new IPEndPoint(IPAddress.IPv6Any, 0));
}
}
// Allocate the async result and the event we'll pass to the thread pool.
ConnectOverlappedAsyncResult asyncResult = new ConnectOverlappedAsyncResult(this, endPointSnapshot, state, callback);
// If context flowing is enabled, set it up here. No need to lock since the context isn't used until the callback.
if (flowContext)
{
asyncResult.StartPostingAsyncOp(false);
}
EndPoint oldEndPoint = _rightEndPoint;
if (_rightEndPoint == null)
{
_rightEndPoint = endPointSnapshot;
}
SocketError errorCode;
try
{
errorCode = SocketPal.ConnectAsync(this, _handle, socketAddress.Buffer, socketAddress.Size, asyncResult);
}
catch
{
// _rightEndPoint will always equal oldEndPoint.
_rightEndPoint = oldEndPoint;
throw;
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.connect returns:{errorCode}");
if (errorCode == SocketError.Success)
{
// Synchronous success. Indicate that we're connected.
SetToConnected();
}
if (!CheckErrorAndUpdateStatus(errorCode))
{
// Update the internal state of this socket according to the error before throwing.
_rightEndPoint = oldEndPoint;
throw new SocketException((int)errorCode);
}
// We didn't throw, so indicate that we're returning this result to the user. This may call the callback.
// This is a nop if the context isn't being flowed.
asyncResult.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(this, $"{endPointSnapshot} returning AsyncResult:{asyncResult}");
NetEventSource.Exit(this, asyncResult);
}
return asyncResult;
}
private static void DnsCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
bool invokeCallback = false;
MultipleAddressConnectAsyncResult context = (MultipleAddressConnectAsyncResult)result.AsyncState;
try
{
invokeCallback = DoDnsCallback(result, context);
}
catch (Exception exception)
{
context.InvokeCallback(exception);
}
// Invoke the callback outside of the try block so we don't catch user exceptions.
if (invokeCallback)
{
context.InvokeCallback();
}
}
private static bool DoDnsCallback(IAsyncResult result, MultipleAddressConnectAsyncResult context)
{
IPAddress[] addresses = Dns.EndGetHostAddresses(result);
context._addresses = addresses;
return DoMultipleAddressConnectCallback(PostOneBeginConnect(context), context);
}
private sealed class ConnectAsyncResult : ContextAwareResult
{
private EndPoint _endPoint;
internal ConnectAsyncResult(object myObject, EndPoint endPoint, object myState, AsyncCallback myCallBack) :
base(myObject, myState, myCallBack)
{
_endPoint = endPoint;
}
internal override EndPoint RemoteEndPoint
{
get { return _endPoint; }
}
}
private sealed class MultipleAddressConnectAsyncResult : ContextAwareResult
{
internal MultipleAddressConnectAsyncResult(IPAddress[] addresses, int port, Socket socket, object myState, AsyncCallback myCallBack) :
base(socket, myState, myCallBack)
{
_addresses = addresses;
_port = port;
_socket = socket;
}
internal Socket _socket; // Keep this member just to avoid all the casting.
internal IPAddress[] _addresses;
internal int _index;
internal int _port;
internal Exception _lastException;
internal override EndPoint RemoteEndPoint
{
get
{
if (_addresses != null && _index > 0 && _index < _addresses.Length)
{
return new IPEndPoint(_addresses[_index], _port);
}
else
{
return null;
}
}
}
}
private static AsyncCallback s_multipleAddressConnectCallback;
private static AsyncCallback CachedMultipleAddressConnectCallback
{
get
{
if (s_multipleAddressConnectCallback == null)
{
s_multipleAddressConnectCallback = new AsyncCallback(MultipleAddressConnectCallback);
}
return s_multipleAddressConnectCallback;
}
}
private static object PostOneBeginConnect(MultipleAddressConnectAsyncResult context)
{
IPAddress currentAddressSnapshot = context._addresses[context._index];
context._socket.ReplaceHandleIfNecessaryAfterFailedConnect();
if (!context._socket.CanTryAddressFamily(currentAddressSnapshot.AddressFamily))
{
return context._lastException != null ? context._lastException : new ArgumentException(SR.net_invalidAddressList, nameof(context));
}
try
{
EndPoint endPoint = new IPEndPoint(currentAddressSnapshot, context._port);
context._socket.SnapshotAndSerialize(ref endPoint);
IAsyncResult connectResult = context._socket.UnsafeBeginConnect(endPoint, CachedMultipleAddressConnectCallback, context);
if (connectResult.CompletedSynchronously)
{
return connectResult;
}
}
catch (Exception exception) when (!(exception is OutOfMemoryException))
{
return exception;
}
return null;
}
private static void MultipleAddressConnectCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
bool invokeCallback = false;
MultipleAddressConnectAsyncResult context = (MultipleAddressConnectAsyncResult)result.AsyncState;
try
{
invokeCallback = DoMultipleAddressConnectCallback(result, context);
}
catch (Exception exception)
{
context.InvokeCallback(exception);
}
// Invoke the callback outside of the try block so we don't catch user Exceptions.
if (invokeCallback)
{
context.InvokeCallback();
}
}
// This is like a regular async callback worker, except the result can be an exception. This is a useful pattern when
// processing should continue whether or not an async step failed.
private static bool DoMultipleAddressConnectCallback(object result, MultipleAddressConnectAsyncResult context)
{
while (result != null)
{
Exception ex = result as Exception;
if (ex == null)
{
try
{
context._socket.EndConnect((IAsyncResult)result);
}
catch (Exception exception)
{
ex = exception;
}
}
if (ex == null)
{
// Don't invoke the callback from here, because we're probably inside
// a catch-all block that would eat exceptions from the callback.
// Instead tell our caller to invoke the callback outside of its catchall.
return true;
}
else
{
if (++context._index >= context._addresses.Length)
{
ExceptionDispatchInfo.Throw(ex);
}
context._lastException = ex;
result = PostOneBeginConnect(context);
}
}
// Don't invoke the callback at all, because we've posted another async connection attempt.
return false;
}
// CreateAcceptSocket - pulls unmanaged results and assembles them into a new Socket object.
internal Socket CreateAcceptSocket(SafeSocketHandle fd, EndPoint remoteEP)
{
// Internal state of the socket is inherited from listener.
Debug.Assert(fd != null && !fd.IsInvalid);
Socket socket = new Socket(fd);
return UpdateAcceptSocket(socket, remoteEP);
}
internal Socket UpdateAcceptSocket(Socket socket, EndPoint remoteEP)
{
// Internal state of the socket is inherited from listener.
socket._addressFamily = _addressFamily;
socket._socketType = _socketType;
socket._protocolType = _protocolType;
socket._rightEndPoint = _rightEndPoint;
socket._remoteEndPoint = remoteEP;
// The socket is connected.
socket.SetToConnected();
// if the socket is returned by an End(), the socket might have
// inherited the WSAEventSelect() call from the accepting socket.
// we need to cancel this otherwise the socket will be in non-blocking
// mode and we cannot force blocking mode using the ioctlsocket() in
// Socket.set_Blocking(), since it fails returning 10022 as documented in MSDN.
// (note that the m_AsyncEvent event will not be created in this case.
socket._willBlock = _willBlock;
// We need to make sure the Socket is in the right blocking state
// even if we don't have to call UnsetAsyncEventSelect
socket.InternalSetBlocking(_willBlock);
return socket;
}
internal void SetToConnected()
{
if (_isConnected)
{
// Socket was already connected.
return;
}
// Update the status: this socket was indeed connected at
// some point in time update the perf counter as well.
_isConnected = true;
_isDisconnected = false;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "now connected");
}
internal void SetToDisconnected()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (!_isConnected)
{
// Socket was already disconnected.
return;
}
// Update the status: this socket was indeed disconnected at
// some point in time, clear any async select bits.
_isConnected = false;
_isDisconnected = true;
if (!CleanedUp)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "!CleanedUp");
}
}
private void UpdateStatusAfterSocketErrorAndThrowException(SocketError error, [CallerMemberName] string callerName = null)
{
// Update the internal state of this socket according to the error before throwing.
var socketException = new SocketException((int)error);
UpdateStatusAfterSocketError(socketException);
if (NetEventSource.IsEnabled) NetEventSource.Error(this, socketException, memberName: callerName);
throw socketException;
}
// UpdateStatusAfterSocketError(socketException) - updates the status of a connected socket
// on which a failure occurred. it'll go to winsock and check if the connection
// is still open and if it needs to update our internal state.
internal void UpdateStatusAfterSocketError(SocketException socketException)
{
UpdateStatusAfterSocketError(socketException.SocketErrorCode);
}
internal void UpdateStatusAfterSocketError(SocketError errorCode)
{
// If we already know the socket is disconnected
// we don't need to do anything else.
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"errorCode:{errorCode}");
if (_isConnected && (_handle.IsInvalid || (errorCode != SocketError.WouldBlock &&
errorCode != SocketError.IOPending && errorCode != SocketError.NoBufferSpaceAvailable &&
errorCode != SocketError.TimedOut)))
{
// The socket is no longer a valid socket.
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Invalidating socket.");
SetToDisconnected();
}
}
private bool CheckErrorAndUpdateStatus(SocketError errorCode)
{
if (errorCode == SocketError.Success || errorCode == SocketError.IOPending)
{
return true;
}
UpdateStatusAfterSocketError(errorCode);
return false;
}
// ValidateBlockingMode - called before synchronous calls to validate
// the fact that we are in blocking mode (not in non-blocking mode) so the
// call will actually be synchronous.
private void ValidateBlockingMode()
{
if (_willBlock && !_willBlockInternal)
{
throw new InvalidOperationException(SR.net_invasync);
}
}
// Validates that the Socket can be used to try another Connect call, in case
// a previous call failed and the platform does not support that. In some cases,
// the call may also be able to "fix" the Socket to continue working, even if the
// platform wouldn't otherwise support it. Windows always supports this.
partial void ValidateForMultiConnect(bool isMultiEndpoint);
// Helper for SendFile implementations
private static FileStream OpenFile(string name) => string.IsNullOrEmpty(name) ? null : File.OpenRead(name);
#endregion
}
}
| 38.590596 | 243 | 0.570493 | [
"MIT"
] | Drawaes/corefx | src/System.Net.Sockets/src/System/Net/Sockets/Socket.cs | 201,906 | C# |
using System;
using Microsoft.Extensions.DependencyInjection;
using R5T.Dacia;
namespace R5T.D0003.Default
{
public static class IServiceCollectionExtension
{
/// <summary>
/// Adds the <see cref="ProcessStartTimeProvider"/> implementation of <see cref="IProcessStartTimeProvider"/> as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddDefaultProcessStartTimeProvider(this IServiceCollection services)
{
services.AddSingleton<IProcessStartTimeProvider, ProcessStartTimeProvider>();
return services;
}
/// <summary>
/// Adds the <see cref="ProcessStartTimeProvider"/> implementation of <see cref="IProcessStartTimeProvider"/> as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static ServiceAction<IProcessStartTimeProvider> AddDefaultProcessStartTimeProviderAction(this IServiceCollection services)
{
var serviceAction = ServiceAction<IProcessStartTimeProvider>.New(() => services.AddDefaultProcessStartTimeProvider());
return serviceAction;
}
}
}
| 37.59375 | 164 | 0.679967 | [
"MIT"
] | MinexAutomation/R5T.D0003 | source/R5T.D0003.Default/Code/Services/Extensions/IServiceCollectionExtension.cs | 1,205 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.UI.Xaml.Documents
{
#if false || false || false || false || false
[global::Uno.NotImplemented]
#endif
public partial class HyperlinkClickEventArgs : global::Windows.UI.Xaml.RoutedEventArgs
{
}
}
| 26.666667 | 88 | 0.746875 | [
"Apache-2.0"
] | 06needhamt/uno | src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Documents/HyperlinkClickEventArgs.cs | 320 | C# |
namespace Machete.Internals.Extensions
{
using Mapping;
using Reflection;
public interface ITypeCache<T>
{
IDictionaryConverter Mapper { get; }
string ShortName { get; }
IReadOnlyPropertyCache<T> ReadOnlyPropertyCache { get; }
IReadWritePropertyCache<T> ReadWritePropertyCache { get; }
T InitializeFromObject(object values);
T InitializeFromObject<TInput>(TInput value);
}
} | 27.176471 | 67 | 0.65368 | [
"Apache-2.0"
] | amccool/Machete | src/Machete/Internals/Extensions/ITypeCache.cs | 464 | C# |
using System;
using System.Diagnostics;
using System.Timers;
namespace Launcher
{
public class ProcessMonitor
{
private Timer monitor;
private readonly string processName;
private readonly Action<ProcessMonitor> aliveCallback;
private readonly Action<ProcessMonitor> exitCallback;
public ProcessMonitor(string processName, double interval, Action<ProcessMonitor> aliveCallback, Action<ProcessMonitor> exitCallback)
{
monitor = new Timer(interval);
monitor.Elapsed += OnPollEvent;
monitor.AutoReset = true;
this.processName = processName;
this.aliveCallback = aliveCallback;
this.exitCallback = exitCallback;
}
public void Start()
{
monitor.Enabled = true;
}
public void Stop()
{
monitor.Enabled = false;
}
private void OnPollEvent(object source, ElapsedEventArgs e)
{
Process[] clientProcess = Process.GetProcessesByName(processName);
// client instances still running
if (clientProcess.Length > 0)
{
aliveCallback(this);
return;
}
// all client instances stopped running
exitCallback(this);
}
}
}
| 21.470588 | 135 | 0.72968 | [
"MIT"
] | CUPNS/Sealed2 | Launcher/Utils/ProcessMonitor.cs | 1,097 | C# |
using grapher.Models.Options.Directionality;
using grapher.Models.Serialized;
using System;
using System.Drawing;
using System.Windows.Forms;
namespace grapher.Models.Options
{
public class ApplyOptions
{
#region Constructors
public ApplyOptions(
CheckBox byComponentVectorXYLock,
AccelOptionSet optionSetX,
AccelOptionSet optionSetY,
DirectionalityOptions directionalityOptions,
Option sensitivity,
LockableOption yxRatio,
Option rotation,
Label lockXYLabel,
AccelCharts accelCharts)
{
Directionality = directionalityOptions;
WholeVectorCheckBox = Directionality.WholeCheckBox;
ByComponentVectorCheckBox = Directionality.ByComponentCheckBox;
WholeVectorCheckBox.Click += new System.EventHandler(OnWholeClicked);
ByComponentVectorCheckBox.Click += new System.EventHandler(OnByComponentClicked);
WholeVectorCheckBox.CheckedChanged += new System.EventHandler(OnWholeCheckedChange);
ByComponentVectorCheckBox.CheckedChanged += new System.EventHandler(OnByComponentCheckedChange);
ByComponentVectorXYLock = byComponentVectorXYLock;
OptionSetX = optionSetX;
OptionSetY = optionSetY;
Sensitivity = sensitivity;
YToXRatio = yxRatio;
Rotation = rotation;
LockXYLabel = lockXYLabel;
AccelCharts = accelCharts;
LockXYLabel.AutoSize = false;
LockXYLabel.TextAlign = ContentAlignment.MiddleCenter;
ByComponentVectorXYLock.CheckedChanged += new System.EventHandler(OnByComponentXYLockChecked);
ByComponentVectorXYLock.Checked = true;
YToXRatio.SnapTo(Sensitivity);
Rotation.SnapTo(YToXRatio);
EnableWholeApplication();
}
#endregion Constructors
#region Properties
public CheckBox WholeVectorCheckBox { get; }
public CheckBox ByComponentVectorCheckBox { get; }
public CheckBox ByComponentVectorXYLock { get; }
public AccelOptionSet OptionSetX { get; }
public AccelOptionSet OptionSetY { get; }
public DirectionalityOptions Directionality { get; }
public Option Sensitivity { get; }
public LockableOption YToXRatio { get; }
public Option Rotation { get; }
public AccelCharts AccelCharts { get; }
public Label ActiveValueTitleY { get; }
public Label LockXYLabel { get; }
public bool IsWhole { get; private set; }
#endregion Properties
#region Methods
public void SetArgsFromActiveValues(ref AccelArgs argsX, ref AccelArgs argsY)
{
OptionSetX.SetArgsFromActiveValues(ref argsX);
if (ByComponentVectorXYLock.Checked)
{
OptionSetX.SetArgsFromActiveValues(ref argsY);
}
else
{
OptionSetY.SetArgsFromActiveValues(ref argsY);
}
}
public void SetActiveValues(Profile settings)
{
Sensitivity.SetActiveValue(settings.sensitivity);
YToXRatio.SetActiveValue(settings.yxSensRatio);
Rotation.SetActiveValue(settings.rotation);
WholeVectorCheckBox.Checked = settings.combineMagnitudes;
ByComponentVectorCheckBox.Checked = !settings.combineMagnitudes;
ByComponentVectorXYLock.Checked = settings.argsX.Equals(settings.argsY);
OptionSetX.SetActiveValues(ref settings.argsX);
OptionSetY.SetActiveValues(ref settings.argsY);
Directionality.SetActiveValues(settings);
AccelCharts.SetLogarithmic(
OptionSetX.Options.AccelerationType.LogarithmicCharts,
OptionSetY.Options.AccelerationType.LogarithmicCharts);
}
public void OnWholeClicked(object sender, EventArgs e)
{
if (!WholeVectorCheckBox.Checked)
{
WholeVectorCheckBox.Checked = true;
ByComponentVectorCheckBox.Checked = false;
Directionality.ToWhole();
}
}
public void OnByComponentClicked(object sender, EventArgs e)
{
if (!ByComponentVectorCheckBox.Checked)
{
WholeVectorCheckBox.Checked = false;
ByComponentVectorCheckBox.Checked = true;
Directionality.ToByComponent();
}
}
public void OnWholeCheckedChange(object sender, EventArgs e)
{
if (WholeVectorCheckBox.Checked)
{
EnableWholeApplication();
}
}
public void OnByComponentCheckedChange(object sender, EventArgs e)
{
if (ByComponentVectorCheckBox.Checked)
{
EnableByComponentApplication();
}
}
public void ShowWholeSet()
{
OptionSetX.SetRegularMode();
OptionSetY.Hide();
//SetActiveTitlesWhole();
}
public void ShowByComponentAsOneSet()
{
OptionSetX.SetTitleMode("X = Y");
OptionSetY.Hide();
//SetActiveTitlesByComponents();
}
public void ShowByComponentAsTwoSets()
{
OptionSetX.SetTitleMode("X");
OptionSetY.SetTitleMode("Y");
OptionSetY.Show();
}
public void ShowByComponentSet()
{
if (ByComponentVectorXYLock.Checked)
{
ShowByComponentAsOneSet();
}
else
{
ShowByComponentAsTwoSets();
}
}
private void OnByComponentXYLockChecked(object sender, EventArgs e)
{
if (!IsWhole)
{
ShowByComponentSet();
}
}
public void EnableWholeApplication()
{
IsWhole = true;
ByComponentVectorXYLock.Hide();
ShowWholeSet();
}
public void EnableByComponentApplication()
{
IsWhole = false;
ByComponentVectorXYLock.Show();
ShowByComponentSet();
}
private void SetActiveTitlesWhole()
{
OptionSetX.ActiveValuesTitle.Left = OptionSetX.Options.Left + OptionSetX.Options.Width;
LockXYLabel.Width = (AccelCharts.Left - OptionSetX.ActiveValuesTitle.Left) / 2;
OptionSetX.ActiveValuesTitle.Width = LockXYLabel.Width;
LockXYLabel.Left = OptionSetX.ActiveValuesTitle.Left + OptionSetX.ActiveValuesTitle.Width;
YToXRatio.LockBox.Left = LockXYLabel.Left + LockXYLabel.Width / 2 - YToXRatio.LockBox.Width / 2;
ByComponentVectorXYLock.Left = YToXRatio.LockBox.Left;
AlignActiveValues();
}
private void SetActiveTitlesByComponents()
{
OptionSetY.ActiveValuesTitle.Left = OptionSetY.Options.Left + OptionSetY.Options.Width;
OptionSetY.ActiveValuesTitle.Width = Constants.NarrowChartLeft - OptionSetY.ActiveValuesTitle.Left;
AlignActiveValues();
}
private void AlignActiveValues()
{
OptionSetX.AlignActiveValues();
OptionSetY.AlignActiveValues();
Sensitivity.AlignActiveValues();
Rotation.AlignActiveValues();
}
#endregion Methods
}
}
| 31.487603 | 111 | 0.603675 | [
"MIT"
] | Conrekatsu/rawaccel | grapher/Models/Options/ApplyOptions.cs | 7,622 | C# |
using System;
using JSIL;
public static class Program {
public static void Main(string[] args)
{
var arr = ((object[]) Verbatim.Expression("[1,2,3]")) ?? new object[] {1, 2, 3};
var arr2 = (object[]) arr.Clone();
foreach (var item in arr2)
{
Console.Write(item);
}
}
} | 23.785714 | 88 | 0.528529 | [
"MIT"
] | RedpointGames/JSIL | Tests/SimpleTestCases/ArrayCloneNative_Issue932.cs | 333 | C# |
namespace SayWhatStarterWebhook.Models.Messages
{
public class ButtonOpenUriAction
{
public string Uri { get; set; }
}
} | 20.142857 | 48 | 0.673759 | [
"MIT"
] | MFazio23/TC2018-SayWhatStarter | csharp/SayWhatStarterWebhook/Models/Messages/ButtonOpenUriAction.cs | 143 | C# |
/*
* Ory Kratos API
*
* Documentation for all public and administrative Ory Kratos APIs. Public and administrative APIs are exposed on different ports. Public APIs can face the public internet without any protection while administrative APIs should never be exposed without prior authorization. To protect the administative API port you should use something like Nginx, Ory Oathkeeper, or any other technology capable of authorizing incoming requests.
*
* The version of the OpenAPI document: v0.7.6-alpha.7
* Contact: hi@ory.sh
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Ory.Kratos.Client.Api;
using Ory.Kratos.Client.Model;
using Ory.Kratos.Client.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace Ory.Kratos.Client.Test.Model
{
/// <summary>
/// Class for testing KratosHealthStatus
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class KratosHealthStatusTests : IDisposable
{
// TODO uncomment below to declare an instance variable for KratosHealthStatus
//private KratosHealthStatus instance;
public KratosHealthStatusTests()
{
// TODO uncomment below to create an instance of KratosHealthStatus
//instance = new KratosHealthStatus();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of KratosHealthStatus
/// </summary>
[Fact]
public void KratosHealthStatusInstanceTest()
{
// TODO uncomment below to test "IsType" KratosHealthStatus
//Assert.IsType<KratosHealthStatus>(instance);
}
/// <summary>
/// Test the property 'Status'
/// </summary>
[Fact]
public void StatusTest()
{
// TODO unit test for the property 'Status'
}
}
}
| 30.513889 | 431 | 0.663177 | [
"Apache-2.0"
] | tobbbles/sdk | clients/kratos/dotnet/src/Ory.Kratos.Client.Test/Model/KratosHealthStatusTests.cs | 2,197 | C# |
using Session06.NoneRelational.DAL;
using System;
namespace Session06.NoneRelational.UI
{
class Program
{
static void Main(string[] args)
{
BlogContext blogContext = new BlogContext();
blogContext.Database.EnsureDeleted();
blogContext.Database.EnsureCreated();
Console.WriteLine("Hello World!");
}
}
}
| 21.611111 | 56 | 0.611825 | [
"Apache-2.0"
] | IMICTO/dotnetcore3 | Session06/Session06.NoneRelational/Session06.NoneRelational.UI/Program.cs | 391 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ThreeEqualNumbers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ThreeEqualNumbers")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ae01be9a-24ac-4e75-b10d-0a672dced73c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.027027 | 84 | 0.746979 | [
"MIT"
] | pavlinpetkov88/ProgramingBasic | SimpleConditionalStatements/ThreeEqualNumbers/Properties/AssemblyInfo.cs | 1,410 | C# |
namespace Chisel.Import.Source.VPKTools
{
struct VTFHeader
{
public const int signature = 0x00465456; // File signature ("VTF\0"). (or as little-endian integer, 0x00465456)
public float version; // (Sizeof 2) version[0].version[1].
public uint headerSize; // Size of the header struct (16 byte aligned; currently 80 bytes).
public ushort width; // Width of the largest mipmap in pixels. Must be a power of 2.
public ushort height; // Height of the largest mipmap in pixels. Must be a power of 2.
public uint flags; // VTF flags.
public ushort frames; // Number of frames, if animated (1 for no animation).
public ushort firstFrame; // First frame in animation (0 based).
public byte[] padding0; // (Sizeof 4) reflectivity padding (16 byte alignment).
public float[] reflectivity; // (Sizeof 3) reflectivity vector.
public byte[] padding1; // (Sizeof 4) reflectivity padding (8 byte packing).
public float bumpmapScale; // Bumpmap scale.
public VTFImageFormat highResImageFormat; // High resolution image format.
public byte mipmapCount; // Number of mipmaps.
public VTFImageFormat lowResImageFormat; // Low resolution image format (always DXT1).
public byte lowResImageWidth; // Low resolution image width.
public byte lowResImageHeight; // Low resolution image height.
public ushort depth; // Depth of the largest mipmap in pixels. Must be a power of 2. Can be 0 or 1 for a 2D texture (v7.2 only).
public byte[] padding2; // (Sizeof 3)
public uint resourceCount; // Number of image resources
public byte[] padding3; // (Sizeof 8)
public VTFResource[] resources; // (Sizeof VTF_RSRC_MAX_DICTIONARY_ENTRIES)
#pragma warning disable CS0649
public VTFResourceData[] data; // (Sizeof VT_RSRC_MAX_DICTIONARY_ENTRIES)
#pragma warning restore CS0649
}
}
| 67.885714 | 136 | 0.560606 | [
"MIT"
] | Kerfuffles/com.chisel.import.source.vpktools | VTF/VTFHeader.cs | 2,378 | C# |
/*
* ******************************************************************************
* Copyright 2014-2020 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.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.
* ****************************************************************************
*/
using System;
namespace SpectraLogic.SpectraRioBrokerClient.Exceptions
{
/// <summary>
///
/// </summary>
/// <seealso cref="System.Exception" />
public class DeviceAlreadyExistsException : Exception
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="DeviceAlreadyExistsException"/> class.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param>
public DeviceAlreadyExistsException(string message, Exception innerException) : base(message, innerException)
{
}
#endregion Constructors
}
} | 41.769231 | 188 | 0.622468 | [
"Apache-2.0"
] | SpectraLogic/ep_net_sdk | SpectraLogic.SpectraRioBrokerClient/Exceptions/DeviceAlreadyExistsException.cs | 1,631 | C# |
using System;
namespace WebNotificationService.API
{
public class TestCancelledWebMessage
{
public int TestId { get; }
public string TestName { get; }
public TestCancelledWebMessage(int testId, string testName)
{
TestId = testId;
TestName = testName;
}
};
}
| 19.823529 | 67 | 0.593472 | [
"MIT"
] | GataullinRR/Testkit | WebNotificationService.API/Messages/TestCanceledWebMessage.cs | 339 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using UnityEditor.TestTools.TestRunner.Api;
namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol
{
internal class TestRunnerApiMapper : ITestRunnerApiMapper
{
public TestPlanMessage MapTestToTestPlanMessage(ITestAdaptor testsToRun)
{
var testsNames = testsToRun != null ? FlattenTestNames(testsToRun) : new List<string>();
var msg = new TestPlanMessage
{
tests = testsNames
};
return msg;
}
public TestStartedMessage MapTestToTestStartedMessage(ITestAdaptor test)
{
return new TestStartedMessage
{
name = test.FullName
};
}
public TestFinishedMessage TestResultToTestFinishedMessage(ITestResultAdaptor result)
{
return new TestFinishedMessage
{
name = result.Test.FullName,
duration = Convert.ToUInt64(result.Duration * 1000),
durationMicroseconds = Convert.ToUInt64(result.Duration * 1000000),
message = result.Message,
state = GetTestStateFromResult(result),
stackTrace = result.StackTrace
};
}
public string GetRunStateFromResultNunitXml(ITestResultAdaptor result)
{
var doc = new XmlDocument();
doc.LoadXml(result.ToXml().OuterXml);
return doc.FirstChild.Attributes["runstate"].Value;
}
public TestState GetTestStateFromResult(ITestResultAdaptor result)
{
var state = TestState.Failure;
if (result.TestStatus == TestStatus.Passed)
{
state = TestState.Success;
var runstate = GetRunStateFromResultNunitXml(result);
runstate = runstate ?? String.Empty;
if (runstate.ToLowerInvariant().Equals("explicit"))
state = TestState.Skipped;
}
else if (result.TestStatus == TestStatus.Skipped)
{
state = TestState.Skipped;
if (result.ResultState.ToLowerInvariant().EndsWith("ignored"))
state = TestState.Ignored;
}
else
{
if (result.ResultState.ToLowerInvariant().Equals("inconclusive"))
state = TestState.Inconclusive;
if (result.ResultState.ToLowerInvariant().EndsWith("cancelled") ||
result.ResultState.ToLowerInvariant().EndsWith("error"))
state = TestState.Error;
}
return state;
}
public List<string> FlattenTestNames(ITestAdaptor test)
{
var results = new List<string>();
if (!test.IsSuite)
results.Add(test.FullName);
if (test.Children != null && test.Children.Any())
foreach (var child in test.Children)
results.AddRange(FlattenTestNames(child));
return results;
}
}
}
| 32.91 | 101 | 0.54725 | [
"MIT"
] | AlePPisa/GameJamPractice1 | Cellular/Library/PackageCache/com.unity.test-framework@1.1.16/UnityEditor.TestRunner/UnityTestProtocol/TestRunnerApiMapper.cs | 3,291 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Globalization;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Globalization
{
internal delegate void EnumCalendarInfoCallback(
[MarshalAs(UnmanagedType.LPWStr)] string calendarString,
IntPtr context);
[DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetCalendars")]
internal static extern int GetCalendars(string localeName, CalendarId[] calendars, int calendarsCapacity);
[DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetCalendarInfo")]
internal static extern unsafe ResultCode GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType calendarDataType, char* result, int resultCapacity);
[DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_EnumCalendarInfo")]
internal static extern bool EnumCalendarInfo(EnumCalendarInfoCallback callback, string localeName, CalendarId calendarId, CalendarDataType calendarDataType, IntPtr context);
[DllImport(Libraries.GlobalizationNative, EntryPoint = "GlobalizationNative_GetLatestJapaneseEra")]
internal static extern int GetLatestJapaneseEra();
[DllImport(Libraries.GlobalizationNative, EntryPoint = "GlobalizationNative_GetJapaneseEraStartDate")]
internal static extern bool GetJapaneseEraStartDate(int era, out int startYear, out int startMonth, out int startDay);
}
}
| 54.5625 | 181 | 0.781214 | [
"MIT"
] | 71221-maker/runtime | src/libraries/Common/src/Interop/Interop.Calendar.cs | 1,746 | C# |
using Bookme.ViewModels.Booking;
using Bookme.WebApp.Areas.Booking.Controllers;
using MyTested.AspNetCore.Mvc;
using Xunit;
using System;
using System.Linq;
using static Bookme.Test.Data.User;
using static Bookme.Test.Data.DataInstances;
using static Bookme.WebApp.Controllers.Constants.RoleConstants;
using static Bookme.WebApp.Controllers.Constants.TempDataConstants;
using Bookme.WebApp.Controllers;
namespace Bookme.Test.Areas.Booking.Controllers
{
public class BookingControllerTest
{
[Fact]
public void GetInfoShouldBeForAuthorizedUsersAndReturnUnautorized()
=> MyController<BookingController>
.Instance(c => c
.WithData(OneUser, OneOfferedService)
.WithUser(OneUser.UserName, new[] { CLIENT }))
.Calling(c => c.Index(OneOfferedService.Id))
.ShouldHave()
.ActionAttributes(attributes => attributes
.RestrictingForAuthorizedRequests())
.AndAlso()
.ShouldReturn()
.Unauthorized();
[Fact]
public void GetInfoShouldBeForAuthorizedUsersAndReturnViewWithModel()
=> MyController<BookingController>
.Instance(c => c
.WithData(SecondUser, OneUser, OneOfferedService)
.WithUser(SecondUser.Id, SecondUser.UserName, new[] { CLIENT }))
.Calling(c => c.Index(OneOfferedService.Id))
.ShouldHave()
.ActionAttributes(attributes => attributes
.RestrictingForAuthorizedRequests())
.AndAlso()
.ShouldReturn()
.View(view => view
.WithModelOfType<ServiceBookingViewModel>());
[Fact]
public void PostInfoShouldBeForAuthorizedUsersAndReturnUnautorized()
=> MyController<BookingController>
.Instance(c => c
.WithData(OneUser, OneOfferedService)
.WithUser(OneUser.UserName, new[] { CLIENT }))
.Calling(c => c.Index(new BookServiceViewModel { OwnerId = OneUser.Id, ClientId = OneUser.Id }))
.ShouldHave()
.ActionAttributes(attributes => attributes
.RestrictingForHttpMethod(HttpMethod.Post)
.RestrictingForAuthorizedRequests())
.AndAlso()
.ShouldReturn()
.Unauthorized();
[Theory]
[InlineData(
1,
60,
"TestService",
"TestId",
"TestId2",
"FirstName",
"LastName",
"+359 885 123123",
"2021-06-07 10:30:00",
"Some testing text here")]
public void PostCreateShouldBeForAuthorizedUsersAndRedirectWithValidModel(
int serviceId,
int duraion,
string Name,
string ownerId,
string clientId,
string clientFirtName,
string clientLastName,
string clientPhone,
string date,
string notes)
=> MyController<BookingController>
.Instance(c => c
.WithData(OneUser, SecondUser, OneOfferedService, OneBusiness)
.WithUser(SecondUser.Id, SecondUser.UserName, new[] { CLIENT }))
.Calling(c => c.Index(new BookServiceViewModel
{
ServiceId = serviceId,
Duration = duraion,
Name = Name,
OwnerId = ownerId,
ClientId = clientId,
FirstName = clientFirtName,
LastName = clientLastName,
PhoneNumber = clientPhone,
Date = date,
Notes = notes
}))
.ShouldHave()
.ActionAttributes(attributes => attributes
.RestrictingForHttpMethod(HttpMethod.Post)
.RestrictingForAuthorizedRequests())
.Data(data => data
.WithSet<Bookme.Data.Models.Booking>(businesses => businesses
.Any(b => b.BusinessId == ownerId
&& b.ClientId == clientId
&& b.ClientFirstName == clientFirtName
&& b.ClientLastName == clientLastName
&& b.ClientPhoneNumber == clientPhone
&& b.BookedService == Name
&& b.Duration == duraion
&& b.Notes == notes)))
.TempData(tempData => tempData
.ContainingEntryWithKey(GLOBAL_MESSAGE_KEY))
.AndAlso()
.ShouldReturn()
.Redirect();
[Theory]
[InlineData(
1,
60,
"TestService",
"TestId",
"TestId2",
"FirstName",
"LastName",
"+359 885 123123",
"2021-06-07 10:30:00",
"Some testing text here")]
public void PostCreateShouldBeForAuthorizedUsersAndRedirectWithInvalidDate(
int serviceId,
int duraion,
string Name,
string ownerId,
string clientId,
string clientFirtName,
string clientLastName,
string clientPhone,
string date,
string notes)
=> MyController<BookingController>
.Instance(c => c
.WithData(OneUser, SecondUser, OneOfferedService, OneBooking)
.WithUser(SecondUser.Id, SecondUser.UserName, new[] { CLIENT }))
.Calling(c => c.Index(new BookServiceViewModel
{
ServiceId = serviceId,
Duration = duraion,
Name = Name,
OwnerId = ownerId,
ClientId = clientId,
FirstName = clientFirtName,
LastName = clientLastName,
PhoneNumber = clientPhone,
Date = date,
Notes = notes
}))
.ShouldHave()
.ActionAttributes(attributes => attributes
.RestrictingForHttpMethod(HttpMethod.Post)
.RestrictingForAuthorizedRequests())
.TempData(tempData => tempData
.ContainingEntryWithKey(GLOBAL_MESSAGE_WARNING_KEY))
.AndAlso()
.ShouldReturn()
.Redirect();
}
}
| 38.913295 | 112 | 0.510695 | [
"MIT"
] | MarioGn1/Bookme.WebApp | Bookme.WebApp/Bookme.Test/Areas/Booking/Controllers/BookingControllerTest.cs | 6,734 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using Aliyun.Acs.Core.Http;
namespace Aliyun.Acs.Core.Reader
{
public class ReaderFactory
{
public static IReader CreateInstance(FormatType? format)
{
if (FormatType.JSON == format)
{
return new JsonReader();
}
if (FormatType.XML == format)
{
return new XmlReader();
}
return null;
}
}
}
| 29.857143 | 64 | 0.653907 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-core/Reader/ReaderFactory.cs | 1,254 | C# |
using System;
using System.Collections.Generic;
using System.Management.Automation;
using QlikView_CLI.QMSAPI;
namespace QlikView_CLI.PWSH
{
[Cmdlet(VerbsCommon.New, "QVTaskServerDocumentLoadServerSetting")]
public class NewQVTaskServerDocumentLoadServerSetting : PSCmdlet
{
private QlikView_CLI.QMSAPI.DocumentTask.TaskServer.TaskServerDocumentLoading.TaskServerDocumentLoadServerSetting taskserverdocumentloadserversetting;
[Parameter]
public List<QlikView_CLI.QMSAPI.DocumentTask.TaskServer.TaskServerDocumentLoading.TaskServerDocumentLoadServerSetting.TaskDocumentLoadClusterSetting> Clustersettings = new List<QlikView_CLI.QMSAPI.DocumentTask.TaskServer.TaskServerDocumentLoading.TaskServerDocumentLoadServerSetting.TaskDocumentLoadClusterSetting>();
[Parameter]
public QlikView_CLI.QMSAPI.ServerDocumentLoadMode Mode = default(QlikView_CLI.QMSAPI.ServerDocumentLoadMode);
[Parameter]
public System.Guid Qlikviewserverid;
protected override void BeginProcessing()
{
base.BeginProcessing();
}
protected override void ProcessRecord()
{
base.ProcessRecord();
taskserverdocumentloadserversetting = new QlikView_CLI.QMSAPI.DocumentTask.TaskServer.TaskServerDocumentLoading.TaskServerDocumentLoadServerSetting() { ClusterSettings = Clustersettings, Mode = Mode, QlikViewServerId = Qlikviewserverid };
}
protected override void EndProcessing()
{
base.EndProcessing();
WriteObject(taskserverdocumentloadserversetting);
}
}
}
| 44.054054 | 325 | 0.758282 | [
"MIT"
] | QlikProfessionalServices/QlikView-CLI | PWSH/Generated/New/TaskServerDocumentLoadServerSetting.cs | 1,630 | C# |
#region Copyright (c) 2011-2022 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2022 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2022 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// The types of event filters that the server could support.
/// </summary>
[Flags]
public enum TsCAeFilterType
{
/// <summary>
/// The server supports filtering by event type.
/// </summary>
Event = 0x0001,
/// <summary>
/// The server supports filtering by event categories.
/// </summary>
Category = 0x0002,
/// <summary>
/// The server supports filtering by severity levels.
/// </summary>
Severity = 0x0004,
/// <summary>
/// The server supports filtering by process area.
/// </summary>
Area = 0x0008,
/// <summary>
/// The server supports filtering by event sources.
/// </summary>
Source = 0x0010,
/// <summary>
/// All filters supported by the server.
/// </summary>
All = 0xFFFF
}
}
| 29.924242 | 79 | 0.64962 | [
"MIT"
] | technosoftware-gmbh/opc-daaehda-client-net | src/Technosoftware/DaAeHdaClient/Ae/FilterType.cs | 1,975 | C# |
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Square;
using Square.Utilities;
namespace Square.Models
{
public class LoyaltyEventCreateReward
{
public LoyaltyEventCreateReward(string loyaltyProgramId,
int points,
string rewardId = null)
{
LoyaltyProgramId = loyaltyProgramId;
RewardId = rewardId;
Points = points;
}
/// <summary>
/// The ID of the [loyalty program](#type-LoyaltyProgram).
/// </summary>
[JsonProperty("loyalty_program_id")]
public string LoyaltyProgramId { get; }
/// <summary>
/// The Square-assigned ID of the created [loyalty reward](#type-LoyaltyReward).
/// This field is returned only if the event source is `LOYALTY_API`.
/// </summary>
[JsonProperty("reward_id")]
public string RewardId { get; }
/// <summary>
/// The loyalty points used to create the reward.
/// </summary>
[JsonProperty("points")]
public int Points { get; }
public Builder ToBuilder()
{
var builder = new Builder(LoyaltyProgramId,
Points)
.RewardId(RewardId);
return builder;
}
public class Builder
{
private string loyaltyProgramId;
private int points;
private string rewardId;
public Builder(string loyaltyProgramId,
int points)
{
this.loyaltyProgramId = loyaltyProgramId;
this.points = points;
}
public Builder LoyaltyProgramId(string value)
{
loyaltyProgramId = value;
return this;
}
public Builder Points(int value)
{
points = value;
return this;
}
public Builder RewardId(string value)
{
rewardId = value;
return this;
}
public LoyaltyEventCreateReward Build()
{
return new LoyaltyEventCreateReward(loyaltyProgramId,
points,
rewardId);
}
}
}
} | 28.208791 | 89 | 0.516946 | [
"Apache-2.0"
] | okenshields/test-dotnet | Fangkuai/Models/LoyaltyEventCreateReward.cs | 2,567 | C# |
using MagiCore.Model;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace CourseShop.Services.Catalog.Model.Entities;
public class Category : IEntity<string>
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; } = default!;
public string? Name { get; set; }
} | 23.571429 | 53 | 0.730303 | [
"MIT"
] | furkanisitan/course-shop | src/Services/Catalog/Catalog.Model/Entities/Category.cs | 332 | C# |
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Paco.Entities.Models.Identity;
namespace Paco.Repositories.Database
{
public static class RoleRepository
{
public static Role GetRole(this DbSet<Role> roles, Guid roleId)
{
return roles.FirstOrDefault(r => r.Id == roleId);
}
}
} | 23.6 | 71 | 0.677966 | [
"MIT"
] | nono3551/paco | Paco/Repositories/Database/RoleRepository.cs | 356 | C# |
using Extensioner.Logging;
using System;
namespace NETCore31
{
class Program
{
static void Main(string[] args)
{
Log.Debug("Hello NETCore3.1");
Console.WriteLine("Hello World!");
}
}
}
| 16.466667 | 46 | 0.550607 | [
"Apache-2.0"
] | Extensioner/Logging | Samples/NETCore31/Program.cs | 249 | C# |
using System;
using System.Text;
using Loki.Interfaces.Dependency;
using Loki.Interfaces.Logging;
using Loki.SignalServer.Interfaces.Queues;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
namespace Loki.SignalServer.Common.Queues.RabbitMq
{
public class RabbitEventedQueue<T> : IEventedQueue<T>
{
#region Properties
/// <summary>
/// Gets the count.
/// </summary>
/// <value>
/// The count.
/// </value>
public int Count => throw new NotSupportedException();
/// <summary>
/// Gets a value indicating whether this instance can dequeue.
/// </summary>
/// <value>
/// <c>true</c> if this instance can dequeue; otherwise, <c>false</c>.
/// </value>
public bool CanDequeue => false;
#endregion
#region Private Readonly Variables
/// <summary>
/// The logger
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// The Json Serializer Settings
/// </summary>
private readonly JsonSerializerSettings _jss;
/// <summary>
/// The exchange identifier
/// </summary>
private readonly string _exchangeId;
/// <summary>
/// The queue identifier
/// </summary>
private readonly string _queueId;
/// <summary>
/// The routekey
/// </summary>
private readonly string _routekey;
/// <summary>
/// The channel
/// </summary>
private readonly IModel _channel;
#endregion
#region Events
/// <summary>
/// Occurs when [dequeued].
/// </summary>
public event EventHandler<T> Dequeued;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="RabbitEventedQueue{T}" /> class.
/// </summary>
public RabbitEventedQueue(string exchangeId, string queueId, string routeKey, IModel channel, IDependencyUtility dependencyUtility)
{
_exchangeId = exchangeId;
_queueId = queueId;
_routekey = routeKey;
_channel = channel;
_logger = dependencyUtility.Resolve<ILogger>();
_jss = dependencyUtility.Resolve<JsonSerializerSettings>();
AddConsumer();
}
#endregion
#region Public Methods
/// <summary>
/// Enqueues the specified item.
/// </summary>
/// <param name="item">The item.</param>
public void Enqueue(T item)
{
byte[] bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(item, _jss));
_channel.BasicPublish(_exchangeId, _routekey, null, bytes);
}
/// <summary>
/// Dequeues this instance.
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public T Dequeue()
{
throw new NotImplementedException();
}
#endregion
#region Private Methods
/// <summary>
/// Adds the consumer.
/// </summary>
private void AddConsumer()
{
EventingBasicConsumer consumer = new EventingBasicConsumer(_channel);
consumer.Received += ConsumerOnReceived;
_channel.BasicConsume(_queueId, true, consumer);
}
/// <summary>
/// The event which fires when the consumer receives a delivery
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="basicDeliverEventArgs">The <see cref="BasicDeliverEventArgs"/> instance containing the event data.</param>
private void ConsumerOnReceived(object sender, BasicDeliverEventArgs basicDeliverEventArgs)
{
byte[] body = basicDeliverEventArgs.Body;
T result = JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(body), _jss);
Dequeued?.Invoke(this, result);
}
#endregion
}
}
| 27.605263 | 139 | 0.565062 | [
"Apache-2.0"
] | systemidx/Loki-SignalServer | Loki.SignalServer.Common/Queues/RabbitMq/RabbitEventedQueue.cs | 4,198 | C# |
using GameUtilities.AnchorPoint;
using GameUtilities.PlayerUtility;
using Item;
using Item.Database;
using UnityEngine;
public class ItemInformation : BaseInteractedObject {
# region Public Variables
[SerializeField]
private ItemNameID itemNameID;
[SerializeField]
private bool hasMiniGame;
[SerializeField]
private GUISkin itemSkin;
# endregion Public Variables
# region Private Variables
private ItemData baseItemData;
# endregion Private Variables
# region Reset Variables
private ItemNameID _itemNameID;
# endregion Reset Variables
// Public Properties
// --
protected override void Start() {
base.Start();
_itemNameID = itemNameID;
baseItemData = ItemDatabase.GetItem(_itemNameID);
}
protected override void Update() {
base.Update();
if (gameManager.GameState == GameState.MainGame) {
if (objectTooltipEnabled && UserInterface.InactiveUI()) {
if (Input.GetButtonDown(PlayerUtility.ItemPickup)) {
if (!HideNSeekUI.current.SideMissionActive) {
AudioSource audioSource = AudioManager.current.GetAudioSource(AudioNameID.ItemPickup, true);
audioSource.gameObject.SetActive(true);
audioSource.Play();
if (hasMiniGame) {
HideNSeekUI.current.RunHideAndSeek(MiniGameReward);
}
else {
// Check if we can still place an item in our inventory
if (!playerInformation.IsInventoryFull()) {
// Show an indicator telling our inventory is almost full
if (playerInformation.GetItemCount() > 8) {
UserInterface.RunTextIndicator(new Color(1f, 1f, 0f), "Inventory Almost Full!");
}
// Add the object to player's inventory
playerInformation.AddInventoryItem(_itemNameID);
ObjectEnabled = false;
}
else {
// Show an indicator telling our inventory is full
UserInterface.RunTextIndicator(Color.red, "Inventory is Full!");
}
}
}
}
}
}
}
protected override void OnGUI() {
base.OnGUI();
if (gameManager.GameState == GameState.MainGame) {
if (objectTooltipEnabled && UserInterface.InactiveUI()) {
ItemTooltip();
}
}
}
public override void ResetObject() {
base.ResetObject();
_itemNameID = itemNameID;
}
private void MiniGameReward() {
playerInformation.AddInventoryItem(_itemNameID);
ObjectEnabled = false;
}
private void ItemTooltip() {
Rect itemTooltipRect = new Rect(objectTooltipToScreen.x, Screen.height - objectTooltipToScreen.y, mainRect.width * 0.22f, mainRect.height * 0.04f);
AnchorPoint.SetAnchor(ref itemTooltipRect, Anchor.BottomCenter);
GUI.BeginGroup(itemTooltipRect);
Rect keyInfoRect = new Rect(itemTooltipRect.width * 0.5f, itemTooltipRect.height * 0.5f, itemTooltipRect.width * 0.95f, itemTooltipRect.height * 0.9f);
AnchorPoint.SetAnchor(ref keyInfoRect, Anchor.MiddleCenter);
GUI.Box(keyInfoRect, baseItemData.ItemName, itemSkin.GetStyle("Item Name Hover"));
GUI.EndGroup();
Rect textRect = new Rect(Screen.width * 0.5f, Screen.height * 0.9f, Screen.width, Screen.height * 0.1f * screenHeightRatio);
AnchorPoint.SetAnchor(ref textRect, Anchor.MiddleCenter);
GUI.BeginGroup(textRect);
Rect keyText = new Rect(textRect.width * 0.5f, textRect.height * 0.5f, textRect.width * 0.2f, textRect.height);
AnchorPoint.SetAnchor(ref keyText, Anchor.MiddleCenter);
GUI.Box(keyText, "[E] Pickup Item", tempSkin.GetStyle("Text"));
GUI.EndGroup();
}
} | 29.577586 | 153 | 0.716409 | [
"MIT"
] | pixelsquare/Chance | Assets/Scripts/Item/ItemInformation.cs | 3,433 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.