content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using ExtendedXmlSerializer.ContentModel.Content;
using ExtendedXmlSerializer.ContentModel.Reflection;
using ExtendedXmlSerializer.Core;
using ExtendedXmlSerializer.ReflectionModel;
using System.Collections.Generic;
using System.Reflection;
namespace ExtendedXmlSerializer.ExtensionModel.References
{
sealed class ReferencesExtension : TypedTable<MemberInfo>, IEntityMembers, ISerializerExtension
{
public ReferencesExtension() : this(new Dictionary<TypeInfo, MemberInfo>()) {}
public ReferencesExtension(IDictionary<TypeInfo, MemberInfo> store) : base(store) {}
public IServiceRepository Get(IServiceRepository parameter) =>
parameter.Register<IRootReferences, RootReferences>()
.RegisterInstance<IEntityMembers>(this)
.RegisterInstance<IReferenceMaps>(ReferenceMaps.Default)
.Register<IReferenceEncounters, ReferenceEncounters>()
.Register<IEntities, Entities>()
.Decorate<IActivation, ReferenceActivation>()
.Decorate<ISerializers, CircularReferenceEnabledSerialization>()
.Decorate<IContents, ReferenceContents>()
;
void ICommand<IServices>.Execute(IServices parameter) {}
}
} | 41.172414 | 96 | 0.762982 | [
"MIT"
] | ExtendedXmlSerializer/ExtendedXmlSerializer | src/ExtendedXmlSerializer/ExtensionModel/References/ReferencesExtension.cs | 1,194 | C# |
// Decompiled with JetBrains decompiler
// Type: SqlDataProvider.Data.WorldMgrDataInfo
// Assembly: SqlDataProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E6C792E1-372D-46D0-B366-36ACC93C90BB
// Assembly location: C:\Users\Pham Van Hungg\Desktop\Decompiler\Road\SqlDataProvider.dll
using ProtoBuf;
using System.Collections.Generic;
namespace SqlDataProvider.Data
{
[ProtoContract]
public class WorldMgrDataInfo
{
[ProtoMember(1)]
public Dictionary<int, ShopFreeCountInfo> ShopFreeCount;
}
}
| 28.157895 | 89 | 0.781308 | [
"MIT"
] | HuyTruong19x/DDTank4.1 | Source Server/SqlDataProvider/SqlDataProvider/Data/WorldMgrDataInfo.cs | 537 | 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/dwrite.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="IDWriteGdiInterop" /> struct.</summary>
public static unsafe class IDWriteGdiInteropTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="IDWriteGdiInterop" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(IDWriteGdiInterop).GUID, Is.EqualTo(IID_IDWriteGdiInterop));
}
/// <summary>Validates that the <see cref="IDWriteGdiInterop" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IDWriteGdiInterop>(), Is.EqualTo(sizeof(IDWriteGdiInterop)));
}
/// <summary>Validates that the <see cref="IDWriteGdiInterop" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IDWriteGdiInterop).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IDWriteGdiInterop" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IDWriteGdiInterop), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(IDWriteGdiInterop), Is.EqualTo(4));
}
}
}
}
| 37.076923 | 145 | 0.637448 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | tests/Interop/Windows/um/dwrite/IDWriteGdiInteropTests.cs | 1,930 | C# |
using Microsoft.AspNetCore.Components.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace bitandbot.demo.blazor
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IComponentsApplicationBuilder app)
{
app.AddComponent<App>("app");
}
}
}
| 21.333333 | 66 | 0.664063 | [
"MIT"
] | bitjimmy/bitandbot-demo | src/bitandbot.demo.blazor/Startup.cs | 384 | C# |
// Copyright 2013 Cultural Heritage Agency of the Netherlands, Dutch National Military Museum and Trezorix bv
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
using System.Linq;
using Trezorix.Checkers.DocumentChecker.Profiles;
using Trezorix.Checkers.DocumentChecker.SkosSources;
namespace Trezorix.Checkers.ManagerApp
{
public static class BindableSkosSourcesList
{
private static IEnumerable<SkosSourceBinding> _skosSourceBindings;
private static readonly object s_skosSourceBindingLock = new object();
public static IEnumerable<SkosSourceBinding> SkosSourceBindings
{
get
{
if (_skosSourceBindings == null)
lock (s_skosSourceBindingLock)
{
if (_skosSourceBindings == null)
{
_skosSourceBindings = new SkosSourceRepository(ManagerAppConfig.SkosSourceRepositoryPath)
.All()
.Select(ss => new SkosSourceBinding()
{
Key = ss.Entity.Key,
Label = ss.Entity.Label
});
}
}
return _skosSourceBindings;
}
}
}
} | 32.673469 | 110 | 0.714553 | [
"Apache-2.0"
] | Joppe-A/rce-checkers2 | CheckersManager/BindableSkosSourcesList.cs | 1,603 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace Server.Services.Helpers
{
internal static class UriExtensions
{
public static Uri AddParameter(this Uri url, string paramName, string paramValue)
{
var uriBuilder = new UriBuilder(url);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query[paramName] = paramValue;
uriBuilder.Query = query.ToString();
return new Uri(uriBuilder.ToString());
}
}
}
| 26.173913 | 89 | 0.664452 | [
"Apache-2.0"
] | CodeFiction/CodeEksi | Core/Services/Helpers/UriExtensions.cs | 604 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20191101
{
/// <summary>
/// Network profile resource.
/// </summary>
[AzureNextGenResourceType("azure-nextgen:network/v20191101:NetworkProfile")]
public partial class NetworkProfile : Pulumi.CustomResource
{
/// <summary>
/// List of chid container network interface configurations.
/// </summary>
[Output("containerNetworkInterfaceConfigurations")]
public Output<ImmutableArray<Outputs.ContainerNetworkInterfaceConfigurationResponse>> ContainerNetworkInterfaceConfigurations { get; private set; } = null!;
/// <summary>
/// List of child container network interfaces.
/// </summary>
[Output("containerNetworkInterfaces")]
public Output<ImmutableArray<Outputs.ContainerNetworkInterfaceResponse>> ContainerNetworkInterfaces { get; private set; } = null!;
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
[Output("etag")]
public Output<string> Etag { get; private set; } = null!;
/// <summary>
/// Resource location.
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// Resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The provisioning state of the network profile resource.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// The resource GUID property of the network profile resource.
/// </summary>
[Output("resourceGuid")]
public Output<string> ResourceGuid { get; private set; } = null!;
/// <summary>
/// Resource tags.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a NetworkProfile resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public NetworkProfile(string name, NetworkProfileArgs args, CustomResourceOptions? options = null)
: base("azure-nextgen:network/v20191101:NetworkProfile", name, args ?? new NetworkProfileArgs(), MakeResourceOptions(options, ""))
{
}
private NetworkProfile(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-nextgen:network/v20191101:NetworkProfile", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:network:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/latest:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:NetworkProfile"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:NetworkProfile"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing NetworkProfile resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static NetworkProfile Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new NetworkProfile(name, id, options);
}
}
public sealed class NetworkProfileArgs : Pulumi.ResourceArgs
{
[Input("containerNetworkInterfaceConfigurations")]
private InputList<Inputs.ContainerNetworkInterfaceConfigurationArgs>? _containerNetworkInterfaceConfigurations;
/// <summary>
/// List of chid container network interface configurations.
/// </summary>
public InputList<Inputs.ContainerNetworkInterfaceConfigurationArgs> ContainerNetworkInterfaceConfigurations
{
get => _containerNetworkInterfaceConfigurations ?? (_containerNetworkInterfaceConfigurations = new InputList<Inputs.ContainerNetworkInterfaceConfigurationArgs>());
set => _containerNetworkInterfaceConfigurations = value;
}
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// Resource location.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The name of the network profile.
/// </summary>
[Input("networkProfileName")]
public Input<string>? NetworkProfileName { get; set; }
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public NetworkProfileArgs()
{
}
}
}
| 43.682292 | 175 | 0.608799 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Network/V20191101/NetworkProfile.cs | 8,387 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ThinkingHome.Plugins.WebUI.Lang {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class AppLang {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal AppLang() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ThinkingHome.Plugins.WebUI.Lang.AppLang", typeof(AppLang).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to en.
/// </summary>
internal static string Lang {
get {
return ResourceManager.GetString("Lang", resourceCulture);
}
}
}
}
| 41.931507 | 182 | 0.600457 | [
"MIT"
] | dima117/thinking-home | ThinkingHome.Plugins.WebUI/Lang/AppLang.Designer.cs | 3,063 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Data.Models;
using System.Threading;
namespace WinFormsView.ParentControls
{
public partial class ParentContactTeacherControl : UserControl
{
public ParentContactTeacherControl(Teacher teacher,string language)
{
if (language == "English")
{
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("aa");
}
else
{
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("bg-BG");
}
InitializeComponent();
firstNameTextBox.Text = teacher.FirstName;
lastNameTextBox.Text = teacher.LastName;
emailTextBox.Text = teacher.Email;
phoneNumberTextBox.Text = teacher.PhoneNumber;
}
}
}
| 28.916667 | 102 | 0.6561 | [
"MIT"
] | kristiyanyanchev/It-Kariera-Software-Development-Project | Kristiyan_Yanchev_Lorenzo_Eccheli/Kristiyan_Yanchev_Lorenzo_Eccheli/ParentControls/ParentContactTeacherControl.cs | 1,043 | C# |
using System.Runtime.Serialization;
using GadzhiCommon.Enums.LibraryData;
using GadzhiCommon.Models.Interfaces.LibraryData;
namespace GadzhiDTOBase.TransferModels.Signatures
{
/// <summary>
/// Информация о пользователе. Трансферная модель
/// </summary>
[DataContract]
public class PersonInformationDto: IPersonInformation
{
public PersonInformationDto(string surname, string name, string patronymic, DepartmentType departmentType)
{
Surname = surname;
Name = name;
Patronymic = patronymic;
DepartmentType = departmentType;
}
/// <summary>
/// Фамилия
/// </summary>
[DataMember]
public string Surname { get; private set; }
/// <summary>
/// Имя
/// </summary>
[DataMember]
public string Name { get; private set; }
/// <summary>
/// Отчество
/// </summary>
[DataMember]
public string Patronymic { get; private set; }
/// <summary>
/// Отдел
/// </summary>
[DataMember]
public DepartmentType DepartmentType { get; private set; }
}
} | 27.6 | 115 | 0.558776 | [
"MIT"
] | rubilnik4/GadzhiResurrected | GadzhiDTOBase/TransferModels/Signatures/PersonInformationDto.cs | 1,307 | C# |
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
/// Delete a system-level Application Server alias from the system.
/// The response is either SuccessResponse or ErrorResponse.
/// <see cref="SuccessResponse"/>
/// <see cref="ErrorResponse"/>
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""7f663d5135470c33ca64b0eed3c3aa0c:2218""}]")]
public class SystemAliasDeleteRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest<BroadWorksConnector.Ocip.Models.C.SuccessResponse>
{
private string _aliasNetAddress;
[XmlElement(ElementName = "aliasNetAddress", IsNullable = false, Namespace = "")]
[Group(@"7f663d5135470c33ca64b0eed3c3aa0c:2218")]
[MinLength(1)]
[MaxLength(80)]
public string AliasNetAddress
{
get => _aliasNetAddress;
set
{
AliasNetAddressSpecified = true;
_aliasNetAddress = value;
}
}
[XmlIgnore]
protected bool AliasNetAddressSpecified { get; set; }
}
}
| 31.348837 | 139 | 0.653561 | [
"MIT"
] | cwmiller/broadworks-connector-net | BroadworksConnector/Ocip/Models/SystemAliasDeleteRequest.cs | 1,348 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace JitInterface
{
public static unsafe partial class ClrJit
{
[Flags]
public enum CorJitFlag : uint
{
SPEED_OPT = 0x00000001,
SIZE_OPT = 0x00000002,
DEBUG_CODE = 0x00000004,
DEBUG_EnC = 0x00000008,
DEBUG_INFO = 0x00000010,
MIN_OPT = 0x00000020,
GCPOLL_CALLS = 0x00000040,
MCJIT_BACKGROUND = 0x00000080,
UNUSED1 = 0x00000100,
UNUSED2 = 0x00000200,
UNUSED3 = 0x00000400,
UNUSED4 = 0x00000800,
UNUSED5 = 0x00001000,
UNUSED6 = 0x00002000,
MAKEFINALCODE = 0x00008000,
READYTORUN = 0x00010000,
PROF_ENTERLEAVE = 0x00020000,
PROF_REJIT_NOPS = 0x00040000,
PROF_NO_PINVOKE_INLINE
= 0x00080000,
SKIP_VERIFICATION = 0x00100000,
PREJIT = 0x00200000,
RELOC = 0x00400000,
IMPORT_ONLY = 0x00800000,
IL_STUB = 0x01000000,
PROCSPLIT = 0x02000000,
BBINSTR = 0x04000000,
BBOPT = 0x08000000,
FRAMED = 0x10000000,
ALIGN_LOOPS = 0x20000000,
PUBLISH_SECRET_PARAM = 0x40000000,
GCPOLL_INLINE = 0x80000000,
};
public enum CorJitResult : uint
{
OK = 0,
BADCODE = 1,
OUTOFMEM = 2,
INTERNALERROR = 3,
SKIPPED = 4,
RECOVERABLEERROR = 5,
};
[Flags]
public enum CorInfoOptions
{
OPT_INIT_LOCALS = 0x00000010,
GENERICS_CTXT_FROM_THIS = 0x00000020,
GENERICS_CTXT_FROM_METHODDESC = 0x00000040,
GENERICS_CTXT_FROM_METHODTABLE = 0x00000080,
GENERICS_CTXT_MASK = (GENERICS_CTXT_FROM_THIS |
GENERICS_CTXT_FROM_METHODDESC |
GENERICS_CTXT_FROM_METHODTABLE),
GENERICS_CTXT_KEEP_ALIVE = 0x00000100,
}
[Flags]
public enum CorInfoRegionKind
{
NONE,
HOT,
COLD,
JIT,
}
[Flags]
public enum CorInfoCallConv
{
DEFAULT = 0x0,
C = 0x1,
STDCALL = 0x2,
THISCALL = 0x3,
FASTCALL = 0x4,
VARARG = 0x5,
FIELD = 0x6,
LOCAL_SIG = 0x7,
PROPERTY = 0x8,
NATIVEVARARG = 0xb,
MASK = 0x0f,
GENERIC = 0x10,
HASTHIS = 0x20,
EXPLICITTHIS = 0x40,
PARAMTYPE = 0x80,
};
public enum CorInfoType
{
UNDEF = 0x0,
VOID = 0x1,
BOOL = 0x2,
CHAR = 0x3,
BYTE = 0x4,
UBYTE = 0x5,
SHORT = 0x6,
USHORT = 0x7,
INT = 0x8,
UINT = 0x9,
LONG = 0xa,
ULONG = 0xb,
NATIVEINT = 0xc,
NATIVEUINT = 0xd,
FLOAT = 0xe,
DOUBLE = 0xf,
STRING = 0x10,
PTR = 0x11,
BYREF = 0x12,
VALUECLASS = 0x13,
CLASS = 0x14,
REFANY = 0x15,
VAR = 0x16,
COUNT,
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CORINFO_METHOD_INFO
{
public IntPtr methodHandle;
public IntPtr moduleHandle;
public byte* ILCode;
public uint ILCodeSize;
public ushort maxStack;
public ushort EHcount;
public CorInfoOptions options;
public CorInfoRegionKind regionKind;
// TODO: add support for 32-bit and 64-bit apps.
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CORINFO_SIG_INFO
{
public CorInfoCallConv callConv;
public IntPtr retTypeClass;
public IntPtr retTypeSigClass;
public CorInfoType retType;
public uint flags;
public uint numArgs;
public CORINFO_SIG_INST sigInst;
public IntPtr args;
public IntPtr pSig;
public uint cbSig;
public IntPtr scope;
public uint token;
};
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CORINFO_SIG_INST
{
uint classInstCount;
IntPtr* classInst;
uint methInstCount;
IntPtr* methInst;
};
}
}
| 27.38764 | 66 | 0.493538 | [
"MIT"
] | FenixDan/JitInterface | JitInterface/ClrJit.cs | 4,877 | C# |
using UnityEngine;
using System.Collections;
public class WFX_RealtimeReflection : MonoBehaviour {
#if UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6
#else
ReflectionProbe probe;
private Transform camT;
void Awake()
{
probe = GetComponent<ReflectionProbe>();
camT = Camera.main.transform;
}
void Update()
{
var pos = camT.position;
probe.transform.position = new Vector3(
pos.x,
pos.y * -1,
pos.z
);
probe.RenderProbe();
}
#endif
}
| 19.655172 | 67 | 0.584211 | [
"Apache-2.0"
] | rasbot/9_to_5_Smash_It_AI | Project/Assets/KriptoFX/WeaponEffects/Scene/Other/WFX_RealtimeReflection.cs | 572 | C# |
using System.Xml.Linq;
namespace DefaultDocumentation.Api
{
public interface IElement
{
string Name { get; }
void Write(IWriter writer, XElement element);
}
}
| 15.833333 | 53 | 0.647368 | [
"MIT-0"
] | IdkGoodName/DefaultDocumentation | source/DefaultDocumentation.Api/Api/IElement.cs | 192 | C# |
using System.Collections.Generic;
namespace Project0.StoreApplication.Domain.Models
{
public class PanaceaStore : Store
{
public PanaceaStore()
{
Name = "Panacea Store";
Location = "X Ave, Uptobia";
Products = new List<Product>(){
new Product(){
Name ="万灵药",
Price = 50
}
};
}
}
} | 16.454545 | 49 | 0.555249 | [
"MIT"
] | 08162021-dotnet-uta/CaseyPengRepo01 | projects/project_0/Project0.StoreApplication.Domain/Models/PanaceaStore.cs | 368 | C# |
// MIT License
// Copyright (c) 2018 Felix Lange
// 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.Collections.Generic;
using UnityEngine;
using System.Linq;
namespace RecordAndRepeat
{
public class Recording : RecordingBase
{
[SerializeField]
private List<DataFrame> frames = new List<DataFrame>();
public override void Add(IDataFrame frame)
{
frames.Add((DataFrame)frame);
}
protected override IEnumerable<IDataFrame> ConvertDataFrames()
{
return frames.Cast<IDataFrame>();
}
public override int Count()
{
return frames.Count();
}
}
} | 34.918367 | 81 | 0.708358 | [
"MIT"
] | fx-lange/unity-record-and-repeat | Source/Recording/Recording.cs | 1,711 | C# |
using System;
using System.Threading;
using Content.Server.Chat.Managers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Timer = Robust.Shared.Timing.Timer;
namespace Content.Server.GameTicking.Rules
{
public sealed class RuleMaxTimeRestart : GameRule
{
[Dependency] private readonly IChatManager _chatManager = default!;
[Dependency] private readonly IEntityManager _entityManager = default!;
private CancellationTokenSource _timerCancel = new();
public TimeSpan RoundMaxTime { get; set; } = TimeSpan.FromMinutes(5);
public TimeSpan RoundEndDelay { get; set; } = TimeSpan.FromSeconds(10);
public override void Added()
{
base.Added();
_entityManager.EventBus.SubscribeEvent<GameRunLevelChangedEvent>(EventSource.Local, this, RunLevelChanged);
}
public override void Removed()
{
base.Removed();
_entityManager.EventBus.UnsubscribeEvents(this);
StopTimer();
}
public void RestartTimer()
{
_timerCancel.Cancel();
_timerCancel = new CancellationTokenSource();
Timer.Spawn(RoundMaxTime, TimerFired, _timerCancel.Token);
}
public void StopTimer()
{
_timerCancel.Cancel();
}
private void TimerFired()
{
EntitySystem.Get<GameTicker>().EndRound(Loc.GetString("rule-time-has-run-out"));
_chatManager.DispatchServerAnnouncement(Loc.GetString("rule-restarting-in-seconds",("seconds", (int) RoundEndDelay.TotalSeconds)));
Timer.Spawn(RoundEndDelay, () => EntitySystem.Get<GameTicker>().RestartRound());
}
private void RunLevelChanged(GameRunLevelChangedEvent args)
{
switch (args.New)
{
case GameRunLevel.InRound:
RestartTimer();
break;
case GameRunLevel.PreRoundLobby:
case GameRunLevel.PostRound:
StopTimer();
break;
}
}
}
}
| 30.305556 | 143 | 0.606783 | [
"MIT"
] | A-Box-12/space-station-14 | Content.Server/GameTicking/Rules/RuleMaxTimeRestart.cs | 2,182 | C# |
using WDE.Common.Types;
using WDE.Module.Attributes;
namespace WDE.Common.Solution
{
[NonUniqueProvider]
public interface ISolutionItemIconProvider
{
}
public interface ISolutionItemIconProvider<in T> : ISolutionItemIconProvider where T : ISolutionItem
{
ImageUri GetIcon(T icon);
}
} | 21.733333 | 104 | 0.714724 | [
"Unlicense"
] | BAndysc/WoWDatabaseEditor | WoWDatabaseEditor.Common/WDE.Common/Solution/ISolutionItemIconProvider.cs | 326 | 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.Linq;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp
{
[UseExportProvider]
public abstract class AbstractSignatureHelpProviderTests<TWorkspaceFixture> : TestBase
where TWorkspaceFixture : TestWorkspaceFixture, new()
{
private readonly TestFixtureHelper<TWorkspaceFixture> _fixtureHelper = new();
internal abstract Type GetSignatureHelpProviderType();
private protected ReferenceCountedDisposable<TWorkspaceFixture> GetOrCreateWorkspaceFixture()
=> _fixtureHelper.GetOrCreateFixture();
/// <summary>
/// Verifies that sighelp comes up at the indicated location in markup ($$), with the indicated span [| ... |].
/// </summary>
/// <param name="markup">Input markup with $$ denoting the cursor position, and [| ... |]
/// denoting the expected sighelp span</param>
/// <param name="expectedOrderedItemsOrNull">The exact expected sighelp items list. If null, this part of the test is ignored.</param>
/// <param name="usePreviousCharAsTrigger">If true, uses the last character before $$ to trigger sighelp.
/// If false, invokes sighelp explicitly at the cursor location.</param>
/// <param name="sourceCodeKind">The sourcecodekind to run this test on. If null, runs on both regular and script sources.</param>
protected virtual async Task TestAsync(
string markup,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null,
bool usePreviousCharAsTrigger = false,
SourceCodeKind? sourceCodeKind = null,
bool experimental = false)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
if (sourceCodeKind.HasValue)
{
await TestSignatureHelpWorkerAsync(markup, sourceCodeKind.Value, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
}
else
{
await TestSignatureHelpWorkerAsync(markup, SourceCodeKind.Regular, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
await TestSignatureHelpWorkerAsync(markup, SourceCodeKind.Script, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
}
}
private async Task TestSignatureHelpWorkerAsync(
string markupWithPositionAndOptSpan,
SourceCodeKind sourceCodeKind,
bool experimental,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null,
bool usePreviousCharAsTrigger = false)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
markupWithPositionAndOptSpan = markupWithPositionAndOptSpan.NormalizeLineEndings();
TextSpan? textSpan = null;
MarkupTestFile.GetPositionAndSpans(
markupWithPositionAndOptSpan,
out var code,
out var cursorPosition,
out ImmutableArray<TextSpan> textSpans);
if (textSpans.Any())
{
textSpan = textSpans.First();
}
var parseOptions = CreateExperimentalParseOptions();
// regular
var document1 = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind);
if (experimental)
{
document1 = document1.Project.WithParseOptions(parseOptions).GetDocument(document1.Id);
}
await TestSignatureHelpWorkerSharedAsync(workspaceFixture.Target.GetWorkspace(), code, cursorPosition, document1, textSpan, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
// speculative semantic model
if (await CanUseSpeculativeSemanticModelAsync(document1, cursorPosition))
{
var document2 = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind, cleanBeforeUpdate: false);
if (experimental)
{
document2 = document2.Project.WithParseOptions(parseOptions).GetDocument(document2.Id);
}
await TestSignatureHelpWorkerSharedAsync(workspaceFixture.Target.GetWorkspace(), code, cursorPosition, document2, textSpan, expectedOrderedItemsOrNull, usePreviousCharAsTrigger);
}
}
protected abstract ParseOptions CreateExperimentalParseOptions();
private static async Task<bool> CanUseSpeculativeSemanticModelAsync(Document document, int position)
{
var service = document.GetLanguageService<ISyntaxFactsService>();
var node = (await document.GetSyntaxRootAsync()).FindToken(position).Parent;
return !service.GetMemberBodySpanForSpeculativeBinding(node).IsEmpty;
}
protected void VerifyTriggerCharacters(char[] expectedTriggerCharacters, char[] unexpectedTriggerCharacters)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
var signatureHelpProviderType = GetSignatureHelpProviderType();
var signatureHelpProvider = workspaceFixture.Target.GetWorkspace().ExportProvider.GetExportedValues<ISignatureHelpProvider>().Single(provider => provider.GetType() == signatureHelpProviderType);
foreach (var expectedTriggerCharacter in expectedTriggerCharacters)
{
Assert.True(signatureHelpProvider.IsTriggerCharacter(expectedTriggerCharacter), "Expected '" + expectedTriggerCharacter + "' to be a trigger character");
}
foreach (var unexpectedTriggerCharacter in unexpectedTriggerCharacters)
{
Assert.False(signatureHelpProvider.IsTriggerCharacter(unexpectedTriggerCharacter), "Expected '" + unexpectedTriggerCharacter + "' to NOT be a trigger character");
}
}
protected virtual async Task VerifyCurrentParameterNameAsync(string markup, string expectedParameterName, SourceCodeKind? sourceCodeKind = null)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
if (sourceCodeKind.HasValue)
{
await VerifyCurrentParameterNameWorkerAsync(markup, expectedParameterName, sourceCodeKind.Value);
}
else
{
await VerifyCurrentParameterNameWorkerAsync(markup, expectedParameterName, SourceCodeKind.Regular);
await VerifyCurrentParameterNameWorkerAsync(markup, expectedParameterName, SourceCodeKind.Script);
}
}
private static async Task<SignatureHelpState> GetArgumentStateAsync(int cursorPosition, Document document, ISignatureHelpProvider signatureHelpProvider, SignatureHelpTriggerInfo triggerInfo)
{
var items = await signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None);
return items == null ? null : new SignatureHelpState(items.ArgumentIndex, items.ArgumentCount, items.ArgumentName, null);
}
private async Task VerifyCurrentParameterNameWorkerAsync(string markup, string expectedParameterName, SourceCodeKind sourceCodeKind)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
MarkupTestFile.GetPosition(markup.NormalizeLineEndings(), out var code, out int cursorPosition);
var document = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind);
var signatureHelpProviderType = GetSignatureHelpProviderType();
var signatureHelpProvider = workspaceFixture.Target.GetWorkspace().ExportProvider.GetExportedValues<ISignatureHelpProvider>().Single(provider => provider.GetType() == signatureHelpProviderType);
var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand);
_ = await signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None);
Assert.Equal(expectedParameterName, (await GetArgumentStateAsync(cursorPosition, document, signatureHelpProvider, triggerInfo)).ArgumentName);
}
private static void CompareAndAssertCollectionsAndCurrentParameter(
IEnumerable<SignatureHelpTestItem> expectedTestItems, SignatureHelpItems actualSignatureHelpItems)
{
Assert.Equal(expectedTestItems.Count(), actualSignatureHelpItems.Items.Count());
for (var i = 0; i < expectedTestItems.Count(); i++)
{
CompareSigHelpItemsAndCurrentPosition(
actualSignatureHelpItems,
actualSignatureHelpItems.Items.ElementAt(i),
expectedTestItems.ElementAt(i));
}
}
private static void CompareSigHelpItemsAndCurrentPosition(
SignatureHelpItems items,
SignatureHelpItem actualSignatureHelpItem,
SignatureHelpTestItem expectedTestItem)
{
var currentParameterIndex = -1;
if (expectedTestItem.CurrentParameterIndex != null)
{
if (expectedTestItem.CurrentParameterIndex.Value >= 0 && expectedTestItem.CurrentParameterIndex.Value < actualSignatureHelpItem.Parameters.Length)
{
currentParameterIndex = expectedTestItem.CurrentParameterIndex.Value;
}
}
var signature = new Signature(applicableToSpan: null, signatureHelpItem: actualSignatureHelpItem, selectedParameterIndex: currentParameterIndex);
// We're a match if the signature matches...
// We're now combining the signature and documentation to make classification work.
if (!string.IsNullOrEmpty(expectedTestItem.MethodDocumentation))
{
Assert.Equal(expectedTestItem.Signature + "\r\n" + expectedTestItem.MethodDocumentation, signature.Content);
}
else
{
Assert.Equal(expectedTestItem.Signature, signature.Content);
}
if (expectedTestItem.PrettyPrintedSignature != null)
{
Assert.Equal(expectedTestItem.PrettyPrintedSignature, signature.PrettyPrintedContent);
}
if (expectedTestItem.MethodDocumentation != null)
{
Assert.Equal(expectedTestItem.MethodDocumentation, actualSignatureHelpItem.DocumentationFactory(CancellationToken.None).GetFullText());
}
if (expectedTestItem.ParameterDocumentation != null)
{
Assert.Equal(expectedTestItem.ParameterDocumentation, signature.CurrentParameter.Documentation);
}
if (expectedTestItem.CurrentParameterIndex != null)
{
Assert.Equal(expectedTestItem.CurrentParameterIndex, items.ArgumentIndex);
}
if (expectedTestItem.Description != null)
{
Assert.Equal(expectedTestItem.Description, ToString(actualSignatureHelpItem.DescriptionParts));
}
}
private static string ToString(IEnumerable<TaggedText> list)
=> string.Concat(list.Select(i => i.ToString()));
protected async Task TestSignatureHelpInEditorBrowsableContextsAsync(
string markup,
string referencedCode,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsMetadataReference,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsSameSolution,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers = false)
{
if (expectedOrderedItemsMetadataReference == null || expectedOrderedItemsSameSolution == null)
{
AssertEx.Fail("Expected signature help items must be provided for EditorBrowsable tests. If there are no expected items, provide an empty IEnumerable rather than null.");
}
await TestSignatureHelpWithMetadataReferenceHelperAsync(markup, referencedCode, expectedOrderedItemsMetadataReference, sourceLanguage, referencedLanguage, hideAdvancedMembers);
await TestSignatureHelpWithProjectReferenceHelperAsync(markup, referencedCode, expectedOrderedItemsSameSolution, sourceLanguage, referencedLanguage, hideAdvancedMembers);
// Multi-language projects are not supported.
if (sourceLanguage == referencedLanguage)
{
await TestSignatureHelpInSameProjectHelperAsync(markup, referencedCode, expectedOrderedItemsSameSolution, sourceLanguage, hideAdvancedMembers);
}
}
public Task TestSignatureHelpWithMetadataReferenceHelperAsync(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</MetadataReferenceFromSource>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
return VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers);
}
public async Task TestSignatureHelpWithProjectReferenceHelperAsync(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<ProjectReference>ReferencedProject</ProjectReference>
<Document FilePath=""SourceDocument"">
{1}
</Document>
</Project>
<Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
await VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers);
}
private async Task TestSignatureHelpInSameProjectHelperAsync(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<Document FilePath=""ReferencedDocument"">
{2}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode));
await VerifyItemWithReferenceWorkerAsync(xmlString, expectedOrderedItems, hideAdvancedMembers);
}
protected async Task VerifyItemWithReferenceWorkerAsync(string xmlString, IEnumerable<SignatureHelpTestItem> expectedOrderedItems, bool hideAdvancedMembers)
{
using var testWorkspace = TestWorkspace.Create(xmlString);
var cursorPosition = testWorkspace.Documents.First(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = testWorkspace.Documents.First(d => d.Name == "SourceDocument").Id;
var document = testWorkspace.CurrentSolution.GetDocument(documentId);
testWorkspace.TryApplyChanges(testWorkspace.CurrentSolution.WithOptions(testWorkspace.Options
.WithChangedOption(CompletionOptions.HideAdvancedMembers, document.Project.Language, hideAdvancedMembers)));
document = testWorkspace.CurrentSolution.GetDocument(documentId);
var code = (await document.GetTextAsync()).ToString();
IList<TextSpan> textSpans = null;
var selectedSpans = testWorkspace.Documents.First(d => d.Name == "SourceDocument").SelectedSpans;
if (selectedSpans.Any())
{
textSpans = selectedSpans;
}
TextSpan? textSpan = null;
if (textSpans != null && textSpans.Any())
{
textSpan = textSpans.First();
}
await TestSignatureHelpWorkerSharedAsync(testWorkspace, code, cursorPosition, document, textSpan, expectedOrderedItems);
}
private async Task TestSignatureHelpWorkerSharedAsync(
TestWorkspace workspace,
string code,
int cursorPosition,
Document document,
TextSpan? textSpan,
IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null,
bool usePreviousCharAsTrigger = false)
{
var signatureHelpProviderType = GetSignatureHelpProviderType();
var signatureHelpProvider = workspace.ExportProvider.GetExportedValues<ISignatureHelpProvider>().Single(provider => provider.GetType() == signatureHelpProviderType);
var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand);
if (usePreviousCharAsTrigger)
{
triggerInfo = new SignatureHelpTriggerInfo(
SignatureHelpTriggerReason.TypeCharCommand,
code.ElementAt(cursorPosition - 1));
if (!signatureHelpProvider.IsTriggerCharacter(triggerInfo.TriggerCharacter.Value))
{
return;
}
}
var items = await signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None);
// If we're expecting 0 items, then there's no need to compare them
if ((expectedOrderedItemsOrNull == null || !expectedOrderedItemsOrNull.Any()) && items == null)
{
return;
}
AssertEx.NotNull(items, "Signature help provider returned null for items. Did you forget $$ in the test or is the test otherwise malformed, e.g. quotes not escaped?");
// Verify the span
if (textSpan != null)
{
Assert.Equal(textSpan, items.ApplicableSpan);
}
if (expectedOrderedItemsOrNull != null)
{
CompareAndAssertCollectionsAndCurrentParameter(expectedOrderedItemsOrNull, items);
CompareSelectedIndex(expectedOrderedItemsOrNull, items.SelectedItemIndex);
}
}
private static void CompareSelectedIndex(IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull, int? selectedItemIndex)
{
if (expectedOrderedItemsOrNull == null ||
!expectedOrderedItemsOrNull.Any(i => i.IsSelected))
{
return;
}
Assert.True(expectedOrderedItemsOrNull.Count(i => i.IsSelected) == 1, "Only one expected item can be marked with 'IsSelected'");
Assert.True(selectedItemIndex != null, "Expected an item to be selected, but no item was actually selected");
var counter = 0;
foreach (var item in expectedOrderedItemsOrNull)
{
if (item.IsSelected)
{
Assert.True(selectedItemIndex == counter,
$"Expected item with index {counter} to be selected, but the actual selected index is {selectedItemIndex}.");
}
else
{
Assert.True(selectedItemIndex != counter,
$"Found unexpected selected item. Actual selected index is {selectedItemIndex}.");
}
counter++;
}
}
protected async Task TestSignatureHelpWithMscorlib45Async(
string markup,
IEnumerable<SignatureHelpTestItem> expectedOrderedItems,
string sourceLanguage)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferencesNet45=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(markup));
using var testWorkspace = TestWorkspace.Create(xmlString);
var cursorPosition = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = testWorkspace.Documents.Where(d => d.Name == "SourceDocument").Single().Id;
var document = testWorkspace.CurrentSolution.GetDocument(documentId);
var code = (await document.GetTextAsync()).ToString();
IList<TextSpan> textSpans = null;
var selectedSpans = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").SelectedSpans;
if (selectedSpans.Any())
{
textSpans = selectedSpans;
}
TextSpan? textSpan = null;
if (textSpans != null && textSpans.Any())
{
textSpan = textSpans.First();
}
await TestSignatureHelpWorkerSharedAsync(testWorkspace, code, cursorPosition, document, textSpan, expectedOrderedItems);
}
}
}
| 47.582463 | 206 | 0.666243 | [
"Apache-2.0"
] | cshung/roslyn | src/EditorFeatures/TestUtilities/SignatureHelp/AbstractSignatureHelpProviderTests.cs | 22,794 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.IO;
using System.Configuration;
namespace SSTDeskBooks.english.atrium.content_manager
{
public partial class SAMStructure : System.Web.UI.Page
{
atriumBE.HelpManager atBEHelp;
atriumDAL.atriumDALManager atDal;
private string XSLT_PATH_COMMON = System.Configuration.ConfigurationManager.AppSettings["XSLT_PATH_COMMON"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
SetPageTitle();
atriumBE.AtriumApp appMan = Global.Login();
atDal = appMan.DALMngrX;// new atriumDAL.atriumDALManager(user, pwd, "DATABASE1");
atBEHelp = appMan.AtMng.HelpMng();
//P.P.Ho wrote: 29/08/2013
// Verify this line before check-in
XmlDocument LinkData_filename = HelpHelper.LoadXmlFile("sidemenu.xml", "", atDal, true);
if (!IsPostBack) //GET
{
string id;
id = (string)Request.QueryString["id"];
if (id != null) // GET 1
{
showEditForm(id, LinkData_filename);
}
else if (Request.QueryString["new"] == "Y") // GET 2
{
XmlNode vnn = LinkData_filename.SelectSingleNode("//nextid");
int newnextid;
newnextid = Convert.ToInt32(vnn.InnerXml) + 1;
vnn.InnerXml = newnextid.ToString();
HelpHelper.SaveXmlFile("sidemenu.xml", LinkData_filename, atBEHelp, true);
XmlDocument blankXML = new XmlDocument();
if (Request.QueryString["orphan"] == "Y")
{
blankXML.LoadXml("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><menu><item orphan='true' id='" + newnextid + "'/></menu>");
}
else
{
blankXML.LoadXml("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><menu><item orphan='false' id='" + newnextid + "'/></menu>");
}
Literal h1PgTitle;
h1PgTitle = (Literal)Master.FindControl("h1PgTitle");
showNewForm(newnextid.ToString(), blankXML, h1PgTitle.Text, null, Request.QueryString["nodetype"]);
}//"GET 3"
else if (Request.QueryString["ColId"] != null)
{
XmlNode TopNode = LinkData_filename.SelectSingleNode("//item[@id='" + Request.QueryString["ColId"] + "']");
TopNode.Attributes["ColExp"].Value = Request.QueryString["colExp"];
HelpHelper.SaveXmlFile("sidemenu.xml", LinkData_filename, atBEHelp, true);
showList(TopNode.Attributes["id"].Value, LinkData_filename);
}
//"GET 4"
else if (Request.QueryString["paste"] == "Y")
{
if (Request.QueryString["ParentItem"] == "ROOT")
{
XmlElement ParentItem = LinkData_filename.DocumentElement;
XmlNode CutItem = LinkData_filename.SelectSingleNode("//item[@id='" + Request.QueryString["PasteItem"] + "']");
XmlNode removedNode = CutItem.ParentNode.RemoveChild(CutItem);
ParentItem.AppendChild(removedNode);
HelpHelper.SaveXmlFile("sidemenu.xml", LinkData_filename, atBEHelp, true);
showList(CutItem.Attributes["id"].Value, LinkData_filename);
}
else
{
XmlNode ParentItem = LinkData_filename.SelectSingleNode("//item[@id='" + Request.QueryString["ParentItem"] + "']");
XmlNode CutItem = LinkData_filename.SelectSingleNode("//item[@id='" + Request.QueryString["PasteItem"] + "']");
XmlNode removedNode = CutItem.ParentNode.RemoveChild(CutItem);
if (Request.QueryString["parent"] == "N") //Paste as Child
{
ParentItem.ParentNode.InsertAfter(CutItem, ParentItem);
}
else
{
removedNode.Attributes["orphan"].Value = "false"; // to bring orphan files to the hierarchy
ParentItem.AppendChild(removedNode);
}
HelpHelper.SaveXmlFile("sidemenu.xml", LinkData_filename, atBEHelp, true);
showList(CutItem.Attributes["id"].Value, LinkData_filename);
ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#" + Request.QueryString["ParentItem"] + "';", true);
}
}
else if (Request.QueryString["parentId"] != null)// GET 5 ' insert new node or leaf
{
XmlNode vnn = LinkData_filename.SelectSingleNode("item/nextid");
int newnextid = Convert.ToInt32(vnn.InnerXml) + 1;
vnn.InnerXml = newnextid.ToString();
HelpHelper.SaveXmlFile("sidemenu.xml", LinkData_filename, atBEHelp, true);
XmlDocument blankXML = new XmlDocument();
blankXML.LoadXml("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><menu><item id='" + newnextid + "' orphan='false' pgid='' fre='' eng='' nodeType='" + Request.QueryString["nodetype"] + "' tocPath='' tocPathF=''/></menu>");
XmlNode N = LinkData_filename.SelectSingleNode("//item[@id='" + Request.QueryString["parentId"] + "']");
string vParentEng = N.Attributes["eng"].Value;
showNewForm(newnextid.ToString(), blankXML, vParentEng, Request.QueryString["parentId"], Request.QueryString["nodetype"]);
}
else if (Request.QueryString["move"] == "down") // GET 6" 'move selected item down
{
XmlNode NodeToMove = LinkData_filename.SelectSingleNode("//item[@id='" + Request.QueryString["moveid"] + "']");
XmlNode NodeToMoveParent = NodeToMove.ParentNode;
XmlNode ReferenceNode = NodeToMove.NextSibling.NextSibling;
XmlNode RemovedNodeToMove = NodeToMove.ParentNode.RemoveChild(NodeToMove);
if (ReferenceNode != null)
ReferenceNode.ParentNode.InsertBefore(RemovedNodeToMove, ReferenceNode);
else
NodeToMoveParent.AppendChild(RemovedNodeToMove);
HelpHelper.SaveXmlFile("sidemenu.xml", LinkData_filename, atBEHelp, true);
showList(NodeToMove.Attributes["id"].Value, LinkData_filename);
ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#" + Request.QueryString["moveid"] + "';", true);
}
else if (Request.QueryString["move"] == "up") //GET 7"
{
XmlNode NodeToMove = LinkData_filename.SelectSingleNode("//item[@id='" + Request.QueryString["moveid"] + "']");
XmlNode ReferenceNode = NodeToMove.PreviousSibling;
XmlNode RemovedNodeToMove = NodeToMove.ParentNode.RemoveChild(NodeToMove);
ReferenceNode.ParentNode.InsertBefore(RemovedNodeToMove, ReferenceNode);
HelpHelper.SaveXmlFile("sidemenu.xml", LinkData_filename, atBEHelp, true);
showList(NodeToMove.Attributes["id"].Value, LinkData_filename);
ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#" + Request.QueryString["moveid"] + "';", true);
}
else if (Request.QueryString["list"] == "Y") //GET document list"
{
if (Request.QueryString["Export"] == "Y")
{
excelDocumentList("", LinkData_filename);
}
else
{
showDocumentList("", LinkData_filename);
}
}
else
{
showList("", LinkData_filename);
}
}
else //POST
{
ProcessActionButtons(LinkData_filename);
}
}
private void ProcessActionButtons(XmlDocument xmlDoc)
{
bool SaveAndReturn = false;
string btnAction = Request.Form["btnAction"];
string pageXMLFile;
bool isFilesExist;
XmlDocument pXML;
XmlNode N;
switch (btnAction)
{
case "Save": // POST 1
case "SaveReturn":
SaveAndReturn = false;
if (Request.Form["btnAction"] == "SaveReturn") // POST 2
{
SaveAndReturn = true;
}
XmlNode pageNode = xmlDoc.SelectSingleNode("//item[@id='" + Request.Form["id"] + "']");
if (pageNode != null)
{
//POST 3
UpdateNode(pageNode);
// peter
// xmlDoc.Save(@fileName);
HelpHelper.SaveXmlFile("sidemenu.xml", xmlDoc, atBEHelp, true);
// add js function to verify if ENG has changed, and if so, provide checkbox option to sync with page.xml
string itempgid = pageNode.Attributes["pgid"].Value;
//Peter: This section does nothing
// pageXMLFile = HttpContext.Current.Server.MapPath("~") + XML_PATH_COMMON + "pages.xml";
pXML = HelpHelper.LoadXmlFile("pages.xml", "", atDal, true);
pageNode = pXML.SelectSingleNode("pages/page[@id='" + itempgid + "']");
if (pageNode != null)
{
pageNode.Attributes["eng"].Value = Request.Form["eng"];
pageNode.Attributes["fre"].Value = Request.Form["fre"];
pageNode.Attributes["type"].Value = Request.Form["nodetype"];
// peter xmlDoc.Save(@fileName);
HelpHelper.SaveXmlFile("pages.xml", pXML, atBEHelp, true);
}
//Peter:This section does nothing
}
else //no node found - new page
{
//POST 4
//create Content Pages
string id1;
id1 = Request.Form["id"];
createContentPages(id1);
pXML = HelpHelper.LoadXmlFile("pages.xml", "", atDal, true);
XmlElement element = pXML.CreateElement("page");
element.SetAttribute("id", (string)Request.Form["id"]);
element.SetAttribute("type", Request.Form["nodetype"]);
element.SetAttribute("path", Request.Form["id"] + ".asp");
element.SetAttribute("eng", Request.Form["eng"]);
element.SetAttribute("fre", Request.Form["fre"]);
pXML.DocumentElement.AppendChild(element);
HelpHelper.SaveXmlFile("pages.xml", pXML, atBEHelp, true);
UpdateElement(xmlDoc);
HelpHelper.SaveXmlFile("sidemenu.xml", xmlDoc, atBEHelp, true);
}
if (SaveAndReturn)// POST 5
{
showList(Request.Form["id"], xmlDoc);
ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#" + Request.Form["id"] + "';", true);
}
else // POST 6
{
showEditForm(Request.Form["id"], xmlDoc);
}
break;
case "Delete": // POST 7
string engFile;
string freFile;
N = xmlDoc.SelectSingleNode("//item[@id='" + Request.Form["id"] + "']");
string pgpgid = N.Attributes["pgid"].Value;
XmlNode parentXMLNode = N.ParentNode;
//pageXMLFile = HttpContext.Current.Server.MapPath("~") + XML_PATH_COMMON + "pages.xml";
pXML = HelpHelper.LoadXmlFile("pages.xml", "", atDal, true);
pageNode = pXML.SelectSingleNode("pages/page[@id='" + pgpgid + "']");
//engFile = HttpContext.Current.Server.MapPath("~") + DESKBOOK_ENGLISH_CONTENT + Request.Form["id"] + ".asp";
//freFile = HttpContext.Current.Server.MapPath("~") + DESKBOOK_FRANCAIS_CONTENT + Request.Form["id"] + ".asp";
engFile = Request.Form["id"] + ".asp";
freFile = Request.Form["id"] + ".asp";
HelpHelper.DeletePageFile(engFile, "Eng", atBEHelp, true);
HelpHelper.DeletePageFile(freFile, "Fre", atBEHelp, true);
if (N != null)
parentXMLNode.RemoveChild(N);
if (pageNode != null)
pXML.DocumentElement.RemoveChild(pageNode);
//peter pXML.Save(@pageXMLFile);
HelpHelper.SaveXmlFile("pages.xml", pXML, atBEHelp, true);
HelpHelper.SaveXmlFile("sidemenu.xml", xmlDoc, atBEHelp, true);
showList("", xmlDoc);
break;
case "Cancel": //POST 8
N = xmlDoc.SelectSingleNode("//item[@id='" + Request.Form["id"] + "']");
if (N != null)
{
showList(N.Attributes["id"].Value, xmlDoc);
}
else
{
showList("", xmlDoc);
}
ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#" + Request.Form["id"] + "';", true);
break;
}
}
public void createContentPages(string vPgId)
{
string fileName = vPgId + ".asp";
HelpHelper.AddPageFile(fileName, "eng", atBEHelp);
HelpHelper.AddPageFile(fileName, "fre", atBEHelp);
}
// response.write "createContentPages"
// Const adTypeText = 2
// Const adSaveCreateNotExist = 1
// strFileNameEng=server.MapPath(session("ISDefaultPath\") & "content_manager\include\newpagetemplateEng.asp")
// strFileNameFre=server.MapPath(session("ISDefaultPath\") & "content_manager\include\newpagetemplateFre.asp")
// Set objStreamFileEng = CreateObject("Adodb.Stream")
// Set objStreamFileFre = CreateObject("Adodb.Stream")
// objStreamFileEng.Open
// objStreamFileEng.Type= adTypeText
// objStreamFileEng.CharSet = "UTF-8"
// objStreamFileEng.LoadFromFile strFileNameEng
// objStreamFileEng.SaveToFile engPagePath & "\" & vPgId &".asp", adSaveCreateNotExist
// objStreamFileFre.Open
// objStreamFileFre.Type= adTypeText
// objStreamFileFre.CharSet = "UTF-8"
// objStreamFileFre.LoadFromFile strFileNameFre
// objStreamFileFre.SaveToFile frePagePath & "\" & vPgId &".asp", adSaveCreateNotExist
// objStreamFileEng.Close
// objStreamFileFre.Close
// Set objStreamFileEng = Nothing
// Set objStreamFileFre = Nothing
//end sub
private void UpdateElement(XmlDocument xmlDoc)
{
XmlElement element = xmlDoc.CreateElement("item");
element.SetAttribute("id", Request.Form["id"]);
element.SetAttribute("pgid", Request.Form["id"]);
element.SetAttribute("nodeType", (string)Request.Form["nodetype"]);
element.SetAttribute("eng", Request.Form["eng"]);
element.SetAttribute("fre", Request.Form["fre"]);
element.SetAttribute("orphan", Request.Form["orphan"]);
element.SetAttribute("tocPath", Request.Form["tocPath"]);
element.SetAttribute("tocPathF", Request.Form["tocPathF"]);
element.SetAttribute("dcSubjectEng", Request.Form["dcSubjectEng"]);
element.SetAttribute("dcSubjectFre", Request.Form["dcSubjectFre"]);
element.SetAttribute("dcDescriptionEng", Request.Form["dcDescriptionEng"]);
element.SetAttribute("dcDescriptionFre", Request.Form["dcDescriptionFre"]);
element.SetAttribute("keywordsEng", Request.Form["keywordsEng"]);
element.SetAttribute("keywordsFre", Request.Form["keywordsFre"]);
element.SetAttribute("translateTo", Request.Form["translateTo"]);
element.SetAttribute("translationProcess", Request.Form["translationProcess"]);
element.SetAttribute("responsability", Request.Form["responsability"]);
element.SetAttribute("process", Request.Form["process"]);
element.SetAttribute("dateAssigned", Request.Form["dateAssigned"]);
element.SetAttribute("fileNumber", Request.Form["fileNumber"]);
element.SetAttribute("comment", Request.Form["comment"]);
element.SetAttribute("updated", "1");
element.SetAttribute("updatePerson", (string)Session["DLSUUser"]);
element.SetAttribute("updateDate", (string)DateTime.UtcNow.ToString());
if (Request.Form["parentID"] == null || Request.Form["parentID"] == "")
xmlDoc.DocumentElement.AppendChild(element);
else
{
XmlNode parentN;
parentN = xmlDoc.SelectSingleNode("//item[@id='" + Request.Form["parentID"] + "']");
parentN.AppendChild(element);
}
//element.Attributes["nodeType"].Value = (string)Request.Form["nodetype"];
//element.Attributes["eng"].Value = Request.Form["eng"];
//element.Attributes["fre"].Value = Request.Form["fre"];
//element.Attributes["orphan"].Value = Request.Form["orphan"];
//element.Attributes["tocPath"].Value = Request.Form["tocPath"];
//element.Attributes["tocPathF"].Value = Request.Form["tocPathF"];
//element.Attributes["dcSubjectEng"].Value = Request.Form["dcSubjectEng"];
//element.Attributes["dcSubjectFre"].Value = Request.Form["dcSubjectFre"];
//element.Attributes["dcDescriptionEng"].Value = Request.Form["dcDescriptionEng"];
//element.Attributes["dcDescriptionFre"].Value = Request.Form["dcDescriptionFre"];
//element.Attributes["keywordsEng"].Value = Request.Form["keywordsEng"];
//element.Attributes["keywordsFre"].Value = Request.Form["keywordsFre"];
//element.Attributes["translateTo"].Value = Request.Form["translateTo"];
//element.Attributes["translationProcess"].Value = Request.Form["translationProcess"];
//element.Attributes["responsability"].Value = Request.Form["responsability"];
//element.Attributes["process"].Value = Request.Form["process"];
//element.Attributes["dateAssigned"].Value = Request.Form["dateAssigned"];
//element.Attributes["fileNumber"].Value = Request.Form["fileNumber"];
//element.Attributes["comment"].Value = Request.Form["comment"];
//element.Attributes["updated"].Value = "1";
//element.Attributes["updatePerson"].Value = (string)Session["DLSUUser"];
//element.Attributes["updateDate"].Value = (string)DateTime.Now.ToString();
}
private void UpdateNode(XmlNode xNode)
{
xNode.Attributes["nodeType"].Value = (string)Request.Form["nodetype"];
xNode.Attributes["eng"].Value = Request.Form["eng"];
xNode.Attributes["fre"].Value = Request.Form["fre"];
xNode.Attributes["orphan"].Value = Request.Form["orphan"];
xNode.Attributes["tocPath"].Value = Request.Form["tocPath"];
xNode.Attributes["tocPathF"].Value = Request.Form["tocPathF"];
xNode.Attributes["dcSubjectEng"].Value = Request.Form["dcSubjectEng"];
xNode.Attributes["dcSubjectFre"].Value = Request.Form["dcSubjectFre"];
xNode.Attributes["dcDescriptionEng"].Value = Request.Form["dcDescriptionEng"];
xNode.Attributes["dcDescriptionFre"].Value = Request.Form["dcDescriptionFre"];
xNode.Attributes["keywordsEng"].Value = Request.Form["keywordsEng"];
xNode.Attributes["keywordsFre"].Value = Request.Form["keywordsFre"];
xNode.Attributes["translateTo"].Value = Request.Form["translateTo"];
xNode.Attributes["translationProcess"].Value = Request.Form["translationProcess"];
xNode.Attributes["responsability"].Value = Request.Form["responsability"];
xNode.Attributes["process"].Value = Request.Form["process"];
xNode.Attributes["dateAssigned"].Value = Request.Form["dateAssigned"];
xNode.Attributes["fileNumber"].Value = Request.Form["fileNumber"];
xNode.Attributes["comment"].Value = Request.Form["comment"];
xNode.Attributes["updated"].Value = "1";
xNode.Attributes["updatePerson"].Value = (string)Session["DLSUUser"];
xNode.Attributes["updateDate"].Value = (string)DateTime.UtcNow.ToString();
}
private void SetPageTitle()
{
string PgId;
string vQS = Request.QueryString["pgid"];
if (vQS == null || vQS == "")
PgId = "1999";
else
PgId = vQS;
Literal h1PgTitle;
h1PgTitle = (Literal)Master.FindControl("h1PgTitle");
XmlDocument xmlPagesAdmin;
atriumDAL.atriumDALManager atDal;
atDal = new atriumDAL.atriumDALManager(ConfigurationManager.AppSettings["DBConnUserName"], ConfigurationManager.AppSettings["DBConnPassword"], "DATABASE1");
xmlPagesAdmin = HelpHelper.LoadXmlFile("pagesAdmin.xml", "", atDal, true);
XmlNode pageNode = xmlPagesAdmin.SelectSingleNode("pages/page[@id='" + PgId + "']");
if (pageNode == null)
{
Response.Redirect(HttpContext.Current.Server.MapPath("~") + "404.aspx", true);
}
if (h1PgTitle != null)
{
h1PgTitle.Text = pageNode.Attributes["eng"].Value;
}
}
private void showEditForm(string id, XmlDocument xmlDoc)
{
//.xsl
string DESKBOOK_SAM_PATH_XSL = System.Configuration.ConfigurationManager.AppSettings["DESKBOOK_SAM_PATH_XSL"].ToString();
XslCompiledTransform xslStructure = HelpHelper.LoadXslTransformFile("manual_edit.xsl", DESKBOOK_SAM_PATH_XSL, atDal, false);
XsltArgumentList xslarg = new XsltArgumentList();
xslarg.AddParam("id", "", id);
StringWriter sw = new StringWriter();
xslStructure.Transform(xmlDoc, xslarg, sw);
string result = sw.ToString().Replace("<", "<").Replace(">", ">");
sw.Close();
pgContent.Text = result;
}
private void showNewForm(string id, XmlDocument xmlDoc, string parentName, string parentID, string nodeType)
{
string DESKBOOK_SAM_PATH_XSL = System.Configuration.ConfigurationManager.AppSettings["DESKBOOK_SAM_PATH_XSL"].ToString();
XslCompiledTransform xslStructure = HelpHelper.LoadXslTransformFile("manual_new.xsl", DESKBOOK_SAM_PATH_XSL, atDal, false);
XsltArgumentList xslarg = new XsltArgumentList();
xslarg.AddParam("id", "", id);
if (parentName != null)
xslarg.AddParam("parentName", "", parentName);
if (parentID != null)
xslarg.AddParam("parentID", "", parentID);
if (nodeType != null)
xslarg.AddParam("nodeType", "", nodeType);
StringWriter sw = new StringWriter();
xslStructure.Transform(xmlDoc, xslarg, sw);
string result = sw.ToString().Replace("<", "<").Replace(">", ">");
sw.Close();
pgContent.Text = result;
}
private void showList(string nodeToHighlight, XmlDocument LinkData_filename)
{
string DESKBOOK_SAM_PATH_XSL = System.Configuration.ConfigurationManager.AppSettings["DESKBOOK_SAM_PATH_XSL"].ToString();
string id = (string)Request.QueryString["pgid"];
XslCompiledTransform xslStructure = HelpHelper.LoadXslTransformFile("manual_select.xsl", DESKBOOK_SAM_PATH_XSL, atDal, false);
XsltArgumentList xslarg = new XsltArgumentList();
if (id != null)
xslarg.AddParam("pgid", "", id);
if (nodeToHighlight != null)
xslarg.AddParam("nodeToHighlight", "", nodeToHighlight);
StringWriter sw = new StringWriter();
xslStructure.Transform(LinkData_filename, xslarg, sw);
string result = sw.ToString().Replace("<", "<").Replace(">", ">");
sw.Close();
pgContent.Text = result;
}
private void showDocumentList(string nodeToHighlight, XmlDocument LinkData_filename)
{
string DESKBOOK_SAM_PATH_XSL = System.Configuration.ConfigurationManager.AppSettings["DESKBOOK_SAM_PATH_XSL"].ToString();
string id = (string)Request.QueryString["pgid"];
XslCompiledTransform xslStructure = HelpHelper.LoadXslTransformFile("structure_list.xsl", DESKBOOK_SAM_PATH_XSL, atDal, false);
XsltArgumentList xslarg = new XsltArgumentList();
if (id != null)
xslarg.AddParam("pgid", "", id);
if (nodeToHighlight != null)
xslarg.AddParam("nodeToHighlight", "", nodeToHighlight);
StringWriter sw = new StringWriter();
xslStructure.Transform(LinkData_filename, xslarg, sw);
string result = sw.ToString().Replace("<", "<").Replace(">", ">");
sw.Close();
pgContent.Text = result;
}
private void excelDocumentList(string nodeToHighlight, XmlDocument LinkData_filename)
{
string DESKBOOK_SAM_PATH_XSL = System.Configuration.ConfigurationManager.AppSettings["DESKBOOK_SAM_PATH_XSL"].ToString();
string id = (string)Request.QueryString["pgid"];
XslCompiledTransform xslStructure = HelpHelper.LoadXslTransformFile("structure_excelexport.xslt", DESKBOOK_SAM_PATH_XSL, atDal, false);
XsltArgumentList xslarg = new XsltArgumentList();
if (id != null)
xslarg.AddParam("pgid", "", id);
if (nodeToHighlight != null)
xslarg.AddParam("nodeToHighlight", "", nodeToHighlight);
StringWriter sw = new StringWriter();
xslStructure.Transform(LinkData_filename, xslarg, sw);
this.Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=Export.xls");
Response.Charset = "";
this.EnableViewState = false;
Response.Write(sw.ToString());
//Response.End();
//string result = sw.ToString().Replace("<", "<").Replace(">", ">");
sw.Close();
//pgContent.Text = result;
Response.End();
}
}
} | 49.763573 | 242 | 0.551223 | [
"MIT"
] | chris-weekes/atrium | lmras/DeskbookSAM/english/atrium/content_manager/SAMStructure.aspx.cs | 28,417 | C# |
namespace RESTAPI.Util
{
/// <summary>
/// Generic file utility functions.
/// </summary>
public static class FileUtil
{
/// <summary>
/// Returns the file extension of a passed
/// file path and name or null, if the file
/// name has no extension.
/// </summary>
/// <param name="fileName">file path and name</param>
/// <returns></returns>
public static string? GetFileExtension(string fileName)
{
var i = fileName.LastIndexOf('.');
if (i < 0)
return null;
return fileName.Substring(i + 1);
}
/// <summary>
/// Retrurns a file extension by passed MIME type.
/// If no extension matches the passed MIME type,
/// "unknown" will be returned.
/// </summary>
/// <param name="contentType">file MIME type</param>
/// <returns></returns>
public static string GetFileExtensionByContentType(string contentType)
{
contentType = contentType.ToLower();
if (!Constants.FILE_EXTENSIONS_BY_CONTENT_TYPE.ContainsKey(contentType))
return "unknown";
return Constants.FILE_EXTENSIONS_BY_CONTENT_TYPE[contentType];
}
}
}
| 30.880952 | 84 | 0.562066 | [
"MIT"
] | zekroTJA/voidseeker | RESTAPI/Util/FileUtil.cs | 1,299 | C# |
using Microsoft.EntityFrameworkCore;
using JetBrains.Annotations;
namespace L2L.Data.Model
{
public class L2lDbContext : DbContext
{
public L2lDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<Course> Courses { get; set; }
}
} | 23.538462 | 77 | 0.630719 | [
"MIT"
] | Hivesp/L2L | L2L.data/Model/L2lDbContext.cs | 306 | C# |
using System;
using System.Diagnostics;
using System.IO;
using Maui.Controls.Sample.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Maui;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Essentials;
namespace Maui.Controls.Sample
{
public partial class XamlApp : Application
{
public XamlApp(IServiceProvider services, ITextService textService)
{
InitializeComponent();
Services = services;
Debug.WriteLine($"The injected text service had a message: '{textService.GetText()}'");
Debug.WriteLine($"Current app theme: {RequestedTheme}");
RequestedThemeChanged += (sender, args) =>
{
// Respond to the theme change
Debug.WriteLine($"Requested theme changed: {args.RequestedTheme}");
};
LoadAsset();
}
async void LoadAsset()
{
try
{
using var stream = await FileSystem.OpenAppPackageFileAsync("RawAsset.txt");
using var reader = new StreamReader(stream);
Debug.WriteLine($"The raw Maui asset contents: '{reader.ReadToEnd().Trim()}'");
}
catch (Exception ex)
{
Debug.WriteLine($"Error loading the raw Maui asset contents: {ex}");
}
}
// Must not use MainPage for multi-window
protected override Window CreateWindow(IActivationState activationState)
{
var window = new Window(Services.GetRequiredService<Page>());
window.Title = ".NET MAUI Samples Gallery";
return window;
}
public IServiceProvider Services { get; }
}
}
| 24.644068 | 90 | 0.71458 | [
"MIT"
] | GabrieleMessina/maui | src/Controls/samples/Controls.Sample/XamlApp.xaml.cs | 1,454 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("P05-FilterByAge")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("P05-FilterByAge")]
[assembly: System.Reflection.AssemblyTitleAttribute("P05-FilterByAge")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 41.458333 | 80 | 0.649246 | [
"MIT"
] | MertYumer/C-Fundamentals---January-2019 | C# Advanced - January 2019/05. Functional Programming/P05-FilterByAge/obj/Debug/netcoreapp2.1/P05-FilterByAge.AssemblyInfo.cs | 995 | 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void TestNotZAndNotCInt32()
{
var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanTwoComparisonOpTest__TestNotZAndNotCInt32
{
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector256<Int32> _clsVar1;
private static Vector256<Int32> _clsVar2;
private Vector256<Int32> _fld1;
private Vector256<Int32> _fld2;
private BooleanTwoComparisonOpTest__DataTable<Int32, Int32> _dataTable;
static BooleanTwoComparisonOpTest__TestNotZAndNotCInt32()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
}
public BooleanTwoComparisonOpTest__TestNotZAndNotCInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new BooleanTwoComparisonOpTest__DataTable<Int32, Int32>(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.TestNotZAndNotC(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.TestNotZAndNotC(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var method = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_Load()
{
var method = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_LoadAligned()
{var method = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunClsVarScenario()
{
var result = Avx.TestNotZAndNotC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr);
var result = Avx.TestNotZAndNotC(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx.TestNotZAndNotC(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx.TestNotZAndNotC(left, right);
ValidateResult(left, right, result);
}
public void RunLclFldScenario()
{
var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCInt32();
var result = Avx.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunFldScenario()
{
var result = Avx.TestNotZAndNotC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Int32> left, Vector256<Int32> right, bool result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), right);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int32[] left, Int32[] right, bool result, [CallerMemberName] string method = "")
{
var expectedResult1 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult1 &= (((left[i] & right[i]) == 0));
}
var expectedResult2 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult2 &= (((~left[i] & right[i]) == 0));
}
if (((expectedResult1 == false) && (expectedResult2 == false)) != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.TestNotZAndNotC)}<Int32>(Vector256<Int32>, Vector256<Int32>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| 40.489231 | 175 | 0.568736 | [
"MIT"
] | AaronRobinsonMSFT/coreclr | tests/src/JIT/HardwareIntrinsics/X86/Avx/TestNotZAndNotC.Int32.cs | 13,159 | C# |
using System.Text.Json.Serialization;
namespace GlucoseTray.Models
{
/// <summary>
/// Class that maps to the JSON from NightScout status.
/// </summary>
/// <remarks>
/// Currently only maps the status value.
///
/// Would it be possible to read the units and alarm thresholds from nightscout?
/// </remarks>
public class NightScoutStatus
{
[JsonPropertyName("status")]
public string Status { get; set; }
}
}
| 24.894737 | 84 | 0.623679 | [
"MIT"
] | sschocke/GlucoseTray | GlucoseTray/Models/NightScoutStatus.cs | 475 | C# |
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using NHibernate;
using hackathonishbd.Models;
using System;
namespace hackathonishbd.Controllers
{
[RoutePrefix("Administrador")]
public class AdministradorController : Controller
{
[HttpGet]
[Route("AltaUsuario")]
public ActionResult AltaUsuario()
{
return View();
}
[HttpPost]
[Route("AltaUsuario")]
public ActionResult AltaUsuario(T_usuarios usuario)
{
ISession session = NHibernateHelper.GetCurrentSession();
try
{
using (ITransaction tx = session.BeginTransaction())
{
usuario.Fecha_registro = DateTime.Now;
session.Save(usuario);
tx.Commit();
}
}
finally
{
NHibernateHelper.CloseSession();
}
return RedirectToAction("Index");
}
}
}
| 24.714286 | 68 | 0.531792 | [
"MIT"
] | TritiumMonoid/hackathon-ish-bd | src/hackathonishbd/Controllers/AdministradorController.cs | 1,038 | C# |
namespace UoT.ui.main.tabs.animation {
partial class AnimationTab {
/// <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() {
System.Windows.Forms.SplitContainer splitContainer_;
this.animationSelectorPanel_ = new UoT.ui.main.tabs.animation.AnimationSelectorPanel();
this.animationPlaybackPanel_ = new UoT.ui.main.tabs.animation.AnimationPlaybackPanel();
splitContainer_ = new System.Windows.Forms.SplitContainer();
((System.ComponentModel.ISupportInitialize)(splitContainer_)).BeginInit();
splitContainer_.Panel1.SuspendLayout();
splitContainer_.Panel2.SuspendLayout();
splitContainer_.SuspendLayout();
this.SuspendLayout();
//
// splitContainer_
//
splitContainer_.Dock = System.Windows.Forms.DockStyle.Fill;
splitContainer_.FixedPanel = System.Windows.Forms.FixedPanel.Panel2;
splitContainer_.IsSplitterFixed = true;
splitContainer_.Location = new System.Drawing.Point(0, 0);
splitContainer_.Name = "splitContainer_";
splitContainer_.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer_.Panel1
//
splitContainer_.Panel1.Controls.Add(this.animationSelectorPanel_);
//
// splitContainer_.Panel2
//
splitContainer_.Panel2.Controls.Add(this.animationPlaybackPanel_);
splitContainer_.Panel2MinSize = 147;
splitContainer_.Size = new System.Drawing.Size(236, 458);
splitContainer_.SplitterDistance = 307;
splitContainer_.TabIndex = 16;
//
// animationSelectorPanel_
//
this.animationSelectorPanel_.Dock = System.Windows.Forms.DockStyle.Fill;
this.animationSelectorPanel_.Location = new System.Drawing.Point(0, 0);
this.animationSelectorPanel_.Name = "animationSelectorPanel_";
this.animationSelectorPanel_.Size = new System.Drawing.Size(236, 307);
this.animationSelectorPanel_.TabIndex = 11;
//
// animationPlaybackPanel_
//
this.animationPlaybackPanel_.Dock = System.Windows.Forms.DockStyle.Fill;
this.animationPlaybackPanel_.Frame = 0D;
this.animationPlaybackPanel_.FrameRate = 20;
this.animationPlaybackPanel_.IsPlaying = false;
this.animationPlaybackPanel_.Location = new System.Drawing.Point(0, 0);
this.animationPlaybackPanel_.Name = "animationPlaybackPanel_";
this.animationPlaybackPanel_.ShouldLoop = false;
this.animationPlaybackPanel_.Size = new System.Drawing.Size(236, 147);
this.animationPlaybackPanel_.TabIndex = 14;
this.animationPlaybackPanel_.TotalFrames = 0;
//
// AnimationTab
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(splitContainer_);
this.Name = "AnimationTab";
this.Size = new System.Drawing.Size(236, 458);
splitContainer_.Panel1.ResumeLayout(false);
splitContainer_.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(splitContainer_)).EndInit();
splitContainer_.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private AnimationSelectorPanel animationSelectorPanel_;
private AnimationPlaybackPanel animationPlaybackPanel_;
}
}
| 40.606061 | 103 | 0.701493 | [
"CC0-1.0"
] | MeltyPlayer/uot | Utility of Time CSharp/ui/main/tabs/animation/AnimationTab.Designer.cs | 4,022 | C# |
/*******************************************************
*
* 作者:王国超
* 创建日期:20180522
* 运行环境:.NET 4.5
* 版本号:1.0.0
*
* 历史记录:
* 创建文件 王国超 20180522 16:53
*
*******************************************************/
namespace Rafy.MultiTenancy.Exception
{
/// <summary>
/// 多租户数据分片映射配置异常类
/// </summary>
public class MultiTenancyShardMapUnfoundException : System.Exception
{
public MultiTenancyShardMapUnfoundException() : base("未找到租户ID对应分片数据库")
{ }
public MultiTenancyShardMapUnfoundException(string message) : base(message)
{ }
}
}
| 22.074074 | 83 | 0.511745 | [
"MIT"
] | zgynhqf/trunk | Rafy/Plugins/Rafy.MultiTenancy/Exception/MultiTenancyShardMapUnfoundException.cs | 714 | C# |
namespace EEFApps.ApiInstructions.DataInstructions.Instructions.Interfaces
{
using System.Threading.Tasks;
public interface IOperationInstruction<TResult>
{
Task<TResult> Execute();
}
}
| 21.2 | 75 | 0.731132 | [
"MIT"
] | EugeneElkin/eef-api-instructions | DataInstructions/Instructions/Interfaces/IOperationInstruction.cs | 214 | 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.Kusto.ServiceLayer.Metadata.Contracts
{
public enum MetadataType
{
Table = 0,
View = 1,
SProc = 2,
Function = 3,
Schema = 4,
Database = 5
}
/// <summary>
/// Object metadata information
/// </summary>
public class ObjectMetadata
{
public MetadataType MetadataType { get; set; }
public string MetadataTypeName { get; set; }
public string Schema { get; set; }
public string Name { get; set; }
public string Urn { get; set; }
}
}
| 22.205882 | 101 | 0.574834 | [
"MIT"
] | ConnectionMaster/sqltoolsservice | src/Microsoft.Kusto.ServiceLayer/Metadata/Contracts/ObjectMetadata.cs | 755 | C# |
// Copyright (c) Josef Pihrt and Contributors. 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.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.MSBuild;
using Roslynator.CodeGeneration.Markdown;
using Roslynator.Metadata;
using Roslynator.Utilities;
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
namespace Roslynator.CodeGeneration
{
internal static class Program
{
private static readonly UTF8Encoding _utf8NoBom = new(encoderShouldEmitUTF8Identifier: false);
private static async Task Main(string[] args)
{
if (args == null || args.Length == 0)
{
#if DEBUG
args = new[] { @"..\..\..\..\.." };
#else
args = new string[] { Environment.CurrentDirectory };
#endif
}
string rootPath = args[0];
StringComparer comparer = StringComparer.InvariantCulture;
var metadata = new RoslynatorMetadata(rootPath);
ImmutableArray<AnalyzerMetadata> analyzers = metadata.Analyzers;
ImmutableArray<AnalyzerMetadata> codeAnalysisAnalyzers = metadata.CodeAnalysisAnalyzers;
ImmutableArray<AnalyzerMetadata> formattingAnalyzers = metadata.FormattingAnalyzers;
ImmutableArray<RefactoringMetadata> refactorings = metadata.Refactorings;
ImmutableArray<CodeFixMetadata> codeFixes = metadata.CodeFixes;
ImmutableArray<CompilerDiagnosticMetadata> compilerDiagnostics = metadata.CompilerDiagnostics;
WriteAnalyzersReadMe(@"Analyzers\README.md", analyzers, "Roslynator.Analyzers");
WriteAnalyzersReadMe(@"CodeAnalysis.Analyzers\README.md", codeAnalysisAnalyzers, "Roslynator.CodeAnalysis.Analyzers");
WriteAnalyzersReadMe(@"Formatting.Analyzers\README.md", formattingAnalyzers, "Roslynator.Formatting.Analyzers");
#if !DEBUG
VisualStudioInstance instance = MSBuildLocator.QueryVisualStudioInstances().First(f => f.Version.Major == 16);
MSBuildLocator.RegisterInstance(instance);
using (MSBuildWorkspace workspace = MSBuildWorkspace.Create())
{
workspace.WorkspaceFailed += (o, e) => Console.WriteLine(e.Diagnostic.Message);
string solutionPath = Path.Combine(rootPath, "Roslynator.sln");
Console.WriteLine($"Loading solution '{solutionPath}'");
Solution solution = await workspace.OpenSolutionAsync(solutionPath).ConfigureAwait(false);
Console.WriteLine($"Finished loading solution '{solutionPath}'");
RoslynatorInfo roslynatorInfo = await RoslynatorInfo.Create(solution).ConfigureAwait(false);
IOrderedEnumerable<SourceFile> sourceFiles = analyzers
.Concat(codeAnalysisAnalyzers)
.Concat(formattingAnalyzers)
.Select(f => new SourceFile(f.Id, roslynatorInfo.GetAnalyzerFilesAsync(f.Identifier).Result))
.Concat(refactorings
.Select(f => new SourceFile(f.Id, roslynatorInfo.GetRefactoringFilesAsync(f.Identifier).Result)))
.OrderBy(f => f.Id);
MetadataFile.SaveSourceFiles(sourceFiles, @"..\SourceFiles.xml");
}
#endif
WriteAnalyzerMarkdowns(codeAnalysisAnalyzers, new (string, string)[] { ("Roslynator.CodeAnalysis.Analyzers", "https://www.nuget.org/packages/Roslynator.CodeAnalysis.Analyzers") });
WriteAnalyzerMarkdowns(formattingAnalyzers, new (string, string)[] { ("Roslynator.Formatting.Analyzers", "https://www.nuget.org/packages/Roslynator.Formatting.Analyzers") });
WriteAnalyzerMarkdowns(analyzers);
DeleteInvalidAnalyzerMarkdowns();
foreach (RefactoringMetadata refactoring in refactorings)
{
WriteAllText(
$@"..\docs\refactorings\{refactoring.Id}.md",
MarkdownGenerator.CreateRefactoringMarkdown(refactoring),
fileMustExists: false);
}
IEnumerable<CompilerDiagnosticMetadata> fixableCompilerDiagnostics = compilerDiagnostics
.Join(codeFixes.SelectMany(f => f.FixableDiagnosticIds), f => f.Id, f => f, (f, _) => f)
.Distinct();
ImmutableArray<CodeFixOption> codeFixOptions = typeof(CodeFixOptions).GetFields()
.Select(f =>
{
var key = (string)f.GetValue(null);
string value = f.GetCustomAttribute<CodeFixOptionAttribute>().Value;
return new CodeFixOption(key, value);
})
.ToImmutableArray();
foreach (CompilerDiagnosticMetadata diagnostic in fixableCompilerDiagnostics)
{
WriteAllText(
$@"..\docs\cs\{diagnostic.Id}.md",
MarkdownGenerator.CreateCompilerDiagnosticMarkdown(diagnostic, codeFixes, codeFixOptions, comparer),
fileMustExists: false);
}
WriteAllText(
@"..\docs\refactorings\Refactorings.md",
MarkdownGenerator.CreateRefactoringsMarkdown(refactorings, comparer));
WriteAllText(
@"Refactorings\README.md",
MarkdownGenerator.CreateRefactoringsReadMe(refactorings.Where(f => !f.IsObsolete), comparer));
WriteAllText(
@"CodeFixes\README.md",
MarkdownGenerator.CreateCodeFixesReadMe(fixableCompilerDiagnostics, comparer));
// find files to delete
foreach (string path in Directory.EnumerateFiles(GetPath(@"..\docs\refactorings")))
{
if (Path.GetFileName(path) != "Refactorings.md"
&& !refactorings.Any(f => f.Id == Path.GetFileNameWithoutExtension(path)))
{
Console.WriteLine($"FILE TO DELETE: {path}");
}
}
// find missing samples
foreach (RefactoringMetadata refactoring in refactorings)
{
if (!refactoring.IsObsolete
&& refactoring.Samples.Count == 0)
{
foreach (ImageMetadata image in refactoring.ImagesOrDefaultImage())
{
string imagePath = Path.Combine(GetPath(@"..\images\refactorings"), image.Name + ".png");
if (!File.Exists(imagePath))
Console.WriteLine($"MISSING SAMPLE: {imagePath}");
}
}
}
UpdateChangeLog();
void WriteAnalyzerMarkdowns(IEnumerable<AnalyzerMetadata> analyzers, IEnumerable<(string title, string url)> appliesTo = null)
{
foreach (AnalyzerMetadata analyzer in analyzers)
WriteAnalyzerMarkdown(analyzer, appliesTo);
}
void WriteAnalyzerMarkdown(AnalyzerMetadata analyzer, IEnumerable<(string title, string url)> appliesTo = null)
{
WriteAllText(
$@"..\docs\analyzers\{analyzer.Id}.md",
MarkdownGenerator.CreateAnalyzerMarkdown(analyzer, metadata.ConfigOptions, appliesTo),
fileMustExists: false);
foreach (AnalyzerOptionMetadata option in analyzer.Options
.Where(f => f.Id != null))
{
WriteAllText(
$@"..\docs\analyzers\{option.ParentId}{option.Id}.md",
MarkdownGenerator.CreateAnalyzerOptionMarkdown(option),
fileMustExists: false);
}
}
void DeleteInvalidAnalyzerMarkdowns()
{
AnalyzerMetadata[] allAnalyzers = analyzers
.Concat(codeAnalysisAnalyzers)
.Concat(formattingAnalyzers)
.ToArray();
IEnumerable<string> allIds = allAnalyzers
.Concat(allAnalyzers.SelectMany(f => f.OptionAnalyzers))
.Select(f => f.Id);
string directoryPath = GetPath(@"..\docs\analyzers");
foreach (string id in Directory.GetFiles(directoryPath, "*.*", SearchOption.TopDirectoryOnly)
.Select(f => Path.GetFileNameWithoutExtension(f))
.Except(allIds))
{
if (id == "RCSXXXX")
break;
string filePath = Path.Combine(directoryPath, Path.ChangeExtension(id, ".md"));
Console.WriteLine($"Delete file '{filePath}'");
File.Delete(filePath);
}
}
void WriteAnalyzersReadMe(string path, ImmutableArray<AnalyzerMetadata> descriptors, string title)
{
WriteAllText(
path,
MarkdownGenerator.CreateAnalyzersReadMe(descriptors.Where(f => !f.IsObsolete), title, comparer));
}
void UpdateChangeLog()
{
var issueRegex = new Regex(@"\(\#(?<issue>\d+)\)");
var analyzerRegex = new Regex(@"(\p{Lu}\p{Ll}+){2,}\ +\((?<id>RCS\d{4}[a-z]?)\)");
string path = GetPath(@"..\ChangeLog.md");
string s = File.ReadAllText(path, _utf8NoBom);
List<AnalyzerMetadata> allAnalyzers = analyzers
.Concat(formattingAnalyzers)
.Concat(codeAnalysisAnalyzers)
.ToList();
ImmutableDictionary<string, AnalyzerMetadata> dic = allAnalyzers
.Concat(allAnalyzers.SelectMany(f => f.OptionAnalyzers))
.Where(f => f.Id != null)
.ToImmutableDictionary(f => f.Id, f => f);
s = issueRegex.Replace(s, "([issue](https://github.com/JosefPihrt/Roslynator/issues/${issue}))");
s = analyzerRegex.Replace(
s,
m =>
{
string id = m.Groups["id"].Value;
Debug.Assert(dic.ContainsKey(id), id);
AnalyzerMetadata analyzer = dic[id];
return $"[{id}](https://github.com/JosefPihrt/Roslynator/blob/master/docs/analyzers/{id}.md) ({analyzer.Title.TrimEnd('.')})";
});
File.WriteAllText(path, s, _utf8NoBom);
}
void WriteAllText(string relativePath, string content, bool onlyIfChanges = true, bool fileMustExists = true)
{
string path = GetPath(relativePath);
Encoding encoding = (Path.GetExtension(path) == ".md") ? _utf8NoBom : Encoding.UTF8;
FileHelper.WriteAllText(path, content, encoding, onlyIfChanges, fileMustExists);
}
string GetPath(string path)
{
return Path.Combine(rootPath, path);
}
}
}
}
| 42.061818 | 192 | 0.578888 | [
"Apache-2.0"
] | ProphetLamb-Organistion/Roslynator | src/Tools/MetadataGenerator/Program.cs | 11,569 | C# |
using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using OmniSharp.Solution;
using OmniSharp.Common;
namespace OmniSharp.ProjectManipulation.AddToProject
{
public class AddToProjectHandler
{
private readonly ISolution _solution;
private readonly XNamespace _msBuildNameSpace = "http://schemas.microsoft.com/developer/msbuild/2003";
private readonly IFileSystem _fileSystem;
public AddToProjectHandler(ISolution solution, IFileSystem fileSystem)
{
_fileSystem = fileSystem;
_solution = solution;
}
public void AddToProject(AddToProjectRequest request)
{
if (request.FileName == null || !request.FileName.EndsWith(".cs"))
{
return;
}
var relativeProject = _solution.ProjectContainingFile(request.FileName);
if (relativeProject == null || relativeProject is OrphanProject)
{
throw new ProjectNotFoundException(string.Format("Unable to find project relative to file {0}", request.FileName));
}
var project = relativeProject.AsXml();
var requestFile = request.FileName;
var projectDirectory = _fileSystem.GetDirectoryName(relativeProject.FileName);
var relativeFileName = requestFile.Replace(projectDirectory, "").ForceWindowsPathSeparator().Substring(1);
var compilationNodes = project.Element(_msBuildNameSpace + "Project")
.Elements(_msBuildNameSpace + "ItemGroup")
.Elements(_msBuildNameSpace + "Compile").ToList();
var fileAlreadyInProject = compilationNodes.Any(n => n.Attribute("Include").Value.Equals(relativeFileName, StringComparison.InvariantCultureIgnoreCase));
if (!fileAlreadyInProject)
{
var compilationNodeParent = compilationNodes.First().Parent;
var newFileElement = new XElement(_msBuildNameSpace + "Compile", new XAttribute("Include", relativeFileName));
compilationNodeParent.Add(newFileElement);
relativeProject.Save(project);
}
}
}
} | 37.65 | 165 | 0.63745 | [
"MIT"
] | jchannon/OmniSharpServer | OmniSharp/ProjectManipulation/AddToProject/AddToProjectHandler.cs | 2,261 | C# |
using FakeItEasy;
using FakeXrmEasy.Extensions;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
namespace FakeXrmEasy
{
public partial class XrmFakedContext : IXrmContext
{
protected const int EntityActiveStateCode = 0;
protected const int EntityInactiveStateCode = 1;
public bool ValidateReferences { get; set; }
#region CRUD
public Guid GetRecordUniqueId(EntityReference record)
{
if (string.IsNullOrWhiteSpace(record.LogicalName))
{
throw new InvalidOperationException("The entity logical name must not be null or empty.");
}
// Don't fail with invalid operation exception, if no record of this entity exists, but entity is known
if (!Data.ContainsKey(record.LogicalName) && !EntityMetadata.ContainsKey(record.LogicalName))
{
if (ProxyTypesAssembly == null)
{
throw new InvalidOperationException($"The entity logical name {record.LogicalName} is not valid.");
}
if (!ProxyTypesAssembly.GetTypes().Any(type => FindReflectedType(record.LogicalName) != null))
{
throw new InvalidOperationException($"The entity logical name {record.LogicalName} is not valid.");
}
}
#if !FAKE_XRM_EASY && !FAKE_XRM_EASY_2013 && !FAKE_XRM_EASY_2015
if (record.Id == Guid.Empty && record.HasKeyAttributes())
{
if (EntityMetadata.ContainsKey(record.LogicalName))
{
var entityMetadata = EntityMetadata[record.LogicalName];
foreach (var key in entityMetadata.Keys)
{
if (record.KeyAttributes.Keys.Count == key.KeyAttributes.Length && key.KeyAttributes.All(x => record.KeyAttributes.Keys.Contains(x)))
{
var matchedRecord = Data[record.LogicalName].Values.SingleOrDefault(x => record.KeyAttributes.All(k => x.Attributes.ContainsKey(k.Key) && x.Attributes[k.Key] != null && x.Attributes[k.Key].Equals(k.Value)));
if (matchedRecord == null)
{
new FaultException<OrganizationServiceFault>(new OrganizationServiceFault(), $"{record.LogicalName} with the specified Alternate Keys Does Not Exist");
}
return matchedRecord.Id;
}
}
throw new InvalidOperationException($"The requested key attributes do not exist for the entity {record.LogicalName}");
}
else
{
throw new InvalidOperationException($"The requested key attributes do not exist for the entity {record.LogicalName}");
}
}
#endif
if (record.Id == Guid.Empty)
{
throw new InvalidOperationException("The id must not be empty.");
}
return record.Id;
}
/// <summary>
/// A fake retrieve method that will query the FakedContext to retrieve the specified
/// entity and Guid, or null, if the entity was not found
/// </summary>
/// <param name="context">The faked context</param>
/// <param name="fakedService">The faked service where the Retrieve method will be faked</param>
/// <returns></returns>
protected static void FakeRetrieve(XrmFakedContext context, IOrganizationService fakedService)
{
A.CallTo(() => fakedService.Retrieve(A<string>._, A<Guid>._, A<ColumnSet>._))
.ReturnsLazily((string entityName, Guid id, ColumnSet columnSet) =>
{
if (string.IsNullOrWhiteSpace(entityName))
{
throw new InvalidOperationException("The entity logical name must not be null or empty.");
}
if (id == Guid.Empty)
{
throw new InvalidOperationException("The id must not be empty.");
}
if (columnSet == null)
{
throw new InvalidOperationException("The columnset parameter must not be null.");
}
// Don't fail with invalid operation exception, if no record of this entity exists, but entity is known
if (!context.Data.ContainsKey(entityName))
{
if (context.ProxyTypesAssembly == null)
{
throw new InvalidOperationException($"The entity logical name {entityName} is not valid.");
}
if (!context.ProxyTypesAssembly.GetTypes().Any(type => context.FindReflectedType(entityName) != null))
{
throw new InvalidOperationException($"The entity logical name {entityName} is not valid.");
}
}
//Return the subset of columns requested only
var reflectedType = context.FindReflectedType(entityName);
//Entity logical name exists, so , check if the requested entity exists
if (context.Data.ContainsKey(entityName) && context.Data[entityName] != null
&& context.Data[entityName].ContainsKey(id))
{
//Entity found => return only the subset of columns specified or all of them
var foundEntity = context.Data[entityName][id].Clone(reflectedType);
if (columnSet.AllColumns)
{
foundEntity.ApplyDateBehaviour(context);
return foundEntity;
}
else
{
var projected = foundEntity.ProjectAttributes(columnSet, context);
projected.ApplyDateBehaviour(context);
return projected;
}
}
else
{
// Entity not found in the context => FaultException
throw new FaultException<OrganizationServiceFault>(new OrganizationServiceFault(), $"{entityName} With Id = {id:D} Does Not Exist");
}
});
}
/// <summary>
/// Fakes the Create message
/// </summary>
/// <param name="context"></param>
/// <param name="fakedService"></param>
protected static void FakeCreate(XrmFakedContext context, IOrganizationService fakedService)
{
A.CallTo(() => fakedService.Create(A<Entity>._))
.ReturnsLazily((Entity e) =>
{
return context.CreateEntity(e);
});
}
protected static void FakeUpdate(XrmFakedContext context, IOrganizationService fakedService)
{
A.CallTo(() => fakedService.Update(A<Entity>._))
.Invokes((Entity e) =>
{
context.UpdateEntity(e);
});
}
protected void UpdateEntity(Entity e)
{
if (e == null)
{
throw new InvalidOperationException("The entity must not be null");
}
e = e.Clone(e.GetType());
e.Id = GetRecordUniqueId(e.ToEntityReferenceWithKeyAttributes());
// Update specific validations: The entity record must exist in the context
if (Data.ContainsKey(e.LogicalName) &&
Data[e.LogicalName].ContainsKey(e.Id))
{
if (this.UsePipelineSimulation)
{
ExecutePipelineStage("Update", ProcessingStepStage.Preoperation, ProcessingStepMode.Synchronous, e);
}
// Add as many attributes to the entity as the ones received (this will keep existing ones)
var cachedEntity = Data[e.LogicalName][e.Id];
foreach (var sAttributeName in e.Attributes.Keys.ToList())
{
var attribute = e[sAttributeName];
if (attribute is DateTime)
{
cachedEntity[sAttributeName] = ConvertToUtc((DateTime)e[sAttributeName]);
}
else
{
if (attribute is EntityReference && ValidateReferences)
{
var target = (EntityReference)e[sAttributeName];
attribute = ResolveEntityReference(target);
}
cachedEntity[sAttributeName] = attribute;
}
}
// Update ModifiedOn
cachedEntity["modifiedon"] = DateTime.UtcNow;
cachedEntity["modifiedby"] = CallerId;
if (this.UsePipelineSimulation)
{
ExecutePipelineStage("Update", ProcessingStepStage.Postoperation, ProcessingStepMode.Synchronous, e);
var clone = e.Clone(e.GetType());
ExecutePipelineStage("Update", ProcessingStepStage.Postoperation, ProcessingStepMode.Asynchronous, clone);
}
}
else
{
// The entity record was not found, return a CRM-ish update error message
throw new FaultException<OrganizationServiceFault>(new OrganizationServiceFault(), $"{e.LogicalName} with Id {e.Id} Does Not Exist");
}
}
protected EntityReference ResolveEntityReference(EntityReference er)
{
if (!Data.ContainsKey(er.LogicalName) || !Data[er.LogicalName].ContainsKey(er.Id))
{
if (er.Id == Guid.Empty && er.HasKeyAttributes())
{
return ResolveEntityReferenceByAlternateKeys(er);
}
else
{
throw new FaultException<OrganizationServiceFault>(new OrganizationServiceFault(), $"{er.LogicalName} With Id = {er.Id:D} Does Not Exist");
}
}
return er;
}
protected EntityReference ResolveEntityReferenceByAlternateKeys(EntityReference er)
{
var resolvedId = GetRecordUniqueId(er);
return new EntityReference()
{
LogicalName = er.LogicalName,
Id = resolvedId
};
}
/// <summary>
/// Fakes the delete method. Very similar to the Retrieve one
/// </summary>
/// <param name="context"></param>
/// <param name="fakedService"></param>
protected static void FakeDelete(XrmFakedContext context, IOrganizationService fakedService)
{
A.CallTo(() => fakedService.Delete(A<string>._, A<Guid>._))
.Invokes((string entityName, Guid id) =>
{
if (string.IsNullOrWhiteSpace(entityName))
{
throw new InvalidOperationException("The entity logical name must not be null or empty.");
}
if (id == Guid.Empty)
{
throw new InvalidOperationException("The id must not be empty.");
}
var entityReference = new EntityReference(entityName, id);
context.DeleteEntity(entityReference);
});
}
protected void DeleteEntity(EntityReference er)
{
// Don't fail with invalid operation exception, if no record of this entity exists, but entity is known
if (!this.Data.ContainsKey(er.LogicalName))
{
if (this.ProxyTypesAssembly == null)
{
throw new InvalidOperationException($"The entity logical name {er.LogicalName} is not valid.");
}
if (!this.ProxyTypesAssembly.GetTypes().Any(type => this.FindReflectedType(er.LogicalName) != null))
{
throw new InvalidOperationException($"The entity logical name {er.LogicalName} is not valid.");
}
}
// Entity logical name exists, so , check if the requested entity exists
if (this.Data.ContainsKey(er.LogicalName) && this.Data[er.LogicalName] != null &&
this.Data[er.LogicalName].ContainsKey(er.Id))
{
if (this.UsePipelineSimulation)
{
ExecutePipelineStage("Delete", ProcessingStepStage.Preoperation, ProcessingStepMode.Synchronous, er);
}
// Entity found => return only the subset of columns specified or all of them
this.Data[er.LogicalName].Remove(er.Id);
if (this.UsePipelineSimulation)
{
ExecutePipelineStage("Delete", ProcessingStepStage.Postoperation, ProcessingStepMode.Synchronous, er);
ExecutePipelineStage("Delete", ProcessingStepStage.Postoperation, ProcessingStepMode.Asynchronous, er);
}
}
else
{
// Entity not found in the context => throw not found exception
// The entity record was not found, return a CRM-ish update error message
throw new FaultException<OrganizationServiceFault>(new OrganizationServiceFault(), $"{er.LogicalName} with Id {er.Id} Does Not Exist");
}
}
#endregion
#region Other protected methods
protected void EnsureEntityNameExistsInMetadata(string sEntityName)
{
if (Relationships.Values.Any(value => new[] { value.Entity1LogicalName, value.Entity2LogicalName, value.IntersectEntity }.Contains(sEntityName, StringComparer.InvariantCultureIgnoreCase)))
{
return;
}
// Entity metadata is checked differently when we are using a ProxyTypesAssembly => we can infer that from the generated types assembly
if (ProxyTypesAssembly != null)
{
var subClassType = FindReflectedType(sEntityName);
if (subClassType == null)
{
throw new Exception($"Entity {sEntityName} does not exist in the metadata cache");
}
}
//else if (!Data.ContainsKey(sEntityName))
//{
// //No Proxy Types Assembly
// throw new Exception(string.Format("Entity {0} does not exist in the metadata cache", sEntityName));
//};
}
protected void AddEntityDefaultAttributes(Entity e)
{
// Add createdon, modifiedon, createdby, modifiedby properties
if (CallerId == null)
{
CallerId = new EntityReference("systemuser", Guid.NewGuid()); // Create a new instance by default
if (ValidateReferences)
{
if (!Data.ContainsKey("systemuser"))
{
Data.Add("systemuser", new Dictionary<Guid, Entity>());
}
if (!Data["systemuser"].ContainsKey(CallerId.Id))
{
Data["systemuser"].Add(CallerId.Id, new Entity("systemuser") { Id = CallerId.Id });
}
}
}
var isManyToManyRelationshipEntity = e.LogicalName != null && this.Relationships.ContainsKey(e.LogicalName);
EntityInitializerService.Initialize(e, CallerId.Id, this, isManyToManyRelationshipEntity);
}
protected void ValidateEntity(Entity e)
{
if (e == null)
{
throw new InvalidOperationException("The entity must not be null");
}
// Validate the entity
if (string.IsNullOrWhiteSpace(e.LogicalName))
{
throw new InvalidOperationException("The LogicalName property must not be empty");
}
if (e.Id == Guid.Empty)
{
throw new InvalidOperationException("The Id property must not be empty");
}
}
protected internal Guid CreateEntity(Entity e)
{
if (e == null)
{
throw new InvalidOperationException("The entity must not be null");
}
var clone = e.Clone(e.GetType());
if (clone.Id == Guid.Empty)
{
clone.Id = Guid.NewGuid(); // Add default guid if none present
}
// Hack for Dynamic Entities where the Id property doesn't populate the "entitynameid" primary key
var primaryKeyAttribute = $"{e.LogicalName}id";
if (!clone.Attributes.ContainsKey(primaryKeyAttribute))
{
clone[primaryKeyAttribute] = clone.Id;
}
ValidateEntity(clone);
// Create specific validations
if (clone.Id != Guid.Empty && Data.ContainsKey(clone.LogicalName) &&
Data[clone.LogicalName].ContainsKey(clone.Id))
{
throw new InvalidOperationException($"There is already a record of entity {clone.LogicalName} with id {clone.Id}, can't create with this Id.");
}
// Create specific validations
if (clone.Attributes.ContainsKey("statecode"))
{
throw new InvalidOperationException($"When creating an entity with logical name '{clone.LogicalName}', or any other entity, it is not possible to create records with the statecode property. Statecode must be set after creation.");
}
AddEntityWithDefaults(clone, false, this.UsePipelineSimulation);
if (e.RelatedEntities.Count > 0)
{
foreach (var relationshipSet in e.RelatedEntities)
{
var relationship = relationshipSet.Key;
var entityReferenceCollection = new EntityReferenceCollection();
foreach (var relatedEntity in relationshipSet.Value.Entities)
{
var relatedId = CreateEntity(relatedEntity);
entityReferenceCollection.Add(new EntityReference(relatedEntity.LogicalName, relatedId));
}
if (FakeMessageExecutors.ContainsKey(typeof(AssociateRequest)))
{
var request = new AssociateRequest
{
Target = clone.ToEntityReference(),
Relationship = relationship,
RelatedEntities = entityReferenceCollection
};
FakeMessageExecutors[typeof(AssociateRequest)].Execute(request, this);
}
else
{
throw PullRequestException.NotImplementedOrganizationRequest(typeof(AssociateRequest));
}
}
}
return clone.Id;
}
protected internal void AddEntityWithDefaults(Entity e, bool clone = false, bool usePluginPipeline = false)
{
// Create the entity with defaults
AddEntityDefaultAttributes(e);
if (usePluginPipeline)
{
ExecutePipelineStage("Create", ProcessingStepStage.Preoperation, ProcessingStepMode.Synchronous, e);
}
// Store
AddEntity(clone ? e.Clone(e.GetType()) : e);
if (usePluginPipeline)
{
ExecutePipelineStage("Create", ProcessingStepStage.Postoperation, ProcessingStepMode.Synchronous, e);
ExecutePipelineStage("Create", ProcessingStepStage.Postoperation, ProcessingStepMode.Asynchronous, e);
}
}
protected internal void AddEntity(Entity e)
{
//Automatically detect proxy types assembly if an early bound type was used.
if (ProxyTypesAssembly == null &&
e.GetType().IsSubclassOf(typeof(Entity)))
{
ProxyTypesAssembly = Assembly.GetAssembly(e.GetType());
}
ValidateEntity(e); //Entity must have a logical name and an Id
foreach (var sAttributeName in e.Attributes.Keys.ToList())
{
var attribute = e[sAttributeName];
if (attribute is DateTime)
{
e[sAttributeName] = ConvertToUtc((DateTime)e[sAttributeName]);
}
if (attribute is EntityReference && ValidateReferences)
{
var target = (EntityReference)e[sAttributeName];
e[sAttributeName] = ResolveEntityReference(target);
}
}
//Add the entity collection
if (!Data.ContainsKey(e.LogicalName))
{
Data.Add(e.LogicalName, new Dictionary<Guid, Entity>());
}
if (Data[e.LogicalName].ContainsKey(e.Id))
{
Data[e.LogicalName][e.Id] = e;
}
else
{
Data[e.LogicalName].Add(e.Id, e);
}
//Update metadata for that entity
if (!AttributeMetadataNames.ContainsKey(e.LogicalName))
AttributeMetadataNames.Add(e.LogicalName, new Dictionary<string, string>());
//Update attribute metadata
if (ProxyTypesAssembly != null)
{
//If the context is using a proxy types assembly then we can just guess the metadata from the generated attributes
var type = FindReflectedType(e.LogicalName);
if (type != null)
{
var props = type.GetProperties();
foreach (var p in props)
{
if (!AttributeMetadataNames[e.LogicalName].ContainsKey(p.Name))
AttributeMetadataNames[e.LogicalName].Add(p.Name, p.Name);
}
}
else
throw new Exception(string.Format("Couldnt find reflected type for {0}", e.LogicalName));
}
else
{
//If dynamic entities are being used, then the only way of guessing if a property exists is just by checking
//if the entity has the attribute in the dictionary
foreach (var attKey in e.Attributes.Keys)
{
if (!AttributeMetadataNames[e.LogicalName].ContainsKey(attKey))
AttributeMetadataNames[e.LogicalName].Add(attKey, attKey);
}
}
}
protected internal bool AttributeExistsInMetadata(string sEntityName, string sAttributeName)
{
var relationships = this.Relationships.Values.Where(value => new[] { value.Entity1LogicalName, value.Entity2LogicalName, value.IntersectEntity }.Contains(sEntityName, StringComparer.InvariantCultureIgnoreCase)).ToArray();
if (relationships.Any(e => e.Entity1Attribute == sAttributeName || e.Entity2Attribute == sAttributeName))
{
return true;
}
//Early bound types
if (ProxyTypesAssembly != null)
{
//Check if attribute exists in the early bound type
var earlyBoundType = FindReflectedType(sEntityName);
if (earlyBoundType != null)
{
//Get that type properties
var attributeFound = earlyBoundType
.GetProperties()
.Where(pi => pi.GetCustomAttributes(typeof(AttributeLogicalNameAttribute), true).Length > 0)
.Where(pi => (pi.GetCustomAttributes(typeof(AttributeLogicalNameAttribute), true)[0] as AttributeLogicalNameAttribute).LogicalName.Equals(sAttributeName))
.FirstOrDefault();
if (attributeFound != null)
return true;
if (attributeFound == null && EntityMetadata.ContainsKey(sEntityName))
{
//Try with metadata
return AttributeExistsInInjectedMetadata(sEntityName, sAttributeName);
}
else
{
return false;
}
}
//Try with metadata
return false;
}
if (EntityMetadata.ContainsKey(sEntityName))
{
//Try with metadata
return AttributeExistsInInjectedMetadata(sEntityName, sAttributeName);
}
//Dynamic entities and not entity metadata injected for entity => just return true if not found
return true;
}
protected internal bool AttributeExistsInInjectedMetadata(string sEntityName, string sAttributeName)
{
var attributeInMetadata = FindAttributeTypeInInjectedMetadata(sEntityName, sAttributeName);
return attributeInMetadata != null;
}
protected internal DateTime ConvertToUtc(DateTime attribute)
{
return DateTime.SpecifyKind(attribute, DateTimeKind.Utc);
}
#endregion
}
}
| 42.537842 | 246 | 0.533578 | [
"MIT"
] | VinnyDyn/fake-xrm-easy | FakeXrmEasy.Shared/XrmFakedContext.Crud.cs | 26,418 | 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.Waf.V20180125.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeCustomRulesResponse : AbstractModel
{
/// <summary>
/// 规则详情
/// </summary>
[JsonProperty("RuleList")]
public DescribeCustomRulesRspRuleListItem[] RuleList{ get; set; }
/// <summary>
/// 规则条数
/// </summary>
[JsonProperty("TotalCount")]
public string TotalCount{ get; set; }
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamArrayObj(map, prefix + "RuleList.", this.RuleList);
this.SetParamSimple(map, prefix + "TotalCount", this.TotalCount);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 31.172414 | 81 | 0.634956 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Waf/V20180125/Models/DescribeCustomRulesResponse.cs | 1,882 | C# |
#nullable disable
using System;
using System.Linq;
using System.Runtime.Serialization;
using VocaDb.Model.Domain.ReleaseEvents;
using VocaDb.Model.Utils;
namespace VocaDb.Model.DataContracts.ReleaseEvents
{
[DataContract(Namespace = Schemas.VocaDb)]
public class ArchivedEventSeriesContract
{
private static void DoIfExists(ArchivedReleaseEventSeriesVersion version, ReleaseEventSeriesEditableFields field,
XmlCache<ArchivedEventSeriesContract> xmlCache, Action<ArchivedEventSeriesContract> func)
{
var versionWithField = version.GetLatestVersionWithField(field);
if (versionWithField?.Data != null)
{
var data = xmlCache.Deserialize(versionWithField.Version, versionWithField.Data);
func(data);
}
}
public static ArchivedEventSeriesContract GetAllProperties(ArchivedReleaseEventSeriesVersion version)
{
var data = new ArchivedEventSeriesContract();
var xmlCache = new XmlCache<ArchivedEventSeriesContract>();
var thisVersion = version.Data != null ? xmlCache.Deserialize(version.Version, version.Data) : new ArchivedEventSeriesContract();
data.Category = thisVersion.Category;
data.Description = thisVersion.Description;
data.Id = thisVersion.Id;
data.MainPictureMime = thisVersion.MainPictureMime;
data.TranslatedName = thisVersion.TranslatedName;
DoIfExists(version, ReleaseEventSeriesEditableFields.Names, xmlCache, v => data.Names = v.Names);
DoIfExists(version, ReleaseEventSeriesEditableFields.WebLinks, xmlCache, v => data.WebLinks = v.WebLinks);
return data;
}
public ArchivedEventSeriesContract() { }
#nullable enable
public ArchivedEventSeriesContract(ReleaseEventSeries series, ReleaseEventSeriesDiff diff)
{
ParamIs.NotNull(() => series);
Category = series.Category;
Description = series.Description;
Id = series.Id;
MainPictureMime = series.PictureMime;
Names = diff.IncludeNames ? series.Names.Names.Select(n => new LocalizedStringContract(n)).ToArray() : null;
TranslatedName = new ArchivedTranslatedStringContract(series.TranslatedName);
WebLinks = diff.IncludeWebLinks ? series.WebLinks.Select(l => new ArchivedWebLinkContract(l)).ToArray() : null;
}
#nullable disable
[DataMember]
public string[] Aliases { get; init; }
[DataMember]
public EventCategory Category { get; set; }
[DataMember]
public string Description { get; set; }
[DataMember]
public int Id { get; set; }
[DataMember]
public string MainPictureMime { get; set; }
[DataMember]
public LocalizedStringContract[] Names { get; set; }
[DataMember]
public ArchivedTranslatedStringContract TranslatedName { get; set; }
[DataMember]
public ArchivedWebLinkContract[] WebLinks { get; set; }
}
}
| 32.639535 | 133 | 0.73958 | [
"MIT"
] | AgFlore/vocadb | VocaDbModel/DataContracts/ReleaseEvents/ArchivedEventSeriesContract.cs | 2,807 | C# |
//
// System.CodeDom CodeDirective class
//
// Author:
// Marek Safar (marek.safar@seznam.cz)
//
// (C) 2004 Ximian, Inc.
//
//
// 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.
//
#if NET_2_0
using System.Runtime.InteropServices;
namespace System.CodeDom
{
[Serializable]
[ComVisible (true), ClassInterface (ClassInterfaceType.AutoDispatch)]
public class CodeDirective: CodeObject
{
public CodeDirective () {}
}
}
#endif
| 31.804348 | 73 | 0.749829 | [
"Apache-2.0"
] | Sectoid/debian-mono | mcs/class/System/System.CodeDom/CodeDirective.cs | 1,463 | C# |
using UnityEngine;
public class RandomMatchmaker : Photon.PunBehaviour
{
private PhotonView myPhotonView;
// Use this for initialization
public void Start()
{
PhotonNetwork.ConnectUsingSettings("0.1");
}
public override void OnJoinedLobby()
{
Debug.Log("JoinRandom");
PhotonNetwork.JoinRandomRoom();
}
public override void OnConnectedToMaster()
{
// when AutoJoinLobby is off, this method gets called when PUN finished the connection (instead of OnJoinedLobby())
PhotonNetwork.JoinRandomRoom();
}
public void OnPhotonRandomJoinFailed()
{
PhotonNetwork.CreateRoom(null);
}
public override void OnJoinedRoom()
{
GameObject monster = PhotonNetwork.Instantiate("monsterprefab", Vector3.zero, Quaternion.identity, 0);
monster.GetComponent<myThirdPersonController>().isControllable = true;
myPhotonView = monster.GetComponent<PhotonView>();
}
public void OnGUI()
{
GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());
if (PhotonNetwork.inRoom)
{
bool shoutMarco = GameLogic.playerWhoIsIt == PhotonNetwork.player.ID;
if (shoutMarco && GUILayout.Button("Marco!"))
{
myPhotonView.RPC("Marco", PhotonTargets.All);
}
if (!shoutMarco && GUILayout.Button("Polo!"))
{
myPhotonView.RPC("Polo", PhotonTargets.All);
}
}
}
}
| 27.321429 | 123 | 0.62549 | [
"Apache-2.0"
] | AndersonMarquess/mankind | Assets/Photon Unity Networking/Demos/MarcoPolo-Tutorial/RandomMatchmaker.cs | 1,530 | C# |
using Microsoft.EntityFrameworkCore;
using MSK.Core.Module.Domain;
namespace MSK.Application.Module.Data
{
public interface IEfRepositoryAsync<TEntity> : IEfRepositoryAsync<ApplicationDbContext, TEntity>
where TEntity : IEntity
{
}
public interface IEfQueryRepository<TEntity> : IEfQueryRepository<ApplicationDbContext, TEntity>
where TEntity : IEntity
{
}
public interface IEfRepositoryAsync<TDbContext, TEntity> : IRepositoryAsync<TEntity>
where TDbContext : DbContext
where TEntity : IEntity
{
}
public interface IEfQueryRepository<TDbContext, TEntity> : IQueryRepository<TEntity>
where TDbContext : DbContext
where TEntity : IEntity
{
}
}
| 26.571429 | 100 | 0.712366 | [
"MIT"
] | thangchung/modular-starter-kit | src/MSK.Application.Module.Data/IEfRepository.cs | 746 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using QlikView_CLI.QMSAPI;
namespace QlikView_CLI.PWSH
{
[Cmdlet(VerbsCommon.Get, "QVRemoteTasks")]
public class GetQVRemoteTasks : PSClient
{
[Parameter]
public Guid Remoteqmsid;
[Parameter]
public Guid Remoteqdsid;
private System.Collections.Generic.List<QlikView_CLI.QMSAPI.TaskInfo> Taskinfo = new System.Collections.Generic.List<QlikView_CLI.QMSAPI.TaskInfo>();
protected override void BeginProcessing()
{
base.BeginProcessing();
}
protected override void ProcessRecord()
{
try
{
Taskinfo = Connection.client.RemoteGetTasks(Remoteqmsid, Remoteqdsid);
}
catch (System.Exception e)
{
var errorRecord = new ErrorRecord(e, e.Source, ErrorCategory.NotSpecified, Connection.client);
WriteError(errorRecord);
}
}
protected override void EndProcessing()
{
base.EndProcessing();
WriteObject(Taskinfo);
}
}
}
| 24.530612 | 157 | 0.606489 | [
"MIT"
] | QlikProfessionalServices/QlikView-CLI | PWSH/Generated/Get/RemoteTasks.cs | 1,204 | C# |
namespace CustomCode.CompileTimeInject.Annotations
{
/// <summary>
/// Used in combination with an <see cref="ExportAttribute"/> to define the lifetime policy of a service.
/// </summary>
public enum Lifetime : byte
{
/// <summary> A new service instance is created per request. </summary>
Transient = 0,
/// <summary> A new service instance is created once per container. </summary>
Singleton = 1,
/// <summary> A new service instance is created once per scope. </summary>
Scoped = 2
}
} | 37.333333 | 109 | 0.632143 | [
"MIT"
] | git-custom-code/CompileTimeInject | src/CompileTimeInject.Annotations/Lifetime.cs | 560 | C# |
using System;
namespace Exercises.StackExercise
{
public class StackExceededSizeException : Exception
{
public StackExceededSizeException()
{
}
public StackExceededSizeException(string message)
: base(message)
{
}
public StackExceededSizeException(string message, Exception inner)
: base(message, inner)
{
}
}
}
| 19.272727 | 74 | 0.591981 | [
"MIT"
] | AnnaLviv/Exercises | Exercises/StackExercise/StackExceededSizeException.cs | 426 | C# |
using ExpenseManager.Entities.Concrete;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace ExpenseManager.WebApp.Models
{
public class ExpenseCategoryViewModel: BaseViewModel
{
[Required]
public string Name { get; set; }
[Display(Name = "Parent Category")]
public int? ParentCategoryId { get; set; }
public ExpenseCategory ParentCategory { get; set; }
public ICollection<ExpenseCategory> ChildCategories { get; set; }
public ICollection<Expense> Expenses { get; set; }
public ICollection<ExpenseCategory> ListOfExpenseCategories { get; set; }
public ExpenseCategoryViewModel()
{
}
public ExpenseCategoryViewModel(ExpenseCategory category)
{
Id = category.Id;
CreatedTime = category.CreatedTime;
ModifiedTime = category.ModifiedTime;
Name = category.Name;
ParentCategoryId = category.ParentCategoryId;
ParentCategory = category.ParentCategory;
ChildCategories = category.ChildCategories;
Expenses = category.Expenses;
}
public static ICollection<ExpenseCategoryViewModel> Convert(ICollection<ExpenseCategory> categories)
{
if (categories == null) return null;
return categories.Select(x => new ExpenseCategoryViewModel(x)).ToList();
}
}
}
| 31.583333 | 108 | 0.66029 | [
"MIT"
] | dudelis/expense-manager | ExpenseManager.WebApp/Models/ExpenseCategoryViewModel.cs | 1,518 | C# |
namespace Content.Server
{
public static class IgnoredComponents
{
public static string[] List => new string[] {
// Stick components you want ignored here.
};
}
} | 22.555556 | 54 | 0.591133 | [
"MIT"
] | 20kdc/RobustToolboxTemplate | Content.Server/IgnoredComponents.cs | 203 | C# |
using System;
namespace Nest
{
public abstract class QueryDescriptorBase<TDescriptor, TInterface>
: DescriptorBase<TDescriptor, TInterface>, IQuery
where TDescriptor : QueryDescriptorBase<TDescriptor, TInterface>, TInterface
where TInterface : class, IQuery
{
string IQuery.Name { get; set; }
public TDescriptor Name(string name) => Assign(a => a.Name = name);
double? IQuery.Boost { get; set; }
public TDescriptor Boost(double? boost) => Assign(a => a.Boost = boost);
bool IQuery.Conditionless => this.Conditionless;
protected abstract bool Conditionless { get; }
bool IQuery.IsVerbatim { get; set; }
public TDescriptor Verbatim(bool verbatim = true) => Assign(a => a.IsVerbatim = verbatim);
bool IQuery.IsStrict { get; set; }
public TDescriptor Strict(bool strict = true) => Assign(a => a.IsStrict = strict);
bool IQuery.IsWritable => Self.IsVerbatim || !Self.Conditionless;
}
}
| 31.724138 | 92 | 0.720652 | [
"Apache-2.0"
] | BedeGaming/elasticsearch-net | src/Nest/QueryDsl/Abstractions/Query/QueryDescriptorBase.cs | 922 | C# |
namespace BankTransferSample.Domain
{
/// <summary>交易状态
/// </summary>
public enum TransactionStatus
{
Started = 1,
PreparationCompleted,
Completed,
Canceled
}
}
| 17.461538 | 37 | 0.54185 | [
"MIT"
] | berkaroad/ENode.Eventual2PC | src/Samples/BankTransferSample/Domain/TransactionStatus.cs | 237 | C# |
using Microsoft.EntityFrameworkCore;
using Mix.Cms.Lib.Extensions;
namespace Mix.Cms.Lib.Models.Cms
{
public partial class MySqlMixCmsContext : MixCmsContext
{
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationDbContext" /> class.
/// </summary>
/// <param name="options">The options.</param>
public MySqlMixCmsContext(DbContextOptions<MixCmsContext> options)
: base(options)
{
}
public MySqlMixCmsContext()
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyAllConfigurationsFromNamespace(
this.GetType().Assembly,
"Mix.Cms.Lib.Models.EntityConfigurations.MySQL");
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
} | 30.387097 | 88 | 0.626327 | [
"MIT"
] | 1furkankaratas/mix.core | src/Mix.Cms.Lib/Models/Cms/_MySqlMixCmsContext.cs | 944 | C# |
namespace Unity.Tests.Override
{
public class TypeToInject2 : IInterfaceForTypesToInject
{
public TypeToInject2(int value)
{
Value = value;
}
public int Value { get; set; }
}
} | 21.090909 | 59 | 0.577586 | [
"Apache-2.0"
] | danielp37/container | tests/Unity.Tests/Override/TypeToInject2.cs | 232 | C# |
using ElBastard0.Api.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore.Sqlite;
using Microsoft.EntityFrameworkCore;
using ElBastard0.Api.Services;
namespace ElBastard0.Api.Extensions
{
/// <summary>
/// Extensions for IServiceCollection used by dependency injection
/// </summary>
internal static class ServiceCollectionExtensions
{
/// <summary>
/// Add database context from configuration connection string
/// </summary>
/// <param name="services">Application service collection</param>
/// <param name="configuration">Application configuration</param>
/// <returns>updated application service collection</returns>
public static IServiceCollection AddSqlServices(this IServiceCollection services, IConfiguration configuration)
{
// Sqlite context provider for demo purposes use e.g. SQL Server for production use
services.AddDbContext<MyDbContext>(
options => options.UseSqlite(configuration.GetConnectionString("DefaultConnection"))
);
return services;
}
/// <summary>
/// Add services for repository pattern data access
/// </summary>
/// <param name="services">Application service collection</param>
/// <returns>updated application service collection</returns>
public static IServiceCollection AddDataServices(this IServiceCollection services)
{
// Example entity service generic implementation
services.AddScoped(typeof(IEntityService<>), typeof(EntityService<>));
return services;
}
}
}
| 38.866667 | 119 | 0.679817 | [
"BSD-2-Clause"
] | el-bastard0/simple-inter-system-api-example | src/api/Extensions/ServiceCollectionExtensions.cs | 1,751 | C# |
/*****************************************************************************
* Copyright 2016 Aurora Solutions
*
* http://www.aurorasolutions.io
*
* Aurora Solutions is an innovative services and product company at
* the forefront of the software industry, with processes and practices
* involving Domain Driven Design(DDD), Agile methodologies to build
* scalable, secure, reliable and high performance products.
*
* Trade Mirror provides an infrastructure for low latency trade copying
* services from master to child traders, and also trader to different
* channels including social media. It is a highly customizable solution
* with low-latency signal transmission capabilities. The tool can copy trades
* from sender and publish them to all subscribed receiver’s in real time
* across a local network or the internet. Trade Mirror is built using
* languages and frameworks that include C#, C++, WPF, WCF, Socket Programming,
* MySQL, NUnit and MT4 and MT5 MetaTrader platforms.
*
* 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.
*****************************************************************************/
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.269
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(Namespace = "http://UpDownSingnalsServer.Services", ConfigurationName = "IUpDownSignals", CallbackContract = typeof(IUpDownSignalsCallback), SessionMode = System.ServiceModel.SessionMode.Required)]
public interface IUpDownSignals
{
[System.ServiceModel.OperationContractAttribute(Action = "http://UpDownSingnalsServer.Services/IUpDownSignals/Subscribe", ReplyAction = "http://UpDownSingnalsServer.Services/IUpDownSignals/SubscribeResponse")]
string Subscribe(string userName);
[System.ServiceModel.OperationContractAttribute(Action = "http://UpDownSingnalsServer.Services/IUpDownSignals/Unsubscribe", ReplyAction = "http://UpDownSingnalsServer.Services/IUpDownSignals/UnsubscribeResponse")]
bool Unsubscribe(string userName);
[System.ServiceModel.OperationContractAttribute(Action = "http://UpDownSingnalsServer.Services/IUpDownSignals/PublishNewSignal", ReplyAction = "http://UpDownSingnalsServer.Services/IUpDownSignals/PublishNewSignalResponse")]
void PublishNewSignal(string signalInformation);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface IUpDownSignalsCallback
{
[System.ServiceModel.OperationContractAttribute(IsOneWay = true, Action = "http://UpDownSingnalsServer.Services/IUpDownSignals/NewSignal")]
void NewSignal(string signalInformation);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface IUpDownSignalsChannel : IUpDownSignals, System.ServiceModel.IClientChannel
{
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class UpDownSignalsClient : System.ServiceModel.DuplexClientBase<IUpDownSignals>, IUpDownSignals
{
public UpDownSignalsClient(System.ServiceModel.InstanceContext callbackInstance) :
base(callbackInstance)
{
}
public UpDownSignalsClient(System.ServiceModel.InstanceContext callbackInstance, string endpointConfigurationName) :
base(callbackInstance, endpointConfigurationName)
{
}
public UpDownSignalsClient(System.ServiceModel.InstanceContext callbackInstance, string endpointConfigurationName, string remoteAddress) :
base(callbackInstance, endpointConfigurationName, remoteAddress)
{
}
public UpDownSignalsClient(System.ServiceModel.InstanceContext callbackInstance, string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(callbackInstance, endpointConfigurationName, remoteAddress)
{
}
public UpDownSignalsClient(System.ServiceModel.InstanceContext callbackInstance, System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(callbackInstance, binding, remoteAddress)
{
}
public string Subscribe(string userName)
{
return base.Channel.Subscribe(userName);
}
public bool Unsubscribe(string userName)
{
return base.Channel.Unsubscribe(userName);
}
public void PublishNewSignal(string signalInformation)
{
base.Channel.PublishNewSignal(signalInformation);
}
}
| 45.663866 | 244 | 0.722304 | [
"Apache-2.0"
] | trade-nexus/trade-mirror | Signals to Forex - BEN/Up Down Signals/UpDownSingnalsClientTerminal/Service/UpDownSignalsService.cs | 5,438 | C# |
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace AspNetCore.Security.Jwt.Microservice.Repository.Clients
{
/// <summary>
/// Class MovieProviderClient
/// </summary>
public class MovieProviderClient : IMovieProviderClient
{
HttpClient _client;
string _token;
int _noOfRetries;
public MovieProviderClient(string token, int noOfRetries)
{
_token = token;
_noOfRetries = noOfRetries;
}
/// <summary>
/// Get
/// </summary>
/// <typeparam name="TResponse">The response type</typeparam>
/// <param name="url">The url</param>
/// <returns><see cref="Task{TResponse}"/></returns>
public async Task<TResponse> Get<TResponse>(string url)
where TResponse : class
{
int i = 0;
bool isError = false;
do
{
try
{
isError = false;
_client = new HttpClient() { Timeout = new TimeSpan(0, 0, 2) };
_client.DefaultRequestHeaders.Add("x-access-token", _token);
return await _client.GetAsync(url)
.ContinueWith(async x =>
{
var result = x.Result;
result.EnsureSuccessStatusCode();
var response = await result.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TResponse>(response);
}).Result;
}
catch (Exception ex)
{
Thread.Sleep(1000);
Console.WriteLine($"Attempt {i+1} failed to get data from Provider {url}. {ex.Message}. Trying again.");
isError = true;
}
i++;
}
while (isError && (i < _noOfRetries));
return null;
}
}
}
| 32.142857 | 124 | 0.456889 | [
"MIT"
] | VeritasSoftware/AspNetCore.Security.Jwt.Microservice | AspNetCore.Security.Jwt.Microservice/Repository/Clients/MovieProviderClient.cs | 2,252 | C# |
using System.ComponentModel;
namespace Ztop.Todo.Model
{
public enum OASystemClass
{
[Description("任务系统")]
TaskSystem,
[Description("报销系统")]
ReimburseSystem
}
}
| 15.923077 | 29 | 0.603865 | [
"MIT"
] | LooWooTech/Kaopu | Ztop.Todo.Model/SystemClass.cs | 225 | C# |
// <auto-generated />
namespace DataModel.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 InitialDatabase : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(InitialDatabase));
string IMigrationMetadata.Id
{
get { return "201710272016597_InitialDatabase"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 28.5 | 99 | 0.603509 | [
"MIT"
] | MaxReinerAAE/Kundenverwaltung | DataModel/Migrations/201710272016597_InitialDatabase.Designer.cs | 855 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using Xunit;
namespace Yarp.ReverseProxy.Abstractions.Tests
{
public class ProxyRouteTests
{
[Fact]
public void Equals_Positive()
{
var a = new ProxyRoute()
{
AuthorizationPolicy = "a",
ClusterId = "c",
CorsPolicy = "co",
Match = new ProxyMatch()
{
Headers = new[]
{
new RouteHeader()
{
Name = "Hi",
Values = new[] { "v1", "v2" },
IsCaseSensitive = true,
Mode = HeaderMatchMode.HeaderPrefix,
}
},
Hosts = new[] { "foo:90" },
Methods = new[] { "GET", "POST" },
Path = "/p",
},
Metadata = new Dictionary<string, string>()
{
{ "m", "m1" }
},
Order = 1,
RouteId = "R",
};
var b = new ProxyRoute()
{
AuthorizationPolicy = "a",
ClusterId = "c",
CorsPolicy = "co",
Match = new ProxyMatch()
{
Headers = new[]
{
new RouteHeader()
{
Name = "Hi",
Values = new[] { "v1", "v2" },
IsCaseSensitive = true,
Mode = HeaderMatchMode.HeaderPrefix,
}
},
Hosts = new[] { "foo:90" },
Methods = new[] { "GET", "POST" },
Path = "/p"
},
Metadata = new Dictionary<string, string>()
{
{ "m", "m1" }
},
Order = 1,
RouteId = "R",
};
var c = b with { }; // Clone
Assert.True(a.Equals(b));
Assert.True(a.Equals(c));
}
[Fact]
public void Equals_Negative()
{
var a = new ProxyRoute()
{
AuthorizationPolicy = "a",
ClusterId = "c",
CorsPolicy = "co",
Match = new ProxyMatch()
{
Headers = new[]
{
new RouteHeader()
{
Name = "Hi",
Values = new[] { "v1", "v2" },
IsCaseSensitive = true,
Mode = HeaderMatchMode.HeaderPrefix,
}
},
Hosts = new[] { "foo:90" },
Methods = new[] { "GET", "POST" },
Path = "/p",
},
Metadata = new Dictionary<string, string>()
{
{ "m", "m1" }
},
Order = 1,
RouteId = "R",
};
var b = a with { AuthorizationPolicy = "b" };
var c = a with { ClusterId = "d" };
var d = a with { CorsPolicy = "p" };
var e = a with { Match = new ProxyMatch() };
var f = a with { Metadata = new Dictionary<string, string>() { { "f", "f1" } } };
var g = a with { Order = null };
var h = a with { RouteId = "h" };
Assert.False(a.Equals(b));
Assert.False(a.Equals(c));
Assert.False(a.Equals(d));
Assert.False(a.Equals(e));
Assert.False(a.Equals(f));
Assert.False(a.Equals(g));
Assert.False(a.Equals(h));
}
[Fact]
public void Equals_Null_False()
{
Assert.False(new ProxyRoute().Equals(null));
}
}
}
| 32.091603 | 93 | 0.335157 | [
"MIT"
] | JamesNK/reverse-proxy | test/ReverseProxy.Tests/Abstractions/RouteDiscovery/Contract/ProxyRouteTests.cs | 4,204 | C# |
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.2
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
namespace Grib.Api.Interop.SWIG {
public class GribStringList : global::System.IDisposable {
private global::System.Runtime.InteropServices.HandleRef swigCPtr;
protected bool swigCMemOwn;
internal GribStringList(global::System.IntPtr cPtr, bool cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
}
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(GribStringList obj) {
return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
}
~GribStringList() {
Dispose();
}
public virtual void Dispose() {
lock(this) {
if (swigCPtr.Handle != global::System.IntPtr.Zero) {
if (swigCMemOwn) {
swigCMemOwn = false;
GribApiProxyPINVOKE.delete_GribStringList(swigCPtr);
}
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
}
global::System.GC.SuppressFinalize(this);
}
}
public string value {
set {
GribApiProxyPINVOKE.GribStringList_value_set(swigCPtr, value);
}
get {
string ret = GribApiProxyPINVOKE.GribStringList_value_get(swigCPtr);
return ret;
}
}
public SWIGTYPE_p_grib_string_list next {
set {
GribApiProxyPINVOKE.GribStringList_next_set(swigCPtr, SWIGTYPE_p_grib_string_list.getCPtr(value));
}
get {
global::System.IntPtr cPtr = GribApiProxyPINVOKE.GribStringList_next_get(swigCPtr);
SWIGTYPE_p_grib_string_list ret = (cPtr == global::System.IntPtr.Zero) ? null : new SWIGTYPE_p_grib_string_list(cPtr, false);
return ret;
}
}
public GribStringList() : this(GribApiProxyPINVOKE.new_GribStringList(), true) {
}
}
}
| 32.205882 | 131 | 0.653881 | [
"Apache-2.0"
] | Jojas/GribApi.NET | src/GribApi.NET/Grib.Api/Interop/SWIG/GribStringList.cs | 2,190 | C# |
using DaSoft.Riviera.Modulador.Bordeo.Model;
using DaSoft.Riviera.Modulador.Bordeo.Model.Enities;
using DaSoft.Riviera.Modulador.Bordeo.Runtime;
using DaSoft.Riviera.Modulador.Core.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static DaSoft.Riviera.Modulador.Bordeo.Assets.Strings;
using static DaSoft.Riviera.Modulador.Bordeo.Assets.Codes;
namespace DaSoft.Riviera.Modulador.Bordeo.Controller
{
/// <summary>
/// Defines the bordeo class utils
/// Size Utility
/// </summary>
public static partial class BordeoUtils
{
/// <summary>
/// Gets the size of the linear drawing.
/// </summary>
/// <param name="nominal">The nominal value.</param>
/// <returns>The linear double value</returns>
public static Double GetLinearDrawingSize(this Double nominal)
{
double val;
if (nominal == 18d)
val = 0.457d;
else if (nominal == 24d)
val = 0.61d;
else if (nominal == 30d)
val = 0.762d;
else if (nominal == 36d)
val = 0.915d;
else if (nominal == 42d)
val = 1.067d;
else if (nominal == 48d)
val = 1.22d;
else
throw new BordeoException(String.Format(ERR_UNKNOWN_DRAWING_SIZE, nominal));
return val;
}
/// <summary>
/// Gets the size of the Panel L 90 drawing.
/// </summary>
/// <param name="nominal">The nominal value.</param>
/// <returns>The L double value</returns>
public static Double GetPanel90DrawingSize(this Double nominal)
{
double val;
if (nominal == 18d)
val = 0.3748d;
else if (nominal == 24d)
val = 0.5278d;
else if (nominal == 30d)
val = 0.67880210d;
else if (nominal == 36d)
val = 0.8328d;
else if (nominal == 42d)
val = 0.98380210d;
else if (nominal == 48d)
val = 1.1378d;
else
throw new BordeoException(String.Format(ERR_UNKNOWN_DRAWING_SIZE, nominal));
return val;
}
/// <summary>
/// Gets the size of the Panel L 135 drawing.
/// </summary>
/// <param name="nominal">The nominal value.</param>
/// <returns>The L double value</returns>
public static Double GetPanel135DrawingSize(this Double nominal)
{
double val;
if (nominal == 18d)
val = 0.42295164d;
else if (nominal == 24d)
val = 0.57595165d;
else if (nominal == 30d)
val = 0.72794954d;
else if (nominal == 36d)
val = 0.88095165d;
else if (nominal == 42d)
val = 1.03294954d;
else if (nominal == 48d)
val = 1.18595165d;
else
throw new BordeoException(String.Format(ERR_UNKNOWN_DRAWING_SIZE, nominal));
return val;
}
public static BordeoPanelHeight GetHeights(this IEnumerable<BordeoPanel> panels)
{
String panelHeightString = String.Empty;
foreach (BordeoPanel panel in panels)
panelHeightString += panel.PanelSize.Alto.Nominal == 27 ? "PB" : "Ps";
return panelHeightString.GetHeight();
}
public static BordeoPanelHeight GetHeights(this IEnumerable<BordeoLPanel> panels)
{
String panelHeightString = String.Empty;
foreach (BordeoLPanel panel in panels)
panelHeightString += panel.PanelSize.Alto.Nominal == 27 ? "PB" : "Ps";
return panelHeightString.GetHeight();
}
/// <summary>
/// Gets the height.
/// </summary>
/// <param name="panelHeightString">The panel height string.</param>
/// <returns>The panel height</returns>
public static BordeoPanelHeight GetHeight(this String panelHeightString)
{
BordeoPanelHeight value;
switch (panelHeightString)
{
case "PBPs":
value = BordeoPanelHeight.NormalMini;
break;
case "PBPsPB":
value = BordeoPanelHeight.NormalMiniNormal;
break;
case "PBPsPsPs":
value = BordeoPanelHeight.NormalThreeMini;
break;
case "PBPsPs":
value = BordeoPanelHeight.NormalTwoMinis;
break;
case "PBPBPB":
value = BordeoPanelHeight.ThreeNormals;
break;
case "PBPBPs":
value = BordeoPanelHeight.TwoNormalOneMini;
break;
case "PBPB":
value = BordeoPanelHeight.TwoNormals;
break;
default:
value = BordeoPanelHeight.None;
break;
}
return value;
}
/// <summary>
/// Gets the panel measure.
/// </summary>
/// <param name="code">The code.</param>
/// <param name="sizes">The sizes.</param>
/// <param name="selectedHeights">The selected heights.</param>
/// <param name="selectedFronts">The selected fronts.</param>
/// <returns></returns>
public static List<RivieraMeasure> GetPanelMeasure(this String code, Dictionary<String, ElementSizeCollection> sizes, RivieraSize[] selectedHeights, params RivieraSize[] selectedFronts)
{
List<RivieraMeasure> measure = new List<RivieraMeasure>();
var heights = selectedHeights;
RivieraSize startFront = selectedFronts[0];
RivieraSize endFront = selectedFronts.Length > 1 ? selectedFronts[1] : default(RivieraSize);
foreach (RivieraSize height in heights)
switch (code)
{
case CODE_PANEL_RECTO:
measure.Add(sizes[CODE_PANEL_RECTO].Sizes.Select(x => x as PanelMeasure).
FirstOrDefault(y => y.Alto == height && y.Frente == startFront));
break;
case CODE_PANEL_90:
measure.Add(sizes[CODE_PANEL_90].Sizes.Select(x => x as LPanelMeasure).
FirstOrDefault(y => y.Alto == height && y.FrenteStart == startFront && y.FrenteEnd == endFront));
break;
case CODE_PANEL_135:
measure.Add(sizes[CODE_PANEL_135].Sizes.Select(x => x as LPanelMeasure).
FirstOrDefault(y => y.Alto == height && y.FrenteStart == startFront && y.FrenteEnd == endFront));
break;
}
return measure;
}
}
}
| 40.219101 | 193 | 0.526191 | [
"MIT"
] | ANamelessWolf/RivieraModulador | Bordeo/Controller/BordeoSizeUtils.cs | 7,161 | C# |
using Assets.Scripts.Commands;
using Assets.Scripts.Communication.BluePrints;
using Assets.Scripts.StateMachine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using static Assets.Scripts.GameManager;
namespace Assets.Scripts
{
class IOTouchSwipeHandler : AbstractIOHandler
{
public enum Actions
{
SwipeUp,
SwipeDown
}
#region FIELDS
public static IOTouchSwipeHandler mInstance;
//private enum DraggedDirection
//{
// Up,
// Down,
// Right,
// Left
//}
#endregion
#region IDragHandler - IEndDragHandler
//bool isChosen = false;
//private static IOHandler mInstance = new IOHandler();
//private SubScene m_Subscene;
private GameManager m_GameManager;
private SceneEventManager mEventManager;
private int m_SceneIndex;
int fingerId;
private void Awake()
{
mInstance = this;
text.text = "IO started";
}
public void Start()
{
m_GameManager = GameManager.GetInstance();
//m_Subscene = GetComponentInParent<SubScene>();
//m_SceneIndex = m_Subscene.GetIndex();
}
//public static IOHandler GetIntance()
//{
// if(mInstance == null)
// {
// mInstance = new IOHandler();
// }
// return mInstance;
//}
//int GetSelectedScene(Vector2 position)
//{
// return (int)Math.Floor(Math.Max(0, Math.Min(Screen.height,
// position.y * 3 / Screen.height)));
//}
//bool IsChosenScene(Vector2 position)
//{
// bool isChosen = false;
// float min = Math.Min(Screen.height, position.y * 3 / Screen.height);
// float max = Math.Max(min, 0);
// double floor = Math.Floor(max);
// int floor2 = (int)floor;
// if (floor2 == m_SceneIndex)
// {
// isChosen = true;
// }
// return isChosen;
// //todo fix
// //return ((double)(Math.Floor(Math.Max(0, Math.Min(Screen.height, Input.mousePosition.y * 3 / Screen.height))) == m_SceneIndex;
//}
//public void Update()
//{
// ;
// if (IsChosenScene())
// {
// HandleInput();
// }
//}
public void HandleInput()
{
}
//private void SendSwipeToPlayer(int selectedSubScene, SwipeDirection direction)
//{
// PRActions action = PRActions.NULL;
// if (direction.Equals(SwipeDirection.Up))
// {
// action = PRActions.TOUCH_SWIPE_UP;
// text.text = "SwipeUp";
// }
// else if (direction.Equals(SwipeDirection.Down))
// {
// action = PRActions.TOUCH_SWIPE_DOWN;
// text.text = "SwipeDown";
// }
// ICommand command = CommandFactory.CreateCommandBehaviour()
// .WithAction(action)
// .Build();
// Request request = Request.CreateRequest()
// .WithReceiver(m_GameManager.GetReceiver(ReceiverId.Players, selectedSubScene))
// .WithCommand(command)
// .Build();
// Send(request);
//}
public void Send(Request request)
{
m_GameManager.SendMessage("AddRequest", request);
}
////It must be implemented otherwise IEndDragHandler won't work
//public void OnDrag(PointerEventData eventData)
//{
//}
//public void OnEndDrag(PointerEventData eventData)
//{
// Debug.Log("Press position + " + eventData.pressPosition);
// Debug.Log("End position + " + eventData.position);
// Vector3 dragVectorDirection = (eventData.position - eventData.pressPosition).normalized;
// Debug.Log("norm + " + dragVectorDirection);
// GetDragDirection(dragVectorDirection);
// if (IsChosenScene(eventData.pressPosition))
// {
// HandleInput();
// }
//}
//private DraggedDirection GetDragDirection(Vector3 dragVector)
//{
// float positiveX = Mathf.Abs(dragVector.x);
// float positiveY = Mathf.Abs(dragVector.y);
// DraggedDirection draggedDir;
// if (positiveX > positiveY)
// {
// draggedDir = (dragVector.x > 0) ? DraggedDirection.Right : DraggedDirection.Left;
// }
// else
// {
// draggedDir = (dragVector.y > 0) ? DraggedDirection.Up : DraggedDirection.Down;
// }
// Debug.Log(draggedDir);
// return draggedDir;
//}
#endregion
}
}
| 25.76699 | 141 | 0.508855 | [
"MIT"
] | StavFaran92/PiggyRun_Code | Scripts/IO/IOTouchSwipeHandler.cs | 5,310 | C# |
// ==========================================================================
// StringExtensionsTests.cs
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex Group
// All rights reserved.
// ==========================================================================
using System.Collections.Generic;
using Xunit;
namespace Squidex.Infrastructure
{
public class StringExtensionsTests
{
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void Should_provide_fallback_if_invalid(string value)
{
Assert.Equal("fallback", value.WithFallback("fallback"));
}
[Theory]
[InlineData("", "")]
[InlineData("m", "M")]
[InlineData("m-y", "MY")]
[InlineData("my", "My")]
[InlineData("myProperty ", "MyProperty")]
[InlineData("my property", "MyProperty")]
[InlineData("my_property", "MyProperty")]
[InlineData("my-property", "MyProperty")]
public void Should_convert_to_pascal_case(string input, string output)
{
Assert.Equal(output, input.ToPascalCase());
}
[Theory]
[InlineData("", "")]
[InlineData("M", "m")]
[InlineData("My", "my")]
[InlineData("M-y", "mY")]
[InlineData("MyProperty ", "myProperty")]
[InlineData("My property", "myProperty")]
[InlineData("My_property", "myProperty")]
[InlineData("My-property", "myProperty")]
public void Should_convert_to_camel_case(string input, string output)
{
Assert.Equal(output, input.ToCamelCase());
}
[Theory]
[InlineData("Hello World", '-', "hello-world")]
[InlineData("Hello/World", '-', "hello-world")]
[InlineData("Hello World", '_', "hello_world")]
[InlineData("Hello/World", '_', "hello_world")]
[InlineData("Hello World ", '_', "hello_world")]
[InlineData("Hello World-", '_', "hello_world")]
[InlineData("Hello/World_", '_', "hello_world")]
public void Should_replace_special_characters_with_sepator_when_simplifying(string input, char separator, string output)
{
Assert.Equal(output, input.Simplify(separator: separator));
}
[Theory]
[InlineData("ö", "oe")]
[InlineData("ü", "ue")]
[InlineData("ä", "ae")]
public void Should_replace_multi_char_diacritics_when_simplifying(string input, string output)
{
Assert.Equal(output, input.Simplify());
}
[Theory]
[InlineData("ö", "o")]
[InlineData("ü", "u")]
[InlineData("ä", "a")]
public void Should_not_replace_multi_char_diacritics_when_simplifying(string input, string output)
{
Assert.Equal(output, input.Simplify(singleCharDiactric: true));
}
[Theory]
[InlineData("Físh", "fish")]
[InlineData("źish", "zish")]
[InlineData("żish", "zish")]
[InlineData("fórm", "form")]
[InlineData("fòrm", "form")]
[InlineData("fårt", "fart")]
public void Should_replace_single_char_diacritics_when_simplifying(string input, string output)
{
Assert.Equal(output, input.Simplify());
}
[Theory]
[InlineData("Hello my&World ", '_', "hello_my&world")]
[InlineData("Hello my&World-", '_', "hello_my&world")]
[InlineData("Hello my/World_", '_', "hello_my/world")]
public void Should_keep_characters_when_simplifying(string input, char separator, string output)
{
Assert.Equal(output, input.Simplify(new HashSet<char> { '&', '/' }, false, separator));
}
[Fact]
public void Should_provide_value()
{
const string value = "value";
Assert.Equal(value, value.WithFallback("fallback"));
}
[Theory]
[InlineData("http://squidex.io/base/", "path/to/res", false, "http://squidex.io/base/path/to/res")]
[InlineData("http://squidex.io/base/", "path/to/res", true, "http://squidex.io/base/path/to/res/")]
[InlineData("http://squidex.io/base/", "/path/to/res", true, "http://squidex.io/base/path/to/res/")]
public void Should_provide_full_url_without_query_or_fragment(string baseUrl, string path, bool trailingSlash, string output)
{
var result = baseUrl.BuildFullUrl(path, trailingSlash);
Assert.Equal(output, result);
}
[Theory]
[InlineData("http://squidex.io/base/", "path/to/res?query=1", false, "http://squidex.io/base/path/to/res?query=1")]
[InlineData("http://squidex.io/base/", "path/to/res#query=1", true, "http://squidex.io/base/path/to/res#query=1")]
[InlineData("http://squidex.io/base/", "path/to/res;query=1", true, "http://squidex.io/base/path/to/res;query=1")]
public void Should_provide_full_url_wit_query_or_fragment(string baseUrl, string path, bool trailingSlash, string output)
{
var result = baseUrl.BuildFullUrl(path, trailingSlash);
Assert.Equal(output, result);
}
}
}
| 38.705882 | 133 | 0.565729 | [
"MIT"
] | maooson/squidex | tests/Squidex.Infrastructure.Tests/StringExtensionsTests.cs | 5,278 | C# |
using UnityEngine;
namespace NotificationSamples.Demo
{
/// <summary>
/// Inventory item data.
/// </summary>
[CreateAssetMenu(fileName = "InventoryItemData", menuName = "NotificationsSamples/Inventory Item", order = 1)]
public class InventoryItemData : ScriptableObject
{
[Tooltip("Item's title.")]
public string Title;
[Tooltip("Item's description.")]
public string Description;
[Tooltip("The item's icon to use in the UI.")]
public Sprite Icon;
[Tooltip("Item's initial cost.")]
public int InitialCost;
[Tooltip("Cost increase every time it is bought.")]
public int CostIncrease;
[Tooltip("How long it takes to create the item after buying it (minutes).")]
public float InitialCreationTime;
[Tooltip("Increase the creation time every time it is bought (minutes).")]
public float CreationTimeIncrease;
[Tooltip("Currency bonus the item provides per second.")]
public float CurrencyBonus;
[Tooltip("Notification icon ID.")]
public string IconId;
}
}
| 29.025641 | 114 | 0.638693 | [
"MIT"
] | AI3SW/ai_job_teacher_unity | AiJobTeacherUnity/Assets/Samples/Mobile Notifications/1.4.2/Notification Samples/Demo/InventoryItemData.cs | 1,132 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft.Azure.Devices.Shared.UWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft.Azure.Devices.Shared.UWP")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: ComVisible(false)]
#if (RELEASE_DELAY_SIGN)
[assembly: AssemblyDelaySignAttribute(true)]
[assembly: AssemblyKeyFileAttribute("35MSSharedLib1024.snk")]
#endif
// Version information for an assembly follows semantic versioning 1.0.0 (because
// NuGet didn't support semver 2.0.0 before VS 2015). See semver.org for details.
[assembly: AssemblyInformationalVersion("1.0.8")]
| 36.972973 | 84 | 0.754386 | [
"MIT"
] | harunpehlivan/azure-iot-sdk-csharp | shared/Microsoft.Azure.Devices.Shared.UWP/Properties/AssemblyInfo.cs | 1,371 | 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 servicecatalog-appregistry-2020-06-24.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AppRegistry.Model
{
/// <summary>
/// This is the response object from the DisassociateAttributeGroup operation.
/// </summary>
public partial class DisassociateAttributeGroupResponse : AmazonWebServiceResponse
{
private string _applicationArn;
private string _attributeGroupArn;
/// <summary>
/// Gets and sets the property ApplicationArn.
/// <para>
/// The Amazon resource name (ARN) that specifies the application.
/// </para>
/// </summary>
public string ApplicationArn
{
get { return this._applicationArn; }
set { this._applicationArn = value; }
}
// Check to see if ApplicationArn property is set
internal bool IsSetApplicationArn()
{
return this._applicationArn != null;
}
/// <summary>
/// Gets and sets the property AttributeGroupArn.
/// <para>
/// The Amazon resource name (ARN) that specifies the attribute group.
/// </para>
/// </summary>
public string AttributeGroupArn
{
get { return this._attributeGroupArn; }
set { this._attributeGroupArn = value; }
}
// Check to see if AttributeGroupArn property is set
internal bool IsSetAttributeGroupArn()
{
return this._attributeGroupArn != null;
}
}
} | 31.960526 | 125 | 0.626184 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/AppRegistry/Generated/Model/DisassociateAttributeGroupResponse.cs | 2,429 | C# |
// <copyright file="ProcessDataReceivedEventArgs.cs" company="Hottinger Baldwin Messtechnik GmbH">
//
// Hbm.Automation.Api, a library to communicate with HBM weighing technology devices
//
// The MIT License (MIT)
//
// Copyright (C) Hottinger Baldwin Messtechnik GmbH
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// </copyright>
namespace Hbm.Automation.Api.Data
{
using System;
/// <summary>
/// Event to extend the event based call with an interface containing real-time process data.
/// Called by the update method ("OnData()") of the classes WtxJet and WtxModbus to send the
/// process data to the application class.
/// </summary>
public class ProcessDataReceivedEventArgs : EventArgs
{
#region =============== constructors & destructors =================
/// <summary>
/// Initializes a new instance of the <see cref="ProcessDataReceivedEventArgs" /> class.
/// </summary>
/// <param name="processData">Instance of interface IProcessData</param>
public ProcessDataReceivedEventArgs(IProcessData processData)
{
ProcessData = processData;
}
#endregion
#region ======================== properties ========================
/// <summary>
/// Gets or sets an instance of interface IProcessData containing the process data
/// </summary>
public IProcessData ProcessData { get; set; }
#endregion
}
} | 41.9 | 99 | 0.681782 | [
"MIT"
] | HBM/Automation-API | Hbm.Automation.API/Data/ProcessDataReceivedEventArgs.cs | 2,516 | C# |
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using KellermanSoftware.CompareNetObjects;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Utility functions providing some benefit to API client consumers.
/// </summary>
public static class ClientUtils
{
/// <summary>
/// An instance of CompareLogic.
/// </summary>
public static CompareLogic compareLogic;
/// <summary>
/// Static constructor to initialise compareLogic.
/// </summary>
static ClientUtils()
{
compareLogic = new CompareLogic();
}
/// <summary>
/// Sanitize filename by removing the path
/// </summary>
/// <param name="filename">Filename</param>
/// <returns>Filename</returns>
public static string SanitizeFilename(string filename)
{
Match match = Regex.Match(filename, @".*[/\\](.*)$");
return match.Success ? match.Groups[1].Value : filename;
}
/// <summary>
/// Convert params to key/value pairs.
/// Use collectionFormat to properly format lists and collections.
/// </summary>
/// <param name="collectionFormat">The swagger-supported collection format, one of: csv, tsv, ssv, pipes, multi</param>
/// <param name="name">Key name.</param>
/// <param name="value">Value object.</param>
/// <returns>A multimap of keys with 1..n associated values.</returns>
public static Multimap<string, string> ParameterToMultiMap(string collectionFormat, string name, object value)
{
var parameters = new Multimap<string, string>();
if (value is ICollection collection && collectionFormat == "multi")
{
foreach (var item in collection)
{
parameters.Add(name, ParameterToString(item));
}
}
else if (value is IDictionary dictionary)
{
if(collectionFormat == "deepObject") {
foreach (DictionaryEntry entry in dictionary)
{
parameters.Add(name + "[" + entry.Key + "]", ParameterToString(entry.Value));
}
}
else {
foreach (DictionaryEntry entry in dictionary)
{
parameters.Add(entry.Key.ToString(), ParameterToString(entry.Value));
}
}
}
else
{
parameters.Add(name, ParameterToString(value));
}
return parameters;
}
/// <summary>
/// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime.
/// If parameter is a list, join the list with ",".
/// Otherwise just return the string.
/// </summary>
/// <param name="obj">The parameter (header, path, query, form).</param>
/// <param name="configuration">An optional configuration instance, providing formatting options used in processing.</param>
/// <returns>Formatted string.</returns>
public static string ParameterToString(object obj, IReadableConfiguration configuration = null)
{
if (obj is DateTime dateTime)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return dateTime.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat);
if (obj is DateTimeOffset dateTimeOffset)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return dateTimeOffset.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat);
if (obj is bool boolean)
return boolean ? "true" : "false";
if (obj is ICollection collection)
return string.Join(",", collection.Cast<object>());
return Convert.ToString(obj, CultureInfo.InvariantCulture);
}
/// <summary>
/// Encode string in base64 format.
/// </summary>
/// <param name="text">string to be encoded.</param>
/// <returns>Encoded string.</returns>
public static string Base64Encode(string text)
{
return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text));
}
/// <summary>
/// Convert stream to byte array
/// </summary>
/// <param name="inputStream">Input stream to be converted</param>
/// <returns>Byte array</returns>
public static byte[] ReadAsBytes(Stream inputStream)
{
using (var ms = new MemoryStream())
{
inputStream.CopyTo(ms);
return ms.ToArray();
}
}
/// <summary>
/// Select the Content-Type header's value from the given content-type array:
/// if JSON type exists in the given array, use it;
/// otherwise use the first one defined in 'consumes'
/// </summary>
/// <param name="contentTypes">The Content-Type array to select from.</param>
/// <returns>The Content-Type header to use.</returns>
public static string SelectHeaderContentType(string[] contentTypes)
{
if (contentTypes.Length == 0)
return null;
foreach (var contentType in contentTypes)
{
if (IsJsonMime(contentType))
return contentType;
}
return contentTypes[0]; // use the first content type specified in 'consumes'
}
/// <summary>
/// Select the Accept header's value from the given accepts array:
/// if JSON exists in the given array, use it;
/// otherwise use all of them (joining into a string)
/// </summary>
/// <param name="accepts">The accepts array to select from.</param>
/// <returns>The Accept header to use.</returns>
public static string SelectHeaderAccept(string[] accepts)
{
if (accepts.Length == 0)
return null;
if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase))
return "application/json";
return string.Join(",", accepts);
}
/// <summary>
/// Provides a case-insensitive check that a provided content type is a known JSON-like content type.
/// </summary>
public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$");
/// <summary>
/// Check if the given MIME is a JSON MIME.
/// JSON MIME examples:
/// application/json
/// application/json; charset=UTF8
/// APPLICATION/JSON
/// application/vnd.company+json
/// </summary>
/// <param name="mime">MIME</param>
/// <returns>Returns True if MIME type is json.</returns>
public static bool IsJsonMime(string mime)
{
if (string.IsNullOrWhiteSpace(mime)) return false;
return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json");
}
}
}
| 39.827751 | 133 | 0.574003 | [
"Apache-2.0"
] | 1inker/openapi-generator | samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ClientUtils.cs | 8,324 | C# |
using JT808.Protocol.Attributes;
using JT808.Protocol.Formatters;
using JT808.Protocol.MessagePack;
namespace JT808.Protocol
{
/// <summary>
/// 统一分包数据体
/// </summary>
public class JT808SplitPackageBodies : JT808Bodies, IJT808MessagePackFormatter<JT808SplitPackageBodies>
{
public byte[] Data { get; set; }
public override ushort MsgId => 0xFFFF;
public JT808SplitPackageBodies Deserialize(ref JT808MessagePackReader reader, IJT808Config config)
{
JT808SplitPackageBodies jT808SplitPackageBodies = new JT808SplitPackageBodies
{
Data = reader.ReadContent().ToArray()
};
return jT808SplitPackageBodies;
}
public void Serialize(ref JT808MessagePackWriter writer, JT808SplitPackageBodies value, IJT808Config config)
{
writer.WriteArray(value.Data);
}
}
}
| 28.8125 | 116 | 0.663774 | [
"MIT"
] | 491134648/JT808 | src/JT808.Protocol/JT808SplitPackageBodies.cs | 938 | 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 resourcegroupstaggingapi-2017-01-26.normal.json service model.
*/
using System;
using System.Collections.Generic;
using Amazon.ResourceGroupsTaggingAPI.Model;
using Amazon.ResourceGroupsTaggingAPI.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.ResourceGroupsTaggingAPI
{
/// <summary>
/// Implementation for accessing ResourceGroupsTaggingAPI
///
/// Resource Groups Tagging API
/// <para>
/// This guide describes the API operations for the resource groups tagging.
/// </para>
///
/// <para>
/// A tag is a label that you assign to an AWS resource. A tag consists of a key and a
/// value, both of which you define. For example, if you have two Amazon EC2 instances,
/// you might assign both a tag key of "Stack." But the value of "Stack" might be "Testing"
/// for one and "Production" for the other.
/// </para>
///
/// <para>
/// Tagging can help you organize your resources and enables you to simplify resource
/// management, access management and cost allocation. For more information about tagging,
/// see <a href="http://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/tag-editor.html">Working
/// with Tag Editor</a> and <a href="http://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/resource-groups.html">Working
/// with Resource Groups</a>. For more information about permissions you need to use the
/// resource groups tagging APIs, see <a href="http://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/obtaining-permissions-for-resource-groups.html">Obtaining
/// Permissions for Resource Groups </a> and <a href="http://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/obtaining-permissions-for-tagging.html">Obtaining
/// Permissions for Tagging </a>.
/// </para>
///
/// <para>
/// You can use the resource groups tagging APIs to complete the following tasks:
/// </para>
/// <ul> <li>
/// <para>
/// Tag and untag supported resources located in the specified region for the AWS account
/// </para>
/// </li> <li>
/// <para>
/// Use tag-based filters to search for resources located in the specified region for
/// the AWS account
/// </para>
/// </li> <li>
/// <para>
/// List all existing tag keys in the specified region for the AWS account
/// </para>
/// </li> <li>
/// <para>
/// List all existing values for the specified key in the specified region for the AWS
/// account
/// </para>
/// </li> </ul>
/// <para>
/// Not all resources can have tags. For a lists of resources that you can tag, see <a
/// href="http://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/supported-resources.html">Supported
/// Resources</a> in the <i>AWS Resource Groups and Tag Editor User Guide</i>.
/// </para>
///
/// <para>
/// To make full use of the resource groups tagging APIs, you might need additional IAM
/// permissions, including permission to access the resources of individual services as
/// well as permission to view and apply tags to those resources. For more information,
/// see <a href="http://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/obtaining-permissions-for-tagging.html">Obtaining
/// Permissions for Tagging</a> in the <i>AWS Resource Groups and Tag Editor User Guide</i>.
/// </para>
/// </summary>
public partial class AmazonResourceGroupsTaggingAPIClient : AmazonServiceClient, IAmazonResourceGroupsTaggingAPI
{
#region Constructors
/// <summary>
/// Constructs AmazonResourceGroupsTaggingAPIClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonResourceGroupsTaggingAPIClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonResourceGroupsTaggingAPIConfig()) { }
/// <summary>
/// Constructs AmazonResourceGroupsTaggingAPIClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonResourceGroupsTaggingAPIClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonResourceGroupsTaggingAPIConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonResourceGroupsTaggingAPIClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonResourceGroupsTaggingAPIClient Configuration Object</param>
public AmazonResourceGroupsTaggingAPIClient(AmazonResourceGroupsTaggingAPIConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonResourceGroupsTaggingAPIClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonResourceGroupsTaggingAPIClient(AWSCredentials credentials)
: this(credentials, new AmazonResourceGroupsTaggingAPIConfig())
{
}
/// <summary>
/// Constructs AmazonResourceGroupsTaggingAPIClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonResourceGroupsTaggingAPIClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonResourceGroupsTaggingAPIConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonResourceGroupsTaggingAPIClient with AWS Credentials and an
/// AmazonResourceGroupsTaggingAPIClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonResourceGroupsTaggingAPIClient Configuration Object</param>
public AmazonResourceGroupsTaggingAPIClient(AWSCredentials credentials, AmazonResourceGroupsTaggingAPIConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonResourceGroupsTaggingAPIClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonResourceGroupsTaggingAPIClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonResourceGroupsTaggingAPIConfig())
{
}
/// <summary>
/// Constructs AmazonResourceGroupsTaggingAPIClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonResourceGroupsTaggingAPIClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonResourceGroupsTaggingAPIConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonResourceGroupsTaggingAPIClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonResourceGroupsTaggingAPIClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonResourceGroupsTaggingAPIClient Configuration Object</param>
public AmazonResourceGroupsTaggingAPIClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonResourceGroupsTaggingAPIConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonResourceGroupsTaggingAPIClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonResourceGroupsTaggingAPIClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonResourceGroupsTaggingAPIConfig())
{
}
/// <summary>
/// Constructs AmazonResourceGroupsTaggingAPIClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonResourceGroupsTaggingAPIClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonResourceGroupsTaggingAPIConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonResourceGroupsTaggingAPIClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonResourceGroupsTaggingAPIClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonResourceGroupsTaggingAPIClient Configuration Object</param>
public AmazonResourceGroupsTaggingAPIClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonResourceGroupsTaggingAPIConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region GetResources
/// <summary>
/// Returns all the tagged resources that are associated with the specified tags (keys
/// and values) located in the specified region for the AWS account. The tags and the
/// resource types that you specify in the request are known as <i>filters</i>. The response
/// includes all tags that are associated with the requested resources. If no filter is
/// provided, this action returns a paginated resource list with the associated tags.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetResources service method.</param>
///
/// <returns>The response from the GetResources service method, as returned by ResourceGroupsTaggingAPI.</returns>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.InternalServiceException">
/// The request processing failed because of an unknown error, exception, or failure.
/// You can retry the request.
/// </exception>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.InvalidParameterException">
/// A parameter is missing or a malformed string or invalid or out-of-range value was
/// supplied for the request parameter.
/// </exception>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.PaginationTokenExpiredException">
/// A <code>PaginationToken</code> is valid for a maximum of 15 minutes. Your request
/// was denied because the specified <code>PaginationToken</code> has expired.
/// </exception>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.ThrottledException">
/// The request was denied to limit the frequency of submitted requests.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/GetResources">REST API Reference for GetResources Operation</seealso>
public virtual GetResourcesResponse GetResources(GetResourcesRequest request)
{
var marshaller = new GetResourcesRequestMarshaller();
var unmarshaller = GetResourcesResponseUnmarshaller.Instance;
return Invoke<GetResourcesRequest,GetResourcesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetResources operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetResources operation on AmazonResourceGroupsTaggingAPIClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetResources
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/GetResources">REST API Reference for GetResources Operation</seealso>
public virtual IAsyncResult BeginGetResources(GetResourcesRequest request, AsyncCallback callback, object state)
{
var marshaller = new GetResourcesRequestMarshaller();
var unmarshaller = GetResourcesResponseUnmarshaller.Instance;
return BeginInvoke<GetResourcesRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetResources operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetResources.</param>
///
/// <returns>Returns a GetResourcesResult from ResourceGroupsTaggingAPI.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/GetResources">REST API Reference for GetResources Operation</seealso>
public virtual GetResourcesResponse EndGetResources(IAsyncResult asyncResult)
{
return EndInvoke<GetResourcesResponse>(asyncResult);
}
#endregion
#region GetTagKeys
/// <summary>
/// Returns all tag keys in the specified region for the AWS account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetTagKeys service method.</param>
///
/// <returns>The response from the GetTagKeys service method, as returned by ResourceGroupsTaggingAPI.</returns>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.InternalServiceException">
/// The request processing failed because of an unknown error, exception, or failure.
/// You can retry the request.
/// </exception>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.InvalidParameterException">
/// A parameter is missing or a malformed string or invalid or out-of-range value was
/// supplied for the request parameter.
/// </exception>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.PaginationTokenExpiredException">
/// A <code>PaginationToken</code> is valid for a maximum of 15 minutes. Your request
/// was denied because the specified <code>PaginationToken</code> has expired.
/// </exception>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.ThrottledException">
/// The request was denied to limit the frequency of submitted requests.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/GetTagKeys">REST API Reference for GetTagKeys Operation</seealso>
public virtual GetTagKeysResponse GetTagKeys(GetTagKeysRequest request)
{
var marshaller = new GetTagKeysRequestMarshaller();
var unmarshaller = GetTagKeysResponseUnmarshaller.Instance;
return Invoke<GetTagKeysRequest,GetTagKeysResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetTagKeys operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetTagKeys operation on AmazonResourceGroupsTaggingAPIClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetTagKeys
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/GetTagKeys">REST API Reference for GetTagKeys Operation</seealso>
public virtual IAsyncResult BeginGetTagKeys(GetTagKeysRequest request, AsyncCallback callback, object state)
{
var marshaller = new GetTagKeysRequestMarshaller();
var unmarshaller = GetTagKeysResponseUnmarshaller.Instance;
return BeginInvoke<GetTagKeysRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetTagKeys operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetTagKeys.</param>
///
/// <returns>Returns a GetTagKeysResult from ResourceGroupsTaggingAPI.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/GetTagKeys">REST API Reference for GetTagKeys Operation</seealso>
public virtual GetTagKeysResponse EndGetTagKeys(IAsyncResult asyncResult)
{
return EndInvoke<GetTagKeysResponse>(asyncResult);
}
#endregion
#region GetTagValues
/// <summary>
/// Returns all tag values for the specified key in the specified region for the AWS account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetTagValues service method.</param>
///
/// <returns>The response from the GetTagValues service method, as returned by ResourceGroupsTaggingAPI.</returns>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.InternalServiceException">
/// The request processing failed because of an unknown error, exception, or failure.
/// You can retry the request.
/// </exception>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.InvalidParameterException">
/// A parameter is missing or a malformed string or invalid or out-of-range value was
/// supplied for the request parameter.
/// </exception>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.PaginationTokenExpiredException">
/// A <code>PaginationToken</code> is valid for a maximum of 15 minutes. Your request
/// was denied because the specified <code>PaginationToken</code> has expired.
/// </exception>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.ThrottledException">
/// The request was denied to limit the frequency of submitted requests.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/GetTagValues">REST API Reference for GetTagValues Operation</seealso>
public virtual GetTagValuesResponse GetTagValues(GetTagValuesRequest request)
{
var marshaller = new GetTagValuesRequestMarshaller();
var unmarshaller = GetTagValuesResponseUnmarshaller.Instance;
return Invoke<GetTagValuesRequest,GetTagValuesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetTagValues operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetTagValues operation on AmazonResourceGroupsTaggingAPIClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetTagValues
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/GetTagValues">REST API Reference for GetTagValues Operation</seealso>
public virtual IAsyncResult BeginGetTagValues(GetTagValuesRequest request, AsyncCallback callback, object state)
{
var marshaller = new GetTagValuesRequestMarshaller();
var unmarshaller = GetTagValuesResponseUnmarshaller.Instance;
return BeginInvoke<GetTagValuesRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetTagValues operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetTagValues.</param>
///
/// <returns>Returns a GetTagValuesResult from ResourceGroupsTaggingAPI.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/GetTagValues">REST API Reference for GetTagValues Operation</seealso>
public virtual GetTagValuesResponse EndGetTagValues(IAsyncResult asyncResult)
{
return EndInvoke<GetTagValuesResponse>(asyncResult);
}
#endregion
#region TagResources
/// <summary>
/// Applies one or more tags to the specified resources. Note the following:
///
/// <ul> <li>
/// <para>
/// Not all resources can have tags. For a list of resources that support tagging, see
/// <a href="http://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/supported-resources.html">Supported
/// Resources</a> in the <i>AWS Resource Groups and Tag Editor User Guide</i>.
/// </para>
/// </li> <li>
/// <para>
/// Each resource can have up to 50 tags. For other limits, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-restrictions">Tag
/// Restrictions</a> in the <i>Amazon EC2 User Guide for Linux Instances</i>.
/// </para>
/// </li> <li>
/// <para>
/// You can only tag resources that are located in the specified region for the AWS account.
/// </para>
/// </li> <li>
/// <para>
/// To add tags to a resource, you need the necessary permissions for the service that
/// the resource belongs to as well as permissions for adding tags. For more information,
/// see <a href="http://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/obtaining-permissions-for-tagging.html">Obtaining
/// Permissions for Tagging</a> in the <i>AWS Resource Groups and Tag Editor User Guide</i>.
/// </para>
/// </li> </ul>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TagResources service method.</param>
///
/// <returns>The response from the TagResources service method, as returned by ResourceGroupsTaggingAPI.</returns>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.InternalServiceException">
/// The request processing failed because of an unknown error, exception, or failure.
/// You can retry the request.
/// </exception>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.InvalidParameterException">
/// A parameter is missing or a malformed string or invalid or out-of-range value was
/// supplied for the request parameter.
/// </exception>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.ThrottledException">
/// The request was denied to limit the frequency of submitted requests.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/TagResources">REST API Reference for TagResources Operation</seealso>
public virtual TagResourcesResponse TagResources(TagResourcesRequest request)
{
var marshaller = new TagResourcesRequestMarshaller();
var unmarshaller = TagResourcesResponseUnmarshaller.Instance;
return Invoke<TagResourcesRequest,TagResourcesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the TagResources operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the TagResources operation on AmazonResourceGroupsTaggingAPIClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndTagResources
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/TagResources">REST API Reference for TagResources Operation</seealso>
public virtual IAsyncResult BeginTagResources(TagResourcesRequest request, AsyncCallback callback, object state)
{
var marshaller = new TagResourcesRequestMarshaller();
var unmarshaller = TagResourcesResponseUnmarshaller.Instance;
return BeginInvoke<TagResourcesRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the TagResources operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginTagResources.</param>
///
/// <returns>Returns a TagResourcesResult from ResourceGroupsTaggingAPI.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/TagResources">REST API Reference for TagResources Operation</seealso>
public virtual TagResourcesResponse EndTagResources(IAsyncResult asyncResult)
{
return EndInvoke<TagResourcesResponse>(asyncResult);
}
#endregion
#region UntagResources
/// <summary>
/// Removes the specified tags from the specified resources. When you specify a tag key,
/// the action removes both that key and its associated value. The operation succeeds
/// even if you attempt to remove tags from a resource that were already removed. Note
/// the following:
///
/// <ul> <li>
/// <para>
/// To remove tags from a resource, you need the necessary permissions for the service
/// that the resource belongs to as well as permissions for removing tags. For more information,
/// see <a href="http://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/obtaining-permissions-for-tagging.html">Obtaining
/// Permissions for Tagging</a> in the <i>AWS Resource Groups and Tag Editor User Guide</i>.
/// </para>
/// </li> <li>
/// <para>
/// You can only tag resources that are located in the specified region for the AWS account.
/// </para>
/// </li> </ul>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UntagResources service method.</param>
///
/// <returns>The response from the UntagResources service method, as returned by ResourceGroupsTaggingAPI.</returns>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.InternalServiceException">
/// The request processing failed because of an unknown error, exception, or failure.
/// You can retry the request.
/// </exception>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.InvalidParameterException">
/// A parameter is missing or a malformed string or invalid or out-of-range value was
/// supplied for the request parameter.
/// </exception>
/// <exception cref="Amazon.ResourceGroupsTaggingAPI.Model.ThrottledException">
/// The request was denied to limit the frequency of submitted requests.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/UntagResources">REST API Reference for UntagResources Operation</seealso>
public virtual UntagResourcesResponse UntagResources(UntagResourcesRequest request)
{
var marshaller = new UntagResourcesRequestMarshaller();
var unmarshaller = UntagResourcesResponseUnmarshaller.Instance;
return Invoke<UntagResourcesRequest,UntagResourcesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the UntagResources operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UntagResources operation on AmazonResourceGroupsTaggingAPIClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUntagResources
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/UntagResources">REST API Reference for UntagResources Operation</seealso>
public virtual IAsyncResult BeginUntagResources(UntagResourcesRequest request, AsyncCallback callback, object state)
{
var marshaller = new UntagResourcesRequestMarshaller();
var unmarshaller = UntagResourcesResponseUnmarshaller.Instance;
return BeginInvoke<UntagResourcesRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UntagResources operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUntagResources.</param>
///
/// <returns>Returns a UntagResourcesResult from ResourceGroupsTaggingAPI.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/UntagResources">REST API Reference for UntagResources Operation</seealso>
public virtual UntagResourcesResponse EndUntagResources(IAsyncResult asyncResult)
{
return EndInvoke<UntagResourcesResponse>(asyncResult);
}
#endregion
}
} | 53.925758 | 176 | 0.669523 | [
"Apache-2.0"
] | Murcho/aws-sdk-net | sdk/src/Services/ResourceGroupsTaggingAPI/Generated/_bcl35/AmazonResourceGroupsTaggingAPIClient.cs | 35,591 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace AsyncStreams
{
class Program
{
static async Task Main(string[] args)
{
await foreach (int i in GetEmployeeIDAsync(5))
{
Console.WriteLine(i);
}
Console.ReadLine();
}
static async IAsyncEnumerable<int> GetEmployeeIDAsync(int input)
{
int id = 0;
List<int> tempID = new List<int>();
for (int i = 0; i < input; i++)
{
await Task.Delay(1000);
id += i; // Hypothetical calculation
yield return id;
}
}
}
}
| 22 | 72 | 0.486226 | [
"MIT"
] | BhupeshGuptha/Enterprise-Application-Development-with-C-Sharp-9-and-.NET-5 | Chapter04/AsyncStreams/Program.cs | 728 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace SmartValley.Domain.Entities
{
public class Country
{
public long Id { get; set; }
[Required, MaxLength(2)]
public string Code { get; set; }
public ICollection<User> Users { get; set; }
public ICollection<Project> Projects { get; set; }
public ICollection<ScoringApplication> ScoringApplications { get; set; }
public ICollection<ExpertApplication> ExpertApplications { get; set; }
}
} | 30.222222 | 80 | 0.674632 | [
"MIT"
] | SmartValleyEcosystem/smartvalley | SmartValley.Domain/Entities/Country.cs | 546 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using Charlotte.Tools;
using Charlotte.Tests;
namespace Charlotte
{
class Program
{
public const string APP_IDENT = "{3ef0127e-8a83-4299-8af9-1f7afeacf106}";
public const string APP_TITLE = "Knapsack";
static void Main(string[] args)
{
ProcMain.CUIMain(new Program().Main2, APP_IDENT, APP_TITLE);
#if DEBUG
//if (ProcMain.CUIError)
{
Console.WriteLine("Press ENTER.");
Console.ReadLine();
}
#endif
}
private void Main2(ArgsReader ar)
{
new Test0001().Test01();
}
}
}
| 17.916667 | 75 | 0.703876 | [
"MIT"
] | stackprobe/CSharp | Labo/Knapsack/Knapsack/Program.cs | 647 | C# |
// The MIT License (MIT)
//
// Copyright (c) 2015-2020 Rasmus Mikkelsen
// Copyright (c) 2015-2020 eBay Software Foundation
// Modified from original source https://github.com/eventflow/EventFlow
//
// Copyright (c) 2018 - 2020 Lutando Ngqakaza
// https://github.com/Lutando/Akkatecture
//
//
// 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.ComponentModel;
using FluentAssertions;
using M5x.Akka.Aggregates;
using M5x.Akka.Core;
using M5x.Akka.Extensions;
using M5x.Akka.TestHelpers;
using Xunit;
namespace M5x.Akka.Tests.UnitTests.Extensions
{
[Category(Categories.Unit)]
public class TypeExtensionTests
{
[Theory]
[InlineData(typeof(string), "String")]
[InlineData(typeof(int), "Int32")]
[InlineData(typeof(IEnumerable<>), "IEnumerable<>")]
[InlineData(typeof(KeyValuePair<,>), "KeyValuePair<,>")]
[InlineData(typeof(IEnumerable<string>), "IEnumerable<String>")]
[InlineData(typeof(IEnumerable<IEnumerable<string>>), "IEnumerable<IEnumerable<String>>")]
[InlineData(typeof(KeyValuePair<bool, long>), "KeyValuePair<Boolean,Int64>")]
[InlineData(typeof(KeyValuePair<KeyValuePair<bool, long>, KeyValuePair<bool, long>>), "KeyValuePair<KeyValuePair<Boolean,Int64>,KeyValuePair<Boolean,Int64>>")]
public void PrettyPrint_Output_ShouldBeExpected(Type type, string expectedPrettyPrint)
{
var prettyPrint = type.PrettyPrint();
prettyPrint.Should().Be(expectedPrettyPrint);
}
[Theory]
[InlineData(typeof(FooAggregateWithOutAttribute), "FooAggregateWithOutAttribute")]
[InlineData(typeof(FooAggregateWithAttribute), "BetterNameForAggregate")]
public void AggregateName_FromType_ShouldBeExpected(Type aggregateType, string expectedAggregateName)
{
var aggregateName = aggregateType.GetAggregateName();
aggregateName.Value.Should().Be(expectedAggregateName);
}
[Fact]
public void AggregateName_WithNullString_Throws()
{
this.Invoking(test => new AggregateNameAttribute(null)).Should().Throw<ArgumentNullException>();
}
public class FooId : Identity<FooId>
{
public FooId(string value) : base(value)
{
}
}
public class FooAggregateWithOutAttribute : AggregateRoot<FooAggregateWithOutAttribute, FooId, FooStateWithOutAttribute>
{
public FooAggregateWithOutAttribute(FooId id) : base(id)
{
}
}
[AggregateName("BetterNameForAggregate")]
public class FooAggregateWithAttribute : AggregateRoot<FooAggregateWithAttribute, FooId, FooStateWithAttribute>
{
public FooAggregateWithAttribute(FooId id) : base(id)
{
}
}
public class FooStateWithAttribute : AggregateState<FooAggregateWithAttribute, FooId,
IMessageApplier<FooAggregateWithAttribute, FooId>>
{
}
public class FooStateWithOutAttribute : AggregateState<FooAggregateWithOutAttribute, FooId,
IMessageApplier<FooAggregateWithOutAttribute, FooId>>
{
}
}
}
| 39.5 | 167 | 0.689758 | [
"MIT"
] | rgfaber/m5x-sdk | tests/obsolete/Akka/M5x.Akka.Tests/UnitTests/Extensions/TypeExtensionTests.cs | 4,347 | C# |
// Decompiled with JetBrains decompiler
// Type: SqlDataProvider.Data.EventAwardInfo
// Assembly: SqlDataProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E6C792E1-372D-46D0-B366-36ACC93C90BB
// Assembly location: C:\Users\Pham Van Hungg\Desktop\Decompiler\Road\SqlDataProvider.dll
namespace SqlDataProvider.Data
{
public class EventAwardInfo
{
public int ActivityType;
public int AgilityCompose;
public int AttackCompose;
public int Count;
public int DefendCompose;
public int ID;
public bool IsBinds;
public int LuckCompose;
public int Random;
public int StrengthenLevel;
public int TemplateID;
public int ValidDate;
public int Position { get; set; }
}
}
| 27.444444 | 89 | 0.738192 | [
"MIT"
] | HuyTruong19x/DDTank4.1 | Source Server/SqlDataProvider/SqlDataProvider/Data/EventAwardInfo.cs | 743 | C# |
namespace GameHighlightClipper.Converters
{
public sealed class BooleanToBooleanConverter : BooleanConverter<bool>
{
}
} | 22.166667 | 74 | 0.759398 | [
"MIT"
] | alaviivarantala/VGClipTrimmer | GameHighlightClipper/Converters/BooleanToBooleanConverter.cs | 135 | C# |
using System;
using NUnit.Framework;
namespace WebGL.UnitTests
{
[TestFixture]
public class ArrayBufferTests
{
[Test]
public void ShouldCreateBufferOfSpecificedSize()
{
var length = new Random(Environment.TickCount).Next(255);
Assert.That(new ArrayBuffer(length).byteLength, Is.EqualTo(length));
}
[Test]
public void ShouldLockBufferOnlyOnce()
{
var buffer = new ArrayBuffer(16);
var ptr = buffer.@lock();
Assert.That(ptr, Is.Not.EqualTo(IntPtr.Zero));
Assert.That(ptr, Is.EqualTo(buffer.@lock()));
}
[Test]
public void ShouldUnlockBufferWhenLocked()
{
var buffer = new ArrayBuffer(16);
Assert.That(buffer.isLocked, Is.False);
buffer.@lock();
Assert.That(buffer.isLocked, Is.True);
buffer.unlock();
Assert.That(buffer.isLocked, Is.False);
}
[Test]
public void ShouldIgnoreRedundantUnlockRequests()
{
var buffer = new ArrayBuffer(16);
Assert.That(buffer.isLocked, Is.False);
buffer.unlock();
Assert.That(buffer.isLocked, Is.False);
buffer.unlock();
Assert.That(buffer.isLocked, Is.False);
}
}
} | 28.893617 | 80 | 0.557437 | [
"Apache-2.0"
] | jdarc/webgl.net | WebGL.UnitTests/typedarrays/ArrayBufferTests.cs | 1,360 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BTree;
namespace Core.UnitTest
{
[TestClass]
public class CoreTest
{
[TestMethod]
public void TestMethod1()
{
var cl = new InvertedIndex();
}
}
}
| 14.428571 | 51 | 0.554455 | [
"MIT"
] | bmaximus/inverted_index_with_btree_and_stemmer | Core/Core.UnitTest/CoreTest.cs | 305 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.dcdn.Model.V20180115;
using System;
using System.Collections.Generic;
namespace Aliyun.Acs.dcdn.Transform.V20180115
{
public class PreloadDcdnObjectCachesResponseUnmarshaller
{
public static PreloadDcdnObjectCachesResponse Unmarshall(UnmarshallerContext context)
{
PreloadDcdnObjectCachesResponse preloadDcdnObjectCachesResponse = new PreloadDcdnObjectCachesResponse();
preloadDcdnObjectCachesResponse.HttpResponse = context.HttpResponse;
preloadDcdnObjectCachesResponse.RequestId = context.StringValue("PreloadDcdnObjectCaches.RequestId");
preloadDcdnObjectCachesResponse.PreloadTaskId = context.StringValue("PreloadDcdnObjectCaches.PreloadTaskId");
return preloadDcdnObjectCachesResponse;
}
}
} | 41.615385 | 112 | 0.777572 | [
"Apache-2.0"
] | bitType/aliyun-openapi-net-sdk | aliyun-net-sdk-dcdn/Dcdn/Transform/V20180115/PreloadDcdnObjectCachesResponseUnmarshaller.cs | 1,623 | C# |
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers
* for more information concerning the license and the contributors participating to this project.
*/
namespace AspNet.Security.OAuth.Salesforce
{
/// <summary>
/// Defines a list of environments used to determine the appropriate
/// OAuth2 endpoints when communicating with Salesforce.
/// </summary>
public enum SalesforceAuthenticationEnvironment
{
/// <summary>
/// Use login.salesforce.com in the OAuth2 endpoints.
/// </summary>
Production = 0,
/// <summary>
/// Uses test.salesforce.com in the OAuth2 endpoints.
/// </summary>
Test = 1
}
}
| 31.307692 | 98 | 0.657248 | [
"Apache-2.0"
] | AaqibAhamed/AspNet.Security.OAuth.Providers | src/AspNet.Security.OAuth.Salesforce/SalesforceAuthenticationEnvironment.cs | 816 | 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 iot-2015-05-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.IoT.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.IoT.Model.Internal.MarshallTransformations
{
/// <summary>
/// DescribeAuthorizer Request Marshaller
/// </summary>
public class DescribeAuthorizerRequestMarshaller : IMarshaller<IRequest, DescribeAuthorizerRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((DescribeAuthorizerRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(DescribeAuthorizerRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.IoT");
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-05-28";
request.HttpMethod = "GET";
if (!publicRequest.IsSetAuthorizerName())
throw new AmazonIoTException("Request object does not have required field AuthorizerName set");
request.AddPathResource("{authorizerName}", StringUtils.FromString(publicRequest.AuthorizerName));
request.ResourcePath = "/authorizer/{authorizerName}";
request.MarshallerVersion = 2;
return request;
}
private static DescribeAuthorizerRequestMarshaller _instance = new DescribeAuthorizerRequestMarshaller();
internal static DescribeAuthorizerRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeAuthorizerRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.011364 | 152 | 0.641527 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/IoT/Generated/Model/Internal/MarshallTransformations/DescribeAuthorizerRequestMarshaller.cs | 3,169 | C# |
using GPConnectAdaptor.Models.AddAppointment;
using Newtonsoft.Json;
namespace GPConnectAdaptor.AddAppointment
{
public class AddAppointmentRequestDeserializer : IAddAppointmentRequestDeserializer
{
public AddAppointmentRequest Deserialize(string request)
{
return JsonConvert.DeserializeObject<AddAppointmentRequest>(request);
}
}
} | 29.384615 | 87 | 0.759162 | [
"Apache-2.0"
] | nhsconnect/prm-appointments-migrator | app-migrator/GPConnectAdaptor/AddAppointment/AddAppointmentRequestDeserializer.cs | 382 | 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 iot-2015-05-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.IoT.Model
{
/// <summary>
/// The output of the CreateThing operation.
/// </summary>
public partial class CreateThingResponse : AmazonWebServiceResponse
{
private string _thingArn;
private string _thingId;
private string _thingName;
/// <summary>
/// Gets and sets the property ThingArn.
/// <para>
/// The ARN of the new thing.
/// </para>
/// </summary>
public string ThingArn
{
get { return this._thingArn; }
set { this._thingArn = value; }
}
// Check to see if ThingArn property is set
internal bool IsSetThingArn()
{
return this._thingArn != null;
}
/// <summary>
/// Gets and sets the property ThingId.
/// <para>
/// The thing ID.
/// </para>
/// </summary>
public string ThingId
{
get { return this._thingId; }
set { this._thingId = value; }
}
// Check to see if ThingId property is set
internal bool IsSetThingId()
{
return this._thingId != null;
}
/// <summary>
/// Gets and sets the property ThingName.
/// <para>
/// The name of the new thing.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=128)]
public string ThingName
{
get { return this._thingName; }
set { this._thingName = value; }
}
// Check to see if ThingName property is set
internal bool IsSetThingName()
{
return this._thingName != null;
}
}
} | 27.305263 | 101 | 0.579029 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/IoT/Generated/Model/CreateThingResponse.cs | 2,594 | C# |
namespace opendota_twitch_bot.Configurations
{
public class FormaterConfigurations
{
public string TimeZone { get; set; }
public string TimeViewFormat { get; set; }
}
}
| 18.181818 | 50 | 0.665 | [
"MIT"
] | Rakaveli/opendota_twitch_bot | src/Configurations/FormaterConfigurations.cs | 202 | C# |
using System;
using Arcus.Messaging.Abstractions;
using Arcus.Observability.Correlation;
using Arcus.Observability.Telemetry.Serilog.Enrichers;
using Serilog.Core;
using Serilog.Events;
// ReSharper disable once CheckNamespace - made deprecated.
namespace Arcus.Messaging.Pumps.Abstractions.Telemetry
{
/// <summary>
/// Logger enrichment of the <see cref="MessageCorrelationInfo" /> model.
/// </summary>
[Obsolete("Use the message correlation enricher in a different namespace instead: " + nameof(Messaging.Abstractions.Telemetry.MessageCorrelationInfoEnricher) + " without 'Pumps'")]
public class MessageCorrelationInfoEnricher : CorrelationInfoEnricher<MessageCorrelationInfo>
{
private const string CycleId = "CycleId";
/// <summary>
/// Initializes a new instance of the <see cref="T:Arcus.Observability.Telemetry.Serilog.Enrichers.CorrelationInfoEnricher`1" /> class.
/// </summary>
/// <param name="correlationInfoAccessor">The accessor implementation for the custom <see cref="T:Arcus.Observability.Correlation.CorrelationInfo" /> model.</param>
public MessageCorrelationInfoEnricher(ICorrelationInfoAccessor<MessageCorrelationInfo> correlationInfoAccessor)
: base(correlationInfoAccessor)
{
}
/// <summary>
/// Enrich the <paramref name="logEvent" /> with the given <paramref name="correlationInfo" /> model.
/// </summary>
/// <param name="logEvent">The log event to enrich with correlation information.</param>
/// <param name="propertyFactory">The log property factory to create log properties with correlation information.</param>
/// <param name="correlationInfo">The correlation model that contains the current correlation information.</param>
protected override void EnrichCorrelationInfo(
LogEvent logEvent,
ILogEventPropertyFactory propertyFactory,
MessageCorrelationInfo correlationInfo)
{
base.EnrichCorrelationInfo(logEvent, propertyFactory, correlationInfo);
if (!String.IsNullOrEmpty(correlationInfo.CycleId))
{
LogEventProperty property = propertyFactory.CreateProperty(CycleId, correlationInfo.CycleId);
logEvent.AddPropertyIfAbsent(property);
}
}
}
}
| 48.510204 | 185 | 0.703828 | [
"MIT"
] | arcus-azure/arcus.messaging- | src/Arcus.Messaging.Abstractions/Telemetry/ObsoleteMessageCorrelationInfoEnricher.cs | 2,379 | C# |
using System;
using Squishy.Network;
using WCell.Util.Commands;
using WCell.Util.Strings;
using StringStream = WCell.Util.Strings.StringStream;
namespace Squishy.Irc.Commands
{
/// <summary>
/// Triggers through NOTICE
/// </summary>
public class NoticeCmdTrigger : IrcCmdTrigger
{
public NoticeCmdTrigger(string args, IrcUser user, IrcChannel chan = null)
: this(new StringStream(args), user, chan)
{
}
public NoticeCmdTrigger(StringStream args, IrcUser user, IrcChannel chan = null)
: base(args, user, chan)
{
}
public override void Reply(string text)
{
Args.Target.Notice(text);
}
}
} | 22.448276 | 83 | 0.688172 | [
"MIT"
] | Domiii/Squishy.IRC | Squishy.Irc/Commands/NoticeCmdTrigger.cs | 651 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.DocumentDB.V20210301Preview
{
/// <summary>
/// An Azure Cosmos DB MongoDB database.
/// </summary>
[AzureNativeResourceType("azure-native:documentdb/v20210301preview:MongoDBResourceMongoDBDatabase")]
public partial class MongoDBResourceMongoDBDatabase : Pulumi.CustomResource
{
/// <summary>
/// Identity for the resource.
/// </summary>
[Output("identity")]
public Output<Outputs.ManagedServiceIdentityResponse?> Identity { get; private set; } = null!;
/// <summary>
/// The location of the resource group to which the resource belongs.
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// The name of the ARM resource.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
[Output("options")]
public Output<Outputs.MongoDBDatabaseGetPropertiesResponseOptions?> Options { get; private set; } = null!;
[Output("resource")]
public Output<Outputs.MongoDBDatabaseGetPropertiesResponseResource?> Resource { get; private set; } = null!;
/// <summary>
/// Tags are a list of key-value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters. For example, the default experience for a template type is set with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", "Graph", "DocumentDB", and "MongoDB".
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// The type of Azure resource.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a MongoDBResourceMongoDBDatabase resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public MongoDBResourceMongoDBDatabase(string name, MongoDBResourceMongoDBDatabaseArgs args, CustomResourceOptions? options = null)
: base("azure-native:documentdb/v20210301preview:MongoDBResourceMongoDBDatabase", name, args ?? new MongoDBResourceMongoDBDatabaseArgs(), MakeResourceOptions(options, ""))
{
}
private MongoDBResourceMongoDBDatabase(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:documentdb/v20210301preview:MongoDBResourceMongoDBDatabase", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20210301preview:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-native:documentdb:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-nextgen:documentdb:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-native:documentdb/v20150401:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20150401:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-native:documentdb/v20150408:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20150408:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-native:documentdb/v20151106:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20151106:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-native:documentdb/v20160319:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20160319:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-native:documentdb/v20160331:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20160331:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-native:documentdb/v20190801:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20190801:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-native:documentdb/v20191212:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20191212:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-native:documentdb/v20200301:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20200301:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-native:documentdb/v20200401:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20200401:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-native:documentdb/v20200601preview:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20200601preview:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-native:documentdb/v20200901:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20200901:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-native:documentdb/v20210115:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20210115:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-native:documentdb/v20210315:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20210315:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-native:documentdb/v20210401preview:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20210401preview:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-native:documentdb/v20210415:MongoDBResourceMongoDBDatabase"},
new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20210415:MongoDBResourceMongoDBDatabase"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing MongoDBResourceMongoDBDatabase resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static MongoDBResourceMongoDBDatabase Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new MongoDBResourceMongoDBDatabase(name, id, options);
}
}
public sealed class MongoDBResourceMongoDBDatabaseArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Cosmos DB database account name.
/// </summary>
[Input("accountName", required: true)]
public Input<string> AccountName { get; set; } = null!;
/// <summary>
/// Cosmos DB database name.
/// </summary>
[Input("databaseName")]
public Input<string>? DatabaseName { get; set; }
/// <summary>
/// Identity for the resource.
/// </summary>
[Input("identity")]
public Input<Inputs.ManagedServiceIdentityArgs>? Identity { get; set; }
/// <summary>
/// The location of the resource group to which the resource belongs.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// A key-value pair of options to be applied for the request. This corresponds to the headers sent with the request.
/// </summary>
[Input("options")]
public Input<Inputs.CreateUpdateOptionsArgs>? Options { get; set; }
/// <summary>
/// The standard JSON format of a MongoDB database
/// </summary>
[Input("resource", required: true)]
public Input<Inputs.MongoDBDatabaseResourceArgs> Resource { get; set; } = null!;
/// <summary>
/// The name of the resource group. The name is case insensitive.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Tags are a list of key-value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters. For example, the default experience for a template type is set with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", "Graph", "DocumentDB", and "MongoDB".
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public MongoDBResourceMongoDBDatabaseArgs()
{
}
}
}
| 56.938144 | 509 | 0.6501 | [
"Apache-2.0"
] | sebtelko/pulumi-azure-native | sdk/dotnet/DocumentDB/V20210301Preview/MongoDBResourceMongoDBDatabase.cs | 11,046 | C# |
namespace MassiveKnob.Plugin.CoreAudio.Base
{
/// <summary>
/// Interaction logic for BaseDeviceSettingsView.xaml
/// </summary>
public partial class BaseDeviceSettingsView
{
public BaseDeviceSettingsView()
{
InitializeComponent();
}
}
}
| 21.357143 | 57 | 0.618729 | [
"Unlicense"
] | MvRens/MassiveKnob | Windows/MassiveKnob.Plugin.CoreAudio/Base/BaseDeviceSettingsView.xaml.cs | 301 | C# |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2021 Ingo Herbote
* https://www.yetanotherforum.net/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace YAF.Types.Extensions
{
#region Using
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using YAF.Types;
using YAF.Types.Attributes;
#endregion
/// <summary>
/// The string helper.
/// </summary>
public static class StringExtensions
{
#region Public Methods
/// <summary>
/// Converts a string to an escaped JavaString string.
/// </summary>
/// <param name="str">The string.</param>
/// <returns>
/// The JS string.
/// </returns>
public static string ToJsString([CanBeNull] this string str)
{
if (!str.IsSet())
{
return str;
}
str = str.Replace("\\", @"\\");
str = str.Replace("'", @"\'");
str = str.Replace("\r", @"\r");
str = str.Replace("\n", @"\n");
str = str.Replace("\"", "\'");
return str;
}
/// <summary>
/// Fast index of.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="pattern">The pattern.</param>
/// <returns>
/// The fast index of.
/// </returns>
public static int FastIndexOf([NotNull] this string source, [NotNull] string pattern)
{
CodeContracts.VerifyNotNull(source);
CodeContracts.VerifyNotNull(pattern);
switch (pattern.Length)
{
case 0:
return 0;
case 1:
return source.IndexOf(pattern[0]);
}
var limit = source.Length - pattern.Length + 1;
if (limit < 1)
{
return -1;
}
// Store the first 2 characters of "pattern"
var c0 = pattern[0];
var c1 = pattern[1];
// Find the first occurrence of the first character
var first = source.IndexOf(c0, 0, limit);
while (first != -1)
{
// Check if the following character is the same like
// the 2nd character of "pattern"
if (source[first + 1] != c1)
{
first = source.IndexOf(c0, ++first, limit - first);
continue;
}
// Check the rest of "pattern" (starting with the 3rd character)
var found = true;
for (var j = 2; j < pattern.Length; j++)
{
if (source[first + j] == pattern[j])
{
continue;
}
found = false;
break;
}
// If the whole word was found, return its index, otherwise try again
if (found)
{
return first;
}
first = source.IndexOf(c0, ++first, limit - first);
}
return -1;
}
/// <summary>
/// Does an action for each character in the input string. Kind of useless, but in a
/// useful way. ;)
/// </summary>
/// <param name="input">The input.</param>
/// <param name="forEachAction">For each action.</param>
public static void ForEachChar([NotNull] this string input, [NotNull] Action<char> forEachAction)
{
CodeContracts.VerifyNotNull(input);
CodeContracts.VerifyNotNull(forEachAction);
input.ForEach(forEachAction);
}
/// <summary>
/// Returns a "random" alpha-numeric string of specified length and characters.
/// </summary>
/// <param name="length">
/// the length of the random string
/// </param>
/// <param name="pickFrom">
/// the string of characters to pick randomly from
/// </param>
/// <returns>
/// The generate random string.
/// </returns>
public static string GenerateRandomString(int length, [NotNull] string pickFrom)
{
CodeContracts.VerifyNotNull(pickFrom);
var r = new Random();
var result = new StringBuilder();
var pickFromLength = pickFrom.Length - 1;
for (var i = 0; i < length; i++)
{
var index = r.Next(pickFromLength);
result.Append(pickFrom.Substring(index, 1));
}
return result.ToString();
}
/// <summary>
/// Removes empty strings from the list
/// </summary>
/// <param name="inputList">
/// The input list.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="inputList"/> is <c>null</c>.
/// </exception>
/// <returns>
/// Returns the Cleaned List
/// </returns>
[NotNull]
public static List<string> GetNewNoEmptyStrings([NotNull] this IEnumerable<string> inputList)
{
CodeContracts.VerifyNotNull(inputList);
return inputList.Where(x => x.IsSet()).ToList();
}
/// <summary>
/// Removes strings that are smaller then <paramref name="minSize"/>
/// </summary>
/// <param name="inputList">
/// The input list.
/// </param>
/// <param name="minSize">
/// The minimum size.
/// </param>
/// <returns>
/// The <see cref="List"/>.
/// </returns>
[NotNull]
public static List<string> GetNewNoSmallStrings([NotNull] this IEnumerable<string> inputList, int minSize)
{
CodeContracts.VerifyNotNull(inputList);
return inputList.Where(x => x.Length >= minSize).ToList();
}
/// <summary>
/// When the string is trimmed, is it <see langword="null" /> or empty?
/// </summary>
/// <param name="inputString">The input string.</param>
/// <returns>
/// The is <see langword="null" /> or empty trimmed.
/// </returns>
[ContractAnnotation("str:null => true")]
public static bool IsNotSet([CanBeNull] this string inputString)
{
return string.IsNullOrWhiteSpace(inputString);
}
/// <summary>
/// When the string is trimmed, is it <see langword="null" /> or empty?
/// </summary>
/// <param name="inputString">The input string.</param>
/// <returns>
/// The is <see langword="null" /> or empty trimmed.
/// </returns>
[ContractAnnotation("str:null => false")]
public static bool IsSet([CanBeNull] this string inputString)
{
return !string.IsNullOrWhiteSpace(inputString);
}
/// <summary>
/// Processes the text.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>
/// The process text.
/// </returns>
public static string ProcessText(string text)
{
return ProcessText(text, true);
}
/// <summary>
/// Processes the text.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="nullify">The nullify.</param>
/// <returns>
/// The process text.
/// </returns>
public static string ProcessText(string text, bool nullify)
{
return ProcessText(text, nullify, true);
}
/// <summary>
/// Processes the text.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="nullify">The nullify.</param>
/// <param name="trim">The trim.</param>
/// <returns>
/// The process text.
/// </returns>
public static string ProcessText(string text, bool nullify, bool trim)
{
if (trim && text.IsSet())
{
text = text.Trim();
}
if (nullify && text.IsNotSet())
{
text = null;
}
return text;
}
/// <summary>
/// Removes multiple whitespace characters from a string.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>
/// The remove multiple whitespace.
/// </returns>
public static string RemoveMultipleWhitespace(this string text)
{
var result = string.Empty;
if (text.IsNotSet())
{
return result;
}
var r = new Regex(@"\s+");
return r.Replace(text, @" ");
}
/// <summary>
/// Converts a string to a list using delimiter.
/// </summary>
/// <param name="str">
/// starting string
/// </param>
/// <param name="delimiter">
/// value that delineates the string
/// </param>
/// <returns>
/// list of strings
/// </returns>
public static List<string> StringToList(this string str, char delimiter)
{
return str.StringToList(delimiter, new List<string>());
}
/// <summary>
/// Converts a string to a list using delimiter.
/// </summary>
/// <param name="str">
/// starting string
/// </param>
/// <param name="delimiter">
/// value that delineates the string
/// </param>
/// <param name="exclude">
/// items to exclude from list
/// </param>
/// <returns>
/// list of strings
/// </returns>
[NotNull]
public static List<string> StringToList(
[NotNull] this string str,
char delimiter,
[NotNull] List<string> exclude)
{
CodeContracts.VerifyNotNull(str);
CodeContracts.VerifyNotNull(exclude);
var list = str.Split(delimiter).ToList();
list.RemoveAll(exclude.Contains);
list.Remove(delimiter.ToString());
return list;
}
/// <summary>
/// Creates a delimited string an enumerable list of T.
/// </summary>
/// <typeparam name="T">The typed Parameter</typeparam>
/// <param name="objList">The object list.</param>
/// <param name="delimiter">The delimiter.</param>
/// <returns>
/// The list to string.
/// </returns>
public static string ToDelimitedString<T>(this IEnumerable<T> objList, string delimiter) where T : IConvertible
{
if (objList == null)
{
throw new ArgumentNullException(nameof(objList), "objList is null.");
}
var sb = new StringBuilder();
objList.ForEachFirst(
(x, isFirst) =>
{
if (!isFirst)
{
// append delimiter if this isn't the first string
sb.Append(delimiter);
}
// append string...
sb.Append(x);
});
return sb.ToString();
}
/// <summary>
/// Cleans a string into a proper Regular Expression statement.
/// E.g. "[b]Whatever[/b]" will be converted to:
/// "\[b\]Whatever\[\/b\]"
/// </summary>
/// <param name="input">
/// The input.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
[NotNull]
public static string ToRegExString([NotNull] this string input)
{
CodeContracts.VerifyNotNull(input);
var sb = new StringBuilder();
input.ForEachChar(
c =>
{
if (!char.IsWhiteSpace(c) && !char.IsLetterOrDigit(c) && c != '_')
{
sb.Append("\\");
}
sb.Append(c);
});
return sb.ToString();
}
/// <summary>
/// Converts a String to a MemoryStream.
/// </summary>
/// <param name="inputString">
/// The input String.
/// </param>
/// <returns>
/// The <see cref="Stream"/>.
/// </returns>
[NotNull]
public static Stream ToStream([NotNull] this string inputString)
{
CodeContracts.VerifyNotNull(inputString);
var byteArray = Encoding.ASCII.GetBytes(inputString);
return new MemoryStream(byteArray);
}
/// <summary>
/// Truncates a string with the specified limits and adds (...) to the end if truncated
/// </summary>
/// <param name="input">
/// input string
/// </param>
/// <param name="inputLimit">
/// The input Limit.
/// </param>
/// <param name="cutOfString">
/// The cut Of String.
/// </param>
/// <returns>
/// truncated string
/// </returns>
public static string Truncate(
[CanBeNull] this string input,
int inputLimit,
[NotNull] string cutOfString = "...")
{
CodeContracts.VerifyNotNull(cutOfString);
var output = input;
if (input.IsNotSet())
{
return null;
}
var limit = inputLimit - cutOfString.Length;
// Check if the string is longer than the allowed amount
// otherwise do nothing
if (output.Length <= limit || limit <= 0)
{
return output;
}
// cut the string down to the maximum number of characters
output = output.Substring(0, limit);
// Check if the space right after the truncate point
// was a space. if not, we are in the middle of a word and
// need to cut out the rest of it
if (input.Substring(output.Length, 1) != " ")
{
var lastSpace = output.LastIndexOf(" ", StringComparison.Ordinal);
// if we found a space then, cut back to that space
if (lastSpace != -1)
{
output = output.Substring(0, lastSpace);
}
}
// Finally, add the the cut off string...
output += cutOfString;
return output;
}
/// <summary>
/// Determines whether [is image name] [the specified input string].
/// </summary>
/// <param name="inputString">The input string.</param>
/// <returns>Returns if the String is a Image Name</returns>
public static bool IsImageName(this string inputString)
{
return inputString.EndsWith("png", StringComparison.InvariantCultureIgnoreCase)
|| inputString.EndsWith("gif", StringComparison.InvariantCultureIgnoreCase)
|| inputString.EndsWith("jpeg", StringComparison.InvariantCultureIgnoreCase)
|| inputString.EndsWith("jpg", StringComparison.InvariantCultureIgnoreCase)
|| inputString.EndsWith("bmp", StringComparison.InvariantCultureIgnoreCase);
}
/// <summary>
/// Converts persian Numbers to english.
/// </summary>
/// <param name="persianString">
/// The persian string.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string PersianNumberToEnglish(this string persianString)
{
var lettersDictionary = new Dictionary<string, string>
{
["۰"] = "0",
["۱"] = "1",
["۲"] = "2",
["۳"] = "3",
["۴"] = "4",
["۵"] = "5",
["۶"] = "6",
["۷"] = "7",
["۸"] = "8",
["۹"] = "9"
};
return lettersDictionary.Aggregate(persianString, (current, item) => current.Replace(item.Key, item.Value));
}
/// <summary>
/// Converts a String Number to GUID.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
/// <returns>
/// The <see cref="Guid"/>.
/// </returns>
public static Guid ToGuid([NotNull] this string value)
{
CodeContracts.VerifyNotNull(value);
byte[] bytes = new byte[16];
BitConverter.GetBytes(value.ToType<int>()).CopyTo(bytes, 0);
return new Guid(bytes);
}
#endregion
}
} | 32.735552 | 121 | 0.477958 | [
"Apache-2.0"
] | Spinks90/YAFNET | yafsrc/YAF.Types/Extensions/StringExtensions.cs | 18,135 | C# |
namespace PicoMoonSharp.Interpreter.Debugging
{
/// <summary>
/// Enumeration of the possible watch types
/// </summary>
public enum WatchType
{
/// <summary>
/// A real variable watch
/// </summary>
Watches,
/// <summary>
/// The status of the v-stack
/// </summary>
VStack,
/// <summary>
/// The call stack
/// </summary>
CallStack,
/// <summary>
/// The list of coroutines
/// </summary>
Coroutines,
/// <summary>
/// Topmost local variables
/// </summary>
Locals,
/// <summary>
/// The list of currently active coroutines
/// </summary>
Threads,
/// <summary>
/// The maximum value of this enum
/// </summary>
MaxValue
}
}
| 17.717949 | 45 | 0.591896 | [
"MIT"
] | Inkwalker/PicoUnity | Assets/Source/PicoMoonSharp/Interpreter/Debugging/WatchType.cs | 693 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.StreamAnalytics.Latest
{
/// <summary>
/// A streaming job object, containing all information associated with the named streaming job.
/// Latest API Version: 2016-03-01.
/// </summary>
[Obsolete(@"The 'latest' version is deprecated. Please migrate to the resource in the top-level module: 'azure-native:streamanalytics:StreamingJob'.")]
[AzureNativeResourceType("azure-native:streamanalytics/latest:StreamingJob")]
public partial class StreamingJob : Pulumi.CustomResource
{
/// <summary>
/// Controls certain runtime behaviors of the streaming job.
/// </summary>
[Output("compatibilityLevel")]
public Output<string?> CompatibilityLevel { get; private set; } = null!;
/// <summary>
/// Value is an ISO-8601 formatted UTC timestamp indicating when the streaming job was created.
/// </summary>
[Output("createdDate")]
public Output<string> CreatedDate { get; private set; } = null!;
/// <summary>
/// The data locale of the stream analytics job. Value should be the name of a supported .NET Culture from the set https://msdn.microsoft.com/en-us/library/system.globalization.culturetypes(v=vs.110).aspx. Defaults to 'en-US' if none specified.
/// </summary>
[Output("dataLocale")]
public Output<string?> DataLocale { get; private set; } = null!;
/// <summary>
/// The current entity tag for the streaming job. This is an opaque string. You can use it to detect whether the resource has changed between requests. You can also use it in the If-Match or If-None-Match headers for write operations for optimistic concurrency.
/// </summary>
[Output("etag")]
public Output<string> Etag { get; private set; } = null!;
/// <summary>
/// The maximum tolerable delay in seconds where events arriving late could be included. Supported range is -1 to 1814399 (20.23:59:59 days) and -1 is used to specify wait indefinitely. If the property is absent, it is interpreted to have a value of -1.
/// </summary>
[Output("eventsLateArrivalMaxDelayInSeconds")]
public Output<int?> EventsLateArrivalMaxDelayInSeconds { get; private set; } = null!;
/// <summary>
/// The maximum tolerable delay in seconds where out-of-order events can be adjusted to be back in order.
/// </summary>
[Output("eventsOutOfOrderMaxDelayInSeconds")]
public Output<int?> EventsOutOfOrderMaxDelayInSeconds { get; private set; } = null!;
/// <summary>
/// Indicates the policy to apply to events that arrive out of order in the input event stream.
/// </summary>
[Output("eventsOutOfOrderPolicy")]
public Output<string?> EventsOutOfOrderPolicy { get; private set; } = null!;
/// <summary>
/// A list of one or more functions for the streaming job. The name property for each function is required when specifying this property in a PUT request. This property cannot be modify via a PATCH operation. You must use the PATCH API available for the individual transformation.
/// </summary>
[Output("functions")]
public Output<ImmutableArray<Outputs.FunctionResponse>> Functions { get; private set; } = null!;
/// <summary>
/// A list of one or more inputs to the streaming job. The name property for each input is required when specifying this property in a PUT request. This property cannot be modify via a PATCH operation. You must use the PATCH API available for the individual input.
/// </summary>
[Output("inputs")]
public Output<ImmutableArray<Outputs.InputResponse>> Inputs { get; private set; } = null!;
/// <summary>
/// A GUID uniquely identifying the streaming job. This GUID is generated upon creation of the streaming job.
/// </summary>
[Output("jobId")]
public Output<string> JobId { get; private set; } = null!;
/// <summary>
/// Describes the state of the streaming job.
/// </summary>
[Output("jobState")]
public Output<string> JobState { get; private set; } = null!;
/// <summary>
/// Value is either an ISO-8601 formatted timestamp indicating the last output event time of the streaming job or null indicating that output has not yet been produced. In case of multiple outputs or multiple streams, this shows the latest value in that set.
/// </summary>
[Output("lastOutputEventTime")]
public Output<string> LastOutputEventTime { get; private set; } = null!;
/// <summary>
/// Resource location. Required on PUT (CreateOrReplace) requests.
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// Resource name
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Indicates the policy to apply to events that arrive at the output and cannot be written to the external storage due to being malformed (missing column values, column values of wrong type or size).
/// </summary>
[Output("outputErrorPolicy")]
public Output<string?> OutputErrorPolicy { get; private set; } = null!;
/// <summary>
/// This property should only be utilized when it is desired that the job be started immediately upon creation. Value may be JobStartTime, CustomTime, or LastOutputEventTime to indicate whether the starting point of the output event stream should start whenever the job is started, start at a custom user time stamp specified via the outputStartTime property, or start from the last event output time.
/// </summary>
[Output("outputStartMode")]
public Output<string?> OutputStartMode { get; private set; } = null!;
/// <summary>
/// Value is either an ISO-8601 formatted time stamp that indicates the starting point of the output event stream, or null to indicate that the output event stream will start whenever the streaming job is started. This property must have a value if outputStartMode is set to CustomTime.
/// </summary>
[Output("outputStartTime")]
public Output<string?> OutputStartTime { get; private set; } = null!;
/// <summary>
/// A list of one or more outputs for the streaming job. The name property for each output is required when specifying this property in a PUT request. This property cannot be modify via a PATCH operation. You must use the PATCH API available for the individual output.
/// </summary>
[Output("outputs")]
public Output<ImmutableArray<Outputs.OutputResponse>> Outputs { get; private set; } = null!;
/// <summary>
/// Describes the provisioning status of the streaming job.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// Describes the SKU of the streaming job. Required on PUT (CreateOrReplace) requests.
/// </summary>
[Output("sku")]
public Output<Outputs.SkuResponse?> Sku { get; private set; } = null!;
/// <summary>
/// Resource tags
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Indicates the query and the number of streaming units to use for the streaming job. The name property of the transformation is required when specifying this property in a PUT request. This property cannot be modify via a PATCH operation. You must use the PATCH API available for the individual transformation.
/// </summary>
[Output("transformation")]
public Output<Outputs.TransformationResponse?> Transformation { get; private set; } = null!;
/// <summary>
/// Resource type
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a StreamingJob resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public StreamingJob(string name, StreamingJobArgs args, CustomResourceOptions? options = null)
: base("azure-native:streamanalytics/latest:StreamingJob", name, args ?? new StreamingJobArgs(), MakeResourceOptions(options, ""))
{
}
private StreamingJob(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:streamanalytics/latest:StreamingJob", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:streamanalytics/latest:StreamingJob"},
new Pulumi.Alias { Type = "azure-native:streamanalytics:StreamingJob"},
new Pulumi.Alias { Type = "azure-nextgen:streamanalytics:StreamingJob"},
new Pulumi.Alias { Type = "azure-native:streamanalytics/v20160301:StreamingJob"},
new Pulumi.Alias { Type = "azure-nextgen:streamanalytics/v20160301:StreamingJob"},
new Pulumi.Alias { Type = "azure-native:streamanalytics/v20170401preview:StreamingJob"},
new Pulumi.Alias { Type = "azure-nextgen:streamanalytics/v20170401preview:StreamingJob"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing StreamingJob resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static StreamingJob Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new StreamingJob(name, id, options);
}
}
public sealed class StreamingJobArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Controls certain runtime behaviors of the streaming job.
/// </summary>
[Input("compatibilityLevel")]
public InputUnion<string, Pulumi.AzureNative.StreamAnalytics.Latest.CompatibilityLevel>? CompatibilityLevel { get; set; }
/// <summary>
/// The data locale of the stream analytics job. Value should be the name of a supported .NET Culture from the set https://msdn.microsoft.com/en-us/library/system.globalization.culturetypes(v=vs.110).aspx. Defaults to 'en-US' if none specified.
/// </summary>
[Input("dataLocale")]
public Input<string>? DataLocale { get; set; }
/// <summary>
/// The maximum tolerable delay in seconds where events arriving late could be included. Supported range is -1 to 1814399 (20.23:59:59 days) and -1 is used to specify wait indefinitely. If the property is absent, it is interpreted to have a value of -1.
/// </summary>
[Input("eventsLateArrivalMaxDelayInSeconds")]
public Input<int>? EventsLateArrivalMaxDelayInSeconds { get; set; }
/// <summary>
/// The maximum tolerable delay in seconds where out-of-order events can be adjusted to be back in order.
/// </summary>
[Input("eventsOutOfOrderMaxDelayInSeconds")]
public Input<int>? EventsOutOfOrderMaxDelayInSeconds { get; set; }
/// <summary>
/// Indicates the policy to apply to events that arrive out of order in the input event stream.
/// </summary>
[Input("eventsOutOfOrderPolicy")]
public InputUnion<string, Pulumi.AzureNative.StreamAnalytics.Latest.EventsOutOfOrderPolicy>? EventsOutOfOrderPolicy { get; set; }
[Input("functions")]
private InputList<Inputs.FunctionArgs>? _functions;
/// <summary>
/// A list of one or more functions for the streaming job. The name property for each function is required when specifying this property in a PUT request. This property cannot be modify via a PATCH operation. You must use the PATCH API available for the individual transformation.
/// </summary>
public InputList<Inputs.FunctionArgs> Functions
{
get => _functions ?? (_functions = new InputList<Inputs.FunctionArgs>());
set => _functions = value;
}
[Input("inputs")]
private InputList<Inputs.InputArgs>? _inputs;
/// <summary>
/// A list of one or more inputs to the streaming job. The name property for each input is required when specifying this property in a PUT request. This property cannot be modify via a PATCH operation. You must use the PATCH API available for the individual input.
/// </summary>
public InputList<Inputs.InputArgs> Inputs
{
get => _inputs ?? (_inputs = new InputList<Inputs.InputArgs>());
set => _inputs = value;
}
/// <summary>
/// The name of the streaming job.
/// </summary>
[Input("jobName")]
public Input<string>? JobName { get; set; }
/// <summary>
/// Resource location. Required on PUT (CreateOrReplace) requests.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// Indicates the policy to apply to events that arrive at the output and cannot be written to the external storage due to being malformed (missing column values, column values of wrong type or size).
/// </summary>
[Input("outputErrorPolicy")]
public InputUnion<string, Pulumi.AzureNative.StreamAnalytics.Latest.OutputErrorPolicy>? OutputErrorPolicy { get; set; }
/// <summary>
/// This property should only be utilized when it is desired that the job be started immediately upon creation. Value may be JobStartTime, CustomTime, or LastOutputEventTime to indicate whether the starting point of the output event stream should start whenever the job is started, start at a custom user time stamp specified via the outputStartTime property, or start from the last event output time.
/// </summary>
[Input("outputStartMode")]
public InputUnion<string, Pulumi.AzureNative.StreamAnalytics.Latest.OutputStartMode>? OutputStartMode { get; set; }
/// <summary>
/// Value is either an ISO-8601 formatted time stamp that indicates the starting point of the output event stream, or null to indicate that the output event stream will start whenever the streaming job is started. This property must have a value if outputStartMode is set to CustomTime.
/// </summary>
[Input("outputStartTime")]
public Input<string>? OutputStartTime { get; set; }
[Input("outputs")]
private InputList<Inputs.OutputArgs>? _outputs;
/// <summary>
/// A list of one or more outputs for the streaming job. The name property for each output is required when specifying this property in a PUT request. This property cannot be modify via a PATCH operation. You must use the PATCH API available for the individual output.
/// </summary>
public InputList<Inputs.OutputArgs> Outputs
{
get => _outputs ?? (_outputs = new InputList<Inputs.OutputArgs>());
set => _outputs = value;
}
/// <summary>
/// The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// Describes the SKU of the streaming job. Required on PUT (CreateOrReplace) requests.
/// </summary>
[Input("sku")]
public Input<Inputs.SkuArgs>? Sku { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
/// <summary>
/// Indicates the query and the number of streaming units to use for the streaming job. The name property of the transformation is required when specifying this property in a PUT request. This property cannot be modify via a PATCH operation. You must use the PATCH API available for the individual transformation.
/// </summary>
[Input("transformation")]
public Input<Inputs.TransformationArgs>? Transformation { get; set; }
public StreamingJobArgs()
{
}
}
}
| 53.011628 | 409 | 0.649265 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/StreamAnalytics/Latest/StreamingJob.cs | 18,236 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.CommandLine.Rendering.Views;
using System.CommandLine.Tests;
using System.CommandLine.Tests.Utility;
using System.Drawing;
using FluentAssertions;
using Xunit;
using static System.CommandLine.Rendering.TestTerminal;
namespace System.CommandLine.Rendering.Tests.Views
{
public class ContentViewTests
{
private readonly TestTerminal _terminal;
private readonly ConsoleRenderer _renderer;
public ContentViewTests()
{
_terminal = new TestTerminal();
_renderer = new ConsoleRenderer(_terminal);
}
[Fact]
public void When_constructing_with_a_string_a_ContentSpan_is_created()
{
var contentView = new TestContentView("Four");
var span = contentView.GetSpan();
span.Should().BeOfType<ContentSpan>().Which.Content.Should().Contain("Four");
}
[Fact]
public void When_constructing_the_span_argument_cannot_be_null()
{
TextSpan span = null;
Action constructView = () => new ContentView(span);
constructView.Should().Throw<ArgumentNullException>();
}
[Fact]
public void Span_is_not_created_by_default()
{
var contentView = new TestContentView();
contentView.IsSpanNull.Should().BeTrue();
}
[Fact]
public void Measure_requires_renderer()
{
var contentView = new ContentView("Four");
contentView
.Invoking(x => x.Measure(null, new Size(0, 0)))
.Should()
.Throw<ArgumentNullException>();
}
[Fact]
public void Measure_requires_maxSize()
{
var contentView = new ContentView("Four");
contentView
.Invoking(x => x.Measure(_renderer, null))
.Should()
.Throw<ArgumentNullException>();
}
[Fact]
public void Measure_returns_content_string_size()
{
var contentView = new ContentView("Four");
var size = contentView.Measure(_renderer, new Size(10, 1));
size.Height.Should().Be(1);
size.Width.Should().Be(4);
}
[Fact]
public void Measuring_without_span_is_zero_size()
{
var contentView = new TestContentView();
var size = contentView.Measure(_renderer, new Size(10, 1));
size.Height.Should().Be(0);
size.Width.Should().Be(0);
}
[Fact]
public void Render_requires_renderer()
{
var contentView = new ContentView("Four");
contentView
.Invoking(x => x.Render(null, new Region(0, 0, 4, 1)))
.Should()
.Throw<ArgumentNullException>();
}
[Fact]
public void Render_requires_region()
{
var contentView = new ContentView("Four");
contentView
.Invoking(x => x.Render(_renderer, null))
.Should()
.Throw<ArgumentNullException>();
}
[Fact]
public void Render_writes_span_in_region()
{
var contentView = new ContentView("Four");
contentView.Render(_renderer, new Region(0, 0, 4, 1));
_terminal.Events
.Should()
.BeEquivalentSequenceTo(
new CursorPositionChanged(new Point(0, 0)),
new ContentWritten("Four"));
}
[Fact]
public void Views_created_from_an_observable_can_be_updated_by_the_observable()
{
var observable = new TestObservable();
var view = ContentView.FromObservable(observable);
var isViewUpdated = false;
view.Updated += (s, e) => { isViewUpdated = true; };
var initialSize = view.Measure(_renderer, new Size(10, 10));
initialSize.Height.Should().Be(0);
initialSize.Width.Should().Be(0);
observable.UpdateViews("Four");
isViewUpdated.Should().BeTrue();
var updatedSize = view.Measure(_renderer, new Size(10, 10));
updatedSize.Height.Should().Be(1);
updatedSize.Width.Should().Be(4);
}
[Fact]
public void View_measures_whitespace()
{
var view = new ContentView(" One Two ");
Size measuredSize = view.Measure(_renderer, new Size(6, 2));
measuredSize.Should().BeEquivalentTo(new Size(6, 2));
}
[Fact]
public void View_renders_whitespace()
{
var view = new ContentView(" One Two ");
view.Render(_renderer, new Region(0, 0, 6, 2));
_terminal.Events.Should().BeEquivalentSequenceTo(
new CursorPositionChanged(new Point(0,0)),
new ContentWritten(" One"),
new CursorPositionChanged(new Point(0, 1)),
new ContentWritten("Two ")
);
}
private class TestContentView : ContentView
{
public bool IsSpanNull => Span == null;
public TextSpan GetSpan() => Span;
public TestContentView()
{ }
public TestContentView(string content) : base(content) { }
}
private class TestObservable : IObservable<string>
{
private readonly List<IObserver<string>> _observers;
public TestObservable()
{
_observers = new List<IObserver<string>>();
}
public IDisposable Subscribe(IObserver<string> observer)
{
if (!_observers.Contains(observer))
{
_observers.Add(observer);
}
return new TestDisposable(_observers, observer);
}
public void UpdateViews(string value)
{
foreach(var observer in _observers)
{
observer.OnNext(value);
}
}
}
private class TestDisposable : IDisposable
{
private readonly List<IObserver<string>> _observers;
private readonly IObserver<string> _observer;
public TestDisposable(List<IObserver<string>> observers, IObserver<string> observer)
{
_observers = observers;
_observer = observer;
}
public void Dispose()
{
if (_observer != null) _observers.Remove(_observer);
}
}
}
}
| 30.885965 | 101 | 0.539477 | [
"MIT"
] | jeredm/command-line-api | src/System.CommandLine.Rendering.Tests/Views/ContentViewTests.cs | 7,044 | C# |
// Copyright (C) 2003-2010 Xtensive LLC.
// All rights reserved.
// For conditions of distribution and use, see license.
// Created by: Alex Yakunin
// Created: 2010.03.01
using System;
using System.Collections.Generic;
using Xtensive.Core;
using Xtensive.Tuples.Transform;
using System.Linq;
namespace Xtensive.Orm
{
/// <summary>
/// A service listening to entity change-related events in <see cref="Session"/>
/// and writing the information on their original version to <see cref="Versions"/> set
/// (<see cref="VersionSet"/>).
/// </summary>
public sealed class VersionCapturer : SessionBound,
IDisposable
{
private readonly VersionSet materializedVersions = new VersionSet();
private readonly VersionSet modifiedVersions = new VersionSet();
private readonly List<Key> removedKeys = new List<Key>();
/// <summary>
/// Gets the version set updated by this service.
/// </summary>
public VersionSet Versions { get; private set; }
#region Session event handlers
private void EntityMaterialized(object sender, EntityEventArgs e)
{
materializedVersions.Add(e.Entity, true);
}
private void TransactionRollbacked(object sender, TransactionEventArgs transactionEventArgs)
{
removedKeys.Clear();
modifiedVersions.Clear();
}
private void TransactionCommitted(object sender, TransactionEventArgs transactionEventArgs)
{
if (transactionEventArgs.Transaction.IsNested)
return;
Versions.MergeWith(materializedVersions, Session);
Versions.MergeWith(modifiedVersions, Session);
foreach (var key in removedKeys)
Versions.Remove(key);
materializedVersions.Clear();
modifiedVersions.Clear();
removedKeys.Clear();
}
private void TransactionOpened(object sender, TransactionEventArgs transactionEventArgs)
{
if (transactionEventArgs.Transaction.IsNested)
return;
Versions.MergeWith(materializedVersions, Session);
materializedVersions.Clear();
}
private void Persisting(object sender, EventArgs eventArgs)
{
var registry = Session.EntityChangeRegistry;
var modifiedStates = registry.GetItems(PersistenceState.Modified)
.Concat(registry.GetItems(PersistenceState.New));
foreach (var state in modifiedStates) {
var versionTuple = state.Type.VersionExtractor.Apply(TupleTransformType.Tuple, state.Tuple);
modifiedVersions.Add(state.Key, new VersionInfo(versionTuple), true);
}
removedKeys.AddRange(registry.GetItems(PersistenceState.Removed).Select(s => s.Key));
}
#endregion
#region Private methods
private void AttachEventHandlers()
{
Session.SystemEvents.TransactionOpened += TransactionOpened;
Session.SystemEvents.TransactionCommitted +=TransactionCommitted;
Session.SystemEvents.TransactionRollbacked += TransactionRollbacked;
Session.SystemEvents.EntityMaterialized += EntityMaterialized;
Session.SystemEvents.Persisting += Persisting;
}
private void DetachEventHandlers()
{
Session.SystemEvents.TransactionOpened -= TransactionOpened;
Session.SystemEvents.TransactionCommitted -= TransactionCommitted;
Session.SystemEvents.TransactionRollbacked -= TransactionRollbacked;
Session.SystemEvents.EntityMaterialized -= EntityMaterialized;
Session.SystemEvents.Persisting -= Persisting;
}
#endregion
// Factory methods
/// <summary>
/// Attaches the version capturer to the current session.
/// </summary>
/// <param name="versions">The <see cref="VersionSet"/> to append captured versions to.</param>
/// <returns>
/// A newly created <see cref="VersionCapturer"/> attached
/// to the current session.
/// </returns>
[Obsolete("Use Attach(Session, VersionSet) instead")]
public static VersionCapturer Attach(VersionSet versions)
{
return Attach(Session.Demand(), versions);
}
/// <summary>
/// Attaches the version capturer to the current session.
/// </summary>
/// <param name="session">The session to attach the capturer to.</param>
/// <param name="versions">The <see cref="VersionSet"/> to append captured versions to.</param>
/// <returns>
/// A newly created <see cref="VersionCapturer"/> attached
/// to the specified <paramref name="session"/>.
/// </returns>
public static VersionCapturer Attach(Session session, VersionSet versions)
{
return new VersionCapturer(session, versions);
}
// Constructors
private VersionCapturer(Session session, VersionSet versions)
: base(session)
{
ArgumentValidator.EnsureArgumentNotNull(versions, "versions");
Versions = versions;
AttachEventHandlers();
}
// Dispose
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
DetachEventHandlers();
}
}
} | 32.876623 | 112 | 0.698005 | [
"MIT"
] | NekrasovSt/dataobjects-net | Orm/Xtensive.Orm/Orm/VersionCapturer.cs | 5,063 | C# |
//---------------------------------------------------------------------------------------------------
// <auto-generated>
// Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
// Generated by DynamicsCrm.DevKit - https://github.com/phuocle/Dynamics-Crm-DevKit
// </auto-generated>
//---------------------------------------------------------------------------------------------------
using Microsoft.Xrm.Sdk;
using System;
using System.Diagnostics;
namespace Abc.LuckyStar2.Shared.Entities.LookUpMappingOptionSets
{
public enum ComponentState
{
/// <summary>
/// Deleted = 2
/// </summary>
Deleted = 2,
/// <summary>
/// Deleted_Unpublished = 3
/// </summary>
Deleted_Unpublished = 3,
/// <summary>
/// Published = 0
/// </summary>
Published = 0,
/// <summary>
/// Unpublished = 1
/// </summary>
Unpublished = 1
}
public enum LookUpSourceCode
{
/// <summary>
/// Source = 0
/// </summary>
Source = 0,
/// <summary>
/// System = 1
/// </summary>
System = 1
}
public enum ProcessCode
{
/// <summary>
/// Ignore = 2
/// </summary>
Ignore = 2,
/// <summary>
/// Internal = 3
/// </summary>
Internal = 3,
/// <summary>
/// Process = 1
/// </summary>
Process = 1
}
public enum StateCode
{
/// <summary>
/// Active = 0
/// </summary>
Active = 0
}
public enum StatusCode
{
/// <summary>
/// Active = 0
/// </summary>
Active = 0
}
}
namespace Abc.LuckyStar2.Shared.Entities
{
public partial class LookUpMapping : EntityBase
{
public struct Fields
{
public const string ColumnMappingId = "columnmappingid";
public const string ComponentState = "componentstate";
public const string CreatedBy = "createdby";
public const string CreatedOn = "createdon";
public const string CreatedOnBehalfBy = "createdonbehalfby";
public const string IntroducedVersion = "introducedversion";
public const string IsManaged = "ismanaged";
public const string LookUpAttributeName = "lookupattributename";
public const string LookUpEntityName = "lookupentityname";
public const string LookUpMappingId = "lookupmappingid";
public const string LookUpMappingIdUnique = "lookupmappingidunique";
public const string LookUpSourceCode = "lookupsourcecode";
public const string ModifiedBy = "modifiedby";
public const string ModifiedOn = "modifiedon";
public const string ModifiedOnBehalfBy = "modifiedonbehalfby";
public const string OverwriteTime = "overwritetime";
public const string ProcessCode = "processcode";
public const string SolutionId = "solutionid";
public const string StateCode = "statecode";
public const string StatusCode = "statuscode";
public const string SupportingSolutionId = "supportingsolutionid";
public const string TransformationParameterMappingId = "transformationparametermappingid";
}
public const string EntityLogicalName = "lookupmapping";
public const int EntityTypeCode = 4419;
[DebuggerNonUserCode()]
public LookUpMapping()
{
Entity = new Entity(EntityLogicalName);
PreEntity = CloneThisEntity(Entity);
}
[DebuggerNonUserCode()]
public LookUpMapping(Guid LookUpMappingId)
{
Entity = new Entity(EntityLogicalName, LookUpMappingId);
PreEntity = CloneThisEntity(Entity);
}
[DebuggerNonUserCode()]
public LookUpMapping(string keyName, object keyValue)
{
Entity = new Entity(EntityLogicalName, keyName, keyValue);
PreEntity = CloneThisEntity(Entity);
}
[DebuggerNonUserCode()]
public LookUpMapping(Entity entity)
{
Entity = entity;
PreEntity = CloneThisEntity(Entity);
}
[DebuggerNonUserCode()]
public LookUpMapping(Entity entity, Entity merge)
{
Entity = entity;
foreach (var property in merge?.Attributes)
{
var key = property.Key;
var value = property.Value;
Entity[key] = value;
}
PreEntity = CloneThisEntity(Entity);
}
[DebuggerNonUserCode()]
public LookUpMapping(KeyAttributeCollection keys)
{
Entity = new Entity(EntityLogicalName, keys);
PreEntity = CloneThisEntity(Entity);
}
/// <summary>
/// <para>Unique identifier of the column mapping with which this lookup mapping is associated.</para>
/// <para>Lookup</para>
/// <para>Column Mapping Id</para>
/// </summary>
[DebuggerNonUserCode()]
public EntityReference ColumnMappingId
{
get { return Entity.GetAttributeValue<EntityReference>(Fields.ColumnMappingId); }
set { Entity.Attributes[Fields.ColumnMappingId] = value; }
}
/// <summary>
/// <para>For internal use only.</para>
/// <para>ReadOnly - Picklist</para>
/// <para>Component State</para>
/// </summary>
[DebuggerNonUserCode()]
public Abc.LuckyStar2.Shared.Entities.LookUpMappingOptionSets.ComponentState? ComponentState
{
get
{
var value = Entity.GetAttributeValue<OptionSetValue>(Fields.ComponentState);
if (value == null) return null;
return (Abc.LuckyStar2.Shared.Entities.LookUpMappingOptionSets.ComponentState)value.Value;
}
}
/// <summary>
/// <para>Unique identifier of the user who created the lookup mapping.</para>
/// <para>ReadOnly - Lookup</para>
/// <para>Created By</para>
/// </summary>
[DebuggerNonUserCode()]
public EntityReference CreatedBy
{
get { return Entity.GetAttributeValue<EntityReference>(Fields.CreatedBy); }
}
/// <summary>
/// <para>Date and time when the lookup mapping was created.</para>
/// <para>ReadOnly - DateTimeBehavior: UserLocal - DateTimeFormat: DateAndTime</para>
/// <para></para>
/// </summary>
[DebuggerNonUserCode()]
public DateTime? CreatedOnUtc
{
get { return Entity.GetAttributeValue<DateTime?>(Fields.CreatedOn); }
}
/// <summary>
/// <para>Unique identifier of the delegate user who created the lookupmapping.</para>
/// <para>ReadOnly - Lookup</para>
/// <para>Created By (Delegate)</para>
/// </summary>
[DebuggerNonUserCode()]
public EntityReference CreatedOnBehalfBy
{
get { return Entity.GetAttributeValue<EntityReference>(Fields.CreatedOnBehalfBy); }
}
/// <summary>
/// <para>Version in which the component is introduced.</para>
/// <para>String - MaxLength: 48</para>
/// <para>Introduced Version</para>
/// </summary>
[DebuggerNonUserCode()]
public string IntroducedVersion
{
get { return Entity.GetAttributeValue<string>(Fields.IntroducedVersion); }
set { Entity.Attributes[Fields.IntroducedVersion] = value; }
}
/// <summary>
/// <para>Information that specifies whether this component is managed.</para>
/// <para>ReadOnly - Boolean</para>
/// <para>State</para>
/// </summary>
[DebuggerNonUserCode()]
public bool? IsManaged
{
get { return Entity.GetAttributeValue<bool?>(Fields.IsManaged); }
}
/// <summary>
/// <para>Name of the field with which the lookup is associated.</para>
/// <para>Required - String - MaxLength: 160</para>
/// <para>Lookup Field Name</para>
/// </summary>
[DebuggerNonUserCode()]
public string LookUpAttributeName
{
get { return Entity.GetAttributeValue<string>(Fields.LookUpAttributeName); }
set { Entity.Attributes[Fields.LookUpAttributeName] = value; }
}
/// <summary>
/// <para>Name of the entity with which the lookup is associated.</para>
/// <para>Required - String - MaxLength: 160</para>
/// <para>Lookup Entity Name</para>
/// </summary>
[DebuggerNonUserCode()]
public string LookUpEntityName
{
get { return Entity.GetAttributeValue<string>(Fields.LookUpEntityName); }
set { Entity.Attributes[Fields.LookUpEntityName] = value; }
}
/// <summary>
/// <para>Unique identifier of the lookup mapping.</para>
/// <para>Primary Key - Uniqueidentifier</para>
/// <para></para>
/// </summary>
[DebuggerNonUserCode()]
public Guid LookUpMappingId
{
get { return Id; }
set
{
Entity.Attributes[Fields.LookUpMappingId] = value;
Entity.Id = value;
}
}
/// <summary>
/// <para>Unique identifier of the LookUp Mapping.</para>
/// <para>ReadOnly - Uniqueidentifier</para>
/// <para></para>
/// </summary>
[DebuggerNonUserCode()]
public Guid? LookUpMappingIdUnique
{
get { return Entity.GetAttributeValue<Guid?>(Fields.LookUpMappingIdUnique); }
}
/// <summary>
/// <para>Lookup source code for lookup mapping.</para>
/// <para>Picklist</para>
/// <para>Lookup Source</para>
/// </summary>
[DebuggerNonUserCode()]
public Abc.LuckyStar2.Shared.Entities.LookUpMappingOptionSets.LookUpSourceCode? LookUpSourceCode
{
get
{
var value = Entity.GetAttributeValue<OptionSetValue>(Fields.LookUpSourceCode);
if (value == null) return null;
return (Abc.LuckyStar2.Shared.Entities.LookUpMappingOptionSets.LookUpSourceCode)value.Value;
}
set
{
if (value.HasValue)
Entity.Attributes[Fields.LookUpSourceCode] = new OptionSetValue((int)value.Value);
else
Entity.Attributes[Fields.LookUpSourceCode] = null;
}
}
/// <summary>
/// <para>Unique identifier of the user who last modified the lookup mapping.</para>
/// <para>ReadOnly - Lookup</para>
/// <para>Modified By</para>
/// </summary>
[DebuggerNonUserCode()]
public EntityReference ModifiedBy
{
get { return Entity.GetAttributeValue<EntityReference>(Fields.ModifiedBy); }
}
/// <summary>
/// <para>Date and time when the lookup mapping was last modified.</para>
/// <para>ReadOnly - DateTimeBehavior: UserLocal - DateTimeFormat: DateAndTime</para>
/// <para>Modified On</para>
/// </summary>
[DebuggerNonUserCode()]
public DateTime? ModifiedOnUtc
{
get { return Entity.GetAttributeValue<DateTime?>(Fields.ModifiedOn); }
}
/// <summary>
/// <para>Unique identifier of the delegate user who last modified the lookupmapping.</para>
/// <para>ReadOnly - Lookup</para>
/// <para>Modified By (Delegate)</para>
/// </summary>
[DebuggerNonUserCode()]
public EntityReference ModifiedOnBehalfBy
{
get { return Entity.GetAttributeValue<EntityReference>(Fields.ModifiedOnBehalfBy); }
}
/// <summary>
/// <para>For internal use only.</para>
/// <para>ReadOnly - DateTimeBehavior: UserLocal - DateTimeFormat: DateOnly</para>
/// <para>Record Overwrite Time</para>
/// </summary>
[DebuggerNonUserCode()]
public DateTime? OverwriteTimeUtc
{
get { return Entity.GetAttributeValue<DateTime?>(Fields.OverwriteTime); }
}
/// <summary>
/// <para>Information about whether the lookup mapping has to be processed.</para>
/// <para>Picklist</para>
/// <para>Process Code</para>
/// </summary>
[DebuggerNonUserCode()]
public Abc.LuckyStar2.Shared.Entities.LookUpMappingOptionSets.ProcessCode? ProcessCode
{
get
{
var value = Entity.GetAttributeValue<OptionSetValue>(Fields.ProcessCode);
if (value == null) return null;
return (Abc.LuckyStar2.Shared.Entities.LookUpMappingOptionSets.ProcessCode)value.Value;
}
set
{
if (value.HasValue)
Entity.Attributes[Fields.ProcessCode] = new OptionSetValue((int)value.Value);
else
Entity.Attributes[Fields.ProcessCode] = null;
}
}
/// <summary>
/// <para>Unique identifier of the associated solution.</para>
/// <para>ReadOnly - Uniqueidentifier</para>
/// <para>Solution</para>
/// </summary>
[DebuggerNonUserCode()]
public Guid? SolutionId
{
get { return Entity.GetAttributeValue<Guid?>(Fields.SolutionId); }
}
/// <summary>
/// <para>Status of the lookup mapping.</para>
/// <para>ReadOnly - State</para>
/// <para>Status</para>
/// </summary>
[DebuggerNonUserCode()]
public Abc.LuckyStar2.Shared.Entities.LookUpMappingOptionSets.StateCode? StateCode
{
get
{
var value = Entity.GetAttributeValue<OptionSetValue>(Fields.StateCode);
if (value == null) return null;
return (Abc.LuckyStar2.Shared.Entities.LookUpMappingOptionSets.StateCode)value.Value;
}
}
/// <summary>
/// <para>Reason for the status of the lookup mapping.</para>
/// <para>Status</para>
/// <para>Status Reason</para>
/// </summary>
[DebuggerNonUserCode()]
public Abc.LuckyStar2.Shared.Entities.LookUpMappingOptionSets.StatusCode? StatusCode
{
get
{
var value = Entity.GetAttributeValue<OptionSetValue>(Fields.StatusCode);
if (value == null) return null;
return (Abc.LuckyStar2.Shared.Entities.LookUpMappingOptionSets.StatusCode)value.Value;
}
set
{
if (value.HasValue)
Entity.Attributes[Fields.StatusCode] = new OptionSetValue((int)value.Value);
else
Entity.Attributes[Fields.StatusCode] = null;
}
}
/// <summary>
/// <para>For internal use only.</para>
/// <para>ReadOnly - Uniqueidentifier</para>
/// <para>Solution</para>
/// </summary>
[DebuggerNonUserCode()]
public Guid? SupportingSolutionId
{
get { return Entity.GetAttributeValue<Guid?>(Fields.SupportingSolutionId); }
}
/// <summary>
/// <para>Unique identifier of the transformation parameter mapping with which this lookup mapping is associated.</para>
/// <para>Lookup</para>
/// <para>Transformation Parameter Mapping Id</para>
/// </summary>
[DebuggerNonUserCode()]
public EntityReference TransformationParameterMappingId
{
get { return Entity.GetAttributeValue<EntityReference>(Fields.TransformationParameterMappingId); }
set { Entity.Attributes[Fields.TransformationParameterMappingId] = value; }
}
}
}
| 29.22658 | 122 | 0.67924 | [
"MIT"
] | Kayserheimer/Dynamics-Crm-DevKit | test/v.2.10.31/Abc.LuckyStar2/Abc.LuckyStar2.Shared/Entities/LookUpMapping.generated.cs | 13,417 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace IdentityServervNextDemo.Migrations
{
public partial class Upgraded_To_Abp_5_4_0 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_AbpOrganizationUnits_TenantId_Code",
table: "AbpOrganizationUnits");
migrationBuilder.CreateTable(
name: "AbpDynamicParameters",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ParameterName = table.Column<string>(nullable: true),
InputType = table.Column<string>(nullable: true),
Permission = table.Column<string>(nullable: true),
TenantId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpDynamicParameters", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AbpDynamicParameterValues",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Value = table.Column<string>(nullable: false),
TenantId = table.Column<int>(nullable: true),
DynamicParameterId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpDynamicParameterValues", x => x.Id);
table.ForeignKey(
name: "FK_AbpDynamicParameterValues_AbpDynamicParameters_DynamicParameterId",
column: x => x.DynamicParameterId,
principalTable: "AbpDynamicParameters",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AbpEntityDynamicParameters",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
EntityFullName = table.Column<string>(nullable: true),
DynamicParameterId = table.Column<int>(nullable: false),
TenantId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpEntityDynamicParameters", x => x.Id);
table.ForeignKey(
name: "FK_AbpEntityDynamicParameters_AbpDynamicParameters_DynamicParameterId",
column: x => x.DynamicParameterId,
principalTable: "AbpDynamicParameters",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AbpEntityDynamicParameterValues",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Value = table.Column<string>(nullable: false),
EntityId = table.Column<string>(nullable: true),
EntityDynamicParameterId = table.Column<int>(nullable: false),
TenantId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AbpEntityDynamicParameterValues", x => x.Id);
table.ForeignKey(
name: "FK_AbpEntityDynamicParameterValues_AbpEntityDynamicParameters_EntityDynamicParameterId",
column: x => x.EntityDynamicParameterId,
principalTable: "AbpEntityDynamicParameters",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AbpOrganizationUnits_TenantId_Code",
table: "AbpOrganizationUnits",
columns: new[] { "TenantId", "Code" },
unique: true,
filter: "[TenantId] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_AbpDynamicParameters_ParameterName_TenantId",
table: "AbpDynamicParameters",
columns: new[] { "ParameterName", "TenantId" },
unique: true,
filter: "[ParameterName] IS NOT NULL AND [TenantId] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_AbpDynamicParameterValues_DynamicParameterId",
table: "AbpDynamicParameterValues",
column: "DynamicParameterId");
migrationBuilder.CreateIndex(
name: "IX_AbpEntityDynamicParameters_DynamicParameterId",
table: "AbpEntityDynamicParameters",
column: "DynamicParameterId");
migrationBuilder.CreateIndex(
name: "IX_AbpEntityDynamicParameters_EntityFullName_DynamicParameterId_TenantId",
table: "AbpEntityDynamicParameters",
columns: new[] { "EntityFullName", "DynamicParameterId", "TenantId" },
unique: true,
filter: "[EntityFullName] IS NOT NULL AND [TenantId] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_AbpEntityDynamicParameterValues_EntityDynamicParameterId",
table: "AbpEntityDynamicParameterValues",
column: "EntityDynamicParameterId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AbpDynamicParameterValues");
migrationBuilder.DropTable(
name: "AbpEntityDynamicParameterValues");
migrationBuilder.DropTable(
name: "AbpEntityDynamicParameters");
migrationBuilder.DropTable(
name: "AbpDynamicParameters");
migrationBuilder.DropIndex(
name: "IX_AbpOrganizationUnits_TenantId_Code",
table: "AbpOrganizationUnits");
migrationBuilder.CreateIndex(
name: "IX_AbpOrganizationUnits_TenantId_Code",
table: "AbpOrganizationUnits",
columns: new[] { "TenantId", "Code" });
}
}
}
| 44.419355 | 119 | 0.537545 | [
"MIT"
] | OzBob/aspnetboilerplate-samples | IdentityServervNextDemo/aspnet-core/src/IdentityServervNextDemo.EntityFrameworkCore/Migrations/20200320114152_Upgraded_To_Abp_5_4_0.cs | 6,887 | C# |
using System;
using System.Diagnostics;
using BenchmarkDotNet.Characteristics;
using BenchmarkDotNet.Environments;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Loggers;
using BenchmarkDotNet.Portability;
using BenchmarkDotNet.Running;
using JetBrains.Annotations;
namespace BenchmarkDotNet.Extensions
{
// we need it public to reuse it in the auto-generated dll
// but we hide it from intellisense with following attribute
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[PublicAPI]
public static class ProcessExtensions
{
public static void EnsureHighPriority(this Process process, ILogger logger)
{
try
{
process.PriorityClass = ProcessPriorityClass.High;
}
catch (Exception ex)
{
logger.WriteLineError($"Failed to set up high priority. Make sure you have the right permissions. Message: {ex.Message}");
}
}
internal static string ToPresentation(this IntPtr processorAffinity, int processorCount)
=> (RuntimeInformation.GetCurrentPlatform() == Platform.X64
? Convert.ToString(processorAffinity.ToInt64(), 2)
: Convert.ToString(processorAffinity.ToInt32(), 2))
.PadLeft(processorCount, '0');
private static IntPtr FixAffinity(IntPtr processorAffinity)
{
int cpuMask = (1 << Environment.ProcessorCount) - 1;
return RuntimeInformation.GetCurrentPlatform() == Platform.X64
? new IntPtr(processorAffinity.ToInt64() & cpuMask)
: new IntPtr(processorAffinity.ToInt32() & cpuMask);
}
public static bool TrySetPriority(
[NotNull] this Process process,
ProcessPriorityClass priority,
[NotNull] ILogger logger)
{
if (process == null)
throw new ArgumentNullException(nameof(process));
if (logger == null)
throw new ArgumentNullException(nameof(logger));
try
{
process.PriorityClass = priority;
return true;
}
catch (Exception ex)
{
logger.WriteLineError(
$"// ! Failed to set up priority {priority} for process {process}. Make sure you have the right permissions. Message: {ex.Message}");
}
return false;
}
public static bool TrySetAffinity(
[NotNull] this Process process,
IntPtr processorAffinity,
[NotNull] ILogger logger)
{
if (process == null)
throw new ArgumentNullException(nameof(process));
if (logger == null)
throw new ArgumentNullException(nameof(logger));
try
{
process.ProcessorAffinity = FixAffinity(processorAffinity);
return true;
}
catch (Exception ex)
{
logger.WriteLineError(
$"// ! Failed to set up processor affinity 0x{(long)processorAffinity:X} for process {process}. Make sure you have the right permissions. Message: {ex.Message}");
}
return false;
}
public static IntPtr? TryGetAffinity([NotNull] this Process process)
{
if (process == null)
throw new ArgumentNullException(nameof(process));
try
{
return process.ProcessorAffinity;
}
catch (PlatformNotSupportedException)
{
return null;
}
}
internal static void SetEnvironmentVariables(this ProcessStartInfo start, BenchmarkCase benchmarkCase, IResolver resolver)
{
if (benchmarkCase.Job.Environment.Runtime is ClrRuntime clrRuntime && !string.IsNullOrEmpty(clrRuntime.Version))
start.EnvironmentVariables["COMPLUS_Version"] = clrRuntime.Version;
if (!benchmarkCase.Job.HasValue(EnvironmentMode.EnvironmentVariablesCharacteristic))
return;
foreach (var environmentVariable in benchmarkCase.Job.Environment.EnvironmentVariables)
start.EnvironmentVariables[environmentVariable.Key] = environmentVariable.Value;
}
}
} | 36.884298 | 182 | 0.598252 | [
"MIT"
] | alexanderkyte/BenchmarkDotNet | src/BenchmarkDotNet/Extensions/ProcessExtensions.cs | 4,465 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Linq;
namespace TypeScript.Syntax
{
public class EqualsEqualsToken : Node
{
public override NodeKind Kind
{
get { return NodeKind.EqualsEqualsToken; }
}
public override void Init(JObject jsonObj)
{
base.Init(jsonObj);
}
public override void AddChild(Node childNode)
{
base.AddChild(childNode);
string nodeName = childNode.NodeName;
switch (nodeName)
{
default:
this.ProcessUnknownNode(childNode);
break;
}
}
}
}
| 20.857143 | 55 | 0.539726 | [
"MIT"
] | Luiz-Monad/typescript-converter | src/Syntax/SyntaxNodes/EqualsEqualsToken.cs | 730 | 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/mfmediaengine.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace TerraFX.Interop.Windows;
/// <include file='IMFMediaKeys.xml' path='doc/member[@name="IMFMediaKeys"]/*' />
[Guid("5CB31C05-61FF-418F-AFDA-CAAF41421A38")]
[NativeTypeName("struct IMFMediaKeys : IUnknown")]
[NativeInheritance("IUnknown")]
[SupportedOSPlatform("windows8.1")]
public unsafe partial struct IMFMediaKeys : IMFMediaKeys.Interface
{
public void** lpVtbl;
/// <inheritdoc cref="IUnknown.QueryInterface" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(0)]
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
{
return ((delegate* unmanaged<IMFMediaKeys*, Guid*, void**, int>)(lpVtbl[0]))((IMFMediaKeys*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
/// <inheritdoc cref="IUnknown.AddRef" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(1)]
[return: NativeTypeName("ULONG")]
public uint AddRef()
{
return ((delegate* unmanaged<IMFMediaKeys*, uint>)(lpVtbl[1]))((IMFMediaKeys*)Unsafe.AsPointer(ref this));
}
/// <inheritdoc cref="IUnknown.Release" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(2)]
[return: NativeTypeName("ULONG")]
public uint Release()
{
return ((delegate* unmanaged<IMFMediaKeys*, uint>)(lpVtbl[2]))((IMFMediaKeys*)Unsafe.AsPointer(ref this));
}
/// <include file='IMFMediaKeys.xml' path='doc/member[@name="IMFMediaKeys.CreateSession"]/*' />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(3)]
public HRESULT CreateSession([NativeTypeName("BSTR")] ushort* mimeType, [NativeTypeName("const BYTE *")] byte* initData, [NativeTypeName("DWORD")] uint cb, [NativeTypeName("const BYTE *")] byte* customData, [NativeTypeName("DWORD")] uint cbCustomData, IMFMediaKeySessionNotify* notify, IMFMediaKeySession** ppSession)
{
return ((delegate* unmanaged<IMFMediaKeys*, ushort*, byte*, uint, byte*, uint, IMFMediaKeySessionNotify*, IMFMediaKeySession**, int>)(lpVtbl[3]))((IMFMediaKeys*)Unsafe.AsPointer(ref this), mimeType, initData, cb, customData, cbCustomData, notify, ppSession);
}
/// <include file='IMFMediaKeys.xml' path='doc/member[@name="IMFMediaKeys.get_KeySystem"]/*' />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(4)]
public HRESULT get_KeySystem([NativeTypeName("BSTR *")] ushort** keySystem)
{
return ((delegate* unmanaged<IMFMediaKeys*, ushort**, int>)(lpVtbl[4]))((IMFMediaKeys*)Unsafe.AsPointer(ref this), keySystem);
}
/// <include file='IMFMediaKeys.xml' path='doc/member[@name="IMFMediaKeys.Shutdown"]/*' />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(5)]
public HRESULT Shutdown()
{
return ((delegate* unmanaged<IMFMediaKeys*, int>)(lpVtbl[5]))((IMFMediaKeys*)Unsafe.AsPointer(ref this));
}
/// <include file='IMFMediaKeys.xml' path='doc/member[@name="IMFMediaKeys.GetSuspendNotify"]/*' />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(6)]
public HRESULT GetSuspendNotify(IMFCdmSuspendNotify** notify)
{
return ((delegate* unmanaged<IMFMediaKeys*, IMFCdmSuspendNotify**, int>)(lpVtbl[6]))((IMFMediaKeys*)Unsafe.AsPointer(ref this), notify);
}
public interface Interface : IUnknown.Interface
{
[VtblIndex(3)]
HRESULT CreateSession([NativeTypeName("BSTR")] ushort* mimeType, [NativeTypeName("const BYTE *")] byte* initData, [NativeTypeName("DWORD")] uint cb, [NativeTypeName("const BYTE *")] byte* customData, [NativeTypeName("DWORD")] uint cbCustomData, IMFMediaKeySessionNotify* notify, IMFMediaKeySession** ppSession);
[VtblIndex(4)]
HRESULT get_KeySystem([NativeTypeName("BSTR *")] ushort** keySystem);
[VtblIndex(5)]
HRESULT Shutdown();
[VtblIndex(6)]
HRESULT GetSuspendNotify(IMFCdmSuspendNotify** notify);
}
public partial struct Vtbl<TSelf>
where TSelf : unmanaged, Interface
{
[NativeTypeName("HRESULT (const IID &, void **) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, Guid*, void**, int> QueryInterface;
[NativeTypeName("ULONG () __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint> AddRef;
[NativeTypeName("ULONG () __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint> Release;
[NativeTypeName("HRESULT (BSTR, const BYTE *, DWORD, const BYTE *, DWORD, IMFMediaKeySessionNotify *, IMFMediaKeySession **) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, ushort*, byte*, uint, byte*, uint, IMFMediaKeySessionNotify*, IMFMediaKeySession**, int> CreateSession;
[NativeTypeName("HRESULT (BSTR *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, ushort**, int> get_KeySystem;
[NativeTypeName("HRESULT () __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, int> Shutdown;
[NativeTypeName("HRESULT (IMFCdmSuspendNotify **) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, IMFCdmSuspendNotify**, int> GetSuspendNotify;
}
}
| 46.75 | 321 | 0.698039 | [
"MIT"
] | reflectronic/terrafx.interop.windows | sources/Interop/Windows/Windows/um/mfmediaengine/IMFMediaKeys.cs | 5,612 | C# |
using UnityEngine;
using Wenzil.Console.Commands;
using DaggerfallWorkshop.Game;
using System.Linq;
using System;
using DaggerfallConnect.Arena2;
using System.Collections;
using System.Collections.Generic;
using DaggerfallWorkshop;
using DaggerfallWorkshop.Game.Entity;
using System.IO;
using DaggerfallWorkshop.Utility;
using DaggerfallWorkshop.Game.Items;
using DaggerfallWorkshop.Game.Weather;
using DaggerfallWorkshop.Game.Questing;
using DaggerfallWorkshop.Game.MagicAndEffects;
using DaggerfallWorkshop.Game.UserInterface;
using DaggerfallWorkshop.Game.UserInterfaceWindows;
using DaggerfallWorkshop.Game.Formulas;
using DaggerfallConnect;
using DaggerfallWorkshop.Game.Serialization;
using DaggerfallWorkshop.Utility.AssetInjection;
using DaggerfallConnect.FallExe;
using DaggerfallWorkshop.Game.Utility.ModSupport;
using DaggerfallWorkshop.Game.Utility.ModSupport.ModSettings;
namespace Wenzil.Console
{
public class DefaultCommands : MonoBehaviour
{
public static bool showDebugStrings = false;
void Start()
{
ConsoleCommandsDatabase.RegisterCommand(QuitCommand.name, QuitCommand.description, QuitCommand.usage, QuitCommand.Execute);
ConsoleCommandsDatabase.RegisterCommand(HelpCommand.name, HelpCommand.description, HelpCommand.usage, HelpCommand.Execute);
ConsoleCommandsDatabase.RegisterCommand(LoadCommand.name, LoadCommand.description, LoadCommand.usage, LoadCommand.Execute);
ConsoleCommandsDatabase.RegisterCommand(GodCommand.name, GodCommand.description, GodCommand.usage, GodCommand.Execute);
ConsoleCommandsDatabase.RegisterCommand(NoTargetCommand.name, NoTargetCommand.description, NoTargetCommand.usage, NoTargetCommand.Execute);
ConsoleCommandsDatabase.RegisterCommand(ToggleAICommand.name, ToggleAICommand.description, ToggleAICommand.usage, ToggleAICommand.Execute);
ConsoleCommandsDatabase.RegisterCommand(CreateMobileCommand.name, CreateMobileCommand.description, CreateMobileCommand.usage, CreateMobileCommand.Execute);
ConsoleCommandsDatabase.RegisterCommand(Suicide.name, Suicide.description, Suicide.usage, Suicide.Execute);
ConsoleCommandsDatabase.RegisterCommand(ShowDebugStrings.name, ShowDebugStrings.description, ShowDebugStrings.usage, ShowDebugStrings.Execute);
ConsoleCommandsDatabase.RegisterCommand(SetWeather.name, SetWeather.description, SetWeather.usage, SetWeather.Execute);
ConsoleCommandsDatabase.RegisterCommand(TeleportToMapPixel.name, TeleportToMapPixel.description, TeleportToMapPixel.usage, TeleportToMapPixel.Execute);
ConsoleCommandsDatabase.RegisterCommand(TeleportToDungeonDoor.name, TeleportToDungeonDoor.description, TeleportToDungeonDoor.usage, TeleportToDungeonDoor.Execute);
ConsoleCommandsDatabase.RegisterCommand(TeleportToQuestSpawnMarker.name, TeleportToQuestSpawnMarker.description, TeleportToQuestSpawnMarker.usage, TeleportToQuestSpawnMarker.Execute);
ConsoleCommandsDatabase.RegisterCommand(TeleportToQuestItemMarker.name, TeleportToQuestItemMarker.description, TeleportToQuestItemMarker.usage, TeleportToQuestItemMarker.Execute);
ConsoleCommandsDatabase.RegisterCommand(TeleportToQuestMarker.name, TeleportToQuestMarker.description, TeleportToQuestMarker.usage, TeleportToQuestMarker.Execute);
ConsoleCommandsDatabase.RegisterCommand(GetAllQuestItems.name, GetAllQuestItems.description, GetAllQuestItems.usage, GetAllQuestItems.Execute);
ConsoleCommandsDatabase.RegisterCommand(EndDebugQuest.name, EndDebugQuest.description, EndDebugQuest.usage, EndDebugQuest.Execute);
ConsoleCommandsDatabase.RegisterCommand(EndQuest.name, EndQuest.description, EndQuest.usage, EndQuest.Execute);
ConsoleCommandsDatabase.RegisterCommand(PurgeAllQuests.name, PurgeAllQuests.description, PurgeAllQuests.usage, PurgeAllQuests.Execute);
ConsoleCommandsDatabase.RegisterCommand(ModNPCRep.name, ModNPCRep.description, ModNPCRep.usage, ModNPCRep.Execute);
ConsoleCommandsDatabase.RegisterCommand(SetLevel.name, SetLevel.description, SetLevel.usage, SetLevel.Execute);
ConsoleCommandsDatabase.RegisterCommand(Levitate.name, Levitate.description, Levitate.usage, Levitate.Execute);
ConsoleCommandsDatabase.RegisterCommand(OpenAllDoors.name, OpenAllDoors.description, OpenAllDoors.usage, OpenAllDoors.Execute);
ConsoleCommandsDatabase.RegisterCommand(OpenDoor.name, OpenDoor.description, OpenDoor.usage, OpenDoor.Execute);
ConsoleCommandsDatabase.RegisterCommand(ActivateAction.name, ActivateAction.description, ActivateAction.usage, ActivateAction.Execute);
ConsoleCommandsDatabase.RegisterCommand(KillAllEnemies.name, KillAllEnemies.description, KillAllEnemies.usage, KillAllEnemies.Execute);
ConsoleCommandsDatabase.RegisterCommand(TransitionToExterior.name, TransitionToExterior.description, TransitionToExterior.usage, TransitionToExterior.Execute);
ConsoleCommandsDatabase.RegisterCommand(SetHealth.name, SetHealth.description, SetHealth.usage, SetHealth.Execute);
ConsoleCommandsDatabase.RegisterCommand(RerollMaxHealth.name, RerollMaxHealth.description, RerollMaxHealth.usage, RerollMaxHealth.Execute);
ConsoleCommandsDatabase.RegisterCommand(ResetAssets.name, ResetAssets.description, ResetAssets.usage, ResetAssets.Execute);
ConsoleCommandsDatabase.RegisterCommand(RetryAssetImports.name, RetryAssetImports.description, RetryAssetImports.usage, RetryAssetImports.Execute);
ConsoleCommandsDatabase.RegisterCommand(SetWalkSpeed.name, SetWalkSpeed.description, SetWalkSpeed.usage, SetWalkSpeed.Execute);
ConsoleCommandsDatabase.RegisterCommand(SetMouseSensitivity.name, SetMouseSensitivity.description, SetMouseSensitivity.usage, SetMouseSensitivity.Execute);
ConsoleCommandsDatabase.RegisterCommand(ToggleMouseSmoothing.name, ToggleMouseSmoothing.description, ToggleMouseSmoothing.usage, ToggleMouseSmoothing.Execute);
ConsoleCommandsDatabase.RegisterCommand(AddPopupText.name, AddPopupText.description, AddPopupText.usage, AddPopupText.Execute);
//ConsoleCommandsDatabase.RegisterCommand(SetMouseSmoothing.name, SetMouseSmoothing.description, SetMouseSmoothing.usage, SetMouseSmoothing.Execute);
ConsoleCommandsDatabase.RegisterCommand(SetVSync.name, SetVSync.description, SetVSync.usage, SetVSync.Execute);
ConsoleCommandsDatabase.RegisterCommand(SetRunSpeed.name, SetRunSpeed.description, SetRunSpeed.usage, SetRunSpeed.Execute);
ConsoleCommandsDatabase.RegisterCommand(SetJumpSpeed.name, SetJumpSpeed.description, SetJumpSpeed.usage, SetJumpSpeed.Execute);
ConsoleCommandsDatabase.RegisterCommand(ToggleAirControl.name, ToggleAirControl.description, ToggleAirControl.usage, ToggleAirControl.Execute);
ConsoleCommandsDatabase.RegisterCommand(SetTimeScale.name, SetTimeScale.description, SetTimeScale.usage, SetTimeScale.Execute);
ConsoleCommandsDatabase.RegisterCommand(SetGravity.name, SetGravity.description, SetGravity.usage, SetGravity.Execute);
ConsoleCommandsDatabase.RegisterCommand(GotoLocation.name, GotoLocation.description, GotoLocation.usage, GotoLocation.Execute);
ConsoleCommandsDatabase.RegisterCommand(GetLocationMapPixel.name, GetLocationMapPixel.description, GetLocationMapPixel.usage, GetLocationMapPixel.Execute);
ConsoleCommandsDatabase.RegisterCommand(Teleport.name, Teleport.description, Teleport.usage, Teleport.Execute);
ConsoleCommandsDatabase.RegisterCommand(Groundme.name, Groundme.description, Groundme.usage, Groundme.Execute);
ConsoleCommandsDatabase.RegisterCommand(ExecuteScript.name, ExecuteScript.description, ExecuteScript.usage, ExecuteScript.Execute);
ConsoleCommandsDatabase.RegisterCommand(AddInventoryItem.name, AddInventoryItem.description, AddInventoryItem.usage, AddInventoryItem.Execute);
ConsoleCommandsDatabase.RegisterCommand(AddArtifact.name, AddArtifact.description, AddArtifact.usage, AddArtifact.Execute);
ConsoleCommandsDatabase.RegisterCommand(AddWeapon.name, AddWeapon.description, AddWeapon.usage, AddWeapon.Execute);
ConsoleCommandsDatabase.RegisterCommand(AddArmor.name, AddArmor.description, AddArmor.usage, AddArmor.Execute);
ConsoleCommandsDatabase.RegisterCommand(AddClothing.name, AddClothing.description, AddClothing.usage, AddClothing.Execute);
ConsoleCommandsDatabase.RegisterCommand(AddAllEquip.name, AddAllEquip.description, AddAllEquip.usage, AddAllEquip.Execute);
ConsoleCommandsDatabase.RegisterCommand(AddBook.name, AddBook.description, AddBook.usage, AddBook.Execute);
ConsoleCommandsDatabase.RegisterCommand(ShowBankWindow.name, ShowBankWindow.description, ShowBankWindow.usage, ShowBankWindow.Execute);
ConsoleCommandsDatabase.RegisterCommand(ShowSpellmakerWindow.name, ShowSpellmakerWindow.description, ShowSpellmakerWindow.usage, ShowSpellmakerWindow.Execute);
ConsoleCommandsDatabase.RegisterCommand(ShowItemMakerWindow.name, ShowItemMakerWindow.description, ShowItemMakerWindow.usage, ShowItemMakerWindow.Execute);
ConsoleCommandsDatabase.RegisterCommand(ShowPotionMakerWindow.name, ShowPotionMakerWindow.description, ShowPotionMakerWindow.usage, ShowPotionMakerWindow.Execute);
ConsoleCommandsDatabase.RegisterCommand(AddSpellBook.name, AddSpellBook.description, AddSpellBook.usage, AddSpellBook.Execute);
ConsoleCommandsDatabase.RegisterCommand(StartQuest.name, StartQuest.usage, StartQuest.description, StartQuest.Execute);
ConsoleCommandsDatabase.RegisterCommand(DiseasePlayer.name, DiseasePlayer.usage, DiseasePlayer.description, DiseasePlayer.Execute);
ConsoleCommandsDatabase.RegisterCommand(PoisonPlayer.name, PoisonPlayer.usage, PoisonPlayer.description, PoisonPlayer.Execute);
ConsoleCommandsDatabase.RegisterCommand(DumpRegion.name, DumpRegion.description, DumpRegion.usage, DumpRegion.Execute);
ConsoleCommandsDatabase.RegisterCommand(DumpLocation.name, DumpLocation.description, DumpLocation.usage, DumpLocation.Execute);
ConsoleCommandsDatabase.RegisterCommand(DumpBlock.name, DumpBlock.description, DumpBlock.usage, DumpBlock.Execute);
ConsoleCommandsDatabase.RegisterCommand(DumpLocBlocks.name, DumpLocBlocks.description, DumpLocBlocks.usage, DumpLocBlocks.Execute);
ConsoleCommandsDatabase.RegisterCommand(DumpBuilding.name, DumpBuilding.description, DumpBuilding.usage, DumpBuilding.Execute);
ConsoleCommandsDatabase.RegisterCommand(IngredientUsage.name, IngredientUsage.description, IngredientUsage.usage, IngredientUsage.Execute);
ConsoleCommandsDatabase.RegisterCommand(PlayFLC.name, PlayFLC.description, PlayFLC.usage, PlayFLC.Execute);
ConsoleCommandsDatabase.RegisterCommand(PlayVID.name, PlayVID.description, PlayVID.usage, PlayVID.Execute);
ConsoleCommandsDatabase.RegisterCommand(PrintLegalRep.name, PrintLegalRep.description, PrintLegalRep.usage, PrintLegalRep.Execute);
ConsoleCommandsDatabase.RegisterCommand(ClearNegativeLegalRep.name, ClearNegativeLegalRep.description, ClearNegativeLegalRep.usage, ClearNegativeLegalRep.Execute);
ConsoleCommandsDatabase.RegisterCommand(SummonDaedra.name, SummonDaedra.description, SummonDaedra.usage, SummonDaedra.Execute);
ConsoleCommandsDatabase.RegisterCommand(ChangeModSettings.name, ChangeModSettings.description, ChangeModSettings.usage, ChangeModSettings.Execute);
}
private static class DumpRegion
{
public static readonly string name = "dumpregion";
public static readonly string error = "Player not in a region, unable to dump";
public static readonly string usage = "dumpregion";
public static readonly string description = "Dump the current region (from MAPS.BSA) that the player is currently in to json file";
public static string Execute(params string[] args)
{
if (args.Length != 0)
{
return HelpCommand.Execute(DumpRegion.name);
}
else
{
PlayerGPS playerGPS = GameManager.Instance.PlayerGPS;
if (playerGPS)
{
DFRegion region = playerGPS.CurrentRegion;
string regionJson = SaveLoadManager.Serialize(region.GetType(), region);
string fileName = WorldDataReplacement.GetDFRegionReplacementFilename(playerGPS.CurrentRegionIndex);
File.WriteAllText(Path.Combine(Application.persistentDataPath, fileName), regionJson);
return "Region data json written to " + Path.Combine(Application.persistentDataPath, fileName);
}
return error;
}
}
}
private static class DumpLocation
{
public static readonly string name = "dumplocation";
public static readonly string error = "Player not at a location, unable to dump";
public static readonly string usage = "dumplocation";
public static readonly string description = "Dump the current location (from MAPS.BSA) that the player is currently in to json file";
public static string Execute(params string[] args)
{
if (args.Length != 0)
{
return HelpCommand.Execute(DumpLocation.name);
}
else
{
PlayerGPS playerGPS = GameManager.Instance.PlayerGPS;
if (playerGPS.HasCurrentLocation)
{
DFLocation location = playerGPS.CurrentLocation;
string locJson = SaveLoadManager.Serialize(location.GetType(), location);
string fileName = WorldDataReplacement.GetDFLocationReplacementFilename(location.RegionIndex, location.LocationIndex);
File.WriteAllText(Path.Combine(Application.persistentDataPath, fileName), locJson);
return "Location data json written to " + Path.Combine(Application.persistentDataPath, fileName);
}
return error;
}
}
}
private static class DumpBlock
{
public static readonly string name = "dumpblock";
public static readonly string error = "Failed to dump block";
public static readonly string usage = "dumpblock [blockName]";
public static readonly string description = "Dump a block to json file, or index if no block name specified";
public static string Execute(params string[] args)
{
if (args.Length == 0)
{
string blockIndex = "";
BsaFile blockBsa = DaggerfallUnity.Instance.ContentReader.BlockFileReader.BsaFile;
for (int b = 0; b < blockBsa.Count; b++)
{
blockIndex += string.Format("{0}: {1}\n", b, blockBsa.GetRecordName(b));
}
string fileName = Path.Combine(Application.persistentDataPath, "BlockIndex.txt");
File.WriteAllText(fileName, blockIndex);
return "Block index data written to " + Path.Combine(Application.persistentDataPath, fileName);
}
else
{
DFBlock blockData;
if (!RMBLayout.GetBlockData(args[0], out blockData))
{
if (args[0].EndsWith(".RDB", StringComparison.InvariantCultureIgnoreCase))
{
blockData = DaggerfallUnity.Instance.ContentReader.BlockFileReader.GetBlock(args[0]);
}
}
if (!string.IsNullOrEmpty(blockData.Name))
{
string blockJson = SaveLoadManager.Serialize(blockData.GetType(), blockData);
string fileName = WorldDataReplacement.GetDFBlockReplacementFilename(blockData.Name);
File.WriteAllText(Path.Combine(Application.persistentDataPath, fileName), blockJson);
return "Block data json written to " + Path.Combine(Application.persistentDataPath, fileName);
}
return error;
}
}
}
private static class DumpLocBlocks
{
public static readonly string name = "dumplocblocks";
public static readonly string error = "Failed to dump locations";
public static readonly string usage = "dumplocblocks [locindex|(blockName.RMB )*]\nExamples:\ndumplocblocks\ndumplocblocks locindex\ndumplocblocks RESIAM10.RMB GEMSAM02.RMB";
public static readonly string description = "Dump the names of blocks for each location, location index or locations for list of given block(s), to json file";
public static string Execute(params string[] args)
{
MapsFile mapFileReader = DaggerfallUnity.Instance.ContentReader.MapFileReader;
if (args.Length == 0)
{
Dictionary<string, string[]> locBlocks = new Dictionary<string, string[]>();
for (int region = 0; region < mapFileReader.RegionCount; region++)
{
DFRegion dfRegion = mapFileReader.GetRegion(region);
for (int location = 0; location < dfRegion.LocationCount; location++)
{
DFLocation dfLoc = mapFileReader.GetLocation(region, location);
locBlocks[dfLoc.Name] = dfLoc.Exterior.ExteriorData.BlockNames;
}
}
string locJson = SaveLoadManager.Serialize(locBlocks.GetType(), locBlocks);
string fileName = Path.Combine(Application.persistentDataPath, "LocationBlockNames.json");
File.WriteAllText(fileName, locJson);
return "Location block names json written to " + fileName;
}
else if (args.Length == 1 && args[0] == "locindex")
{
string locIndex = "";
for (int region = 0; region < mapFileReader.RegionCount; region++)
{
DFRegion dfRegion = mapFileReader.GetRegion(region);
for (int location = 0; location < dfRegion.LocationCount; location++)
{
DFLocation dfLoc = mapFileReader.GetLocation(region, location);
locIndex += string.Format("{0}, {1}: {2}\n", region, dfLoc.LocationIndex, dfLoc.Name);
}
}
string fileName = Path.Combine(Application.persistentDataPath, "LocationIndex.txt");
File.WriteAllText(fileName, locIndex);
return "Location index written to " + fileName;
}
else
{
Dictionary<string, List<string>> regionLocs = new Dictionary<string, List<string>>();
for (int region = 0; region < mapFileReader.RegionCount; region++)
{
DFRegion dfRegion = mapFileReader.GetRegion(region);
if (string.IsNullOrEmpty(dfRegion.Name))
{
Debug.Log("region null: " + region);
continue;
}
List<string> locs;
if (regionLocs.ContainsKey(dfRegion.Name))
locs = regionLocs[dfRegion.Name];
else
{
locs = new List<string>();
regionLocs[dfRegion.Name] = locs;
}
for (int location = 0; location < dfRegion.LocationCount; location++)
{
DFLocation dfLoc = mapFileReader.GetLocation(region, location);
foreach (string blockName in dfLoc.Exterior.ExteriorData.BlockNames)
for (int i = 0; i < args.Length; i++)
if (blockName == args[i])
locs.Add(dfLoc.Name);
}
}
string locJson = SaveLoadManager.Serialize(regionLocs.GetType(), regionLocs);
string blocks = "";
for (int i = 0; i < args.Length; i++)
blocks = blocks + "-" + args[i];
string fileName = Path.Combine(Application.persistentDataPath, blocks.Substring(1) + "-locations.json");
File.WriteAllText(fileName, locJson);
return "Location block names json written to " + fileName;
}
}
}
private static class DumpBuilding
{
public static readonly string name = "dumpbuilding";
public static readonly string error = "Failed to dump building";
public static readonly string usage = "dumpbuilding";
public static readonly string description = "Dump the current building player is inside to json file";
public static string Execute(params string[] args)
{
DaggerfallInterior interior = GameManager.Instance.PlayerEnterExit.Interior;
int blockIndex = interior.EntryDoor.blockIndex;
int recordIndex = interior.EntryDoor.recordIndex;
DFBlock blockData = DaggerfallUnity.Instance.ContentReader.BlockFileReader.GetBlock(blockIndex);
if (blockData.Type == DFBlock.BlockTypes.Rmb)
{
string fileName = WorldDataReplacement.GetBuildingReplacementFilename(blockData.Name, blockIndex, recordIndex);
BuildingReplacementData buildingData = new BuildingReplacementData()
{
RmbSubRecord = blockData.RmbBlock.SubRecords[recordIndex],
BuildingType = (int)blockData.RmbBlock.FldHeader.BuildingDataList[recordIndex].BuildingType,
FactionId = blockData.RmbBlock.FldHeader.BuildingDataList[recordIndex].FactionId,
Quality = blockData.RmbBlock.FldHeader.BuildingDataList[recordIndex].Quality,
};
string buildingJson = SaveLoadManager.Serialize(buildingData.GetType(), buildingData);
File.WriteAllText(Path.Combine(Application.persistentDataPath, fileName), buildingJson);
return "Building data written to " + Path.Combine(Application.persistentDataPath, fileName);
}
return error;
}
}
private static class IngredientUsage
{
public static readonly string name = "ingredUsage";
public static readonly string description = "Log an analysis of potion recipe usage of ingredients";
public static readonly string usage = "ingredUsage";
public static string Execute(params string[] args)
{
if (args == null || args.Length > 0)
return usage;
GameManager.Instance.EntityEffectBroker.LogRecipeIngredientUsage();
return "Finished";
}
}
private static class GodCommand
{
public static readonly string name = "tgm";
public static readonly string error = "Failed to set God Mode - Player health object not found?";
public static readonly string usage = "tgm";
public static readonly string description = "Toggle god mode";
public static string Execute(params string[] args)
{
PlayerHealth playerHealth = GameManager.Instance.PlayerHealth;//GameObject.FindObjectOfType<PlayerHealth>();
if (playerHealth)
{
PlayerEntity playerEntity = GameManager.Instance.PlayerEntity;
playerEntity.GodMode = !playerEntity.GodMode;
return string.Format("Godmode enabled: {0}", playerEntity.GodMode);
}
else
return error;
}
}
private static class NoTargetCommand
{
public static readonly string name = "nt";
public static readonly string error = "Failed to set NoTarget mode";
public static readonly string usage = "nt";
public static readonly string description = "Toggle NoTarget mode";
public static string Execute(params string[] args)
{
PlayerEntity playerEntity = GameManager.Instance.PlayerEntity;
if (playerEntity != null)
{
playerEntity.NoTargetMode = !playerEntity.NoTargetMode;
return string.Format("NoTarget enabled: {0}", playerEntity.NoTargetMode);
}
else
return error;
}
}
private static class ToggleAICommand
{
public static readonly string name = "tai";
public static readonly string error = "Failed to toggle AI";
public static readonly string usage = "tai";
public static readonly string description = "Toggles AI on or off";
public static string Execute(params string[] args)
{
GameManager gameManager = GameManager.Instance;
if (gameManager != null)
{
gameManager.DisableAI = !gameManager.DisableAI;
return string.Format("AI disabled: {0}", gameManager.DisableAI);
}
else
return error;
}
}
private static class CreateMobileCommand
{
public static readonly string name = "cm";
public static readonly string error = "Failed to create mobile";
public static readonly string usage = "cm [n] [team]";
public static readonly string description = "Creates a mobile of type [n] on [team]. Omit team argument for default team.";
public static string Execute(params string[] args)
{
if (args.Length < 1) return "See usage.";
GameObject player = GameManager.Instance.PlayerObject;
if (player != null)
{
int id = 0;
if (!int.TryParse(args[0], out id))
return "Invalid mobile ID.";
if (!Enum.IsDefined(typeof(MobileTypes), id))
return "Invalid mobile ID.";
int team = 0;
if (args.Length > 1)
{
if (!int.TryParse(args[1], out team))
return "Invalid team.";
if (!Enum.IsDefined(typeof(MobileTeams), team))
return "Invalid team.";
}
GameObject[] mobile = GameObjectHelper.CreateFoeGameObjects(player.transform.position + player.transform.forward * 2, (MobileTypes)id, 1);
DaggerfallEntityBehaviour behaviour = mobile[0].GetComponent<DaggerfallEntityBehaviour>();
EnemyEntity entity = behaviour.Entity as EnemyEntity;
if (args.Length > 1)
{
entity.Team = (MobileTeams)team;
}
else
team = (int)entity.Team;
mobile[0].transform.LookAt(mobile[0].transform.position + (mobile[0].transform.position - player.transform.position));
mobile[0].SetActive(true);
return string.Format("Created {0} on team {1}", (MobileTypes)id, (MobileTeams)team);
}
else
return error;
}
}
private static class ShowDebugStrings
{
public static readonly string name = "tdbg";
public static readonly string error = "Failed to toggle debug string ";
public static readonly string description = "Toggles if the debug information is displayed";
public static readonly string usage = "tdbg";
public static string Execute(params string[] args)
{
DaggerfallWorkshop.StreamingWorld streamingWorld = GameManager.Instance.StreamingWorld;//GameObject.FindObjectOfType<DaggerfallWorkshop.StreamingWorld>();
DaggerfallWorkshop.DaggerfallUnity daggerfallUnity = DaggerfallUnity.Instance;
DaggerfallSongPlayer[] songPlayers = GameObject.FindObjectsOfType<DaggerfallSongPlayer>();
DefaultCommands.showDebugStrings = !DefaultCommands.showDebugStrings;
bool show = DefaultCommands.showDebugStrings;
if (streamingWorld)
streamingWorld.ShowDebugString = show;
if (daggerfallUnity)
daggerfallUnity.WorldTime.ShowDebugString = show;
foreach (DaggerfallSongPlayer songPlayer in songPlayers)
{
if (songPlayer && songPlayer.IsPlaying)
{
songPlayer.ShowDebugString = show;
break;
}
}
if (FPSDisplay.fpsDisplay == null)
GameManager.Instance.gameObject.AddComponent<FPSDisplay>();
FPSDisplay.fpsDisplay.ShowDebugString = show;
return string.Format("Debug string show: {0}", show);
}
}
private static class SetHealth
{
public static readonly string name = "set_health";
public static readonly string error = "Failed to set health - invalid setting or player object not found";
public static readonly string description = "Set Health";
public static readonly string usage = "set_Health [#]";
public static string Execute(params string[] args)
{
DaggerfallEntityBehaviour playerBehavior = GameManager.Instance.PlayerEntityBehaviour;
int health = 0;
if (args == null || args.Length < 1 || !int.TryParse(args[0], out health))
{
return HelpCommand.Execute(SetHealth.name);
}
else if (playerBehavior != null)
{
playerBehavior.Entity.SetHealth(health);
return string.Format("Set health to: {0}", playerBehavior.Entity.CurrentHealth);
}
else
return error;
}
}
private static class RerollMaxHealth
{
public static readonly string name = "reroll_maxhealth";
public static readonly string error = "";
public static readonly string description = @"Repair permanently reduced maximum health caused by a level-up bug in 0.10.3 and earlier. " +
@"This bug is resolved in 0.10.4 and later but some older save games might still need repair. " +
@"Note that new maximum health is set by forumla and may be slightly higher or lower than before bug.";
public static readonly string usage = "reroll_maxhealth";
public static string Execute(params string[] args)
{
DaggerfallEntityBehaviour playerBehavior = GameManager.Instance.PlayerEntityBehaviour;
int rerolledHealth = FormulaHelper.RollMaxHealth(GameManager.Instance.PlayerEntity);
GameManager.Instance.PlayerEntity.MaxHealth = rerolledHealth;
return string.Format("Your new maximum health is {0}", rerolledHealth);
}
}
private static class ResetAssets
{
public static readonly string name = "reset_assets";
public static readonly string error = "Could not reset assets";
public static readonly string description = "Clears mesh and material asset caches then reloads game. Warning: Uses QuickSave slot to reload game in-place. The in-place reload will trigger a longer than usual delay.";
public static readonly string usage = "reset_assets";
public static string Execute(params string[] args)
{
DaggerfallUnity.Instance.MeshReader.ClearCache();
DaggerfallUnity.Instance.MaterialReader.ClearCache();
SaveLoadManager.Instance.QuickSave(true);
return "Cleared cache and reloaded world.";
}
}
private static class RetryAssetImports
{
public static readonly string name = "retry_assets";
public static readonly string error = "Could not retry asset imports";
public static readonly string description = "Clears records of import attempts for assets from loose files and mods.";
public static readonly string usage = "retry_assets";
public static string Execute(params string[] args)
{
MeshReplacement.RetryAssetImports();
return "Cleared records of import attempts for assets from loose files and mods.";
}
}
private static class Suicide
{
public static readonly string name = "suicide";
public static readonly string error = "Failed to suicide :D";
public static readonly string description = "Kill self";
public static readonly string usage = "suicide";
public static string Execute(params string[] args)
{
DaggerfallEntityBehaviour playerBehavior = GameManager.Instance.PlayerEntityBehaviour;
if (playerBehavior == null)
return error;
else
{
playerBehavior.Entity.SetHealth(0);
return "Are you still there?";
}
}
}
private static class SetWeather
{
public static readonly string name = "set_weather";
public static readonly string description = "Sets the weather to indicated type";
public static readonly string usage = "set_weather [#] \n0 = Sunny \n1 = Cloudy \n2 = Overcast \n3 = Fog \n4 = Rain \n5 = Thunder \n6 = Snow";
public static string Execute(params string[] args)
{
WeatherManager weatherManager = GameManager.Instance.WeatherManager;
int weatherCode;
if (args == null || args.Length < 1)
return HelpCommand.Execute(SetWeather.name);
if (weatherManager == null)
return HelpCommand.Execute(SetWeather.name);
if (int.TryParse(args[0], out weatherCode) && weatherCode >= 0 && weatherCode <= 6)
{
var type = (WeatherType)weatherCode;
weatherManager.SetWeather(type);
return "Set weather: " + type.ToString();
}
return HelpCommand.Execute(SetWeather.name);
}
}
private static class SetWalkSpeed
{
public static readonly string name = "set_walkspeed";
public static readonly string error = "Failed to set walk speed - invalid setting or PlayerMotor object not found";
public static readonly string description = "Set walk speed. Set to -1 to return to default speed.";
public static readonly string usage = "set_walkspeed [#]";
public static string Execute(params string[] args)
{
int speed;
PlayerSpeedChanger speedChanger = GameManager.Instance.SpeedChanger;
if (speedChanger == null)
return error;
if (args == null || args.Length < 1)
{
try
{
Console.Log(string.Format("Current Walk Speed: {0}", speedChanger.GetWalkSpeed(GameManager.Instance.PlayerEntity)));
return HelpCommand.Execute(SetWalkSpeed.name);
}
catch
{
return HelpCommand.Execute(SetWalkSpeed.name);
}
}
else if (!int.TryParse(args[0], out speed))
return error;
else if (speed == -1)
{
speedChanger.useWalkSpeedOverride = false;
return string.Format("Walk speed set to default.");
}
else
{
speedChanger.useWalkSpeedOverride = true;
speedChanger.walkSpeedOverride = speed;
return string.Format("Walk speed set to: {0}", speed);
}
}
}
private static class SetRunSpeed
{
public static readonly string name = "set_runspeed";
public static readonly string error = "Failed to set run speed - invalid setting or PlayerMotor object not found";
public static readonly string description = "Set run speed. Set to -1 to return to default speed.";
public static readonly string usage = "set_runspeed [#]";
public static string Execute(params string[] args)
{
int speed;
PlayerSpeedChanger speedChanger = GameManager.Instance.SpeedChanger;//GameObject.FindObjectOfType<PlayerMotor>();
if (speedChanger == null)
return error;
if (args == null || args.Length < 1)
{
try
{
Console.Log(string.Format("Current RunSpeed: {0}", speedChanger.GetRunSpeed(speedChanger.GetWalkSpeed(GameManager.Instance.PlayerEntity))));
return HelpCommand.Execute(SetRunSpeed.name);
}
catch
{
return HelpCommand.Execute(SetRunSpeed.name);
}
}
else if (!int.TryParse(args[0], out speed))
{
return error;
}
else if (speed == -1)
{
speedChanger.useRunSpeedOverride = false;
return string.Format("Run speed set to default.");
}
else
{
speedChanger.runSpeedOverride = speed;
speedChanger.useRunSpeedOverride = true;
return string.Format("Run speed set to: {0}", speed);
}
}
}
private static class SetTimeScale
{
public static readonly string name = "set_timescale";
public static readonly string error = "Failed to set timescale - invalid setting or DaggerfallUnity singleton object";
public static readonly string description = "Set Timescale; Default 12. Setting it too high can have adverse affects";
public static readonly string usage = "set_timescale [#]";
public static string Execute(params string[] args)
{
int speed;
DaggerfallWorkshop.DaggerfallUnity daggerfallUnity = DaggerfallWorkshop.DaggerfallUnity.Instance;
if (daggerfallUnity == null)
return error;
if (args == null || args.Length < 1)
{
try
{
Console.Log(string.Format("Current TimeScale: {0}", DaggerfallWorkshop.DaggerfallUnity.Instance.WorldTime.TimeScale));
return HelpCommand.Execute(SetTimeScale.name);
}
catch
{
return HelpCommand.Execute(SetTimeScale.name);
}
}
else if (!int.TryParse(args[0], out speed))
return error;
else if (speed < 0)
return "Invalid time scale";
else
{
try
{
DaggerfallWorkshop.DaggerfallUnity.Instance.WorldTime.TimeScale = speed;
return string.Format("Time Scale set to: {0}", speed);
}
catch
{
return "Unspecified error; failed to set timescale";
}
}
}
}
private static class SetMouseSensitivity
{
public static readonly string name = "set_mspeed";
public static readonly string error = "Failed to set mouse sensitivity- invalid setting or PlayerMouseLook object not found";
public static readonly string description = "Set mouse sensitivity. Default is 1.5";
public static readonly string usage = "set_mspeed [#]";
public static string Execute(params string[] args)
{
PlayerMouseLook mLook = GameManager.Instance.PlayerMouseLook;//GameObject.FindObjectOfType<PlayerMouseLook>();
float speed = 0;
if (args == null || args.Length < 1 || !float.TryParse(args[0], out speed))
{
if (mLook)
Console.Log(string.Format("Current mouse sensitivity: {0}", mLook.sensitivity));
return HelpCommand.Execute(SetMouseSensitivity.name);
}
else if (mLook == null)
return error;
else
{
mLook.sensitivity = new Vector2(speed, speed);
return string.Format("Set mouse sensitivity to: {0}", mLook.sensitivity.ToString());
}
}
}
private static class ToggleMouseSmoothing
{
public static readonly string name = "tmsmooth";
public static readonly string error = "Failed to toggle mouse smoothing - PlayerMouseLook object not found?";
public static readonly string description = "Toggle mouse smoothing.";
public static readonly string usage = "tmsmooth";
public static string Execute(params string[] args)
{
PlayerMouseLook mLook = GameManager.Instance.PlayerMouseLook;//GameObject.FindObjectOfType<PlayerMouseLook>();
if (mLook == null)
return error;
else
{
//mLook.smoothing = new Vector2(speed, speed);
mLook.enableSmoothing = !mLook.enableSmoothing;
return string.Format("Mouse smoothing is on: {0}", mLook.enableSmoothing.ToString());
}
}
}
private static class SetMouseSmoothing
{
public static readonly string name = "set_msmooth";
public static readonly string error = "Failed to set mouse smoothing - invalid setting or PlayerMouseLook object not found";
public static readonly string description = "Set mouse smoothing. Default is 3";
public static readonly string usage = "set_msmooth [#]";
public static string Execute(params string[] args)
{
PlayerMouseLook mLook = GameManager.Instance.PlayerMouseLook;//GameObject.FindObjectOfType<PlayerMouseLook>();
float speed = 0;
if (args == null || args.Length < 1 || !float.TryParse(args[0], out speed))
{
if (mLook)
Console.Log(string.Format("Current mouse smoothing: {0}", mLook.smoothing));
return HelpCommand.Execute(SetMouseSmoothing.name);
}
else if (mLook == null)
return error;
else
{
mLook.smoothing = new Vector2(speed, speed);
return string.Format("Set mouse smoothing to: {0}", mLook.smoothing.ToString());
}
}
}
private static class SetVSync
{
public static readonly string name = "set_vsync";
public static readonly string error = "Failed to toggle vsync";
public static readonly string description = "Set Vertical Sync count. Must be 0, 1, 2;";
public static readonly string usage = "set_vsync";
public static string Execute(params string[] args)
{
int count = 0;
if (args == null || args.Count() < 1)
{
Console.Log(string.Format("Current VSync Count: {0}", UnityEngine.QualitySettings.vSyncCount));
return HelpCommand.Execute(SetVSync.name);
}
else if (!int.TryParse(args[0], out count))
{
Console.Log(string.Format("Current VSync Count: {0}", UnityEngine.QualitySettings.vSyncCount));
return HelpCommand.Execute(SetVSync.name);
}
else if (count == 0 || count == 1 || count == 2)
{
UnityEngine.QualitySettings.vSyncCount = count;
return string.Format("Set vSyncCount to: {0}", UnityEngine.QualitySettings.vSyncCount.ToString());
}
else
return error;
}
}
private static class SetGravity
{
public static readonly string name = "set_grav";
public static readonly string error = "Failed to set gravity - invalid setting or PlayerMotor object not found";
public static readonly string description = "Set gravity. Default is 20";
public static readonly string usage = "set_grav [#]";
public static string Execute(params string[] args)
{
int gravity = 0;
AcrobatMotor acrobatMotor = GameManager.Instance.AcrobatMotor;
if (acrobatMotor == null)
return error;
if (args == null || args.Length < 1)
{
try
{
Console.Log(string.Format("Current gravity: {0}", acrobatMotor.gravity));
return HelpCommand.Execute(SetGravity.name);
}
catch
{
return HelpCommand.Execute(SetGravity.name);
}
}
else if (!int.TryParse(args[0], out gravity))
return error;
else
{
acrobatMotor.gravity = gravity;
return string.Format("Gravity set to: {0}", acrobatMotor.gravity);
}
}
}
private static class SetJumpSpeed
{
public static readonly string name = "set_jump";
public static readonly string error = "Failed to set jump speed - invalid setting or PlayerMotor object not found";
public static readonly string description = "Set jump speed. Default is 8";
public static readonly string usage = "set_jump [#]";
public static string Execute(params string[] args)
{
int speed;
AcrobatMotor acrobatMotor = GameManager.Instance.AcrobatMotor;
if (acrobatMotor == null)
{
return error;
}
if (args == null || args.Length < 1)
{
try
{
Console.Log(string.Format("Current Jump Speed: {0}", acrobatMotor.jumpSpeed));
return HelpCommand.Execute(SetJumpSpeed.name);
}
catch
{
return HelpCommand.Execute(SetJumpSpeed.name);
}
}
else if (!int.TryParse(args[0], out speed))
return error;
else
{
acrobatMotor.jumpSpeed = speed;
return string.Format("Jump speed set to: {0}", acrobatMotor.jumpSpeed);
}
}
}
private static class ToggleAirControl
{
public static readonly string name = "tac";
public static readonly string error = "Failed to toggle air control - PlayerMotor object not found?";
public static readonly string description = "Toggle air control, which allows player to move while in the air.";
public static readonly string usage = "tac";
public static string Execute(params string[] args)
{
AcrobatMotor acrobatMotor = GameManager.Instance.AcrobatMotor;
if (acrobatMotor == null)
return error;
else
{
acrobatMotor.airControl = !acrobatMotor.airControl;
return string.Format("air control set to: {0}", acrobatMotor.airControl);
}
}
}
private static class TeleportToMapPixel
{
public static readonly string name = "tele2pixel";
public static readonly string description = "Send the player to the x,y coordinates";
public static readonly string usage = "tele2pixel [x y]; where x is between 0 & 1000 and y is between 0 & 500";
public static string Execute(params string[] args)
{
int x = 0; int y = 0;
DaggerfallWorkshop.StreamingWorld streamingWorld = GameManager.Instance.StreamingWorld;//GameObject.FindObjectOfType<DaggerfallWorkshop.StreamingWorld>();
PlayerEnterExit playerEE = GameManager.Instance.PlayerEnterExit;//GameObject.FindObjectOfType<PlayerEnterExit>();
if (args == null || args.Length < 2)
return HelpCommand.Execute(TeleportToMapPixel.name);
else if (streamingWorld == null)
return "Could not locate Streaming world object";
else if (playerEE == null || playerEE.IsPlayerInside)
return "PlayerEnterExit could not be found or player inside";
else if (int.TryParse(args[0], out x) && int.TryParse(args[1], out y))
{
if (x <= 0 || y <= 0)
return "Invalid Coordinates";
else if (x >= MapsFile.MaxMapPixelX || y >= MapsFile.MaxMapPixelY)
return "Invalid coordiantes";
else
streamingWorld.TeleportToCoordinates(x, y);
return string.Format("Teleporting player to: {0} {1}", x, y);
}
return "Invalid coordiantes";
}
}
private static class GotoLocation
{
public static readonly string name = "location";
public static readonly string description = "Send the player to the predefined location";
public static readonly string usage = "location [n]; where n is between 0 & 9:\n0 ... random location\n1 ... Daggerfall/Daggerfall\n2 ... Wayrest/Wayrest\n3 ... Sentinel/Sentinel\n4 ... Orsinium Area/Orsinium\n5 ... Tulune/The Old Copperham Place\n6 ... Pothago/The Stronghold of Cirden\n7 ... Daggerfall/Privateer's Hold\n8 ... Wayrest/Merwark Hollow\n9 ... Isle of Balfiera/Direnni Tower\n";
public static string Execute(params string[] args)
{
int n = 0;
DaggerfallWorkshop.StreamingWorld streamingWorld = GameManager.Instance.StreamingWorld;//GameObject.FindObjectOfType<DaggerfallWorkshop.StreamingWorld>();
PlayerEnterExit playerEE = GameManager.Instance.PlayerEnterExit;//GameObject.FindObjectOfType<PlayerEnterExit>();
if (args == null || args.Length < 1)
return HelpCommand.Execute(GotoLocation.name);
else if (streamingWorld == null)
return "Could not locate Streaming world object";
else if (playerEE == null || playerEE.IsPlayerInside)
return "PlayerEnterExit could not be found or player inside";
else if (int.TryParse(args[0], out n))
{
if (n < 0 || n > 9)
return "Invalid location index";
else
{
switch (n)
{
case 0:
int xpos, ypos;
while (true)
{
xpos = UnityEngine.Random.Range(0, MapsFile.MaxMapPixelX);
ypos = UnityEngine.Random.Range(0, MapsFile.MaxMapPixelY);
DaggerfallWorkshop.Utility.ContentReader.MapSummary mapSummary;
if (DaggerfallWorkshop.DaggerfallUnity.Instance.ContentReader.HasLocation(xpos, ypos, out mapSummary))
{
streamingWorld.TeleportToCoordinates(xpos + 1, ypos - 1); // random location - locations always seem to be one pixel to the northern east - so compensate for this (since locations are never at the border - there should not occur a index out of bounds...)
return (string.Format("Teleported player to location at: {0}, {1}", xpos, ypos));
}
}
case 1:
streamingWorld.TeleportToCoordinates(207, 213, StreamingWorld.RepositionMethods.RandomStartMarker);
return ("Teleported player to Daggerfall/Daggerfall");
case 2:
streamingWorld.TeleportToCoordinates(859, 244, StreamingWorld.RepositionMethods.RandomStartMarker);
return ("Teleported player to Wayrest/Wayrest");
case 3:
streamingWorld.TeleportToCoordinates(397, 343, StreamingWorld.RepositionMethods.RandomStartMarker);
return ("Teleported player to Sentinel/Sentinel");
case 4:
streamingWorld.TeleportToCoordinates(892, 146, StreamingWorld.RepositionMethods.RandomStartMarker);
return ("Teleported player to Orsinium Area/Orsinium");
case 5:
streamingWorld.TeleportToCoordinates(67, 119, StreamingWorld.RepositionMethods.RandomStartMarker);
return ("Teleported player to Tulune/The Old Copperham Place");
case 6:
streamingWorld.TeleportToCoordinates(254, 408, StreamingWorld.RepositionMethods.RandomStartMarker);
return ("Teleported player to Pothago/The Stronghold of Cirden");
case 7:
streamingWorld.TeleportToCoordinates(109, 158, StreamingWorld.RepositionMethods.RandomStartMarker);
return ("Teleported player to Daggerfall/Privateer's Hold");
case 8:
streamingWorld.TeleportToCoordinates(860, 245, StreamingWorld.RepositionMethods.RandomStartMarker);
return ("Teleported player to Wayrest/Merwark Hollow");
case 9:
streamingWorld.TeleportToCoordinates(718, 204, StreamingWorld.RepositionMethods.RandomStartMarker);
return ("Teleported player to Isle of Balfiera/Direnni Tower");
default:
break;
}
return "Teleported successfully.";
}
}
return "Invalid location index";
}
}
private static class TransitionToExterior
{
public static readonly string name = "trans_out";
public static readonly string error = "Player not inside, or couldn't locate PlayerEnterExit";
public static readonly string description = "Leave dungeon or building and load exterior area, only works if player inside";
public static readonly string usage = "trans_out";
public static string Execute(params string[] args)
{
PlayerEnterExit playerEnterExit = GameManager.Instance.PlayerEnterExit;//GameObject.FindObjectOfType<PlayerEnterExit>();
if (playerEnterExit == null || !playerEnterExit.IsPlayerInside)
{
Console.Log(HelpCommand.Execute(TransitionToExterior.name));
return error;
}
else
{
try
{
if (playerEnterExit.IsPlayerInsideDungeon)
{
playerEnterExit.TransitionDungeonExterior();
}
else
{
playerEnterExit.TransitionExterior();
}
return "Transitioning to exterior";
}
catch
{
return "Error on transitioning";
}
}
}
}
private static class TeleportToDungeonDoor
{
public static readonly string name = "tele2exit";
public static readonly string error = "Player not inside dungeon, or couldn't locate player";
public static readonly string description = "Teleport player to dungeon exit without leaving";
public static readonly string usage = "tele2exit";
public static string Execute(params string[] args)
{
PlayerEnterExit playerEnterExit = GameManager.Instance.PlayerEnterExit;//GameObject.FindObjectOfType<PlayerEnterExit>();
GameObject playerObj = GameManager.Instance.PlayerObject;//GameObject.FindGameObjectWithTag("Player") as GameObject;
if (playerObj == null || playerEnterExit == null || !playerEnterExit.IsPlayerInsideDungeon)
{
return error;
}
else
{
try
{
// Teleport to StartMarker at dungeon entrance
playerObj.transform.position = playerEnterExit.Dungeon.StartMarker.transform.position;
return "Transitioning to door position";
}
catch
{
return "Unspecified Error";
}
}
}
}
private static class TeleportToQuestMarker
{
public static readonly string name = "tele2qmarker";
public static readonly string error = "Could not find quest marker at current location";
public static readonly string description = "Teleport player to active quest marker (monster, NPC placement, item, etc.)";
public static readonly string usage = "tele2qmarker";
public static string Execute(params string[] args)
{
QuestMarker spawnMarker;
Vector3 buildingOrigin;
bool result = QuestMachine.Instance.GetCurrentLocationQuestMarker(out spawnMarker, out buildingOrigin);
if (!result)
return error;
if (spawnMarker.targetResources == null || spawnMarker.targetResources.Count == 0)
return error;
if (GameManager.Instance.PlayerEnterExit.IsPlayerInsideDungeon)
{
Vector3 dungeonBlockPosition = new Vector3(spawnMarker.dungeonX * RDBLayout.RDBSide, 0, spawnMarker.dungeonZ * RDBLayout.RDBSide);
GameManager.Instance.PlayerObject.transform.localPosition = dungeonBlockPosition + spawnMarker.flatPosition;
}
else if (GameManager.Instance.PlayerEnterExit.IsPlayerInsideBuilding)
{
// Find active marker type - saves on applying building matrix, etc. to derive position again
Vector3 markerPos;
if (GameManager.Instance.PlayerEnterExit.Interior.FindClosestMarker(
out markerPos,
(DaggerfallInterior.InteriorMarkerTypes)spawnMarker.markerType,
GameManager.Instance.PlayerObject.transform.position))
{
GameManager.Instance.PlayerObject.transform.position = markerPos;
}
}
else
{
return error;
}
GameManager.Instance.PlayerMotor.FixStanding();
return "Finished";
}
}
private static class TeleportToQuestSpawnMarker
{
public static readonly string name = "tele2qspawn";
public static readonly string error = "Could not find quest spawn marker at current location";
public static readonly string description = "Teleport player to quest spawn marker (monster, NPC placement)";
public static readonly string usage = "tele2qspawn";
public static string Execute(params string[] args)
{
return TeleportToQuestMarker.Execute() + "...tele2qspawn is deprecated - please use tele2qmarker";
}
}
private static class TeleportToQuestItemMarker
{
public static readonly string name = "tele2qitem";
public static readonly string error = "Could not find quest item marker at current location";
public static readonly string description = "Teleport player to quest item marker";
public static readonly string usage = "tele2qitem";
public static string Execute(params string[] args)
{
return TeleportToQuestMarker.Execute() + "...tele2qitem is deprecated - please use tele2qmarker";
}
}
private static class GetAllQuestItems
{
public static readonly string name = "getallquestitems";
public static readonly string error = "Could not find any active quests with Item resources.";
public static readonly string description = "Immediately give player a copy of any items referenced by active quests (including rewards). This can break quest execution flow.";
public static readonly string usage = "getallquestitems";
public static string Execute(params string[] args)
{
int itemsFound = 0;
ulong[] uids = QuestMachine.Instance.GetAllActiveQuests();
foreach (ulong questUID in uids)
{
Quest quest = QuestMachine.Instance.GetQuest(questUID);
if (quest != null)
{
QuestResource[] itemResources = quest.GetAllResources(typeof(Item));
foreach (Item item in itemResources)
{
GameManager.Instance.PlayerEntity.Items.AddItem(item.DaggerfallUnityItem, ItemCollection.AddPosition.Front);
itemsFound++;
}
}
}
if (itemsFound > 0)
return string.Format("Transferred {0} items into player inventory", itemsFound);
else
return error;
}
}
private static class EndQuest
{
public static readonly string name = "endquest";
public static readonly string error = "Could not find quest.";
public static readonly string description = "Tombstone quest. Does not issue reward.";
public static readonly string usage = "endquest <questUID>";
public static string Execute(params string[] args)
{
if (QuestMachine.Instance.QuestCount == 0)
return "No quests are running";
if (args == null || args.Length != 1)
return HelpCommand.Execute(EndQuest.name);
int questUID;
if (!int.TryParse(args[0], out questUID))
return HelpCommand.Execute(EndQuest.name);
Quest quest = QuestMachine.Instance.GetQuest((ulong)questUID);
if (quest == null)
return string.Format("Could not find quest {0}", questUID);
if (quest.QuestTombstoned)
return "Quest is already tombstoned";
QuestMachine.Instance.TombstoneQuest(quest);
return string.Format("Tombstoned quest {0}", questUID);
}
}
private static class EndDebugQuest
{
public static readonly string name = "enddebugquest";
public static readonly string error = "Could not find debug quest.";
public static readonly string description = "Tombstone quest currently shown by HUD quest debugger (if any). Does not issue reward.";
public static readonly string usage = "enddebugquest";
public static string Execute(params string[] args)
{
if (DaggerfallUI.Instance.DaggerfallHUD.QuestDebugger.State == HUDQuestDebugger.DisplayState.Nothing)
return "Quest debugger is not open.";
Quest currentQuest = DaggerfallUI.Instance.DaggerfallHUD.QuestDebugger.CurrentQuest;
if (currentQuest == null)
return "Quest debugger has no quest selected";
if (currentQuest.QuestTombstoned)
return "Quest is already tombstoned";
// Disallow ending main quest backbone
if (QuestMachine.IsProtectedQuest(currentQuest))
{
return "Cannot end main quest backbone with 'enddebugquest'. Use 'clearmqstate' instead. Not this will clear ALL quests and ALL global variables.";
}
QuestMachine.Instance.TombstoneQuest(currentQuest);
return string.Format("Tombstoned quest {0}", currentQuest.UID);
}
}
private static class PurgeAllQuests
{
public static readonly string name = "purgeallquests";
public static readonly string error = "Could not find any quests.";
public static readonly string description = "Immediately tombstones all quests then removes from quest machine. Does not issue rewards.";
public static readonly string usage = "purgeallquests";
public static string Execute(params string[] args)
{
if (QuestMachine.Instance.QuestCount == 0)
return error;
int count = QuestMachine.Instance.PurgeAllQuests();
return string.Format("Removed {0} quests.", count);
}
}
private static class ModNPCRep
{
public static readonly string name = "modnpcrep";
public static readonly string error = "You must click an NPC before modifying your reputation with them.";
public static readonly string description = "Modify reputation with last NPC clicked by a positive or negative amount. Clamped at -100 through 100.";
public static readonly string usage = "modnpcrep <amount>";
public static string Execute(params string[] args)
{
if (args == null || args.Length != 1)
return HelpCommand.Execute(ModNPCRep.name);
int amount;
if (!int.TryParse(args[0], out amount))
return HelpCommand.Execute(ModNPCRep.name);
// Get faction data of last NPC clicked
StaticNPC npc = QuestMachine.Instance.LastNPCClicked;
if (npc == null)
return error;
if (GameManager.Instance.PlayerEntity.FactionData.ChangeReputation(npc.Data.factionID, amount))
{
return string.Format("Changed NPC rep for {0} by {1}", npc.DisplayName, amount);
}
return "Could not raise rep - unknown error.";
}
}
private static class SetLevel
{
public static readonly string name = "setlevel";
public static readonly string error = "Could not set player level.";
public static readonly string description = "Change player level to a value from 1 to 30. Does not allow player to distribute points, only changes level value.";
public static readonly string usage = "setlevel <level>";
public static string Execute(params string[] args)
{
if (args == null || args.Length != 1)
return HelpCommand.Execute(SetLevel.name);
int level;
if (!int.TryParse(args[0], out level))
return HelpCommand.Execute(SetLevel.name);
GameManager.Instance.PlayerEntity.Level = Mathf.Clamp(level, 1, 30);
return "Finished";
}
}
private static class Levitate
{
public static readonly string name = "levitate";
public static readonly string error = "Could not start levitating.";
public static readonly string description = "Start or stop levitating.";
public static readonly string usage = "levitate on|off";
public static string Execute(params string[] args)
{
if (args == null || args.Length != 1)
return HelpCommand.Execute(name);
LevitateMotor levitateMotor = GameManager.Instance.PlayerMotor.GetComponent<LevitateMotor>();
if (!levitateMotor)
return "Could not find LevitateMotor component peered with PlayerMotor.";
string state = args[0];
if (string.Compare(state, "on", true) == 0)
{
levitateMotor.IsLevitating = true;
return "Player is now levitating";
}
else if (string.Compare(state, "off", true) == 0)
{
levitateMotor.IsLevitating = false;
return "Player is no longer levitating";
}
return HelpCommand.Execute(name);
}
}
private static class OpenAllDoors
{
public static readonly string name = "openalldoors";
public static readonly string error = "You are not inside";
public static readonly string description = "Opens all doors in an interior or dungeon, regardless of locked state";
public static readonly string usage = "openalldoors";
public static string Execute(params string[] args)
{
if (!GameManager.Instance.IsPlayerInside)
return error;
else
{
DaggerfallActionDoor[] doors = GameObject.FindObjectsOfType<DaggerfallActionDoor>();
int count = 0;
for (int i = 0; i < doors.Length; i++)
{
if (!doors[i].IsOpen)
{
doors[i].SetOpen(true, false, true);
count++;
}
}
return string.Format("Finished. Opened {0} doors out of {1}", count, doors.Count());
}
}
}
private static class OpenDoor
{
public static readonly string name = "opendoor";
public static readonly string error = "No door type object found";
public static readonly string description = "Opens a single door the player is looking at, regardless of locked state";
public static readonly string usage = "opendoor";
public static string Execute(params string[] args)
{
if (!GameManager.Instance.IsPlayerInside)
return "You are not inside";
else
{
DaggerfallActionDoor door;
RaycastHit hitInfo;
Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
if (!(Physics.Raycast(ray, out hitInfo)))
return error;
else
{
door = hitInfo.transform.GetComponent<DaggerfallActionDoor>();
if (door == null)
return error;
else
door.SetOpen(true, false, true);
}
return string.Format("Finished");
}
}
}
private static class ActivateAction
{
public static readonly string name = "activate";
public static readonly string error = "No action object found";
public static readonly string description = "Triggers an action object regardless of whether it is able to be activated normally";
public static readonly string usage = "activate";
public static string Execute(params string[] args)
{
DaggerfallAction action;
RaycastHit hitInfo;
Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
if (!(Physics.Raycast(ray, out hitInfo)))
return error;
else
{
action = hitInfo.transform.GetComponent<DaggerfallAction>();
if (action == null)
return error;
else
action.Play(GameManager.Instance.PlayerObject);
}
return string.Format("Finished");
}
}
private static class KillAllEnemies
{
public static readonly string name = "killall";
public static readonly string description = "Kills any enemies currently in scene";
public static readonly string usage = "killall";
public static string Execute(params string[] args)
{
DaggerfallEntityBehaviour[] entityBehaviours = FindObjectsOfType<DaggerfallEntityBehaviour>();
int count = 0;
for (int i = 0; i < entityBehaviours.Length; i++)
{
DaggerfallEntityBehaviour entityBehaviour = entityBehaviours[i];
if (entityBehaviour.EntityType == EntityTypes.EnemyMonster || entityBehaviour.EntityType == EntityTypes.EnemyClass)
{
entityBehaviour.Entity.SetHealth(0);
count++;
}
}
return string.Format("Finished. Killed: {0} enemies.", count);
}
}
private static class GetLocationMapPixel
{
public static readonly string name = "getlocpixel";
public static readonly string description = "get pixel coordinates for a location";
public static readonly string usage = "getlocpixel <region name>/<location name> (no space between region name & location name)";
public static string Execute(params string[] args)
{
if (args == null || args.Count() < 1)
{
return string.Format("Invalid paramaters; \n {0}", usage);
}
DaggerfallConnect.DFLocation loc;
string name = args[0];
for (int i = 1; i < args.Count(); i++)
{
name += " " + args[i];
}
if (DaggerfallWorkshop.Utility.GameObjectHelper.FindMultiNameLocation(name, out loc))
{
DaggerfallConnect.Utility.DFPosition pos = MapsFile.LongitudeLatitudeToMapPixel((int)loc.MapTableData.Longitude, (int)loc.MapTableData.Latitude);
return string.Format("{0} found; Pixel Coordinates: \nx: {1} y: {2}", name, pos.X, pos.Y);
}
else
{
return "Invalid location. Check spelling?";
}
}
}
/// <summary>
/// Short distance teleport, uses raycast to move player to where they are looking
/// </summary>
private static class Teleport
{
public static readonly string name = "teleport";
public static readonly string description = "teleport player to object they are looking at. God mode recommended";
public static readonly string usage = "teleport \noptional paramaters: \n{true/false} always teleport if true, even if looking at empty space (default false) \n{max distance}" +
"max distance to teleport (default 500) \n{up/down/left/right} final position adjustment (default up) \n Examples:\nteleport \n teleport up \n teleport 999 left true";
public static string Execute(params string[] args)
{
bool forceTeleOnNoHit = false; //teleport maxDistance even if raycast doesn't hit
float maxDistance = 500; //max distance
int step = 0;
Vector3 dir = Camera.main.transform.up;
Vector3 loc;
if (args != null)
{
for (int i = 0; i < args.Length; i++)
{
float temp = 0;
if (string.IsNullOrEmpty(args[i]))
continue;
else if (args[i] == "true" || args[i] == "false")
Boolean.TryParse(args[i], out forceTeleOnNoHit);
else if (float.TryParse(args[i], out temp))
maxDistance = temp;
else if (args[i].ToLower() == "up")
dir = Camera.main.transform.up;
else if (args[i].ToLower() == "down")
dir = Camera.main.transform.up * -1;
else if (args[i].ToLower() == "right")
dir = Camera.main.transform.right;
else if (args[i].ToLower() == "left")
dir = Camera.main.transform.right * -1;
else if (args[i].ToLower() == "forward")
dir = Camera.main.transform.forward;
else if (args[i].ToLower() == "back")
dir = Camera.main.transform.forward * -1;
}
}
RaycastHit hitInfo;
Vector3 origin = Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0));
Ray ray = new Ray(origin + Camera.main.transform.forward * .2f, Camera.main.transform.forward);
GameManager.Instance.AcrobatMotor.ClearFallingDamage();
if (!(Physics.Raycast(ray, out hitInfo, maxDistance)))
{
Console.Log("Didn't hit anything...");
if (forceTeleOnNoHit)
{
GameManager.Instance.PlayerObject.transform.position = ray.GetPoint(maxDistance);
Console.Log("...teleporting anyways");
}
}
else
{
loc = hitInfo.point;
while (Physics.CheckCapsule(loc, loc + dir, GameManager.Instance.PlayerController.radius + .1f) && step < 50)
{
loc = dir + loc;
step++;
}
GameManager.Instance.PlayerObject.transform.position = loc;
}
return "Finished";
}
}
private static class AddInventoryItem
{
public static readonly string name = "add";
public static readonly string description = "Adds n inventory items to the character, based on the given keyword. n = 1 by default";
public static readonly string usage = "add (book|weapon|armor|cloth|ingr|relig|soul|gold|magic|drug|map|torch) [n]";
public static string Execute(params string[] args)
{
if (args.Length < 1)
return usage;
GameObject player = GameObject.FindGameObjectWithTag("Player");
PlayerEntity playerEntity = player.GetComponent<DaggerfallEntityBehaviour>().Entity as PlayerEntity;
ItemCollection items = playerEntity.Items;
DaggerfallUnityItem newItem = null;
int n = 1;
if (args.Length >= 2)
{
Int32.TryParse(args[1], out n);
}
if (n < 1)
return usage;
if (args[0] == "gold")
{
playerEntity.GoldPieces += n;
return string.Format("Added {0} gold pieces", n);
}
UnityEngine.Random.InitState(Time.frameCount);
while (n >= 1)
{
n--;
switch (args[0])
{
case "book":
newItem = ItemBuilder.CreateRandomBook();
break;
case "weapon":
newItem = ItemBuilder.CreateRandomWeapon(playerEntity.Level);
break;
case "armor":
newItem = ItemBuilder.CreateRandomArmor(playerEntity.Level, playerEntity.Gender, playerEntity.Race);
break;
case "cloth":
newItem = ItemBuilder.CreateRandomClothing(playerEntity.Gender, playerEntity.Race);
break;
case "ingr":
newItem = ItemBuilder.CreateRandomIngredient();
break;
case "relig":
newItem = ItemBuilder.CreateRandomReligiousItem();
break;
case "soul":
newItem = ItemBuilder.CreateRandomlyFilledSoulTrap();
break;
case "magic":
newItem = ItemBuilder.CreateRandomMagicItem(playerEntity.Level, playerEntity.Gender, playerEntity.Race);
break;
case "drug":
newItem = ItemBuilder.CreateRandomDrug();
break;
case "map":
newItem = ItemBuilder.CreateItem(ItemGroups.MiscItems, (int)MiscItems.Map);
break;
case "torch":
newItem = ItemBuilder.CreateItem(ItemGroups.UselessItems2, (int)UselessItems2.Torch);
break;
case "soultrap":
newItem = ItemBuilder.CreateItem(ItemGroups.MiscItems, (int)MiscItems.Soul_trap);
break;
default:
return "unrecognized keyword. see usage";
}
items.AddItem(newItem);
}
return "success";
}
private static T RandomEnumValue<T>()
{
var v = Enum.GetValues(typeof(T));
return (T)v.GetValue(UnityEngine.Random.Range(0, v.Length));
}
}
private static class AddArtifact
{
public static readonly string name = "addArtifact";
public static readonly string description = "Adds an artifact of ID n to the character";
public static readonly string usage = "addArtifact [n]";
public static string Execute(params string[] args)
{
if (args.Length < 1) return "See usage.";
GameObject player = GameObject.FindGameObjectWithTag("Player");
PlayerEntity playerEntity = player.GetComponent<DaggerfallEntityBehaviour>().Entity as PlayerEntity;
ItemCollection items = playerEntity.Items;
DaggerfallUnityItem newItem = null;
switch (args[0])
{
case "0":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Masque_of_Clavicus);
break;
case "1":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Mehrunes_Razor);
break;
case "2":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Mace_of_Molag_Bal);
break;
case "3":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Hircine_Ring);
break;
case "4":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Sanguine_Rose);
break;
case "5":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Oghma_Infinium);
break;
case "6":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Wabbajack);
break;
case "7":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Ring_of_Namira);
break;
case "8":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Skull_of_Corruption);
break;
case "9":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Azuras_Star);
break;
case "10":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Volendrung);
break;
case "11":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Warlocks_Ring);
break;
case "12":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Auriels_Bow);
break;
case "13":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Necromancers_Amulet);
break;
case "14":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Chrysamere);
break;
case "15":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Lords_Mail);
break;
case "16":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Staff_of_Magnus);
break;
case "17":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Ring_of_Khajiit);
break;
case "18":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Ebony_Mail);
break;
case "19":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Auriels_Shield);
break;
case "20":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Spell_Breaker);
break;
case "21":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Skeletons_Key);
break;
case "22":
newItem = ItemBuilder.CreateItem(ItemGroups.Artifacts, (int)ArtifactsSubTypes.Ebony_Blade);
break;
default:
return "Invalid artifact ID.";
}
items.AddItem(newItem);
return "Success";
}
}
private class AddItemHelper
{
readonly Queue<string> args;
private AddItemHelper(string[] args)
{
this.args = new Queue<string>(args);
}
public T Parse<T>()
{
return (T)Enum.Parse(typeof(T), args.Dequeue());
}
public static string Execute(string[] args, Func<AddItemHelper, DaggerfallUnityItem> getItem)
{
try
{
DaggerfallUnityItem item = getItem(new AddItemHelper(args));
GameManager.Instance.PlayerEntity.Items.AddItem(item);
return string.Format("Added {0} to inventory.", item.ItemName);
}
catch (Exception e)
{
return e.Message;
}
}
}
private static class AddWeapon
{
public static readonly string name = "add_weapon";
public static readonly string description = "Adds a weapon to inventory.";
public static readonly string usage = "add_weapon {Weapons} {WeaponMaterialTypes}";
public static string Execute(params string[] args)
{
return args.Length == 2 ?
AddItemHelper.Execute(args, x => ItemBuilder.CreateWeapon(x.Parse<Weapons>(), x.Parse<WeaponMaterialTypes>())) :
usage;
}
}
private static class AddArmor
{
public static readonly string name = "add_armor";
public static readonly string description = "Adds an armor to inventory.";
public static readonly string usage = "add_armor {Genders} {Races} {Armor} {ArmorMaterialTypes}";
public static string Execute(params string[] args)
{
return args.Length == 4 ?
AddItemHelper.Execute(args, x => ItemBuilder.CreateArmor(x.Parse<Genders>(), x.Parse<Races>(), x.Parse<Armor>(), x.Parse<ArmorMaterialTypes>())) :
usage;
}
}
private static class AddClothing
{
public static readonly string name = "add_clothing";
public static readonly string description = "Adds clothing to inventory.";
public static readonly string usage = "add_clothing {Genders} {MensClothing|WomensClothing} {Races} {DyeColors}";
public static string Execute(params string[] args)
{
if (args.Length != 4)
return usage;
return AddItemHelper.Execute(args, x => x.Parse<Genders>() == Genders.Male ?
ItemBuilder.CreateMensClothing(x.Parse<MensClothing>(), x.Parse<Races>(), -1, x.Parse<DyeColors>()) :
ItemBuilder.CreateWomensClothing(x.Parse<WomensClothing>(), x.Parse<Races>(), -1, x.Parse<DyeColors>())
);
}
}
private static class AddAllEquip
{
public static readonly string name = "add_all_equip";
public static readonly string description = "Adds all equippable item types to inventory for the current characters gender & race. (for testing paperdoll images)";
public static readonly string usage = "add_all_equip (clothing|clothingAllDyes|armor|weapons)";
public static ArmorMaterialTypes[] armorMaterials = {
ArmorMaterialTypes.Leather, ArmorMaterialTypes.Chain, ArmorMaterialTypes.Iron, ArmorMaterialTypes.Steel,
ArmorMaterialTypes.Silver, ArmorMaterialTypes.Elven, ArmorMaterialTypes.Dwarven, ArmorMaterialTypes.Mithril,
ArmorMaterialTypes.Adamantium, ArmorMaterialTypes.Ebony, ArmorMaterialTypes.Orcish, ArmorMaterialTypes.Daedric
};
public static WeaponMaterialTypes[] weaponMaterials = {
WeaponMaterialTypes.Iron, WeaponMaterialTypes.Steel, WeaponMaterialTypes.Silver, WeaponMaterialTypes.Elven,
WeaponMaterialTypes.Dwarven, WeaponMaterialTypes.Mithril, WeaponMaterialTypes.Adamantium, WeaponMaterialTypes.Ebony,
WeaponMaterialTypes.Orcish, WeaponMaterialTypes.Daedric
};
public static List<MensClothing> mensUsableClothing = new List<MensClothing>() {
MensClothing.Casual_cloak, MensClothing.Formal_cloak, MensClothing.Reversible_tunic, MensClothing.Plain_robes,
MensClothing.Short_shirt, MensClothing.Short_shirt_with_belt, MensClothing.Long_shirt, MensClothing.Long_shirt_with_belt,
MensClothing.Short_shirt_closed_top, MensClothing.Short_shirt_closed_top2, MensClothing.Long_shirt_closed_top, MensClothing.Long_shirt_closed_top2
};
public static List<WomensClothing> womensUsableClothing = new List<WomensClothing>() {
WomensClothing.Casual_cloak, WomensClothing.Formal_cloak, WomensClothing.Strapless_dress, WomensClothing.Plain_robes,
WomensClothing.Short_shirt, WomensClothing.Short_shirt_belt, WomensClothing.Long_shirt, WomensClothing.Long_shirt_belt,
WomensClothing.Short_shirt_closed, WomensClothing.Short_shirt_closed_belt, WomensClothing.Long_shirt_closed, WomensClothing.Long_shirt_closed_belt
};
public static string Execute(params string[] args)
{
if (args.Length != 1)
return usage;
PlayerEntity playerEntity = GameManager.Instance.PlayerEntity;
ItemCollection items = playerEntity.Items;
DaggerfallUnityItem newItem = null;
switch (args[0])
{
case "clothing":
case "clothingAllDyes":
DyeColors[] clothingDyes = (args[0] == "clothing") ? new DyeColors[] { DyeColors.White } : ItemBuilder.clothingDyes;
ItemGroups clothing = (playerEntity.Gender == Genders.Male) ? ItemGroups.MensClothing : ItemGroups.WomensClothing;
foreach (DyeColors dye in clothingDyes)
{
Array enumArray = DaggerfallUnity.Instance.ItemHelper.GetEnumArray(clothing);
for (int i = 0; i < enumArray.Length; i++)
{
ItemTemplate itemTemplate = DaggerfallUnity.Instance.ItemHelper.GetItemTemplate(clothing, i);
if ((playerEntity.Gender == Genders.Male && mensUsableClothing.Contains((MensClothing)enumArray.GetValue(i))) ||
womensUsableClothing.Contains((WomensClothing)enumArray.GetValue(i)))
itemTemplate.variants = 1;
for (int v = 0; v < itemTemplate.variants; v++)
{
newItem = new DaggerfallUnityItem(clothing, i);
ItemBuilder.SetRace(newItem, playerEntity.Race);
newItem.dyeColor = dye;
newItem.CurrentVariant = v;
playerEntity.Items.AddItem(newItem);
}
}
}
return string.Format("Added all clothing types for a {0} {1}", playerEntity.Gender, playerEntity.Race);
case "armor":
foreach (ArmorMaterialTypes material in armorMaterials)
{
Array enumArray = DaggerfallUnity.Instance.ItemHelper.GetEnumArray(ItemGroups.Armor);
for (int i = 0; i < enumArray.Length; i++)
{
Armor armorType = (Armor)enumArray.GetValue(i);
int vs = 0;
int vf = 0;
if (armorType == Armor.Cuirass || armorType == Armor.Left_Pauldron || armorType == Armor.Right_Pauldron)
{
if (material == ArmorMaterialTypes.Chain)
{
vs = 4;
}
else if (material >= ArmorMaterialTypes.Iron)
{
vs = 1;
vf = 4;
}
}
else if (armorType == Armor.Greaves)
{
if (material == ArmorMaterialTypes.Leather)
{
vs = 0;
vf = 2;
}
else if (material == ArmorMaterialTypes.Chain)
{
vs = 6;
}
else if (material >= ArmorMaterialTypes.Iron)
{
vs = 2;
vf = 6;
}
}
else if (armorType == Armor.Gauntlets && material != ArmorMaterialTypes.Leather)
{
vs = 1;
}
else
{
ItemTemplate itemTemplate = DaggerfallUnity.Instance.ItemHelper.GetItemTemplate(ItemGroups.Armor, i);
vf = itemTemplate.variants;
}
if (vf == 0)
vf = vs + 1;
for (int v = vs; v < vf; v++)
{
newItem = ItemBuilder.CreateArmor(playerEntity.Gender, playerEntity.Race, armorType, material, v);
playerEntity.Items.AddItem(newItem);
}
}
}
return string.Format("Added all armor types for a {0} {1}", playerEntity.Gender, playerEntity.Race);
case "weapons":
foreach (WeaponMaterialTypes material in weaponMaterials)
{
Array enumArray = DaggerfallUnity.Instance.ItemHelper.GetEnumArray(ItemGroups.Weapons);
for (int i = 0; i < enumArray.Length; i++)
{
newItem = ItemBuilder.CreateWeapon((Weapons)enumArray.GetValue(i), material);
playerEntity.Items.AddItem(newItem);
}
}
return string.Format("Added all weapon types for any gender/race.");
default:
return "No valid equippable item group specified.";
}
}
}
private static class AddBook
{
public static readonly string name = "addbook";
public static readonly string description = "Gives player the book with the given id or name.";
public static readonly string usage = "addbook {id|name}";
public static string Execute(params string[] args)
{
if (args.Length != 1)
return usage;
int id;
DaggerfallUnityItem book = int.TryParse(args[0], out id) ? ItemBuilder.CreateBook(id) : ItemBuilder.CreateBook(args[0]);
if (book == null)
return "Failed to create book";
GameManager.Instance.PlayerEntity.Items.AddItem(book);
return string.Format("Added {0} to inventory.", book.ItemName);
}
}
private static class Groundme
{
public static readonly string name = "groundme";
public static readonly string description = "Move back to last known good position";
public static readonly string usage = "groundme";
public static string Execute(params string[] args)
{
AcrobatMotor acrobatMotor = GameManager.Instance.AcrobatMotor;
FrictionMotor frictionMotor = GameManager.Instance.FrictionMotor;
CharacterController cc = GameManager.Instance.PlayerController;
acrobatMotor.ClearFallingDamage();
RaycastHit hitInfo;
Vector3 origin = frictionMotor.ContactPoint;
origin.y += cc.height;
Ray ray = new Ray(origin, Vector3.down);
if (!(Physics.Raycast(ray, out hitInfo, cc.height * 2)))
{
return "Failed to reposition - try Teleport or if inside tele2exit";
}
else
{
GameManager.Instance.PlayerObject.transform.position = frictionMotor.ContactPoint;
GameManager.Instance.PlayerMotor.FixStanding(cc.height / 2);
return "Finished - moved to last known good location at " + frictionMotor.ContactPoint.ToString();
}
}
}
private static class ShowBankWindow
{
public static readonly string name = "showbankwindow";
public static readonly string description = "Opens a banking window for specified region";
public static readonly string usage = "showbankwindow {region index}";
public static DaggerfallWorkshop.Game.UserInterface.DaggerfallBankingWindow bankWindow;
public static string Execute(params string[] args)
{
if (bankWindow == null)
bankWindow = new DaggerfallWorkshop.Game.UserInterface.DaggerfallBankingWindow(DaggerfallUI.UIManager);
DaggerfallUI.UIManager.PushWindow(bankWindow);
return "Finished";
}
}
private static class ShowSpellmakerWindow
{
public static readonly string name = "showspellmaker";
public static readonly string description = "Opens a spellmaker window for creating spells";
public static readonly string usage = "showspellmaker";
public static string Execute(params string[] args)
{
DaggerfallUI.UIManager.PostMessage(DaggerfallUIMessages.dfuiOpenSpellMakerWindow);
return "Finished";
}
}
private static class ShowItemMakerWindow
{
public static readonly string name = "showitemmaker";
public static readonly string description = "Opens a item maker window for enchanting items";
public static readonly string usage = "showitemmaker";
public static string Execute(params string[] args)
{
DaggerfallUI.UIManager.PostMessage(DaggerfallUIMessages.dfuiOpenItemMakerWindow);
return "Finished";
}
}
private static class ShowPotionMakerWindow
{
public static readonly string name = "showpotionmaker";
public static readonly string description = "Opens a potion maker window to brew potions";
public static readonly string usage = "showpotionmaker";
public static string Execute(params string[] args)
{
DaggerfallUI.UIManager.PostMessage(DaggerfallUIMessages.dfuiOpenPotionMakerWindow);
return "Finished";
}
}
private static class AddSpellBook
{
public static readonly string name = "addspellbook";
public static readonly string description = "Gives player a new spellbook if they do not have one.";
public static readonly string usage = "addspellbook";
public static string Execute(params string[] args)
{
if (GameManager.Instance.ItemHelper.AddSpellbookItem(GameManager.Instance.PlayerEntity))
return "Spellbook added";
else
return "Player already has a spellbook";
}
}
private static class StartQuest
{
public static readonly string name = "startquest";
public static readonly string description = "Starts the specified quest";
public static readonly string usage = "startquest {quest name}";
public static string Execute(params string[] args)
{
if (args == null || args.Length < 1)
return usage;
UnityEngine.Random.InitState(Time.frameCount);
DaggerfallWorkshop.Game.Questing.QuestMachine.Instance.InstantiateQuest(args[0]);
return "Finished";
}
}
private static class DiseasePlayer
{
public static readonly string name = "diseaseplayer";
public static readonly string description = "Infect player with a classic disease.";
public static readonly string usage = "diseaseplayer index (a number 0-16) OR diseaseplayer vampire|werewolf|wereboar (Note: only vampire currently implemented)";
enum CommandDiseaseTypes
{
Numerical,
Vampire,
Werewolf,
Wereboar,
}
public static string Execute(params string[] args)
{
if (args == null || args.Length != 1)
return usage;
// Determine if valid string or expecting index
CommandDiseaseTypes diseaseType;
switch (args[0].ToLower())
{
case "vampire":
diseaseType = CommandDiseaseTypes.Vampire;
break;
case "werewolf":
diseaseType = CommandDiseaseTypes.Werewolf;
break;
case "wereboar":
diseaseType = CommandDiseaseTypes.Wereboar;
break;
default:
diseaseType = CommandDiseaseTypes.Numerical;
break;
}
// Disease player by index
if (diseaseType == CommandDiseaseTypes.Numerical)
{
// Get index and validate range
int index = -1;
if (!int.TryParse(args[0], out index))
return string.Format("Could not parse argument `{0}` to a number", args[0]);
if (index < 0 || index > 16)
return string.Format("Index {0} is out range. Must be 0-16.", index);
// Infect player
Diseases disease = (Diseases)index;
EntityEffectBundle bundle = GameManager.Instance.PlayerEffectManager.CreateDisease(disease);
GameManager.Instance.PlayerEffectManager.AssignBundle(bundle, AssignBundleFlags.BypassSavingThrows);
return string.Format("Player infected with {0}", disease.ToString());
}
// Vampirism/Werewolf/Wereboar
if (diseaseType == CommandDiseaseTypes.Vampire)
{
// Infect player with vampirism stage one
EntityEffectBundle bundle = GameManager.Instance.PlayerEffectManager.CreateVampirismDisease();
GameManager.Instance.PlayerEffectManager.AssignBundle(bundle, AssignBundleFlags.SpecialInfection);
return "Player infected with vampirism.";
}
else if (diseaseType == CommandDiseaseTypes.Werewolf)
{
// Infect player with werewolf lycanthropy stage one
EntityEffectBundle bundle = GameManager.Instance.PlayerEffectManager.CreateLycanthropyDisease(LycanthropyTypes.Werewolf);
GameManager.Instance.PlayerEffectManager.AssignBundle(bundle, AssignBundleFlags.SpecialInfection);
return "Player infected with werewolf lycanthropy.";
}
else if (diseaseType == CommandDiseaseTypes.Wereboar)
{
// Infect player with wereboar lycanthropy stage one
EntityEffectBundle bundle = GameManager.Instance.PlayerEffectManager.CreateLycanthropyDisease(LycanthropyTypes.Wereboar);
GameManager.Instance.PlayerEffectManager.AssignBundle(bundle, AssignBundleFlags.SpecialInfection);
return "Player infected with wereboar lycanthropy.";
}
else
{
return usage;
}
}
}
private static class PoisonPlayer
{
public static readonly string name = "poisonplayer";
public static readonly string description = "Infect player with a classic poison.";
public static readonly string usage = "poisonplayer index (a number 0-11)";
public static string Execute(params string[] args)
{
if (args == null || args.Length != 1)
return usage;
// Get index and validate range
int index;
if (!int.TryParse(args[0], out index))
return string.Format("Could not parse argument `{0}` to a number", args[0]);
if (index < 0 || index > 11)
return string.Format("Index {0} is out range. Must be 0-11.", index);
// Poison player
Poisons poisonType = (Poisons)index + 128;
DaggerfallWorkshop.Game.Formulas.FormulaHelper.InflictPoison(GameManager.Instance.PlayerEntity, poisonType, true);
return string.Format("Player poisoned with {0}", poisonType.ToString());
}
}
private static class ExecuteScript
{
public static readonly string name = "execute";
public static readonly string description = "compiles source files (and instanties objects when possible) from streaming assets path.";
public static readonly string error = "invalid paramater.";
public static readonly string usage = "execute Script00.cs Script01.cs Script02.cs....";
public static string Execute(params string[] args)
{
if (args == null)
return error;
else if (args.Length < 1)
return error;
int count = 0;
string[] files = new string[args.Length];
for (int i = 0; i < args.Length; i++)
{
if (string.IsNullOrEmpty(args[i]))
continue;
string fullName = Path.Combine(Application.streamingAssetsPath, args[i]);
if (!fullName.EndsWith(".cs")) //limiting to only .cs files isn't really necessary - any text file should work fine
return error;
if (!File.Exists(fullName))
return error;
else
{
Console.Log("Found File: " + fullName);
files[i] = fullName;
count++;
}
}
if (count < 1)
return error;
//string[] source = new string[files.Length];
//for (int i = 0; i < files.Length; i++)
//{
// source[i] = File.ReadAllText(files[i]);
//}
try
{
System.Reflection.Assembly assembly = DaggerfallWorkshop.Game.Utility.Compiler.CompileSource(files, false);//(files.ToArray(), false);
var loadableTypes = DaggerfallWorkshop.Game.Utility.Compiler.GetLoadableTypes(assembly);
foreach (Type t in loadableTypes)
{
bool isAssignable = typeof(Component).IsAssignableFrom(t);
bool hasDefaultConstructor = (t.GetConstructor(Type.EmptyTypes) != null && !t.IsAbstract);
if (isAssignable)
{
GameObject newObj = new GameObject(t.Name);
newObj.AddComponent(t);
}
else if (hasDefaultConstructor)
{
Activator.CreateInstance(t); //only works if has a default constructor
}
}
return "Finished";
}
catch (Exception ex)
{
return ex.Message;
}
}
}
private static class PlayFLC
{
public static readonly string name = "playflc";
public static readonly string description = "Play the specified .FLC or .CEL file";
public static readonly string usage = "playflc {filename.flc|.cel} (e.g. playflc azura.flc | playflc warrior.cel)";
public static string Execute(params string[] args)
{
if (args == null || args.Length < 1)
return usage;
DemoFLCWindow window = new DemoFLCWindow(DaggerfallUI.Instance.UserInterfaceManager);
window.Filename = args[0];
DaggerfallUI.Instance.UserInterfaceManager.PushWindow(window);
return "Finished";
}
}
private static class PlayVID
{
public static readonly string name = "playvid";
public static readonly string description = "Play the specified .VID file";
public static readonly string usage = "playvid {filename.vid} (e.g. playvid anim0000.vid)";
public static string Execute(params string[] args)
{
if (args == null || args.Length < 1)
return usage;
// Start video and set to exit on escape only, as enter keypress can fall through and close video instantly
DaggerfallVidPlayerWindow vidPlayerWindow = new DaggerfallVidPlayerWindow(DaggerfallUI.UIManager, args[0]);
vidPlayerWindow.EndOnAnyKey = false;
DaggerfallUI.Instance.UserInterfaceManager.PushWindow(vidPlayerWindow);
return "Finished";
}
}
private static class PrintLegalRep
{
public static readonly string name = "print_legalrep";
public static readonly string description = "Output current legal status and reputation value for all regions";
public static readonly string usage = "print_legalrep";
public static string Execute(params string[] args)
{
string output = string.Empty;
if (GameManager.Instance.PlayerEntity != null && GameManager.Instance.PlayerEntity.RegionData != null)
{
for (int region = 0; region < GameManager.Instance.PlayerEntity.RegionData.Length; region++)
{
string regionName = DaggerfallUnity.Instance.ContentReader.MapFileReader.GetRegionName(region);
string reputationString = string.Empty;
int rep = GameManager.Instance.PlayerEntity.RegionData[region].LegalRep;
if (rep > 80)
reputationString = HardStrings.revered;
else if (rep > 60)
reputationString = HardStrings.esteemed;
else if (rep > 40)
reputationString = HardStrings.honored;
else if (rep > 20)
reputationString = HardStrings.admired;
else if (rep > 10)
reputationString = HardStrings.respected;
else if (rep > 0)
reputationString = HardStrings.dependable;
else if (rep == 0)
reputationString = HardStrings.aCommonCitizen;
else if (rep < -80)
reputationString = HardStrings.hated;
else if (rep < -60)
reputationString = HardStrings.pondScum;
else if (rep < -40)
reputationString = HardStrings.aVillain;
else if (rep < -20)
reputationString = HardStrings.aCriminal;
else if (rep < -10)
reputationString = HardStrings.aScoundrel;
else if (rep < 0)
reputationString = HardStrings.undependable;
output += string.Format("In '{0}' you are {1} [{2}]\n", regionName, reputationString, rep);
}
output += "Finished";
}
else
{
return "Could not read legal reputation data.";
}
return output;
}
}
private static class ClearNegativeLegalRep
{
public static readonly string name = "clear_negativelegalrep";
public static readonly string description = "Negative legal reputation and banishment state for all regions is set back to 0. Does not affect positive legal reputation. Does not change factional reputation.";
public static readonly string usage = "clear_negativelegalrep";
public static string Execute(params string[] args)
{
string output = string.Empty;
if (GameManager.Instance.PlayerEntity != null && GameManager.Instance.PlayerEntity.RegionData != null)
{
for (int region = 0; region < GameManager.Instance.PlayerEntity.RegionData.Length; region++)
{
string regionName = DaggerfallUnity.Instance.ContentReader.MapFileReader.GetRegionName(region);
int rep = GameManager.Instance.PlayerEntity.RegionData[region].LegalRep;
if (rep < 0)
{
GameManager.Instance.PlayerEntity.RegionData[region].LegalRep = 0;
GameManager.Instance.PlayerEntity.RegionData[region].SeverePunishmentFlags = 0;
output += string.Format("Cleared negative legal reputation for '{0}'.\n", regionName);
}
}
output += "Finished";
}
else
{
return "Could not read legal reputation data.";
}
return output;
}
}
private static class SummonDaedra
{
public static readonly string name = "summondaedra";
public static readonly string description = "Summons a daedra prince to test quest delivery.";
public static readonly string usage = "summondaedra [filename] (note: matches the .VID filename for daedea in /arena2 folder.)";
public static string Execute(params string[] args)
{
if (args == null || args.Length < 1)
return usage;
bool found = false;
string validNames = string.Empty;
DaggerfallQuestPopupWindow.DaedraData daedraToSummon = new DaggerfallQuestPopupWindow.DaedraData();
DaggerfallQuestPopupWindow.DaedraData[] daedraData = DaggerfallQuestPopupWindow.daedraData;
foreach (var daedra in daedraData)
{
string name = daedra.vidFile.Split('.')[0];
if (string.Compare(args[0], name, true) == 0)
{
daedraToSummon = daedra;
found = true;
}
validNames += name + ", ";
}
if (!found)
return string.Format("Could not find daedra named {0}. Valid names are {1}", args[0], validNames);
IUserInterfaceManager uiManager = DaggerfallUI.UIManager;
Quest quest = GameManager.Instance.QuestListsManager.GetQuest(daedraToSummon.quest);
if (quest != null)
uiManager.PushWindow(UIWindowFactory.GetInstanceWithArgs(UIWindowType.DaedraSummoned, new object[] { uiManager, daedraToSummon, quest }));
else
return string.Format("Could not find quest {0} for deadra {1}", daedraToSummon.quest, args[0]);
return "Finished";
}
}
private static class AddPopupText
{
public static readonly string name = "addpopuptext";
public static readonly string description = "Fill HUD buffer with messages";
public static readonly string usage = "addpopuptext count";
public static string Execute(params string[] args)
{
if (args.Length < 1) return "see usage";
int n = 1;
Int32.TryParse(args[0], out n);
if (n < 1 || n > 100000)
return "Error - see usage";
for (int i = 1; i <= n; i++)
DaggerfallUI.Instance.PopupMessage("message " + i);
return "Finished";
}
}
private static class ChangeModSettings
{
static ConsoleController controller;
public static readonly string name = "change_modsettings";
public static readonly string description = "Change mod settings (experimental).";
public static readonly string usage = "change_modsettings";
public static string Execute(params string[] args)
{
if (!ModManager.Instance)
return "ModManager instance not found.";
string[] modTitles = ModManager.Instance.Mods.Where(x => x.HasSettings && x.LoadSettingsCallback != null).Select(x => x.Title).ToArray();
if (modTitles.Length == 0)
return "There are no mods that support live changes to settings.";
ModManager.Instance.StartCoroutine(OpenSettingsWindow(modTitles));
return string.Format("Found {0} mod(s) that support live changes to settings. Close the console to open settings window.", modTitles.Length);
}
private static IEnumerator OpenSettingsWindow(string[] modTitles)
{
if (!FindController())
yield break;
while (controller.ui.isConsoleOpen)
yield return null;
var userInterfaceManager = DaggerfallUI.Instance.UserInterfaceManager;
var listPicker = new DaggerfallListPickerWindow(userInterfaceManager);
listPicker.ListBox.AddItems(modTitles);
listPicker.OnItemPicked += (index, modTitle) =>
{
listPicker.PopWindow();
userInterfaceManager.PushWindow(new ModSettingsWindow(userInterfaceManager, ModManager.Instance.GetMod(modTitle), true));
};
userInterfaceManager.PushWindow(listPicker);
}
private static bool FindController()
{
if (controller)
return true;
GameObject console = GameObject.Find("Console");
if (console && (controller = console.GetComponent<ConsoleController>()))
return true;
Debug.LogError("Failed to find console controller.");
return false;
}
}
}
}
| 48.889057 | 405 | 0.550884 | [
"MIT"
] | JasonBreen/daggerfall-unity | Assets/Game/Addons/UnityConsole/Console/Scripts/DefaultCommands.cs | 129,116 | C# |
using System;
using Android.App;
using Android.OS;
using Android.Runtime;
using Android.Widget;
using Plugin.CurrentActivity;
namespace CurrentActivityTest
{
[Application]
public class MainApplication : Application
{
public MainApplication(IntPtr handle, JniHandleOwnership transer)
: base(handle, transer)
{
}
public override void OnCreate()
{
base.OnCreate();
CrossCurrentActivity.Current.Init(this);
CrossCurrentActivity.Current.ActivityStateChanged += Current_ActivityStateChanged;
}
private void Current_ActivityStateChanged(object sender, ActivityEventArgs e)
{
Toast.MakeText(Application.Context, $"Activity Changed: {e.Activity.LocalClassName} - {e.Event}", ToastLength.Short).Show();
}
}
} | 23.3125 | 128 | 0.758713 | [
"MIT"
] | dave11111/CurrentActivityPlugin | src/CurrentActivityTest.Droid/MainApplication.cs | 748 | C# |
using System;
using Memoria.Prime;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Memoria.Assets
{
public class EncryptFontManager
{
private static readonly Font DefaultFont = InitializeFont();
static EncryptFontManager()
{
loadInEditMode = false;
}
public static Font LoadFont(Font originalFont)
{
Log.Message("[FontInterceptor] Loading font [Original: {0}]", originalFont);
try
{
return DefaultFont ?? originalFont;
}
catch (Exception ex)
{
Log.Error(ex, "[FontInterceptor] Failed to intercept font.");
return originalFont;
}
}
private static void LoadFont()
{
String path = "EmbeddedAsset/FA/" + AssetManagerUtil.GetPlatformPrefix(Application.platform) + "_fa.mpc";
if (fontBundle == null)
{
String[] fontInfo;
Byte[] binAsset = AssetManager.LoadBytes(path, out fontInfo, false);
Byte[] binary = ByteEncryption.Decryption(binAsset);
fontBundle = AssetBundle.CreateFromMemoryImmediate(binary);
}
if (Configuration.Font.Names.Length > 0 && EncryptFontManager.fontBundle.Contains(Configuration.Font.Names[0]))
EncryptFontManager.defaultFont = EncryptFontManager.LoadFont(EncryptFontManager.fontBundle.LoadAsset<Font>(Configuration.Font.Names[0]));
else
EncryptFontManager.defaultFont = EncryptFontManager.LoadFont(EncryptFontManager.fontBundle.LoadAsset<Font>("TBUDGoStd-Bold"));
fontBundle.Unload(false);
Object.DestroyImmediate(fontBundle);
fontBundle = null;
}
private static void StateChange()
{
if (!Application.isPlaying)
{
if (fontBundle != null)
{
fontBundle.Unload(true);
Object.DestroyImmediate(fontBundle);
fontBundle = null;
}
defaultFont = null;
}
}
public static Font SetDefaultFont()
{
if (defaultFont == null)
{
LoadFont();
}
return defaultFont;
}
public static Font defaultFont;
private static AssetBundle fontBundle;
private static Boolean loadInEditMode = true;
private static Font InitializeFont()
{
Log.Message("[FontInterceptor] Dynamic font initialization.");
try
{
if (!Configuration.Font.Enabled)
{
Log.Message("[FontInterceptor] Pass through {Configuration.Font.Enabled = 0}.");
return null;
}
if (Configuration.Font.Names.IsNullOrEmpty())
{
Log.Error("[FontInterceptor] An invalid font configuration [Configuration.Font.Names is empty].");
return null;
}
Log.Message("[FontInterceptor] Initialize new font: [Names: {{{0}}}, Size: {1}]", String.Join(", ", Configuration.Font.Names), Configuration.Font.Size);
if (Configuration.Font.Names.Length > 0 && Array.Exists(Font.GetOSInstalledFontNames(), font => font.CompareTo(Configuration.Font.Names[0]) == 0))
return Font.CreateDynamicFontFromOSFont(Configuration.Font.Names, Configuration.Font.Size);
return null;
}
catch (Exception ex)
{
Log.Error(ex, "[FontInterceptor] Failed to create a dynamic font.");
return null;
}
}
}
}
| 35.220183 | 168 | 0.54858 | [
"MIT"
] | Iamgoofball/Memoria | Assembly-CSharp/Memoria/Assets/EncryptFontManager.cs | 3,839 | C# |
using Aggregates.Contracts;
using Aggregates.Messages;
using NServiceBus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aggregates.Internal;
namespace Aggregates
{
public static class ContextExtensions
{
public static IRepository<T> For<T>(this IMessageHandlerContext context) where T : class, IEntity
{
var uow = context.Extensions.Get<IDomainUnitOfWork>();
return uow.For<T>();
}
public static IPocoRepository<T> Poco<T>(this IMessageHandlerContext context) where T : class, new()
{
var uow = context.Extensions.Get<IDomainUnitOfWork>();
return uow.Poco<T>();
}
public static Task<TResponse> Query<TQuery, TResponse>(this IMessageHandlerContext context, TQuery query) where TQuery : class, IQuery<TResponse>
{
var container = context.Extensions.Get<IContainer>();
var uow = context.Extensions.Get<IDomainUnitOfWork>();
return uow.Query<TQuery, TResponse>(query, container);
}
public static Task<TResponse> Query<TQuery, TResponse>(this IMessageHandlerContext context, Action<TQuery> query) where TQuery : class, IQuery<TResponse>
{
var container = context.Extensions.Get<IContainer>();
var uow = context.Extensions.Get<IDomainUnitOfWork>();
return uow.Query<TQuery, TResponse>(query, container);
}
public static TUnitOfWork App<TUnitOfWork>(this IMessageHandlerContext context) where TUnitOfWork : class, IUnitOfWork
{
var uow = context.Extensions.Get<IUnitOfWork>();
return uow as TUnitOfWork;
}
public static Task SendToSelf(this IMessageHandlerContext context, Messages.ICommand command)
{
var container = context.Extensions.Get<IContainer>();
var dispatcher = container.Resolve<IMessageDispatcher>();
var message = new FullMessage
{
Headers = context.MessageHeaders.Where(x => x.Key != $"{Defaults.PrefixHeader}.{Defaults.MessageIdHeader}").ToDictionary(kv => kv.Key, kv => kv.Value),
Message = command
};
Task.Run(() => dispatcher.SendLocal(message));
return Task.CompletedTask;
}
}
}
| 39.833333 | 167 | 0.645607 | [
"MIT"
] | virajs/Aggregates.NET | src/Aggregates.NET.NServiceBus/ContextExtensions.cs | 2,392 | C# |
using Microsoft.EntityFrameworkCore;
using PushServer.PushConfiguration.Abstractions.Models;
using PushServer.PushConfiguration.Abstractions.Services;
using PushServer.PushConfiguration.EntityFramework.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PushServer.PushConfiguration.EntityFramework
{
public class PushConfigurationStore : IPushConfigurationStore
{
private readonly ConfigurationDbContext configurationContext;
public PushConfigurationStore(ConfigurationDbContext configurationContext)
{
this.configurationContext = configurationContext;
}
public async Task<bool> DeleteAsync(string userId, string configurationId)
{
var channel = configurationContext.PushChannelConfigurations.Where(v => v.UserId == userId && v.Id == configurationId).SingleOrDefault();
if (null == channel)
{
return false;
}
configurationContext.PushChannelConfigurations.Remove(channel);
await configurationContext.SaveChangesAsync();
return true;
}
public async Task<Abstractions.Models.PushChannelConfiguration[]> GetAllAsync(string userId)
{
return await configurationContext.PushChannelConfigurations.Include(v => v.Options).Where(v => v.UserId == userId)
.Select(v => new Abstractions.Models.PushChannelConfiguration()
{
EndpointInfo = v.EndpointInfo,
Id = v.Id,
Options = new PushChannelOptions(v.Options.Where(d => !d.EndpointOption).ToDictionary(d => d.Key, d => d.Value)),
ChannelType = v.Type
}).ToArrayAsync();
}
private async Task CreateOptionsAsync(IDictionary<string, string> options, string channelId, bool endpointOptions)
{
if (null == options)
{
return;
}
foreach (var pair in options)
{
var option = new PushChannelOption()
{
ID = Guid.NewGuid().ToString(),
Key = pair.Key,
Value = pair.Value,
PushChannelConfigurationID = channelId,
EndpointOption = endpointOptions
};
await configurationContext.PushChannelOptions.AddAsync(option);
}
}
public async Task<Abstractions.Models.PushChannelConfiguration> RegisterAsync(string userId, PushChannelRegistration registration)
{
var channel = new Entities.PushChannelConfiguration()
{
Id = Guid.NewGuid().ToString(),
UserId = userId,
Endpoint = registration.Endpoint,
EndpointInfo = registration.EndpointInfo,
Type = registration.PushChannelType,
ExpirationTime = registration.ExpirationTime,
};
await configurationContext.PushChannelConfigurations.AddAsync(channel);
await CreateOptionsAsync(registration.Options, channel.Id, false);
await CreateOptionsAsync(registration.EndpointOptions, channel.Id, true);
await configurationContext.SaveChangesAsync();
return new Abstractions.Models.PushChannelConfiguration()
{
EndpointInfo = channel.EndpointInfo,
Id = channel.Id,
ChannelType = channel.Type,
Options = registration.Options
};
}
public async Task UpdateAsync(string userId, string configurationId, PushChannelRegistration registration)
{
var channel = configurationContext.PushChannelConfigurations.Include(v => v.Options).Where(v => v.UserId == userId && v.Id == configurationId).Single();
foreach (var opt in channel.Options)
{
configurationContext.PushChannelOptions.Remove(opt);
}
channel.Endpoint = registration.Endpoint;
channel.ExpirationTime = registration.ExpirationTime;
channel.EndpointInfo = registration.EndpointInfo;
channel.Type = registration.PushChannelType;
await CreateOptionsAsync(registration.Options, channel.Id, false);
await CreateOptionsAsync(registration.EndpointOptions, channel.Id, true);
await configurationContext.SaveChangesAsync();
}
public async Task<Abstractions.Models.PushChannelConfiguration> GetAsync(string configurationId)
{
return await configurationContext.PushChannelConfigurations.Include(v => v.Options).Where(v => v.Id == configurationId)
.Select(v => new Abstractions.Models.PushChannelConfiguration()
{
EndpointInfo = v.EndpointInfo,
Id = v.Id,
Options = new PushChannelOptions(v.Options.Where(d => !d.EndpointOption).ToDictionary(d => d.Key, d => d.Value)),
ChannelType = v.Type
}).SingleAsync();
}
public async Task<PushEndpoint> GetEndpointAsync(string configurationId)
{
return await configurationContext.PushChannelConfigurations.Include(v => v.Options).Where(v => v.Id == configurationId)
.Select(v => new PushEndpoint()
{
Endpoint = v.Endpoint,
EndpointOptions = v.Options.Where(d => d.EndpointOption).ToDictionary(d => d.Key, d => d.Value)
}).SingleAsync();
}
public async Task<Abstractions.Models.PushChannelConfiguration[]> GetForOptionsAsync(string userId, IDictionary<string, string> configurationOptions)
{
var query = configurationContext.PushChannelConfigurations.Include(v => v.Options).Where(v => v.UserId == userId);
foreach (var option in configurationOptions)
{
if (null != option.Value)
{
query = query.Where(v => v.Options.Any(d => !d.EndpointOption && d.Key == option.Key && d.Value == option.Value));
}
else
{
query = query.Where(v => v.Options.Any(d => !d.EndpointOption && d.Key == option.Key));
}
}
return await query.Select(v => new Abstractions.Models.PushChannelConfiguration()
{
EndpointInfo = v.EndpointInfo,
Id = v.Id,
Options = new PushChannelOptions(v.Options.Where(d => !d.EndpointOption).ToDictionary(d => d.Key, d => d.Value)),
ChannelType = v.Type
}).ToArrayAsync();
}
public async Task UpdateOptionsAsync(string userId, string configurationId, PushChannelOptions options)
{
var channel = configurationContext.PushChannelConfigurations.Include(v => v.Options).Where(v => v.UserId == userId && v.Id == configurationId).Single();
foreach (var opt in channel.Options)
{
configurationContext.PushChannelOptions.Remove(opt);
}
await CreateOptionsAsync(options, channel.Id, false);
await configurationContext.SaveChangesAsync();
}
}
}
| 45.901235 | 164 | 0.602474 | [
"MIT"
] | tuwrraphael/PushServer | PushConfiguration.EntityFramework/PushConfigurationStore.cs | 7,436 | C# |
using System;
using Nest;
using Tests.Core.ManagedElasticsearch.Clusters;
using Tests.Domain;
using Tests.Framework.Integration;
namespace Tests.Mapping.Types.Core.Date
{
public class DatePropertyTests : PropertyTestsBase
{
public DatePropertyTests(WritableCluster cluster, EndpointUsage usage) : base(cluster, usage) { }
protected override object ExpectJson => new
{
properties = new
{
lastActivity = new
{
type = "date",
doc_values = false,
similarity = "classic",
store = true,
index = false,
boost = 1.2,
ignore_malformed = true,
format = "MM/dd/yyyy",
null_value = DateTime.MinValue
}
}
};
protected override Func<PropertiesDescriptor<Project>, IPromise<IProperties>> FluentProperties => f => f
.Date(b => b
.Name(p => p.LastActivity)
.DocValues(false)
.Similarity(SimilarityOption.Classic)
.Store()
.Index(false)
.Boost(1.2)
.IgnoreMalformed()
.Format("MM/dd/yyyy")
.NullValue(DateTime.MinValue)
);
protected override IProperties InitializerProperties => new Properties
{
{
"lastActivity", new DateProperty
{
DocValues = false,
Similarity = SimilarityOption.Classic,
Store = true,
Index = false,
Boost = 1.2,
IgnoreMalformed = true,
Format = "MM/dd/yyyy",
NullValue = DateTime.MinValue
}
}
};
}
}
| 22.111111 | 106 | 0.651831 | [
"Apache-2.0"
] | Henr1k80/elasticsearch-net | src/Tests/Tests/Mapping/Types/Core/Date/DatePropertyTests.cs | 1,395 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using Aliyun.Acs.Core;
namespace Aliyun.Acs.Ecs.Model.V20140526
{
public class ResizeDiskResponse : AcsResponse
{
}
} | 35.807692 | 63 | 0.75188 | [
"Apache-2.0"
] | VAllens/aliyun-openapi-sdk-net-core | src/aliyun-net-sdk-ecs/Model/V20140526/ResizeDiskResponse.cs | 931 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.