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) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\IEntityCollectionRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
/// <summary>
/// The interface IDeviceManagementAbstractComplexSettingInstanceValueCollectionRequestBuilder.
/// </summary>
public partial interface IDeviceManagementAbstractComplexSettingInstanceValueCollectionRequestBuilder : IBaseRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
IDeviceManagementAbstractComplexSettingInstanceValueCollectionRequest Request();
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
IDeviceManagementAbstractComplexSettingInstanceValueCollectionRequest Request(IEnumerable<Option> options);
/// <summary>
/// Gets an <see cref="IDeviceManagementSettingInstanceRequestBuilder"/> for the specified DeviceManagementSettingInstance.
/// </summary>
/// <param name="id">The ID for the DeviceManagementSettingInstance.</param>
/// <returns>The <see cref="IDeviceManagementSettingInstanceRequestBuilder"/>.</returns>
IDeviceManagementSettingInstanceRequestBuilder this[string id] { get; }
}
}
| 44.52381 | 153 | 0.645989 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IDeviceManagementAbstractComplexSettingInstanceValueCollectionRequestBuilder.cs | 1,870 | 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.Bm.V20180423.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeDevicePriceInfoResponse : AbstractModel
{
/// <summary>
/// 服务器价格信息列表
/// </summary>
[JsonProperty("DevicePriceInfoSet")]
public DevicePriceInfo[] DevicePriceInfoSet{ get; set; }
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamArrayObj(map, prefix + "DevicePriceInfoSet.", this.DevicePriceInfoSet);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 31.666667 | 96 | 0.656347 | [
"Apache-2.0"
] | ImEdisonJiang/tencentcloud-sdk-dotnet | TencentCloud/Bm/V20180423/Models/DescribeDevicePriceInfoResponse.cs | 1,691 | C# |
using GraphQL.Types;
using System.Collections.Generic;
namespace Our.Umbraco.GraphQL.Adapters.Examine.Types
{
public class SearchResultFieldsGraphType : ObjectGraphType<KeyValuePair<string, IReadOnlyList<string>>>
{
}
}
| 23.3 | 107 | 0.781116 | [
"MIT"
] | ProworksDevTeam/umbraco-graphql | src/Our.Umbraco.GraphQL/Adapters/Examine/Types/SearchResultFieldsGraphType.cs | 233 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Confuser.Core.Project;
using Confuser.Core.Properties;
using Confuser.Core.Services;
using dnlib.DotNet;
using dnlib.DotNet.Emit;
using dnlib.DotNet.Writer;
using Microsoft.Win32;
using InformationalAttribute = System.Reflection.AssemblyInformationalVersionAttribute;
using ProductAttribute = System.Reflection.AssemblyProductAttribute;
using CopyrightAttribute = System.Reflection.AssemblyCopyrightAttribute;
using MethodAttributes = dnlib.DotNet.MethodAttributes;
using MethodImplAttributes = dnlib.DotNet.MethodImplAttributes;
using TypeAttributes = dnlib.DotNet.TypeAttributes;
namespace Confuser.Core {
/// <summary>
/// The processing engine of ConfuserEx.
/// </summary>
public static class ConfuserEngine {
/// <summary>
/// The version of ConfuserEx.
/// </summary>
public static readonly string Version;
static readonly string Copyright;
static ConfuserEngine() {
Assembly assembly = typeof(ConfuserEngine).Assembly;
var nameAttr = (ProductAttribute)assembly.GetCustomAttributes(typeof(ProductAttribute), false)[0];
var verAttr = (InformationalAttribute)assembly.GetCustomAttributes(typeof(InformationalAttribute), false)[0];
var cpAttr = (CopyrightAttribute)assembly.GetCustomAttributes(typeof(CopyrightAttribute), false)[0];
Version = string.Format("{0} {1}", nameAttr.Product, verAttr.InformationalVersion);
Copyright = cpAttr.Copyright;
AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => {
try {
var asmName = new AssemblyName(e.Name);
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
if (asm.GetName().Name == asmName.Name)
return asm;
return null;
}
catch {
return null;
}
};
}
/// <summary>
/// Runs the engine with the specified parameters.
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <param name="token">The token used for cancellation.</param>
/// <returns>Task to run the engine.</returns>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="parameters" />.Project is <c>null</c>.
/// </exception>
public static Task Run(ConfuserParameters parameters, CancellationToken? token = null) {
if (parameters.Project == null)
throw new ArgumentNullException("parameters");
if (token == null)
token = new CancellationTokenSource().Token;
return Task.Factory.StartNew(() => RunInternal(parameters, token.Value), token.Value);
}
/// <summary>
/// Runs the engine.
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <param name="token">The cancellation token.</param>
static void RunInternal(ConfuserParameters parameters, CancellationToken token) {
// 1. Setup context
var context = new ConfuserContext();
context.Logger = parameters.GetLogger();
context.Project = parameters.Project.Clone();
context.PackerInitiated = parameters.PackerInitiated;
context.token = token;
PrintInfo(context);
bool ok = false;
try {
// Enable watermarking by default
context.Project.Rules.Insert(0, new Rule {
new SettingItem<Protection>(WatermarkingProtection._Id)
});
var asmResolver = new ConfuserAssemblyResolver {EnableTypeDefCache = true};
asmResolver.DefaultModuleContext = new ModuleContext(asmResolver);
context.InternalResolver = asmResolver;
context.BaseDirectory = Path.Combine(Environment.CurrentDirectory, context.Project.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar);
context.OutputDirectory = Path.Combine(context.Project.BaseDirectory, context.Project.OutputDirectory.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar);
foreach (string probePath in context.Project.ProbePaths)
asmResolver.PostSearchPaths.Insert(0, Path.Combine(context.BaseDirectory, probePath));
context.CheckCancellation();
Marker marker = parameters.GetMarker();
// 2. Discover plugins
context.Logger.Debug(Resources.ConfuserEngine_RunInternal_Discovering_plugins);
IList<Protection> prots;
IList<Packer> packers;
IList<ConfuserComponent> components;
parameters.GetPluginDiscovery().GetPlugins(context, out prots, out packers, out components);
context.Logger.InfoFormat(Resources.ConfuserEngine_RunInternal_Discovered__protections, prots.Count, packers.Count);
context.CheckCancellation();
// 3. Resolve dependency
context.Logger.Debug(Resources.ConfuserEngine_RunInternal_Resolving_component_dependency);
try {
var resolver = new DependencyResolver(prots);
prots = resolver.SortDependency();
}
catch (CircularDependencyException ex) {
context.Logger.ErrorException("", ex);
throw new ConfuserException(ex);
}
components.Insert(0, new CoreComponent(context, marker));
foreach (Protection prot in prots)
components.Add(prot);
foreach (Packer packer in packers)
components.Add(packer);
context.CheckCancellation();
// 4. Load modules
context.Logger.Info(Resources.ConfuserEngine_RunInternal_Loading_input_modules);
marker.Initalize(prots, packers);
MarkerResult markings = marker.MarkProject(context.Project, context);
context.Modules = new ModuleSorter(markings.Modules).Sort().ToList().AsReadOnly();
foreach (var module in context.Modules)
module.EnableTypeDefFindCache = false;
context.OutputModules = Enumerable.Repeat<byte[]>(null, context.Modules.Count).ToArray();
context.OutputSymbols = Enumerable.Repeat<byte[]>(null, context.Modules.Count).ToArray();
context.OutputPaths = Enumerable.Repeat<string>(null, context.Modules.Count).ToArray();
context.Packer = markings.Packer;
context.ExternalModules = markings.ExternalModules;
context.CheckCancellation();
// 5. Initialize components
context.Logger.Info(Resources.ConfuserEngine_RunInternal_Initializing);
foreach (ConfuserComponent comp in components) {
try {
comp.Initialize(context);
}
catch (Exception ex) {
context.Logger.ErrorException( string.Format(Resources.ConfuserEngine_RunInternal_Error_occured_during_initialization, comp.Name), ex);
throw new ConfuserException(ex);
}
context.CheckCancellation();
}
context.CheckCancellation();
// 6. Build pipeline
context.Logger.Debug(Resources.ConfuserEngine_RunInternal_Building_pipeline);
var pipeline = new ProtectionPipeline();
context.Pipeline = pipeline;
foreach (ConfuserComponent comp in components) {
comp.PopulatePipeline(pipeline);
}
context.CheckCancellation();
//7. Run pipeline
RunPipeline(pipeline, context);
ok = true;
}
catch (AssemblyResolveException ex) {
context.Logger.ErrorException("Failed to resolve an assembly, check if all dependencies are present in the correct version.", ex);
PrintEnvironmentInfo(context);
}
catch (TypeResolveException ex) {
context.Logger.ErrorException("Failed to resolve a type, check if all dependencies are present in the correct version.", ex);
PrintEnvironmentInfo(context);
}
catch (MemberRefResolveException ex) {
context.Logger.ErrorException("Failed to resolve a member, check if all dependencies are present in the correct version.", ex);
PrintEnvironmentInfo(context);
}
catch (IOException ex) {
context.Logger.ErrorException("An IO error occurred, check if all input/output locations are readable/writable.", ex);
}
catch (OperationCanceledException) {
context.Logger.Error(Resources.ConfuserEngine_RunInternal_Operation_cancelled);
}
catch (ConfuserException) {
// Exception is already handled/logged, so just ignore and report failure
}
catch (Exception ex) {
context.Logger.ErrorException(Resources.ConfuserEngine_RunInternal_Unknown_error_occurred, ex);
}
finally {
if (context.Resolver != null)
context.InternalResolver.Clear();
context.Logger.Finish(ok);
}
}
/// <summary>
/// Runs the protection pipeline.
/// </summary>
/// <param name="pipeline">The protection pipeline.</param>
/// <param name="context">The context.</param>
static void RunPipeline(ProtectionPipeline pipeline, ConfuserContext context) {
Func<IList<IDnlibDef>> getAllDefs = () => context.Modules.SelectMany(module => module.FindDefinitions()).ToList();
Func<ModuleDef, IList<IDnlibDef>> getModuleDefs = module => module.FindDefinitions().ToList();
context.CurrentModuleIndex = -1;
pipeline.ExecuteStage(PipelineStage.Inspection, Inspection, () => getAllDefs(), context);
var options = new ModuleWriterOptionsBase[context.Modules.Count];
for (int i = 0; i < context.Modules.Count; i++) {
context.CurrentModuleIndex = i;
context.CurrentModuleWriterOptions = null;
pipeline.ExecuteStage(PipelineStage.BeginModule, BeginModule, () => getModuleDefs(context.CurrentModule), context);
pipeline.ExecuteStage(PipelineStage.ProcessModule, ProcessModule, () => getModuleDefs(context.CurrentModule), context);
pipeline.ExecuteStage(PipelineStage.OptimizeMethods, OptimizeMethods, () => getModuleDefs(context.CurrentModule), context);
pipeline.ExecuteStage(PipelineStage.EndModule, EndModule, () => getModuleDefs(context.CurrentModule), context);
options[i] = context.CurrentModuleWriterOptions;
}
for (int i = 0; i < context.Modules.Count; i++) {
context.CurrentModuleIndex = i;
context.CurrentModuleWriterOptions = options[i];
pipeline.ExecuteStage(PipelineStage.WriteModule, WriteModule, () => getModuleDefs(context.CurrentModule), context);
context.OutputModules[i] = context.CurrentModuleOutput;
context.OutputSymbols[i] = context.CurrentModuleSymbol;
context.CurrentModuleWriterOptions = null;
context.CurrentModuleOutput = null;
context.CurrentModuleSymbol = null;
}
context.CurrentModuleIndex = -1;
pipeline.ExecuteStage(PipelineStage.Debug, Debug, () => getAllDefs(), context);
pipeline.ExecuteStage(PipelineStage.Pack, Pack, () => getAllDefs(), context);
pipeline.ExecuteStage(PipelineStage.SaveModules, SaveModules, () => getAllDefs(), context);
if (!context.PackerInitiated)
context.Logger.Info(Resources.ConfuserEngine_RunPipeline_Done);
}
static void Inspection(ConfuserContext context) {
context.Logger.Info(Resources.ConfuserEngine_Inspection_Resolving_dependencies);
foreach (var dependency in context.Modules
.SelectMany(module => module.GetAssemblyRefs().Select(asmRef => Tuple.Create(asmRef, module)))) {
try {
context.Resolver.ResolveThrow(dependency.Item1, dependency.Item2);
}
catch (AssemblyResolveException ex) {
context.Logger.ErrorException(string.Format(Resources.ConfuserEngine_Inspection_Failed_to_resolve_dependency, dependency.Item2.Name), ex);
throw new ConfuserException(ex);
}
}
context.Logger.Debug(Resources.ConfuserEngine_Inspection_Checking_Strong_Name);
foreach (var module in context.Modules) {
CheckStrongName(context, module);
}
var marker = context.Registry.GetService<IMarkerService>();
context.Logger.Debug(Resources.ConfuserEngine_Inspection_Creating_global__cctors);
foreach (ModuleDefMD module in context.Modules) {
TypeDef modType = module.GlobalType;
if (modType == null) {
modType = new TypeDefUser("", "<Module>", null);
modType.Attributes = TypeAttributes.AnsiClass;
module.Types.Add(modType);
marker.Mark(modType, null);
}
MethodDef cctor = modType.FindOrCreateStaticConstructor();
if (!marker.IsMarked(cctor))
marker.Mark(cctor, null);
}
}
static void CheckStrongName(ConfuserContext context, ModuleDef module) {
var snKey = context.Annotations.Get<StrongNameKey>(module, Marker.SNKey);
var snPubKeyBytes = context.Annotations.Get<StrongNamePublicKey>(module, Marker.SNPubKey)?.CreatePublicKey();
var snDelaySign = context.Annotations.Get<bool>(module, Marker.SNDelaySig);
if (snPubKeyBytes == null && snKey != null)
snPubKeyBytes = snKey.PublicKey;
bool moduleIsSignedOrDelayedSigned = module.IsStrongNameSigned || !module.Assembly.PublicKey.IsNullOrEmpty;
bool isKeyProvided = snKey != null || (snDelaySign && snPubKeyBytes != null);
if (!isKeyProvided && moduleIsSignedOrDelayedSigned)
context.Logger.WarnFormat(Resources.ConfuserEngine_CheckStrongName1, module.Name);
else if (isKeyProvided && !moduleIsSignedOrDelayedSigned)
context.Logger.WarnFormat(Resources.ConfuserEngine_CheckStrongName2, module.Name);
else if (snPubKeyBytes != null && moduleIsSignedOrDelayedSigned &&
!module.Assembly.PublicKey.Data.SequenceEqual(snPubKeyBytes))
context.Logger.WarnFormat(Resources.ConfuserEngine_CheckStrongName3,
module.Name);
}
static void CopyPEHeaders(PEHeadersOptions writerOptions, ModuleDefMD module) {
var image = module.Metadata.PEImage;
writerOptions.MajorImageVersion = image.ImageNTHeaders.OptionalHeader.MajorImageVersion;
writerOptions.MajorLinkerVersion = image.ImageNTHeaders.OptionalHeader.MajorLinkerVersion;
writerOptions.MajorOperatingSystemVersion = image.ImageNTHeaders.OptionalHeader.MajorOperatingSystemVersion;
writerOptions.MajorSubsystemVersion = image.ImageNTHeaders.OptionalHeader.MajorSubsystemVersion;
writerOptions.MinorImageVersion = image.ImageNTHeaders.OptionalHeader.MinorImageVersion;
writerOptions.MinorLinkerVersion = image.ImageNTHeaders.OptionalHeader.MinorLinkerVersion;
writerOptions.MinorOperatingSystemVersion = image.ImageNTHeaders.OptionalHeader.MinorOperatingSystemVersion;
writerOptions.MinorSubsystemVersion = image.ImageNTHeaders.OptionalHeader.MinorSubsystemVersion;
}
static void BeginModule(ConfuserContext context) {
context.Logger.InfoFormat(Resources.ConfuserEngine_BeginModule_Processing_module, context.CurrentModule.Name);
context.CurrentModuleWriterOptions = new ModuleWriterOptions(context.CurrentModule);
context.Logger.InfoFormat(Resources.ConfuserEngine_BeginModule_Processing_PEHeaders);
CopyPEHeaders(context.CurrentModuleWriterOptions.PEHeadersOptions, context.CurrentModule);
if (!context.CurrentModule.IsILOnly || context.CurrentModule.VTableFixups != null)
context.RequestNative(true);
context.Logger.InfoFormat(Resources.ConfuserEngine_BeginModule_Processing_StrongName);
var snKey = context.Annotations.Get<StrongNameKey>(context.CurrentModule, Marker.SNKey);
var snPubKey = context.Annotations.Get<StrongNamePublicKey>(context.CurrentModule, Marker.SNPubKey);
var snSigKey = context.Annotations.Get<StrongNameKey>(context.CurrentModule, Marker.SNSigKey);
var snSigPubKey = context.Annotations.Get<StrongNamePublicKey>(context.CurrentModule, Marker.SNSigPubKey);
var snDelaySig = context.Annotations.Get<bool>(context.CurrentModule, Marker.SNDelaySig, false);
context.CurrentModuleWriterOptions.DelaySign = snDelaySig;
if (snKey != null && snPubKey != null && snSigKey != null && snSigPubKey != null)
context.CurrentModuleWriterOptions.InitializeEnhancedStrongNameSigning(context.CurrentModule, snSigKey, snSigPubKey, snKey, snPubKey);
else if (snSigPubKey != null && snSigKey != null)
context.CurrentModuleWriterOptions.InitializeEnhancedStrongNameSigning(context.CurrentModule, snSigKey, snSigPubKey);
else
context.CurrentModuleWriterOptions.InitializeStrongNameSigning(context.CurrentModule, snKey);
if (snDelaySig) {
context.CurrentModuleWriterOptions.StrongNamePublicKey = snPubKey;
context.CurrentModuleWriterOptions.StrongNameKey = null;
context.Logger.InfoFormat(Resources.ConfuserEngine_BeginModule_Processing_DelayedStrongName, context.CurrentModule.Name);
}
foreach (TypeDef type in context.CurrentModule.GetTypes())
foreach (MethodDef method in type.Methods) {
if (method.Body != null) {
method.Body.Instructions.SimplifyMacros(method.Body.Variables, method.Parameters);
}
}
}
static void ProcessModule(ConfuserContext context) =>
context.CurrentModuleWriterOptions.WriterEvent += (sender, e) => context.CheckCancellation();
static void OptimizeMethods(ConfuserContext context) {
foreach (TypeDef type in context.CurrentModule.GetTypes())
foreach (MethodDef method in type.Methods) {
if (method.Body != null)
method.Body.Instructions.OptimizeMacros();
}
}
static void EndModule(ConfuserContext context) {
string output = context.Modules[context.CurrentModuleIndex].Location;
if (output != null) {
if (!Path.IsPathRooted(output))
output = Path.Combine(Environment.CurrentDirectory, output);
output = Utils.GetRelativePath(output, context.BaseDirectory);
}
else {
output = context.CurrentModule.Name;
}
context.OutputPaths[context.CurrentModuleIndex] = output;
}
static void WriteModule(ConfuserContext context) {
context.Logger.InfoFormat(Resources.ConfuserEngine_WriteModule_Writing_module, context.CurrentModule.Name);
MemoryStream pdb = null, output = new MemoryStream();
if (context.CurrentModule.PdbState != null) {
pdb = new MemoryStream();
context.CurrentModuleWriterOptions.WritePdb = true;
context.CurrentModuleWriterOptions.PdbFileName = Path.ChangeExtension(Path.GetFileName(context.OutputPaths[context.CurrentModuleIndex]), "pdb");
context.CurrentModuleWriterOptions.PdbStream = pdb;
}
if (context.CurrentModuleWriterOptions is ModuleWriterOptions)
context.CurrentModule.Write(output, (ModuleWriterOptions)context.CurrentModuleWriterOptions);
else
context.CurrentModule.NativeWrite(output, (NativeModuleWriterOptions)context.CurrentModuleWriterOptions);
context.CurrentModuleOutput = output.ToArray();
if (context.CurrentModule.PdbState != null)
context.CurrentModuleSymbol = pdb.ToArray();
}
static void Debug(ConfuserContext context) {
context.Logger.Info(Resources.ConfuserEngine_Debug_Finalizing);
for (int i = 0; i < context.OutputModules.Count; i++) {
if (context.OutputSymbols[i] == null)
continue;
string path = Path.GetFullPath(Path.Combine(context.OutputDirectory, context.OutputPaths[i]));
string dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
File.WriteAllBytes(Path.ChangeExtension(path, "pdb"), context.OutputSymbols[i]);
}
}
static void Pack(ConfuserContext context) {
if (context.Packer != null) {
context.Logger.Info(Resources.ConfuserEngine_Pack_Packing);
context.Packer.Pack(context, new ProtectionParameters(context.Packer, context.Modules.OfType<IDnlibDef>().ToList()));
}
}
static void SaveModules(ConfuserContext context) {
context.InternalResolver.Clear();
for (int i = 0; i < context.OutputModules.Count; i++) {
string path = Path.GetFullPath(Path.Combine(context.OutputDirectory, context.OutputPaths[i]));
string dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
context.Logger.DebugFormat(Resources.ConfuserEngine_SaveModules_Saving_to, path);
File.WriteAllBytes(path, context.OutputModules[i]);
}
}
/// <summary>
/// Prints the copyright stuff and environment information.
/// </summary>
/// <param name="context">The working context.</param>
static void PrintInfo(ConfuserContext context) {
if (context.PackerInitiated) {
context.Logger.Info(Resources.ConfuserEngine_PrintInfo_Protecting_packer_stub);
}
else {
context.Logger.InfoFormat("{0} {1}", Version, Copyright);
Type mono = Type.GetType("Mono.Runtime");
context.Logger.InfoFormat(Resources.ConfuserEngine_PrintInfo_Running_on,
Environment.OSVersion,
mono == null ?
".NET Framework v" + Environment.Version :
mono.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, null),
IntPtr.Size * 8);
}
}
static IEnumerable<string> GetFrameworkVersions() {
// http://msdn.microsoft.com/en-us/library/hh925568.aspx
using (RegistryKey ndpKey =
RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "").
OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\")) {
foreach (string versionKeyName in ndpKey.GetSubKeyNames()) {
if (!versionKeyName.StartsWith("v"))
continue;
RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName);
var name = (string)versionKey.GetValue("Version", "");
string sp = versionKey.GetValue("SP", "").ToString();
string install = versionKey.GetValue("Install", "").ToString();
if (install == "" || sp != "" && install == "1")
yield return versionKeyName + " " + name;
if (name != "")
continue;
foreach (string subKeyName in versionKey.GetSubKeyNames()) {
RegistryKey subKey = versionKey.OpenSubKey(subKeyName);
name = (string)subKey.GetValue("Version", "");
if (name != "")
sp = subKey.GetValue("SP", "").ToString();
install = subKey.GetValue("Install", "").ToString();
if (install == "")
yield return versionKeyName + " " + name;
else if (install == "1")
yield return " " + subKeyName + " " + name;
}
}
}
using (RegistryKey ndpKey =
RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "").
OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\")) {
if (ndpKey.GetValue("Release") == null)
yield break;
var releaseKey = (int)ndpKey.GetValue("Release");
yield return "v4.5 " + releaseKey;
}
}
/// <summary>
/// Prints the environment information when error occurred.
/// </summary>
/// <param name="context">The working context.</param>
static void PrintEnvironmentInfo(ConfuserContext context) {
if (context.PackerInitiated)
return;
context.Logger.Error("---BEGIN DEBUG INFO---");
context.Logger.Error(Resources.ConfuserEngine_PrintEnvironmentInfo_Installed_Framework_Versions);
foreach (string ver in GetFrameworkVersions()) {
context.Logger.ErrorFormat(" {0}", ver.Trim());
}
context.Logger.Error("");
if (context.Resolver != null) {
context.Logger.Error(Resources.ConfuserEngine_PrintEnvironmentInfo_Cached_assemblies);
foreach (AssemblyDef asm in context.InternalResolver.GetCachedAssemblies()) {
if (string.IsNullOrEmpty(asm.ManifestModule.Location))
context.Logger.ErrorFormat(" {0}", asm.FullName);
else
context.Logger.ErrorFormat(" {0} ({1})", asm.FullName, asm.ManifestModule.Location);
foreach (var reference in asm.Modules.OfType<ModuleDefMD>().SelectMany(m => m.GetAssemblyRefs()))
context.Logger.ErrorFormat(" {0}", reference.FullName);
}
}
context.Logger.Error("---END DEBUG INFO---");
}
}
}
| 42 | 174 | 0.737835 | [
"MIT"
] | andywu188/ConfuserEx | Confuser.Core/ConfuserEngine.cs | 23,060 | 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/MsHTML.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows;
/// <include file='SVGAElement.xml' path='doc/member[@name="SVGAElement"]/*' />
[Guid("305105DB-98B5-11CF-BB82-00AA00BDCE0B")]
public partial struct SVGAElement
{
}
| 35 | 145 | 0.76381 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/Windows/um/MsHTML/SVGAElement.cs | 527 | C# |
using Acr.UserDialogs;
using Plugin.Geolocator;
using Plugin.Geolocator.Abstractions;
using Plugin.Permissions;
using Plugin.Permissions.Abstractions;
using Plugin.XSnack;
using ProMama.Components;
using ProMama.Models;
using ProMama.ViewModels.Services;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
namespace ProMama.ViewModels.Home.Paginas
{
class PostosSaudeViewModel : ViewModelBase
{
public List<Posto> postos = App.PostoDatabase.GetAll();
private ObservableCollection<Posto> _postosSaude;
public ObservableCollection<Posto> PostosSaude {
get
{
return _postosSaude;
}
set
{
_postosSaude = value;
Notify("PostosSaude");
}
}
private bool _permissaoLocalizacaoConcedida;
public bool PermissaoLocalizacaoConcedida {
get
{
return _permissaoLocalizacaoConcedida;
}
set
{
_permissaoLocalizacaoConcedida = value;
Notify("PermissaoLocalizacaoConcedida");
}
}
public ICommand VerMapaCommand { get; set; }
public ICommand LigarCommand { get; set; }
public ICommand PermissaoLocalizacaoCommand { get; set; }
// MessageService
private static readonly IMessageService MessageService = DependencyService.Get<IMessageService>();
public PostosSaudeViewModel()
{
VerMapaCommand = new Command<Posto>(VerMapa);
LigarCommand = new Command<Posto>(Ligar);
PermissaoLocalizacaoCommand = new Command(PermissaoLocalizacao);
var indexToRemove = -1;
foreach (var p in postos)
{
if (p.nome.Equals("Outro"))
{
indexToRemove = postos.IndexOf(p);
} else
{
p.MostraTelefone = string.IsNullOrEmpty(p.telefone) ? false : true;
string[] coords = p.lat_long.Split(',');
var latitude = double.Parse(coords[0], CultureInfo.InvariantCulture);
var longitude = double.Parse(coords[1], CultureInfo.InvariantCulture);
p.Coordinates = new GeoCoordinate(latitude, longitude);
}
}
if (indexToRemove != -1)
postos.RemoveAt(indexToRemove);
PostosSaude = new ObservableCollection<Posto>(postos);
#pragma warning disable CS1998 // O método assíncrono não possui operadores 'await' e será executado de forma síncrona
Task.Run(async () =>
#pragma warning restore CS1998 // O método assíncrono não possui operadores 'await' e será executado de forma síncrona
{
OrdenaPostosPorProximidade();
});
if (VerificaPermissao().Result != PermissionStatus.Granted && App.NaoPerguntePermissaoLocalizacao == false)
CrossXSnack.Current.ShowMessage("Permissão de localização é necessária para mostrar os postos mais próximos.", 10, "OK", PermissaoLocalizacaoCommand);
}
// Verificação do posto de saúde mais próximo + reordenação
private void OrdenaPostosPorProximidade()
{
if (VerificaPermissao().Result == PermissionStatus.Granted)
{
UserDialogs.Instance.Toast(new ToastConfig("Organizando lista..."));
var currentLocation = GetCurrentPosition().Result;
if (currentLocation != null)
{
postos = postos.OrderBy(x => x.Coordinates.GetDistanceTo(currentLocation)).ToList();
PostosSaude = new ObservableCollection<Posto>(postos);
}
}
}
private async Task<PermissionStatus> VerificaPermissao()
{
return await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
}
private async void PermissaoLocalizacao()
{
App.VezesPerguntadoPermissaoLocalizacao++;
// Pede permissão de acesso à localização
if (App.VezesPerguntadoPermissaoLocalizacao <= 3)
{
var escolha = await MessageService.ConfirmationDialog("Se a permissão de localização for concedida, o aplicativo utilizará sua localização para organizar os postos de saúde por proximidade. Deseja concedê-la?", "Sim", "Não");
if (escolha)
await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Location });
} else {
var escolha = await MessageService.ConfirmationDialog("Se a permissão de localização for concedida, o aplicativo utilizará sua localização para organizar os postos de saúde por proximidade. Deseja concedê-la?", "Sim", "Não e não me peça novamente");
if (escolha)
await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Location });
else
App.NaoPerguntePermissaoLocalizacao = true;
}
#pragma warning disable CS4014 // Como esta chamada não é esperada, a execução do método atual continua antes de a chamada ser concluída
#pragma warning disable CS1998 // O método assíncrono não possui operadores 'await' e será executado de forma síncrona
Task.Run(async () =>
#pragma warning restore CS1998 // O método assíncrono não possui operadores 'await' e será executado de forma síncrona
{
OrdenaPostosPorProximidade();
});
#pragma warning restore CS4014 // Como esta chamada não é esperada, a execução do método atual continua antes de a chamada ser concluída
}
private void VerMapa(Posto obj)
{
string url = "https://www.google.com/maps/search/?api=1&query=" + obj.lat_long;
try
{
Device.OpenUri(new Uri(url));
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
private void Ligar(Posto obj)
{
string telefone = "tel:" + obj.telefone.Replace(" ", "");
try
{
Device.OpenUri(new Uri(telefone));
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
// https://jamesmontemagno.github.io/GeolocatorPlugin/CurrentLocation.html
private static async Task<GeoCoordinate> GetCurrentPosition()
{
Position position = null;
try
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 100;
// Descomentar seção abaixo para ligar o cache de localização.
/*position = await locator.GetLastKnownLocationAsync();
if (position != null)
{
//got a cached position, so let's use it.
//return position;
return new Coordinates(position.Latitude, position.Longitude);
}*/
if (!locator.IsGeolocationAvailable || !locator.IsGeolocationEnabled)
{
//not available or enabled
Debug.WriteLine("Geolocation not available or disabled.");
return null;
}
position = await locator.GetPositionAsync(TimeSpan.FromSeconds(20), null, true);
}
catch (Exception ex)
{
Debug.WriteLine("Unable to get location: " + ex);
}
if (position == null)
return null;
var output = string.Format("Time: {0} \nLat: {1} \nLong: {2} \nAltitude: {3} \nAltitude Accuracy: {4} \nAccuracy: {5} \nHeading: {6} \nSpeed: {7}",
position.Timestamp, position.Latitude, position.Longitude,
position.Altitude, position.AltitudeAccuracy, position.Accuracy, position.Heading, position.Speed);
Debug.WriteLine(output);
return new GeoCoordinate(position.Latitude, position.Longitude);
}
}
}
| 38.58371 | 265 | 0.587428 | [
"Apache-2.0"
] | agharium/ProMama | ProMama/ProMama/ViewModels/Home/Paginas/PostosSaudeViewModel.cs | 8,601 | C# |
using System;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace EzTextingApiClient
{
public class WrappedObjectConverter : JsonConverter
{
public override bool CanConvert(Type objectType) => true;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var token = JToken.Load(reader);
// Get the value of the first property of the inner object
// and deserialize it to the requisite object type
return token.Children<JProperty>().First().Value.ToObject(objectType);
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
} | 31.785714 | 98 | 0.666292 | [
"MIT"
] | CallFire/eztexting-api-client-csharp | src/EzTextingApiClient/WrappedObjectConverter.cs | 892 | C# |
using UnityEngine;
using System;
namespace DerelictComputer
{
/// <summary>
/// The heartbeat of a Pulse Sequencer.
/// Triggers a pulse/tick/bang/whatever you call it at a specified interval.
/// Uses lookahead to trigger steps
/// </summary>
public class Pulse : MonoBehaviour
{
public event Action DidReset;
public event Action<double> Triggered;
// really don't want this to be any shorter than a frame at 60FPS
private const double PeriodMinimum = 0.016;
// so it doesn't go zero of negative, but really, do you ever want one beat every 10 minutes?
private const double BpmMinimum = 0.1;
/// <summary>
/// Period in seconds
/// </summary>
[SerializeField, HideInInspector] private double _period = 1d;
/// <summary>
/// How many pulses per beat? This is only used for the inspector, but is serialized so we can keep it around.
/// </summary>
[SerializeField, HideInInspector] private uint _pulsesPerBeat = 4;
/// <summary>
/// How much time should we look ahead?
/// </summary>
[SerializeField] private double _latency = 0.1;
private double _nextPulseTime;
public double Period
{
get { return _period; }
set {
_period = value < PeriodMinimum ? PeriodMinimum : value;
}
}
public uint PulsesPerBeat
{
get { return _pulsesPerBeat; }
}
public void Reset()
{
_nextPulseTime = AudioSettings.dspTime;
if (DidReset != null)
{
DidReset();
}
}
public double GetBpm()
{
return 60.0/(Period*_pulsesPerBeat);
}
public void SetBpm(double bpm, uint pulsesPerBeat)
{
if (bpm < BpmMinimum)
{
bpm = BpmMinimum;
}
Period = 60.0/(bpm*pulsesPerBeat);
_pulsesPerBeat = pulsesPerBeat;
}
private void Awake()
{
Reset();
}
private void Update()
{
while (AudioSettings.dspTime + _latency > _nextPulseTime)
{
var thisPulseTime = _nextPulseTime;
_nextPulseTime += Period;
if (Triggered != null)
{
Triggered(thisPulseTime);
}
}
}
}
} | 25.737374 | 118 | 0.520408 | [
"MIT"
] | Adjuvant/PulseSequencer | Assets/PulseSequencer/Source/Scripts/Core/Pulse.cs | 2,550 | C# |
namespace VoiceSystem.Services.Data.Contracts
{
using System.Linq;
using VoiceSystem.Data.Models;
public interface IUsersService
{
IQueryable<ApplicationUser> GetAll();
ApplicationUser GetById(string id);
void Update();
void AddUser(ApplicationUser user, string password);
void Delete(string id);
}
} | 21.470588 | 60 | 0.665753 | [
"MIT"
] | todorm85/TelerikAcademy | Courses/Software Technologies/AspNet MVC/Exam/Services/HikingPlanAndRescue.Services.Data/Contracts/IUsersService.cs | 367 | C# |
using System;
namespace Zoro.Wallets.NEP6
{
internal class WalletLocker : IDisposable
{
private NEP6Wallet wallet;
public WalletLocker(NEP6Wallet wallet)
{
this.wallet = wallet;
}
public void Dispose()
{
wallet.Lock();
}
}
}
| 16.05 | 46 | 0.53271 | [
"MIT"
] | ProDog/Zoro | Zoro/Wallets/NEP6/WalletLocker.cs | 323 | C# |
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using Abp.Application.Services.Dto;
using TrackingSystem.Users;
using TrackingSystem.Users.Dto;
namespace TrackingSystem.Tests.Users
{
public class UserAppServiceTests : TrackingSystemTestBase
{
private readonly IUserAppService _userAppService;
public UserAppServiceTests()
{
_userAppService = Resolve<IUserAppService>();
}
[Fact]
public async Task GetUsers_Test()
{
// Act
var output = await _userAppService.GetAll(new PagedResultRequestDto{MaxResultCount=20, SkipCount=0} );
// Assert
output.Items.Count.ShouldBeGreaterThan(0);
}
[Fact]
public async Task CreateUser_Test()
{
// Act
await _userAppService.Create(
new CreateUserDto
{
EmailAddress = "john@volosoft.com",
IsActive = true,
Name = "John",
Surname = "Nash",
Password = "123qwe",
UserName = "john.nash"
});
await UsingDbContextAsync(async context =>
{
var johnNashUser = await context.Users.FirstOrDefaultAsync(u => u.UserName == "john.nash");
johnNashUser.ShouldNotBeNull();
});
}
}
}
| 27.886792 | 114 | 0.551421 | [
"MIT"
] | Sandeep321/TrackingSystem | test/TrackingSystem.Tests/Users/UserAppService_Tests.cs | 1,480 | C# |
// ILegalMarketingErrorsBuilder
using Disney.Mix.SDK;
using Disney.Mix.SDK.Internal;
using Disney.Mix.SDK.Internal.GuestControllerDomain;
using System;
public interface ILegalMarketingErrorsBuilder
{
void BuildErrors(ISession session, GuestApiErrorCollection errors, Action<BuildLegalMarketingErrorsResult> successCallback, Action failureCallback);
}
| 32.090909 | 149 | 0.855524 | [
"MIT"
] | smdx24/CPI-Source-Code | Disney.Mix.SDK.Internal/ILegalMarketingErrorsBuilder.cs | 353 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ExcelWebProject
{
public class CSVExcelConfig
{
public CSVExcelConfig()
{
GravarEmFormatoTexto = false;
TrimFields = false;
}
public bool GravarEmFormatoTexto { get; set; }
public bool TrimFields { get; set; }
}
} | 19.4 | 54 | 0.618557 | [
"Apache-2.0"
] | Paulofsr/excel-example | ExcelWebProject/ExcelWebProject/CSVExcelConfig.cs | 390 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace _08._Custom_Comparator
{
class Program
{
class MyComparator : IComparer<int>
{
public int Compare(int x, int y)
{
int compare = Math.Abs(x % 2).CompareTo(Math.Abs(y % 2));
if (compare == 0)
{
compare = x.CompareTo(y);
}
return compare;
}
}
static void Main(string[] args)
{
int[] arr = Console.ReadLine()
.Split()
.Select(int.Parse)
.ToArray();
Array.Sort(arr, new MyComparator());
Console.WriteLine(string.Join(" ", arr));
}
}
}
| 22.628571 | 73 | 0.448232 | [
"Apache-2.0"
] | Vladimir-Dodnikov/CSharp---Advanced | 05. Functional Programming - Exercise/08. Custom Comparator/Program.cs | 794 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the codecommit-2015-04-13.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.CodeCommit.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CodeCommit.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ConcurrentReferenceUpdateException Object
/// </summary>
public class ConcurrentReferenceUpdateExceptionUnmarshaller : IErrorResponseUnmarshaller<ConcurrentReferenceUpdateException, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public ConcurrentReferenceUpdateException Unmarshall(JsonUnmarshallerContext context)
{
return this.Unmarshall(context, new ErrorResponse());
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <param name="errorResponse"></param>
/// <returns></returns>
public ConcurrentReferenceUpdateException Unmarshall(JsonUnmarshallerContext context, ErrorResponse errorResponse)
{
context.Read();
ConcurrentReferenceUpdateException unmarshalledObject = new ConcurrentReferenceUpdateException(errorResponse.Message, errorResponse.InnerException,
errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
}
return unmarshalledObject;
}
private static ConcurrentReferenceUpdateExceptionUnmarshaller _instance = new ConcurrentReferenceUpdateExceptionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static ConcurrentReferenceUpdateExceptionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.058824 | 159 | 0.681892 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/CodeCommit/Generated/Model/Internal/MarshallTransformations/ConcurrentReferenceUpdateExceptionUnmarshaller.cs | 3,065 | C# |
using System;
using Aspose.Cells;
using System.Data;
namespace Aspose.Cells.Examples.CSharp.Articles
{
public class GetSmartMarkerNotifications
{
public static void Run()
{
//Source directory
string sourceDir = RunExamples.Get_SourceDirectory();
//Output directory
string outputDir = RunExamples.Get_OutputDirectory();
// Creating a DataTable that will serve as data source for designer spreadsheet
DataTable table = new DataTable("OppLineItems");
table.Columns.Add("PRODUCT_FAMILY");
table.Columns.Add("OPPORTUNITY_LINEITEM_PRODUCTNAME");
table.Rows.Add(new object[] { "MMM", "P1" });
table.Rows.Add(new object[] { "MMM", "P2" });
table.Rows.Add(new object[] { "DDD", "P1" });
table.Rows.Add(new object[] { "DDD", "P2" });
table.Rows.Add(new object[] { "AAA", "P1" });
// Loading the designer spreadsheet in an instance of Workbook
Workbook workbook = new Workbook(sourceDir + "sampleGetSmartMarkerNotifications.xlsx");
// Loading the instance of Workbook in an instance of WorkbookDesigner
WorkbookDesigner designer = new WorkbookDesigner(workbook);
// Set the WorkbookDesigner.CallBack property to an instance of newly created class
designer.CallBack = new SmartMarkerCallBack(workbook);
// Set the data source
designer.SetDataSource(table);
// Process the Smart Markers in the designer spreadsheet
designer.Process(false);
// Save the result
workbook.Save(outputDir + "outputGetSmartMarkerNotifications.xlsx");
Console.WriteLine("GetSmartMarkerNotifications executed successfully.");
}
}
class SmartMarkerCallBack: ISmartMarkerCallBack
{
Workbook workbook;
public SmartMarkerCallBack(Workbook workbook) {
this.workbook = workbook;
}
public void Process(int sheetIndex, int rowIndex, int colIndex, String tableName, String columnName) {
Console.WriteLine("Processing Cell: " + workbook.Worksheets[sheetIndex].Name + "!" + CellsHelper.CellIndexToName(rowIndex, colIndex));
Console.WriteLine("Processing Marker: " + tableName + "." + columnName);
}
}
}
| 38.174603 | 146 | 0.631601 | [
"MIT"
] | aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/Articles/GetSmartMarkerNotifications.cs | 2,407 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
namespace MessyCoderCommunity.AI.NavMeshMovement
{
/// <summary>
/// Wander semi-randomly such that the character looks like they have intent.
/// </summary>
[CreateAssetMenu(fileName = "Wander with Intent Behaviour", menuName = "Messy AI/Movement/Nav Mesh/Wander with Intent")]
public class WanderWithIntent : GenericAiBehaviour<NavMeshAgent>
{
[SerializeField, Tooltip("How close does the agent need to be to a target to be deemed to have reached that target.")]
public float minimumReachDistance = 0.25f;
[SerializeField, Tooltip("What is the minimum distance the agent should be prepared to wander, time allowing? " +
"When a new targt is selected a target at a distance between this and the max distance is selected. ")]
public float minDistanceOfRandomPathChange = 10f;
[SerializeField, Tooltip("What is the maximum distance the agent should be prepared to wander, time allowing? " +
"When a new targt is selected a target at a distance between this and the min distance is selected. ")]
public float maxDistanceOfRandomPathChange = 20f;
[SerializeField, Tooltip("What is the minimum angle from the current path the agent should be prepared to wander? " +
"When a new targt is selected a target at an angle between this and the max angle is selected. ")]
public float minAngleOfRandomPathChange = -30;
[SerializeField, Tooltip("What is the minimum angle from the current path the agent should be prepared to wander? " +
"When a new targt is selected a target at an angle between this and the max angle is selected. ")]
public float maxAngleOfRandomPathChange = 30;
[SerializeField, Tooltip("How far from the Home position (the starting position of this agent) will the agent be " +
"allowed to wander? If a destination cannot be found within this range the AI will turn around " +
"and head back towards home.")]
public float maxRange = 100;
private Vector3 homePosition;
private float sqrMagnitudeRange;
NavMeshAgent navMeshAgent = null;
public override void Initialize(GameObject agent, IChalkboard chalkboard)
{
base.Initialize(agent, chalkboard);
homePosition = agent.transform.position;
sqrMagnitudeRange = maxRange * maxRange;
navMeshAgent = agent.GetComponent<NavMeshAgent>();
Debug.Assert(navMeshAgent != null, "MoveTo behaviour requires a NavMeshAgent component on the agent.");
}
public override void Tick(IChalkboard chalkboard)
{
navMeshAgent.SetDestination(GetValidWanderPosition(navMeshAgent.transform, 0));
navMeshAgent.isStopped = false;
}
private Vector3 GetValidWanderPosition(Transform transform, int attemptCount)
{
int maxAttempts = 6;
bool turnAround = false;
attemptCount++;
if (attemptCount > maxAttempts)
{
return homePosition;
}
else if (attemptCount > maxAttempts / 2)
{
turnAround = true;
}
Vector3 position;
float minDistance = minDistanceOfRandomPathChange;
float maxDistance = maxDistanceOfRandomPathChange;
Quaternion randAng;
if (!turnAround)
{
randAng = Quaternion.Euler(0, UnityEngine.Random.Range(minAngleOfRandomPathChange, maxAngleOfRandomPathChange), 0);
}
else
{
randAng = Quaternion.Euler(0, UnityEngine.Random.Range(180 - minAngleOfRandomPathChange, 180 + maxAngleOfRandomPathChange), 0);
minDistance = maxDistance;
}
position = transform.position + randAng * transform.forward * UnityEngine.Random.Range(minDistance, maxDistance);
// TODO: should handle height on multiple terrains
// TODO: should handle height on meshes too
if (UnityEngine.Terrain.activeTerrain != null)
{
position.y = UnityEngine.Terrain.activeTerrain.SampleHeight(position);
}
NavMeshHit hit;
if (NavMesh.SamplePosition(position, out hit, 1.0f, NavMesh.AllAreas))
{
position = hit.position;
}
else
{
GetValidWanderPosition(transform, attemptCount);
}
if (Vector3.SqrMagnitude(homePosition - position) > sqrMagnitudeRange)
{
return homePosition;
}
return position;
}
public override void OnDrawGizmosSelected(UnityEngine.Object agent)
{
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(((NavMeshAgent)agent).destination, 0.25f);
Gizmos.color = Color.gray;
Gizmos.DrawCube(homePosition, new Vector3(0.25f, 0.25f, 0.25f));
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(homePosition, maxRange);
}
}
}
| 42.846774 | 143 | 0.630529 | [
"Apache-2.0"
] | MessyCoderCommunity/AI-Playground | Assets/_Challenges/Scripts/AI Behaviours/Movement/NavMesh/WanderWithIntent.cs | 5,315 | C# |
namespace Up.NET.Api.Webhooks.Logs;
public class WebhookDeliveryLogRequest
{
public string Body { get; set; }
} | 19.5 | 38 | 0.74359 | [
"MIT"
] | Hona/Up.NET | Up.NET/Api/Webhooks/Logs/WebhookDeliveryLogRequest.cs | 119 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace DrawManager.Api.Entities
{
public class Prize
{
/// <summary>
/// Id del premio. Autogenerado. Llave primaria.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Nombre del premio.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Descripción del premio.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Intentos perdedores para escoger el ganador del premio.
/// </summary>
public int AttemptsUntilChooseWinner { get; set; }
/// <summary>
/// Fecha de entrega del premio.
/// </summary>
public DateTime? ExecutedOn { get; set; }
/// <summary>
/// Id del sorteo al que pertenece. Llave foránea.
/// </summary>
public int DrawId { get; set; }
/// <summary>
/// Bandera que indica si el premio ya fue entregado.
/// </summary>
public bool Delivered => SelectionSteps.Count == AttemptsUntilChooseWinner + 1 && SelectionSteps.Any(st => st.PrizeSelectionStepType == PrizeSelectionStepType.Winner);
/// <summary>
/// Sorteo.
/// </summary>
public Draw Draw { get; set; }
/// <summary>
/// Pasos de selección.
/// </summary>
public List<PrizeSelectionStep> SelectionSteps { get; set; }
public Prize()
{
SelectionSteps = new List<PrizeSelectionStep>();
}
}
}
| 29.981481 | 175 | 0.543545 | [
"MIT"
] | javico02/DrawManager | src/DrawManager.Api/Entities/Prize.cs | 1,624 | 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 lambda-2015-03-31.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.Lambda.Model
{
///<summary>
/// Lambda exception
/// </summary>
#if !PCL && !CORECLR
[Serializable]
#endif
public class KMSAccessDeniedException : AmazonLambdaException
{
/// <summary>
/// Constructs a new KMSAccessDeniedException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public KMSAccessDeniedException(string message)
: base(message) {}
/// <summary>
/// Construct instance of KMSAccessDeniedException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public KMSAccessDeniedException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of KMSAccessDeniedException
/// </summary>
/// <param name="innerException"></param>
public KMSAccessDeniedException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of KMSAccessDeniedException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public KMSAccessDeniedException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of KMSAccessDeniedException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public KMSAccessDeniedException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !PCL && !CORECLR
/// <summary>
/// Constructs a new instance of the KMSAccessDeniedException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected KMSAccessDeniedException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
} | 42.814433 | 178 | 0.647484 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/Lambda/Generated/Model/KMSAccessDeniedException.cs | 4,153 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RDAGen.RDA_Data
{
/// <summary>
/// Lista de convenios para o ListView
/// </summary>
public class AgreementList
{
public ObservableCollection<AgreementDescriptor> List { get; set; } = new ObservableCollection<AgreementDescriptor>();
}
/// <summary>
/// Descritor de Convenio
/// </summary>
public class AgreementDescriptor
{
public string AgreementNumber { get; set; }
public string StartDate { get; set; }
public string EndDate{ get; set; }
public AgreementDescriptor(string number, string start, string end)
{
AgreementNumber = number;
StartDate = start;
EndDate = end;
}
}
}
| 25.371429 | 126 | 0.636261 | [
"Unlicense"
] | rcaropreso/RDAGen | RDAGen/RDA_Data/AgreementDescriptor.cs | 890 | C# |
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using xLiAd.DiagnosticLogCenter.Agent.DiagnosticProcessors;
using xLiAd.DiagnosticLogCenter.Agent.Helper;
using xLiAd.DiagnosticLogCenter.Agent.Logger;
namespace xLiAd.DiagnosticLogCenter.Agent
{
public static class Extension
{
public static IServiceCollection AddDiagnosticLog(this IServiceCollection services, Action<DiagnosticLogConfig> action = null)
{
DiagnosticLogConfig config = new DiagnosticLogConfig();
action?.Invoke(config);
if (!config.Enable)
return services;
DiagnosticLogConfig.Config = config;
services.AddSingleton<ITracingDiagnosticProcessor, AspNetCoreDiagnosticProcessor>();
if (config.EnableDapperEx)
services.AddSingleton<ITracingDiagnosticProcessor, DapperExDiagnosticProcessor>();
if (config.EnableHttpClient)
services.AddSingleton<ITracingDiagnosticProcessor, HttpClientDiagnosticProcessor>();
if (config.EnableMethod)
services.AddSingleton<ITracingDiagnosticProcessor, MethodDiagnosticProcessor>();
if (config.EnableSqlClient)
services.AddSingleton<ITracingDiagnosticProcessor, SqlClientDiagnosticProcessor>();
if (config.EnableSystemLog)
services.AddSingleton<ILoggerProvider, DiagnosticLogCenterLoggerProvider>();
services.AddSingleton<ConsoleDiagnosticProcessor>();
services.AddSingleton<TracingDiagnosticProcessorObserver>();
services.AddSingleton<IHostedService, InstrumentationHostedService>();
FilterRule.AllowPath = config.AllowPath;
FilterRule.ForbbidenPath = config.ForbbidenPath;
PostHelper.Init(config.CollectServerAddress, config.ClientName, config.EnvName, config.TimeoutBySecond);
return services;
}
}
}
| 46.066667 | 134 | 0.7178 | [
"Apache-2.0"
] | zl33842901/DiagnosticLogCenter | xLiAd.DiagnosticLogCenter.Agent/Extension.cs | 2,075 | C# |
// MIT License
//
// Copyright (c) 2021-2022 Rasmus Mikkelsen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
namespace Bake.ValueObjects.Artifacts
{
[Artifact(Names.Artifacts.NuGetArtifact)]
public class NuGetArtifact : FileArtifact
{
[Obsolete]
public NuGetArtifact() { }
public NuGetArtifact(
string path)
: base(path)
{
}
}
}
| 36.45 | 81 | 0.719479 | [
"MIT"
] | rasmus/Bake | Source/Bake/ValueObjects/Artifacts/NuGetArtifact.cs | 1,458 | C# |
using Nefarius.ViGEm.Client.Targets;
using Nefarius.ViGEm.Client.Targets.Xbox360;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
namespace BetterJoyForCemu {
public partial class MainForm : Form {
public bool useControllerStickCalibration;
public bool nonOriginal;
public bool allowCalibration = Boolean.Parse(ConfigurationManager.AppSettings["AllowCalibration"]);
public List<Button> con, loc;
public bool calibrate;
public List<KeyValuePair<string, float[]>> caliData;
private Timer countDown;
private int count;
public List<int> xG, yG, zG, xA, yA, zA;
public bool shakeInputEnabled = Boolean.Parse(ConfigurationManager.AppSettings["EnableShakeInput"]);
public float shakeSesitivity = float.Parse(ConfigurationManager.AppSettings["ShakeInputSensitivity"]);
public float shakeDelay = float.Parse(ConfigurationManager.AppSettings["ShakeInputDelay"]);
public enum NonOriginalController : int {
Disabled = 0,
DefaultCalibration = 1,
ControllerCalibration = 2,
}
public MainForm() {
xG = new List<int>(); yG = new List<int>(); zG = new List<int>();
xA = new List<int>(); yA = new List<int>(); zA = new List<int>();
caliData = new List<KeyValuePair<string, float[]>> {
new KeyValuePair<string, float[]>("0", new float[6] {0,0,0,-710,0,0})
};
SetNonOriginalControllerSettings();
InitializeComponent();
if (!allowCalibration)
AutoCalibrate.Hide();
con = new List<Button> { con1, con2, con3, con4 };
loc = new List<Button> { loc1, loc2, loc3, loc4 };
//list all options
string[] myConfigs = ConfigurationManager.AppSettings.AllKeys;
Size childSize = new Size(150, 20);
for (int i = 0; i != myConfigs.Length; i++) {
settingsTable.RowCount++;
settingsTable.Controls.Add(new Label() { Text = myConfigs[i], TextAlign = ContentAlignment.BottomLeft, AutoEllipsis = true, Size = childSize }, 0, i);
var value = ConfigurationManager.AppSettings[myConfigs[i]];
Control childControl;
if (value == "true" || value == "false") {
childControl = new CheckBox() { Checked = Boolean.Parse(value), Size = childSize };
} else {
childControl = new TextBox() { Text = value, Size = childSize };
}
childControl.MouseClick += cbBox_Changed;
settingsTable.Controls.Add(childControl, 1, i);
}
}
private void SetNonOriginalControllerSettings() {
Enum.TryParse(ConfigurationManager.AppSettings["NonOriginalController"], true, out NonOriginalController nonOriginalController);
switch ((int)nonOriginalController) {
case 0:
nonOriginal = false;
break;
case 1:
case 2:
nonOriginal = true;
break;
}
switch ((int)nonOriginalController) {
case 0:
case 2:
useControllerStickCalibration = true;
break;
case 1:
useControllerStickCalibration = false;
break;
}
}
private void HideToTray() {
this.WindowState = FormWindowState.Minimized;
notifyIcon.Visible = true;
notifyIcon.BalloonTipText = "Double click the tray icon to maximise!";
notifyIcon.ShowBalloonTip(0);
this.ShowInTaskbar = false;
this.Hide();
}
private void ShowFromTray() {
this.Show();
this.WindowState = FormWindowState.Normal;
this.ShowInTaskbar = true;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.Icon = Properties.Resources.betterjoyforcemu_icon;
notifyIcon.Visible = false;
}
private void MainForm_Resize(object sender, EventArgs e) {
if (this.WindowState == FormWindowState.Minimized) {
HideToTray();
}
}
private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e) {
ShowFromTray();
}
private void MainForm_Load(object sender, EventArgs e) {
Config.Init(caliData);
Program.Start();
passiveScanBox.Checked = Config.IntValue("ProgressiveScan") == 1;
startInTrayBox.Checked = Config.IntValue("StartInTray") == 1;
if (Config.IntValue("StartInTray") == 1) {
HideToTray();
} else {
ShowFromTray();
}
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) {
try {
Program.Stop();
Environment.Exit(0);
} catch { }
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e) { // this does not work, for some reason. Fix before release
try {
Program.Stop();
Close();
Environment.Exit(0);
} catch { }
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
donationLink.LinkVisited = true;
System.Diagnostics.Process.Start("http://paypal.me/DavidKhachaturov/5");
}
private void passiveScanBox_CheckedChanged(object sender, EventArgs e) {
Config.SetValue("ProgressiveScan", passiveScanBox.Checked ? "1" : "0");
Config.Save();
}
public void AppendTextBox(string value) { // https://stackoverflow.com/questions/519233/writing-to-a-textbox-from-another-thread
if (InvokeRequired) {
this.Invoke(new Action<string>(AppendTextBox), new object[] { value });
return;
}
console.AppendText(value);
}
bool toRumble = Boolean.Parse(ConfigurationManager.AppSettings["EnableRumble"]);
bool showAsXInput = Boolean.Parse(ConfigurationManager.AppSettings["ShowAsXInput"]);
bool showAsDS4 = Boolean.Parse(ConfigurationManager.AppSettings["ShowAsDS4"]);
public async void locBtnClickAsync(object sender, EventArgs e) {
Button bb = sender as Button;
if (bb.Tag.GetType() == typeof(Button)) {
Button button = bb.Tag as Button;
if (button.Tag.GetType() == typeof(Joycon)) {
Joycon v = (Joycon)button.Tag;
v.SetRumble(160.0f, 320.0f, 1.0f);
await Task.Delay(300);
v.SetRumble(160.0f, 320.0f, 0);
}
}
}
public void conBtnClick(object sender, EventArgs e) {
Button button = sender as Button;
if (button.Tag.GetType() == typeof(Joycon)) {
Joycon v = (Joycon)button.Tag;
if (v.other == null && !v.isPro) { // needs connecting to other joycon (so messy omg)
bool succ = false;
if (Program.mgr.j.Count == 1) { // when want to have a single joycon in vertical mode
v.other = v; // hacky; implement check in Joycon.cs to account for this
succ = true;
} else {
foreach (Joycon jc in Program.mgr.j) {
if (!jc.isPro && jc.isLeft != v.isLeft && jc != v && jc.other == null) {
v.other = jc;
jc.other = v;
//Set both Joycon LEDs to the one with the lowest ID
byte led = jc.LED <= v.LED ? jc.LED : v.LED;
jc.LED = led;
v.LED = led;
jc.SetPlayerLED(led);
v.SetPlayerLED(led);
if (v.out_xbox != null) {
v.out_xbox.Disconnect();
v.out_xbox = null;
}
if (v.out_ds4 != null) {
v.out_ds4.Disconnect();
v.out_ds4 = null;
}
// setting the other joycon's button image
foreach (Button b in con)
if (b.Tag == jc)
b.BackgroundImage = jc.isLeft ? Properties.Resources.jc_left : Properties.Resources.jc_right;
succ = true;
break;
}
}
}
if (succ)
foreach (Button b in con)
if (b.Tag == v)
b.BackgroundImage = v.isLeft ? Properties.Resources.jc_left : Properties.Resources.jc_right;
} else if (v.other != null && !v.isPro) { // needs disconnecting from other joycon
ReenableViGEm(v);
ReenableViGEm(v.other);
button.BackgroundImage = v.isLeft ? Properties.Resources.jc_left_s : Properties.Resources.jc_right_s;
foreach (Button b in con)
if (b.Tag == v.other)
b.BackgroundImage = v.other.isLeft ? Properties.Resources.jc_left_s : Properties.Resources.jc_right_s;
//Set original Joycon LEDs
v.other.LED = (byte)(0x1 << v.other.PadId);
v.LED = (byte)(0x1 << v.PadId);
v.other.SetPlayerLED(v.other.LED);
v.SetPlayerLED(v.LED);
v.other.other = null;
v.other = null;
}
}
}
private void startInTrayBox_CheckedChanged(object sender, EventArgs e) {
Config.SetValue("StartInTray", startInTrayBox.Checked ? "1" : "0");
Config.Save();
}
private void btn_open3rdP_Click(object sender, EventArgs e) {
_3rdPartyControllers partyForm = new _3rdPartyControllers();
partyForm.ShowDialog();
}
private void settingsApply_Click(object sender, EventArgs e) {
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configFile.AppSettings.Settings;
for (int row = 0; row < ConfigurationManager.AppSettings.AllKeys.Length; row++) {
var valCtl = settingsTable.GetControlFromPosition(1, row);
var KeyCtl = settingsTable.GetControlFromPosition(0, row).Text;
if (valCtl.GetType() == typeof(CheckBox) && settings[KeyCtl] != null) {
settings[KeyCtl].Value = ((CheckBox)valCtl).Checked.ToString().ToLower();
} else if (valCtl.GetType() == typeof(TextBox) && settings[KeyCtl] != null) {
settings[KeyCtl].Value = ((TextBox)valCtl).Text.ToLower();
}
}
try {
configFile.Save(ConfigurationSaveMode.Modified);
} catch (ConfigurationErrorsException) {
AppendTextBox("Error writing app settings.\r\n");
}
ConfigurationManager.AppSettings["AutoPowerOff"] = "false"; // Prevent joycons poweroff when applying settings
Application.Restart();
Environment.Exit(0);
}
void ReenableViGEm(Joycon v) {
if (showAsXInput && v.out_xbox == null) {
v.out_xbox = new Controller.OutputControllerXbox360();
if (toRumble)
v.out_xbox.FeedbackReceived += v.ReceiveRumble;
v.out_xbox.Connect();
}
if (showAsDS4 && v.out_ds4 == null) {
v.out_ds4 = new Controller.OutputControllerDualShock4();
if (toRumble)
v.out_ds4.FeedbackReceived += v.Ds4_FeedbackReceived;
v.out_ds4.Connect();
}
}
private void foldLbl_Click(object sender, EventArgs e) {
rightPanel.Visible = !rightPanel.Visible;
foldLbl.Text = rightPanel.Visible ? "<" : ">";
}
private void cbBox_Changed(object sender, EventArgs e) {
var coord = settingsTable.GetPositionFromControl(sender as Control);
var valCtl = settingsTable.GetControlFromPosition(coord.Column, coord.Row);
var KeyCtl = settingsTable.GetControlFromPosition(coord.Column - 1, coord.Row).Text;
try {
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configFile.AppSettings.Settings;
if (valCtl.GetType() == typeof(CheckBox) && settings[KeyCtl] != null) {
settings[KeyCtl].Value = ((CheckBox)valCtl).Checked.ToString().ToLower();
} else if (valCtl.GetType() == typeof(TextBox) && settings[KeyCtl] != null) {
settings[KeyCtl].Value = ((TextBox)valCtl).Text.ToLower();
}
if (KeyCtl == "HomeLEDOn") {
bool on = settings[KeyCtl].Value.ToLower() == "true";
foreach (Joycon j in Program.mgr.j) {
j.SetHomeLight(on);
}
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
} catch (ConfigurationErrorsException) {
AppendTextBox("Error writing app settings\r\n");
Trace.WriteLine(String.Format("rw {0}, column {1}, {2}, {3}", coord.Row, coord.Column, sender.GetType(), KeyCtl));
}
}
private void StartCalibrate(object sender, EventArgs e) {
if (Program.mgr.j.Count == 0) {
this.console.Text = "Please connect a single pro controller.";
return;
}
if (Program.mgr.j.Count > 1) {
this.console.Text = "Please calibrate one controller at a time (disconnect others).";
return;
}
this.AutoCalibrate.Enabled = false;
countDown = new Timer();
this.count = 4;
this.CountDown(null, null);
countDown.Tick += new EventHandler(CountDown);
countDown.Interval = 1000;
countDown.Enabled = true;
}
private void StartGetData() {
this.xG.Clear(); this.yG.Clear(); this.zG.Clear();
this.xA.Clear(); this.yA.Clear(); this.zA.Clear();
countDown = new Timer();
this.count = 3;
this.calibrate = true;
countDown.Tick += new EventHandler(CalcData);
countDown.Interval = 1000;
countDown.Enabled = true;
}
private void btn_reassign_open_Click(object sender, EventArgs e) {
Reassign mapForm = new Reassign();
mapForm.ShowDialog();
}
private void CountDown(object sender, EventArgs e) {
if (this.count == 0) {
this.console.Text = "Calibrating...";
countDown.Stop();
this.StartGetData();
} else {
this.console.Text = "Plese keep the controller flat." + "\r\n";
this.console.Text += "Calibration will start in " + this.count + " seconds.";
this.count--;
}
}
private void CalcData(object sender, EventArgs e) {
if (this.count == 0) {
countDown.Stop();
this.calibrate = false;
string serNum = Program.mgr.j.First().serial_number;
int serIndex = this.findSer(serNum);
float[] Arr = new float[6] { 0, 0, 0, 0, 0, 0 };
if (serIndex == -1) {
this.caliData.Add(new KeyValuePair<string, float[]>(
serNum,
Arr
));
} else {
Arr = this.caliData[serIndex].Value;
}
Random rnd = new Random();
Arr[0] = (float)quickselect_median(this.xG, rnd.Next);
Arr[1] = (float)quickselect_median(this.yG, rnd.Next);
Arr[2] = (float)quickselect_median(this.zG, rnd.Next);
Arr[3] = (float)quickselect_median(this.xA, rnd.Next);
Arr[4] = (float)quickselect_median(this.yA, rnd.Next);
Arr[5] = (float)quickselect_median(this.zA, rnd.Next) - 4010; //Joycon.cs acc_sen 16384
this.console.Text += "Calibration completed!!!" + "\r\n";
Config.SaveCaliData(this.caliData);
Program.mgr.j.First().getActiveData();
this.AutoCalibrate.Enabled = true;
} else {
this.count--;
}
}
private double quickselect_median(List<int> l, Func<int, int> pivot_fn) {
int ll = l.Count;
if (ll % 2 == 1) {
return this.quickselect(l, ll / 2, pivot_fn);
} else {
return 0.5 * (quickselect(l, ll / 2 - 1, pivot_fn) + quickselect(l, ll / 2, pivot_fn));
}
}
private int quickselect(List<int> l, int k, Func<int, int> pivot_fn) {
if (l.Count == 1 && k == 0) {
return l[0];
}
int pivot = l[pivot_fn(l.Count)];
List<int> lows = l.Where(x => x < pivot).ToList();
List<int> highs = l.Where(x => x > pivot).ToList();
List<int> pivots = l.Where(x => x == pivot).ToList();
if (k < lows.Count) {
return quickselect(lows, k, pivot_fn);
} else if (k < (lows.Count + pivots.Count)) {
return pivots[0];
} else {
return quickselect(highs, k - lows.Count - pivots.Count, pivot_fn);
}
}
public float[] activeCaliData(string serNum) {
for (int i = 0; i < this.caliData.Count; i++) {
if (this.caliData[i].Key == serNum) {
return this.caliData[i].Value;
}
}
return this.caliData[0].Value;
}
private int findSer(string serNum) {
for (int i = 0; i < this.caliData.Count; i++) {
if (this.caliData[i].Key == serNum) {
return i;
}
}
return -1;
}
}
}
| 41.401274 | 166 | 0.51641 | [
"MIT"
] | OhBlihv/BetterJoy | BetterJoyForCemu/MainForm.cs | 19,502 | C# |
using NUnit.Framework;
using System;
using System.Threading;
namespace SignUp.EndToEndTests
{
public static class AssertHelper
{
public static void RetryAssert(int retryInterval, int retryCount, string failureMessage, Func<bool> assertion)
{
var assert = assertion();
var count = 1;
while (assert == false && count < retryCount)
{
Thread.Sleep(retryInterval);
assert = assertion();
count++;
}
Assert.IsTrue(assert, failureMessage);
}
}
}
| 25.913043 | 118 | 0.560403 | [
"MIT"
] | PacktPublishing/Docker-on-Windows | Chapter10/ch10-newsletter/src/SignUp/SignUp.EndToEndTests/AssertHelper.cs | 598 | C# |
namespace SnagCardGameBlazor;
public class Bootstrapper : MultiplayerBasicBootstrapper<SnagCardGameShellViewModel>
{
public Bootstrapper(IStartUp starts, EnumGamePackageMode mode) : base(starts, mode)
{
}
protected override Task ConfigureAsync(IGamePackageRegister register)
{
IBasicDiceGamesData<SimpleDice>.NeedsRollIncrement = true; //default to true.
//if using misc deck, use this line
//register.RegisterSingleton<IDeckCount, SnagCardGameDeckCount>();
SnagCardGameCP.DIFinishProcesses.GlobalDIAutoRegisterClass.RegisterNonSavedClasses(GetDIContainer);
SnagCardGameCP.DIFinishProcesses.SpecializedRegistrationHelpers.RegisterCommonMultplayerClasses(GetDIContainer);
//if using misc deck, then remove this line of code.
SnagCardGameCP.DIFinishProcesses.SpecializedRegularCardHelpers.RegisterRegularDeckOfCardClasses(GetDIContainer);
SnagCardGameCP.DIFinishProcesses.AutoResetClass.RegisterAutoResets();
return Task.CompletedTask;
}
//this part should not change
protected override void FinishRegistrations(IGamePackageRegister register)
{
register.RegisterType<SnagCardGameShellViewModel>(); //has to use interface part to make it work with source generators.
SnagCardGameCP.DIFinishProcesses.GlobalDIFinishClass.FinishDIRegistrations(GetDIContainer);
DIFinishProcesses.GlobalDIFinishClass.FinishDIRegistrations(GetDIContainer);
SnagCardGameCP.AutoResumeContexts.GlobalRegistrations.Register();
}
} | 51.633333 | 128 | 0.785668 | [
"MIT"
] | musictopia2/GamingPackXV3 | Blazor/Games/SnagCardGameBlazor/Bootstrapper.cs | 1,549 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SimpleRotator : MonoBehaviour
{
private void Update()
{
transform.Rotate(0f, 0f, 90f * Time.deltaTime);
}
}
| 18.5 | 55 | 0.702703 | [
"Apache-2.0"
] | aeyonblack/tanya-masvita-software-development-projects | Reborn - Mobile Game Codebase (C#)/Reborn/Assets/Scripts/Utilities/SimpleRotator.cs | 224 | C# |
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace WalletWasabi.Fluent.Views.Wallets.Home.Tiles.WalletBalance
{
public class WalletBalanceWideTileView : UserControl
{
public WalletBalanceWideTileView()
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
} | 18.722222 | 68 | 0.765579 | [
"MIT"
] | BTCparadigm/WalletWasabi | WalletWasabi.Fluent/Views/Wallets/Home/Tiles/WalletBalance/WalletBalanceWideTileView.axaml.cs | 337 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Differencing;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue
{
internal sealed class CSharpEditAndContinueAnalyzer : AbstractEditAndContinueAnalyzer
{
[ExportLanguageServiceFactory(typeof(IEditAndContinueAnalyzer), LanguageNames.CSharp), Shared]
internal sealed class Factory : ILanguageServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory()
{
}
public ILanguageService CreateLanguageService(HostLanguageServices languageServices)
{
return new CSharpEditAndContinueAnalyzer(testFaultInjector: null);
}
}
// Public for testing purposes
public CSharpEditAndContinueAnalyzer(Action<SyntaxNode>? testFaultInjector = null)
: base(testFaultInjector)
{
}
#region Syntax Analysis
private enum BlockPart
{
OpenBrace = DefaultStatementPart,
CloseBrace = 1,
}
private enum ForEachPart
{
ForEach = DefaultStatementPart,
VariableDeclaration = 1,
In = 2,
Expression = 3,
}
private enum SwitchExpressionPart
{
WholeExpression = DefaultStatementPart,
// An active statement that covers IL generated for the decision tree:
// <governing-expression> [|switch { <arm>, ..., <arm> }|]
// This active statement is never a leaf active statement (does not correspond to a breakpoint span).
SwitchBody = 1,
}
/// <returns>
/// <see cref="BaseMethodDeclarationSyntax"/> for methods, operators, constructors, destructors and accessors.
/// <see cref="VariableDeclaratorSyntax"/> for field initializers.
/// <see cref="PropertyDeclarationSyntax"/> for property initializers and expression bodies.
/// <see cref="IndexerDeclarationSyntax"/> for indexer expression bodies.
/// </returns>
internal override SyntaxNode? FindMemberDeclaration(SyntaxNode? root, SyntaxNode node)
{
while (node != root)
{
RoslynDebug.Assert(node is object);
switch (node.Kind())
{
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
return node;
case SyntaxKind.PropertyDeclaration:
// int P { get; } = [|initializer|];
RoslynDebug.Assert(((PropertyDeclarationSyntax)node).Initializer != null);
return node;
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
// Active statements encompassing modifiers or type correspond to the first initialized field.
// [|public static int F = 1|], G = 2;
return ((BaseFieldDeclarationSyntax)node).Declaration.Variables.First();
case SyntaxKind.VariableDeclarator:
// public static int F = 1, [|G = 2|];
RoslynDebug.Assert(node.Parent.IsKind(SyntaxKind.VariableDeclaration));
switch (node.Parent.Parent!.Kind())
{
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
return node;
}
node = node.Parent;
break;
}
node = node.Parent!;
}
return null;
}
/// <returns>
/// Given a node representing a declaration (<paramref name="isMember"/> = true) or a top-level match node (<paramref name="isMember"/> = false) returns:
/// - <see cref="BlockSyntax"/> for method-like member declarations with block bodies (methods, operators, constructors, destructors, accessors).
/// - <see cref="ExpressionSyntax"/> for variable declarators of fields, properties with an initializer expression, or
/// for method-like member declarations with expression bodies (methods, properties, indexers, operators)
///
/// A null reference otherwise.
/// </returns>
internal override SyntaxNode? TryGetDeclarationBody(SyntaxNode node, bool isMember)
{
if (node.IsKind(SyntaxKind.VariableDeclarator, out VariableDeclaratorSyntax? variableDeclarator))
{
return variableDeclarator.Initializer?.Value;
}
return SyntaxUtilities.TryGetMethodDeclarationBody(node);
}
protected override ImmutableArray<ISymbol> GetCapturedVariables(SemanticModel model, SyntaxNode memberBody)
{
Debug.Assert(memberBody.IsKind(SyntaxKind.Block) || memberBody is ExpressionSyntax);
return model.AnalyzeDataFlow(memberBody).Captured;
}
internal override bool HasParameterClosureScope(ISymbol member)
{
// in instance constructor parameters are lifted to a closure different from method body
return (member as IMethodSymbol)?.MethodKind == MethodKind.Constructor;
}
protected override IEnumerable<SyntaxNode> GetVariableUseSites(IEnumerable<SyntaxNode> roots, ISymbol localOrParameter, SemanticModel model, CancellationToken cancellationToken)
{
Debug.Assert(localOrParameter is IParameterSymbol || localOrParameter is ILocalSymbol || localOrParameter is IRangeVariableSymbol);
// not supported (it's non trivial to find all places where "this" is used):
Debug.Assert(!localOrParameter.IsThisParameter());
return from root in roots
from node in root.DescendantNodesAndSelf()
where node.IsKind(SyntaxKind.IdentifierName)
let nameSyntax = (IdentifierNameSyntax)node
where (string?)nameSyntax.Identifier.Value == localOrParameter.Name &&
(model.GetSymbolInfo(nameSyntax, cancellationToken).Symbol?.Equals(localOrParameter) ?? false)
select node;
}
/// <returns>
/// If <paramref name="node"/> is a method, accessor, operator, destructor, or constructor without an initializer,
/// tokens of its block body, or tokens of the expression body.
///
/// If <paramref name="node"/> is an indexer declaration the tokens of its expression body.
///
/// If <paramref name="node"/> is a property declaration the tokens of its expression body or initializer.
///
/// If <paramref name="node"/> is a constructor with an initializer,
/// tokens of the initializer concatenated with tokens of the constructor body.
///
/// If <paramref name="node"/> is a variable declarator of a field with an initializer,
/// tokens of the field initializer.
///
/// Null reference otherwise.
/// </returns>
internal override IEnumerable<SyntaxToken>? TryGetActiveTokens(SyntaxNode node)
{
if (node.IsKind(SyntaxKind.VariableDeclarator))
{
// TODO: The logic is similar to BreakpointSpans.TryCreateSpanForVariableDeclaration. Can we abstract it?
var declarator = node;
var fieldDeclaration = (BaseFieldDeclarationSyntax)declarator.Parent!.Parent!;
var variableDeclaration = fieldDeclaration.Declaration;
if (fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword))
{
return null;
}
if (variableDeclaration.Variables.Count == 1)
{
if (variableDeclaration.Variables[0].Initializer == null)
{
return null;
}
return fieldDeclaration.Modifiers.Concat(variableDeclaration.DescendantTokens()).Concat(fieldDeclaration.SemicolonToken);
}
if (declarator == variableDeclaration.Variables[0])
{
return fieldDeclaration.Modifiers.Concat(variableDeclaration.Type.DescendantTokens()).Concat(node.DescendantTokens());
}
return declarator.DescendantTokens();
}
var bodyTokens = SyntaxUtilities.TryGetMethodDeclarationBody(node)?.DescendantTokens();
if (node.IsKind(SyntaxKind.ConstructorDeclaration, out ConstructorDeclarationSyntax? ctor))
{
if (ctor.Initializer != null)
{
bodyTokens = ctor.Initializer.DescendantTokens().Concat(bodyTokens);
}
}
return bodyTokens;
}
protected override SyntaxNode GetEncompassingAncestorImpl(SyntaxNode bodyOrMatchRoot)
{
// Constructor may contain active nodes outside of its body (constructor initializer),
// but within the body of the member declaration (the parent).
if (bodyOrMatchRoot.Parent.IsKind(SyntaxKind.ConstructorDeclaration))
{
return bodyOrMatchRoot.Parent;
}
// Field initializer match root -- an active statement may include the modifiers
// and type specification of the field declaration.
if (bodyOrMatchRoot.IsKind(SyntaxKind.EqualsValueClause) &&
bodyOrMatchRoot.Parent.IsKind(SyntaxKind.VariableDeclarator) &&
bodyOrMatchRoot.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration))
{
return bodyOrMatchRoot.Parent.Parent;
}
// Field initializer body -- an active statement may include the modifiers
// and type specification of the field declaration.
if (bodyOrMatchRoot.Parent.IsKind(SyntaxKind.EqualsValueClause) &&
bodyOrMatchRoot.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator) &&
bodyOrMatchRoot.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration))
{
return bodyOrMatchRoot.Parent.Parent.Parent;
}
// otherwise all active statements are covered by the body/match root itself:
return bodyOrMatchRoot;
}
protected override SyntaxNode FindStatementAndPartner(SyntaxNode declarationBody, TextSpan span, SyntaxNode? partnerDeclarationBody, out SyntaxNode? partner, out int statementPart)
{
var position = span.Start;
SyntaxUtilities.AssertIsBody(declarationBody, allowLambda: false);
if (position < declarationBody.SpanStart)
{
// Only constructors and the field initializers may have an [|active statement|] starting outside of the <<body>>.
// Constructor: [|public C()|] <<{ }>>
// Constructor initializer: public C() : [|base(expr)|] <<{ }>>
// Constructor initializer with lambda: public C() : base(() => { [|...|] }) <<{ }>>
// Field initializers: [|public int a = <<expr>>|], [|b = <<expr>>|];
// No need to special case property initializers here, the active statement always spans the initializer expression.
if (declarationBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration))
{
var constructor = (ConstructorDeclarationSyntax)declarationBody.Parent;
var partnerConstructor = (ConstructorDeclarationSyntax?)partnerDeclarationBody?.Parent;
if (constructor.Initializer == null || position < constructor.Initializer.ColonToken.SpanStart)
{
statementPart = DefaultStatementPart;
partner = partnerConstructor;
return constructor;
}
declarationBody = constructor.Initializer;
partnerDeclarationBody = partnerConstructor?.Initializer;
}
}
if (!declarationBody.FullSpan.Contains(position))
{
// invalid position, let's find a labeled node that encompasses the body:
position = declarationBody.SpanStart;
}
SyntaxNode node;
if (partnerDeclarationBody != null)
{
SyntaxUtilities.FindLeafNodeAndPartner(declarationBody, position, partnerDeclarationBody, out node, out partner);
}
else
{
node = declarationBody.FindToken(position).Parent!;
partner = null;
}
while (true)
{
var isBody = node == declarationBody || LambdaUtilities.IsLambdaBodyStatementOrExpression(node);
if (isBody || SyntaxComparer.Statement.HasLabel(node))
{
switch (node.Kind())
{
case SyntaxKind.Block:
statementPart = (int)GetStatementPart((BlockSyntax)node, position);
return node;
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
Debug.Assert(!isBody);
statementPart = (int)GetStatementPart((CommonForEachStatementSyntax)node, position);
return node;
case SyntaxKind.DoStatement:
// The active statement of DoStatement node is the while condition,
// which is lexically not the closest breakpoint span (the body is).
// do { ... } [|while (condition);|]
Debug.Assert(position == ((DoStatementSyntax)node).WhileKeyword.SpanStart);
Debug.Assert(!isBody);
goto default;
case SyntaxKind.PropertyDeclaration:
// The active span corresponding to a property declaration is the span corresponding to its initializer (if any),
// not the span corresponding to the accessor.
// int P { [|get;|] } = [|<initializer>|];
Debug.Assert(position == ((PropertyDeclarationSyntax)node).Initializer!.SpanStart);
goto default;
case SyntaxKind.VariableDeclaration:
// VariableDeclaration ::= TypeSyntax CommaSeparatedList(VariableDeclarator)
//
// The compiler places sequence points after each local variable initialization.
// The TypeSyntax is considered to be part of the first sequence span.
Debug.Assert(!isBody);
node = ((VariableDeclarationSyntax)node).Variables.First();
if (partner != null)
{
partner = ((VariableDeclarationSyntax)partner).Variables.First();
}
statementPart = DefaultStatementPart;
return node;
case SyntaxKind.SwitchExpression:
// An active statement that covers IL generated for the decision tree:
// <governing-expression> [|switch { <arm>, ..., <arm> }|]
// This active statement is never a leaf active statement (does not correspond to a breakpoint span).
var switchExpression = (SwitchExpressionSyntax)node;
if (position == switchExpression.SwitchKeyword.SpanStart)
{
Debug.Assert(span.End == switchExpression.CloseBraceToken.Span.End);
statementPart = (int)SwitchExpressionPart.SwitchBody;
return node;
}
// The switch expression itself can be (a part of) an active statement associated with the containing node
// For example, when it is used as a switch arm expression like so:
// <expr> switch { <pattern> [|when <expr> switch { ... }|] ... }
Debug.Assert(position == switchExpression.Span.Start);
if (isBody)
{
goto default;
}
// ascend to parent node:
break;
case SyntaxKind.SwitchExpressionArm:
// An active statement may occur in the when clause and in the arm expression:
// <constant-pattern> [|when <condition>|] => [|<expression>|]
// The former is covered by when-clause node - it's a labeled node.
// The latter isn't enclosed in a distinct labeled syntax node and thus needs to be covered
// by the arm node itself.
Debug.Assert(position == ((SwitchExpressionArmSyntax)node).Expression.SpanStart);
Debug.Assert(!isBody);
goto default;
default:
statementPart = DefaultStatementPart;
return node;
}
}
node = node.Parent!;
if (partner != null)
{
partner = partner.Parent;
}
}
}
private static BlockPart GetStatementPart(BlockSyntax node, int position)
=> position < node.OpenBraceToken.Span.End ? BlockPart.OpenBrace : BlockPart.CloseBrace;
private static TextSpan GetActiveSpan(BlockSyntax node, BlockPart part)
=> part switch
{
BlockPart.OpenBrace => node.OpenBraceToken.Span,
BlockPart.CloseBrace => node.CloseBraceToken.Span,
_ => throw ExceptionUtilities.UnexpectedValue(part),
};
private static ForEachPart GetStatementPart(CommonForEachStatementSyntax node, int position)
=> position < node.OpenParenToken.SpanStart ? ForEachPart.ForEach :
position < node.InKeyword.SpanStart ? ForEachPart.VariableDeclaration :
position < node.Expression.SpanStart ? ForEachPart.In :
ForEachPart.Expression;
private static TextSpan GetActiveSpan(ForEachStatementSyntax node, ForEachPart part)
=> part switch
{
ForEachPart.ForEach => node.ForEachKeyword.Span,
ForEachPart.VariableDeclaration => TextSpan.FromBounds(node.Type.SpanStart, node.Identifier.Span.End),
ForEachPart.In => node.InKeyword.Span,
ForEachPart.Expression => node.Expression.Span,
_ => throw ExceptionUtilities.UnexpectedValue(part),
};
private static TextSpan GetActiveSpan(ForEachVariableStatementSyntax node, ForEachPart part)
=> part switch
{
ForEachPart.ForEach => node.ForEachKeyword.Span,
ForEachPart.VariableDeclaration => TextSpan.FromBounds(node.Variable.SpanStart, node.Variable.Span.End),
ForEachPart.In => node.InKeyword.Span,
ForEachPart.Expression => node.Expression.Span,
_ => throw ExceptionUtilities.UnexpectedValue(part),
};
private static TextSpan GetActiveSpan(SwitchExpressionSyntax node, SwitchExpressionPart part)
=> part switch
{
SwitchExpressionPart.WholeExpression => node.Span,
SwitchExpressionPart.SwitchBody => TextSpan.FromBounds(node.SwitchKeyword.SpanStart, node.CloseBraceToken.Span.End),
_ => throw ExceptionUtilities.UnexpectedValue(part),
};
protected override bool AreEquivalent(SyntaxNode left, SyntaxNode right)
=> SyntaxFactory.AreEquivalent(left, right);
private static bool AreEquivalentIgnoringLambdaBodies(SyntaxNode left, SyntaxNode right)
{
// usual case:
if (SyntaxFactory.AreEquivalent(left, right))
{
return true;
}
return LambdaUtilities.AreEquivalentIgnoringLambdaBodies(left, right);
}
internal override SyntaxNode FindPartner(SyntaxNode leftRoot, SyntaxNode rightRoot, SyntaxNode leftNode)
=> SyntaxUtilities.FindPartner(leftRoot, rightRoot, leftNode);
internal override SyntaxNode? FindPartnerInMemberInitializer(SemanticModel leftModel, INamedTypeSymbol leftType, SyntaxNode leftNode, INamedTypeSymbol rightType, CancellationToken cancellationToken)
{
var leftEqualsClause = leftNode.FirstAncestorOrSelf<EqualsValueClauseSyntax>(
node => node.Parent.IsKind(SyntaxKind.PropertyDeclaration) || node.Parent!.Parent!.Parent.IsKind(SyntaxKind.FieldDeclaration));
if (leftEqualsClause == null)
{
return null;
}
SyntaxNode? rightEqualsClause;
if (leftEqualsClause.Parent.IsKind(SyntaxKind.PropertyDeclaration, out PropertyDeclarationSyntax? leftDeclaration))
{
var leftSymbol = leftModel.GetDeclaredSymbol(leftDeclaration, cancellationToken);
RoslynDebug.Assert(leftSymbol != null);
var rightProperty = rightType.GetMembers(leftSymbol.Name).Single();
var rightDeclaration = (PropertyDeclarationSyntax)GetSymbolSyntax(rightProperty, cancellationToken);
rightEqualsClause = rightDeclaration.Initializer;
}
else
{
var leftDeclarator = (VariableDeclaratorSyntax)leftEqualsClause.Parent!;
var leftSymbol = leftModel.GetDeclaredSymbol(leftDeclarator, cancellationToken);
RoslynDebug.Assert(leftSymbol != null);
var rightField = rightType.GetMembers(leftSymbol.Name).Single();
var rightDeclarator = (VariableDeclaratorSyntax)GetSymbolSyntax(rightField, cancellationToken);
rightEqualsClause = rightDeclarator.Initializer;
}
if (rightEqualsClause == null)
{
return null;
}
return FindPartner(leftEqualsClause, rightEqualsClause, leftNode);
}
internal override bool IsClosureScope(SyntaxNode node)
=> LambdaUtilities.IsClosureScope(node);
protected override SyntaxNode? FindEnclosingLambdaBody(SyntaxNode? container, SyntaxNode node)
{
var root = GetEncompassingAncestor(container);
var current = node;
while (current != root && current != null)
{
if (LambdaUtilities.IsLambdaBodyStatementOrExpression(current, out var body))
{
return body;
}
current = current.Parent;
}
return null;
}
protected override IEnumerable<SyntaxNode> GetLambdaBodyExpressionsAndStatements(SyntaxNode lambdaBody)
=> SpecializedCollections.SingletonEnumerable(lambdaBody);
protected override SyntaxNode? TryGetPartnerLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda)
=> LambdaUtilities.TryGetCorrespondingLambdaBody(oldBody, newLambda);
protected override Match<SyntaxNode> ComputeTopLevelMatch(SyntaxNode oldCompilationUnit, SyntaxNode newCompilationUnit)
=> SyntaxComparer.TopLevel.ComputeMatch(oldCompilationUnit, newCompilationUnit);
protected override Match<SyntaxNode> ComputeBodyMatch(SyntaxNode oldBody, SyntaxNode newBody, IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>>? knownMatches)
{
SyntaxUtilities.AssertIsBody(oldBody, allowLambda: true);
SyntaxUtilities.AssertIsBody(newBody, allowLambda: true);
if (oldBody is ExpressionSyntax || newBody is ExpressionSyntax || (oldBody.Parent.IsKind(SyntaxKind.LocalFunctionStatement) && newBody.Parent.IsKind(SyntaxKind.LocalFunctionStatement)))
{
Debug.Assert(oldBody is ExpressionSyntax || oldBody is BlockSyntax);
Debug.Assert(newBody is ExpressionSyntax || newBody is BlockSyntax);
// The matching algorithm requires the roots to match each other.
// Lambda bodies, field/property initializers, and method/property/indexer/operator expression-bodies may also be lambda expressions.
// Say we have oldBody 'x => x' and newBody 'F(x => x + 1)', then
// the algorithm would match 'x => x' to 'F(x => x + 1)' instead of
// matching 'x => x' to 'x => x + 1'.
// We use the parent node as a root:
// - for field/property initializers the root is EqualsValueClause.
// - for member expression-bodies the root is ArrowExpressionClauseSyntax.
// - for block bodies the root is a method/operator/accessor declaration (only happens when matching expression body with a block body)
// - for lambdas the root is a LambdaExpression.
// - for query lambdas the root is the query clause containing the lambda (e.g. where).
// - for local functions the root is LocalFunctionStatement.
static SyntaxNode GetMatchingRoot(SyntaxNode body)
{
var parent = body.Parent!;
// We could apply this change across all ArrowExpressionClause consistently not just for ones with LocalFunctionStatement parents
// but it would require an essential refactoring.
return parent.IsKind(SyntaxKind.ArrowExpressionClause) && parent.Parent.IsKind(SyntaxKind.LocalFunctionStatement) ? parent.Parent : parent;
}
var oldRoot = GetMatchingRoot(oldBody);
var newRoot = GetMatchingRoot(newBody);
return new SyntaxComparer(oldRoot, newRoot, GetChildNodes(oldRoot, oldBody), GetChildNodes(newRoot, newBody), compareStatementSyntax: true).ComputeMatch(oldRoot, newRoot, knownMatches);
}
if (oldBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration))
{
// We need to include constructor initializer in the match, since it may contain lambdas.
// Use the constructor declaration as a root.
RoslynDebug.Assert(oldBody.IsKind(SyntaxKind.Block));
RoslynDebug.Assert(newBody.IsKind(SyntaxKind.Block));
RoslynDebug.Assert(newBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration));
RoslynDebug.Assert(newBody.Parent is object);
return SyntaxComparer.Statement.ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches);
}
return SyntaxComparer.Statement.ComputeMatch(oldBody, newBody, knownMatches);
}
private static IEnumerable<SyntaxNode> GetChildNodes(SyntaxNode root, SyntaxNode body)
{
if (root is LocalFunctionStatementSyntax localFunc)
{
// local functions have multiple children we need to process for matches, but we won't automatically
// descend into them, assuming they're nested, so we override the default behaviour and return
// multiple children
foreach (var attributeList in localFunc.AttributeLists)
{
yield return attributeList;
}
yield return localFunc.ReturnType;
if (localFunc.TypeParameterList is not null)
{
yield return localFunc.TypeParameterList;
}
yield return localFunc.ParameterList;
if (localFunc.Body is not null)
{
yield return localFunc.Body;
}
else if (localFunc.ExpressionBody is not null)
{
// Skip the ArrowExpressionClause that is ExressionBody and just return the expression itself
yield return localFunc.ExpressionBody.Expression;
}
}
else
{
yield return body;
}
}
protected override void ReportLocalFunctionsDeclarationRudeEdits(Match<SyntaxNode> bodyMatch, List<RudeEditDiagnostic> diagnostics)
{
var bodyEditsForLambda = bodyMatch.GetTreeEdits();
var editMap = BuildEditMap(bodyEditsForLambda);
foreach (var edit in bodyEditsForLambda.Edits)
{
if (HasParentEdit(editMap, edit))
{
return;
}
var classifier = new EditClassifier(this, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, bodyMatch, classifyStatementSyntax: true);
classifier.ClassifyEdit();
}
}
protected override bool TryMatchActiveStatement(
SyntaxNode oldStatement,
int statementPart,
SyntaxNode oldBody,
SyntaxNode newBody,
[NotNullWhen(true)] out SyntaxNode? newStatement)
{
SyntaxUtilities.AssertIsBody(oldBody, allowLambda: true);
SyntaxUtilities.AssertIsBody(newBody, allowLambda: true);
switch (oldStatement.Kind())
{
case SyntaxKind.ThisConstructorInitializer:
case SyntaxKind.BaseConstructorInitializer:
case SyntaxKind.ConstructorDeclaration:
var newConstructor = (ConstructorDeclarationSyntax)(newBody.Parent.IsKind(SyntaxKind.ArrowExpressionClause) ? newBody.Parent.Parent : newBody.Parent)!;
newStatement = (SyntaxNode?)newConstructor.Initializer ?? newConstructor;
return true;
default:
// TODO: Consider mapping an expression body to an equivalent statement expression or return statement and vice versa.
// It would benefit transformations of expression bodies to block bodies of lambdas, methods, operators and properties.
// See https://github.com/dotnet/roslyn/issues/22696
// field initializer, lambda and query expressions:
if (oldStatement == oldBody && !newBody.IsKind(SyntaxKind.Block))
{
newStatement = newBody;
return true;
}
newStatement = null;
return false;
}
}
#endregion
#region Syntax and Semantic Utils
protected override IEnumerable<SequenceEdit> GetSyntaxSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes)
=> SyntaxComparer.GetSequenceEdits(oldNodes, newNodes);
internal override SyntaxNode EmptyCompilationUnit
=> SyntaxFactory.CompilationUnit();
// there are no experimental features at this time.
internal override bool ExperimentalFeaturesEnabled(SyntaxTree tree)
=> false;
protected override bool StateMachineSuspensionPointKindEquals(SyntaxNode suspensionPoint1, SyntaxNode suspensionPoint2)
=> (suspensionPoint1 is CommonForEachStatementSyntax) ? suspensionPoint2 is CommonForEachStatementSyntax : suspensionPoint1.RawKind == suspensionPoint2.RawKind;
protected override bool StatementLabelEquals(SyntaxNode node1, SyntaxNode node2)
=> SyntaxComparer.Statement.GetLabel(node1) == SyntaxComparer.Statement.GetLabel(node2);
protected override bool TryGetEnclosingBreakpointSpan(SyntaxNode root, int position, out TextSpan span)
=> BreakpointSpans.TryGetClosestBreakpointSpan(root, position, out span);
protected override bool TryGetActiveSpan(SyntaxNode node, int statementPart, int minLength, out TextSpan span)
{
switch (node.Kind())
{
case SyntaxKind.Block:
span = GetActiveSpan((BlockSyntax)node, (BlockPart)statementPart);
return true;
case SyntaxKind.ForEachStatement:
span = GetActiveSpan((ForEachStatementSyntax)node, (ForEachPart)statementPart);
return true;
case SyntaxKind.ForEachVariableStatement:
span = GetActiveSpan((ForEachVariableStatementSyntax)node, (ForEachPart)statementPart);
return true;
case SyntaxKind.DoStatement:
// The active statement of DoStatement node is the while condition,
// which is lexically not the closest breakpoint span (the body is).
// do { ... } [|while (condition);|]
Debug.Assert(statementPart == DefaultStatementPart);
var doStatement = (DoStatementSyntax)node;
return BreakpointSpans.TryGetClosestBreakpointSpan(node, doStatement.WhileKeyword.SpanStart, out span);
case SyntaxKind.PropertyDeclaration:
// The active span corresponding to a property declaration is the span corresponding to its initializer (if any),
// not the span corresponding to the accessor.
// int P { [|get;|] } = [|<initializer>|];
Debug.Assert(statementPart == DefaultStatementPart);
var propertyDeclaration = (PropertyDeclarationSyntax)node;
if (propertyDeclaration.Initializer != null &&
BreakpointSpans.TryGetClosestBreakpointSpan(node, propertyDeclaration.Initializer.SpanStart, out span))
{
return true;
}
span = default;
return false;
case SyntaxKind.SwitchExpression:
span = GetActiveSpan((SwitchExpressionSyntax)node, (SwitchExpressionPart)statementPart);
return true;
case SyntaxKind.SwitchExpressionArm:
// An active statement may occur in the when clause and in the arm expression:
// <constant-pattern> [|when <condition>|] => [|<expression>|]
// The former is covered by when-clause node - it's a labeled node.
// The latter isn't enclosed in a distinct labeled syntax node and thus needs to be covered
// by the arm node itself.
Debug.Assert(statementPart == DefaultStatementPart);
span = ((SwitchExpressionArmSyntax)node).Expression.Span;
return true;
default:
// make sure all nodes that use statement parts are handled above:
Debug.Assert(statementPart == DefaultStatementPart);
return BreakpointSpans.TryGetClosestBreakpointSpan(node, node.SpanStart, out span);
}
}
protected override IEnumerable<(SyntaxNode statement, int statementPart)> EnumerateNearStatements(SyntaxNode statement)
{
var direction = +1;
SyntaxNodeOrToken nodeOrToken = statement;
var fieldOrPropertyModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(statement);
while (true)
{
nodeOrToken = (direction < 0) ? nodeOrToken.GetPreviousSibling() : nodeOrToken.GetNextSibling();
if (nodeOrToken.RawKind == 0)
{
var parent = statement.Parent;
if (parent == null)
{
yield break;
}
switch (parent.Kind())
{
case SyntaxKind.Block:
// The next sequence point hit after the last statement of a block is the closing brace:
yield return (parent, (int)(direction > 0 ? BlockPart.CloseBrace : BlockPart.OpenBrace));
break;
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
// The next sequence point hit after the body is the in keyword:
// [|foreach|] ([|variable-declaration|] [|in|] [|expression|]) [|<body>|]
yield return (parent, (int)ForEachPart.In);
break;
}
if (direction > 0)
{
nodeOrToken = statement;
direction = -1;
continue;
}
if (fieldOrPropertyModifiers.HasValue)
{
// We enumerated all members and none of them has an initializer.
// We don't have any better place where to place the span than the initial field.
// Consider: in non-partial classes we could find a single constructor.
// Otherwise, it would be confusing to select one arbitrarily.
yield return (statement, -1);
}
nodeOrToken = statement = parent;
fieldOrPropertyModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(statement);
direction = +1;
yield return (nodeOrToken.AsNode()!, DefaultStatementPart);
}
else
{
var node = nodeOrToken.AsNode();
if (node == null)
{
continue;
}
if (fieldOrPropertyModifiers.HasValue)
{
var nodeModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(node);
if (!nodeModifiers.HasValue ||
nodeModifiers.Value.Any(SyntaxKind.StaticKeyword) != fieldOrPropertyModifiers.Value.Any(SyntaxKind.StaticKeyword))
{
continue;
}
}
switch (node.Kind())
{
case SyntaxKind.Block:
yield return (node, (int)(direction > 0 ? BlockPart.OpenBrace : BlockPart.CloseBrace));
break;
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
yield return (node, (int)ForEachPart.ForEach);
break;
}
yield return (node, DefaultStatementPart);
}
}
}
protected override bool AreEquivalentActiveStatements(SyntaxNode oldStatement, SyntaxNode newStatement, int statementPart)
{
if (oldStatement.Kind() != newStatement.Kind())
{
return false;
}
switch (oldStatement.Kind())
{
case SyntaxKind.Block:
// closing brace of a using statement or a block that contains using local declarations:
if (statementPart == (int)BlockPart.CloseBrace)
{
if (oldStatement.Parent.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? oldUsing))
{
return newStatement.Parent.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? newUsing) &&
AreEquivalentActiveStatements(oldUsing, newUsing);
}
return HasEquivalentUsingDeclarations((BlockSyntax)oldStatement, (BlockSyntax)newStatement);
}
return true;
case SyntaxKind.ConstructorDeclaration:
// The call could only change if the base type of the containing class changed.
return true;
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
// only check the expression, edits in the body and the variable declaration are allowed:
return AreEquivalentActiveStatements((CommonForEachStatementSyntax)oldStatement, (CommonForEachStatementSyntax)newStatement);
case SyntaxKind.IfStatement:
// only check the condition, edits in the body are allowed:
return AreEquivalentActiveStatements((IfStatementSyntax)oldStatement, (IfStatementSyntax)newStatement);
case SyntaxKind.WhileStatement:
// only check the condition, edits in the body are allowed:
return AreEquivalentActiveStatements((WhileStatementSyntax)oldStatement, (WhileStatementSyntax)newStatement);
case SyntaxKind.DoStatement:
// only check the condition, edits in the body are allowed:
return AreEquivalentActiveStatements((DoStatementSyntax)oldStatement, (DoStatementSyntax)newStatement);
case SyntaxKind.SwitchStatement:
return AreEquivalentActiveStatements((SwitchStatementSyntax)oldStatement, (SwitchStatementSyntax)newStatement);
case SyntaxKind.LockStatement:
return AreEquivalentActiveStatements((LockStatementSyntax)oldStatement, (LockStatementSyntax)newStatement);
case SyntaxKind.UsingStatement:
return AreEquivalentActiveStatements((UsingStatementSyntax)oldStatement, (UsingStatementSyntax)newStatement);
// fixed and for statements don't need special handling since the active statement is a variable declaration
default:
return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement);
}
}
private static bool HasEquivalentUsingDeclarations(BlockSyntax oldBlock, BlockSyntax newBlock)
{
var oldUsingDeclarations = oldBlock.Statements.Where(s => s is LocalDeclarationStatementSyntax l && l.UsingKeyword != default);
var newUsingDeclarations = newBlock.Statements.Where(s => s is LocalDeclarationStatementSyntax l && l.UsingKeyword != default);
return oldUsingDeclarations.SequenceEqual(newUsingDeclarations, AreEquivalentIgnoringLambdaBodies);
}
private static bool AreEquivalentActiveStatements(IfStatementSyntax oldNode, IfStatementSyntax newNode)
{
// only check the condition, edits in the body are allowed:
return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition);
}
private static bool AreEquivalentActiveStatements(WhileStatementSyntax oldNode, WhileStatementSyntax newNode)
{
// only check the condition, edits in the body are allowed:
return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition);
}
private static bool AreEquivalentActiveStatements(DoStatementSyntax oldNode, DoStatementSyntax newNode)
{
// only check the condition, edits in the body are allowed:
return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition);
}
private static bool AreEquivalentActiveStatements(SwitchStatementSyntax oldNode, SwitchStatementSyntax newNode)
{
// only check the expression, edits in the body are allowed, unless the switch expression contains patterns:
if (!AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression))
{
return false;
}
// Check that switch statement decision tree has not changed.
var hasDecitionTree = oldNode.Sections.Any(s => s.Labels.Any(l => l is CasePatternSwitchLabelSyntax));
return !hasDecitionTree || AreEquivalentSwitchStatementDecisionTrees(oldNode, newNode);
}
private static bool AreEquivalentActiveStatements(LockStatementSyntax oldNode, LockStatementSyntax newNode)
{
// only check the expression, edits in the body are allowed:
return AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression);
}
private static bool AreEquivalentActiveStatements(FixedStatementSyntax oldNode, FixedStatementSyntax newNode)
=> AreEquivalentIgnoringLambdaBodies(oldNode.Declaration, newNode.Declaration);
private static bool AreEquivalentActiveStatements(UsingStatementSyntax oldNode, UsingStatementSyntax newNode)
{
// only check the expression/declaration, edits in the body are allowed:
return AreEquivalentIgnoringLambdaBodies(
(SyntaxNode?)oldNode.Declaration ?? oldNode.Expression!,
(SyntaxNode?)newNode.Declaration ?? newNode.Expression!);
}
private static bool AreEquivalentActiveStatements(CommonForEachStatementSyntax oldNode, CommonForEachStatementSyntax newNode)
{
if (oldNode.Kind() != newNode.Kind() || !AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression))
{
return false;
}
switch (oldNode.Kind())
{
case SyntaxKind.ForEachStatement: return AreEquivalentIgnoringLambdaBodies(((ForEachStatementSyntax)oldNode).Type, ((ForEachStatementSyntax)newNode).Type);
case SyntaxKind.ForEachVariableStatement: return AreEquivalentIgnoringLambdaBodies(((ForEachVariableStatementSyntax)oldNode).Variable, ((ForEachVariableStatementSyntax)newNode).Variable);
default: throw ExceptionUtilities.UnexpectedValue(oldNode.Kind());
}
}
private static bool AreSimilarActiveStatements(CommonForEachStatementSyntax oldNode, CommonForEachStatementSyntax newNode)
{
List<SyntaxToken>? oldTokens = null;
List<SyntaxToken>? newTokens = null;
SyntaxComparer.GetLocalNames(oldNode, ref oldTokens);
SyntaxComparer.GetLocalNames(newNode, ref newTokens);
// A valid foreach statement declares at least one variable.
RoslynDebug.Assert(oldTokens != null);
RoslynDebug.Assert(newTokens != null);
return DeclareSameIdentifiers(oldTokens.ToArray(), newTokens.ToArray());
}
internal override bool IsInterfaceDeclaration(SyntaxNode node)
=> node.IsKind(SyntaxKind.InterfaceDeclaration);
internal override SyntaxNode? TryGetContainingTypeDeclaration(SyntaxNode node)
=> node.Parent!.FirstAncestorOrSelf<TypeDeclarationSyntax>();
internal override bool HasBackingField(SyntaxNode propertyOrIndexerDeclaration)
=> propertyOrIndexerDeclaration.IsKind(SyntaxKind.PropertyDeclaration, out PropertyDeclarationSyntax? propertyDecl) &&
SyntaxUtilities.HasBackingField(propertyDecl);
internal override bool IsDeclarationWithInitializer(SyntaxNode declaration)
{
switch (declaration.Kind())
{
case SyntaxKind.VariableDeclarator:
return ((VariableDeclaratorSyntax)declaration).Initializer != null;
case SyntaxKind.PropertyDeclaration:
return ((PropertyDeclarationSyntax)declaration).Initializer != null;
default:
return false;
}
}
internal override bool IsConstructorWithMemberInitializers(SyntaxNode constructorDeclaration)
=> constructorDeclaration is ConstructorDeclarationSyntax ctor && (ctor.Initializer == null || ctor.Initializer.IsKind(SyntaxKind.BaseConstructorInitializer));
internal override bool IsPartial(INamedTypeSymbol type)
{
var syntaxRefs = type.DeclaringSyntaxReferences;
return syntaxRefs.Length > 1
|| ((TypeDeclarationSyntax)syntaxRefs.Single().GetSyntax()).Modifiers.Any(SyntaxKind.PartialKeyword);
}
protected override ISymbol? GetSymbolForEdit(SemanticModel model, SyntaxNode node, EditKind editKind, Dictionary<SyntaxNode, EditKind> editMap, CancellationToken cancellationToken)
{
if (node.IsKind(SyntaxKind.Parameter))
{
return null;
}
if (editKind == EditKind.Update)
{
if (node.IsKind(SyntaxKind.EnumDeclaration))
{
// Enum declaration update that removes/adds a trailing comma.
return null;
}
if (node.IsKind(SyntaxKind.IndexerDeclaration) || node.IsKind(SyntaxKind.PropertyDeclaration))
{
// The only legitimate update of an indexer/property declaration is an update of its expression body.
// The expression body itself may have been updated, replaced with an explicit getter, or added to replace an explicit getter.
// In any case, the update is to the property getter symbol.
var propertyOrIndexer = model.GetRequiredDeclaredSymbol(node, cancellationToken);
return ((IPropertySymbol)propertyOrIndexer).GetMethod;
}
}
if (IsGetterToExpressionBodyTransformation(editKind, node, editMap))
{
return null;
}
return model.GetDeclaredSymbol(node, cancellationToken);
}
protected override bool TryGetDeclarationBodyEdit(Edit<SyntaxNode> edit, Dictionary<SyntaxNode, EditKind> editMap, out SyntaxNode? oldBody, out SyntaxNode? newBody)
{
// Detect a transition between a property/indexer with an expression body and with an explicit getter.
// int P => old_body; <-> int P { get { new_body } }
// int this[args] => old_body; <-> int this[args] { get { new_body } }
// First, return getter or expression body for property/indexer update:
if (edit.Kind == EditKind.Update && (edit.OldNode.IsKind(SyntaxKind.PropertyDeclaration) || edit.OldNode.IsKind(SyntaxKind.IndexerDeclaration)))
{
oldBody = SyntaxUtilities.TryGetEffectiveGetterBody(edit.OldNode);
newBody = SyntaxUtilities.TryGetEffectiveGetterBody(edit.NewNode);
if (oldBody != null && newBody != null)
{
return true;
}
}
// Second, ignore deletion of a getter body:
if (IsGetterToExpressionBodyTransformation(edit.Kind, edit.OldNode ?? edit.NewNode, editMap))
{
oldBody = newBody = null;
return false;
}
return base.TryGetDeclarationBodyEdit(edit, editMap, out oldBody, out newBody);
}
private static bool IsGetterToExpressionBodyTransformation(EditKind editKind, SyntaxNode node, Dictionary<SyntaxNode, EditKind> editMap)
{
if ((editKind == EditKind.Insert || editKind == EditKind.Delete) && node.IsKind(SyntaxKind.GetAccessorDeclaration))
{
RoslynDebug.Assert(node.Parent.IsKind(SyntaxKind.AccessorList));
RoslynDebug.Assert(node.Parent.Parent.IsKind(SyntaxKind.PropertyDeclaration) || node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration));
return editMap.TryGetValue(node.Parent, out var parentEdit) && parentEdit == editKind &&
editMap.TryGetValue(node.Parent!.Parent, out parentEdit) && parentEdit == EditKind.Update;
}
return false;
}
internal override bool ContainsLambda(SyntaxNode declaration)
=> declaration.DescendantNodes().Any(LambdaUtilities.IsLambda);
internal override bool IsLambda(SyntaxNode node)
=> LambdaUtilities.IsLambda(node);
internal override bool IsLocalFunction(SyntaxNode node)
=> node.IsKind(SyntaxKind.LocalFunctionStatement);
internal override bool IsNestedFunction(SyntaxNode node)
=> node is LambdaExpressionSyntax || node is LocalFunctionStatementSyntax;
internal override bool TryGetLambdaBodies(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? body1, out SyntaxNode? body2)
=> LambdaUtilities.TryGetLambdaBodies(node, out body1, out body2);
internal override SyntaxNode GetLambda(SyntaxNode lambdaBody)
=> LambdaUtilities.GetLambda(lambdaBody);
internal override IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken)
{
var bodyExpression = LambdaUtilities.GetNestedFunctionBody(lambdaExpression);
return (IMethodSymbol)model.GetRequiredEnclosingSymbol(bodyExpression.SpanStart, cancellationToken);
}
internal override SyntaxNode? GetContainingQueryExpression(SyntaxNode node)
=> node.FirstAncestorOrSelf<QueryExpressionSyntax>();
internal override bool QueryClauseLambdasTypeEquivalent(SemanticModel oldModel, SyntaxNode oldNode, SemanticModel newModel, SyntaxNode newNode, CancellationToken cancellationToken)
{
switch (oldNode.Kind())
{
case SyntaxKind.FromClause:
case SyntaxKind.LetClause:
case SyntaxKind.WhereClause:
case SyntaxKind.OrderByClause:
case SyntaxKind.JoinClause:
var oldQueryClauseInfo = oldModel.GetQueryClauseInfo((QueryClauseSyntax)oldNode, cancellationToken);
var newQueryClauseInfo = newModel.GetQueryClauseInfo((QueryClauseSyntax)newNode, cancellationToken);
return MemberSignaturesEquivalent(oldQueryClauseInfo.CastInfo.Symbol, newQueryClauseInfo.CastInfo.Symbol) &&
MemberSignaturesEquivalent(oldQueryClauseInfo.OperationInfo.Symbol, newQueryClauseInfo.OperationInfo.Symbol);
case SyntaxKind.AscendingOrdering:
case SyntaxKind.DescendingOrdering:
var oldOrderingInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken);
var newOrderingInfo = newModel.GetSymbolInfo(newNode, cancellationToken);
return MemberSignaturesEquivalent(oldOrderingInfo.Symbol, newOrderingInfo.Symbol);
case SyntaxKind.SelectClause:
var oldSelectInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken);
var newSelectInfo = newModel.GetSymbolInfo(newNode, cancellationToken);
// Changing reduced select clause to a non-reduced form or vice versa
// adds/removes a call to Select method, which is a supported change.
return oldSelectInfo.Symbol == null ||
newSelectInfo.Symbol == null ||
MemberSignaturesEquivalent(oldSelectInfo.Symbol, newSelectInfo.Symbol);
case SyntaxKind.GroupClause:
var oldGroupByInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken);
var newGroupByInfo = newModel.GetSymbolInfo(newNode, cancellationToken);
return MemberSignaturesEquivalent(oldGroupByInfo.Symbol, newGroupByInfo.Symbol, GroupBySignatureComparer);
default:
return true;
}
}
protected override void ReportLambdaSignatureRudeEdits(
SemanticModel oldModel,
SyntaxNode oldLambdaBody,
SemanticModel newModel,
SyntaxNode newLambdaBody,
List<RudeEditDiagnostic> diagnostics,
out bool hasErrors,
CancellationToken cancellationToken)
{
base.ReportLambdaSignatureRudeEdits(oldModel, oldLambdaBody, newModel, newLambdaBody, diagnostics, out hasErrors, cancellationToken);
if (IsLocalFunctionBody(oldLambdaBody) != IsLocalFunctionBody(newLambdaBody))
{
var newLambda = GetLambda(newLambdaBody);
diagnostics.Add(new RudeEditDiagnostic(
RudeEditKind.SwitchBetweenLambdaAndLocalFunction,
GetDiagnosticSpan(newLambda, EditKind.Update),
newLambda,
new[] { GetDisplayName(newLambda) }));
hasErrors = true;
}
}
private static bool IsLocalFunctionBody(SyntaxNode lambdaBody)
{
var lambda = LambdaUtilities.GetLambda(lambdaBody);
return lambda.Kind() == SyntaxKind.LocalFunctionStatement;
}
private static bool GroupBySignatureComparer(ImmutableArray<IParameterSymbol> oldParameters, ITypeSymbol oldReturnType, ImmutableArray<IParameterSymbol> newParameters, ITypeSymbol newReturnType)
{
// C# spec paragraph 7.16.2.6 "Groupby clauses":
//
// A query expression of the form
// from x in e group v by k
// is translated into
// (e).GroupBy(x => k, x => v)
// except when v is the identifier x, the translation is
// (e).GroupBy(x => k)
//
// Possible signatures:
// C<G<K, T>> GroupBy<K>(Func<T, K> keySelector);
// C<G<K, E>> GroupBy<K, E>(Func<T, K> keySelector, Func<T, E> elementSelector);
if (!s_assemblyEqualityComparer.Equals(oldReturnType, newReturnType))
{
return false;
}
Debug.Assert(oldParameters.Length == 1 || oldParameters.Length == 2);
Debug.Assert(newParameters.Length == 1 || newParameters.Length == 2);
// The types of the lambdas have to be the same if present.
// The element selector may be added/removed.
if (!s_assemblyEqualityComparer.ParameterEquivalenceComparer.Equals(oldParameters[0], newParameters[0]))
{
return false;
}
if (oldParameters.Length == newParameters.Length && newParameters.Length == 2)
{
return s_assemblyEqualityComparer.ParameterEquivalenceComparer.Equals(oldParameters[1], newParameters[1]);
}
return true;
}
#endregion
#region Diagnostic Info
protected override SymbolDisplayFormat ErrorDisplayFormat => SymbolDisplayFormat.CSharpErrorMessageFormat;
protected override TextSpan? TryGetDiagnosticSpan(SyntaxNode node, EditKind editKind)
=> TryGetDiagnosticSpanImpl(node, editKind);
internal static new TextSpan GetDiagnosticSpan(SyntaxNode node, EditKind editKind)
=> TryGetDiagnosticSpanImpl(node, editKind) ?? node.Span;
private static TextSpan? TryGetDiagnosticSpanImpl(SyntaxNode node, EditKind editKind)
=> TryGetDiagnosticSpanImpl(node.Kind(), node, editKind);
// internal for testing; kind is passed explicitly for testing as well
internal static TextSpan? TryGetDiagnosticSpanImpl(SyntaxKind kind, SyntaxNode node, EditKind editKind)
{
switch (kind)
{
case SyntaxKind.CompilationUnit:
return default(TextSpan);
case SyntaxKind.GlobalStatement:
// TODO:
return node.Span;
case SyntaxKind.ExternAliasDirective:
case SyntaxKind.UsingDirective:
return node.Span;
case SyntaxKind.NamespaceDeclaration:
var ns = (NamespaceDeclarationSyntax)node;
return TextSpan.FromBounds(ns.NamespaceKeyword.SpanStart, ns.Name.Span.End);
case SyntaxKind.ClassDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.InterfaceDeclaration:
var typeDeclaration = (TypeDeclarationSyntax)node;
return GetDiagnosticSpan(typeDeclaration.Modifiers, typeDeclaration.Keyword,
typeDeclaration.TypeParameterList ?? (SyntaxNodeOrToken)typeDeclaration.Identifier);
case SyntaxKind.EnumDeclaration:
var enumDeclaration = (EnumDeclarationSyntax)node;
return GetDiagnosticSpan(enumDeclaration.Modifiers, enumDeclaration.EnumKeyword, enumDeclaration.Identifier);
case SyntaxKind.DelegateDeclaration:
var delegateDeclaration = (DelegateDeclarationSyntax)node;
return GetDiagnosticSpan(delegateDeclaration.Modifiers, delegateDeclaration.DelegateKeyword, delegateDeclaration.ParameterList);
case SyntaxKind.FieldDeclaration:
var fieldDeclaration = (BaseFieldDeclarationSyntax)node;
return GetDiagnosticSpan(fieldDeclaration.Modifiers, fieldDeclaration.Declaration, fieldDeclaration.Declaration);
case SyntaxKind.EventFieldDeclaration:
var eventFieldDeclaration = (EventFieldDeclarationSyntax)node;
return GetDiagnosticSpan(eventFieldDeclaration.Modifiers, eventFieldDeclaration.EventKeyword, eventFieldDeclaration.Declaration);
case SyntaxKind.VariableDeclaration:
return TryGetDiagnosticSpanImpl(node.Parent!, editKind);
case SyntaxKind.VariableDeclarator:
return node.Span;
case SyntaxKind.MethodDeclaration:
var methodDeclaration = (MethodDeclarationSyntax)node;
return GetDiagnosticSpan(methodDeclaration.Modifiers, methodDeclaration.ReturnType, methodDeclaration.ParameterList);
case SyntaxKind.ConversionOperatorDeclaration:
var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node;
return GetDiagnosticSpan(conversionOperatorDeclaration.Modifiers, conversionOperatorDeclaration.ImplicitOrExplicitKeyword, conversionOperatorDeclaration.ParameterList);
case SyntaxKind.OperatorDeclaration:
var operatorDeclaration = (OperatorDeclarationSyntax)node;
return GetDiagnosticSpan(operatorDeclaration.Modifiers, operatorDeclaration.ReturnType, operatorDeclaration.ParameterList);
case SyntaxKind.ConstructorDeclaration:
var constructorDeclaration = (ConstructorDeclarationSyntax)node;
return GetDiagnosticSpan(constructorDeclaration.Modifiers, constructorDeclaration.Identifier, constructorDeclaration.ParameterList);
case SyntaxKind.DestructorDeclaration:
var destructorDeclaration = (DestructorDeclarationSyntax)node;
return GetDiagnosticSpan(destructorDeclaration.Modifiers, destructorDeclaration.TildeToken, destructorDeclaration.ParameterList);
case SyntaxKind.PropertyDeclaration:
var propertyDeclaration = (PropertyDeclarationSyntax)node;
return GetDiagnosticSpan(propertyDeclaration.Modifiers, propertyDeclaration.Type, propertyDeclaration.Identifier);
case SyntaxKind.IndexerDeclaration:
var indexerDeclaration = (IndexerDeclarationSyntax)node;
return GetDiagnosticSpan(indexerDeclaration.Modifiers, indexerDeclaration.Type, indexerDeclaration.ParameterList);
case SyntaxKind.EventDeclaration:
var eventDeclaration = (EventDeclarationSyntax)node;
return GetDiagnosticSpan(eventDeclaration.Modifiers, eventDeclaration.EventKeyword, eventDeclaration.Identifier);
case SyntaxKind.EnumMemberDeclaration:
return node.Span;
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
case SyntaxKind.UnknownAccessorDeclaration:
var accessorDeclaration = (AccessorDeclarationSyntax)node;
return GetDiagnosticSpan(accessorDeclaration.Modifiers, accessorDeclaration.Keyword, accessorDeclaration.Keyword);
case SyntaxKind.TypeParameterConstraintClause:
var constraint = (TypeParameterConstraintClauseSyntax)node;
return TextSpan.FromBounds(constraint.WhereKeyword.SpanStart, constraint.Constraints.Last().Span.End);
case SyntaxKind.TypeParameter:
var typeParameter = (TypeParameterSyntax)node;
return typeParameter.Identifier.Span;
case SyntaxKind.AccessorList:
case SyntaxKind.TypeParameterList:
case SyntaxKind.ParameterList:
case SyntaxKind.BracketedParameterList:
if (editKind == EditKind.Delete)
{
return TryGetDiagnosticSpanImpl(node.Parent!, editKind);
}
else
{
return node.Span;
}
case SyntaxKind.Parameter:
var parameter = (ParameterSyntax)node;
// Lambda parameters don't have types or modifiers, so the parameter is the only node
var startNode = parameter.Type ?? (SyntaxNode)parameter;
return GetDiagnosticSpan(parameter.Modifiers, startNode, parameter);
case SyntaxKind.AttributeList:
var attributeList = (AttributeListSyntax)node;
return attributeList.Span;
case SyntaxKind.Attribute:
return node.Span;
case SyntaxKind.ArrowExpressionClause:
return TryGetDiagnosticSpanImpl(node.Parent!, editKind);
// We only need a diagnostic span if reporting an error for a child statement.
// The following statements may have child statements.
case SyntaxKind.Block:
return ((BlockSyntax)node).OpenBraceToken.Span;
case SyntaxKind.UsingStatement:
var usingStatement = (UsingStatementSyntax)node;
return TextSpan.FromBounds(usingStatement.UsingKeyword.SpanStart, usingStatement.CloseParenToken.Span.End);
case SyntaxKind.FixedStatement:
var fixedStatement = (FixedStatementSyntax)node;
return TextSpan.FromBounds(fixedStatement.FixedKeyword.SpanStart, fixedStatement.CloseParenToken.Span.End);
case SyntaxKind.LockStatement:
var lockStatement = (LockStatementSyntax)node;
return TextSpan.FromBounds(lockStatement.LockKeyword.SpanStart, lockStatement.CloseParenToken.Span.End);
case SyntaxKind.StackAllocArrayCreationExpression:
return ((StackAllocArrayCreationExpressionSyntax)node).StackAllocKeyword.Span;
case SyntaxKind.ImplicitStackAllocArrayCreationExpression:
return ((ImplicitStackAllocArrayCreationExpressionSyntax)node).StackAllocKeyword.Span;
case SyntaxKind.TryStatement:
return ((TryStatementSyntax)node).TryKeyword.Span;
case SyntaxKind.CatchClause:
return ((CatchClauseSyntax)node).CatchKeyword.Span;
case SyntaxKind.CatchDeclaration:
case SyntaxKind.CatchFilterClause:
return node.Span;
case SyntaxKind.FinallyClause:
return ((FinallyClauseSyntax)node).FinallyKeyword.Span;
case SyntaxKind.IfStatement:
var ifStatement = (IfStatementSyntax)node;
return TextSpan.FromBounds(ifStatement.IfKeyword.SpanStart, ifStatement.CloseParenToken.Span.End);
case SyntaxKind.ElseClause:
return ((ElseClauseSyntax)node).ElseKeyword.Span;
case SyntaxKind.SwitchStatement:
var switchStatement = (SwitchStatementSyntax)node;
return TextSpan.FromBounds(switchStatement.SwitchKeyword.SpanStart,
(switchStatement.CloseParenToken != default) ? switchStatement.CloseParenToken.Span.End : switchStatement.Expression.Span.End);
case SyntaxKind.SwitchSection:
return ((SwitchSectionSyntax)node).Labels.Last().Span;
case SyntaxKind.WhileStatement:
var whileStatement = (WhileStatementSyntax)node;
return TextSpan.FromBounds(whileStatement.WhileKeyword.SpanStart, whileStatement.CloseParenToken.Span.End);
case SyntaxKind.DoStatement:
return ((DoStatementSyntax)node).DoKeyword.Span;
case SyntaxKind.ForStatement:
var forStatement = (ForStatementSyntax)node;
return TextSpan.FromBounds(forStatement.ForKeyword.SpanStart, forStatement.CloseParenToken.Span.End);
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
var commonForEachStatement = (CommonForEachStatementSyntax)node;
return TextSpan.FromBounds(
(commonForEachStatement.AwaitKeyword.Span.Length > 0) ? commonForEachStatement.AwaitKeyword.SpanStart : commonForEachStatement.ForEachKeyword.SpanStart,
commonForEachStatement.CloseParenToken.Span.End);
case SyntaxKind.LabeledStatement:
return ((LabeledStatementSyntax)node).Identifier.Span;
case SyntaxKind.CheckedStatement:
case SyntaxKind.UncheckedStatement:
return ((CheckedStatementSyntax)node).Keyword.Span;
case SyntaxKind.UnsafeStatement:
return ((UnsafeStatementSyntax)node).UnsafeKeyword.Span;
case SyntaxKind.LocalFunctionStatement:
var lfd = (LocalFunctionStatementSyntax)node;
return lfd.Identifier.Span;
case SyntaxKind.YieldBreakStatement:
case SyntaxKind.YieldReturnStatement:
case SyntaxKind.ReturnStatement:
case SyntaxKind.ThrowStatement:
case SyntaxKind.ExpressionStatement:
case SyntaxKind.EmptyStatement:
case SyntaxKind.GotoStatement:
case SyntaxKind.GotoCaseStatement:
case SyntaxKind.GotoDefaultStatement:
case SyntaxKind.BreakStatement:
case SyntaxKind.ContinueStatement:
return node.Span;
case SyntaxKind.LocalDeclarationStatement:
var localDeclarationStatement = (LocalDeclarationStatementSyntax)node;
return CombineSpans(localDeclarationStatement.AwaitKeyword.Span, localDeclarationStatement.UsingKeyword.Span, node.Span);
case SyntaxKind.AwaitExpression:
return ((AwaitExpressionSyntax)node).AwaitKeyword.Span;
case SyntaxKind.AnonymousObjectCreationExpression:
return ((AnonymousObjectCreationExpressionSyntax)node).NewKeyword.Span;
case SyntaxKind.ParenthesizedLambdaExpression:
return ((ParenthesizedLambdaExpressionSyntax)node).ParameterList.Span;
case SyntaxKind.SimpleLambdaExpression:
return ((SimpleLambdaExpressionSyntax)node).Parameter.Span;
case SyntaxKind.AnonymousMethodExpression:
return ((AnonymousMethodExpressionSyntax)node).DelegateKeyword.Span;
case SyntaxKind.QueryExpression:
return ((QueryExpressionSyntax)node).FromClause.FromKeyword.Span;
case SyntaxKind.QueryBody:
var queryBody = (QueryBodySyntax)node;
return TryGetDiagnosticSpanImpl(queryBody.Clauses.FirstOrDefault() ?? queryBody.Parent!, editKind);
case SyntaxKind.QueryContinuation:
return ((QueryContinuationSyntax)node).IntoKeyword.Span;
case SyntaxKind.FromClause:
return ((FromClauseSyntax)node).FromKeyword.Span;
case SyntaxKind.JoinClause:
return ((JoinClauseSyntax)node).JoinKeyword.Span;
case SyntaxKind.JoinIntoClause:
return ((JoinIntoClauseSyntax)node).IntoKeyword.Span;
case SyntaxKind.LetClause:
return ((LetClauseSyntax)node).LetKeyword.Span;
case SyntaxKind.WhereClause:
return ((WhereClauseSyntax)node).WhereKeyword.Span;
case SyntaxKind.OrderByClause:
return ((OrderByClauseSyntax)node).OrderByKeyword.Span;
case SyntaxKind.AscendingOrdering:
case SyntaxKind.DescendingOrdering:
return node.Span;
case SyntaxKind.SelectClause:
return ((SelectClauseSyntax)node).SelectKeyword.Span;
case SyntaxKind.GroupClause:
return ((GroupClauseSyntax)node).GroupKeyword.Span;
case SyntaxKind.IsPatternExpression:
case SyntaxKind.TupleType:
case SyntaxKind.TupleExpression:
case SyntaxKind.DeclarationExpression:
case SyntaxKind.RefType:
case SyntaxKind.RefExpression:
case SyntaxKind.DeclarationPattern:
case SyntaxKind.SimpleAssignmentExpression:
case SyntaxKind.WhenClause:
case SyntaxKind.SingleVariableDesignation:
case SyntaxKind.CasePatternSwitchLabel:
return node.Span;
case SyntaxKind.SwitchExpression:
return ((SwitchExpressionSyntax)node).SwitchKeyword.Span;
case SyntaxKind.SwitchExpressionArm:
return ((SwitchExpressionArmSyntax)node).EqualsGreaterThanToken.Span;
default:
return null;
}
}
private static TextSpan GetDiagnosticSpan(SyntaxTokenList modifiers, SyntaxNodeOrToken start, SyntaxNodeOrToken end)
=> TextSpan.FromBounds((modifiers.Count != 0) ? modifiers.First().SpanStart : start.SpanStart, end.Span.End);
private static TextSpan CombineSpans(TextSpan first, TextSpan second, TextSpan defaultSpan)
=> (first.Length > 0 && second.Length > 0) ? TextSpan.FromBounds(first.Start, second.End) : (first.Length > 0) ? first : (second.Length > 0) ? second : defaultSpan;
internal override TextSpan GetLambdaParameterDiagnosticSpan(SyntaxNode lambda, int ordinal)
{
Debug.Assert(ordinal >= 0);
switch (lambda.Kind())
{
case SyntaxKind.ParenthesizedLambdaExpression:
return ((ParenthesizedLambdaExpressionSyntax)lambda).ParameterList.Parameters[ordinal].Identifier.Span;
case SyntaxKind.SimpleLambdaExpression:
Debug.Assert(ordinal == 0);
return ((SimpleLambdaExpressionSyntax)lambda).Parameter.Identifier.Span;
case SyntaxKind.AnonymousMethodExpression:
// since we are given a parameter ordinal there has to be a parameter list:
return ((AnonymousMethodExpressionSyntax)lambda).ParameterList!.Parameters[ordinal].Identifier.Span;
default:
return lambda.Span;
}
}
protected override string? TryGetDisplayName(SyntaxNode node, EditKind editKind)
=> TryGetDisplayNameImpl(node, editKind);
internal static new string? GetDisplayName(SyntaxNode node, EditKind editKind)
=> TryGetDisplayNameImpl(node, editKind) ?? throw ExceptionUtilities.UnexpectedValue(node.Kind());
internal static string? TryGetDisplayNameImpl(SyntaxNode node, EditKind editKind)
{
switch (node.Kind())
{
// top-level
case SyntaxKind.GlobalStatement:
return CSharpFeaturesResources.global_statement;
case SyntaxKind.ExternAliasDirective:
return CSharpFeaturesResources.using_namespace;
case SyntaxKind.UsingDirective:
// Dev12 distinguishes using alias from using namespace and reports different errors for removing alias.
// None of these changes are allowed anyways, so let's keep it simple.
return CSharpFeaturesResources.using_directive;
case SyntaxKind.NamespaceDeclaration:
return FeaturesResources.namespace_;
case SyntaxKind.ClassDeclaration:
return FeaturesResources.class_;
case SyntaxKind.StructDeclaration:
return CSharpFeaturesResources.struct_;
case SyntaxKind.InterfaceDeclaration:
return FeaturesResources.interface_;
case SyntaxKind.EnumDeclaration:
return FeaturesResources.enum_;
case SyntaxKind.DelegateDeclaration:
return FeaturesResources.delegate_;
case SyntaxKind.FieldDeclaration:
var declaration = (FieldDeclarationSyntax)node;
return declaration.Modifiers.Any(SyntaxKind.ConstKeyword) ? FeaturesResources.const_field : FeaturesResources.field;
case SyntaxKind.EventFieldDeclaration:
return CSharpFeaturesResources.event_field;
case SyntaxKind.VariableDeclaration:
case SyntaxKind.VariableDeclarator:
return TryGetDisplayNameImpl(node.Parent!, editKind);
case SyntaxKind.MethodDeclaration:
return FeaturesResources.method;
case SyntaxKind.ConversionOperatorDeclaration:
return CSharpFeaturesResources.conversion_operator;
case SyntaxKind.OperatorDeclaration:
return FeaturesResources.operator_;
case SyntaxKind.ConstructorDeclaration:
return FeaturesResources.constructor;
case SyntaxKind.DestructorDeclaration:
return CSharpFeaturesResources.destructor;
case SyntaxKind.PropertyDeclaration:
return SyntaxUtilities.HasBackingField((PropertyDeclarationSyntax)node) ? FeaturesResources.auto_property : FeaturesResources.property_;
case SyntaxKind.IndexerDeclaration:
return CSharpFeaturesResources.indexer;
case SyntaxKind.EventDeclaration:
return FeaturesResources.event_;
case SyntaxKind.EnumMemberDeclaration:
return FeaturesResources.enum_value;
case SyntaxKind.GetAccessorDeclaration:
if (node.Parent!.Parent!.IsKind(SyntaxKind.PropertyDeclaration))
{
return CSharpFeaturesResources.property_getter;
}
else
{
RoslynDebug.Assert(node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration));
return CSharpFeaturesResources.indexer_getter;
}
case SyntaxKind.SetAccessorDeclaration:
if (node.Parent!.Parent!.IsKind(SyntaxKind.PropertyDeclaration))
{
return CSharpFeaturesResources.property_setter;
}
else
{
RoslynDebug.Assert(node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration));
return CSharpFeaturesResources.indexer_setter;
}
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
return FeaturesResources.event_accessor;
case SyntaxKind.TypeParameterConstraintClause:
return FeaturesResources.type_constraint;
case SyntaxKind.TypeParameterList:
case SyntaxKind.TypeParameter:
return FeaturesResources.type_parameter;
case SyntaxKind.Parameter:
return FeaturesResources.parameter;
case SyntaxKind.AttributeList:
return FeaturesResources.attribute;
case SyntaxKind.Attribute:
return FeaturesResources.attribute;
case SyntaxKind.AttributeTargetSpecifier:
return CSharpFeaturesResources.attribute_target;
// statement:
case SyntaxKind.TryStatement:
return CSharpFeaturesResources.try_block;
case SyntaxKind.CatchClause:
case SyntaxKind.CatchDeclaration:
return CSharpFeaturesResources.catch_clause;
case SyntaxKind.CatchFilterClause:
return CSharpFeaturesResources.filter_clause;
case SyntaxKind.FinallyClause:
return CSharpFeaturesResources.finally_clause;
case SyntaxKind.FixedStatement:
return CSharpFeaturesResources.fixed_statement;
case SyntaxKind.UsingStatement:
return CSharpFeaturesResources.using_statement;
case SyntaxKind.LockStatement:
return CSharpFeaturesResources.lock_statement;
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
return CSharpFeaturesResources.foreach_statement;
case SyntaxKind.CheckedStatement:
return CSharpFeaturesResources.checked_statement;
case SyntaxKind.UncheckedStatement:
return CSharpFeaturesResources.unchecked_statement;
case SyntaxKind.YieldBreakStatement:
return CSharpFeaturesResources.yield_break_statement;
case SyntaxKind.YieldReturnStatement:
return CSharpFeaturesResources.yield_return_statement;
case SyntaxKind.AwaitExpression:
return CSharpFeaturesResources.await_expression;
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
return CSharpFeaturesResources.lambda;
case SyntaxKind.AnonymousMethodExpression:
return CSharpFeaturesResources.anonymous_method;
case SyntaxKind.FromClause:
return CSharpFeaturesResources.from_clause;
case SyntaxKind.JoinClause:
case SyntaxKind.JoinIntoClause:
return CSharpFeaturesResources.join_clause;
case SyntaxKind.LetClause:
return CSharpFeaturesResources.let_clause;
case SyntaxKind.WhereClause:
return CSharpFeaturesResources.where_clause;
case SyntaxKind.OrderByClause:
case SyntaxKind.AscendingOrdering:
case SyntaxKind.DescendingOrdering:
return CSharpFeaturesResources.orderby_clause;
case SyntaxKind.SelectClause:
return CSharpFeaturesResources.select_clause;
case SyntaxKind.GroupClause:
return CSharpFeaturesResources.groupby_clause;
case SyntaxKind.QueryBody:
return CSharpFeaturesResources.query_body;
case SyntaxKind.QueryContinuation:
return CSharpFeaturesResources.into_clause;
case SyntaxKind.IsPatternExpression:
return CSharpFeaturesResources.is_pattern;
case SyntaxKind.SimpleAssignmentExpression:
if (((AssignmentExpressionSyntax)node).IsDeconstruction())
{
return CSharpFeaturesResources.deconstruction;
}
else
{
throw ExceptionUtilities.UnexpectedValue(node.Kind());
}
case SyntaxKind.TupleType:
case SyntaxKind.TupleExpression:
return CSharpFeaturesResources.tuple;
case SyntaxKind.LocalFunctionStatement:
return CSharpFeaturesResources.local_function;
case SyntaxKind.DeclarationExpression:
return CSharpFeaturesResources.out_var;
case SyntaxKind.RefType:
case SyntaxKind.RefExpression:
return CSharpFeaturesResources.ref_local_or_expression;
case SyntaxKind.SwitchStatement:
return CSharpFeaturesResources.switch_statement;
case SyntaxKind.LocalDeclarationStatement:
if (((LocalDeclarationStatementSyntax)node).UsingKeyword.IsKind(SyntaxKind.UsingKeyword))
{
return CSharpFeaturesResources.using_declaration;
}
return CSharpFeaturesResources.local_variable_declaration;
default:
return null;
}
}
protected override string GetSuspensionPointDisplayName(SyntaxNode node, EditKind editKind)
{
switch (node.Kind())
{
case SyntaxKind.ForEachStatement:
Debug.Assert(((CommonForEachStatementSyntax)node).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword));
return CSharpFeaturesResources.asynchronous_foreach_statement;
case SyntaxKind.VariableDeclarator:
RoslynDebug.Assert(((LocalDeclarationStatementSyntax)node.Parent!.Parent!).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword));
return CSharpFeaturesResources.asynchronous_using_declaration;
default:
return base.GetSuspensionPointDisplayName(node, editKind);
}
}
#endregion
#region Top-Level Syntactic Rude Edits
private readonly struct EditClassifier
{
private readonly CSharpEditAndContinueAnalyzer _analyzer;
private readonly List<RudeEditDiagnostic> _diagnostics;
private readonly Match<SyntaxNode>? _match;
private readonly SyntaxNode? _oldNode;
private readonly SyntaxNode? _newNode;
private readonly EditKind _kind;
private readonly TextSpan? _span;
private readonly bool _classifyStatementSyntax;
public EditClassifier(
CSharpEditAndContinueAnalyzer analyzer,
List<RudeEditDiagnostic> diagnostics,
SyntaxNode? oldNode,
SyntaxNode? newNode,
EditKind kind,
Match<SyntaxNode>? match = null,
TextSpan? span = null,
bool classifyStatementSyntax = false)
{
RoslynDebug.Assert(oldNode != null || newNode != null);
// if the node is deleted we have map that can be used to closest new ancestor
RoslynDebug.Assert(newNode != null || match != null);
_analyzer = analyzer;
_diagnostics = diagnostics;
_oldNode = oldNode;
_newNode = newNode;
_kind = kind;
_span = span;
_match = match;
_classifyStatementSyntax = classifyStatementSyntax;
}
private void ReportError(RudeEditKind kind, SyntaxNode? spanNode = null, SyntaxNode? displayNode = null)
{
var span = (spanNode != null) ? GetDiagnosticSpan(spanNode, _kind) : GetSpan();
var node = displayNode ?? _newNode ?? _oldNode;
var displayName = GetDisplayName(node!, _kind);
_diagnostics.Add(new RudeEditDiagnostic(kind, span, node, arguments: new[] { displayName }));
}
private TextSpan GetSpan()
{
if (_span.HasValue)
{
return _span.Value;
}
if (_newNode == null)
{
return _analyzer.GetDeletedNodeDiagnosticSpan(_match!.Matches, _oldNode!);
}
return GetDiagnosticSpan(_newNode, _kind);
}
public void ClassifyEdit()
{
switch (_kind)
{
case EditKind.Delete:
ClassifyDelete(_oldNode!);
return;
case EditKind.Update:
ClassifyUpdate(_oldNode!, _newNode!);
return;
case EditKind.Move:
ClassifyMove();
return;
case EditKind.Insert:
ClassifyInsert(_newNode!);
return;
case EditKind.Reorder:
ClassifyReorder(_newNode!);
return;
default:
throw ExceptionUtilities.UnexpectedValue(_kind);
}
}
#region Move and Reorder
private void ClassifyMove()
{
if (_newNode.IsKind(SyntaxKind.LocalFunctionStatement))
{
return;
}
// We could perhaps allow moving a type declaration to a different namespace syntax node
// as long as it represents semantically the same namespace as the one of the original type declaration.
ReportError(RudeEditKind.Move);
}
private void ClassifyReorder(SyntaxNode newNode)
{
if (_newNode.IsKind(SyntaxKind.LocalFunctionStatement))
{
return;
}
switch (newNode.Kind())
{
case SyntaxKind.GlobalStatement:
// TODO:
ReportError(RudeEditKind.Move);
return;
case SyntaxKind.ExternAliasDirective:
case SyntaxKind.UsingDirective:
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.VariableDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
case SyntaxKind.TypeParameterConstraintClause:
case SyntaxKind.AttributeList:
case SyntaxKind.Attribute:
// We'll ignore these edits. A general policy is to ignore edits that are only discoverable via reflection.
return;
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
case SyntaxKind.VariableDeclarator:
// Maybe we could allow changing order of field declarations unless the containing type layout is sequential.
ReportError(RudeEditKind.Move);
return;
case SyntaxKind.EnumMemberDeclaration:
// To allow this change we would need to check that values of all fields of the enum
// are preserved, or make sure we can update all method bodies that accessed those that changed.
ReportError(RudeEditKind.Move);
return;
case SyntaxKind.TypeParameter:
case SyntaxKind.Parameter:
ReportError(RudeEditKind.Move);
return;
default:
throw ExceptionUtilities.UnexpectedValue(newNode.Kind());
}
}
#endregion
#region Insert
private void ClassifyInsert(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.GlobalStatement:
// TODO:
ReportError(RudeEditKind.Insert);
return;
case SyntaxKind.ExternAliasDirective:
case SyntaxKind.UsingDirective:
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.DestructorDeclaration:
ReportError(RudeEditKind.Insert);
return;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.StructDeclaration:
var typeDeclaration = (TypeDeclarationSyntax)node;
ClassifyTypeWithPossibleExternMembersInsert(typeDeclaration);
return;
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.DelegateDeclaration:
return;
case SyntaxKind.PropertyDeclaration:
var propertyDeclaration = (PropertyDeclarationSyntax)node;
ClassifyModifiedMemberInsert(propertyDeclaration, propertyDeclaration.Modifiers);
return;
case SyntaxKind.EventDeclaration:
var eventDeclaration = (EventDeclarationSyntax)node;
ClassifyModifiedMemberInsert(eventDeclaration, eventDeclaration.Modifiers);
return;
case SyntaxKind.IndexerDeclaration:
var indexerDeclaration = (IndexerDeclarationSyntax)node;
ClassifyModifiedMemberInsert(indexerDeclaration, indexerDeclaration.Modifiers);
return;
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.OperatorDeclaration:
ReportError(RudeEditKind.InsertOperator);
return;
case SyntaxKind.MethodDeclaration:
ClassifyMethodInsert((MethodDeclarationSyntax)node);
return;
case SyntaxKind.ConstructorDeclaration:
// Allow adding parameterless constructor.
// Semantic analysis will determine if it's an actual addition or
// just an update of an existing implicit constructor.
var method = (BaseMethodDeclarationSyntax)node;
if (SyntaxUtilities.IsParameterlessConstructor(method))
{
// Disallow adding an extern constructor
if (method.Modifiers.Any(SyntaxKind.ExternKeyword))
{
ReportError(RudeEditKind.InsertExtern);
}
return;
}
ClassifyModifiedMemberInsert(method, method.Modifiers);
return;
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
ClassifyAccessorInsert((AccessorDeclarationSyntax)node);
return;
case SyntaxKind.AccessorList:
// an error will be reported for each accessor
return;
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
// allowed: private fields in classes
ClassifyFieldInsert((BaseFieldDeclarationSyntax)node);
return;
case SyntaxKind.VariableDeclarator:
// allowed: private fields in classes
ClassifyFieldInsert((VariableDeclaratorSyntax)node);
return;
case SyntaxKind.VariableDeclaration:
// allowed: private fields in classes
ClassifyFieldInsert((VariableDeclarationSyntax)node);
return;
case SyntaxKind.Parameter when !_classifyStatementSyntax:
// Parameter inserts are allowed for local functions
ReportError(RudeEditKind.Insert);
return;
case SyntaxKind.EnumMemberDeclaration:
case SyntaxKind.TypeParameter:
case SyntaxKind.TypeParameterConstraintClause:
case SyntaxKind.TypeParameterList:
case SyntaxKind.Attribute:
case SyntaxKind.AttributeList:
ReportError(RudeEditKind.Insert);
return;
}
// When classifying statement syntax we could see potentially any node as an edit
if (!_classifyStatementSyntax)
{
throw ExceptionUtilities.UnexpectedValue(node.Kind());
}
}
private bool ClassifyModifiedMemberInsert(MemberDeclarationSyntax declaration, SyntaxTokenList modifiers)
{
if (modifiers.Any(SyntaxKind.ExternKeyword))
{
ReportError(RudeEditKind.InsertExtern);
return false;
}
var isExplicitlyVirtual = modifiers.Any(SyntaxKind.VirtualKeyword) || modifiers.Any(SyntaxKind.AbstractKeyword) || modifiers.Any(SyntaxKind.OverrideKeyword);
var isInterfaceVirtual =
declaration.Parent.IsKind(SyntaxKind.InterfaceDeclaration) &&
!declaration.IsKind(SyntaxKind.EventFieldDeclaration) &&
!declaration.IsKind(SyntaxKind.FieldDeclaration) &&
!modifiers.Any(SyntaxKind.SealedKeyword) &&
!modifiers.Any(SyntaxKind.StaticKeyword);
if (isExplicitlyVirtual || isInterfaceVirtual)
{
ReportError(RudeEditKind.InsertVirtual);
return false;
}
// TODO: Adding a non-virtual member to an interface also fails at runtime
// https://github.com/dotnet/roslyn/issues/37128
if (declaration.Parent.IsKind(SyntaxKind.InterfaceDeclaration))
{
ReportError(RudeEditKind.InsertIntoInterface);
return false;
}
return true;
}
private void ClassifyTypeWithPossibleExternMembersInsert(TypeDeclarationSyntax type)
{
// extern members are not allowed, even in a new type
foreach (var member in type.Members)
{
var modifiers = default(SyntaxTokenList);
switch (member.Kind())
{
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.EventDeclaration:
modifiers = ((BasePropertyDeclarationSyntax)member).Modifiers;
break;
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
modifiers = ((BaseMethodDeclarationSyntax)member).Modifiers;
break;
}
if (modifiers.Any(SyntaxKind.ExternKeyword))
{
ReportError(RudeEditKind.InsertExtern, member, member);
}
}
}
private void ClassifyMethodInsert(MethodDeclarationSyntax method)
{
ClassifyModifiedMemberInsert(method, method.Modifiers);
if (method.Arity > 0)
{
ReportError(RudeEditKind.InsertGenericMethod);
}
if (method.ExplicitInterfaceSpecifier != null)
{
ReportError(RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier);
}
}
private void ClassifyAccessorInsert(AccessorDeclarationSyntax accessor)
{
var baseProperty = (BasePropertyDeclarationSyntax)accessor.Parent!.Parent!;
ClassifyModifiedMemberInsert(baseProperty, baseProperty.Modifiers);
}
private void ClassifyFieldInsert(BaseFieldDeclarationSyntax field)
=> ClassifyModifiedMemberInsert(field, field.Modifiers);
private void ClassifyFieldInsert(VariableDeclaratorSyntax fieldVariable)
=> ClassifyFieldInsert((VariableDeclarationSyntax)fieldVariable.Parent!);
private void ClassifyFieldInsert(VariableDeclarationSyntax fieldVariable)
=> ClassifyFieldInsert((BaseFieldDeclarationSyntax)fieldVariable.Parent!);
#endregion
#region Delete
private void ClassifyDelete(SyntaxNode oldNode)
{
switch (oldNode.Kind())
{
case SyntaxKind.GlobalStatement:
// TODO:
ReportError(RudeEditKind.Delete);
return;
case SyntaxKind.ExternAliasDirective:
case SyntaxKind.UsingDirective:
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
case SyntaxKind.VariableDeclarator:
case SyntaxKind.VariableDeclaration:
// To allow removal of declarations we would need to update method bodies that
// were previously binding to them but now are binding to another symbol that was previously hidden.
ReportError(RudeEditKind.Delete);
return;
case SyntaxKind.ConstructorDeclaration:
// Allow deletion of a parameterless constructor.
// Semantic analysis reports an error if the parameterless ctor isn't replaced by a default ctor.
if (!SyntaxUtilities.IsParameterlessConstructor(oldNode))
{
ReportError(RudeEditKind.Delete);
}
return;
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
// An accessor can be removed. Accessors are not hiding other symbols.
// If the new compilation still uses the removed accessor a semantic error will be reported.
// For simplicity though we disallow deletion of accessors for now.
// The compiler would need to remember that the accessor has been deleted,
// so that its addition back is interpreted as an update.
// Additional issues might involve changing accessibility of the accessor.
ReportError(RudeEditKind.Delete);
return;
case SyntaxKind.AccessorList:
Debug.Assert(
oldNode.Parent.IsKind(SyntaxKind.PropertyDeclaration) ||
oldNode.Parent.IsKind(SyntaxKind.IndexerDeclaration));
var accessorList = (AccessorListSyntax)oldNode;
var setter = accessorList.Accessors.FirstOrDefault(a => a.IsKind(SyntaxKind.SetAccessorDeclaration));
if (setter != null)
{
ReportError(RudeEditKind.Delete, accessorList.Parent, setter);
}
return;
case SyntaxKind.AttributeList:
case SyntaxKind.Attribute:
// To allow removal of attributes we would need to check if the removed attribute
// is a pseudo-custom attribute that CLR allows us to change, or if it is a compiler well-know attribute
// that affects the generated IL.
ReportError(RudeEditKind.Delete);
return;
case SyntaxKind.EnumMemberDeclaration:
// We could allow removing enum member if it didn't affect the values of other enum members.
// If the updated compilation binds without errors it means that the enum value wasn't used.
ReportError(RudeEditKind.Delete);
return;
case SyntaxKind.TypeParameter:
case SyntaxKind.TypeParameterList:
case SyntaxKind.TypeParameterConstraintClause:
ReportError(RudeEditKind.Delete);
return;
case SyntaxKind.Parameter when !_classifyStatementSyntax:
case SyntaxKind.ParameterList when !_classifyStatementSyntax:
ReportError(RudeEditKind.Delete);
return;
}
// When classifying statement syntax we could see potentially any node as an edit
if (!_classifyStatementSyntax)
{
throw ExceptionUtilities.UnexpectedValue(oldNode.Kind());
}
}
#endregion
#region Update
private void ClassifyUpdate(SyntaxNode oldNode, SyntaxNode newNode)
{
switch (newNode.Kind())
{
case SyntaxKind.GlobalStatement:
ReportError(RudeEditKind.Update);
return;
case SyntaxKind.ExternAliasDirective:
ReportError(RudeEditKind.Update);
return;
case SyntaxKind.UsingDirective:
// Dev12 distinguishes using alias from using namespace and reports different errors for removing alias.
// None of these changes are allowed anyways, so let's keep it simple.
ReportError(RudeEditKind.Update);
return;
case SyntaxKind.NamespaceDeclaration:
ClassifyUpdate((NamespaceDeclarationSyntax)oldNode, (NamespaceDeclarationSyntax)newNode);
return;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.InterfaceDeclaration:
ClassifyUpdate((TypeDeclarationSyntax)oldNode, (TypeDeclarationSyntax)newNode);
return;
case SyntaxKind.EnumDeclaration:
ClassifyUpdate((EnumDeclarationSyntax)oldNode, (EnumDeclarationSyntax)newNode);
return;
case SyntaxKind.DelegateDeclaration:
ClassifyUpdate((DelegateDeclarationSyntax)oldNode, (DelegateDeclarationSyntax)newNode);
return;
case SyntaxKind.FieldDeclaration:
ClassifyUpdate((BaseFieldDeclarationSyntax)oldNode, (BaseFieldDeclarationSyntax)newNode);
return;
case SyntaxKind.EventFieldDeclaration:
ClassifyUpdate((BaseFieldDeclarationSyntax)oldNode, (BaseFieldDeclarationSyntax)newNode);
return;
case SyntaxKind.VariableDeclaration:
ClassifyUpdate((VariableDeclarationSyntax)oldNode, (VariableDeclarationSyntax)newNode);
return;
case SyntaxKind.VariableDeclarator:
ClassifyUpdate((VariableDeclaratorSyntax)oldNode, (VariableDeclaratorSyntax)newNode);
return;
case SyntaxKind.MethodDeclaration:
ClassifyUpdate((MethodDeclarationSyntax)oldNode, (MethodDeclarationSyntax)newNode);
return;
case SyntaxKind.ConversionOperatorDeclaration:
ClassifyUpdate((ConversionOperatorDeclarationSyntax)oldNode, (ConversionOperatorDeclarationSyntax)newNode);
return;
case SyntaxKind.OperatorDeclaration:
ClassifyUpdate((OperatorDeclarationSyntax)oldNode, (OperatorDeclarationSyntax)newNode);
return;
case SyntaxKind.ConstructorDeclaration:
ClassifyUpdate((ConstructorDeclarationSyntax)oldNode, (ConstructorDeclarationSyntax)newNode);
return;
case SyntaxKind.DestructorDeclaration:
ClassifyUpdate((DestructorDeclarationSyntax)oldNode, (DestructorDeclarationSyntax)newNode);
return;
case SyntaxKind.PropertyDeclaration:
ClassifyUpdate((PropertyDeclarationSyntax)oldNode, (PropertyDeclarationSyntax)newNode);
return;
case SyntaxKind.IndexerDeclaration:
ClassifyUpdate((IndexerDeclarationSyntax)oldNode, (IndexerDeclarationSyntax)newNode);
return;
case SyntaxKind.EventDeclaration:
return;
case SyntaxKind.EnumMemberDeclaration:
ClassifyUpdate((EnumMemberDeclarationSyntax)oldNode, (EnumMemberDeclarationSyntax)newNode);
return;
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
ClassifyUpdate((AccessorDeclarationSyntax)oldNode, (AccessorDeclarationSyntax)newNode);
return;
case SyntaxKind.TypeParameterConstraintClause:
ClassifyUpdate((TypeParameterConstraintClauseSyntax)oldNode, (TypeParameterConstraintClauseSyntax)newNode);
return;
case SyntaxKind.TypeParameter:
ClassifyUpdate((TypeParameterSyntax)oldNode, (TypeParameterSyntax)newNode);
return;
case SyntaxKind.Parameter when !_classifyStatementSyntax:
// Parameter updates are allowed for local functions
ClassifyUpdate((ParameterSyntax)oldNode, (ParameterSyntax)newNode);
return;
case SyntaxKind.AttributeList:
ClassifyUpdate((AttributeListSyntax)oldNode, (AttributeListSyntax)newNode);
return;
case SyntaxKind.Attribute:
// Dev12 reports "Rename" if the attribute type name is changed.
// But such update is actually not renaming the attribute, it's changing what attribute is applied.
ReportError(RudeEditKind.Update);
return;
case SyntaxKind.TypeParameterList:
case SyntaxKind.ParameterList:
case SyntaxKind.BracketedParameterList:
case SyntaxKind.AccessorList:
return;
}
// When classifying statement syntax we could see potentially any node as an edit
if (!_classifyStatementSyntax)
{
throw ExceptionUtilities.UnexpectedValue(newNode.Kind());
}
}
private void ClassifyUpdate(NamespaceDeclarationSyntax oldNode, NamespaceDeclarationSyntax newNode)
{
Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Name, newNode.Name));
ReportError(RudeEditKind.Renamed);
}
private void ClassifyUpdate(TypeDeclarationSyntax oldNode, TypeDeclarationSyntax newNode)
{
if (oldNode.Kind() != newNode.Kind())
{
ReportError(RudeEditKind.TypeKindUpdate);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
{
ReportError(RudeEditKind.ModifiersUpdate);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier))
{
ReportError(RudeEditKind.Renamed);
return;
}
Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.BaseList, newNode.BaseList));
ReportError(RudeEditKind.BaseTypeOrInterfaceUpdate);
}
private void ClassifyUpdate(EnumDeclarationSyntax oldNode, EnumDeclarationSyntax newNode)
{
if (!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier))
{
ReportError(RudeEditKind.Renamed);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
{
ReportError(RudeEditKind.ModifiersUpdate);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.BaseList, newNode.BaseList))
{
ReportError(RudeEditKind.EnumUnderlyingTypeUpdate);
return;
}
// The list of members has been updated (separators added).
// We report a Rude Edit for each updated member.
}
private void ClassifyUpdate(DelegateDeclarationSyntax oldNode, DelegateDeclarationSyntax newNode)
{
if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
{
ReportError(RudeEditKind.ModifiersUpdate);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.ReturnType, newNode.ReturnType))
{
ReportError(RudeEditKind.TypeUpdate);
return;
}
Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier));
ReportError(RudeEditKind.Renamed);
}
private void ClassifyUpdate(BaseFieldDeclarationSyntax oldNode, BaseFieldDeclarationSyntax newNode)
{
if (oldNode.Kind() != newNode.Kind())
{
ReportError(RudeEditKind.FieldKindUpdate);
return;
}
Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers));
ReportError(RudeEditKind.ModifiersUpdate);
return;
}
private void ClassifyUpdate(VariableDeclarationSyntax oldNode, VariableDeclarationSyntax newNode)
{
if (!SyntaxFactory.AreEquivalent(oldNode.Type, newNode.Type))
{
ReportError(RudeEditKind.TypeUpdate);
return;
}
// separators may be added/removed:
}
private void ClassifyUpdate(VariableDeclaratorSyntax oldNode, VariableDeclaratorSyntax newNode)
{
if (!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier))
{
ReportError(RudeEditKind.Renamed);
return;
}
// If the argument lists are mismatched the field must have mismatched "fixed" modifier,
// which is reported by the field declaration.
if ((oldNode.ArgumentList == null) == (newNode.ArgumentList == null))
{
if (!SyntaxFactory.AreEquivalent(oldNode.ArgumentList, newNode.ArgumentList))
{
ReportError(RudeEditKind.FixedSizeFieldUpdate);
return;
}
}
var typeDeclaration = (TypeDeclarationSyntax?)oldNode.Parent!.Parent!.Parent!;
if (typeDeclaration.Arity > 0)
{
ReportError(RudeEditKind.GenericTypeInitializerUpdate);
return;
}
// Check if a constant field is updated:
var fieldDeclaration = (BaseFieldDeclarationSyntax)oldNode.Parent.Parent;
if (fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword))
{
ReportError(RudeEditKind.Update);
return;
}
ClassifyDeclarationBodyRudeUpdates(newNode);
}
private void ClassifyUpdate(MethodDeclarationSyntax oldNode, MethodDeclarationSyntax newNode)
{
if (!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier))
{
ReportError(RudeEditKind.Renamed);
return;
}
if (!ClassifyMethodModifierUpdate(oldNode.Modifiers, newNode.Modifiers))
{
ReportError(RudeEditKind.ModifiersUpdate);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.ReturnType, newNode.ReturnType))
{
ReportError(RudeEditKind.TypeUpdate);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.ExplicitInterfaceSpecifier, newNode.ExplicitInterfaceSpecifier))
{
ReportError(RudeEditKind.Renamed);
return;
}
ClassifyMethodBodyRudeUpdate(
(SyntaxNode?)oldNode.Body ?? oldNode.ExpressionBody?.Expression,
(SyntaxNode?)newNode.Body ?? newNode.ExpressionBody?.Expression,
containingMethod: newNode,
containingType: (TypeDeclarationSyntax?)newNode.Parent);
}
private static bool ClassifyMethodModifierUpdate(SyntaxTokenList oldModifiers, SyntaxTokenList newModifiers)
{
// Ignore async keyword when matching modifiers.
// async checks are done in ComputeBodyMatch.
var oldAsyncIndex = oldModifiers.IndexOf(SyntaxKind.AsyncKeyword);
var newAsyncIndex = newModifiers.IndexOf(SyntaxKind.AsyncKeyword);
if (oldAsyncIndex >= 0)
{
oldModifiers = oldModifiers.RemoveAt(oldAsyncIndex);
}
if (newAsyncIndex >= 0)
{
newModifiers = newModifiers.RemoveAt(newAsyncIndex);
}
return SyntaxFactory.AreEquivalent(oldModifiers, newModifiers);
}
private void ClassifyUpdate(ConversionOperatorDeclarationSyntax oldNode, ConversionOperatorDeclarationSyntax newNode)
{
if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
{
ReportError(RudeEditKind.ModifiersUpdate);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.ImplicitOrExplicitKeyword, newNode.ImplicitOrExplicitKeyword))
{
ReportError(RudeEditKind.Renamed);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.Type, newNode.Type))
{
ReportError(RudeEditKind.TypeUpdate);
return;
}
ClassifyMethodBodyRudeUpdate(
(SyntaxNode?)oldNode.Body ?? oldNode.ExpressionBody?.Expression,
(SyntaxNode?)newNode.Body ?? newNode.ExpressionBody?.Expression,
containingMethod: null,
containingType: (TypeDeclarationSyntax?)newNode.Parent);
}
private void ClassifyUpdate(OperatorDeclarationSyntax oldNode, OperatorDeclarationSyntax newNode)
{
if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
{
ReportError(RudeEditKind.ModifiersUpdate);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.OperatorToken, newNode.OperatorToken))
{
ReportError(RudeEditKind.Renamed);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.ReturnType, newNode.ReturnType))
{
ReportError(RudeEditKind.TypeUpdate);
return;
}
ClassifyMethodBodyRudeUpdate(
(SyntaxNode?)oldNode.Body ?? oldNode.ExpressionBody?.Expression,
(SyntaxNode?)newNode.Body ?? newNode.ExpressionBody?.Expression,
containingMethod: null,
containingType: (TypeDeclarationSyntax?)newNode.Parent);
}
private void ClassifyUpdate(AccessorDeclarationSyntax oldNode, AccessorDeclarationSyntax newNode)
{
if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
{
ReportError(RudeEditKind.ModifiersUpdate);
return;
}
if (oldNode.Kind() != newNode.Kind())
{
ReportError(RudeEditKind.AccessorKindUpdate);
return;
}
RoslynDebug.Assert(newNode.Parent is AccessorListSyntax);
RoslynDebug.Assert(newNode.Parent.Parent is BasePropertyDeclarationSyntax);
ClassifyMethodBodyRudeUpdate(
(SyntaxNode?)oldNode.Body ?? oldNode.ExpressionBody?.Expression,
(SyntaxNode?)newNode.Body ?? newNode.ExpressionBody?.Expression,
containingMethod: null,
containingType: (TypeDeclarationSyntax?)newNode.Parent.Parent.Parent);
}
private void ClassifyUpdate(EnumMemberDeclarationSyntax oldNode, EnumMemberDeclarationSyntax newNode)
{
if (!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier))
{
ReportError(RudeEditKind.Renamed);
return;
}
Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.EqualsValue, newNode.EqualsValue));
ReportError(RudeEditKind.InitializerUpdate);
}
private void ClassifyUpdate(ConstructorDeclarationSyntax oldNode, ConstructorDeclarationSyntax newNode)
{
if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
{
ReportError(RudeEditKind.ModifiersUpdate);
return;
}
ClassifyMethodBodyRudeUpdate(
(SyntaxNode?)oldNode.Body ?? oldNode.ExpressionBody?.Expression,
(SyntaxNode?)newNode.Body ?? newNode.ExpressionBody?.Expression,
containingMethod: null,
containingType: (TypeDeclarationSyntax?)newNode.Parent);
}
private void ClassifyUpdate(DestructorDeclarationSyntax oldNode, DestructorDeclarationSyntax newNode)
{
ClassifyMethodBodyRudeUpdate(
(SyntaxNode?)oldNode.Body ?? oldNode.ExpressionBody?.Expression,
(SyntaxNode?)newNode.Body ?? newNode.ExpressionBody?.Expression,
containingMethod: null,
containingType: (TypeDeclarationSyntax?)newNode.Parent);
}
private void ClassifyUpdate(PropertyDeclarationSyntax oldNode, PropertyDeclarationSyntax newNode)
{
if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
{
ReportError(RudeEditKind.ModifiersUpdate);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.Type, newNode.Type))
{
ReportError(RudeEditKind.TypeUpdate);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier))
{
ReportError(RudeEditKind.Renamed);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.ExplicitInterfaceSpecifier, newNode.ExplicitInterfaceSpecifier))
{
ReportError(RudeEditKind.Renamed);
return;
}
var containingType = (TypeDeclarationSyntax)newNode.Parent!;
// TODO: We currently don't support switching from auto-props to properties with accessors and vice versa.
// If we do we should also allow it for expression bodies.
if (!SyntaxFactory.AreEquivalent(oldNode.ExpressionBody, newNode.ExpressionBody))
{
var oldBody = SyntaxUtilities.TryGetEffectiveGetterBody(oldNode.ExpressionBody, oldNode.AccessorList);
var newBody = SyntaxUtilities.TryGetEffectiveGetterBody(newNode.ExpressionBody, newNode.AccessorList);
ClassifyMethodBodyRudeUpdate(
oldBody,
newBody,
containingMethod: null,
containingType: containingType);
return;
}
Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Initializer, newNode.Initializer));
if (containingType.Arity > 0)
{
ReportError(RudeEditKind.GenericTypeInitializerUpdate);
return;
}
if (newNode.Initializer != null)
{
ClassifyDeclarationBodyRudeUpdates(newNode.Initializer);
}
}
private void ClassifyUpdate(IndexerDeclarationSyntax oldNode, IndexerDeclarationSyntax newNode)
{
if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
{
ReportError(RudeEditKind.ModifiersUpdate);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.Type, newNode.Type))
{
ReportError(RudeEditKind.TypeUpdate);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.ExplicitInterfaceSpecifier, newNode.ExplicitInterfaceSpecifier))
{
ReportError(RudeEditKind.Renamed);
return;
}
Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.ExpressionBody, newNode.ExpressionBody));
var oldBody = SyntaxUtilities.TryGetEffectiveGetterBody(oldNode.ExpressionBody, oldNode.AccessorList);
var newBody = SyntaxUtilities.TryGetEffectiveGetterBody(newNode.ExpressionBody, newNode.AccessorList);
ClassifyMethodBodyRudeUpdate(
oldBody,
newBody,
containingMethod: null,
containingType: (TypeDeclarationSyntax?)newNode.Parent);
}
private void ClassifyUpdate(TypeParameterSyntax oldNode, TypeParameterSyntax newNode)
{
if (!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier))
{
ReportError(RudeEditKind.Renamed);
return;
}
Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.VarianceKeyword, newNode.VarianceKeyword));
ReportError(RudeEditKind.VarianceUpdate);
}
private void ClassifyUpdate(TypeParameterConstraintClauseSyntax oldNode, TypeParameterConstraintClauseSyntax newNode)
{
if (!SyntaxFactory.AreEquivalent(oldNode.Name, newNode.Name))
{
ReportError(RudeEditKind.Renamed);
return;
}
Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Constraints, newNode.Constraints));
ReportError(RudeEditKind.TypeUpdate);
}
private void ClassifyUpdate(ParameterSyntax oldNode, ParameterSyntax newNode)
{
if (!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier))
{
ReportError(RudeEditKind.Renamed);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
{
ReportError(RudeEditKind.ModifiersUpdate);
return;
}
if (!SyntaxFactory.AreEquivalent(oldNode.Type, newNode.Type))
{
ReportError(RudeEditKind.TypeUpdate);
return;
}
Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Default, newNode.Default));
ReportError(RudeEditKind.InitializerUpdate);
}
private void ClassifyUpdate(AttributeListSyntax oldNode, AttributeListSyntax newNode)
{
if (!SyntaxFactory.AreEquivalent(oldNode.Target, newNode.Target))
{
var spanNode = ((SyntaxNode?)newNode.Target) ?? newNode;
ReportError(RudeEditKind.Update, spanNode: spanNode, displayNode: spanNode);
return;
}
// changes in attribute separators are not interesting:
}
private void ClassifyMethodBodyRudeUpdate(
SyntaxNode? oldBody,
SyntaxNode? newBody,
MethodDeclarationSyntax? containingMethod,
TypeDeclarationSyntax? containingType)
{
Debug.Assert(oldBody is BlockSyntax || oldBody is ExpressionSyntax || oldBody == null);
Debug.Assert(newBody is BlockSyntax || newBody is ExpressionSyntax || newBody == null);
if ((oldBody == null) != (newBody == null))
{
if (oldBody == null)
{
ReportError(RudeEditKind.MethodBodyAdd);
return;
}
else
{
ReportError(RudeEditKind.MethodBodyDelete);
return;
}
}
ClassifyMemberBodyRudeUpdate(containingMethod, containingType, isTriviaUpdate: false);
if (newBody != null)
{
ClassifyDeclarationBodyRudeUpdates(newBody);
}
}
public void ClassifyMemberBodyRudeUpdate(
MethodDeclarationSyntax? containingMethod,
TypeDeclarationSyntax? containingType,
bool isTriviaUpdate)
{
if (SyntaxUtilities.Any(containingMethod?.TypeParameterList))
{
ReportError(isTriviaUpdate ? RudeEditKind.GenericMethodTriviaUpdate : RudeEditKind.GenericMethodUpdate);
return;
}
if (SyntaxUtilities.Any(containingType?.TypeParameterList))
{
ReportError(isTriviaUpdate ? RudeEditKind.GenericTypeTriviaUpdate : RudeEditKind.GenericTypeUpdate);
return;
}
}
public void ClassifyDeclarationBodyRudeUpdates(SyntaxNode newDeclarationOrBody)
{
foreach (var node in newDeclarationOrBody.DescendantNodesAndSelf(LambdaUtilities.IsNotLambda))
{
switch (node.Kind())
{
case SyntaxKind.StackAllocArrayCreationExpression:
case SyntaxKind.ImplicitStackAllocArrayCreationExpression:
ReportError(RudeEditKind.StackAllocUpdate, node, _newNode);
return;
case SyntaxKind.SwitchExpression:
// TODO: remove (https://github.com/dotnet/roslyn/issues/43099)
ReportError(RudeEditKind.SwitchExpressionUpdate, node, _newNode);
break;
}
}
}
#endregion
}
internal override void ReportSyntacticRudeEdits(
List<RudeEditDiagnostic> diagnostics,
Match<SyntaxNode> match,
Edit<SyntaxNode> edit,
Dictionary<SyntaxNode, EditKind> editMap)
{
if (HasParentEdit(editMap, edit))
{
return;
}
var classifier = new EditClassifier(this, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, match);
classifier.ClassifyEdit();
}
internal override void ReportMemberUpdateRudeEdits(List<RudeEditDiagnostic> diagnostics, SyntaxNode newMember, TextSpan? span)
{
var classifier = new EditClassifier(this, diagnostics, oldNode: null, newMember, EditKind.Update, span: span);
classifier.ClassifyMemberBodyRudeUpdate(
newMember as MethodDeclarationSyntax,
newMember.FirstAncestorOrSelf<TypeDeclarationSyntax>(),
isTriviaUpdate: true);
classifier.ClassifyDeclarationBodyRudeUpdates(newMember);
}
#endregion
#region Semantic Rude Edits
internal override void ReportInsertedMemberSymbolRudeEdits(List<RudeEditDiagnostic> diagnostics, ISymbol newSymbol)
{
// We rejected all exported methods during syntax analysis, so no additional work is needed here.
}
#endregion
#region Exception Handling Rude Edits
/// <summary>
/// Return nodes that represent exception handlers encompassing the given active statement node.
/// </summary>
protected override List<SyntaxNode> GetExceptionHandlingAncestors(SyntaxNode node, bool isNonLeaf)
{
var result = new List<SyntaxNode>();
var current = node;
while (current != null)
{
var kind = current.Kind();
switch (kind)
{
case SyntaxKind.TryStatement:
if (isNonLeaf)
{
result.Add(current);
}
break;
case SyntaxKind.CatchClause:
case SyntaxKind.FinallyClause:
result.Add(current);
// skip try:
RoslynDebug.Assert(current.Parent is object);
RoslynDebug.Assert(current.Parent.Kind() == SyntaxKind.TryStatement);
current = current.Parent;
break;
// stop at type declaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.StructDeclaration:
return result;
}
// stop at lambda:
if (LambdaUtilities.IsLambda(current))
{
return result;
}
current = current.Parent;
}
return result;
}
internal override void ReportEnclosingExceptionHandlingRudeEdits(
List<RudeEditDiagnostic> diagnostics,
IEnumerable<Edit<SyntaxNode>> exceptionHandlingEdits,
SyntaxNode oldStatement,
TextSpan newStatementSpan)
{
foreach (var edit in exceptionHandlingEdits)
{
// try/catch/finally have distinct labels so only the nodes of the same kind may match:
Debug.Assert(edit.Kind != EditKind.Update || edit.OldNode.RawKind == edit.NewNode.RawKind);
if (edit.Kind != EditKind.Update || !AreExceptionClausesEquivalent(edit.OldNode, edit.NewNode))
{
AddAroundActiveStatementRudeDiagnostic(diagnostics, edit.OldNode, edit.NewNode, newStatementSpan);
}
}
}
private static bool AreExceptionClausesEquivalent(SyntaxNode oldNode, SyntaxNode newNode)
{
switch (oldNode.Kind())
{
case SyntaxKind.TryStatement:
var oldTryStatement = (TryStatementSyntax)oldNode;
var newTryStatement = (TryStatementSyntax)newNode;
return SyntaxFactory.AreEquivalent(oldTryStatement.Finally, newTryStatement.Finally)
&& SyntaxFactory.AreEquivalent(oldTryStatement.Catches, newTryStatement.Catches);
case SyntaxKind.CatchClause:
case SyntaxKind.FinallyClause:
return SyntaxFactory.AreEquivalent(oldNode, newNode);
default:
throw ExceptionUtilities.UnexpectedValue(oldNode.Kind());
}
}
/// <summary>
/// An active statement (leaf or not) inside a "catch" makes the catch block read-only.
/// An active statement (leaf or not) inside a "finally" makes the whole try/catch/finally block read-only.
/// An active statement (non leaf) inside a "try" makes the catch/finally block read-only.
/// </summary>
/// <remarks>
/// Exception handling regions are only needed to be tracked if they contain user code.
/// <see cref="UsingStatementSyntax"/> and using <see cref="LocalDeclarationStatementSyntax"/> generate finally blocks,
/// but they do not contain non-hidden sequence points.
/// </remarks>
/// <param name="node">An exception handling ancestor of an active statement node.</param>
/// <param name="coversAllChildren">
/// True if all child nodes of the <paramref name="node"/> are contained in the exception region represented by the <paramref name="node"/>.
/// </param>
protected override TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool coversAllChildren)
{
TryStatementSyntax tryStatement;
switch (node.Kind())
{
case SyntaxKind.TryStatement:
tryStatement = (TryStatementSyntax)node;
coversAllChildren = false;
if (tryStatement.Catches.Count == 0)
{
RoslynDebug.Assert(tryStatement.Finally != null);
return tryStatement.Finally.Span;
}
return TextSpan.FromBounds(
tryStatement.Catches.First().SpanStart,
(tryStatement.Finally != null) ?
tryStatement.Finally.Span.End :
tryStatement.Catches.Last().Span.End);
case SyntaxKind.CatchClause:
coversAllChildren = true;
return node.Span;
case SyntaxKind.FinallyClause:
coversAllChildren = true;
tryStatement = (TryStatementSyntax)node.Parent!;
return tryStatement.Span;
default:
throw ExceptionUtilities.UnexpectedValue(node.Kind());
}
}
#endregion
#region State Machines
internal override bool IsStateMachineMethod(SyntaxNode declaration)
=> SyntaxUtilities.IsAsyncDeclaration(declaration) || SyntaxUtilities.GetSuspensionPoints(declaration).Any();
protected override void GetStateMachineInfo(SyntaxNode body, out ImmutableArray<SyntaxNode> suspensionPoints, out StateMachineKinds kinds)
{
suspensionPoints = SyntaxUtilities.GetSuspensionPoints(body).ToImmutableArray();
kinds = StateMachineKinds.None;
if (suspensionPoints.Any(n => n.IsKind(SyntaxKind.YieldBreakStatement) || n.IsKind(SyntaxKind.YieldReturnStatement)))
{
kinds |= StateMachineKinds.Iterator;
}
if (SyntaxUtilities.IsAsyncDeclaration(body.Parent))
{
kinds |= StateMachineKinds.Async;
}
}
internal override void ReportStateMachineSuspensionPointRudeEdits(List<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode)
{
// TODO: changes around suspension points (foreach, lock, using, etc.)
if (newNode.IsKind(SyntaxKind.AwaitExpression))
{
var oldContainingStatementPart = FindContainingStatementPart(oldNode);
var newContainingStatementPart = FindContainingStatementPart(newNode);
// If the old statement has spilled state and the new doesn't the edit is ok. We'll just not use the spilled state.
if (!SyntaxFactory.AreEquivalent(oldContainingStatementPart, newContainingStatementPart) &&
!HasNoSpilledState(newNode, newContainingStatementPart))
{
diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.AwaitStatementUpdate, newContainingStatementPart.Span));
}
}
}
internal override void ReportStateMachineSuspensionPointDeletedRudeEdit(List<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode deletedSuspensionPoint)
{
// Handle deletion of await keyword from await foreach statement.
if (deletedSuspensionPoint is CommonForEachStatementSyntax deletedForeachStatement &&
match.Matches.TryGetValue(deletedSuspensionPoint, out var newForEachStatement) &&
newForEachStatement is CommonForEachStatementSyntax &&
deletedForeachStatement.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword))
{
diagnostics.Add(new RudeEditDiagnostic(
RudeEditKind.ChangingFromAsynchronousToSynchronous,
GetDiagnosticSpan(newForEachStatement, EditKind.Update),
newForEachStatement,
new[] { GetDisplayName(newForEachStatement, EditKind.Update) }));
return;
}
// Handle deletion of await keyword from await using declaration.
if (deletedSuspensionPoint.IsKind(SyntaxKind.VariableDeclarator) &&
match.Matches.TryGetValue(deletedSuspensionPoint.Parent!.Parent!, out var newLocalDeclaration) &&
!((LocalDeclarationStatementSyntax)newLocalDeclaration).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword))
{
diagnostics.Add(new RudeEditDiagnostic(
RudeEditKind.ChangingFromAsynchronousToSynchronous,
GetDiagnosticSpan(newLocalDeclaration, EditKind.Update),
newLocalDeclaration,
new[] { GetDisplayName(newLocalDeclaration, EditKind.Update) }));
return;
}
base.ReportStateMachineSuspensionPointDeletedRudeEdit(diagnostics, match, deletedSuspensionPoint);
}
internal override void ReportStateMachineSuspensionPointInsertedRudeEdit(List<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode insertedSuspensionPoint, bool aroundActiveStatement)
{
// Handle addition of await keyword to foreach statement.
if (insertedSuspensionPoint is CommonForEachStatementSyntax insertedForEachStatement &&
match.ReverseMatches.TryGetValue(insertedSuspensionPoint, out var oldNode) &&
oldNode is CommonForEachStatementSyntax oldForEachStatement &&
!oldForEachStatement.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword))
{
diagnostics.Add(new RudeEditDiagnostic(
RudeEditKind.Insert,
insertedForEachStatement.AwaitKeyword.Span,
insertedForEachStatement,
new[] { insertedForEachStatement.AwaitKeyword.ToString() }));
return;
}
// Handle addition of using keyword to using declaration.
if (insertedSuspensionPoint.IsKind(SyntaxKind.VariableDeclarator) &&
match.ReverseMatches.TryGetValue(insertedSuspensionPoint.Parent!.Parent!, out var oldLocalDeclaration) &&
!((LocalDeclarationStatementSyntax)oldLocalDeclaration).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword))
{
var newLocalDeclaration = (LocalDeclarationStatementSyntax)insertedSuspensionPoint!.Parent!.Parent!;
diagnostics.Add(new RudeEditDiagnostic(
RudeEditKind.Insert,
newLocalDeclaration.AwaitKeyword.Span,
newLocalDeclaration,
new[] { newLocalDeclaration.AwaitKeyword.ToString() }));
return;
}
base.ReportStateMachineSuspensionPointInsertedRudeEdit(diagnostics, match, insertedSuspensionPoint, aroundActiveStatement);
}
private static SyntaxNode FindContainingStatementPart(SyntaxNode node)
{
while (true)
{
if (node is StatementSyntax statement)
{
return statement;
}
RoslynDebug.Assert(node is object);
RoslynDebug.Assert(node.Parent is object);
switch (node.Parent.Kind())
{
case SyntaxKind.ForStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.IfStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.SwitchStatement:
case SyntaxKind.LockStatement:
case SyntaxKind.UsingStatement:
case SyntaxKind.ArrowExpressionClause:
return node;
}
if (LambdaUtilities.IsLambdaBodyStatementOrExpression(node))
{
return node;
}
node = node.Parent;
}
}
private static bool HasNoSpilledState(SyntaxNode awaitExpression, SyntaxNode containingStatementPart)
{
Debug.Assert(awaitExpression.IsKind(SyntaxKind.AwaitExpression));
// There is nothing within the statement part surrounding the await expression.
if (containingStatementPart == awaitExpression)
{
return true;
}
switch (containingStatementPart.Kind())
{
case SyntaxKind.ExpressionStatement:
case SyntaxKind.ReturnStatement:
var expression = GetExpressionFromStatementPart(containingStatementPart);
// await expr;
// return await expr;
if (expression == awaitExpression)
{
return true;
}
// identifier = await expr;
// return identifier = await expr;
return IsSimpleAwaitAssignment(expression, awaitExpression);
case SyntaxKind.VariableDeclaration:
// var idf = await expr in using, for, etc.
// EqualsValueClause -> VariableDeclarator -> VariableDeclaration
return awaitExpression.Parent!.Parent!.Parent == containingStatementPart;
case SyntaxKind.LocalDeclarationStatement:
// var idf = await expr;
// EqualsValueClause -> VariableDeclarator -> VariableDeclaration -> LocalDeclarationStatement
return awaitExpression.Parent!.Parent!.Parent!.Parent == containingStatementPart;
}
return IsSimpleAwaitAssignment(containingStatementPart, awaitExpression);
}
private static ExpressionSyntax GetExpressionFromStatementPart(SyntaxNode statement)
{
switch (statement.Kind())
{
case SyntaxKind.ExpressionStatement:
return ((ExpressionStatementSyntax)statement).Expression;
case SyntaxKind.ReturnStatement:
// Must have an expression since we are only inspecting at statements that contain an expression.
return ((ReturnStatementSyntax)statement).Expression!;
default:
throw ExceptionUtilities.UnexpectedValue(statement.Kind());
}
}
private static bool IsSimpleAwaitAssignment(SyntaxNode node, SyntaxNode awaitExpression)
{
if (node.IsKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment))
{
return assignment.Left.IsKind(SyntaxKind.IdentifierName) && assignment.Right == awaitExpression;
}
return false;
}
#endregion
#region Rude Edits around Active Statement
internal override void ReportOtherRudeEditsAroundActiveStatement(
List<RudeEditDiagnostic> diagnostics,
Match<SyntaxNode> match,
SyntaxNode oldActiveStatement,
SyntaxNode newActiveStatement,
bool isNonLeaf)
{
ReportRudeEditsForSwitchWhenClauses(diagnostics, oldActiveStatement, newActiveStatement);
ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics, match, oldActiveStatement, newActiveStatement);
ReportRudeEditsForCheckedStatements(diagnostics, oldActiveStatement, newActiveStatement, isNonLeaf);
}
/// <summary>
/// Reports rude edits when an active statement is a when clause in a switch statement and any of the switch cases or the switch value changed.
/// This is necessary since the switch emits long-lived synthesized variables to store results of pattern evaluations.
/// These synthesized variables are mapped to the slots of the new methods via ordinals. The mapping preserves the values of these variables as long as
/// exactly the same variables are emitted for the new switch as they were for the old one and their order didn't change either.
/// This is guaranteed if none of the case clauses have changed.
/// </summary>
private void ReportRudeEditsForSwitchWhenClauses(List<RudeEditDiagnostic> diagnostics, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement)
{
if (!oldActiveStatement.IsKind(SyntaxKind.WhenClause))
{
return;
}
// switch expression does not have sequence points (active statements):
if (!(oldActiveStatement.Parent!.Parent!.Parent is SwitchStatementSyntax oldSwitch))
{
return;
}
// switch statement does not match switch expression, so it must be part of a switch statement as well.
var newSwitch = (SwitchStatementSyntax)newActiveStatement.Parent!.Parent!.Parent!;
// when clauses can only match other when clauses:
Debug.Assert(newActiveStatement.IsKind(SyntaxKind.WhenClause));
if (!AreEquivalentIgnoringLambdaBodies(oldSwitch.Expression, newSwitch.Expression))
{
AddRudeUpdateAroundActiveStatement(diagnostics, newSwitch);
}
if (!AreEquivalentSwitchStatementDecisionTrees(oldSwitch, newSwitch))
{
diagnostics.Add(new RudeEditDiagnostic(
RudeEditKind.UpdateAroundActiveStatement,
GetDiagnosticSpan(newSwitch, EditKind.Update),
newSwitch,
new[] { CSharpFeaturesResources.switch_statement_case_clause }));
}
}
private static bool AreEquivalentSwitchStatementDecisionTrees(SwitchStatementSyntax oldSwitch, SwitchStatementSyntax newSwitch)
=> oldSwitch.Sections.SequenceEqual(newSwitch.Sections, AreSwitchSectionsEquivalent);
private static bool AreSwitchSectionsEquivalent(SwitchSectionSyntax oldSection, SwitchSectionSyntax newSection)
=> oldSection.Labels.SequenceEqual(newSection.Labels, AreLabelsEquivalent);
private static bool AreLabelsEquivalent(SwitchLabelSyntax oldLabel, SwitchLabelSyntax newLabel)
{
if (oldLabel.IsKind(SyntaxKind.CasePatternSwitchLabel, out CasePatternSwitchLabelSyntax? oldCasePatternLabel) &&
newLabel.IsKind(SyntaxKind.CasePatternSwitchLabel, out CasePatternSwitchLabelSyntax? newCasePatternLabel))
{
// ignore the actual when expressions:
return SyntaxFactory.AreEquivalent(oldCasePatternLabel.Pattern, newCasePatternLabel.Pattern) &&
(oldCasePatternLabel.WhenClause != null) == (newCasePatternLabel.WhenClause != null);
}
else
{
return SyntaxFactory.AreEquivalent(oldLabel, newLabel);
}
}
private void ReportRudeEditsForCheckedStatements(
List<RudeEditDiagnostic> diagnostics,
SyntaxNode oldActiveStatement,
SyntaxNode newActiveStatement,
bool isNonLeaf)
{
// checked context can't be changed around non-leaf active statement:
if (!isNonLeaf)
{
return;
}
// Changing checked context around an internal active statement may change the instructions
// executed after method calls in the active statement but before the next sequence point.
// Since the debugger remaps the IP at the first sequence point following a call instruction
// allowing overflow context to be changed may lead to execution of code with old semantics.
var oldCheckedStatement = TryGetCheckedStatementAncestor(oldActiveStatement);
var newCheckedStatement = TryGetCheckedStatementAncestor(newActiveStatement);
bool isRude;
if (oldCheckedStatement == null || newCheckedStatement == null)
{
isRude = oldCheckedStatement != newCheckedStatement;
}
else
{
isRude = oldCheckedStatement.Kind() != newCheckedStatement.Kind();
}
if (isRude)
{
AddAroundActiveStatementRudeDiagnostic(diagnostics, oldCheckedStatement, newCheckedStatement, newActiveStatement.Span);
}
}
private static CheckedStatementSyntax? TryGetCheckedStatementAncestor(SyntaxNode? node)
{
// Ignoring lambda boundaries since checked context flows through.
while (node != null)
{
switch (node.Kind())
{
case SyntaxKind.CheckedStatement:
case SyntaxKind.UncheckedStatement:
return (CheckedStatementSyntax)node;
}
node = node.Parent;
}
return null;
}
private void ReportRudeEditsForAncestorsDeclaringInterStatementTemps(
List<RudeEditDiagnostic> diagnostics,
Match<SyntaxNode> match,
SyntaxNode oldActiveStatement,
SyntaxNode newActiveStatement)
{
// Rude Edits for fixed/using/lock/foreach statements that are added/updated around an active statement.
// Although such changes are technically possible, they might lead to confusion since
// the temporary variables these statements generate won't be properly initialized.
//
// We use a simple algorithm to match each new node with its old counterpart.
// If all nodes match this algorithm is linear, otherwise it's quadratic.
//
// Unlike exception regions matching where we use LCS, we allow reordering of the statements.
ReportUnmatchedStatements<LockStatementSyntax>(diagnostics, match, n => n.IsKind(SyntaxKind.LockStatement), oldActiveStatement, newActiveStatement,
areEquivalent: AreEquivalentActiveStatements,
areSimilar: null);
ReportUnmatchedStatements<FixedStatementSyntax>(diagnostics, match, n => n.IsKind(SyntaxKind.FixedStatement), oldActiveStatement, newActiveStatement,
areEquivalent: AreEquivalentActiveStatements,
areSimilar: (n1, n2) => DeclareSameIdentifiers(n1.Declaration.Variables, n2.Declaration.Variables));
// Using statements with declaration do not introduce compiler generated temporary.
ReportUnmatchedStatements<UsingStatementSyntax>(
diagnostics,
match,
n => n.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? usingStatement) && usingStatement.Declaration is null,
oldActiveStatement,
newActiveStatement,
areEquivalent: AreEquivalentActiveStatements,
areSimilar: null);
ReportUnmatchedStatements<CommonForEachStatementSyntax>(
diagnostics,
match,
n => n.IsKind(SyntaxKind.ForEachStatement) || n.IsKind(SyntaxKind.ForEachVariableStatement),
oldActiveStatement,
newActiveStatement,
areEquivalent: AreEquivalentActiveStatements,
areSimilar: AreSimilarActiveStatements);
}
private static bool DeclareSameIdentifiers(SeparatedSyntaxList<VariableDeclaratorSyntax> oldVariables, SeparatedSyntaxList<VariableDeclaratorSyntax> newVariables)
=> DeclareSameIdentifiers(oldVariables.Select(v => v.Identifier).ToArray(), newVariables.Select(v => v.Identifier).ToArray());
private static bool DeclareSameIdentifiers(SyntaxToken[] oldVariables, SyntaxToken[] newVariables)
{
if (oldVariables.Length != newVariables.Length)
{
return false;
}
for (var i = 0; i < oldVariables.Length; i++)
{
if (!SyntaxFactory.AreEquivalent(oldVariables[i], newVariables[i]))
{
return false;
}
}
return true;
}
#endregion
}
}
| 45.991444 | 207 | 0.585481 | [
"MIT"
] | AlekseyTs/roslyn | src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs | 166,629 | C# |
using MixERP.Net.FrontEnd.Base;
using System;
using System.Web.Security;
namespace MixERP.Net.FrontEnd.Site.Account
{
public partial class SignOut : MixERPWebpage
{
protected void Page_Init(object sender, EventArgs e)
{
this.IsLandingPage = true;
this.Session.Remove("UserName");
FormsAuthentication.SignOut();
this.Response.Redirect("~/SignIn.aspx");
}
}
} | 24.666667 | 60 | 0.630631 | [
"MPL-2.0"
] | asine/mixerp | src/FrontEnd/Site/Account/SignOut.aspx.cs | 446 | C# |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 name of the Aurora-Sim Project 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 DEVELOPERS ``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 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.
*/
using System;
using System.Collections.Generic;
using Aurora.Framework;
namespace Aurora.DataManager.Migration.Migrators
{
public class AgentMigrator_5 : Migrator
{
public AgentMigrator_5()
{
Version = new Version(0, 0, 5);
MigrationName = "Agent";
schema = new List<SchemaDefinition>();
AddSchema("userdata", ColDefs(
ColDef("ID", ColumnTypes.String45),
ColDef("Key", ColumnTypes.String50),
ColDef("Value", ColumnTypes.Text)
), IndexDefs(
IndexDef(new string[2] { "ID", "Key" }, IndexType.Primary)
));
AddSchema("userclassifieds", ColDefs(
ColDef("Name", ColumnTypes.String50),
ColDef("Category", ColumnTypes.String50),
ColDef("SimName", ColumnTypes.String50),
ColDef("OwnerUUID", ColumnTypes.String50),
new ColumnDefinition
{
Name = "ScopeID",
Type = new ColumnTypeDef
{
Type = ColumnType.UUID,
defaultValue = OpenMetaverse.UUID.Zero.ToString()
}
},
ColDef("ClassifiedUUID", ColumnTypes.String50),
ColDef("Classified", ColumnTypes.String8196),
new ColumnDefinition
{
Name = "Price",
Type = new ColumnTypeDef
{
Type = ColumnType.Integer,
Size = 11,
defaultValue = "0"
}
},
new ColumnDefinition
{
Name = "Keyword",
Type = new ColumnTypeDef
{
Type = ColumnType.String,
Size = 512,
defaultValue = ""
}
}
), IndexDefs(
IndexDef(new string[1] { "ClassifiedUUID" }, IndexType.Primary),
IndexDef(new string[2] { "Name", "Category" }, IndexType.Index),
IndexDef(new string[1] { "OwnerUUID" }, IndexType.Index),
IndexDef(new string[1] { "Keyword" }, IndexType.Index)
));
AddSchema("userpicks", ColDefs(
ColDef("Name", ColumnTypes.String50),
ColDef("SimName", ColumnTypes.String50),
ColDef("OwnerUUID", ColumnTypes.String50),
ColDef("PickUUID", ColumnTypes.String50),
ColDef("Pick", ColumnTypes.String8196)
), IndexDefs(
IndexDef(new string[1] { "PickUUID" }, IndexType.Primary),
IndexDef(new string[1] { "OwnerUUID" }, IndexType.Index)
));
//Remove in the next schema update... we're not using this anymore
AddSchema("macban", ColDefs(
ColDef("macAddress", ColumnTypes.String50)
), IndexDefs(
IndexDef(new string[1] { "macAddress" }, IndexType.Primary)
));
//Remove in the next schema update... we're not using this anymore
AddSchema("bannedviewers", ColDefs(
ColDef("Client", ColumnTypes.String50)
), IndexDefs(
IndexDef(new string[1] { "Client" }, IndexType.Primary)
));
}
protected override void DoCreateDefaults(IDataConnector genericData)
{
EnsureAllTablesInSchemaExist(genericData);
}
protected override bool DoValidate(IDataConnector genericData)
{
return TestThatAllTablesValidate(genericData);
}
protected override void DoMigrate(IDataConnector genericData)
{
DoCreateDefaults(genericData);
}
protected override void DoPrepareRestorePoint(IDataConnector genericData)
{
CopyAllTablesToTempVersions(genericData);
}
public override void FinishedMigration(IDataConnector genericData)
{
QueryFilter filter = new QueryFilter();
filter.andFilters["ClassifiedUUID"] = OpenMetaverse.UUID.Zero.ToString();
genericData.Delete("userclassifieds", filter);
}
}
} | 42.013605 | 86 | 0.561205 | [
"BSD-3-Clause"
] | BillyWarrhol/Aurora-Sim | Aurora/DataManager/Migration/Migrators/Agent/AgentMigrator_5.cs | 6,176 | C# |
using Microsoft.CodeAnalysis.Diagnostics;
namespace F0.Testing.CodeAnalysis.Diagnostics
{
internal class DiagnosticAnalyzerTester<TDiagnosticAnalyzer> : CSharpAnalyzerTest<TDiagnosticAnalyzer, XUnitVerifier>
where TDiagnosticAnalyzer : DiagnosticAnalyzer, new()
{
internal LanguageVersion? LanguageVersion { get; set; }
protected override ParseOptions CreateParseOptions()
{
var options = (CSharpParseOptions)base.CreateParseOptions();
return LanguageVersion.HasValue
? options.WithLanguageVersion(LanguageVersion.Value)
: options;
}
}
}
| 28.4 | 118 | 0.795775 | [
"MIT"
] | Flash0ver/F0.Analyzers | source/test/F0.CodeAnalysis.Testing/CodeAnalysis/Diagnostics/DiagnosticAnalyzerTester.cs | 568 | C# |
namespace ShatteredTemple.Stockfighter.Common.Repositories
{
/// <summary>
/// Parent class wrapping <see cref="IStockVenue"/>s offered by an <see cref="IStockExchange"/>.
/// </summary>
public interface IStockVenues
{
/// <summary>
/// Gets a specific <see cref="IStockVenue"/> repository.
/// </summary>
/// <param name="venue">Name of the venue to get.</param>
/// <returns>Venue object.</returns>
IStockVenue this[string venue] { get; }
}
}
| 32.375 | 100 | 0.602317 | [
"MIT"
] | FallenTemple/Stockfighter | Stockfighter/Common/Repositories/IStockVenues.cs | 520 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
using Anvil.API;
using Anvil.Tests.Resources;
using NUnit.Framework;
// ReSharper disable UnusedMember.Local
namespace Anvil.Tests.API
{
[TestFixture(Category = "API.Variable")]
public sealed class LocalVariableTests
{
private readonly List<NwGameObject> createdTestObjects = new List<NwGameObject>();
[Test(Description = "Getting a non-existing variable on an object returns a variable object with the correct properties.")]
[TestCase("aaabbb")]
[TestCase("123")]
[TestCase(",;'.-2=,'\"")]
[TestCase("__\n")]
public void GetMissingLocalVariablePropertiesValid(string variableName)
{
Location startLocation = NwModule.Instance.StartingLocation;
NwCreature? creature = NwCreature.Create(StandardResRef.Creature.nw_bandit001, startLocation);
Assert.That(creature, Is.Not.Null);
createdTestObjects.Add(creature!);
VariableAssert(false, default, creature!.GetObjectVariable<LocalVariableBool>(variableName + "bool"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableEnum<ValidEnum>>(variableName + "enum"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableFloat>(variableName + "float"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableGuid>(variableName + "guid"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableInt>(variableName + "int"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableString>(variableName + "string"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableStruct<ExampleSerializable>>(variableName + "string"));
}
[Test(Description = "Setting/getting a variable on an object returns a variable object with the correct properties.")]
[TestCase("aaabbb")]
[TestCase("123")]
[TestCase(",;'.-2=,'\"")]
[TestCase("__\n")]
public void GetValidLocalVariablePropertiesValid(string variableName)
{
Location startLocation = NwModule.Instance.StartingLocation;
NwCreature? creature = NwCreature.Create(StandardResRef.Creature.nw_bandit001, startLocation);
Assert.That(creature, Is.Not.Null);
createdTestObjects.Add(creature!);
creature!.GetObjectVariable<LocalVariableBool>(variableName + "bool").Value = true;
creature.GetObjectVariable<LocalVariableEnum<ValidEnum>>(variableName + "enum").Value = ValidEnum.TestA;
creature.GetObjectVariable<LocalVariableFloat>(variableName + "float").Value = 999f;
creature.GetObjectVariable<LocalVariableGuid>(variableName + "guid").Value = Guid.Parse("81a130d2-502f-4cf1-a376-63edeb000e9f");
creature.GetObjectVariable<LocalVariableInt>(variableName + "int").Value = 506;
creature.GetObjectVariable<LocalVariableString>(variableName + "string").Value = "test_string";
ExampleSerializable serializable = new ExampleSerializable
{
Value = 1,
Value2 = "test",
};
creature.GetObjectVariable<LocalVariableStruct<ExampleSerializable>>(variableName + "struct").Value = serializable;
VariableAssert(true, true, creature.GetObjectVariable<LocalVariableBool>(variableName + "bool"));
VariableAssert(true, ValidEnum.TestA, creature.GetObjectVariable<LocalVariableEnum<ValidEnum>>(variableName + "enum"));
VariableAssert(true, 999f, creature.GetObjectVariable<LocalVariableFloat>(variableName + "float"));
VariableAssert(true, Guid.Parse("81a130d2-502f-4cf1-a376-63edeb000e9f"), creature.GetObjectVariable<LocalVariableGuid>(variableName + "guid"));
VariableAssert(true, 506, creature.GetObjectVariable<LocalVariableInt>(variableName + "int"));
VariableAssert(true, "test_string", creature.GetObjectVariable<LocalVariableString>(variableName + "string"));
VariableAssert(true, serializable, creature.GetObjectVariable<LocalVariableStruct<ExampleSerializable>>(variableName + "struct"));
}
[Test(Description = "Setting a variable on an object and deleting it returns a variable object with the correct properties.")]
[TestCase("aaabbb")]
[TestCase("123")]
[TestCase(",;'.-2=,'\"")]
[TestCase("__\n")]
public void DeleteLocalVariablePropertiesValid(string variableName)
{
Location startLocation = NwModule.Instance.StartingLocation;
NwCreature? creature = NwCreature.Create(StandardResRef.Creature.nw_bandit001, startLocation);
Assert.That(creature, Is.Not.Null);
createdTestObjects.Add(creature!);
creature!.GetObjectVariable<LocalVariableBool>(variableName + "bool").Value = true;
creature.GetObjectVariable<LocalVariableEnum<ValidEnum>>(variableName + "enum").Value = ValidEnum.TestA;
creature.GetObjectVariable<LocalVariableFloat>(variableName + "float").Value = 999f;
creature.GetObjectVariable<LocalVariableGuid>(variableName + "guid").Value = Guid.Parse("81a130d2-502f-4cf1-a376-63edeb000e9f");
creature.GetObjectVariable<LocalVariableInt>(variableName + "int").Value = 506;
creature.GetObjectVariable<LocalVariableString>(variableName + "string").Value = "test_string";
ExampleSerializable serializable = new ExampleSerializable
{
Value = 1,
Value2 = "test",
};
creature.GetObjectVariable<LocalVariableStruct<ExampleSerializable>>(variableName + "struct").Value = serializable;
creature.GetObjectVariable<LocalVariableBool>(variableName + "bool").Delete();
creature.GetObjectVariable<LocalVariableEnum<ValidEnum>>(variableName + "enum").Delete();
creature.GetObjectVariable<LocalVariableFloat>(variableName + "float").Delete();
creature.GetObjectVariable<LocalVariableGuid>(variableName + "guid").Delete();
creature.GetObjectVariable<LocalVariableInt>(variableName + "int").Delete();
creature.GetObjectVariable<LocalVariableString>(variableName + "string").Delete();
creature.GetObjectVariable<LocalVariableStruct<ExampleSerializable>>(variableName + "struct").Delete();
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableBool>(variableName + "bool"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableEnum<ValidEnum>>(variableName + "enum"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableFloat>(variableName + "float"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableGuid>(variableName + "guid"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableInt>(variableName + "int"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableString>(variableName + "string"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableStruct<ExampleSerializable>>(variableName + "struct"));
}
[Test(Description = "Attempting to create an object enum variable with an incorrect size throws an exception.")]
[TestCase("aaabbb")]
[TestCase("123")]
[TestCase(",;'.-2=,'\"")]
[TestCase("__\n")]
public void GetInvalidEnumVariableThrowsException(string variableName)
{
Location startLocation = NwModule.Instance.StartingLocation;
NwCreature? creature = NwCreature.Create(StandardResRef.Creature.nw_bandit001, startLocation);
Assert.That(creature, Is.Not.Null);
createdTestObjects.Add(creature!);
Assert.That(() =>
{
creature!.GetObjectVariable<LocalVariableEnum<InvalidEnumA>>(variableName + "enum").Value = InvalidEnumA.TestA;
}, Throws.TypeOf<TargetInvocationException>());
Assert.That(() =>
{
creature!.GetObjectVariable<LocalVariableEnum<InvalidEnumB>>(variableName + "enum").Value = InvalidEnumB.TestB;
}, Throws.TypeOf<TargetInvocationException>());
}
private void VariableAssert<T>(bool expectHasValue, T? expectedValue, ObjectVariable<T> variable)
{
Assert.That(variable, Is.Not.Null, "Created variable was null.");
if (expectHasValue)
{
Assert.That(variable.HasValue, Is.True, "Expected variable to have value, but HasValue returned false.");
Assert.That(variable.HasNothing, Is.False, "Expected variable to have value, but HasNothing returned true.");
}
else
{
Assert.That(variable.HasNothing, Is.True, "Expected variable to have no value, but HasNothing returned false.");
Assert.That(variable.HasValue, Is.False, "Expected variable to have no value, but HasValue returned true.");
}
Assert.That(expectedValue, Is.EqualTo(variable.Value));
}
private enum ValidEnum
{
Default = 0,
TestA = 1,
TestB = 2,
}
private enum InvalidEnumA : long
{
Default = 0,
TestA = 1,
TestB = 2,
}
private enum InvalidEnumB : byte
{
Default = 0,
TestA = 1,
TestB = 2,
}
[Serializable]
private record ExampleSerializable
{
public int Value { get; set; }
public string? Value2 { get; set; }
}
[TearDown]
public void CleanupTestObject()
{
foreach (NwGameObject testObject in createdTestObjects)
{
testObject.PlotFlag = false;
testObject.Destroy();
}
createdTestObjects.Clear();
}
}
}
| 46.964824 | 149 | 0.71988 | [
"MIT"
] | milliorn/Anvil | NWN.Anvil.Tests/src/main/API/Variable/LocalVariableTests.cs | 9,346 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.ServiceBus.UnitTests
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Xunit;
public class OnSessionQueueTests
{
public static IEnumerable<object[]> TestPermutations => new object[][]
{
new object[] { TestConstants.SessionNonPartitionedQueueName, 1 },
new object[] { TestConstants.SessionNonPartitionedQueueName, 5 },
new object[] { TestConstants.SessionPartitionedQueueName, 1 },
new object[] { TestConstants.SessionPartitionedQueueName, 5 },
};
public static IEnumerable<object[]> PartitionedNonPartitionedTestPermutations => new object[][]
{
new object[] { TestConstants.SessionNonPartitionedQueueName, 5 },
new object[] { TestConstants.SessionPartitionedQueueName, 5 },
};
[Theory]
[MemberData(nameof(TestPermutations))]
[LiveTest]
[DisplayTestMethodName]
Task OnSessionPeekLockWithAutoCompleteTrue(string queueName, int maxConcurrentCalls)
{
return this.OnSessionTestAsync(queueName, maxConcurrentCalls, ReceiveMode.PeekLock, true);
}
[Theory]
[MemberData(nameof(TestPermutations))]
[LiveTest]
[DisplayTestMethodName]
Task OnSessionPeekLockWithAutoCompleteFalse(string queueName, int maxConcurrentCalls)
{
return this.OnSessionTestAsync(queueName, maxConcurrentCalls, ReceiveMode.PeekLock, false);
}
[Theory]
[MemberData(nameof(PartitionedNonPartitionedTestPermutations))]
[LiveTest]
[DisplayTestMethodName]
Task OnSessionReceiveDelete(string queueName, int maxConcurrentCalls)
{
return this.OnSessionTestAsync(queueName, maxConcurrentCalls, ReceiveMode.ReceiveAndDelete, false);
}
[Fact]
[LiveTest]
[DisplayTestMethodName]
async Task OnSessionCanStartWithNullMessageButReturnSessionLater()
{
var queueClient = new QueueClient(
TestUtility.NamespaceConnectionString,
TestConstants.SessionNonPartitionedQueueName,
ReceiveMode.PeekLock);
try
{
var sessionHandlerOptions =
new SessionHandlerOptions(ExceptionReceivedHandler)
{
MaxConcurrentSessions = 5,
MessageWaitTimeout = TimeSpan.FromSeconds(5),
AutoComplete = true
};
var testSessionHandler = new TestSessionHandler(
queueClient.ReceiveMode,
sessionHandlerOptions,
queueClient.InnerSender,
queueClient.SessionPumpHost);
// Register handler first without any messages
testSessionHandler.RegisterSessionHandler(sessionHandlerOptions);
// Send messages to Session
await testSessionHandler.SendSessionMessages();
// Verify messages were received.
await testSessionHandler.VerifyRun();
// Clear the data and re-run the scenario.
testSessionHandler.ClearData();
await testSessionHandler.SendSessionMessages();
// Verify messages were received.
await testSessionHandler.VerifyRun();
}
finally
{
await queueClient.CloseAsync();
}
}
[Fact]
[LiveTest]
[DisplayTestMethodName]
async Task OnSessionExceptionHandlerCalledWhenRegisteredOnNonSessionFulQueue()
{
var exceptionReceivedHandlerCalled = false;
var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedQueueName);
var sessionHandlerOptions = new SessionHandlerOptions(
(eventArgs) =>
{
Assert.NotNull(eventArgs);
Assert.NotNull(eventArgs.Exception);
if (eventArgs.Exception is InvalidOperationException)
{
exceptionReceivedHandlerCalled = true;
}
return Task.CompletedTask;
})
{ MaxConcurrentSessions = 1 };
queueClient.RegisterSessionHandler(
(session, message, token) =>
{
return Task.CompletedTask;
},
sessionHandlerOptions);
var stopwatch = Stopwatch.StartNew();
while (stopwatch.Elapsed.TotalSeconds <= 10)
{
if (exceptionReceivedHandlerCalled)
{
break;
}
await Task.Delay(TimeSpan.FromSeconds(1));
}
Assert.True(exceptionReceivedHandlerCalled);
await queueClient.CloseAsync();
}
async Task OnSessionTestAsync(string queueName, int maxConcurrentCalls, ReceiveMode mode, bool autoComplete)
{
TestUtility.Log($"Queue: {queueName}, MaxConcurrentCalls: {maxConcurrentCalls}, Receive Mode: {mode.ToString()}, AutoComplete: {autoComplete}");
var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, mode);
try
{
var handlerOptions =
new SessionHandlerOptions(ExceptionReceivedHandler)
{
MaxConcurrentSessions = maxConcurrentCalls,
MessageWaitTimeout = TimeSpan.FromSeconds(5),
AutoComplete = autoComplete
};
var testSessionHandler = new TestSessionHandler(
queueClient.ReceiveMode,
handlerOptions,
queueClient.InnerSender,
queueClient.SessionPumpHost);
// Send messages to Session first
await testSessionHandler.SendSessionMessages();
// Register handler
testSessionHandler.RegisterSessionHandler(handlerOptions);
// Verify messages were received.
await testSessionHandler.VerifyRun();
}
finally
{
await queueClient.CloseAsync();
}
}
Task ExceptionReceivedHandler(ExceptionReceivedEventArgs eventArgs)
{
TestUtility.Log($"Exception Received: ClientId: {eventArgs.ExceptionReceivedContext.ClientId}, EntityPath: {eventArgs.ExceptionReceivedContext.EntityPath}, Exception: {eventArgs.Exception.Message}");
return Task.CompletedTask;
}
}
} | 38.112903 | 211 | 0.587812 | [
"MIT"
] | Yiliu-microsoft/azure-sdk-for-net | src/SDKs/ServiceBus/data-plane/tests/Microsoft.Azure.ServiceBus.Tests/OnSessionQueueTests.cs | 7,091 | C# |
using UnityEngine;
using UnityEngine.Events;
using Vuforia;
public class CustomDefaultTrackableEventHandler : DefaultTrackableEventHandler
{
public UnityEvent OnTrackingAction;
public UnityEvent OffTrackingAction;
protected override void OnTrackingFound()
{
base.OnTrackingFound();
OnTrackingAction.Invoke();
}
protected override void OnTrackingLost()
{
base.OnTrackingLost();
OffTrackingAction.Invoke();
}
}
| 18.73913 | 78 | 0.791183 | [
"MIT"
] | cammelworks/AR-Beats | ARDrum/Assets/Script/CustomDefaultTrackableEventHandler.cs | 433 | C# |
using Pims.Api.Controllers;
using Pims.Core.Extensions;
using Pims.Core.Test;
using System.Diagnostics.CodeAnalysis;
using Xunit;
namespace Pims.Api.Test.Routes
{
/// <summary>
/// UserControllerTest class, provides a way to test endpoint routes.
/// </summary>
[Trait("category", "unit")]
[Trait("category", "api")]
[Trait("group", "user")]
[Trait("group", "route")]
[ExcludeFromCodeCoverage]
public class UserControllerTest
{
#region Tests
[Fact]
public void User_Route()
{
// Arrange
// Act
// Assert
var type = typeof(UserController);
type.HasAuthorize();
type.HasRoute("users");
type.HasRoute("v{version:apiVersion}/users");
}
[Fact]
public void UserInfo_Route()
{
// Arrange
var endpoint = typeof(UserController).FindMethod(nameof(UserController.UserInfoAsync));
// Act
// Assert
Assert.NotNull(endpoint);
endpoint.HasGet("info");
}
#endregion
}
}
| 24.717391 | 99 | 0.552331 | [
"Apache-2.0"
] | FuriousLlama/PSP | backend/tests/unit/api/Routes/UserControllerTest.cs | 1,137 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.OleDb;
using System.Data;
using System.Text;
public partial class POS_UploadStock : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadACC_ChartOfAccountLabel4();
}
}
private void loadACC_ChartOfAccountLabel4()
{
List<ACC_ChartOfAccountLabel4> aCC_ChartOfAccountLabel4s = new List<ACC_ChartOfAccountLabel4>();
aCC_ChartOfAccountLabel4s = ACC_ChartOfAccountLabel4Manager.GetAllACC_ChartOfAccountLabel4sForJournalEntry();
ddlShowRoom.Items.Add(new ListItem("All Show Room", "0"));
foreach (ACC_ChartOfAccountLabel4 aCC_ChartOfAccountLabel4 in aCC_ChartOfAccountLabel4s)
{
ListItem item = new ListItem(aCC_ChartOfAccountLabel4.ChartOfAccountLabel4Text.ToString(), aCC_ChartOfAccountLabel4.ACC_HeadTypeID.ToString() + "@" + aCC_ChartOfAccountLabel4.ACC_ChartOfAccountLabel4ID.ToString());
if ((aCC_ChartOfAccountLabel4.ACC_ChartOfAccountLabel4ID == 1 || aCC_ChartOfAccountLabel4.ChartOfAccountLabel4Text.ToLower().Contains("show room")) &&
aCC_ChartOfAccountLabel4.ACC_HeadTypeID == 1)
{
item = new ListItem(aCC_ChartOfAccountLabel4.ChartOfAccountLabel4Text.ToString(), aCC_ChartOfAccountLabel4.ACC_ChartOfAccountLabel4ID.ToString());
ddlShowRoom.Items.Add(item);
}
}
}
private string uplaodFile()
{
if (fuldStock.HasFile)
{
#region fileUpload
string strPath = string.Empty;
string dirURL = "~/files/file/Stock/";
if (!Directory.Exists(MapPath(dirURL)))
Directory.CreateDirectory(MapPath(dirURL));
getFileName fileName = new getFileName(fuldStock.FileName, MapPath(dirURL));
strPath = MapPath(dirURL + "/" + fileName.FileName);
fuldStock.SaveAs(strPath);
#endregion
return fileName.FileName;
}
return "";
}
protected void btnSave_Click(object sender, EventArgs e)
{
string dirURL = "~/files/file/Stock/";
string conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + MapPath(dirURL) + uplaodFile() + "';Extended Properties='Excel 12.0;HDR=Yes';";
// string conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='G:/Anam/Projects/Mavrick/gentlepark/Offline Version/Code/HO/V5/POS/Stock" + uplaodFile() + "';Extended Properties='Excel 12.0;HDR=Yes';";
OleDbConnection objConn = new OleDbConnection(conn);
objConn.Open();
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", objConn);
OleDbDataAdapter objAdapter = new OleDbDataAdapter();
objAdapter.SelectCommand = objCmdSelect;
DataSet objDataset = new DataSet();
objAdapter.Fill(objDataset);
objConn.Close();
GridView1.DataSource = objDataset.Tables[0];
GridView1.DataBind();
string sql = @"
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Table_1]') AND type in (N'U'))
DROP TABLE [dbo].[Table_1]
CREATE TABLE [dbo].[Table_1](
[ProductName] [nvarchar](256) NULL,
[Barcode] [nvarchar](50) NULL,
[Style] [nvarchar](50) NULL,
[Size] [nvarchar](50) NULL,
[Qty] [decimal](18, 2) NULL,
[Price] [decimal](18, 2) NULL
)
delete Table_1;
";
string ex = "";
decimal total = 0;
CommonManager.SQLExec(sql);
foreach (GridViewRow gvr in GridView1.Rows)
{
try
{
if (int.Parse(gvr.Cells[4].Text) > 0)
{
sql = @"
INSERT INTO [GentlePark].[dbo].[Table_1]
([ProductName]
,[Barcode]
,[Style]
,[Size]
,[Qty]
,[Price])
VALUES
('" + gvr.Cells[1].Text + @"'--<ProductName, nvarchar(256),>
,'" + gvr.Cells[0].Text + @"'--<Barcode, nvarchar(50),>
,'" + gvr.Cells[2].Text + @"'--<Style, nvarchar(50),>
,'" + gvr.Cells[3].Text + @"'--<Size, nvarchar(50),>
," + gvr.Cells[4].Text + @"--<Qry, decimal(18,2),>
," + decimal.Parse(gvr.Cells[5].Text).ToString("0.00") + @"--<price, decimal(18,2),>
); ";
total += (decimal.Parse(gvr.Cells[4].Text) * decimal.Parse(gvr.Cells[5].Text));
CommonManager.SQLExec(sql);
}
}
catch (Exception exep)
{
ex += gvr.Cells[0].Text+",";
}
}
#region Brnach
try
{
sql = "/*" + ex + total + @"*/
USE GentlePark
Declare @ProductName nvarchar(256)
Declare @ProductID int
Declare @Pos_ProductID int
Declare @BarCode nvarchar(256)
Declare @Style nvarchar(256)
Declare @Size nvarchar(256)
Declare @Pos_SizeID int
Declare @ExtraField1 nvarchar(256)
declare @Price decimal(10,2)
Declare @WorkStationID int
set @WorkStationID=" + ddlShowRoom.SelectedValue + @"
Declare @Pos_TransactionMasterID int
Set @Pos_TransactionMasterID=" + int.Parse(ddlShowRoom.SelectedItem.Text.Split('-')[1]).ToString() + @"
DECLARE product_cursor CURSOR FOR
SELECT ProductName,Barcode,Qty,Price,Style,Size
FROM Table_1
--where cast(Qty as int) >0
OPEN product_cursor
FETCH NEXT FROM product_cursor INTO @ProductName,@BarCode,@ExtraField1,@Price,@Style,@Size
WHILE @@FETCH_STATUS = 0
BEGIN
Set @ProductID = (Select Count(*) from ACC_ChartOfAccountLabel4 where ChartOfAccountLabel4Text=@ProductName and ACC_HeadTypeID=3)
if @ProductID = 0
BEGIN
--Create Product Name
INSERT INTO [ACC_ChartOfAccountLabel4]
([Code]
,[ACC_HeadTypeID]
,[ChartOfAccountLabel4Text]
,[ExtraField1]
,[ExtraField2]
,[ExtraField3]
,[AddedBy]
,[AddedDate]
,[UpdatedBy]
,[UpdatedDate]
,[RowStatusID])
VALUES
(''
,3
,@ProductName
,SUBSTRING(@BarCode,1,5)
,''
,'@'
,1
,GETDATE()
,1
,GETDATE()
,1)
END
Set @ProductID = (select top 1 ACC_ChartOfAccountLabel4ID from ACC_ChartOfAccountLabel4 where ChartOfAccountLabel4Text=@ProductName and ACC_HeadTypeID=3)
--add Product
Set @Pos_ProductID = (Select Count(*) from Pos_Product where BarCode=@BarCode)
if @Pos_ProductID = 0
BEGIN
if(select Count(Pos_SizeID) from Pos_Size where SizeName =@Size) =0
BEGIN
set @Pos_SizeID= 46
END
ELSE
BEGIN
set @Pos_SizeID =(select top 1 Pos_SizeID from Pos_Size where SizeName =@Size)
END
INSERT INTO [Pos_Product]
([ProductID]
,[ReferenceID]
,[Pos_ProductTypeID]
,[Inv_UtilizationDetailsIDs]
,[ProductStatusID]
,[ProductName]
,[DesignCode]
,[Pos_SizeID]
,[Pos_BrandID]
,[Inv_QuantityUnitID]
,[FabricsCost]
,[AccesoriesCost]
,[Overhead]
,[OthersCost]
,[PurchasePrice]
,[SalePrice]
,[OldSalePrice]
,[Note]
,[BarCode]
,[Pos_ColorID]
,[Pos_FabricsTypeID]
,[StyleCode]
,[Pic1]
,[Pic2]
,[Pic3]
,[VatPercentage]
,[IsVatExclusive]
,[DiscountPercentage]
,[DiscountAmount]
,[FabricsNo]
,[ExtraField1]
,[ExtraField2]
,[ExtraField3]
,[ExtraField4]
,[ExtraField5]
,[ExtraField6]
,[ExtraField7]
,[ExtraField8]
,[ExtraField9]
,[ExtraField10]
,[AddedBy]
,[AddedDate]
,[UpdatedBy]
,[UpdatedDate]
,[RowStatusID])
VALUES
(@ProductID
,1
,1
,''
,1
,@ProductName
,''
,@Pos_SizeID
,1
,3
,0
,0
,0
,0
,0
,@Price
,0
,'Stock entry-BR'
,@BarCode
,1
,1
,@Style
,''
,''
,''
,0
,1
,0
,0
,''
,'0'
,''
,''
,''
,''
,''
,''
,''
,''
,''
,1
,GETDATE()
,1
,GETDATE()
,1);
Set @Pos_ProductID = (Select top 1 Pos_ProductID from Pos_Product where BarCode=@BarCode)
END
Set @Pos_ProductID = (Select top 1 Pos_ProductID from Pos_Product where BarCode=@BarCode)
--Production Transaction
INSERT INTO [Pos_Transaction]
([Pos_ProductID]
,[Quantity]
,[Pos_ProductTrasactionTypeID]
,[Pos_ProductTransactionMasterID]
,[WorkStationID]
,[ExtraField1]
,[ExtraField2]
,[ExtraField3]
,[ExtraField4]
,[ExtraField5]
,[AddedBy]
,[AddedDate]
,[UpdatedBy]
,[UpdatedDate]
,[RowStatusID])
VALUES
(@Pos_ProductID
,Cast(@ExtraField1 as decimal(10,2))
,1
,21
,1
,''
,''
,''
,''
,''
,1
,GETDATE()
,1
,GETDATE()
,1)
--accounts need to update
--Issue Transaction
INSERT INTO [Pos_Transaction]
([Pos_ProductID]
,[Quantity]
,[Pos_ProductTrasactionTypeID]
,[Pos_ProductTransactionMasterID]
,[WorkStationID]
,[ExtraField1]
,[ExtraField2]
,[ExtraField3]
,[ExtraField4]
,[ExtraField5]
,[AddedBy]
,[AddedDate]
,[UpdatedBy]
,[UpdatedDate]
,[RowStatusID])
VALUES
(@Pos_ProductID
,Cast(@ExtraField1 as decimal(10,2))
,9
,@Pos_TransactionMasterID
,@WorkStationID
,''
,''
,''
,''
,''
,1
,GETDATE()
,1
,GETDATE()
,1)
Declare @Count int
set @Count=
(
select COUNT(*) from Pos_WorkStationStock
where ProductID=@Pos_ProductID and WorkStationID=@WorkStationID
)
if @Count = 0
BEGIN
INSERT INTO [Pos_WorkStationStock]
([WorkStationID]
,[ProductID]
,[Stock])
VALUES(@WorkStationID,@Pos_ProductID ,CAST(@ExtraField1 as Decimal(10,2)));
END
ELSE
BEGIN
Update Pos_WorkStationStock set Stock += CAST(@ExtraField1 as Decimal(10,2)) where ProductID=@Pos_ProductID and WorkStationID=@WorkStationID;
END
FETCH NEXT FROM product_cursor INTO @ProductName,@BarCode,@ExtraField1,@Price,@Style,@Size
END
CLOSE product_cursor
DEALLOCATE product_cursor
";
}
catch (Exception ex3)
{ }
#endregion
#region Centeral
string sql_HeadOffice;
sql_HeadOffice = "/*" + ex + total + @"*/
USE GentlePark
Declare @ProductName nvarchar(256)
Declare @ProductID int
Declare @Pos_ProductID int
Declare @BarCode nvarchar(256)
Declare @Style nvarchar(256)
Declare @Size nvarchar(256)
Declare @Pos_SizeID int
Declare @ExtraField1 nvarchar(256)
declare @Price decimal(10,2)
Declare @WorkStationID int
set @WorkStationID=1
Declare @Pos_TransactionMasterID int
Set @Pos_TransactionMasterID=20
DECLARE product_cursor CURSOR FOR
SELECT ProductName,Barcode,Qty,Price,Style,Size
FROM Table_1
--where cast(Qty as int) >0
OPEN product_cursor
FETCH NEXT FROM product_cursor INTO @ProductName,@BarCode,@ExtraField1,@Price,@Style,@Size
WHILE @@FETCH_STATUS = 0
BEGIN
Set @ProductID = (Select Count(*) from ACC_ChartOfAccountLabel4 where ChartOfAccountLabel4Text=@ProductName and ACC_HeadTypeID=3)
if @ProductID = 0
BEGIN
--Create Product Name
INSERT INTO [ACC_ChartOfAccountLabel4]
([Code]
,[ACC_HeadTypeID]
,[ChartOfAccountLabel4Text]
,[ExtraField1]
,[ExtraField2]
,[ExtraField3]
,[AddedBy]
,[AddedDate]
,[UpdatedBy]
,[UpdatedDate]
,[RowStatusID])
VALUES
(''
,3
,@ProductName
,SUBSTRING(@BarCode,1,5)
,''
,'@'
,1
,GETDATE()
,1
,GETDATE()
,1)
END
Set @ProductID = (select top 1 ACC_ChartOfAccountLabel4ID from ACC_ChartOfAccountLabel4 where ChartOfAccountLabel4Text=@ProductName and ACC_HeadTypeID=3)
--add Product
Set @Pos_ProductID = (Select Count(*) from Pos_Product where BarCode=@BarCode)
if @Pos_ProductID = 0
BEGIN
if(select Count(Pos_SizeID) from Pos_Size where SizeName =@Size) =0
BEGIN
set @Pos_SizeID= 46
END
ELSE
BEGIN
set @Pos_SizeID =(select top 1 Pos_SizeID from Pos_Size where SizeName =@Size)
END
INSERT INTO [Pos_Product]
([ProductID]
,[ReferenceID]
,[Pos_ProductTypeID]
,[Inv_UtilizationDetailsIDs]
,[ProductStatusID]
,[ProductName]
,[DesignCode]
,[Pos_SizeID]
,[Pos_BrandID]
,[Inv_QuantityUnitID]
,[FabricsCost]
,[AccesoriesCost]
,[Overhead]
,[OthersCost]
,[PurchasePrice]
,[SalePrice]
,[OldSalePrice]
,[Note]
,[BarCode]
,[Pos_ColorID]
,[Pos_FabricsTypeID]
,[StyleCode]
,[Pic1]
,[Pic2]
,[Pic3]
,[VatPercentage]
,[IsVatExclusive]
,[DiscountPercentage]
,[DiscountAmount]
,[FabricsNo]
,[ExtraField1]
,[ExtraField2]
,[ExtraField3]
,[ExtraField4]
,[ExtraField5]
,[ExtraField6]
,[ExtraField7]
,[ExtraField8]
,[ExtraField9]
,[ExtraField10]
,[AddedBy]
,[AddedDate]
,[UpdatedBy]
,[UpdatedDate]
,[RowStatusID])
VALUES
(@ProductID
,1
,1
,''
,1
,@ProductName
,''
,@Pos_SizeID
,1
,3
,0
,0
,0
,0
,0
,@Price
,0
,'Stock entry-BR'
,@BarCode
,1
,1
,@Style
,''
,''
,''
,0
,1
,0
,0
,''
,@ExtraField1
,''
,''
,''
,''
,''
,''
,''
,''
,''
,1
,GETDATE()
,1
,GETDATE()
,1);
Set @Pos_ProductID = (Select top 1 Pos_ProductID from Pos_Product where BarCode=@BarCode)
--Transaction
INSERT INTO [Pos_Transaction]
([Pos_ProductID]
,[Quantity]
,[Pos_ProductTrasactionTypeID]
,[Pos_ProductTransactionMasterID]
,[WorkStationID]
,[ExtraField1]
,[ExtraField2]
,[ExtraField3]
,[ExtraField4]
,[ExtraField5]
,[AddedBy]
,[AddedDate]
,[UpdatedBy]
,[UpdatedDate]
,[RowStatusID])
VALUES
(@Pos_ProductID
,Cast(@ExtraField1 as decimal(10,2))
,1
,@Pos_TransactionMasterID
,1
,''
,''
,''
,''
,''
,1
,GETDATE()
,1
,GETDATE()
,1)
--accounts need to update
END
Set @Pos_ProductID = (Select top 1 Pos_ProductID from Pos_Product where BarCode=@BarCode)
update Pos_Product set ExtraField1=@ExtraField1 where Pos_ProductID=@Pos_ProductID
FETCH NEXT FROM product_cursor INTO @ProductName,@BarCode,@ExtraField1,@Price,@Style,@Size
END
CLOSE product_cursor
DEALLOCATE product_cursor
";
#endregion
txtCursor.Text = sql;
CommonManager.SQLExec(sql_HeadOffice);
//CommonManager.SQLExec(sql);
//DataSet ds = MSSQL.SQLExec(sql + "; select Count(*) from Mem_Fees where Comn_PaymentByID=2");
//Label1.Text = ds.Tables[0].Rows.Count + " Record(s) Added Successfully";
//btnSave.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
string sql = @"
SELECT [ProductID] into #tmp
FROM [GentlePark].[dbo].[Pos_WorkStationStock]
where ProductID<107
Select BarCode,SalePrice,Pos_ProductID
from Pos_Product where Pos_ProductID
in (select * from #tmp) and BarCode in (Select distinct Barcode from Table_1)
drop table #tmp
";
DataSet ds = CommonManager.SQLExec(sql);
sql = "";
foreach (DataRow dr in ds.Tables[0].Rows)
{
sql += @"
update Pos_Product set SalePrice=(Select top 1 Price from Table_1 where BarCode='" + dr["BarCode"].ToString().Trim() + @"') where Pos_ProductID=" + dr["Pos_ProductID"].ToString().Trim() + @";
";
}
CommonManager.SQLExec(sql);
}
} | 28.149773 | 226 | 0.512925 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | anam/abs | V1/POS/UploadStock.aspx.cs | 18,609 | C# |
// File generated from our OpenAPI spec
namespace Stripe
{
public class PaymentIntentPaymentMethodOptionsIdealOptions : INestedOptions
{
}
}
| 19.125 | 79 | 0.75817 | [
"Apache-2.0"
] | Manny27nyc/stripe-dotnet | src/Stripe.net/Services/PaymentIntents/PaymentIntentPaymentMethodOptionsIdealOptions.cs | 153 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using ReviewLibrary;
namespace Project3
{
public partial class HomePage : System.Web.UI.Page
{
Utilities utilities = new Utilities();
//INDEX of USED columns
private const int RESTID_COLUMN = 4;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ShowRestaurantsList();
ShowCategoriesList();
hidSearchClicked.Value = "false";
}
}
//Show the list of all restaurants
private void ShowRestaurantsList()
{
gvRestaurants.DataSource = utilities.GetRestaurants();
gvRestaurants.DataBind();
}
//Show the list of categories
private void ShowCategoriesList()
{
DataSet ds = utilities.GetCategories();
if (ds.Tables.Count > 0)
{
foreach (DataRow row in ds.Tables[0].Rows)
{
ddlCategory.Items.Add(new ListItem() { Text = row["CategoryName"].ToString(), Value = row["CategoryID"].ToString() });
}
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
DataSet ds = utilities.GetSearchRestaurant(txtSearch.Text, int.Parse(ddlCategory.SelectedValue));
gvRestaurants.DataSource = ds;
gvRestaurants.DataBind();
hidSearchClicked.Value = "true";
}
protected void gvRestaurants_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("ViewRestaurant.aspx?RestID=" + gvRestaurants.SelectedRow.Cells[RESTID_COLUMN].Text);
}
protected void gvRestaurants_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvRestaurants.PageIndex = e.NewPageIndex;
if ("true".Equals(hidSearchClicked.Value))
{
DataSet ds = utilities.GetSearchRestaurant(txtSearch.Text, int.Parse(ddlCategory.SelectedValue));
gvRestaurants.DataSource = ds;
gvRestaurants.DataBind();
}
else
{
gvRestaurants.DataSource = utilities.GetRestaurants();
gvRestaurants.DataBind();
}
}
}
} | 31.55 | 138 | 0.570523 | [
"MIT"
] | tran-temple/CIS3342-PracticeProjects | Project3/HomePage.aspx.cs | 2,526 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace KWUI.Properties {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("KWUI.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 44.453125 | 170 | 0.624253 | [
"MIT"
] | KirsonWorks/HalftoneFx | GUI/Properties/Resources.Designer.cs | 3,356 | C# |
namespace Parliament.ProcedureEditor.Web.Models
{
public enum SeriesMembershipType
{
Country = 1,
EuropeanUnion = 2,
Miscellaneous = 3,
Treaty = 4
}
} | 19.5 | 48 | 0.594872 | [
"MIT"
] | ukparliament/ProcedureEditor | Parliament.ProcedureEditor.Web/Models/SeriesMembershipType.cs | 197 | C# |
using System;
namespace MeetingsApi.Dtos
{
public class Participant
{
public int Id { get; set; }
public int UserId { get; set; }
public int MeetingId { get; set; }
public DateTime Created { get; set; }
}
}
| 16 | 45 | 0.570313 | [
"MIT"
] | ddydeveloper/SpbDotNet_make_a_meet | 3_micro-services/meetings/MeetingsApi/Dtos/Participant.cs | 258 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity.ModelConfiguration;
using DXInfo.Models;
namespace DXInfo.Data.Configuration
{
public class vwBillConfiguration : EntityTypeConfiguration<vwBill>
{
public vwBillConfiguration()
{
this.HasKey(k => k.iSerial);
}
}
}
| 20.833333 | 70 | 0.696 | [
"Apache-2.0"
] | zhenghua75/DXInfo | DXInfo.Data/Configuration/vwBillConfiguration.cs | 377 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: MethodRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type UserGetManagedDevicesWithFailedOrPendingAppsRequestBuilder.
/// </summary>
public partial class UserGetManagedDevicesWithFailedOrPendingAppsRequestBuilder : BaseFunctionMethodRequestBuilder<IUserGetManagedDevicesWithFailedOrPendingAppsRequest>, IUserGetManagedDevicesWithFailedOrPendingAppsRequestBuilder
{
/// <summary>
/// Constructs a new <see cref="UserGetManagedDevicesWithFailedOrPendingAppsRequestBuilder"/>.
/// </summary>
/// <param name="requestUrl">The URL for the request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
public UserGetManagedDevicesWithFailedOrPendingAppsRequestBuilder(
string requestUrl,
IBaseClient client)
: base(requestUrl, client)
{
this.SetFunctionParameters();
}
/// <summary>
/// A method used by the base class to construct a request class instance.
/// </summary>
/// <param name="functionUrl">The request URL to </param>
/// <param name="options">The query and header options for the request.</param>
/// <returns>An instance of a specific request class.</returns>
protected override IUserGetManagedDevicesWithFailedOrPendingAppsRequest CreateRequest(string functionUrl, IEnumerable<Option> options)
{
var request = new UserGetManagedDevicesWithFailedOrPendingAppsRequest(functionUrl, this.Client, options);
return request;
}
}
}
| 44.916667 | 233 | 0.643785 | [
"MIT"
] | GeertVL/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/UserGetManagedDevicesWithFailedOrPendingAppsRequestBuilder.cs | 2,156 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace AssemblyCSharp
{
public class Lego
{
private ColorSpecification color;
private Vector3 position, gpos;
private Vector2 dimen;
private LegoType type;
public List<Vector3> gposList;
public List<Vector3> up;
public List<Vector3> down;
public List<Vector3> left;
public List<Vector3> right;
public List<Vector3> front;
public List<Vector3> back;
public bool isBound = false;
public bool isVisted = false;
public Lego (ColorSpecification color, Vector3 position, LegoType type, bool isBound){
this.color = color;
this.position = position;
this.type = type;
this.isBound = isBound;
this.dimen = new Vector2(1,1);
gposList = new List<Vector3> ();
up = new List<Vector3>();
down = new List<Vector3>();
left = new List<Vector3>();
right = new List<Vector3>();
front = new List<Vector3>();
back = new List<Vector3>();
}
public void setPosition(Vector3 position){
this.position = position;
}
public void setGPos(Vector3 gpos){
this.gpos = gpos;
}
public void addConnectedLego(List<Vector3> up, List<Vector3> down){
this.up.Clear ();
this.down.Clear ();
this.up.AddRange (up);
this.down.AddRange (down);
}
public void addNeighborLego(List<Vector3> up, List<Vector3> down, List<Vector3> left, List<Vector3> right, List<Vector3> front, List<Vector3> back){
this.up.Clear ();
this.down.Clear ();
this.left.Clear ();
this.right.Clear ();
this.front.Clear ();
this.back.Clear ();
this.up.AddRange (up);
this.down.AddRange (down);
this.left.AddRange (left);
this.right.AddRange (right);
this.front.AddRange (front);
this.back.AddRange (back);
}
public void addNeighborLego(List<Vector3> up, List<Vector3> down, List<Vector3> left, List<Vector3> right){
this.up.Clear ();
this.down.Clear ();
this.left.Clear ();
this.right.Clear ();
this.up.AddRange (up);
this.down.AddRange (down);
this.left.AddRange (left);
this.right.AddRange (right);
}
public void changeType(LegoType type){
this.type = type;
}
public void changePosition(Vector3 position){
this.position = position;
}
public void changeDimen(Vector2 dimen){
this.dimen = dimen;
}
public void changeColor(ColorSpecification color){
this.color = color;
}
public Vector3 getGPosition(){
return gpos;
}
public Vector3 getLPosition(){
float lx = gpos.x;
float ly = gpos.y;
float lz = gpos.z;
return new Vector3(lx*0.8f+0.4f,ly*0.32f,lz*0.8f+0.4f);
}
public Vector3 getLPosition(bool isHorizontal){
float lx = gpos.x;
float ly = gpos.y;
float lz = isHorizontal?gpos.z+1 : gpos.z;
return new Vector3(lx*0.8f+0.4f,ly*0.32f,lz*0.8f+0.4f);
}
public Vector2 getDimen(){
return dimen;
}
public ColorSpecification getColor(){
return color;
}
public Vector3 getPosition(){
return position;
}
public LegoType getType(){
return type;
}
}
}
| 24.239437 | 150 | 0.640035 | [
"MIT"
] | dragon1219/Automatic-brick-building-software | Assets/script/Legoization/Lego.cs | 3,442 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
namespace Clase_17ABM
{
public partial class modificacionArticulos : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SqlDataSourceRubros_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void btnBuscar_Click(object sender, EventArgs e)
{
SqlDataSourceArticulo.SelectParameters["id_Articulo"].DefaultValue = txtCodigoArticulo.Text;
SqlDataSourceArticulo.DataSourceMode = SqlDataSourceMode.DataReader;
SqlDataReader registro;
registro = (SqlDataReader)SqlDataSourceArticulo.Select(DataSourceSelectArguments.Empty);
if (registro.Read())
{
txtDescripcion_ar.Text = registro["descripcion_Articulo"].ToString();
txtPrecio_ar.Text = registro["precio_articulo"].ToString();
DropDownList_ar.SelectedValue = registro["id_Rubro"].ToString();
DropDownList_ar.DataSource = SqlDataSourceRubros;
DropDownList_ar.DataTextField = "nombre_rubro";
DropDownList_ar.DataValueField = "id_Rubro";
DropDownList_ar.DataBind();
}
else
{
lblNotificacionArticulo.Text = "<strong style='color:red;'>No Existe el Articulo</strong>";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlDataSourceArticulo.UpdateParameters["descripcion_Articulo"].DefaultValue = txtDescripcion_ar.Text;
SqlDataSourceArticulo.UpdateParameters["precio_Articulo"].DefaultValue = txtPrecio_ar.Text;
SqlDataSourceArticulo.UpdateParameters["id_Rubro"].DefaultValue = DropDownList_ar.Text;
SqlDataSourceArticulo.UpdateParameters["id_Articulo"].DefaultValue = txtCodigoArticulo.Text;
int cant;
cant = SqlDataSourceArticulo.Update();
if(cant == 1)
{
lblNotificacionArticulo.Text = "<strong style='background-color:lightgreen;'>Se Actualizo el Articulo Correctament</strong>";
}
else
{
lblNotificacionArticulo.Text = "<strong style='background-color:red;'>No Existe el Articulo!! </strong>";
}
}
protected void SqlDataSourceArticulo_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
}
} | 37.985714 | 141 | 0.644603 | [
"MIT"
] | manasesortez/SQLDataSource-ABM | Clase-17ABM/modificacionArticulos.aspx.cs | 2,661 | C# |
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Blogfolio.Models.Portfolio;
using Blogfolio.Models.Repositories.Portfolio;
namespace Blogfolio.Data.Repositories.Portfolio
{
/// <summary>
/// Entity framework implementation of <see cref="IProjectRepository" />
/// </summary>
internal class ProjectRepository : Repository<Project>, IProjectRepository
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="context"></param>
internal ProjectRepository(BlogfolioContext context)
: base(context)
{
}
/// <summary>
/// Returns a list of public projects
/// </summary>
/// <param name="count"></param>
/// <returns>List of public <see cref="Project" /></returns>
public List<Project> GetProjects(int count = 0)
{
var projects = Set.Where(p => p.Status == ProjectStatus.Public)
.OrderBy(p => p.DateCreated);
return count > 0
? projects.Take(count).ToList()
: projects.ToList();
}
/// <summary>
/// Asynchronously returns a list of public projects
/// </summary>
/// <param name="count"></param>
/// <returns>List of public <see cref="Project" /></returns>
public Task<List<Project>> GetProjectsAsync(int count = 0)
{
var projects = Set.Where(p => p.Status == ProjectStatus.Public)
.OrderBy(p => p.DateCreated);
return count > 0
? projects.Take(count).ToListAsync()
: projects.ToListAsync();
}
/// <summary>
/// Asynchronously returns a list of public projects
/// with cancellation support
/// </summary>
/// <param name="cancellationToken"></param>
/// <param name="count"></param>
/// <returns>List of public <see cref="Project" /></returns>
public Task<List<Project>> GetProjectsAsync(CancellationToken cancellationToken, int count = 0)
{
var projects = Set.Where(p => p.Status == ProjectStatus.Public)
.OrderBy(p => p.DateCreated);
return count > 0
? projects.Take(count).ToListAsync(cancellationToken)
: projects.ToListAsync(cancellationToken);
}
/// <summary>
/// Returns single public project
/// </summary>
/// <param name="slug"></param>
/// <returns>A public <see cref="Project" /></returns>
public Project GetProject(string slug)
{
var project = Set.FirstOrDefault(p => p.Slug == slug && p.Status == ProjectStatus.Public);
return project;
}
/// <summary>
/// Asynchronously returns single public project
/// </summary>
/// <param name="slug"></param>
/// <returns>A public <see cref="Project" /></returns>
public Task<Project> GetProjectAsync(string slug)
{
var project = Set.FirstOrDefaultAsync(p => p.Slug == slug && p.Status == ProjectStatus.Public);
return project;
}
/// <summary>
/// Asynchronously returns single public project
/// with cancellation support
/// </summary>
/// <param name="cancellationToken"></param>
/// <param name="slug"></param>
/// <returns>A public <see cref="Project" /></returns>
public Task<Project> GetProjectAsync(CancellationToken cancellationToken, string slug)
{
var project = Set.FirstOrDefaultAsync(p => p.Slug == slug && p.Status == ProjectStatus.Public,
cancellationToken);
return project;
}
}
} | 34.837838 | 107 | 0.562969 | [
"MIT"
] | erenpinaz/Blogfolio | Blogfolio.Data/Repositories/Portfolio/ProjectRepository.cs | 3,869 | C# |
using MeetAndGo.Interfaces;
using MeetAndGo.Model;
namespace MeetAndGo.Controllers
{
public class CanceledBuildingController : BaseReadController<Model.CanceledBuilding, object>
{
public CanceledBuildingController(IReadService<CanceledBuilding, object> service) : base(service) { }
}
}
| 28 | 109 | 0.772727 | [
"MIT"
] | emin-alajbegovic/Meet-Go | MeetAndGo/MeetAndGo/Controllers/CanceledBuildingController.cs | 310 | C# |
/*
* Copyright (c) Tomas Johansson , http://www.programmerare.com
* The code in the "core" project is licensed with MIT.
* Other projects within this Visual Studio solution may be released with other licenses e.g. Apache.
* Please find more information in the files "License.txt" and "NOTICE.txt"
* in the project root directory and/or in the solution root directory.
* It should also be possible to find more license information at this URL:
* https://github.com/TomasJohansson/adapters-shortest-paths-dotnet/
*/
namespace Programmerare.ShortestPaths.Core.Impl.Generics
{
/**
* Testing general behaviour independent of implementation.
* Of course, since the base class is abstract, some kind of subclass need to be instantiated.
*
* @author Tomas Johansson
*
*/
public class PathFinderFactoryGenericsBaseTest {
// The Graph validation tests have moved to GraphImplTest
// // TODO: refactor duplication ... the same test class as below is duplicated in another test class file
// public final class PathFinderConcreteTest extends PathFinderBase
// <
// PathGenerics<EdgeGenerics<Vertex, Weight>, Vertex, Weight>,
// EdgeGenerics<Vertex , Weight> ,
// Vertex ,
// Weight
// >
// {
// protected PathFinderConcreteTest(GraphGenerics<EdgeGenerics<Vertex, Weight>, Vertex, Weight> graph
//// GraphEdgesValidationDesired graphEdgesValidationDesired
// ) {
// //super(graph, graphEdgesValidationDesired);
// super(graph);
// Assert.fail("move test to other class since all validation is now done in Graph construction");
// }
//
// @Override
// protected List<PathGenerics<EdgeGenerics<Vertex, Weight>, Vertex, Weight>> findShortestPathHook(Vertex startVertex,
// Vertex endVertex, int maxNumberOfPaths) {
// // TODO Auto-generated method stub
// return null;
// }
//
// }
//
// public final class PathFinderFactoryConcreteForTest extends PathFinderFactoryGenericsBase
// < PathFinderGenerics<PathGenerics<EdgeGenerics<Vertex,Weight>,Vertex,Weight> , EdgeGenerics<Vertex,Weight>,Vertex,Weight> , PathGenerics<EdgeGenerics<Vertex,Weight>,Vertex,Weight> , EdgeGenerics<Vertex , Weight> , Vertex , Weight>
// {
//
// public PathFinderGenerics<PathGenerics<EdgeGenerics<Vertex, Weight>, Vertex, Weight>, EdgeGenerics<Vertex, Weight>, Vertex, Weight> createPathFinder(
// GraphGenerics<EdgeGenerics<Vertex, Weight>, Vertex, Weight> graph
// ) {
// Assert.fail("move test to other class since all validation is now done in Graph construction");
// return new PathFinderConcreteTest(
// graph
// //graphEdgesValidationDesired
// );
// }
// //
//
//// public PathFinder<Edge<Vertex, Weight>, Vertex, Weight> createPathFinder(
//// Graph<Edge<Vertex, Weight>, Vertex, Weight> graph,
//// GraphEdgesValidationDesired graphEdgesValidationDesired) {
//// return new PathFinderConcreteTest(
//// graph,
//// graphEdgesValidationDesired
//// );
//// }
// }
}
} | 39.013333 | 233 | 0.732741 | [
"MIT"
] | TomasJohansson/adapters-shortest-paths-dotnet | Programmerare.ShortestPaths.Test/test/Programmerare.ShortestPaths/Core/Impl/generics/PathFinderFactoryGenericsBaseTest.cs | 2,926 | C# |
using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Data;
using System.Collections;
using System.Collections.Generic;
namespace ColorPicker
{
class InterceptKeys
{
[DllImport("user32.dll")]
static extern bool SetKeyboardState(byte[] lpKeyState);
[DllImport("user32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags,
UIntPtr dwExtraInfo);
public const int KEYEVENTF_EXTENDEDKEY = 0x1;
public const int KEYEVENTF_KEYUP = 0x2;
public const int NUMLOCK = 144;
public const int CAPITAL = 0x14;
public const int SCROLL = 0x91;
public const int INSERT = 45;
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private const int WM_KEYUP = 0x0101;
private const int WM_SYSKEYDOWN = 0x0104;
private const int WM_SYSKEYUP = 0x0105;
private static LowLevelKeyboardProc _proc = HookCallback;
public static bool InAddKeyMode = false;
public static IntPtr _hookID = IntPtr.Zero;
/*
private static bool bShift = false;
private static bool bCtrl = false;
private static bool bAlt = false;
private static bool bAltGr = false;
private static bool bLWin = false;
private static bool bRWin = false;
*/
private static int bShift = 0;
private static int bCtrl = 0;
private static int bAlt = 0;
private static int bAltGr = 0;
private static int bLWin = 0;
private static int bRWin = 0;
public static bool Hooked = false;
public static bool HookedForAddKey = false;
[DllImport("user32.dll")]
public static extern IntPtr GetActiveWindow();
[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);
[StructLayout(LayoutKind.Sequential)]
private struct KBDLLHOOKSTRUCT
{
public Keys key;
public int scanCode;
public int flags;
public int time;
public IntPtr extra;
}
public static void HookKeys()
{
if (!Hooked)
{
/*
bwHookCallbak=new System.ComponentModel.BackgroundWorker();
bwHookCallbak.DoWork += bwHookCallbak_DoWork;
bwHookCallbak.RunWorkerAsync();
*/
bShift = 0;
bCtrl = 0;
bAlt = 0;
bAltGr = 0;
bLWin = 0;
bRWin = 0;
_hookID = SetHook(_proc);
Hooked = true;
}
}
public static void UnHookAll()
{
UnhookWindowsHookEx(_hookID);
Hooked = false;
}
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
GetModuleHandle(curModule.ModuleName), 0);
}
}
//1private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, ref KBDLLHOOKSTRUCT lParam);
private static bool ShouldSendKeys = true;
public static List<HookItem> HookItems = new List<HookItem>();
public static System.ComponentModel.BackgroundWorker bwHookCallbak=null;
public static void SendNumLock()
{
keybd_event(NUMLOCK, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr)0);
keybd_event(NUMLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, (UIntPtr)0);
}
/*
private static IntPtr NewHookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN || wParam == (IntPtr)WM_KEYUP || wParam == (IntPtr)WM_SYSKEYUP)
{
//Module.ShowMessage("WM_KEYDOWN OR WM_KEYUP");
KBDLLHOOKSTRUCT objKeyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(KBDLLHOOKSTRUCT));
int vkCode = (int)objKeyInfo.key;
vkCode = Marshal.ReadInt32(lParam);
//3HookItem hki = new HookItem(nCode, Marshal.ReadInt32(wParam), Marshal.ReadInt32(lParam));
HookItem hki = new HookItem(nCode, (int)wParam, vkCode);
lock (HookItems)
{
HookItems.Add(hki);
}
return new IntPtr(1);
}
else
{
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
}
*/
public static bool CheckSetHookTimer = false;
//private static bool ShowedMsg = false;
//1private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
private static IntPtr HookCallback(int nCode, IntPtr wParam, ref KBDLLHOOKSTRUCT lParamRef)
{
int vkCode = (int)lParamRef.key;
int vkCode2 = vkCode;
int flags = lParamRef.flags;
if (nCode >= 0 && (wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN))
{
if (vkCode == (int)Keys.LWin || vkCode == (int)Keys.RWin)
{
bLWin++;
vkCode = -1;
}
if (vkCode == (int)Keys.Apps)
{
bRWin++;
vkCode = -1;
}
if (vkCode == (int)Keys.LShiftKey || vkCode == (int)Keys.RShiftKey || vkCode == (int)Keys.Shift || vkCode == (int)Keys.ShiftKey)
{
bShift++;
vkCode = -1;
}
if (vkCode == (int)Keys.LControlKey || vkCode == (int)Keys.RControlKey || vkCode == (int)Keys.Control || vkCode == (int)Keys.ControlKey)
{
bCtrl++;
vkCode = -1;
}
if (vkCode == (int)Keys.LMenu)
{
bAlt++;
vkCode = -1;
}
if (vkCode == (int)Keys.RMenu)
{
bAltGr++;
vkCode = -1;
}
if ((bShift == 0 && bAlt == 0 && bCtrl > 0) && (vkCode == (int)Keys.F8))
{
if (!frmMain.Instance.Visible)
{
frmMain.Instance.Visible = true;
frmMain.Instance.WindowState = FormWindowState.Normal;
frmMain.Instance.Show();
frmMain.Instance.BringToFront();
frmMain.Instance.timPickColor.Enabled = true;
frmMain.Instance.timPickColor_Tick(null, null);
}
else
{
frmMain.Instance.Visible = true;
frmMain.Instance.WindowState = FormWindowState.Normal;
frmMain.Instance.Show();
frmMain.Instance.BringToFront();
if (frmMain.Instance.timPickColor.Enabled)
{
frmMain.Instance.SetPaletteColor();
}
frmMain.Instance.timPickColor.Enabled = !frmMain.Instance.timPickColor.Enabled;
}
return new IntPtr(1);
}
}
if (nCode >= 0 && (wParam == (IntPtr)WM_KEYUP || wParam == (IntPtr)WM_SYSKEYUP))
{
int vkCode3 = vkCode;
if (vkCode == (int)Keys.LWin || vkCode == (int)Keys.RWin)
{
vkCode3 = -1;
}
if (vkCode == (int)Keys.Apps)
{
vkCode3 = -1;
}
if (vkCode == (int)Keys.LShiftKey || vkCode == (int)Keys.RShiftKey || vkCode == (int)Keys.Shift || vkCode == (int)Keys.ShiftKey)
{
vkCode3 = -1;
}
if (vkCode == (int)Keys.LControlKey || vkCode == (int)Keys.RControlKey || vkCode == (int)Keys.Control || vkCode == (int)Keys.ControlKey)
{
vkCode3 = -1;
}
if (vkCode == (int)Keys.LMenu)
{
vkCode3 = -1;
}
if (vkCode == (int)Keys.RMenu)
{
vkCode3 = -1;
}
// ===================================
if (vkCode == (int)Keys.LWin || vkCode == (int)Keys.RWin)
{
bLWin = 0;
}
if (vkCode == (int)Keys.Apps)
{
bRWin = 0;
}
if (vkCode == (int)Keys.LShiftKey || vkCode == (int)Keys.RShiftKey || vkCode == (int)Keys.Shift || vkCode == (int)Keys.ShiftKey)
{
bShift = 0;
}
if (vkCode == (int)Keys.LControlKey || vkCode == (int)Keys.RControlKey || vkCode == (int)Keys.Control || vkCode == (int)Keys.ControlKey)
{
bCtrl = 0;
}
if (vkCode == (int)Keys.LMenu)
{
bAlt = 0;
}
if (vkCode == (int)Keys.RMenu)
{
bAltGr = 0;
}
}
return CallNextHookEx(_hookID, nCode, wParam, ref lParamRef);
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook,
LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
//1IntPtr wParam, IntPtr lParam);
IntPtr wParam, ref KBDLLHOOKSTRUCT lParamRef);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
}
public class HookItem
{
public int nCode;
public int wParam;
public int lParam;
public HookItem(int _nCode, int _wParam, int _lParam)
{
nCode = _nCode;
wParam = _wParam;
lParam = _lParam;
}
}
} | 32.570201 | 152 | 0.490631 | [
"MIT"
] | fourDotsSoftware/ColorPicker | ColorPicker/InterceptKeys.cs | 11,369 | C# |
using System;
using System.Windows;
using System.Windows.Controls;
using DevZest.Windows.Docking;
namespace DevZest.DockSample
{
/// <summary>
/// Interaction logic for PropertiesWindow.xaml
/// </summary>
partial class PropertiesWindow
{
public PropertiesWindow()
{
InitializeComponent();
}
}
}
| 18.842105 | 51 | 0.639665 | [
"MIT"
] | DevZest/WpfDocking | Samples/Docking/CSharp/DockSample/PropertiesWindow.xaml.cs | 360 | 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.Azure.Media.Outputs
{
[OutputType]
public sealed class AssetFilterTrackSelection
{
/// <summary>
/// One or more `condition` blocks as defined above.
/// </summary>
public readonly ImmutableArray<Outputs.AssetFilterTrackSelectionCondition> Conditions;
[OutputConstructor]
private AssetFilterTrackSelection(ImmutableArray<Outputs.AssetFilterTrackSelectionCondition> conditions)
{
Conditions = conditions;
}
}
}
| 29.857143 | 112 | 0.700957 | [
"ECL-2.0",
"Apache-2.0"
] | ScriptBox99/pulumi-azure | sdk/dotnet/Media/Outputs/AssetFilterTrackSelection.cs | 836 | C# |
/*
MIT License
Copyright (c) 2019 Digital Ruby, LLC - https://www.digitalruby.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace DigitalRuby.IPBanCore
{
/// <summary>
/// Responsible for managing and parsing log files for failed and successful logins
/// </summary>
public class IPBanLogFileManager : IUpdater
{
private readonly IIPBanService service;
private readonly HashSet<IPBanLogFileScanner> logFilesToParse = new HashSet<IPBanLogFileScanner>();
/// <summary>
/// Log files to parse
/// </summary>
public IReadOnlyCollection<LogFileScanner> LogFilesToParse { get { return logFilesToParse; } }
public IPBanLogFileManager(IIPBanService service)
{
this.service = service;
service.ConfigChanged += UpdateLogFiles;
}
/// <inheritdoc />
public Task Update(CancellationToken cancelToken)
{
UpdateLogFiles(service.Config);
if (service.ManualCycle)
{
foreach (IPBanLogFileScanner scanner in logFilesToParse)
{
scanner.ProcessFiles();
}
}
return Task.CompletedTask;
}
/// <inheritdoc />
public void Dispose()
{
service.ConfigChanged -= UpdateLogFiles;
foreach (LogFileScanner file in logFilesToParse)
{
file.Dispose();
}
}
private void UpdateLogFiles(IPBanConfig newConfig)
{
// remove existing log files that are no longer in config
foreach (IPBanLogFileScanner file in logFilesToParse.ToArray())
{
if (newConfig.LogFilesToParse.FirstOrDefault(f => f.PathsAndMasks.Contains(file.PathAndMask)) is null)
{
file.Dispose();
logFilesToParse.Remove(file);
}
}
foreach (IPBanLogFileToParse newFile in newConfig.LogFilesToParse)
{
string[] pathsAndMasks = newFile.PathAndMask.Split('\n');
for (int i = 0; i < pathsAndMasks.Length; i++)
{
string pathAndMask = pathsAndMasks[i].Trim();
if (pathAndMask.Length != 0)
{
// if we don't have this log file and the platform matches, add it
bool noMatchingLogFile = logFilesToParse.FirstOrDefault(f => f.PathAndMask == pathAndMask) is null;
bool platformMatches = !string.IsNullOrWhiteSpace(newFile.PlatformRegex) &&
Regex.IsMatch(OSUtility.Instance.Description, newFile.PlatformRegex.ToString().Trim(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
if (noMatchingLogFile && platformMatches)
{
// log files use a timer internally and do not need to be updated regularly
IPBanIPAddressLogFileScannerOptions options = new IPBanIPAddressLogFileScannerOptions
{
Dns = service.DnsLookup,
LoginHandler = service,
MaxFileSizeBytes = newFile.MaxFileSize,
PathAndMask = pathAndMask,
PingIntervalMilliseconds = (service.ManualCycle ? 0 : newFile.PingInterval),
RegexFailure = newFile.FailedLoginRegex,
RegexSuccess = newFile.SuccessfulLoginRegex,
RegexFailureTimestampFormat = newFile.FailedLoginRegexTimestampFormat,
RegexSuccessTimestampFormat = newFile.SuccessfulLoginRegexTimestampFormat,
Source = newFile.Source
};
IPBanLogFileScanner scanner = new IPBanLogFileScanner(options);
logFilesToParse.Add(scanner);
Logger.Info("Adding log file to parse: {0}", pathAndMask);
}
else
{
Logger.Debug("Ignoring log file path {0}, regex: {1}, no matching file: {2}, platform match: {3}",
pathAndMask, newFile.PlatformRegex, noMatchingLogFile, platformMatches);
}
}
}
}
}
}
}
| 44.037879 | 172 | 0.583004 | [
"MIT"
] | bluPhy/IPBan | IPBanCore/Core/IPBan/IPBanLogFileManager.cs | 5,815 | C# |
namespace ICSharpCode.SharpZipLib.Core
{
/// <summary>
/// INameTransform defines how file system names are transformed for use with archives, or vice versa.
/// </summary>
public interface INameTransform
{
/// <summary>
/// Given a file name determine the transformed value.
/// </summary>
/// <param name="name">The name to transform.</param>
/// <returns>The transformed file name.</returns>
string TransformFile(string name);
/// <summary>
/// Given a directory name determine the transformed value.
/// </summary>
/// <param name="name">The name to transform.</param>
/// <returns>The transformed directory name</returns>
string TransformDirectory(string name);
}
}
| 30.521739 | 103 | 0.696581 | [
"MIT"
] | 0patch/SharpZipLib | src/ICSharpCode.SharpZipLib/Core/INameTransform.cs | 702 | C# |
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using LamarCodeGeneration;
using LamarCompiler;
using Marten.Internal.Storage;
using Weasel.Postgresql;
using Marten.Schema;
using Marten.Schema.Arguments;
using Marten.Schema.BulkLoading;
using Marten.Util;
using Npgsql;
using CommandExtensions = Weasel.Postgresql.CommandExtensions;
namespace Marten.Internal.CodeGeneration
{
public class DocumentPersistenceBuilder
{
private readonly DocumentMapping _mapping;
private readonly StoreOptions _options;
public DocumentPersistenceBuilder(DocumentMapping mapping, StoreOptions options)
{
_mapping = mapping;
_options = options;
}
public void AssemblyTypes(GeneratedAssembly assembly)
{
var operations = new DocumentOperations(assembly, _mapping, _options);
assembly.Namespaces.Add(typeof(CommandExtensions).Namespace);
assembly.Namespaces.Add(typeof(TenantIdArgument).Namespace);
assembly.Namespaces.Add(typeof(NpgsqlCommand).Namespace);
assembly.Namespaces.Add(typeof(Weasel.Core.CommandExtensions).Namespace);
new DocumentStorageBuilder(_mapping, StorageStyle.QueryOnly, x => x.QueryOnlySelector)
.Build(assembly, operations);
new DocumentStorageBuilder(_mapping, StorageStyle.Lightweight, x => x.LightweightSelector)
.Build(assembly, operations);
new DocumentStorageBuilder(_mapping, StorageStyle.IdentityMap, x => x.IdentityMapSelector)
.Build(assembly, operations);
new DocumentStorageBuilder(_mapping, StorageStyle.DirtyTracking, x => x.DirtyCheckingSelector)
.Build(assembly, operations);
new BulkLoaderBuilder(_mapping).BuildType(assembly);
}
public static DocumentProvider<T> FromPreBuiltTypes<T>(Assembly assembly, DocumentMapping mapping)
{
var queryOnly = assembly.ExportedTypes.FirstOrDefault(x =>
x.Name == DocumentStorageBuilder.DeriveTypeName(mapping, StorageStyle.QueryOnly));
var lightweight = assembly.ExportedTypes.FirstOrDefault(x =>
x.Name == DocumentStorageBuilder.DeriveTypeName(mapping, StorageStyle.Lightweight));
var identityMap = assembly.ExportedTypes.FirstOrDefault(x =>
x.Name == DocumentStorageBuilder.DeriveTypeName(mapping, StorageStyle.IdentityMap));
var dirtyTracking = assembly.ExportedTypes.FirstOrDefault(x =>
x.Name == DocumentStorageBuilder.DeriveTypeName(mapping, StorageStyle.DirtyTracking));
var bulkWriterType =
assembly.ExportedTypes.FirstOrDefault(x => x.Name == new BulkLoaderBuilder(mapping).TypeName);
var slot = new DocumentProvider<T>
{
QueryOnly = (IDocumentStorage<T>)Activator.CreateInstance(queryOnly, mapping),
Lightweight = (IDocumentStorage<T>)Activator.CreateInstance(lightweight, mapping),
IdentityMap = (IDocumentStorage<T>)Activator.CreateInstance(identityMap, mapping),
DirtyTracking = (IDocumentStorage<T>)Activator.CreateInstance(dirtyTracking, mapping),
};
slot.BulkLoader = mapping.IsHierarchy()
? (IBulkLoader<T>)Activator.CreateInstance(bulkWriterType, slot.QueryOnly, mapping)
: (IBulkLoader<T>)Activator.CreateInstance(bulkWriterType, slot.QueryOnly);
return slot;
}
public DocumentProvider<T> Generate<T>()
{
var assembly = new GeneratedAssembly(new GenerationRules(SchemaConstants.MartenGeneratedNamespace));
var operations = new DocumentOperations(assembly, _mapping, _options);
assembly.Namespaces.Add(typeof(CommandExtensions).Namespace);
assembly.Namespaces.Add(typeof(Weasel.Core.CommandExtensions).Namespace);
assembly.Namespaces.Add(typeof(TenantIdArgument).Namespace);
assembly.Namespaces.Add(typeof(NpgsqlCommand).Namespace);
var queryOnly = new DocumentStorageBuilder(_mapping, StorageStyle.QueryOnly, x => x.QueryOnlySelector)
.Build(assembly, operations);
var lightweight = new DocumentStorageBuilder(_mapping, StorageStyle.Lightweight, x => x.LightweightSelector)
.Build(assembly, operations);
var identityMap = new DocumentStorageBuilder(_mapping, StorageStyle.IdentityMap, x => x.IdentityMapSelector)
.Build(assembly, operations);
var dirtyTracking = new DocumentStorageBuilder(_mapping, StorageStyle.DirtyTracking, x => x.DirtyCheckingSelector)
.Build(assembly, operations);
var bulkWriterType = new BulkLoaderBuilder(_mapping).BuildType(assembly);
var compiler = new AssemblyGenerator();
var types = new[]
{
typeof(IDocumentStorage<>),
typeof(T),
};
foreach (var referencedAssembly in WalkReferencedAssemblies.ForTypes(types))
{
compiler.ReferenceAssembly(referencedAssembly);
}
try
{
compiler.Compile(assembly);
}
catch (Exception e)
{
if (e.Message.Contains("is inaccessible due to its protection level"))
{
throw new InvalidOperationException($"Requested document type '{_mapping.DocumentType.FullNameInCode()}' must be either scoped as 'public' or the assembly holding it must use the {nameof(InternalsVisibleToAttribute)} pointing to 'Marten.Generated'", e);
}
throw;
}
var slot = new DocumentProvider<T>
{
QueryOnly = (IDocumentStorage<T>)Activator.CreateInstance(queryOnly.CompiledType, _mapping),
Lightweight = (IDocumentStorage<T>)Activator.CreateInstance(lightweight.CompiledType, _mapping),
IdentityMap = (IDocumentStorage<T>)Activator.CreateInstance(identityMap.CompiledType, _mapping),
DirtyTracking = (IDocumentStorage<T>)Activator.CreateInstance(dirtyTracking.CompiledType, _mapping),
Operations = operations,
QueryOnlyType = queryOnly,
LightweightType = lightweight,
IdentityMapType = identityMap,
DirtyTrackingType = dirtyTracking
};
slot.BulkLoader = _mapping.IsHierarchy()
? (IBulkLoader<T>)Activator.CreateInstance(bulkWriterType.CompiledType, slot.QueryOnly, _mapping)
: (IBulkLoader<T>)Activator.CreateInstance(bulkWriterType.CompiledType, slot.QueryOnly);
slot.BulkLoaderType = bulkWriterType;
return slot;
}
}
}
| 42.345455 | 273 | 0.656648 | [
"MIT"
] | DJBMASTER/marten | src/Marten/Internal/CodeGeneration/DocumentPersistenceBuilder.cs | 6,987 | 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.
//#define DUMP_STATS
using System;
using Microsoft.ML.Runtime;
namespace Microsoft.ML.Internal.Utilities
{
// REVIEW: May want to add an IEnumerable<KeyValuePair<int, TItem>>.
using Conditional = System.Diagnostics.ConditionalAttribute;
/// <summary>
/// A Hash Array that implements both val -> index lookup and index -> val lookup.
/// Also implements memory efficient sorting.
/// Note: Supports adding and looking up of items but does not support removal of items.
/// </summary>
[BestFriend]
internal sealed class HashArray<TItem>
// REVIEW: May want to not consider not making TItem have to be IComparable but instead
// could support user specified sort order.
where TItem : IEquatable<TItem>, IComparable<TItem>
{
private int[] _rgit; // Buckets of prime size.
// Utilizing this struct gives better cache behavior than using parallel arrays. Note that this is a
// mutable struct so the fields can be assigned individually.
private struct Entry : IComparable<Entry>
{
public int ItNext;
public TItem Value;
// This is needed for sorting. It only uses Value.
public int CompareTo(Entry other)
{
return Value.CompareTo(other.Value);
}
}
// Count of TItems stored.
private int _ct;
private Entry[] _entries;
public int Count { get { return _ct; } }
public HashArray()
{
_rgit = new int[HashHelpers.Primes[0]];
for (int i = 0; i < _rgit.Length; i++)
_rgit[i] = -1;
AssertValid();
}
[Conditional("DEBUG")]
private void AssertValid()
{
Contracts.AssertValue(_rgit);
Contracts.AssertNonEmpty(_rgit);
Contracts.Assert(0 <= _ct & _ct <= Utils.Size(_entries));
// The number of buckets should be at least the number of items, unless we're reached the
// biggest number of buckets allowed.
Contracts.Assert(Utils.Size(_rgit) >= _ct || Utils.Size(_rgit) == HashHelpers.MaxPrimeArrayLength);
}
private int GetIit(int hash)
{
return (int)((uint)hash % _rgit.Length);
}
public TItem GetItem(int it)
{
Contracts.Assert(0 <= it && it < _ct);
return _entries[it].Value;
}
/// <summary>
/// Find the index of the given val in the hash array.
/// Returns a bool representing if val is present.
/// Index outputs the index that the val is at in the array, -1 otherwise.
/// </summary>
public bool TryGetIndex(TItem val, out int index)
{
AssertValid();
Contracts.Assert(val != null);
index = GetIndexCore(val, GetIit(val.GetHashCode()));
return index >= 0;
}
// Return the index of value, -1 if it is not present.
private int GetIndexCore(TItem val, int iit)
{
Contracts.Assert(0 <= iit && iit < _rgit.Length);
int it = _rgit[iit];
while (it >= 0)
{
Contracts.Assert(it < _ct);
if (_entries[it].Value.Equals(val))
return it;
// Get the next item in the bucket.
it = _entries[it].ItNext;
}
Contracts.Assert(it == -1);
return -1;
}
/// <summary>
/// Make sure the given value has an equivalent TItem in the hashArray
/// and return the index of the value.
/// </summary>
public int Add(TItem val)
{
int iit = GetIit(val.GetHashCode());
int index = GetIndexCore(val, iit);
if (index >= 0)
return index;
return AddCore(val, iit);
}
/// <summary>
/// Make sure the given value has an equivalent TItem in the hashArray
/// and return the index of the value.
/// </summary>
public bool TryAdd(TItem val)
{
int iit = GetIit(val.GetHashCode());
int index = GetIndexCore(val, iit);
if (index >= 0)
return false;
AddCore(val, iit);
return true;
}
/// <summary>
/// Adds the value as a TItem. Does not check whether the TItem is already present.
/// Returns the index of the added value.
/// </summary>
private int AddCore(TItem val, int iit)
{
AssertValid();
Contracts.Assert(val != null);
Contracts.Assert(0 <= iit && iit < _rgit.Length);
if (_ct >= Utils.Size(_entries))
{
Contracts.Assert(_ct == Utils.Size(_entries));
Utils.EnsureSize(ref _entries, _ct + 1);
}
Contracts.Assert(_ct < _entries.Length);
_entries[_ct].Value = val;
_entries[_ct].ItNext = _rgit[iit];
_rgit[iit] = _ct;
if (++_ct >= _rgit.Length)
GrowTable();
AssertValid();
// Return the index of the added value.
return _ct - 1;
}
private void GrowTable()
{
AssertValid();
int size = HashHelpers.ExpandPrime(_ct);
Contracts.Assert(size >= _rgit.Length);
if (size <= _rgit.Length)
return;
// Populate new buckets.
DumpStats();
_rgit = new int[size];
FillTable();
DumpStats();
AssertValid();
}
public void Sort()
{
AssertValid();
// Sort _rgt, keeping _rghash in parallel.
Array.Sort(_entries, 0, _ct);
// Reconstruct _rgit from now sorted _rgt and _rghash.
FillTable();
AssertValid();
}
/// <summary>
/// Appropriately fills _rgnext and _rgit based on _rgt and _rghash.
/// </summary>
private void FillTable()
{
for (int i = 0; i < _rgit.Length; i++)
_rgit[i] = -1;
for (int it = 0; it < _ct; it++)
{
int iit = GetIit(_entries[it].Value.GetHashCode());
_entries[it].ItNext = _rgit[iit];
_rgit[iit] = it;
}
}
[Conditional("DUMP_STATS")]
private void DumpStats()
{
int c = 0;
for (int i = 0; i < _rgit.Length; i++)
{
if (_rgit[i] >= 0)
c++;
}
Console.WriteLine("Table: {0} out of {1}", c, _rgit.Length);
}
/// <summary>
/// Copies all items to the passed in span. Requires the passed in span to be at least the
/// same length as Count.
/// </summary>
public void CopyTo(Span<TItem> destination)
{
Contracts.Check(destination.Length >= _ct);
for (int i = 0; i < _ct; i++)
destination[i] = _entries[i].Value;
}
private static class HashHelpers
{
// Note: This HashHelpers class was adapted from the BCL code base.
// This is the maximum prime smaller than Array.MaxArrayLength
public const int MaxPrimeArrayLength = 0x7FEFFFFD;
// Table of prime numbers to use as hash table sizes.
// Each subsequent prime ensures that the table will at least double in size upon each growth
// in order to improve the efficiency of the hash table.
public static readonly int[] Primes =
{
3, 7, 17, 37, 79, 163, 331, 673, 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899,
701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557, 359339171,
718678369, 1437356741, 2146435069,
};
public static int GetPrime(int min)
{
Contracts.Assert(0 <= min && min < MaxPrimeArrayLength);
for (int i = 0; i < Primes.Length; i++)
{
int prime = Primes[i];
if (prime >= min)
return prime;
}
Contracts.Assert(false);
return min + 1;
}
// Returns size of hashtable to grow to.
public static int ExpandPrime(int oldSize)
{
int newSize = 2 * oldSize;
// Allow the hashtables to grow to maximum possible size (~2G elements) before encoutering capacity overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast .
if ((uint)newSize >= MaxPrimeArrayLength)
return MaxPrimeArrayLength;
return GetPrime(newSize);
}
}
}
} | 32.359862 | 125 | 0.521279 | [
"MIT"
] | AhmedsafwatEwida/machinelearning | src/Microsoft.ML.Core/Utilities/HashArray.cs | 9,352 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _11.Convert_Speed_Units
{
class Program
{
static void Main(string[] args)
{
uint meters = UInt32.Parse(Console.ReadLine());
byte hours = byte.Parse(Console.ReadLine());
byte minutes = byte.Parse(Console.ReadLine());
byte seconds = byte.Parse(Console.ReadLine());
ushort time = (ushort)(hours * 3600 + minutes * 60 + seconds);
float metersPerSec = (float)meters / time;
float kilometersPerHour = ((float)meters / 1000) / ((float)time / 3600);
float milesPerHour = ((float)meters / 1609) / ((float)time / 3600);
Console.WriteLine("{0:0.#######}", metersPerSec);
Console.WriteLine("{0:0.#######}", kilometersPerHour);
Console.WriteLine("{0:0.#######}", milesPerHour);
}
}
}
| 31.322581 | 84 | 0.580844 | [
"MIT"
] | RubenYordano/Programming-Fundamentals-May-2017-HomeWorks | 02.DATA TYPES AND VARIABLES - EXERCISES/11. Convert Speed Units/Program.cs | 973 | C# |
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Security.Cryptography.X509Certificates;
using Symbol.Builders;
using Symnity.Model.Mosaics;
namespace Symnity.Model.Accounts
{
[Serializable]
public class MultisigAccountInfo
{
/**
* Version
*/
public int version;
/**
* The account multisig address.
*/
public Address accountAddress;
/**
* The number of signatures needed to approve a transaction.
*/
public int minApproval;
/**
* The number of signatures needed to remove a cosignatory.
*/
public int minRemoval;
/**
* The multisig account cosignatories.
*/
public List<Address> cosignatoryAddresses;
/**
* The multisig accounts this account is cosigner of.
*/
public List<Address> multisigAddresses;
public MultisigAccountInfo(
int version,
Address accountAddress,
int minApproval,
int minRemoval,
List<Address> cosignatoryAddresses,
List<Address> multisigAddresses
)
{
this.version = version;
this.accountAddress = accountAddress;
this.minApproval = minApproval;
this.minRemoval = minRemoval;
this.cosignatoryAddresses = cosignatoryAddresses;
this.multisigAddresses = multisigAddresses;
}
/**
* Checks if the account is a multisig account.
* @returns {boolean}
*/
public bool IsMultisig() {
return minRemoval != 0 && minApproval != 0;
}
/**
* Checks if an account is cosignatory of the multisig account.
* @param address
* @returns {boolean}
*/
public bool HasCosigner(Address address) {
return cosignatoryAddresses.Find(cosigner => cosigner.Equals(address)) != null;
}
/**
* Checks if the multisig account is cosignatory of an account.
* @param address
* @returns {boolean}
*/
public bool IsCosignerOfMultisigAccount(Address address) {
return multisigAddresses.Find(multisig => multisig.Equals(address)) != null;
}
}
} | 27.848837 | 91 | 0.566597 | [
"MIT"
] | 0x070696E65/Symnity | Assets/Plugins/Symnity/src/Model/Accounts/MultisigAccountInfo.cs | 2,395 | C# |
using System.Reflection;
using JiraIntegrationTool.NativeHost.Requests;
using JiraIntegrationTool.NativeHost.Responses;
using JiraIntegrationTool.NativeHost.Utils;
namespace JiraIntegrationTool.NativeHost.Services
{
public class NativeHostService
{
public PingResponse Ping(PingRequest _)
{
return new PingResponse()
{
ReceiverName = Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyTitleAttribute>().Title,
ReceiverVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString()
};
}
public CheckoutBranchResponse CheckoutBranch(CheckoutBranchRequest checkoutBranchRequest)
{
var r = checkoutBranchRequest;
var args = $"checkoutBranch {r.DefaultRepositoryPath} {r.BranchId} {r.IssueId}";
ShellHelper.RunCommandInShellWindow($"./actions.sh {args}");
return new CheckoutBranchResponse();
}
}
}
| 35.321429 | 114 | 0.678463 | [
"MIT"
] | gpa/JiraIntegrationTool | JiraIntegrationTool.NativeHost/Services/NativeHostService.cs | 991 | C# |
using System.Resources;
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("Blob Inserter")]
[assembly: AssemblyDescription("Development utility for inserting blobs into SQL.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Blob Inserter")]
[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("830156c4-b86d-4d32-aeac-1ede206306f3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: NeutralResourcesLanguage("en")]
| 37.9 | 84 | 0.75 | [
"MIT"
] | cxminer/SQL-Blob-Inserter | BlobInserter/Properties/AssemblyInfo.cs | 1,519 | C# |
namespace LoRSideTracker
{
partial class GameLogControl
{
/// <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 Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.GameLogDisplay = new System.Windows.Forms.Panel();
this.SuspendLayout();
//
// GameLogDisplay
//
this.GameLogDisplay.Location = new System.Drawing.Point(0, 0);
this.GameLogDisplay.Name = "GameLogDisplay";
this.GameLogDisplay.Size = new System.Drawing.Size(574, 100);
this.GameLogDisplay.TabIndex = 0;
this.GameLogDisplay.Paint += new System.Windows.Forms.PaintEventHandler(this.GameLogDisplay_Paint);
this.GameLogDisplay.DoubleClick += new System.EventHandler(this.GameLogDisplay_Click);
this.GameLogDisplay.MouseLeave += new System.EventHandler(this.GameLogDisplay_MouseLeave);
this.GameLogDisplay.MouseMove += new System.Windows.Forms.MouseEventHandler(this.GameLogDisplay_MouseMove);
//
// GameLogControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoScroll = true;
this.Controls.Add(this.GameLogDisplay);
this.Name = "GameLogControl";
this.Size = new System.Drawing.Size(574, 249);
this.Load += new System.EventHandler(this.GameLogControl_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel GameLogDisplay;
}
}
| 38 | 119 | 0.598997 | [
"MIT"
] | ronbos/LoRSideTracker | LoRSideTracker/Controls/GameLogControl.Designer.cs | 2,396 | C# |
using ESFA.DC.ILR.Model.Interface;
namespace ESFA.DC.ILR.ValidationService.Rules.Derived.Interface
{
/// <summary>
/// derived data rule 28
/// Adult skills funded learner unemployed with benefits on learning aim start date
/// </summary>
public interface IDerivedData_28Rule
{
/// <summary>
/// Determines whether [is adult skills unemployed with benefits] [the specified candidate].
/// </summary>
/// <param name="candidate">The candidate.</param>
/// <returns>
/// <c>true</c> if [is adult skills unemployed with benefits] [the specified candidate]; otherwise, <c>false</c>.
/// </returns>
bool IsAdultFundedUnemployedWithBenefits(ILearner candidate);
}
}
| 36 | 123 | 0.646825 | [
"MIT"
] | sampanu/DC-ILR-1819-ValidationService | src/ESFA.DC.ILR.ValidationService.Rules/Derived/Interface/IDerivedData_28Rule.cs | 758 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Utilities;
#nullable enable
namespace Microsoft.EntityFrameworkCore.Metadata.Internal
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class RelationalModel : Annotatable, IRelationalModel
{
private bool _isReadOnly;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public RelationalModel([NotNull] IModel model)
{
Model = model;
}
/// <inheritdoc />
public virtual IModel Model { get; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override bool IsReadOnly => _isReadOnly;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual SortedDictionary<string, TableBase> DefaultTables { get; }
= new();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual SortedDictionary<(string, string?), Table> Tables { get; }
= new();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual SortedDictionary<(string, string?), View> Views { get; }
= new();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual SortedDictionary<string, SqlQuery> Queries { get; }
= new();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual SortedDictionary<(string, string?, IReadOnlyList<string>), StoreFunction> Functions { get; }
= new(NamedListComparer.Instance);
/// <inheritdoc />
public virtual ITable? FindTable(string name, string? schema)
=> Tables.TryGetValue((name, schema), out var table)
? table
: null;
/// <inheritdoc />
public virtual IView? FindView(string name, string? schema)
=> Views.TryGetValue((name, schema), out var view)
? view
: null;
/// <inheritdoc />
public virtual ISqlQuery? FindQuery(string name)
=> Queries.TryGetValue(name, out var query)
? query
: null;
/// <inheritdoc />
public virtual IStoreFunction? FindFunction(string name, string? schema, IReadOnlyList<string> parameters)
=> Functions.TryGetValue((name, schema, parameters), out var function)
? function
: null;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static IModel Add(
[NotNull] IModel model,
[CanBeNull] IRelationalAnnotationProvider? relationalAnnotationProvider)
{
var databaseModel = new RelationalModel(model);
foreach (var entityType in model.GetEntityTypes())
{
AddDefaultMappings(databaseModel, entityType);
AddTables(databaseModel, entityType);
AddViews(databaseModel, entityType);
AddSqlQueries(databaseModel, entityType);
AddMappedFunctions(databaseModel, entityType);
}
AddTVFs(databaseModel);
foreach (var table in databaseModel.Tables.Values)
{
PopulateRowInternalForeignKeys(table);
PopulateConstraints(table);
if (relationalAnnotationProvider != null)
{
foreach (Column column in table.Columns.Values)
{
column.AddAnnotations(relationalAnnotationProvider.For(column));
}
foreach (var constraint in table.UniqueConstraints.Values)
{
constraint.AddAnnotations(relationalAnnotationProvider.For(constraint));
}
foreach (var index in table.Indexes.Values)
{
index.AddAnnotations(relationalAnnotationProvider.For(index));
}
foreach (var constraint in table.ForeignKeyConstraints.Values)
{
constraint.AddAnnotations(relationalAnnotationProvider.For(constraint));
}
foreach (CheckConstraint checkConstraint in ((ITable)table).CheckConstraints)
{
checkConstraint.AddAnnotations(relationalAnnotationProvider.For(checkConstraint));
}
table.AddAnnotations(relationalAnnotationProvider.For(table));
}
}
foreach (var view in databaseModel.Views.Values)
{
PopulateRowInternalForeignKeys(view);
if (relationalAnnotationProvider != null)
{
foreach (ViewColumn viewColumn in view.Columns.Values)
{
viewColumn.AddAnnotations(relationalAnnotationProvider.For(viewColumn));
}
view.AddAnnotations(relationalAnnotationProvider.For(view));
}
}
foreach (var query in databaseModel.Queries.Values)
{
if (relationalAnnotationProvider != null)
{
foreach (SqlQueryColumn queryColumn in query.Columns.Values)
{
queryColumn.AddAnnotations(relationalAnnotationProvider.For(queryColumn));
}
query.AddAnnotations(relationalAnnotationProvider.For(query));
}
}
foreach (var function in databaseModel.Functions.Values)
{
if (relationalAnnotationProvider != null)
{
foreach (FunctionColumn functionColumn in function.Columns.Values)
{
functionColumn.AddAnnotations(relationalAnnotationProvider.For(functionColumn));
}
function.AddAnnotations(relationalAnnotationProvider.For(function));
}
}
if (relationalAnnotationProvider != null)
{
foreach (Sequence sequence in ((IRelationalModel)databaseModel).Sequences)
{
sequence.AddAnnotations(relationalAnnotationProvider.For(sequence));
}
databaseModel.AddAnnotations(relationalAnnotationProvider.For(databaseModel));
}
databaseModel._isReadOnly = true;
model.AddRuntimeAnnotation(RelationalAnnotationNames.RelationalModel, databaseModel);
return model;
}
private static void AddDefaultMappings(RelationalModel databaseModel, IEntityType entityType)
{
var rootType = entityType.GetRootType();
var name = rootType.HasSharedClrType ? rootType.Name : rootType.ShortName();
if (!databaseModel.DefaultTables.TryGetValue(name, out var defaultTable))
{
defaultTable = new TableBase(name, null, databaseModel);
databaseModel.DefaultTables.Add(name, defaultTable);
}
var tableMapping = new TableMappingBase(entityType, defaultTable, includesDerivedTypes: true)
{
IsSharedTablePrincipal = true,
IsSplitEntityTypePrincipal = true
};
foreach (var property in entityType.GetProperties())
{
var columnName = property.GetColumnBaseName();
if (columnName == null)
{
continue;
}
var column = (ColumnBase?)defaultTable.FindColumn(columnName);
if (column == null)
{
column = new(columnName, property.GetColumnType(), defaultTable);
column.IsNullable = property.IsColumnNullable();
defaultTable.Columns.Add(columnName, column);
}
else if (!property.IsColumnNullable())
{
column.IsNullable = false;
}
var columnMapping = new ColumnMappingBase(property, column, tableMapping);
tableMapping.ColumnMappings.Add(columnMapping);
column.PropertyMappings.Add(columnMapping);
if (property.FindRuntimeAnnotationValue(RelationalAnnotationNames.DefaultColumnMappings)
is not SortedSet<ColumnMappingBase> columnMappings)
{
columnMappings = new SortedSet<ColumnMappingBase>(ColumnMappingBaseComparer.Instance);
property.AddRuntimeAnnotation(RelationalAnnotationNames.DefaultColumnMappings, columnMappings);
}
columnMappings.Add(columnMapping);
}
if (entityType.FindRuntimeAnnotationValue(RelationalAnnotationNames.DefaultMappings)
is not List<TableMappingBase> tableMappings)
{
tableMappings = new List<TableMappingBase>();
entityType.AddRuntimeAnnotation(RelationalAnnotationNames.DefaultMappings, tableMappings);
}
if (tableMapping.ColumnMappings.Count != 0
|| tableMappings.Count == 0)
{
tableMappings.Add(tableMapping);
defaultTable.EntityTypeMappings.Add(tableMapping);
}
tableMappings.Reverse();
}
private static void AddTables(RelationalModel databaseModel, IEntityType entityType)
{
var tableName = entityType.GetTableName();
if (tableName != null)
{
var schema = entityType.GetSchema();
var mappedType = entityType;
List<TableMapping>? tableMappings = null;
while (mappedType != null)
{
var mappedTableName = mappedType.GetTableName();
var mappedSchema = mappedType.GetSchema();
if (mappedTableName == null
|| (mappedTableName == tableName
&& mappedSchema == schema
&& mappedType != entityType))
{
break;
}
var mappedTable = StoreObjectIdentifier.Table(mappedTableName, mappedSchema);
if (!databaseModel.Tables.TryGetValue((mappedTableName, mappedSchema), out var table))
{
table = new Table(mappedTableName, mappedSchema, databaseModel);
databaseModel.Tables.Add((mappedTableName, mappedSchema), table);
}
if (mappedType == entityType)
{
Check.DebugAssert(
table.EntityTypeMappings.Count == 0
|| table.IsExcludedFromMigrations == entityType.IsTableExcludedFromMigrations(),
"Table should be excluded on all entity types");
table.IsExcludedFromMigrations = entityType.IsTableExcludedFromMigrations();
}
var tableMapping = new TableMapping(entityType, table, includesDerivedTypes: mappedType == entityType)
{
IsSplitEntityTypePrincipal = true
};
foreach (var property in mappedType.GetProperties())
{
var columnName = property.GetColumnName(mappedTable);
if (columnName == null)
{
continue;
}
var column = (Column?)table.FindColumn(columnName);
if (column == null)
{
column = new(columnName, property.GetColumnType(mappedTable), table);
column.IsNullable = property.IsColumnNullable(mappedTable);
table.Columns.Add(columnName, column);
}
else if (!property.IsColumnNullable(mappedTable))
{
column.IsNullable = false;
}
var columnMapping = new ColumnMapping(property, column, tableMapping);
tableMapping.ColumnMappings.Add(columnMapping);
column.PropertyMappings.Add(columnMapping);
if (property.FindRuntimeAnnotationValue(RelationalAnnotationNames.TableColumnMappings)
is not SortedSet<ColumnMapping> columnMappings)
{
columnMappings = new SortedSet<ColumnMapping>(ColumnMappingBaseComparer.Instance);
property.AddRuntimeAnnotation(RelationalAnnotationNames.TableColumnMappings, columnMappings);
}
columnMappings.Add(columnMapping);
}
mappedType = mappedType.BaseType;
tableMappings = entityType.FindRuntimeAnnotationValue(RelationalAnnotationNames.TableMappings)
as List<TableMapping>;
if (tableMappings == null)
{
tableMappings = new List<TableMapping>();
entityType.AddRuntimeAnnotation(RelationalAnnotationNames.TableMappings, tableMappings);
}
if (tableMapping.ColumnMappings.Count != 0
|| tableMappings.Count == 0)
{
tableMappings.Add(tableMapping);
table.EntityTypeMappings.Add(tableMapping);
}
}
tableMappings?.Reverse();
}
}
private static void AddViews(RelationalModel databaseModel, IEntityType entityType)
{
var viewName = entityType.GetViewName();
if (viewName == null)
{
return;
}
var schema = entityType.GetViewSchema();
List<ViewMapping>? viewMappings = null;
var mappedType = entityType;
while (mappedType != null)
{
var mappedViewName = mappedType.GetViewName();
var mappedSchema = mappedType.GetViewSchema();
if (mappedViewName == null
|| (mappedViewName == viewName
&& mappedSchema == schema
&& mappedType != entityType))
{
break;
}
if (!databaseModel.Views.TryGetValue((mappedViewName, mappedSchema), out var view))
{
view = new View(mappedViewName, mappedSchema, databaseModel);
databaseModel.Views.Add((mappedViewName, mappedSchema), view);
}
var mappedView = StoreObjectIdentifier.View(mappedViewName, mappedSchema);
var viewMapping = new ViewMapping(entityType, view, includesDerivedTypes: mappedType == entityType)
{
IsSplitEntityTypePrincipal = true
};
foreach (var property in mappedType.GetProperties())
{
var columnName = property.GetColumnName(mappedView);
if (columnName == null)
{
continue;
}
var column = (ViewColumn?)view.FindColumn(columnName);
if (column == null)
{
column = new(columnName, property.GetColumnType(mappedView), view);
column.IsNullable = property.IsColumnNullable(mappedView);
view.Columns.Add(columnName, column);
}
else if (!property.IsColumnNullable(mappedView))
{
column.IsNullable = false;
}
var columnMapping = new ViewColumnMapping(property, column, viewMapping);
viewMapping.ColumnMappings.Add(columnMapping);
column.PropertyMappings.Add(columnMapping);
if (property.FindRuntimeAnnotationValue(RelationalAnnotationNames.ViewColumnMappings)
is not SortedSet<ViewColumnMapping> columnMappings)
{
columnMappings = new SortedSet<ViewColumnMapping>(ColumnMappingBaseComparer.Instance);
property.AddRuntimeAnnotation(RelationalAnnotationNames.ViewColumnMappings, columnMappings);
}
columnMappings.Add(columnMapping);
}
mappedType = mappedType.BaseType;
viewMappings = entityType.FindRuntimeAnnotationValue(RelationalAnnotationNames.ViewMappings) as List<ViewMapping>;
if (viewMappings == null)
{
viewMappings = new List<ViewMapping>();
entityType.AddRuntimeAnnotation(RelationalAnnotationNames.ViewMappings, viewMappings);
}
if (viewMapping.ColumnMappings.Count != 0
|| viewMappings.Count == 0)
{
viewMappings.Add(viewMapping);
view.EntityTypeMappings.Add(viewMapping);
}
}
viewMappings?.Reverse();
}
private static void AddSqlQueries(RelationalModel databaseModel, IEntityType entityType)
{
var entityTypeSqlQuery = entityType.GetSqlQuery();
if (entityTypeSqlQuery == null)
{
return;
}
List<SqlQueryMapping>? queryMappings = null;
var definingType = entityType;
while (definingType != null)
{
var definingTypeSqlQuery = definingType.GetSqlQuery();
if (definingTypeSqlQuery == null
|| definingType.BaseType == null
|| (definingTypeSqlQuery == entityTypeSqlQuery
&& definingType != entityType))
{
break;
}
definingType = definingType.BaseType;
}
Check.DebugAssert(definingType is not null, $"Could not find defining type for {entityType}");
var mappedType = entityType;
while (mappedType != null)
{
var mappedTypeSqlQuery = mappedType.GetSqlQuery();
if (mappedTypeSqlQuery == null
|| (mappedTypeSqlQuery == entityTypeSqlQuery
&& mappedType != entityType))
{
break;
}
var mappedQuery = StoreObjectIdentifier.SqlQuery(definingType);
if (!databaseModel.Queries.TryGetValue(mappedQuery.Name, out var sqlQuery))
{
sqlQuery = new SqlQuery(mappedQuery.Name, databaseModel, mappedTypeSqlQuery);
databaseModel.Queries.Add(mappedQuery.Name, sqlQuery);
}
var queryMapping = new SqlQueryMapping(entityType, sqlQuery, includesDerivedTypes: true)
{
IsDefaultSqlQueryMapping = true,
IsSharedTablePrincipal = true,
IsSplitEntityTypePrincipal = true
};
foreach (var property in mappedType.GetProperties())
{
var columnName = property.GetColumnName(mappedQuery);
if (columnName == null)
{
continue;
}
var column = (SqlQueryColumn?)sqlQuery.FindColumn(columnName);
if (column == null)
{
column = new(columnName, property.GetColumnType(mappedQuery), sqlQuery);
column.IsNullable = property.IsColumnNullable(mappedQuery);
sqlQuery.Columns.Add(columnName, column);
}
else if (!property.IsColumnNullable(mappedQuery))
{
column.IsNullable = false;
}
var columnMapping = new SqlQueryColumnMapping(property, column, queryMapping);
queryMapping.ColumnMappings.Add(columnMapping);
column.PropertyMappings.Add(columnMapping);
if (property.FindRuntimeAnnotationValue(RelationalAnnotationNames.SqlQueryColumnMappings)
is not SortedSet<SqlQueryColumnMapping> columnMappings)
{
columnMappings = new SortedSet<SqlQueryColumnMapping>(ColumnMappingBaseComparer.Instance);
property.AddRuntimeAnnotation(RelationalAnnotationNames.SqlQueryColumnMappings, columnMappings);
}
columnMappings.Add(columnMapping);
}
mappedType = mappedType.BaseType;
queryMappings = entityType.FindRuntimeAnnotationValue(RelationalAnnotationNames.SqlQueryMappings) as List<SqlQueryMapping>;
if (queryMappings == null)
{
queryMappings = new List<SqlQueryMapping>();
entityType.AddRuntimeAnnotation(RelationalAnnotationNames.SqlQueryMappings, queryMappings);
}
if (queryMapping.ColumnMappings.Count != 0
|| queryMappings.Count == 0)
{
queryMappings.Add(queryMapping);
sqlQuery.EntityTypeMappings.Add(queryMapping);
}
}
queryMappings?.Reverse();
}
private static void AddMappedFunctions(RelationalModel databaseModel, IEntityType entityType)
{
var model = databaseModel.Model;
var functionName = entityType.GetFunctionName();
if (functionName == null)
{
return;
}
List<FunctionMapping>? functionMappings = null;
var mappedType = entityType;
while (mappedType != null)
{
var mappedFunctionName = mappedType.GetFunctionName();
if (mappedFunctionName == null
|| (mappedFunctionName == functionName
&& mappedType != entityType))
{
break;
}
var dbFunction = (DbFunction)model.FindDbFunction(mappedFunctionName)!;
var functionMapping = CreateFunctionMapping(entityType, mappedType, dbFunction, databaseModel, @default: true);
mappedType = mappedType.BaseType;
functionMappings = entityType.FindRuntimeAnnotationValue(RelationalAnnotationNames.FunctionMappings) as List<FunctionMapping>;
if (functionMappings == null)
{
functionMappings = new List<FunctionMapping>();
entityType.AddRuntimeAnnotation(RelationalAnnotationNames.FunctionMappings, functionMappings);
}
if (functionMapping.ColumnMappings.Count != 0
|| functionMappings.Count == 0)
{
functionMappings.Add(functionMapping);
((StoreFunction)functionMapping.StoreFunction).EntityTypeMappings.Add(functionMapping);
}
}
functionMappings?.Reverse();
}
private static void AddTVFs(RelationalModel relationalModel)
{
var model = relationalModel.Model;
foreach (DbFunction function in model.GetDbFunctions())
{
var entityType = function.IsScalar
? null
: model.FindEntityType(function.ReturnType.GetGenericArguments()[0]);
if (entityType == null)
{
GetOrCreateStoreFunction(function, relationalModel);
continue;
}
if (entityType.GetFunctionName() == function.ModelName)
{
continue;
}
var functionMapping = CreateFunctionMapping(entityType, entityType, function, relationalModel, @default: false);
if (entityType.FindRuntimeAnnotationValue(RelationalAnnotationNames.FunctionMappings)
is not List<FunctionMapping> functionMappings)
{
functionMappings = new List<FunctionMapping>();
entityType.AddRuntimeAnnotation(RelationalAnnotationNames.FunctionMappings, functionMappings);
}
functionMappings.Add(functionMapping);
((StoreFunction)functionMapping.StoreFunction).EntityTypeMappings.Add(functionMapping);
}
}
private static FunctionMapping CreateFunctionMapping(
IEntityType entityType,
IEntityType mappedType,
DbFunction dbFunction,
RelationalModel model,
bool @default)
{
var storeFunction = GetOrCreateStoreFunction(dbFunction, model);
var mappedFunction = StoreObjectIdentifier.DbFunction(dbFunction.Name);
var functionMapping = new FunctionMapping(entityType, storeFunction, dbFunction, includesDerivedTypes: true)
{
IsDefaultFunctionMapping = @default,
// See Issue #19970
IsSharedTablePrincipal = true,
IsSplitEntityTypePrincipal = true
};
foreach (var property in mappedType.GetProperties())
{
var columnName = property.GetColumnName(mappedFunction);
if (columnName == null)
{
continue;
}
var column = (FunctionColumn?)storeFunction.FindColumn(columnName);
if (column == null)
{
column = new(columnName, property.GetColumnType(mappedFunction), storeFunction);
column.IsNullable = property.IsColumnNullable(mappedFunction);
storeFunction.Columns.Add(columnName, column);
}
else if (!property.IsColumnNullable(mappedFunction))
{
column.IsNullable = false;
}
var columnMapping = new FunctionColumnMapping(property, column, functionMapping);
functionMapping.ColumnMappings.Add(columnMapping);
column.PropertyMappings.Add(columnMapping);
if (property.FindRuntimeAnnotationValue(RelationalAnnotationNames.FunctionColumnMappings)
is not SortedSet<FunctionColumnMapping> columnMappings)
{
columnMappings = new SortedSet<FunctionColumnMapping>(ColumnMappingBaseComparer.Instance);
property.AddRuntimeAnnotation(RelationalAnnotationNames.FunctionColumnMappings, columnMappings);
}
columnMappings.Add(columnMapping);
}
return functionMapping;
}
private static StoreFunction GetOrCreateStoreFunction(DbFunction dbFunction, RelationalModel model)
{
var storeFunction = (StoreFunction?)dbFunction.StoreFunction;
if (storeFunction == null)
{
var parameterTypes = dbFunction.Parameters.Select(p => p.StoreType!).ToArray();
storeFunction = (StoreFunction?)model.FindFunction(dbFunction.Name, dbFunction.Schema, parameterTypes);
if (storeFunction == null)
{
storeFunction = new StoreFunction(dbFunction, model);
model.Functions.Add((storeFunction.Name, storeFunction.Schema, parameterTypes), storeFunction);
}
else
{
dbFunction.StoreFunction = storeFunction;
for (var i = 0; i < dbFunction.Parameters.Count; i++)
{
storeFunction.Parameters[i].DbFunctionParameters.Add(dbFunction.Parameters[i]);
}
storeFunction.DbFunctions.Add(dbFunction.ModelName, dbFunction);
}
}
return storeFunction;
}
private static void PopulateConstraints(Table table)
{
var storeObject = StoreObjectIdentifier.Table(table.Name, table.Schema);
foreach (var entityTypeMapping in ((ITable)table).EntityTypeMappings)
{
if (!entityTypeMapping.IncludesDerivedTypes
&& entityTypeMapping.EntityType.GetTableMappings().Any(m => m.IncludesDerivedTypes))
{
continue;
}
var entityType = (IEntityType)entityTypeMapping.EntityType;
foreach (var foreignKey in entityType.GetForeignKeys())
{
var firstPrincipalMapping = true;
foreach (var principalMapping in foreignKey.PrincipalEntityType.GetTableMappings().Reverse())
{
if (firstPrincipalMapping
&& !principalMapping.IncludesDerivedTypes
&& foreignKey.PrincipalEntityType.GetDirectlyDerivedTypes().Any())
{
// Derived principal entity types are mapped to different tables, so the constraint is not enforceable
break;
}
firstPrincipalMapping = false;
var principalTable = (Table)principalMapping.Table;
var name = foreignKey.GetConstraintName(
storeObject,
StoreObjectIdentifier.Table(principalTable.Name, principalTable.Schema));
if (name == null)
{
continue;
}
var foreignKeyConstraints = foreignKey.FindRuntimeAnnotationValue(RelationalAnnotationNames.ForeignKeyMappings)
as SortedSet<ForeignKeyConstraint>;
if (table.ForeignKeyConstraints.TryGetValue(name, out var constraint))
{
if (foreignKeyConstraints == null)
{
foreignKeyConstraints = new SortedSet<ForeignKeyConstraint>(ForeignKeyConstraintComparer.Instance);
foreignKey.AddRuntimeAnnotation(RelationalAnnotationNames.ForeignKeyMappings, foreignKeyConstraints);
}
foreignKeyConstraints.Add(constraint);
constraint.MappedForeignKeys.Add(foreignKey);
break;
}
var principalColumns = new Column[foreignKey.Properties.Count];
for (var i = 0; i < principalColumns.Length; i++)
{
if (principalTable.FindColumn(foreignKey.PrincipalKey.Properties[i]) is Column principalColumn)
{
principalColumns[i] = principalColumn;
}
else
{
principalColumns = null;
break;
}
}
if (principalColumns == null)
{
continue;
}
var columns = new Column[foreignKey.Properties.Count];
for (var i = 0; i < columns.Length; i++)
{
if (table.FindColumn(foreignKey.Properties[i]) is Column foreignKeyColumn)
{
columns[i] = foreignKeyColumn;
}
else
{
columns = null;
break;
}
}
if (columns == null)
{
break;
}
if (columns.SequenceEqual(principalColumns))
{
// Principal and dependent properties are mapped to the same columns so the constraint is redundant
break;
}
if (entityTypeMapping.IncludesDerivedTypes
&& foreignKey.DeclaringEntityType != entityType
&& entityType.FindPrimaryKey() is IKey primaryKey
&& foreignKey.Properties.SequenceEqual(primaryKey.Properties))
{
// The identifying FK constraint is needed to be created only on the table that corresponds
// to the declaring entity type
break;
}
constraint = new ForeignKeyConstraint(
name, table, principalTable, columns, principalColumns, ToReferentialAction(foreignKey.DeleteBehavior));
constraint.MappedForeignKeys.Add(foreignKey);
if (foreignKeyConstraints == null)
{
foreignKeyConstraints = new SortedSet<ForeignKeyConstraint>(ForeignKeyConstraintComparer.Instance);
foreignKey.AddRuntimeAnnotation(RelationalAnnotationNames.ForeignKeyMappings, foreignKeyConstraints);
}
foreignKeyConstraints.Add(constraint);
table.ForeignKeyConstraints.Add(name, constraint);
break;
}
}
foreach (var key in entityType.GetKeys())
{
var name = key.GetName(storeObject);
if (name == null)
{
continue;
}
var constraint = table.FindUniqueConstraint(name);
if (constraint == null)
{
var columns = new Column[key.Properties.Count];
for (var i = 0; i < columns.Length; i++)
{
if (table.FindColumn(key.Properties[i]) is Column uniqueConstraintColumn)
{
columns[i] = uniqueConstraintColumn;
}
else
{
columns = null;
break;
}
}
if (columns == null)
{
continue;
}
constraint = new UniqueConstraint(name, table, columns);
if (key.IsPrimaryKey())
{
table.PrimaryKey = constraint;
}
table.UniqueConstraints.Add(name, constraint);
}
if (key.FindRuntimeAnnotationValue(RelationalAnnotationNames.UniqueConstraintMappings)
is not SortedSet<UniqueConstraint> uniqueConstraints)
{
uniqueConstraints = new SortedSet<UniqueConstraint>(UniqueConstraintComparer.Instance);
key.AddRuntimeAnnotation(RelationalAnnotationNames.UniqueConstraintMappings, uniqueConstraints);
}
uniqueConstraints.Add(constraint);
constraint.MappedKeys.Add(key);
}
foreach (var index in entityType.GetIndexes())
{
var name = index.GetDatabaseName(storeObject);
if (name == null)
{
continue;
}
if (!table.Indexes.TryGetValue(name, out var tableIndex))
{
var columns = new Column[index.Properties.Count];
for (var i = 0; i < columns.Length; i++)
{
if (table.FindColumn(index.Properties[i]) is Column indexColumn)
{
columns[i] = indexColumn;
}
else
{
columns = null;
break;
}
}
if (columns == null)
{
continue;
}
tableIndex = new TableIndex(name, table, columns, index.GetFilter(storeObject), index.IsUnique);
table.Indexes.Add(name, tableIndex);
}
if (index.FindRuntimeAnnotationValue(RelationalAnnotationNames.TableIndexMappings)
is not SortedSet<TableIndex> tableIndexes)
{
tableIndexes = new SortedSet<TableIndex>(TableIndexComparer.Instance);
index.AddRuntimeAnnotation(RelationalAnnotationNames.TableIndexMappings, tableIndexes);
}
tableIndexes.Add(tableIndex);
tableIndex.MappedIndexes.Add(index);
}
}
}
private static void PopulateRowInternalForeignKeys(TableBase table)
{
SortedDictionary<IEntityType, IEnumerable<IForeignKey>>? internalForeignKeyMap = null;
SortedDictionary<IEntityType, IEnumerable<IForeignKey>>? referencingInternalForeignKeyMap = null;
TableMappingBase? mainMapping = null;
var mappedEntityTypes = new HashSet<IEntityType>();
foreach (TableMappingBase entityTypeMapping in ((ITableBase)table).EntityTypeMappings)
{
var entityType = entityTypeMapping.EntityType;
mappedEntityTypes.Add(entityType);
var primaryKey = entityType.FindPrimaryKey();
if (primaryKey == null)
{
if (mainMapping == null
|| entityTypeMapping.EntityType.IsAssignableFrom(mainMapping.EntityType))
{
mainMapping = entityTypeMapping;
}
continue;
}
SortedSet<IForeignKey>? rowInternalForeignKeys = null;
foreach (var foreignKey in entityType.FindForeignKeys(primaryKey.Properties))
{
if (foreignKey.IsUnique
&& foreignKey.PrincipalKey.IsPrimaryKey()
&& !foreignKey.DeclaringEntityType.IsAssignableFrom(foreignKey.PrincipalEntityType)
&& !foreignKey.PrincipalEntityType.IsAssignableFrom(foreignKey.DeclaringEntityType)
&& ((ITableBase)table).EntityTypeMappings.Any(m => m.EntityType == foreignKey.PrincipalEntityType))
{
if (rowInternalForeignKeys == null)
{
rowInternalForeignKeys = new SortedSet<IForeignKey>(ForeignKeyComparer.Instance);
}
rowInternalForeignKeys.Add(foreignKey);
if (referencingInternalForeignKeyMap == null)
{
referencingInternalForeignKeyMap =
new SortedDictionary<IEntityType, IEnumerable<IForeignKey>>(EntityTypeFullNameComparer.Instance);
}
var principalEntityType = foreignKey.PrincipalEntityType;
if (!referencingInternalForeignKeyMap.TryGetValue(principalEntityType, out var internalReferencingForeignKeys))
{
internalReferencingForeignKeys = new SortedSet<IForeignKey>(ForeignKeyComparer.Instance);
referencingInternalForeignKeyMap[principalEntityType] = internalReferencingForeignKeys;
}
((SortedSet<IForeignKey>)internalReferencingForeignKeys).Add(foreignKey);
}
}
if (rowInternalForeignKeys != null)
{
if (internalForeignKeyMap == null)
{
internalForeignKeyMap =
new SortedDictionary<IEntityType, IEnumerable<IForeignKey>>(EntityTypeFullNameComparer.Instance);
table.RowInternalForeignKeys = internalForeignKeyMap;
}
internalForeignKeyMap[entityType] = rowInternalForeignKeys;
table.IsShared = true;
}
if (rowInternalForeignKeys == null)
{
if (mainMapping == null
|| entityTypeMapping.EntityType.IsAssignableFrom(mainMapping.EntityType))
{
mainMapping = entityTypeMapping;
}
}
}
// Re-add the mapping to update the order
if (mainMapping is TableMapping mainTableMapping)
{
((Table)mainMapping.Table).EntityTypeMappings.Remove(mainTableMapping);
mainMapping.IsSharedTablePrincipal = true;
((Table)mainMapping.Table).EntityTypeMappings.Add(mainTableMapping);
}
else if (mainMapping is ViewMapping mainViewMapping)
{
((View)mainMapping.Table).EntityTypeMappings.Remove(mainViewMapping);
mainMapping.IsSharedTablePrincipal = true;
((View)mainMapping.Table).EntityTypeMappings.Add(mainViewMapping);
}
Check.DebugAssert(mainMapping is not null,
$"{nameof(mainMapping)} is neither a {nameof(TableMapping)} nor a {nameof(ViewMapping)}");
if (referencingInternalForeignKeyMap != null)
{
table.ReferencingRowInternalForeignKeys = referencingInternalForeignKeyMap;
var optionalTypes = new Dictionary<IEntityType, bool>();
var entityTypesToVisit = new Queue<(IEntityType, bool)>();
entityTypesToVisit.Enqueue((mainMapping.EntityType, false));
while (entityTypesToVisit.Count > 0)
{
var (entityType, optional) = entityTypesToVisit.Dequeue();
if (optionalTypes.TryGetValue(entityType, out var previouslyOptional)
&& (!previouslyOptional || optional))
{
continue;
}
optionalTypes[entityType] = optional;
if (referencingInternalForeignKeyMap.TryGetValue(entityType, out var referencingInternalForeignKeys))
{
foreach (var referencingForeignKey in referencingInternalForeignKeys)
{
entityTypesToVisit.Enqueue(
(referencingForeignKey.DeclaringEntityType, optional || !referencingForeignKey.IsRequiredDependent));
}
}
if (table.EntityTypeMappings.Single(etm => etm.EntityType == entityType).IncludesDerivedTypes)
{
foreach (var directlyDerivedEntityType in entityType.GetDerivedTypes())
{
if (mappedEntityTypes.Contains(directlyDerivedEntityType)
&& !optionalTypes.ContainsKey(directlyDerivedEntityType))
{
entityTypesToVisit.Enqueue((directlyDerivedEntityType, optional));
}
}
}
}
table.OptionalEntityTypes = optionalTypes;
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static ReferentialAction ToReferentialAction(DeleteBehavior deleteBehavior)
=> deleteBehavior switch
{
DeleteBehavior.SetNull => ReferentialAction.SetNull,
DeleteBehavior.Cascade => ReferentialAction.Cascade,
DeleteBehavior.NoAction or DeleteBehavior.ClientNoAction => ReferentialAction.NoAction,
DeleteBehavior.Restrict or DeleteBehavior.ClientSetNull or DeleteBehavior.ClientCascade => ReferentialAction.Restrict,
_ => throw new NotSupportedException(deleteBehavior.ToString()),
};
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual DebugView DebugView
=> new(
() => ((IRelationalModel)this).ToDebugString(MetadataDebugStringOptions.ShortDefault),
() => ((IRelationalModel)this).ToDebugString(MetadataDebugStringOptions.LongDefault));
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override string ToString()
=> ((IRelationalModel)this).ToDebugString(MetadataDebugStringOptions.SingleLineDefault);
IEnumerable<ITable> IRelationalModel.Tables
{
[DebuggerStepThrough]
get => Tables.Values;
}
IEnumerable<IView> IRelationalModel.Views
{
[DebuggerStepThrough]
get => Views.Values;
}
IEnumerable<IStoreFunction> IRelationalModel.Functions
{
[DebuggerStepThrough]
get => Functions.Values;
}
IEnumerable<ISqlQuery> IRelationalModel.Queries
{
[DebuggerStepThrough]
get => Queries.Values;
}
}
}
| 45.252766 | 142 | 0.5372 | [
"Apache-2.0"
] | vitorelli/efcore | src/EFCore.Relational/Metadata/Internal/RelationalModel.cs | 53,174 | C# |
using Aspose.Gis.Geometries;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aspose.GIS.Examples.CSharp.Geometries
{
class DetermineIfOneGeometryCoversAnother
{
public static void Run()
{
//ExStart: DetermineIfOneGeometryCoversAnother
var line = new LineString();
line.AddPoint(0, 0);
line.AddPoint(1, 1);
var point = new Point(0, 0);
Console.WriteLine(line.Covers(point)); // True
Console.WriteLine(point.CoveredBy(line)); // True
//ExEnd: DetermineIfOneGeometryCoversAnother
}
}
}
| 26.884615 | 61 | 0.630901 | [
"MIT"
] | aspose-gis/Aspose.GIS-for-.NET | Examples/CSharp/Geometries/DetermineIfOneGeometryCoversAnother.cs | 701 | 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/WebServices.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public unsafe partial struct WS_MESSAGE_PROPERTIES
{
public WS_MESSAGE_PROPERTY* properties;
[NativeTypeName("ULONG")]
public uint propertyCount;
}
}
| 31.5625 | 145 | 0.732673 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/WebServices/WS_MESSAGE_PROPERTIES.cs | 507 | 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 Microsoft.Win32.SafeHandles;
namespace Microsoft.AspNetCore.HttpSys.Internal;
internal sealed class SafeLocalMemHandle : SafeHandleZeroOrMinusOneIsInvalid
{
internal SafeLocalMemHandle()
: base(true)
{
}
internal SafeLocalMemHandle(IntPtr existingHandle, bool ownsHandle)
: base(ownsHandle)
{
SetHandle(existingHandle);
}
protected override bool ReleaseHandle()
{
return UnsafeNclNativeMethods.SafeNetHandles.LocalFree(handle) == IntPtr.Zero;
}
}
| 25.074074 | 86 | 0.725258 | [
"MIT"
] | 3ejki/aspnetcore | src/Shared/HttpSys/NativeInterop/SafeLocalMemHandle.cs | 677 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AspectOrientedProgrammingWithUnity.Tests
{
public class BaseViewModel : MarshalByRefObject, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
}
}
| 23.733333 | 75 | 0.800562 | [
"MIT"
] | Jalalx/AspectOrientedProgrammingWithUnity | AspectOrientedProgrammingWithUnity.Tests/BaseViewModel.cs | 358 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class XiangQiClick : MonoBehaviour, IPointerClickHandler
{
int _width = 50;
RectTransform meRect;
public void Init(int offset, int width)
{
meRect = GetComponent<RectTransform>();
_width = width;
int tmpWidth = 8 * width + 2 * offset;
int tmpHeight = 9 * width + 2 * offset;
Debug.Log(tmpWidth + "/" + tmpHeight);
meRect.sizeDelta = new Vector2(tmpWidth, tmpHeight);
meRect.anchoredPosition = new Vector2(-tmpWidth / 2, tmpHeight / 2);
transform.parent.Find("sign").GetComponent<RectTransform>().anchoredPosition = new Vector2(-4 * width, 4.5f * width);
}
public void OnPointerClick(PointerEventData eventData)
{
Vector2 localPos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(meRect,
eventData.position, eventData.pressEventCamera, out localPos);
int i = (int)(Mathf.Abs(localPos.y) / _width);
int j = (int)(Mathf.Abs(localPos.x) / _width);
XiangQiPanel.instance.QiPanClick(i, j);
}
}
| 36.30303 | 126 | 0.649416 | [
"MIT"
] | rik111cn/qipai | client/Assets/Scripts/Game/XiangQi/XiangQiClick.cs | 1,200 | C# |
using UnityEngine;
namespace StrangeWorld.Patrons
{
//*Static class used to manage singleton instance
public static class SingletonTools
{
//Methods
//Check if a singleton instace allready exists
public static bool CanSetInstance<T>(T singletonReference, T newInstance) => singletonReference == null && newInstance != null;
//Debug if singleton instace exists error
public static void DebugDuplicateSingleton() => Debug.LogWarning("Warning: Tried to duplicate singleton instance");
}
}
| 36.2 | 135 | 0.712707 | [
"CC0-1.0"
] | Seyk10/Portfolio | Scripts/Singleton/SingletonTools.cs | 543 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using SAEA.Common.Newtonsoft.Json.Serialization;
#if NET20
using SAEA.Common.Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using System.Globalization;
using SAEA.Common.Newtonsoft.Json.Utilities;
using SAEA.Common.Newtonsoft.Json.Linq;
namespace SAEA.Common.Newtonsoft.Json.Schema
{
internal class JsonSchemaBuilder
{
private readonly IList<JsonSchema> _stack;
private readonly JsonSchemaResolver _resolver;
private readonly IDictionary<string, JsonSchema> _documentSchemas;
private JsonSchema _currentSchema;
private JObject _rootSchema;
public JsonSchemaBuilder(JsonSchemaResolver resolver)
{
_stack = new List<JsonSchema>();
_documentSchemas = new Dictionary<string, JsonSchema>();
_resolver = resolver;
}
private void Push(JsonSchema value)
{
_currentSchema = value;
_stack.Add(value);
_resolver.LoadedSchemas.Add(value);
_documentSchemas.Add(value.Location, value);
}
private JsonSchema Pop()
{
JsonSchema poppedSchema = _currentSchema;
_stack.RemoveAt(_stack.Count - 1);
_currentSchema = _stack.LastOrDefault();
return poppedSchema;
}
private JsonSchema CurrentSchema
{
get { return _currentSchema; }
}
internal JsonSchema Read(JsonReader reader)
{
JToken schemaToken = JToken.ReadFrom(reader);
_rootSchema = schemaToken as JObject;
JsonSchema schema = BuildSchema(schemaToken);
ResolveReferences(schema);
return schema;
}
private string UnescapeReference(string reference)
{
return Uri.UnescapeDataString(reference).Replace("~1", "/").Replace("~0", "~");
}
private JsonSchema ResolveReferences(JsonSchema schema)
{
if (schema.DeferredReference != null)
{
string reference = schema.DeferredReference;
bool locationReference = (reference.StartsWith("#", StringComparison.Ordinal));
if (locationReference)
reference = UnescapeReference(reference);
JsonSchema resolvedSchema = _resolver.GetSchema(reference);
if (resolvedSchema == null)
{
if (locationReference)
{
string[] escapedParts = schema.DeferredReference.TrimStart('#').Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
JToken currentToken = _rootSchema;
foreach (string escapedPart in escapedParts)
{
string part = UnescapeReference(escapedPart);
if (currentToken.Type == JTokenType.Object)
{
currentToken = currentToken[part];
}
else if (currentToken.Type == JTokenType.Array || currentToken.Type == JTokenType.Constructor)
{
int index;
if (int.TryParse(part, out index) && index >= 0 && index < currentToken.Count())
currentToken = currentToken[index];
else
currentToken = null;
}
if (currentToken == null)
break;
}
if (currentToken != null)
resolvedSchema = BuildSchema(currentToken);
}
if (resolvedSchema == null)
throw new JsonException("Could not resolve schema reference '{0}'.".FormatWith(CultureInfo.InvariantCulture, schema.DeferredReference));
}
schema = resolvedSchema;
}
if (schema.ReferencesResolved)
return schema;
schema.ReferencesResolved = true;
if (schema.Extends != null)
{
for (int i = 0; i < schema.Extends.Count; i++)
{
schema.Extends[i] = ResolveReferences(schema.Extends[i]);
}
}
if (schema.Items != null)
{
for (int i = 0; i < schema.Items.Count; i++)
{
schema.Items[i] = ResolveReferences(schema.Items[i]);
}
}
if (schema.AdditionalItems != null)
schema.AdditionalItems = ResolveReferences(schema.AdditionalItems);
if (schema.PatternProperties != null)
{
foreach (KeyValuePair<string, JsonSchema> patternProperty in schema.PatternProperties.ToList())
{
schema.PatternProperties[patternProperty.Key] = ResolveReferences(patternProperty.Value);
}
}
if (schema.Properties != null)
{
foreach (KeyValuePair<string, JsonSchema> property in schema.Properties.ToList())
{
schema.Properties[property.Key] = ResolveReferences(property.Value);
}
}
if (schema.AdditionalProperties != null)
schema.AdditionalProperties = ResolveReferences(schema.AdditionalProperties);
return schema;
}
private JsonSchema BuildSchema(JToken token)
{
JObject schemaObject = token as JObject;
if (schemaObject == null)
throw JsonException.Create(token, token.Path, "Expected object while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
JToken referenceToken;
if (schemaObject.TryGetValue(JsonTypeReflector.RefPropertyName, out referenceToken))
{
JsonSchema deferredSchema = new JsonSchema();
deferredSchema.DeferredReference = (string)referenceToken;
return deferredSchema;
}
string location = token.Path.Replace(".", "/").Replace("[", "/").Replace("]", string.Empty);
if (!string.IsNullOrEmpty(location))
location = "/" + location;
location = "#" + location;
JsonSchema existingSchema;
if (_documentSchemas.TryGetValue(location, out existingSchema))
return existingSchema;
Push(new JsonSchema { Location = location });
ProcessSchemaProperties(schemaObject);
return Pop();
}
private void ProcessSchemaProperties(JObject schemaObject)
{
foreach (KeyValuePair<string, JToken> property in schemaObject)
{
switch (property.Key)
{
case JsonSchemaConstants.TypePropertyName:
CurrentSchema.Type = ProcessType(property.Value);
break;
case JsonSchemaConstants.IdPropertyName:
CurrentSchema.Id = (string)property.Value;
break;
case JsonSchemaConstants.TitlePropertyName:
CurrentSchema.Title = (string)property.Value;
break;
case JsonSchemaConstants.DescriptionPropertyName:
CurrentSchema.Description = (string)property.Value;
break;
case JsonSchemaConstants.PropertiesPropertyName:
CurrentSchema.Properties = ProcessProperties(property.Value);
break;
case JsonSchemaConstants.ItemsPropertyName:
ProcessItems(property.Value);
break;
case JsonSchemaConstants.AdditionalPropertiesPropertyName:
ProcessAdditionalProperties(property.Value);
break;
case JsonSchemaConstants.AdditionalItemsPropertyName:
ProcessAdditionalItems(property.Value);
break;
case JsonSchemaConstants.PatternPropertiesPropertyName:
CurrentSchema.PatternProperties = ProcessProperties(property.Value);
break;
case JsonSchemaConstants.RequiredPropertyName:
CurrentSchema.Required = (bool)property.Value;
break;
case JsonSchemaConstants.RequiresPropertyName:
CurrentSchema.Requires = (string)property.Value;
break;
case JsonSchemaConstants.MinimumPropertyName:
CurrentSchema.Minimum = (double)property.Value;
break;
case JsonSchemaConstants.MaximumPropertyName:
CurrentSchema.Maximum = (double)property.Value;
break;
case JsonSchemaConstants.ExclusiveMinimumPropertyName:
CurrentSchema.ExclusiveMinimum = (bool)property.Value;
break;
case JsonSchemaConstants.ExclusiveMaximumPropertyName:
CurrentSchema.ExclusiveMaximum = (bool)property.Value;
break;
case JsonSchemaConstants.MaximumLengthPropertyName:
CurrentSchema.MaximumLength = (int)property.Value;
break;
case JsonSchemaConstants.MinimumLengthPropertyName:
CurrentSchema.MinimumLength = (int)property.Value;
break;
case JsonSchemaConstants.MaximumItemsPropertyName:
CurrentSchema.MaximumItems = (int)property.Value;
break;
case JsonSchemaConstants.MinimumItemsPropertyName:
CurrentSchema.MinimumItems = (int)property.Value;
break;
case JsonSchemaConstants.DivisibleByPropertyName:
CurrentSchema.DivisibleBy = (double)property.Value;
break;
case JsonSchemaConstants.DisallowPropertyName:
CurrentSchema.Disallow = ProcessType(property.Value);
break;
case JsonSchemaConstants.DefaultPropertyName:
CurrentSchema.Default = property.Value.DeepClone();
break;
case JsonSchemaConstants.HiddenPropertyName:
CurrentSchema.Hidden = (bool)property.Value;
break;
case JsonSchemaConstants.ReadOnlyPropertyName:
CurrentSchema.ReadOnly = (bool)property.Value;
break;
case JsonSchemaConstants.FormatPropertyName:
CurrentSchema.Format = (string)property.Value;
break;
case JsonSchemaConstants.PatternPropertyName:
CurrentSchema.Pattern = (string)property.Value;
break;
case JsonSchemaConstants.EnumPropertyName:
ProcessEnum(property.Value);
break;
case JsonSchemaConstants.ExtendsPropertyName:
ProcessExtends(property.Value);
break;
case JsonSchemaConstants.UniqueItemsPropertyName:
CurrentSchema.UniqueItems = (bool)property.Value;
break;
}
}
}
private void ProcessExtends(JToken token)
{
IList<JsonSchema> schemas = new List<JsonSchema>();
if (token.Type == JTokenType.Array)
{
foreach (JToken schemaObject in token)
{
schemas.Add(BuildSchema(schemaObject));
}
}
else
{
JsonSchema schema = BuildSchema(token);
if (schema != null)
schemas.Add(schema);
}
if (schemas.Count > 0)
CurrentSchema.Extends = schemas;
}
private void ProcessEnum(JToken token)
{
if (token.Type != JTokenType.Array)
throw JsonException.Create(token, token.Path, "Expected Array token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
CurrentSchema.Enum = new List<JToken>();
foreach (JToken enumValue in token)
{
CurrentSchema.Enum.Add(enumValue.DeepClone());
}
}
private void ProcessAdditionalProperties(JToken token)
{
if (token.Type == JTokenType.Boolean)
CurrentSchema.AllowAdditionalProperties = (bool)token;
else
CurrentSchema.AdditionalProperties = BuildSchema(token);
}
private void ProcessAdditionalItems(JToken token)
{
if (token.Type == JTokenType.Boolean)
CurrentSchema.AllowAdditionalItems = (bool)token;
else
CurrentSchema.AdditionalItems = BuildSchema(token);
}
private IDictionary<string, JsonSchema> ProcessProperties(JToken token)
{
IDictionary<string, JsonSchema> properties = new Dictionary<string, JsonSchema>();
if (token.Type != JTokenType.Object)
throw JsonException.Create(token, token.Path, "Expected Object token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
foreach (JProperty propertyToken in token)
{
if (properties.ContainsKey(propertyToken.Name))
throw new JsonException("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyToken.Name));
properties.Add(propertyToken.Name, BuildSchema(propertyToken.Value));
}
return properties;
}
private void ProcessItems(JToken token)
{
CurrentSchema.Items = new List<JsonSchema>();
switch (token.Type)
{
case JTokenType.Object:
CurrentSchema.Items.Add(BuildSchema(token));
CurrentSchema.PositionalItemsValidation = false;
break;
case JTokenType.Array:
CurrentSchema.PositionalItemsValidation = true;
foreach (JToken schemaToken in token)
{
CurrentSchema.Items.Add(BuildSchema(schemaToken));
}
break;
default:
throw JsonException.Create(token, token.Path, "Expected array or JSON schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
}
}
private JsonSchemaType? ProcessType(JToken token)
{
switch (token.Type)
{
case JTokenType.Array:
// ensure type is in blank state before ORing values
JsonSchemaType? type = JsonSchemaType.None;
foreach (JToken typeToken in token)
{
if (typeToken.Type != JTokenType.String)
throw JsonException.Create(typeToken, typeToken.Path, "Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
type = type | MapType((string)typeToken);
}
return type;
case JTokenType.String:
return MapType((string)token);
default:
throw JsonException.Create(token, token.Path, "Expected array or JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
}
}
internal static JsonSchemaType MapType(string type)
{
JsonSchemaType mappedType;
if (!JsonSchemaConstants.JsonSchemaTypeMapping.TryGetValue(type, out mappedType))
throw new JsonException("Invalid JSON schema type: {0}".FormatWith(CultureInfo.InvariantCulture, type));
return mappedType;
}
internal static string MapType(JsonSchemaType type)
{
return JsonSchemaConstants.JsonSchemaTypeMapping.Single(kv => kv.Value == type).Key;
}
}
}
| 40.997773 | 188 | 0.55063 | [
"Apache-2.0"
] | cty901/SAEA | Src/SAEA.Common/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs | 18,410 | C# |
using System.Collections.Generic;
using DwollaV2.SerializableTypes;
namespace DwollaV2
{
public class Accounts : Rest
{
/// <summary>
/// Returns basic account info for the passed account ID.
/// </summary>
/// <param name="accountId">Account ID</param>
/// <returns>UserBasic object</returns>
public UserBasic Basic(string accountId)
{
var data = new Dictionary<string, string>
{
{"client_id", C.dwolla_key},
{"client_secret", C.dwolla_secret},
};
return DwollaParse<UserBasic>(Get("/users/" + accountId, data)).Response;
}
/// <summary>
/// Returns full account information for the user associated
/// with the currently set OAuth token.
/// </summary>
/// <param name="altToken">Alternate OAuth token</param>
/// <returns>UserFull object</returns>
public UserFull Full(string altToken = null)
{
var data = new Dictionary<string, string>
{
{"oauth_token", altToken ?? C.dwolla_access_token}
};
return DwollaParse<UserFull>(Get("/users", data)).Response;
}
/// <summary>
/// Returns balance for the account associated with the
/// currently set OAuth token.
/// </summary>
/// <param name="altToken">Alternate OAuth token</param>
/// <returns>Balance as double</returns>
public double Balance(string altToken = null)
{
var data = new Dictionary<string, string>
{
{"oauth_token", altToken ?? C.dwolla_access_token}
};
return DwollaParse<double>(Get("/balance", data)).Response;
}
/// <summary>
/// Returns users and venues near a location.
/// </summary>
/// <param name="lat">Latitudinal coordinates</param>
/// <param name="lon">Longitudinal coordinates</param>
/// <returns>List of UserNearby objects</returns>
public List<UserNearby> Nearby(double lat, double lon)
{
var data = new Dictionary<string, string>
{
{"client_id", C.dwolla_key},
{"client_secret", C.dwolla_secret},
{"latitude", lat.ToString()},
{"longitude", lon.ToString()}
};
return DwollaParse<List<UserNearby>>(Get("/users/nearby", data)).Response;
}
/// <summary>
/// Gets auto withdrawal status for the account associated
/// with the currently set OAuth token.
/// </summary>
/// <param name="altToken">Alternate OAuth token</param>
/// <returns>AutoWithdrawalStatus object</returns>
public AutoWithdrawalStatus GetAutoWithdrawalStatus(string altToken = null)
{
var data = new Dictionary<string, string>
{
{"oauth_token", altToken ?? C.dwolla_access_token}
};
return DwollaParse<AutoWithdrawalStatus>(Get("/accounts/features/auto_withdrawl",
data)).Response;
}
/// <summary>
/// Sets auto-withdrawal status of the account associated
/// with the current OAuth token under the specified
/// funding ID.
/// </summary>
/// <param name="status">Enable toggle</param>
/// <param name="fundingId">Target funding ID</param>
/// <param name="altToken">Alternate OAuth token</param>
/// <returns>Account autowithdrawal status</returns>
public bool ToggleAutoWithdrawalStatus(bool status, string fundingId, string altToken = null)
{
var data = new Dictionary<string, string>
{
{"oauth_token", altToken ?? C.dwolla_access_token}
};
var r = DwollaParse<string>(Post("/accounts/features/auto_withdrawl",
data));
// I figure this will be more useful than the string
return r.Response == "Enabled";
}
}
}
| 32.269565 | 97 | 0.622474 | [
"Unlicense"
] | 501st-alpha1/dwolla.net-v2 | Endpoints/Accounts.cs | 3,713 | C# |
using System.Reflection;
using System.Threading.Tasks;
namespace AwsLambdaLauncher.Service.Models.HealthCheck
{
/// <summary>
/// A check item class holds logic for checking the running service itself
/// </summary>
internal class SelfLiveCheckItem : ILiveCheckItem
{
public async Task<dynamic> ExecuteAsync()
{
var result = new SelfLiveCheckResult
{
Message = "The Service Is Live!",
Version = Assembly.GetEntryAssembly().GetName().Version.ToString(4)
};
// For now, this uses "fake" async to meet the interface needs. The expectation
// is that we will want to collect some information, such as server states,
// asynchronosly soon
return await Task.Run(() => result);
}
}
}
| 33.461538 | 92 | 0.590805 | [
"MIT"
] | zhangsiy/AwsLambdaLauncher | src/AwsLambdaLauncher.Service/Models/HealthCheck/SelfLiveCheckItem.cs | 872 | C# |
using Volo.Abp.Settings;
namespace ConcurrentLogin.Settings;
public class ConcurrentLoginSettingDefinitionProvider : SettingDefinitionProvider
{
public override void Define(ISettingDefinitionContext context)
{
//Define your own settings here. Example:
//context.Add(new SettingDefinition(ConcurrentLoginSettings.MySetting1));
}
}
| 27.769231 | 81 | 0.772853 | [
"MIT"
] | Aprite/abp-samples | ConcurrentLogin/src/ConcurrentLogin.Domain/Settings/ConcurrentLoginSettingDefinitionProvider.cs | 363 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.ComponentModel;
namespace ContasimpleAPI.Models
{
/// <summary> The Enum447. </summary>
public readonly partial struct Enum447 : IEquatable<Enum447>
{
private readonly string _value;
/// <summary> Determines if two <see cref="Enum447"/> values are the same. </summary>
/// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
public Enum447(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
private const string EsESValue = "es-ES";
private const string EnUSValue = "en-US";
private const string CaESValue = "ca-ES";
/// <summary> es-ES. </summary>
public static Enum447 EsES { get; } = new Enum447(EsESValue);
/// <summary> en-US. </summary>
public static Enum447 EnUS { get; } = new Enum447(EnUSValue);
/// <summary> ca-ES. </summary>
public static Enum447 CaES { get; } = new Enum447(CaESValue);
/// <summary> Determines if two <see cref="Enum447"/> values are the same. </summary>
public static bool operator ==(Enum447 left, Enum447 right) => left.Equals(right);
/// <summary> Determines if two <see cref="Enum447"/> values are not the same. </summary>
public static bool operator !=(Enum447 left, Enum447 right) => !left.Equals(right);
/// <summary> Converts a string to a <see cref="Enum447"/>. </summary>
public static implicit operator Enum447(string value) => new Enum447(value);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => obj is Enum447 other && Equals(other);
/// <inheritdoc />
public bool Equals(Enum447 other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
/// <inheritdoc />
public override string ToString() => _value;
}
}
| 41.618182 | 126 | 0.638707 | [
"MIT"
] | JonasBr68/ContaSimpleClient | ClientApi/generated/Models/Enum447.cs | 2,289 | C# |
// <auto-generated />
namespace VideoNotes.DataAccess.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
public sealed partial class InitialMigration : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(InitialMigration));
string IMigrationMetadata.Id
{
get { return "201505251033230_InitialMigration"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 28.033333 | 99 | 0.630202 | [
"MIT"
] | PROVideoNotes/Video-Notes-System | VideoNotes/VideoNotes.DataAccess/Migrations/201505251033230_InitialMigration.Designer.cs | 841 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Configuration;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
namespace Apache.NMS.WCF
{
/// <summary>
/// Configuration section for NMS.
/// </summary>
public class NmsTransportElement : BindingElementExtensionElement
{
#region Public properties
/// <summary>
/// Gets or sets the name of the message destination.
/// </summary>
/// <value>The name of the message destination.</value>
[ConfigurationProperty(NmsConfigurationStrings.Destination, IsRequired = true)]
public string Destination
{
get { return (string) base[NmsConfigurationStrings.Destination]; }
set
{
base[NmsConfigurationStrings.Destination] = value;
}
}
/// <summary>
/// Gets or sets the type of the message destination.
/// </summary>
/// <value>The type of the message destination (may be either <c>queue</c> or <c>topic</c>, and temporary
/// or permanent versions of either).</value>
[ConfigurationProperty(NmsConfigurationStrings.DestinationType, DefaultValue = NmsConfigurationDefaults.Destination)]
public DestinationType DestinationType
{
get { return (DestinationType) Enum.Parse(typeof(DestinationType), base[NmsConfigurationStrings.DestinationType].ToString(), true); }
set { base[NmsConfigurationStrings.DestinationType] = value; }
}
#endregion
#region Configuration overrides
/// <summary>
/// When overridden in a derived class, gets the <see cref="T:System.Type" /> object that represents the custom binding element.
/// </summary>
/// <returns>
/// A <see cref="T:System.Type" /> object that represents the custom binding type.
/// </returns>
public override Type BindingElementType
{
get { return typeof(NmsTransportBindingElement); }
}
/// <summary>
/// When overridden in a derived class, returns a custom binding element object.
/// </summary>
/// <returns>
/// A custom <see cref="T:System.ServiceModel.Channels.BindingElement" /> object.
/// </returns>
protected override BindingElement CreateBindingElement()
{
NmsTransportBindingElement bindingElement = new NmsTransportBindingElement();
this.ApplyConfiguration(bindingElement);
return bindingElement;
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="bindingElement"></param>
public override void ApplyConfiguration(BindingElement bindingElement)
{
base.ApplyConfiguration(bindingElement);
NmsTransportBindingElement nmsBindingElement = (NmsTransportBindingElement) bindingElement;
nmsBindingElement.Destination = Destination;
nmsBindingElement.DestinationType = DestinationType;
}
/// <summary>
/// Copies the content of the specified configuration element to this configuration element.
/// </summary>
/// <param name="from">The configuration element to be copied.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="from"/> is null.</exception>
/// <exception cref="T:System.Configuration.ConfigurationErrorsException">The configuration file is read-only.</exception>
public override void CopyFrom(ServiceModelExtensionElement from)
{
base.CopyFrom(from);
NmsTransportElement source = (NmsTransportElement) from;
Destination = source.Destination;
DestinationType = source.DestinationType;
}
/// <summary>
/// Initializes this binding configuration section with the content of the specified binding element.
/// </summary>
/// <param name="bindingElement">A binding element.</param>
protected override void InitializeFrom(BindingElement bindingElement)
{
base.InitializeFrom(bindingElement);
NmsTransportBindingElement nmsBindingElement = (NmsTransportBindingElement) bindingElement;
Destination = nmsBindingElement.Destination;
DestinationType = nmsBindingElement.DestinationType;
}
/// <summary>
/// Gets the collection of properties.
/// </summary>
/// <value></value>
/// <returns>
/// The <see cref="T:System.Configuration.ConfigurationPropertyCollection"/> of properties for the element.
/// </returns>
protected override ConfigurationPropertyCollection Properties
{
get
{
ConfigurationPropertyCollection properties = base.Properties;
properties.Add(new ConfigurationProperty(NmsConfigurationStrings.Destination, typeof(string), null, ConfigurationPropertyOptions.IsRequired));
properties.Add(new ConfigurationProperty(NmsConfigurationStrings.DestinationType, typeof(DestinationType), NmsConfigurationDefaults.Destination));
return properties;
}
}
}
}
| 36.067114 | 150 | 0.742092 | [
"Apache-2.0"
] | malibu/Custom.Channel | src/main/csharp/Configuration/NmsTransportElement.cs | 5,374 | C# |
// Licensed to ifak e.V. under one or more agreements.
// ifak e.V. licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Security.Cryptography;
using System.Text;
namespace Ifak.Fast.Mediator
{
public class SimpleEncryption
{
private static byte[] key = new byte[] { 2, 6, 23, 100, 8, 99, 78, 44 };
private static byte[] iv = new byte[] { 33, 14, 78, 96, 28, 11, 7, 8 };
public static string Encrypt(string text) {
SymmetricAlgorithm algorithm = DES.Create();
ICryptoTransform transform = algorithm.CreateEncryptor(key, iv);
byte[] inputbuffer = Encoding.UTF8.GetBytes(text);
byte[] outputBuffer = transform.TransformFinalBlock(inputbuffer, 0, inputbuffer.Length);
return Convert.ToBase64String(outputBuffer);
}
public static string Decrypt(string text) {
SymmetricAlgorithm algorithm = DES.Create();
ICryptoTransform transform = algorithm.CreateDecryptor(key, iv);
byte[] inputbuffer = Convert.FromBase64String(text);
byte[] outputBuffer = transform.TransformFinalBlock(inputbuffer, 0, inputbuffer.Length);
return Encoding.UTF8.GetString(outputBuffer);
}
}
}
| 40.636364 | 100 | 0.656972 | [
"MIT"
] | ifakFAST/Mediator.Net | Mediator.Net/MediatorCore/SimpleEncryption.cs | 1,343 | C# |
using Sharpen;
namespace android.net.wifi
{
[Sharpen.NakedStub]
public class SupplicantStateTracker
{
[Sharpen.NakedStub]
public class DefaultState
{
}
[Sharpen.NakedStub]
public class UninitializedState
{
}
[Sharpen.NakedStub]
public class InactiveState
{
}
[Sharpen.NakedStub]
public class DisconnectedState
{
}
[Sharpen.NakedStub]
public class ScanState
{
}
[Sharpen.NakedStub]
public class HandshakeState
{
}
[Sharpen.NakedStub]
public class CompletedState
{
}
[Sharpen.NakedStub]
public class DormantState
{
}
}
}
| 12.142857 | 36 | 0.687395 | [
"Apache-2.0"
] | Conceptengineai/XobotOS | android/generated/android/net/wifi/SupplicantStateTracker.cs | 595 | C# |
using System;
namespace NLuaTest.TestTypes
{
public class Vector
{
public double x;
public double y;
public static Vector operator *(float k, Vector v)
{
var r = new Vector();
r.x = v.x * k;
r.y = v.y * k;
return r;
}
public static Vector operator *(Vector v, float k)
{
var r = new Vector();
r.x = v.x * k;
r.y = v.y * k;
return r;
}
public void Func()
{
Console.WriteLine("Func");
}
}
} | 20 | 58 | 0.42 | [
"MIT"
] | Auios/NLua | tests/src/TestTypes/Vector.cs | 602 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ClearScript.Properties;
namespace Microsoft.ClearScript.Util
{
internal static class MiscHelpers
{
#region COM helpers
private static readonly Regex dispIDNameRegex = new Regex(@"^\[DISPID=(-?[0-9]+)\]$");
public static object CreateCOMObject(string progID, string serverName)
{
return Activator.CreateInstance(GetCOMType(progID, serverName));
}
public static object CreateCOMObject(Guid clsid, string serverName)
{
return Activator.CreateInstance(GetCOMType(clsid, serverName));
}
public static bool TryCreateCOMObject<T>(string progID, string serverName, out T obj) where T : class
{
if (!TryGetCOMType(progID, serverName, out var type))
{
obj = null;
return false;
}
obj = Activator.CreateInstance(type) as T;
return obj != null;
}
public static bool TryCreateCOMObject<T>(Guid clsid, string serverName, out T obj) where T : class
{
if (!TryGetCOMType(clsid, serverName, out var type))
{
obj = null;
return false;
}
obj = Activator.CreateInstance(type) as T;
return obj != null;
}
public static Type GetCOMType(string progID, string serverName)
{
VerifyNonBlankArgument(progID, nameof(progID), "Invalid programmatic identifier (ProgID)");
if (!TryGetCOMType(progID, serverName, out var type))
{
throw new TypeLoadException(FormatInvariant("Could not find a registered class for '{0}'", progID));
}
return type;
}
public static Type GetCOMType(Guid clsid, string serverName)
{
if (!TryGetCOMType(clsid, serverName, out var type))
{
throw new TypeLoadException(FormatInvariant("Could not find a registered class for '{0}'", clsid.ToString("B")));
}
return type;
}
public static bool TryGetCOMType(string progID, string serverName, out Type type)
{
type = Guid.TryParseExact(progID, "B", out var clsid) ? Type.GetTypeFromCLSID(clsid, serverName) : Type.GetTypeFromProgID(progID, serverName);
return type != null;
}
public static bool TryGetCOMType(Guid clsid, string serverName, out Type type)
{
type = Type.GetTypeFromCLSID(clsid, serverName);
return type != null;
}
public static string GetDispIDName(int dispid)
{
return FormatInvariant("[DISPID={0}]", dispid);
}
public static bool IsDispIDName(this string name, out int dispid)
{
var match = dispIDNameRegex.Match(name);
if (match.Success && int.TryParse(match.Groups[1].Value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out dispid))
{
return true;
}
dispid = 0;
return false;
}
#endregion
#region argument helpers
public static void VerifyNonNullArgument(object value, string name)
{
if (value == null)
{
throw new ArgumentNullException(name);
}
}
public static void VerifyNonBlankArgument(string value, string name, string message)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException(message, name);
}
}
#endregion
#region string helpers
private static readonly char[] searchPathSeparators = { ';' };
public static string EnsureNonBlank(string input, string alternate)
{
Debug.Assert(!string.IsNullOrWhiteSpace(alternate));
return string.IsNullOrWhiteSpace(input) ? alternate : input;
}
public static string FormatInvariant(string format, params object[] args)
{
return string.Format(CultureInfo.InvariantCulture, format, args);
}
public static StringBuilder AppendInvariant(this StringBuilder builder, string format, params object[] args)
{
return builder.AppendFormat(CultureInfo.InvariantCulture, format, args);
}
public static string FormatCode(string code)
{
var lines = (code ?? string.Empty).Replace("\r\n", "\n").Split('\n');
lines = lines.SkipWhile(string.IsNullOrWhiteSpace).Reverse().SkipWhile(string.IsNullOrWhiteSpace).Reverse().ToArray();
if (lines.Length > 0)
{
var firstLine = lines[0];
for (var indentLength = firstLine.TakeWhile(char.IsWhiteSpace).Count(); indentLength > 0; indentLength--)
{
var indent = firstLine.Substring(0, indentLength);
if (lines.Skip(1).All(line => string.IsNullOrWhiteSpace(line) || line.StartsWith(indent, StringComparison.Ordinal)))
{
lines = lines.Select(line => string.IsNullOrWhiteSpace(line) ? string.Empty : line.Substring(indent.Length)).ToArray();
break;
}
}
}
return string.Join("\n", lines) + '\n';
}
public static string GetUrlOrPath(Uri uri, string alternate)
{
Debug.Assert(alternate != null);
if (uri == null)
{
return alternate;
}
if (!uri.IsAbsoluteUri)
{
return uri.ToString();
}
if (uri.IsFile)
{
return uri.LocalPath;
}
return uri.AbsoluteUri;
}
public static string ToQuotedJson(this string value)
{
var builder = new StringBuilder();
builder.Append('\"');
foreach (var ch in value)
{
switch (ch)
{
case '\"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
default:
builder.Append(ch);
break;
}
}
builder.Append('\"');
return builder.ToString();
}
public static UIntPtr GetDigest(this string code)
{
return (UIntPtr.Size == 4) ? (UIntPtr)code.GetDigestAsUInt32() : (UIntPtr)code.GetDigestAsUInt64();
}
public static uint GetDigestAsUInt32(this string code)
{
var digest = 2166136261U;
const uint prime = 16777619U;
unchecked
{
var bytes = Encoding.Unicode.GetBytes(code);
for (var index = 0; index < bytes.Length; index++)
{
digest ^= bytes[index];
digest *= prime;
}
}
return digest;
}
public static ulong GetDigestAsUInt64(this string code)
{
var digest = 14695981039346656037UL;
const ulong prime = 1099511628211UL;
var bytes = Encoding.Unicode.GetBytes(code);
for (var index = 0; index < bytes.Length; index++)
{
digest ^= bytes[index];
digest *= prime;
}
return digest;
}
public static IEnumerable<string> SplitSearchPath(this string searchPath)
{
return searchPath.Split(searchPathSeparators, StringSplitOptions.RemoveEmptyEntries).Distinct(StringComparer.OrdinalIgnoreCase);
}
#endregion
#region numeric index helpers
public static bool TryGetNumericIndex(object arg, out int index)
{
if (arg != null)
{
switch (Type.GetTypeCode(arg.GetType()))
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
index = Convert.ToInt32(arg);
return true;
}
}
index = -1;
return false;
}
public static bool TryGetNumericIndex(object arg, out long index)
{
if (arg != null)
{
switch (Type.GetTypeCode(arg.GetType()))
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
index = Convert.ToInt64(arg);
return true;
}
}
index = -1;
return false;
}
#endregion
#region simplified exception handling
public static bool Try(Action action)
{
try
{
action();
return true;
}
catch (Exception)
{
return false;
}
}
public static bool Try<T>(out T result, Func<T> func)
{
try
{
result = func();
return true;
}
catch (Exception)
{
result = default;
return false;
}
}
public static async Task<bool> TryAsync(Task task)
{
try
{
await task.ConfigureAwait(false);
return true;
}
catch (Exception)
{
return false;
}
}
public static async Task<bool> TryAsync<T>(Holder<T> holder, Task<T> task)
{
try
{
holder.Value = await task.ConfigureAwait(false);
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region primitive marshaling
public static bool TryMarshalPrimitiveToHost(object obj, out object result)
{
if (obj is IConvertible convertible)
{
switch (convertible.GetTypeCode())
{
case TypeCode.String:
case TypeCode.Boolean:
result = obj;
return true;
case TypeCode.Double:
case TypeCode.Single:
result = MarshalDoubleToHost(convertible.ToDouble(CultureInfo.InvariantCulture));
return true;
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Char:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Decimal:
result = obj;
return true;
}
}
result = null;
return false;
}
public static object MarshalDoubleToHost(double value)
{
// ReSharper disable CompareOfFloatsByEqualityOperator
if (Math.Round(value) == value)
{
const double maxIntInDouble = (1L << 53) - 1;
if (Math.Abs(value) <= maxIntInDouble)
{
var longValue = Convert.ToInt64(value);
if ((longValue >= int.MinValue) && (longValue <= int.MaxValue))
{
return (int)longValue;
}
return longValue;
}
}
else
{
var floatValue = Convert.ToSingle(value);
if (value == floatValue)
{
return floatValue;
}
}
return value;
// ReSharper restore CompareOfFloatsByEqualityOperator
}
#endregion
#region miscellaneous
public static T Exchange<T>(ref T target, T value)
{
var oldValue = target;
target = value;
return oldValue;
}
public static void QueueNativeCallback(INativeCallback callback)
{
ThreadPool.QueueUserWorkItem(state =>
{
using (callback)
{
Try(callback.Invoke);
}
});
}
public static Random CreateSeededRandom()
{
return new Random(Convert.ToUInt32(DateTime.Now.Ticks.ToUnsigned() & 0x00000000FFFFFFFFUL).ToSigned());
}
public static async Task<IDisposable> CreateLockScopeAsync(this SemaphoreSlim semaphore)
{
await semaphore.WaitAsync().ConfigureAwait(false);
return Scope.Create(null, () => semaphore.Release());
}
public static byte[] ReadToEnd(this Stream stream)
{
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
public static string GetTextContents(this Document document)
{
using (var reader = new StreamReader(document.Contents, document.Encoding ?? Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
public static void AssertUnreachable()
{
Debug.Assert(false, "Entered code block presumed unreachable.");
}
public static string GetLocalDataRootPath(out bool usingAppPath)
{
var basePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
if (string.IsNullOrWhiteSpace(basePath))
{
basePath = AppDomain.CurrentDomain.BaseDirectory;
usingAppPath = true;
}
else
{
usingAppPath = false;
}
return GetLocalDataRootPath(basePath);
}
public static string GetLocalDataRootPath(string basePath)
{
var path = Path.Combine(basePath, "Microsoft", "ClearScript", ClearScriptVersion.Triad, Environment.Is64BitProcess ? "x64" : "x86");
if (Try(out var fullPath, () => Path.GetFullPath(path)))
{
return fullPath;
}
return path;
}
public static bool PlatformIsWindows()
{
return RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
}
public static bool ProcessorArchitectureIsIntel()
{
switch (RuntimeInformation.ProcessArchitecture)
{
case Architecture.X64:
case Architecture.X86:
return true;
default:
return false;
}
}
public static bool ProcessorArchitectureIsArm()
{
switch (RuntimeInformation.ProcessArchitecture)
{
case Architecture.Arm:
case Architecture.Arm64:
return true;
default:
return false;
}
}
#endregion
}
}
| 29.648115 | 154 | 0.499394 | [
"Apache-2.0"
] | komiyamma/hm_ecmascript | ClearWork/ClearScript.7.1.0/ClearScript/Util/MiscHelpers.cs | 16,514 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
namespace WebApplication1.Account
{
public partial class ManagePassword : System.Web.UI.Page
{
protected string SuccessMessage
{
get;
private set;
}
private bool HasPassword(ApplicationUserManager manager)
{
return manager.HasPassword(User.Identity.GetUserId());
}
protected void Page_Load(object sender, EventArgs e)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
if (!IsPostBack)
{
// Determine the sections to render
if (HasPassword(manager))
{
changePasswordHolder.Visible = true;
}
else
{
setPassword.Visible = true;
changePasswordHolder.Visible = false;
}
// Render success message
var message = Request.QueryString["m"];
if (message != null)
{
// Strip the query string from action
Form.Action = ResolveUrl("~/Account/Manage");
}
}
}
protected void ChangePassword_Click(object sender, EventArgs e)
{
if (IsValid)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
IdentityResult result = manager.ChangePassword(User.Identity.GetUserId(), CurrentPassword.Text, NewPassword.Text);
if (result.Succeeded)
{
var user = manager.FindById(User.Identity.GetUserId());
signInManager.SignIn( user, isPersistent: false, rememberBrowser: false);
Response.Redirect("~/Account/Manage?m=ChangePwdSuccess");
}
else
{
AddErrors(result);
}
}
}
protected void SetPassword_Click(object sender, EventArgs e)
{
if (IsValid)
{
// Create the local login info and link the local account to the user
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
IdentityResult result = manager.AddPassword(User.Identity.GetUserId(), password.Text);
if (result.Succeeded)
{
Response.Redirect("~/Account/Manage?m=SetPwdSuccess");
}
else
{
AddErrors(result);
}
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
}
} | 33.857143 | 131 | 0.505425 | [
"MIT"
] | Foxpips/ExamQuestions | WebApplication1/Account/ManagePassword.aspx.cs | 3,320 | C# |
using System;
using System.IO;
using System.Windows.Forms;
namespace Heat_equation.Classes
{
class Calculation
{
public double[,] Unew { get; set; } = null; // Значения температур в узле в (k+1)-ый момент времени
public double[,] U { get; set; } = null; // Значения температур в узле в k-ый момент времени
public int SizeX { get; set; } // Количество узлов по OX
public int SizeY { get; set; } // Количество узлов по OY
public long NumIteration { get; set; } // Номер текущей итерации
public Calculation()
{
SizeX = (int)(Global.Lx / Global.Hx) + 1;
SizeY = (int)(Global.Ly / Global.Hy) + 1;
U = new double[SizeX, SizeY];
Unew = new double[SizeX, SizeY];
NumIteration = 0;
}
// Инициализация начальных значений границ и внутренней области
public void Init()
{
for (int i = 1; i < SizeX - 1; i++)
{
for (int j = 1; j < SizeY - 1; j++)
{
Unew[i, j] = Fx(i * Global.Hx, j * Global.Hy);
}
}
// Пересчет границ
switch (Global.IndexTypeBorders)
{
case 0:
Borders_1();
break;
case 1:
Borders_2();
break;
case 2:
Borders_3();
break;
}
Copy(Unew, U);
}
// Основное итерационное вычисление
public void CalcAll()
{
for (int k = 0; k < Global.LastIteration; k++)
{
SimpleAlgorithm();
//ContourAlgorithm();
Copy(Unew, U);
NumIteration++;
}
}
// Вычисление одной итерации
public void CalcIteration()
{
SimpleAlgorithm();
//ContourAlgorithm();
Copy(Unew, U);
NumIteration++;
}
// Сохранение массива температур в Excel файл
public void SaveState()
{
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.FileName = string.Format("Heat_{0}_Out_{1}", NumIteration, DateTime.Now.Millisecond);
saveFile.Filter = "CSV files (*.csv)|*.csv|XLS files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
if (saveFile.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(saveFile.FileName);
for (int i = 0; i < SizeY; i++)
{
for (int j = 0; j < SizeX; j++)
{
sw.Write(Unew[j, i]);
if (j < SizeX - 1)
sw.Write(";");
}
sw.WriteLine();
}
sw.Close();
}
}
// Напечатать текущее состояние
public void Print(RichTextBox rtb)
{
for (int j = 0; j < SizeY; j++)
{
for (int i = 0; i < SizeX; i++)
{
string str = string.Format("{0:f4}", U[i, j]);
rtb.AppendText(str + " ");
}
rtb.AppendText(Environment.NewLine);
}
}
// Последовательный расчет
private void SimpleAlgorithm()
{
for (int i = 1; i < SizeX - 1; i++)
{
for (int j = 1; j < SizeY - 1; j++)
{
Unew[i, j] = MainFormula(i, j);
}
}
// Пересчет границ
switch (Global.IndexTypeBorders)
{
case 0:
Borders_1();
break;
case 1:
Borders_2();
break;
case 2:
Borders_3();
break;
}
}
// Проход по контурам
private void ContourAlgorithm()
{
// Временные границы для движения к центру пластины
int left = 1;
int up = 1;
int right = SizeX - 1;
int bottom = SizeY - 1;
// Внешний контур
switch (Global.IndexTypeBorders)
{
case 0:
Borders_1();
break;
case 1:
Borders_2();
break;
case 2:
Borders_3();
break;
}
// Внутренние контуры
while ((bottom - up > 1) && (right - left > 1))
{
for (int i = up; i < bottom; i++)
{
Unew[left, i] = MainFormula(left, i);
Unew[right - 1, i] = MainFormula(right - 1, i);
}
for (int i = left; i < right; i++)
{
Unew[i, up] = MainFormula(i, up);
Unew[i, bottom - 1] = MainFormula(i, bottom - 1);
}
// Сдвиг временных границ к центру
left++;
up++;
right--;
bottom--;
}
// Остаток
for (int i = left; i < right; i++)
{
for (int j = up; j < bottom; j++)
{
Unew[i, j] = MainFormula(i, j);
}
}
}
// Копирование массивов
private void Copy(double[,] sourceArr, double[,] destinationArr)
{
for (int i = 0; i < SizeX; i++)
{
for (int j = 0; j < SizeY; j++)
{
destinationArr[i, j] = sourceArr[i, j];
}
}
}
// Основная расчетная формула пятиточечного шаблона
private double MainFormula(int i, int j)
{
return U[i, j] + Global.A * Global.A * Global.Tau *
((U[i + 1, j] + U[i - 1, j] - 2 * U[i, j]) / (Global.Hx * Global.Hx) +
(U[i, j + 1] + U[i, j - 1] - 2 * U[i, j]) / (Global.Hy * Global.Hy));
}
// Рассчет внутренней области
private double Fx(double x = 0.0, double y = 0.0)
{
return 0.0;
}
// Вычисление границ 1-го рода
private void Borders_1()
{
for (int i = 0; i < SizeY; i++)
{
Unew[0, i] = Left_1(0.0, i * Global.Hy);
Unew[SizeX - 1, i] = Right_1(Global.Lx, i * Global.Hy);
}
for (int i = 0; i < SizeX; i++)
{
Unew[i, 0] = Up_1(i * Global.Hx, Global.Ly);
Unew[i, SizeY - 1] = Bottom_1(i * Global.Lx, 0.0);
}
}
// Вычисление границ 2-го рода
private void Borders_2()
{
for (int i = 0; i < SizeY; i++)
{
Unew[0, i] = Left_2(i);
Unew[SizeX - 1, i] = Right_2(i);
}
for (int i = 0; i < SizeX; i++)
{
Unew[i, 0] = Up_2(i);
Unew[i, SizeY - 1] = Bottom_2(i);
}
}
// Вычисление границ 3-го рода
private void Borders_3()
{
// Границы без углов
for (int i = 1; i < SizeY - 1; i++)
{
Unew[0, i] = Left_3(i);
Unew[SizeX - 1, i] = Right_3(i);
}
for (int i = 1; i < SizeX - 1; i++)
{
Unew[i, 0] = Up_3(i);
Unew[i, SizeY - 1] = Bottom_3(i);
}
// Угловые точки
Unew[0, 0] = LeftUp_3(U);
Unew[0, SizeY - 1] = LeftBottom_3(U);
Unew[SizeX - 1, 0] = RightUp_3(U);
Unew[SizeX - 1, SizeY - 1] = RightBottom_3(U);
}
#region Границы 1-го рода
private double Left_1(double x, double y)
{
return Global.T1;
}
private double Up_1(double x, double y)
{
return Global.T2;
}
private double Right_1(double x, double y)
{
return Global.T3;
}
private double Bottom_1(double x, double y)
{
return Global.T4;
}
#endregion
#region Границы 2-го рода
private double Left_2(int i)
{
return U[1, i] + Global.Q1 * Global.Hx / Global.Lamda;
}
private double Up_2(int i)
{
return U[i, 1] + Global.Q2 * Global.Hy / Global.Lamda;
}
private double Right_2(int i)
{
return U[SizeX - 2, i] + Global.Q3 * Global.Hx / Global.Lamda;
}
private double Bottom_2(int i)
{
return U[i, SizeY - 2] + Global.Q4 * Global.Hy / Global.Lamda;
}
#endregion
#region Границы 3-го рода
private double Left_3(int i)
{
return (U[1, i] * Global.Lamda + Global.Alpha1 * Global.Hx * Global.Tout1) / (Global.Lamda + Global.Alpha1 * Global.Hx);
}
private double Up_3(int i)
{
return (U[i, 1] * Global.Lamda + Global.Alpha2 * Global.Hy * Global.Tout2) / (Global.Lamda + Global.Alpha2 * Global.Hy); ;
}
private double Right_3(int i)
{
return (U[SizeX - 2, i] * Global.Lamda + Global.Alpha3 * Global.Hx * Global.Tout3) / (Global.Lamda + Global.Alpha3 * Global.Hx);
}
private double Bottom_3(int i)
{
return (U[i, SizeY - 2] * Global.Lamda + Global.Alpha4 * Global.Hy * Global.Tout4) / (Global.Lamda + Global.Alpha4 * Global.Hy);
}
// Угловые точки
private double LeftUp_3(double[,] T)
{
return 0.5 * ((Global.Lamda * T[1, 0] + Global.Alpha1 * Global.Tout1 * Global.Hx) / (Global.Lamda + Global.Alpha1 * Global.Hx) +
(Global.Lamda * T[0, 1] + Global.Alpha2 * Global.Tout2 * Global.Hy) / (Global.Lamda + Global.Alpha2 * Global.Hy));
}
private double RightUp_3(double[,] T)
{
return 0.5 * ((Global.Lamda * T[SizeX - 1, 1] + Global.Alpha2 * Global.Tout2 * Global.Hy) / (Global.Lamda + Global.Alpha2 * Global.Hy) +
(Global.Lamda * T[SizeX - 2, 0] + Global.Alpha3 * Global.Tout3 * Global.Hx) / (Global.Lamda + Global.Alpha3 * Global.Hx));
}
private double LeftBottom_3(double[,] T)
{
return 0.5 * ((Global.Lamda * T[1, SizeY - 1] + Global.Alpha1 * Global.Tout1 * Global.Hx) / (Global.Lamda + Global.Alpha1 * Global.Hx) +
(Global.Lamda * T[0, SizeY - 2] + Global.Alpha4 * Global.Tout4 * Global.Hy) / (Global.Lamda + Global.Alpha4 * Global.Hy));
}
private double RightBottom_3(double[,] T)
{
return 0.5 * ((Global.Lamda * T[SizeX - 2, SizeY - 1] + Global.Alpha3 * Global.Tout3 * Global.Hx) / (Global.Lamda + Global.Alpha3 * Global.Hx) +
(Global.Lamda * T[SizeX - 1, SizeY - 2] + Global.Alpha4 * Global.Tout4 * Global.Hy) / (Global.Lamda + Global.Alpha4 * Global.Hy));
}
#endregion
}
}
| 31.527473 | 156 | 0.425235 | [
"MIT"
] | vlades7/Heat-equation | Heat-equation/Classes/Calculation.cs | 12,178 | C# |
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using Aop.Api.Domain;
namespace Aop.Api.Response
{
/// <summary>
/// AlipayMsaasMediarecogMmtcaftscvMachinegoodsAddResponse.
/// </summary>
public class AlipayMsaasMediarecogMmtcaftscvMachinegoodsAddResponse : AopResponse
{
/// <summary>
/// 柜内区域状态
/// </summary>
[XmlArray("regions")]
[XmlArrayItem("region_state")]
public List<RegionState> Regions { get; set; }
}
}
| 24.809524 | 85 | 0.660269 | [
"Apache-2.0"
] | Varorbc/alipay-sdk-net-all | AlipaySDKNet/Response/AlipayMsaasMediarecogMmtcaftscvMachinegoodsAddResponse.cs | 533 | C# |
using System.IO;
namespace SoftComputing.UTJ.Presentation.Helpers
{
public static class FileHelper
{
public static void ClearTempDirectory()
{
DirectoryInfo di = new DirectoryInfo("temp");
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
}
}
}
| 21.954545 | 62 | 0.513458 | [
"MIT"
] | kockarevicivan/Soft-Computing---UML-to-JSON | app/SoftComputing.UTJ.Presentation/Helpers/FileHelper.cs | 485 | C# |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Stefan Lange
// Klaus Potzesny
// David Stephensen
//
// Copyright (c) 2001-2019 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using MigraDoc.DocumentObjectModel.Internals;
using MigraDoc.DocumentObjectModel.Visitors;
namespace MigraDoc.DocumentObjectModel
{
/// <summary>
/// Represents a MigraDoc document.
/// </summary>
public sealed class Document : DocumentObject, IVisitable
{
/// <summary>
/// Initializes a new instance of the Document class.
/// </summary>
public Document()
{
_styles = new Styles(this);
}
#region Methods
/// <summary>
/// Creates a deep copy of this object.
/// </summary>
public new Document Clone()
{
return (Document)DeepCopy();
}
/// <summary>
/// Implements the deep copy of the object.
/// </summary>
protected override object DeepCopy()
{
Document document = (Document)base.DeepCopy();
if (document._info != null)
{
document._info = document._info.Clone();
document._info._parent = document;
}
if (document._styles != null)
{
document._styles = document._styles.Clone();
document._styles._parent = document;
}
if (document._sections != null)
{
document._sections = document._sections.Clone();
document._sections._parent = document;
}
return document;
}
/// <summary>
/// Internal function used by renderers to bind this instance to it.
/// </summary>
public void BindToRenderer(object renderer)
{
if (_renderer != null && renderer != null && !ReferenceEquals(_renderer, renderer))
{
throw new InvalidOperationException("The document is already bound to another renderer. " +
"A MigraDoc document can be rendered by only one renderer, because the rendering process " +
"modifies its internal structure. If you want to render a MigraDoc document on different renderers, " +
"you must create a copy of it using the Clone function.");
}
_renderer = renderer;
}
object _renderer;
/// <summary>
/// Indicates whether the document is bound to a renderer. A bound document must not be modified anymore.
/// Modifying it leads to undefined results of the rendering process.
/// </summary>
public bool IsBoundToRenderer
{
get { return _renderer != null; }
}
/// <summary>
/// Adds a new section to the document.
/// </summary>
public Section AddSection()
{
return Sections.AddSection();
}
/// <summary>
/// Adds a new style to the document styles.
/// </summary>
/// <param name="name">Name of the style.</param>
/// <param name="baseStyle">Name of the base style.</param>
public Style AddStyle(string name, string baseStyle)
{
if (name == null || baseStyle == null)
throw new ArgumentNullException(name == null ? "name" : "baseStyle");
if (name == "" || baseStyle == "")
throw new ArgumentException(name == "" ? "name" : "baseStyle");
return Styles.AddStyle(name, baseStyle);
}
/// <summary>
/// Adds a new section to the document.
/// </summary>
public void Add(Section section)
{
Sections.Add(section);
}
/// <summary>
/// Adds a new style to the document styles.
/// </summary>
public void Add(Style style)
{
Styles.Add(style);
}
/// <summary>
/// Adds an embedded file to the document.
/// </summary>
/// <param name="name">The name used to refer and to entitle the embedded file.</param>
/// <param name="path">The path of the file to embed.</param>
public void AddEmbeddedFile(string name, string path)
{
EmbeddedFiles.Add(name, path);
}
#endregion
#region Properties
/// <summary>
/// Gets the last section of the document, or null, if the document has no sections.
/// </summary>
public Section LastSection
{
get
{
return (_sections != null && _sections.Count > 0) ?
_sections.LastObject as Section : null;
}
}
/// <summary>
/// Gets or sets a comment associated with this object.
/// </summary>
public string Comment
{
get { return _comment.Value; }
set { _comment.Value = value; }
}
[DV]
internal NString _comment = NString.NullValue;
/// <summary>
/// Gets the document info.
/// </summary>
public DocumentInfo Info
{
get { return _info ?? (_info = new DocumentInfo(this)); }
set
{
SetParent(value);
_info = value;
}
}
[DV]
internal DocumentInfo _info;
/// <summary>
/// Gets or sets the styles of the document.
/// </summary>
public Styles Styles
{
get { return _styles ?? (_styles = new Styles(this)); }
set
{
SetParent(value);
_styles = value;
}
}
[DV]
internal Styles _styles;
/// <summary>
/// Gets or sets the default tab stop position.
/// </summary>
public Unit DefaultTabStop
{
get { return _defaultTabStop; }
set { _defaultTabStop = value; }
}
[DV]
internal Unit _defaultTabStop = Unit.NullValue;
/// <summary>
/// Gets the default page setup.
/// </summary>
public PageSetup DefaultPageSetup
{
get { return PageSetup.DefaultPageSetup; }
}
/// <summary>
/// Gets or sets the location of the Footnote.
/// </summary>
public FootnoteLocation FootnoteLocation
{
get { return (FootnoteLocation)_footnoteLocation.Value; }
set { _footnoteLocation.Value = (int)value; }
}
[DV(Type = typeof(FootnoteLocation))]
internal NEnum _footnoteLocation = NEnum.NullValue(typeof(FootnoteLocation));
/// <summary>
/// Gets or sets the rule which is used to determine the footnote number on a new page.
/// </summary>
public FootnoteNumberingRule FootnoteNumberingRule
{
get { return (FootnoteNumberingRule)_footnoteNumberingRule.Value; }
set { _footnoteNumberingRule.Value = (int)value; }
}
[DV(Type = typeof(FootnoteNumberingRule))]
internal NEnum _footnoteNumberingRule = NEnum.NullValue(typeof(FootnoteNumberingRule));
/// <summary>
/// Gets or sets the type of number which is used for the footnote.
/// </summary>
public FootnoteNumberStyle FootnoteNumberStyle
{
get { return (FootnoteNumberStyle)_footnoteNumberStyle.Value; }
set { _footnoteNumberStyle.Value = (int)value; }
}
[DV(Type = typeof(FootnoteNumberStyle))]
internal NEnum _footnoteNumberStyle = NEnum.NullValue(typeof(FootnoteNumberStyle));
/// <summary>
/// Gets or sets the starting number of the footnote.
/// </summary>
public int FootnoteStartingNumber
{
get { return _footnoteStartingNumber.Value; }
set { _footnoteStartingNumber.Value = value; }
}
[DV]
internal NInt _footnoteStartingNumber = NInt.NullValue;
/// <summary>
/// Gets or sets the path for images used by the document.
/// </summary>
public string ImagePath
{
get { return _imagePath.Value; }
set { _imagePath.Value = value; }
}
[DV]
internal NString _imagePath = NString.NullValue;
/// <summary>
/// Gets or sets a value indicating whether to use the CMYK color model when rendered as PDF.
/// </summary>
public bool UseCmykColor
{
get { return _useCmykColor.Value; }
set { _useCmykColor.Value = value; }
}
[DV]
internal NBool _useCmykColor = NBool.NullValue;
/// <summary>
/// Gets the sections of the document.
/// </summary>
public Sections Sections
{
get { return _sections ?? (_sections = new Sections(this)); }
set
{
SetParent(value);
_sections = value;
}
}
[DV]
internal Sections _sections;
/// <summary>
/// Gets the embedded documents of the document.
/// </summary>
public EmbeddedFiles EmbeddedFiles
{
get { return _embeddedFiles ?? (_embeddedFiles = new EmbeddedFiles()); }
set
{
SetParent(value);
_embeddedFiles = value;
}
}
[DV]
internal EmbeddedFiles _embeddedFiles;
#endregion
/// <summary>
/// Gets the DDL file name.
/// </summary>
public string DdlFile
{
get { return _ddlFile; }
}
internal string _ddlFile = "";
#region Internal
/// <summary>
/// Converts Document into DDL.
/// </summary>
internal override void Serialize(Serializer serializer)
{
serializer.WriteComment(_comment.Value);
serializer.WriteLine("\\document");
int pos = serializer.BeginAttributes();
if (!IsNull("Info"))
Info.Serialize(serializer);
if (!_defaultTabStop.IsNull)
serializer.WriteSimpleAttribute("DefaultTabStop", DefaultTabStop);
if (!_footnoteLocation.IsNull)
serializer.WriteSimpleAttribute("FootnoteLocation", FootnoteLocation);
if (!_footnoteNumberingRule.IsNull)
serializer.WriteSimpleAttribute("FootnoteNumberingRule", FootnoteNumberingRule);
if (!_footnoteNumberStyle.IsNull)
serializer.WriteSimpleAttribute("FootnoteNumberStyle", FootnoteNumberStyle);
if (!_footnoteStartingNumber.IsNull)
serializer.WriteSimpleAttribute("FootnoteStartingNumber", FootnoteStartingNumber);
if (!_imagePath.IsNull)
serializer.WriteSimpleAttribute("ImagePath", ImagePath);
if (!_useCmykColor.IsNull)
serializer.WriteSimpleAttribute("UseCmykColor", UseCmykColor);
serializer.EndAttributes(pos);
serializer.BeginContent();
if (!IsNull("EmbeddedFiles"))
EmbeddedFiles.Serialize(serializer);
Styles.Serialize(serializer);
if (!IsNull("Sections"))
Sections.Serialize(serializer);
serializer.EndContent();
serializer.Flush();
}
/// <summary>
/// Allows the visitor object to visit the document object and all its child objects.
/// </summary>
void IVisitable.AcceptVisitor(DocumentObjectVisitor visitor, bool visitChildren)
{
visitor.VisitDocument(this);
if (visitChildren)
{
((IVisitable)Styles).AcceptVisitor(visitor, true);
((IVisitable)Sections).AcceptVisitor(visitor, true);
}
}
/// <summary>
/// Returns the meta object of this instance.
/// </summary>
internal override Meta Meta
{
get { return _meta ?? (_meta = new Meta(typeof(Document))); }
}
static Meta _meta;
#endregion
}
}
| 33.638614 | 121 | 0.560854 | [
"MIT"
] | BillyWilloughby/MigraDoc | MigraDoc/src/MigraDoc.DocumentObjectModel/DocumentObjectModel/Document.cs | 13,590 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
namespace TransportsNantais.Views.Partials
{
public partial class DeparturesList : UserControl
{
public DeparturesList()
{
InitializeComponent();
}
}
}
| 20.666667 | 53 | 0.721198 | [
"MIT"
] | mpapillon/NantesTramBus | TransportsNantais/Views/Partials/DeparturesList.xaml.cs | 436 | C# |
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using System.Xml.XPath;
using Web.Service.Areas.HelpPage.ModelDescriptions;
namespace Web.Service.Areas.HelpPage
{
/// <summary>
/// A custom <see cref="IDocumentationProvider"/> that reads the API documentation from an XML documentation file.
/// </summary>
public class XmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider
{
private XPathNavigator _documentNavigator;
private const string TypeExpression = "/doc/members/member[@name='T:{0}']";
private const string MethodExpression = "/doc/members/member[@name='M:{0}']";
private const string PropertyExpression = "/doc/members/member[@name='P:{0}']";
private const string FieldExpression = "/doc/members/member[@name='F:{0}']";
private const string ParameterExpression = "param[@name='{0}']";
/// <summary>
/// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class.
/// </summary>
/// <param name="documentPath">The physical path to XML document.</param>
public XmlDocumentationProvider(string documentPath)
{
if (documentPath == null)
{
throw new ArgumentNullException("documentPath");
}
XPathDocument xpath = new XPathDocument(documentPath);
_documentNavigator = xpath.CreateNavigator();
}
public string GetDocumentation(HttpControllerDescriptor controllerDescriptor)
{
XPathNavigator typeNode = GetTypeNode(controllerDescriptor.ControllerType);
return GetTagValue(typeNode, "summary");
}
public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor)
{
XPathNavigator methodNode = GetMethodNode(actionDescriptor);
return GetTagValue(methodNode, "summary");
}
public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor)
{
ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor;
if (reflectedParameterDescriptor != null)
{
XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor);
if (methodNode != null)
{
string parameterName = reflectedParameterDescriptor.ParameterInfo.Name;
XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName));
if (parameterNode != null)
{
return parameterNode.Value.Trim();
}
}
}
return null;
}
public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor)
{
XPathNavigator methodNode = GetMethodNode(actionDescriptor);
return GetTagValue(methodNode, "returns");
}
public string GetDocumentation(MemberInfo member)
{
string memberName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(member.DeclaringType), member.Name);
string expression = member.MemberType == MemberTypes.Field ? FieldExpression : PropertyExpression;
string selectExpression = String.Format(CultureInfo.InvariantCulture, expression, memberName);
XPathNavigator propertyNode = _documentNavigator.SelectSingleNode(selectExpression);
return GetTagValue(propertyNode, "summary");
}
public string GetDocumentation(Type type)
{
XPathNavigator typeNode = GetTypeNode(type);
return GetTagValue(typeNode, "summary");
}
private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor)
{
ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor;
if (reflectedActionDescriptor != null)
{
string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo));
return _documentNavigator.SelectSingleNode(selectExpression);
}
return null;
}
private static string GetMemberName(MethodInfo method)
{
string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(method.DeclaringType), method.Name);
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length != 0)
{
string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray();
name += String.Format(CultureInfo.InvariantCulture, "({0})", String.Join(",", parameterTypeNames));
}
return name;
}
private static string GetTagValue(XPathNavigator parentNode, string tagName)
{
if (parentNode != null)
{
XPathNavigator node = parentNode.SelectSingleNode(tagName);
if (node != null)
{
return node.Value.Trim();
}
}
return null;
}
private XPathNavigator GetTypeNode(Type type)
{
string controllerTypeName = GetTypeName(type);
string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName);
return _documentNavigator.SelectSingleNode(selectExpression);
}
private static string GetTypeName(Type type)
{
string name = type.FullName;
if (type.IsGenericType)
{
// Format the generic type name to something like: Generic{System.Int32,System.String}
Type genericType = type.GetGenericTypeDefinition();
Type[] genericArguments = type.GetGenericArguments();
string genericTypeName = genericType.FullName;
// Trim the generic parameter counts from the name
genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`'));
string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray();
name = String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", genericTypeName, String.Join(",", argumentTypeNames));
}
if (type.IsNested)
{
// Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax.
name = name.Replace("+", ".");
}
return name;
}
}
}
| 43.37037 | 160 | 0.632223 | [
"MIT"
] | sourcewalker/hexago.net | Source/Web/Web.Service/Areas/HelpPage/XmlDocumentationProvider.cs | 7,026 | C# |
using System;
using System.Collections.ObjectModel;
namespace SampleApp.ViewModels
{
/// <summary>
/// View-model for a pane that shows a list of open documents.
/// </summary>
public class OpenDocumentsPaneViewModel : AbstractPaneViewModel
{
public OpenDocumentsPaneViewModel(MainWindowViewModel mainWindowViewModel)
{
if (mainWindowViewModel == null)
{
throw new ArgumentNullException("mainWindowViewModel");
}
this.MainWindowViewModel = mainWindowViewModel;
this.MainWindowViewModel.ActiveDocumentChanged += new EventHandler<EventArgs>(MainWindowViewModel_ActiveDocumentChanged);
}
/// <summary>
/// View-models for documents.
/// </summary>
public ObservableCollection<TextFileDocumentViewModel> Documents
{
get
{
return this.MainWindowViewModel.Documents;
}
}
/// <summary>
/// View-model for the active document.
/// </summary>
public TextFileDocumentViewModel ActiveDocument
{
get
{
return this.MainWindowViewModel.ActiveDocument;
}
set
{
this.MainWindowViewModel.ActiveDocument = value;
}
}
/// <summary>
/// Close the currently selected document.
/// </summary>
public void CloseSelected()
{
var activeDocument = this.MainWindowViewModel.ActiveDocument;
if (activeDocument != null)
{
this.MainWindowViewModel.Documents.Remove(activeDocument);
}
}
/// <summary>
/// Reference to the main window's view model.
/// </summary>
private MainWindowViewModel MainWindowViewModel
{
get;
set;
}
/// <summary>
/// Event raised when the active document in the main window has changed.
/// </summary>
private void MainWindowViewModel_ActiveDocumentChanged(object sender, EventArgs e)
{
OnPropertyChanged("ActiveDocument");
}
}
}
| 28.884615 | 133 | 0.564137 | [
"MIT"
] | kiler398/OGeneration | ViewModels/OpenDocumentsPaneViewModel.cs | 2,255 | C# |
using System.Collections.Generic;
namespace Spinit.Data.Export
{
public interface IExporter<out TReturn>
{
TReturn Write<T>(IEnumerable<T> list);
}
} | 18.888889 | 46 | 0.688235 | [
"MIT"
] | Spinit-AB/Spin | src/Spinit.Data.Export/IExporter.cs | 170 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
using System;
using System.Collections.Generic;
using System.Text;
using Azure.Core.Http;
namespace Azure.Storage.Files.Models
{
/// <summary>
/// Subset of the directory's properties.
/// </summary>
public class StorageDirectoryInfo
{
internal RawStorageDirectoryInfo _rawStorageDirectoryInfo;
/// <summary>
/// The ETag contains a value which represents the version of the directory, in quotes.
/// </summary>
public ETag ETag => _rawStorageDirectoryInfo.ETag;
/// <summary>
/// Returns the date and time the directory was last modified. Any operation that modifies the directory or
/// its properties updates the last modified time. Operations on files do not affect the last modified time of the directory.
/// </summary>
public DateTimeOffset LastModified => _rawStorageDirectoryInfo.LastModified;
/// <summary>
/// The directory's SMB properties.
/// </summary>
public FileSmbProperties? SmbProperties { get; set; }
internal StorageDirectoryInfo(RawStorageDirectoryInfo rawStorageDirectoryInfo)
{
_rawStorageDirectoryInfo = rawStorageDirectoryInfo;
SmbProperties = new FileSmbProperties(rawStorageDirectoryInfo);
}
}
/// <summary>
/// FilesModelFactory provides utilities for mocking.
/// </summary>
public static partial class FilesModelFactory
{
/// <summary>
/// Creates a new StorageDirectoryInfo instance for mocking.
/// </summary>
public static StorageDirectoryInfo StorageDirectoryInfo(RawStorageDirectoryInfo rawStorageDirectoryInfo)
=> new StorageDirectoryInfo(rawStorageDirectoryInfo);
}
}
| 35.703704 | 133 | 0.682573 | [
"MIT"
] | jarango/azure-sdk-for-net | sdk/storage/Azure.Storage.Files/src/Models/StorageDirectoryInfo.cs | 1,930 | C# |
using System.Linq;
using System.Web.Mvc;
using WebApplication16.Models;
namespace WebApplication16.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
//It fetches Customer data from server
public ActionResult GetData()
{
using (EmployeeContext db = new EmployeeContext())
{
var EmoloyeeData = db.Employees.OrderBy(a => a.Name).ToList();
return Json(new { data = EmoloyeeData }, JsonRequestBehavior.AllowGet);
}
}
}
} | 26.6 | 88 | 0.55188 | [
"MIT"
] | medhajoshi27/AllProjectmedha | WebApplication16/WebApplication16/Controllers/HomeController.cs | 667 | C# |
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;
using CCode.Files;
using CCode.Files.Dtos;
using CCode.Files.DomainService;
using CCode.Files.Authorization;
namespace CCode.Files
{
/// <summary>
/// File应用层服务的接口实现方法
///</summary>
[AbpAuthorize]
public class FileAppService : CCodeAppServiceBase, IFileAppService
{
private readonly IRepository<File, long> _entityRepository;
private readonly IFileManager _entityManager;
/// <summary>
/// 构造函数
///</summary>
public FileAppService(
IRepository<File, long> entityRepository
,IFileManager entityManager
)
{
_entityRepository = entityRepository;
_entityManager=entityManager;
}
/// <summary>
/// 获取File的分页列表信息
///</summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(FilePermissions.Query)]
public async Task<PagedResultDto<FileListDto>> GetPaged(GetFilesInput input)
{
var query = _entityRepository.GetAll();
// TODO:根据传入的参数添加过滤条件
var count = await query.CountAsync();
var entityList = await query
.OrderBy(input.Sorting).AsNoTracking()
.PageBy(input)
.ToListAsync();
// var entityListDtos = ObjectMapper.Map<List<FileListDto>>(entityList);
var entityListDtos =entityList.MapTo<List<FileListDto>>();
return new PagedResultDto<FileListDto>(count,entityListDtos);
}
/// <summary>
/// 通过指定id获取FileListDto信息
/// </summary>
[AbpAuthorize(FilePermissions.Query)]
public async Task<FileListDto> GetById(EntityDto<long> input)
{
var entity = await _entityRepository.GetAsync(input.Id);
return entity.MapTo<FileListDto>();
}
/// <summary>
/// 获取编辑 File
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(FilePermissions.Create,FilePermissions.Edit)]
public async Task<GetFileForEditOutput> GetForEdit(NullableIdDto<long> input)
{
var output = new GetFileForEditOutput();
FileEditDto editDto;
if (input.Id.HasValue)
{
var entity = await _entityRepository.GetAsync(input.Id.Value);
editDto = entity.MapTo<FileEditDto>();
//fileEditDto = ObjectMapper.Map<List<fileEditDto>>(entity);
}
else
{
editDto = new FileEditDto();
}
output.File = editDto;
return output;
}
/// <summary>
/// 添加或者修改File的公共方法
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(FilePermissions.Create,FilePermissions.Edit)]
public async Task CreateOrUpdate(CreateOrUpdateFileInput input)
{
if (input.File.Id.HasValue)
{
await Update(input.File);
}
else
{
await Create(input.File);
}
}
/// <summary>
/// 新增File
/// </summary>
[AbpAuthorize(FilePermissions.Create)]
protected virtual async Task<FileEditDto> Create(FileEditDto input)
{
//TODO:新增前的逻辑判断,是否允许新增
// var entity = ObjectMapper.Map <File>(input);
var entity=input.MapTo<File>();
entity = await _entityRepository.InsertAsync(entity);
return entity.MapTo<FileEditDto>();
}
/// <summary>
/// 编辑File
/// </summary>
[AbpAuthorize(FilePermissions.Edit)]
protected virtual async Task Update(FileEditDto input)
{
//TODO:更新前的逻辑判断,是否允许更新
var entity = await _entityRepository.GetAsync(input.Id.Value);
input.MapTo(entity);
// ObjectMapper.Map(input, entity);
await _entityRepository.UpdateAsync(entity);
}
/// <summary>
/// 删除File信息的方法
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AbpAuthorize(FilePermissions.Delete)]
public async Task Delete(EntityDto<long> input)
{
//TODO:删除前的逻辑判断,是否允许删除
await _entityRepository.DeleteAsync(input.Id);
}
/// <summary>
/// 批量删除File的方法
/// </summary>
[AbpAuthorize(FilePermissions.BatchDelete)]
public async Task BatchDelete(List<long> input)
{
// TODO:批量删除前的逻辑判断,是否允许删除
await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
}
/// <summary>
/// 导出File为excel表,等待开发。
/// </summary>
/// <returns></returns>
//public async Task<FileDto> GetToExcel()
//{
// var users = await UserManager.Users.ToListAsync();
// var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
// await FillRoleNames(userListDtos);
// return _userListExcelExporter.ExportToFile(userListDtos);
//}
}
}
| 22.746479 | 84 | 0.668524 | [
"MIT"
] | AmayerGogh/CCode | aspnet-core/src/CCode.Application/Files/FileApplicationService.cs | 5,145 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rotate : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Rotate(0, 5, 0 * Time.deltaTime);
}
}
| 17.526316 | 52 | 0.633634 | [
"MIT"
] | ReanSchwarzer1/Covid-AR-Shooting-RL | Android Version/Assets/Scripts/Rotate.cs | 333 | C# |
namespace MyVote.Services.AppServer.Models
{
public sealed class ResponseItem
{
public int PollOptionID { get; set; }
public bool IsOptionSelected { get; set; }
}
} | 21.5 | 44 | 0.732558 | [
"Apache-2.0"
] | Magenic/MyVoteGC | src/Services/MyVote.Services.AppServer.Core/Models/ResponseItem.cs | 174 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Vertical.HubSpot.Api.Data;
namespace Vertical.HubSpot.Api.Models {
/// <summary>
/// registry for models of entities
/// </summary>
public class ModelRegistry
{
static readonly Type[] IgnoreAttributes = { typeof(IgnoreDataMemberAttribute), typeof(JsonIgnoreAttribute) };
readonly Dictionary<Type, EntityModel> models=new Dictionary<Type, EntityModel>();
readonly object modellock = new object();
/// <summary>
/// get the entitymodel for a type
/// </summary>
/// <param name="entitytype">type of entity for which to get a model</param>
/// <returns>entity model for the specified entity type</returns>
public EntityModel Get(Type entitytype) {
EntityModel model;
lock (modellock) {
if (models.TryGetValue(entitytype, out model)) return model;
model = new EntityModel();
foreach (PropertyInfo property in entitytype.GetProperties()) {
if(Attribute.IsDefined(property, typeof(HubspotIdAttribute))) {
model.IdProperty = property;
continue;
}
if(Attribute.IsDefined(property, typeof(HubspotDeletedAttribute))) {
model.DeletedProperty = property;
continue;
}
if(IgnoreAttributes.Any(t=> Attribute.IsDefined(property, t)) )
continue;
string mappingname = property.Name.ToLower();
if (Attribute.GetCustomAttribute(property, typeof(NameAttribute)) is NameAttribute name)
mappingname = name.Name;
else if(Attribute.GetCustomAttribute(property, typeof(JsonPropertyAttribute)) is JsonPropertyAttribute jsonProperty)
mappingname = jsonProperty.PropertyName;
model.AddProperty(property, mappingname);
}
models[entitytype] = model;
}
return model;
}
}
} | 37.52459 | 136 | 0.582787 | [
"MIT"
] | loker0/hubspot-api | Vertical.HubSpot.Api/Models/ModelRegistry.cs | 2,291 | C# |
using DotVVM.Framework.Configuration;
using DotVVM.Framework.ResourceManagement;
using DotVVM.Framework.Routing;
using Microsoft.Extensions.DependencyInjection;
namespace FlightFinder.Web
{
public class DotvvmStartup : IDotvvmStartup, IDotvvmServiceConfigurator
{
// For more information about this class, visit https://dotvvm.com/docs/tutorials/basics-project-structure
public void Configure(DotvvmConfiguration config, string applicationPath)
{
ConfigureRoutes(config, applicationPath);
ConfigureControls(config, applicationPath);
ConfigureResources(config, applicationPath);
config.RegisterApiClient(typeof(Api.Client), Startup.FlightsApiUrl, "js/ApiClient.js", "_myApi");
}
private void ConfigureRoutes(DotvvmConfiguration config, string applicationPath)
{
config.RouteTable.Add("Default", "", "Views/Default.dothtml");
config.RouteTable.AutoDiscoverRoutes(new DefaultRouteStrategy(config));
}
private void ConfigureControls(DotvvmConfiguration config, string applicationPath)
{
// register code-only controls and markup controls
config.Markup.AddMarkupControl("cc", "GreyOutZone", "Controls/GreyOutZone.dotcontrol");
config.Markup.AddMarkupControl("cc", "Search", "Controls/Search.dotcontrol");
config.Markup.AddMarkupControl("cc", "SearchResultFlightSegment", "Controls/SearchResultFlightSegment.dotcontrol");
config.Markup.AddMarkupControl("cc", "SearchResults", "Controls/SearchResults.dotcontrol");
config.Markup.AddMarkupControl("cc", "Shortlist", "Controls/Shortlist.dotcontrol");
config.Markup.AddMarkupControl("cc", "ShortlistFlightSegment", "Controls/ShortlistFlightSegment.dotcontrol");
}
private void ConfigureResources(DotvvmConfiguration config, string applicationPath)
{
// register custom resources and adjust paths to the built-in resources
}
public void ConfigureServices(IDotvvmServiceCollection options)
{
options.AddDefaultTempStorages("temp");
}
}
}
| 46.680851 | 127 | 0.706016 | [
"Apache-2.0"
] | mirecad/dotvvm-samples-flight-finder | src/FlightFinder.Web/DotvvmStartup.cs | 2,196 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Betlln.Collections
{
public class KeyValueBag<TValue>
: IEnumerable<KeyValuePair<string, TValue>>
{
private readonly List<KeyValuePair<string, TValue>> _valueStore;
public KeyValueBag()
{
_valueStore = new List<KeyValuePair<string, TValue>>();
}
public IEnumerable<string> Keys
{
get { return _valueStore.Select(x => x.Key); }
}
public IEnumerable<TValue> Values
{
get { return _valueStore.Select(x => x.Value); }
}
public uint Count
{
get { return (uint) _valueStore.Count; }
}
public bool ContainsKey(string keyName)
{
return FindCurrentIndex(keyName) != -1;
}
public void Add(string keyName, TValue value)
{
keyName = NormalizeKeyName(keyName);
int currentIndex = FindCurrentIndex(keyName);
KeyValuePair<string, TValue> item = new KeyValuePair<string, TValue>(keyName, value);
if (currentIndex == -1)
{
_valueStore.Add(item);
}
else
{
_valueStore[currentIndex] = item;
}
}
public TValue this[string keyName]
{
get
{
int currentIndex = FindCurrentIndex(keyName);
if (currentIndex == -1)
{
throw new KeyNotFoundException($"The key \'{keyName}\' does not exist.");
}
return _valueStore[currentIndex].Value;
}
}
public bool TryGetValue(string keyName, out TValue value)
{
int index = FindCurrentIndex(keyName);
if (index >= 0)
{
value = _valueStore[index].Value;
return true;
}
value = default(TValue);
return false;
}
private int FindCurrentIndex(string keyName)
{
keyName = NormalizeKeyName(keyName);
return _valueStore.FindIndex(x => x.Key.Equals(keyName, StringComparison.CurrentCultureIgnoreCase));
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<KeyValuePair<string, TValue>> GetEnumerator()
{
return _valueStore.GetEnumerator();
}
public void Remove(string keyName)
{
int index = FindCurrentIndex(keyName);
if (index >= 0)
{
_valueStore.RemoveAt(index);
}
}
private static string NormalizeKeyName(string keyName)
{
if (string.IsNullOrWhiteSpace(keyName))
{
throw new ArgumentNullException(nameof(keyName));
}
return keyName.Trim();
}
}
} | 26.842105 | 112 | 0.519608 | [
"Apache-2.0"
] | cricut/betlln | Common/Collections/KeyValueBag.cs | 3,062 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft Azure Powershell - Compute Resource Provider")]
[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)]
[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)]
[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: Guid("91792853-487B-4DC2-BE6C-DD09A0A1BC10")]
[assembly: AssemblyVersion("4.24.0")]
[assembly: AssemblyFileVersion("4.24.0")]
#if !SIGN
[assembly: InternalsVisibleTo("Microsoft.Azure.PowerShell.Cmdlets.Compute.Test")]
#endif
| 48.242424 | 104 | 0.696608 | [
"MIT"
] | Hurtrus/azure-powershell | src/Compute/Compute/Properties/AssemblyInfo.cs | 1,560 | C# |
// Zeron - Scheduled Task Application for Windows OS
// Copyright (c) 2019 Jiowcl. All rights reserved.
namespace Zeron.ZInterfaces
{
/// <summary>
/// IServicesRequest
/// </summary>
public interface IServicesRequest
{
/// <summary>
/// APIName
/// </summary>
string APIName { get; }
/// <summary>
/// APIKey
/// </summary>
string APIKey { get; set; }
/// <summary>
/// Command
/// </summary>
string Command { get; set; }
/// <summary>
/// Async
/// </summary>
bool Async { get; set; }
}
}
| 20.25 | 53 | 0.483025 | [
"MIT"
] | inwazy/Zeron | Zeron/ZInterfaces/IServicesRequest.cs | 650 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.