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 JetBrains.Annotations; using JetBrains.ReSharper.Plugins.FSharp.Psi.Tree; using JetBrains.ReSharper.Psi.ExtensionsAPI.Caches2; namespace JetBrains.ReSharper.Plugins.FSharp.Psi.Impl.Cache2.Parts { internal class NestedModulePart : ModulePartBase<INestedModuleDeclaration> { public NestedModulePart([NotNull] INestedModuleDeclaration declaration, [NotNull] ICacheBuilder cacheBuilder) : base(declaration, cacheBuilder.Intern(declaration.CompiledName), ModifiersUtil.GetDecoration(declaration.AccessModifiers, declaration.Attributes), cacheBuilder) { } public NestedModulePart(IReader reader) : base(reader) { } protected override byte SerializationTag => (byte) FSharpPartKind.NestedModule; } }
32.913043
113
0.77675
[ "Apache-2.0" ]
slavam2605/fsharp-support
ReSharper.FSharp/src/FSharp.Psi/src/Impl/Cache2/Parts/NestedModulePart.cs
759
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CloudAwesome.Xrm.Core.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CloudAwesome.Xrm.Core.Tests")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("6ab7a47c-fe8a-42b0-9d96-563ba73d77e9")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
31.142857
58
0.756881
[ "MIT" ]
Cloud-Awesome/cds-core
src/CloudAwesome.Xrm.Core/CloudAwesome.Xrm.Core.Tests/Properties/AssemblyInfo.cs
655
C#
// Copyright (c) 2021 DHGMS Solutions and Contributors. All rights reserved. // DHGMS Solutions and Contributors licenses this file to you under the MIT license. // See the LICENSE file in the project root for full license information. using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // 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("ReactiveUI.VetuviemSample.XamDroidApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ReactiveUI.VetuviemSample.XamDroidApp")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision
37.931034
84
0.770909
[ "MIT" ]
dpvreony/Vetuviem
src/ReactiveUI.VetuviemSample.XamDroidApp/Properties/AssemblyInfo.cs
1,103
C#
using System.Collections.Generic; namespace Geonorge.Forvaltningsinformasjon.Web { public class ApplicationSettings { public string BuildVersionNumber { get; set; } public string EnvironmentName { get; set; } public string UrlGeonorgeRoot { get; set; } public string UrlThematicGeoJson { get; set; } public string LocalPathThematicGeoJson { get; set; } public string UrlProxy { get; set; } public string UserNameProxy { get; set; } public string PasswordProxy { get; set; } public string CredentialVerificationDomain { get; set; } public ExternalUrls ExternalUrls { get; set; } public ConnectionStrings ConnectionStrings { get; set; } public Wms Wms { get; set; } public Dictionary<string,string> DataSetToLayerMap { get; set; } public Dictionary<string, string> DataAgeDataSetToLayerMap { get; set; } public Dictionary<string, string> DataQualityDataSetToLayerMap { get; set; } public Dictionary<string,string> AgeCategoryColors { get; set; } public Dictionary<string, string> QualityCategoryColors { get; set; } public ChartLegendSettings ChartLegendSettings { get; set; } } public class Wms { public string UrlBase { get; set; } public string Version { get; set; } } public class ConnectionStrings { public string KOS { get; set; } } public class ChartLegendSettings { public string TitleTextColor { get; set; } public string BodyTextColor { get; set; } public string BackgroundColor { get; set; } public string BorderColor { get; set; } public string BorderWidth { get; set; } } public class ExternalUrls { public string OperationalStatus { get; set; } public string MunicipalitiesGeoJson { get; set; } public string MetadataTransactionData { get; set; } public string MetadataDataQualityDistribution { get; set; } public string MetadataDataAgeDistribution { get; set; } public string MetadataDataQualityClassification { get; set; } } }
36.830508
84
0.654855
[ "MIT" ]
kartverket/Geonorge.Forvaltningsinformasjon
Geonorge.Forvaltningsinformasjon.Web/ApplicationSettings.cs
2,175
C#
using System.Linq.Expressions; using gRPC.Select.Interface; namespace gRPC.Select.CompareConditions { public class CompareConditionLe : ICompareCondition { public BinaryExpression Build(Expression left, Expression right) { return Expression.LessThanOrEqual(left, right); } } }
23.285714
72
0.699387
[ "Apache-2.0" ]
InsonusK/gRPC.Select
gRPC.Select/gRPC.Select/CompareConditions/CompareConditionLe.cs
326
C#
namespace EncoreTickets.SDK.Utilities.CommonModels { public interface IEntityWithAggregateReference { string AggregateReference { get; set; } } }
20.875
51
0.718563
[ "MIT" ]
EncoreLabs/sdk-dotNet
EncoreTickets.SDK/Utilities/CommonModels/IEntityWithAggregateReference.cs
169
C#
using System.Threading.Tasks; namespace FeatureFlags.WebAPI.Feature { /// <summary> /// Abstraction over IFeatureManager /// </summary> public interface IFeatureService { Task<bool> IsEnabledAsync(Features feature); Task<bool> IsNotEnabledAsync(Features feature); Task<bool> IsEnabledAsync<TContext>(Features feature, TContext context); Task<bool> IsNotEnabledAsync<TContext>(Features feature, TContext context); } }
31.6
83
0.702532
[ "MIT" ]
TGrannen/dotnet-samples
FeatureFlags/FeatureFlags.WebAPI/Feature/IFeatureService.cs
476
C#
using UnityEngine; public class CameraManager : MonoBehaviour { [SerializeField] private GameObject playerCamera, placementCamera; [SerializeField] private GameObject shopUI; public void EnableShop() { playerCamera.SetActive(false); placementCamera.SetActive(true); } public void DisableShop() { playerCamera.SetActive(true); placementCamera.SetActive(false); } }
20
53
0.675
[ "Apache-2.0" ]
Xwilarg/42Jam
Assets/Scripts/CameraManager.cs
442
C#
using System.Collections.Generic; using System.Linq; using Verse; using ThingsThatMove.AI; namespace ThingsThatMove { public class MovableThing_MapComponent : MapComponent { public ThingPathPool thingPathPool; public ThingPathFinder thingPathFinder; public MovableThing_MapComponent(Map map) : base(map) { this.thingPathFinder = new ThingPathFinder(map); this.thingPathPool = new ThingPathPool(map); } } public static class MapHelper { public static ThingPathFinder GetThingPathFinder(this Map map) => map.GetComponent<MovableThing_MapComponent>().thingPathFinder; public static ThingPathPool GetThingPathPool(this Map map) => map.GetComponent<MovableThing_MapComponent>().thingPathPool; } }
25.967742
136
0.713043
[ "MIT" ]
AaronCRobinson/ThingsThatMove
Source/ThingsThatMove/MapComponent.cs
807
C#
using Serilog; using System.Text; using System.Text.RegularExpressions; namespace Generator { internal class ScriptGenerator { private IDictionary<string, Regex> removeBeforeCompare = new Dictionary<string, Regex>(); public ScriptGenerator(Settings settings, string path, string originalText) { var fi = new FileInfo(path); var newPath = Path.Combine(Path.GetDirectoryName(fi.FullName), Path.GetFileNameWithoutExtension(path)) + "_output" + fi.Extension; Log.Information("Output path: \"" + newPath + "\""); var pages = settings.Pages; var functions = settings.Functions.ToDictionary(e => $"${e.Key}$", e => e.Value); var js = new List<string>(); js.Add("var activePage;"); foreach (var page in pages) { if (!page.Folder.EndsWith("\\")) { page.Folder = page.Folder + "\\"; } var files = FileHelper.GetAllFiles(page.Folder, "*.*").ToArray(); files = files.Where(e => !e.Contains("~$")).ToArray(); var updatedPageFolder = page.Folder; var wordOrder = page.OrderFromDoc; if (wordOrder != null) { if (page.Order?.Any() == true) { Log.Warning("\"Order\" is defined more than once. Order will be read from doc again."); } var matched = GetMatched(files, wordOrder.File, page.Folder); foreach (var m in matched) { if (matched.Length > 1) { Log.Warning($"Found multiple \"{wordOrder.File}\""); } updatedPageFolder = Path.GetDirectoryName(m); var htmlFile = WordHelper.ConvertWordToHtml(m); var html = new HtmlAgilityPack.HtmlDocument(); html.Load(htmlFile, Encoding.UTF8); var node = html.DocumentNode.SelectNodes(wordOrder.XPath); var strs = node.Select(e => e.InnerText.Trim()).ToArray(); if (wordOrder.IgnoredOrders?.Any() == true) { strs = strs.Except(wordOrder.IgnoredOrders, StringComparer.InvariantCultureIgnoreCase).ToArray(); } Log.Information($"Found orders in \"{wordOrder.File}\":" + Environment.NewLine + string.Join(Environment.NewLine, strs)); page.Order = strs; AddPages(functions, js, page, files, updatedPageFolder); } } else { AddPages(functions, js, page, files, updatedPageFolder); } } for (var i = 0; i < js.Count; i++) { foreach (var f in functions) { js[i] = js[i].Replace(f.Key, f.Value); } } var text = string.Join("\n", js); var newText = originalText.Replace("$SCRIPTS$", text); File.WriteAllText(newPath, newText); } private void AddPages(Dictionary<string, string> functions, List<string> js, Page page, string[] files, string? updatedPageFolder) { AddPageToJs(js); AddTitleToJs(functions, js, page.Title); if (page.File != null) { var matched = GetMatched(files, page.File, page.Folder); if (page.PageRange == "all") { AddFilesAllPagesToJs(functions, js, matched); } else { AddFilesToJs(functions, js, matched); } if (page.LoopBy == "order") { var isFirst = true; foreach (var order in page.Order) { AddNextPages(page, updatedPageFolder, isFirst, js, functions, files, order); isFirst = false; } } } } private void AddNextPages(Page page, string updatedPageFolder, bool isFirst, List<string> js, Dictionary<string, string> functions, string[] files, string order) { var addedFileShortNames = new List<string>(); foreach (var nextPage in page.NextPages) { var localPageFolder = page.Folder; if (!string.IsNullOrEmpty(nextPage.Folder)) { if (nextPage.Folder == "sameFolder") { localPageFolder = updatedPageFolder; } else { localPageFolder = nextPage.Folder; } } if (!localPageFolder.EndsWith("\\")) { localPageFolder = localPageFolder + "\\"; } if (!isFirst && nextPage.Once) { continue; } AddPageToJs(js); if (nextPage.Once) { AddTitleToJs(functions, js, nextPage.Title); var matched2 = GetMatched(files, nextPage.File, localPageFolder); AddFilesToJs(functions, js, matched2); } else { if (nextPage.TitleFormat == "useOrder") { nextPage.Title = order; } AddTitleToJs(functions, js, nextPage.Title); var matched2 = GetMatched(files, nextPage.File, localPageFolder); var regex = new List<Regex>(); var rbc = nextPage.RemoveBeforeCompare; if (rbc != null) { foreach (var r in rbc) { if (!string.IsNullOrEmpty(r)) { if (removeBeforeCompare.ContainsKey(r)) { regex.Add(removeBeforeCompare[r]); } else { var nr = new Regex(r); removeBeforeCompare[r] = nr; regex.Add(nr); } } } } if (!string.IsNullOrEmpty(nextPage.FileHint)) { var regex2 = new Regex(nextPage.FileHint); var matched3 = addedFileShortNames.Select(e => regex2.Match(e).Groups[1].Value).Distinct().ToArray(); matched2 = GetMatched(matched2, matched3, localPageFolder); } if (matched2.Any()) { var filtered = FindBestMatched(matched2, order, localPageFolder, regex); AddFilesToJs(functions, js, filtered); var shortNames = filtered.Select(e => e.Replace(localPageFolder, "")); addedFileShortNames.AddRange(shortNames); } } } } private static void AddFilesAllPagesToJs(Dictionary<string, string> functions, List<string> js, string[] matched) { foreach (var m in matched) { var fi2 = new FileInfo(m); if (fi2.Extension.Equals(".pdf", StringComparison.InvariantCultureIgnoreCase)) { AddPdfAllPagesToJs(functions, js, m); } else { Log.Error($"Doesn't support ${fi2.Extension}"); } } } private static void AddPdfAllPagesToJs(Dictionary<string, string> functions, List<string> js, string m) { if (functions.ContainsKey("$insertPdfAllPages$")) { var func = functions["$insertPdfAllPages$"] .Replace("$file$", m.ToLiteral()); js.Add(func + ";"); } else { Log.Error("Cann't find function insertPdfAllPages()"); } } private static void AddPageToJs(List<string> js) { js.Add("activePage = $insertPage$;"); js.Add("$incrementAfterInsertPage$;"); } private static string[] FindBestMatched(string[] allFiles, string expectedString, string rootFolder, IReadOnlyCollection<Regex> removeBeforeCompare = null) { var dict = new Dictionary<int, string[]>(); var scores = allFiles.Select(e => { var f = e.Replace(rootFolder, ""); if (removeBeforeCompare != null) { foreach (var regex in removeBeforeCompare) { f = regex.Replace(f, ""); } } var per = new string[0]; if (dict.ContainsKey(f.Length)) { per = dict[f.Length]; } else { if (Math.Abs(expectedString.Length - f.Length) > 7 && Math.Max(expectedString.Length, f.Length) > 20) { Log.Warning($"Two strings are too large to compare exactly: {expectedString} (len={expectedString.Length})"); Log.Warning($" {f}(len={f.Length})"); } else { if (expectedString.Length > f.Length) { var ncr = StringHelper.EstimateComb(expectedString.Length, f.Length); if (ncr < 5000) { per = StringHelper.GetCombinations(expectedString.ToCharArray(), f.Length).ToArray(); } else { Log.Warning($"Two strings are too large to compare exactly: {expectedString} (len={expectedString.Length})"); Log.Warning($" {f}(len={f.Length})"); Log.Warning($" possoible combinations: {ncr}"); } } } dict[f.Length] = per; } if (!per.Any()) { per = new[] { expectedString }; } var score = per.Min(e => StringHelper.Compare(e, f)); if (expectedString.ToCharArray().Count(e => f.Contains(e)) == 0) { score += 100; // penalty if no common char } return new { Path = e, ProcessedString = f, Score = score }; }).ToArray(); var min = scores.Min(e => e.Score); var texts = scores.Where(e => e.Score == min).Select(e => e.Path).ToArray(); return texts; } private static void AddTitleToJs(Dictionary<string, string> functions, List<string> js, string title) { if (!string.IsNullOrEmpty(title)) { var func = functions["$addTitle$"].Replace("$title$", title.ToLiteral()); js.Add(func + ";"); } } private static void AddFilesToJs(Dictionary<string, string> functions, List<string> js, string[] matched) { if (matched.Any() == false) { return; } if (functions.ContainsKey("$insertFiles$")) { var func = functions["$insertFiles$"] .Replace("$files$", matched.ToLiteral()); js.Add(func + ";"); } else { for (var i = 0; i < matched.Length; i++) { var func = functions["$insertFile$"] .Replace("$file$", matched[i].ToLiteral()) .Replace("$index$", i.ToString()); js.Add(func + ";"); } } } private static string[] GetMatched(string[] files, string[] keywords, string rootPath) { var matched = new List<string>(); foreach (var f in files) { var f1 = f.Replace(rootPath, ""); foreach (var k in keywords) { if (f1.Contains(k)) { matched.Add(f); break; } } } return matched.ToArray(); } } }
39.997059
169
0.42209
[ "MIT" ]
g2384/InDesign-scripts
generator/ScriptGenerator.cs
13,601
C#
namespace ClearHl7.Codes.V281 { /// <summary> /// HL7 Version 2 Table 0490 - Specimen Reject Reason. /// </summary> /// <remarks>https://www.hl7.org/fhir/v2/0490</remarks> public enum CodeSpecimenRejectReason { /// <summary> /// EX - Expired. /// </summary> Expired, /// <summary> /// QS - Quantity not sufficient. /// </summary> QuantityNotSufficient, /// <summary> /// RA - Missing patient ID number. /// </summary> MissingPatientIdNumber, /// <summary> /// RB - Broken container. /// </summary> BrokenContainer, /// <summary> /// RC - Clotting. /// </summary> Clotting, /// <summary> /// RD - Missing collection date. /// </summary> MissingCollectionDate, /// <summary> /// RE - Missing patient name. /// </summary> MissingPatientName, /// <summary> /// RH - Hemolysis. /// </summary> Hemolysis, /// <summary> /// RI - Identification problem. /// </summary> IdentificationProblem, /// <summary> /// RM - Labeling. /// </summary> Labeling, /// <summary> /// RN - Contamination. /// </summary> Contamination, /// <summary> /// RP - Missing phlebotomist ID. /// </summary> MissingPhlebotomistId, /// <summary> /// RR - Improper storage. /// </summary> ImproperStorage, /// <summary> /// RS - Name misspelling. /// </summary> NameMisspelling } }
23.265823
59
0.437432
[ "MIT" ]
davebronson/clear-hl7-net
src/ClearHl7.Codes/V281/CodeSpecimenRejectReason.cs
1,840
C#
using Microsoft.CodeAnalysis; using System.Collections.Generic; using System; using System.Linq; using TypeRight.CodeModel; namespace TypeRight.Workspaces.Parsing { /// <summary> /// Parses a solution for script classes and enums /// </summary> public class ProjectParser : ITypeIterator { private ITypeVisitor _visitor; /// <summary> /// The current workspace /// </summary> private readonly Workspace _workspace; /// <summary> /// The path of the project currently being processed /// </summary> private readonly ProjectId _projectId; /// <summary> /// Creates a new solution parser /// </summary> /// <param name="workspace">The solution workspace</param> /// <param name="projId">The project ID we are parsing</param> public ProjectParser(Workspace workspace, ProjectId projId) { _workspace = workspace; _projectId = projId; } /// <summary> /// Iterates the types in the project /// </summary> /// <param name="visitor">The visitor for the iterator</param> public void IterateTypes(ITypeVisitor visitor) { _visitor = visitor; Solution sol = _workspace.CurrentSolution; ProjectDependencyGraph graph = sol.GetProjectDependencyGraph(); // Typescript projects show up with the same project path, so make sure it supports compilation Project mainProj = sol.Projects.Where(proj => proj.Id.Equals(_projectId) && proj.SupportsCompilation).FirstOrDefault(); if (mainProj == null) { throw new InvalidOperationException($"Project with path {_projectId} does not exist."); } // Get a list of all classes being extracted Dictionary<string, Compilation> compilations = new Dictionary<string, Compilation>(); AddCompiledProjects(sol, new List<ProjectId> { mainProj.Id }, compilations); AddCompiledProjects(sol, graph.GetProjectsThatThisProjectDirectlyDependsOn(mainProj.Id), compilations); AddCompiledProjects(sol, graph.GetProjectsThatThisProjectTransitivelyDependsOn(mainProj.Id), compilations); foreach (Compilation comp in compilations.Values) { CompilationParser parser = new CompilationParser(comp); parser.IterateTypes(_visitor); } } /// <summary> /// Adds the list of project IDs to the compilation index /// </summary> /// <param name="sol">The solution</param> /// <param name="projIds">The project IDs to add</param> /// <param name="compIndex">The list of compiled projects</param> private void AddCompiledProjects(Solution sol, IEnumerable<ProjectId> projIds, Dictionary<string, Compilation> compIndex) { foreach (ProjectId projId in projIds) { if (compIndex.ContainsKey(projId.Id.ToString())) { continue; } Project proj = sol.GetProject(projId); if (!proj.SupportsCompilation) { continue; } compIndex.Add(projId.Id.ToString(), proj.GetCompilationAsync().Result); } } } }
30.702128
123
0.712058
[ "MIT" ]
someguy20336/TypeRight
src/TypeRight.Workspaces/Parsing/ProjectParser.cs
2,888
C#
/* Copyright (c) 2006-2011 Skype Limited. All Rights Reserved Ported to C# by Logan Stromberg Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Internet Society, IETF or IETF Trust, nor the names of specific contributors, may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Concentus.Silk { using Concentus.Common; using Concentus.Common.CPlusPlus; using Concentus.Silk.Enums; using Concentus.Silk.Structs; using System; using System.Diagnostics; internal static class DecodeAPI { /// <summary> /// Reset decoder state /// </summary> /// <param name="decState">I/O Stat</param> /// <returns>Returns error code</returns> internal static int silk_InitDecoder(SilkDecoder decState) { /* Reset decoder */ decState.Reset(); int n, ret = SilkError.SILK_NO_ERROR; SilkChannelDecoder[] channel_states = decState.channel_state; for (n = 0; n < SilkConstants.DECODER_NUM_CHANNELS; n++) { ret = channel_states[n].silk_init_decoder(); } decState.sStereo.Reset(); /* Not strictly needed, but it's cleaner that way */ decState.prev_decode_only_middle = 0; return ret; } /* Decode a frame */ internal static int silk_Decode( /* O Returns error code */ SilkDecoder psDec, /* I/O State */ DecControlState decControl, /* I/O Control Structure */ int lostFlag, /* I 0: no loss, 1 loss, 2 decode fec */ int newPacketFlag, /* I Indicates first decoder call for this packet */ EntropyCoder psRangeDec, /* I/O Compressor data structure */ short[] samplesOut, /* O Decoded output speech vector */ int samplesOut_ptr, out int nSamplesOut /* O Number of samples decoded */ ) { int i, n, decode_only_middle = 0, ret = SilkError.SILK_NO_ERROR; int LBRR_symbol; BoxedValueInt nSamplesOutDec = new BoxedValueInt(); short[] samplesOut_tmp; int[] samplesOut_tmp_ptrs = new int[2]; short[] samplesOut1_tmp_storage1; short[] samplesOut1_tmp_storage2; short[] samplesOut2_tmp; int[] MS_pred_Q13 = new int[] { 0, 0 }; short[] resample_out; int resample_out_ptr; SilkChannelDecoder[] channel_state = psDec.channel_state; int has_side; int stereo_to_mono; int delay_stack_alloc; nSamplesOut = 0; Inlines.OpusAssert(decControl.nChannelsInternal == 1 || decControl.nChannelsInternal == 2); /**********************************/ /* Test if first frame in payload */ /**********************************/ if (newPacketFlag != 0) { for (n = 0; n < decControl.nChannelsInternal; n++) { channel_state[n].nFramesDecoded = 0; /* Used to count frames in packet */ } } /* If Mono . Stereo transition in bitstream: init state of second channel */ if (decControl.nChannelsInternal > psDec.nChannelsInternal) { ret += channel_state[1].silk_init_decoder(); } stereo_to_mono = (decControl.nChannelsInternal == 1 && psDec.nChannelsInternal == 2 && (decControl.internalSampleRate == 1000 * channel_state[0].fs_kHz)) ? 1 : 0; if (channel_state[0].nFramesDecoded == 0) { for (n = 0; n < decControl.nChannelsInternal; n++) { int fs_kHz_dec; if (decControl.payloadSize_ms == 0) { /* Assuming packet loss, use 10 ms */ channel_state[n].nFramesPerPacket = 1; channel_state[n].nb_subfr = 2; } else if (decControl.payloadSize_ms == 10) { channel_state[n].nFramesPerPacket = 1; channel_state[n].nb_subfr = 2; } else if (decControl.payloadSize_ms == 20) { channel_state[n].nFramesPerPacket = 1; channel_state[n].nb_subfr = 4; } else if (decControl.payloadSize_ms == 40) { channel_state[n].nFramesPerPacket = 2; channel_state[n].nb_subfr = 4; } else if (decControl.payloadSize_ms == 60) { channel_state[n].nFramesPerPacket = 3; channel_state[n].nb_subfr = 4; } else { Inlines.OpusAssert(false); return SilkError.SILK_DEC_INVALID_FRAME_SIZE; } fs_kHz_dec = (decControl.internalSampleRate >> 10) + 1; if (fs_kHz_dec != 8 && fs_kHz_dec != 12 && fs_kHz_dec != 16) { Inlines.OpusAssert(false); return SilkError.SILK_DEC_INVALID_SAMPLING_FREQUENCY; } ret += channel_state[n].silk_decoder_set_fs(fs_kHz_dec, decControl.API_sampleRate); } } if (decControl.nChannelsAPI == 2 && decControl.nChannelsInternal == 2 && (psDec.nChannelsAPI == 1 || psDec.nChannelsInternal == 1)) { Arrays.MemSetShort(psDec.sStereo.pred_prev_Q13, 0, 2); Arrays.MemSetShort(psDec.sStereo.sSide, 0, 2); channel_state[1].resampler_state.Assign(channel_state[0].resampler_state); } psDec.nChannelsAPI = decControl.nChannelsAPI; psDec.nChannelsInternal = decControl.nChannelsInternal; if (decControl.API_sampleRate > (int)SilkConstants.MAX_API_FS_KHZ * 1000 || decControl.API_sampleRate < 8000) { ret = SilkError.SILK_DEC_INVALID_SAMPLING_FREQUENCY; return (ret); } if (lostFlag != DecoderAPIFlag.FLAG_PACKET_LOST && channel_state[0].nFramesDecoded == 0) { /* First decoder call for this payload */ /* Decode VAD flags and LBRR flag */ for (n = 0; n < decControl.nChannelsInternal; n++) { for (i = 0; i < channel_state[n].nFramesPerPacket; i++) { channel_state[n].VAD_flags[i] = psRangeDec.dec_bit_logp(1); } channel_state[n].LBRR_flag = psRangeDec.dec_bit_logp(1); } /* Decode LBRR flags */ for (n = 0; n < decControl.nChannelsInternal; n++) { Arrays.MemSetInt(channel_state[n].LBRR_flags, 0, SilkConstants.MAX_FRAMES_PER_PACKET); if (channel_state[n].LBRR_flag != 0) { if (channel_state[n].nFramesPerPacket == 1) { channel_state[n].LBRR_flags[0] = 1; } else { LBRR_symbol = psRangeDec.dec_icdf(Tables.silk_LBRR_flags_iCDF_ptr[channel_state[n].nFramesPerPacket - 2], 8) + 1; for (i = 0; i < channel_state[n].nFramesPerPacket; i++) { channel_state[n].LBRR_flags[i] = Inlines.silk_RSHIFT(LBRR_symbol, i) & 1; } } } } if (lostFlag == DecoderAPIFlag.FLAG_DECODE_NORMAL) { /* Regular decoding: skip all LBRR data */ for (i = 0; i < channel_state[0].nFramesPerPacket; i++) { for (n = 0; n < decControl.nChannelsInternal; n++) { if (channel_state[n].LBRR_flags[i] != 0) { short[] pulses = new short[SilkConstants.MAX_FRAME_LENGTH]; int condCoding; if (decControl.nChannelsInternal == 2 && n == 0) { Stereo.silk_stereo_decode_pred(psRangeDec, MS_pred_Q13); if (channel_state[1].LBRR_flags[i] == 0) { BoxedValueInt decodeOnlyMiddleBoxed = new BoxedValueInt(decode_only_middle); Stereo.silk_stereo_decode_mid_only(psRangeDec, decodeOnlyMiddleBoxed); decode_only_middle = decodeOnlyMiddleBoxed.Val; } } /* Use conditional coding if previous frame available */ if (i > 0 && (channel_state[n].LBRR_flags[i - 1] != 0)) { condCoding = SilkConstants.CODE_CONDITIONALLY; } else { condCoding = SilkConstants.CODE_INDEPENDENTLY; } DecodeIndices.silk_decode_indices(channel_state[n], psRangeDec, i, 1, condCoding); DecodePulses.silk_decode_pulses(psRangeDec, pulses, channel_state[n].indices.signalType, channel_state[n].indices.quantOffsetType, channel_state[n].frame_length); } } } } } /* Get MS predictor index */ if (decControl.nChannelsInternal == 2) { if (lostFlag == DecoderAPIFlag.FLAG_DECODE_NORMAL || (lostFlag == DecoderAPIFlag.FLAG_DECODE_LBRR && channel_state[0].LBRR_flags[channel_state[0].nFramesDecoded] == 1)) { Stereo.silk_stereo_decode_pred(psRangeDec, MS_pred_Q13); /* For LBRR data, decode mid-only flag only if side-channel's LBRR flag is false */ if ((lostFlag == DecoderAPIFlag.FLAG_DECODE_NORMAL && channel_state[1].VAD_flags[channel_state[0].nFramesDecoded] == 0) || (lostFlag == DecoderAPIFlag.FLAG_DECODE_LBRR && channel_state[1].LBRR_flags[channel_state[0].nFramesDecoded] == 0)) { BoxedValueInt decodeOnlyMiddleBoxed = new BoxedValueInt(decode_only_middle); Stereo.silk_stereo_decode_mid_only(psRangeDec, decodeOnlyMiddleBoxed); decode_only_middle = decodeOnlyMiddleBoxed.Val; } else { decode_only_middle = 0; } } else { for (n = 0; n < 2; n++) { MS_pred_Q13[n] = psDec.sStereo.pred_prev_Q13[n]; } } } /* Reset side channel decoder prediction memory for first frame with side coding */ if (decControl.nChannelsInternal == 2 && decode_only_middle == 0 && psDec.prev_decode_only_middle == 1) { Arrays.MemSetShort(psDec.channel_state[1].outBuf, 0, SilkConstants.MAX_FRAME_LENGTH + 2 * SilkConstants.MAX_SUB_FRAME_LENGTH); Arrays.MemSetInt(psDec.channel_state[1].sLPC_Q14_buf, 0, SilkConstants.MAX_LPC_ORDER); psDec.channel_state[1].lagPrev = 100; psDec.channel_state[1].LastGainIndex = 10; psDec.channel_state[1].prevSignalType = SilkConstants.TYPE_NO_VOICE_ACTIVITY; psDec.channel_state[1].first_frame_after_reset = 1; } /* Check if the temp buffer fits into the output PCM buffer. If it fits, we can delay allocating the temp buffer until after the SILK peak stack usage. We need to use a < and not a <= because of the two extra samples. */ delay_stack_alloc = (decControl.internalSampleRate * decControl.nChannelsInternal < decControl.API_sampleRate * decControl.nChannelsAPI) ? 1 : 0; if (delay_stack_alloc != 0) { samplesOut_tmp = samplesOut; samplesOut_tmp_ptrs[0] = samplesOut_ptr; samplesOut_tmp_ptrs[1] = samplesOut_ptr + channel_state[0].frame_length + 2; } else { samplesOut1_tmp_storage1 = new short[decControl.nChannelsInternal * (channel_state[0].frame_length + 2)]; samplesOut_tmp = samplesOut1_tmp_storage1; samplesOut_tmp_ptrs[0] = 0; samplesOut_tmp_ptrs[1] = channel_state[0].frame_length + 2; } if (lostFlag == DecoderAPIFlag.FLAG_DECODE_NORMAL) { has_side = (decode_only_middle == 0) ? 1 : 0; } else { has_side = (psDec.prev_decode_only_middle == 0 || (decControl.nChannelsInternal == 2 && lostFlag == DecoderAPIFlag.FLAG_DECODE_LBRR && channel_state[1].LBRR_flags[channel_state[1].nFramesDecoded] == 1)) ? 1 : 0; } /* Call decoder for one frame */ for (n = 0; n < decControl.nChannelsInternal; n++) { if (n == 0 || (has_side != 0)) { int FrameIndex; int condCoding; FrameIndex = channel_state[0].nFramesDecoded - n; /* Use independent coding if no previous frame available */ if (FrameIndex <= 0) { condCoding = SilkConstants.CODE_INDEPENDENTLY; } else if (lostFlag == DecoderAPIFlag.FLAG_DECODE_LBRR) { condCoding = (channel_state[n].LBRR_flags[FrameIndex - 1] != 0) ? SilkConstants.CODE_CONDITIONALLY : SilkConstants.CODE_INDEPENDENTLY; } else if (n > 0 && (psDec.prev_decode_only_middle != 0)) { /* If we skipped a side frame in this packet, we don't need LTP scaling; the LTP state is well-defined. */ condCoding = SilkConstants.CODE_INDEPENDENTLY_NO_LTP_SCALING; } else { condCoding = SilkConstants.CODE_CONDITIONALLY; } ret += channel_state[n].silk_decode_frame(psRangeDec, samplesOut_tmp, samplesOut_tmp_ptrs[n] + 2, nSamplesOutDec, lostFlag, condCoding); } else { Arrays.MemSetWithOffset<short>(samplesOut_tmp, 0, samplesOut_tmp_ptrs[n] + 2, nSamplesOutDec.Val); } channel_state[n].nFramesDecoded++; } if (decControl.nChannelsAPI == 2 && decControl.nChannelsInternal == 2) { /* Convert Mid/Side to Left/Right */ Stereo.silk_stereo_MS_to_LR(psDec.sStereo, samplesOut_tmp, samplesOut_tmp_ptrs[0], samplesOut_tmp, samplesOut_tmp_ptrs[1], MS_pred_Q13, channel_state[0].fs_kHz, nSamplesOutDec.Val); } else { /* Buffering */ Array.Copy(psDec.sStereo.sMid, 0, samplesOut_tmp, samplesOut_tmp_ptrs[0], 2); Array.Copy(samplesOut_tmp, samplesOut_tmp_ptrs[0] + nSamplesOutDec.Val, psDec.sStereo.sMid, 0, 2); } /* Number of output samples */ nSamplesOut = Inlines.silk_DIV32(nSamplesOutDec.Val * decControl.API_sampleRate, Inlines.silk_SMULBB(channel_state[0].fs_kHz, 1000)); /* Set up pointers to temp buffers */ if (decControl.nChannelsAPI == 2) { samplesOut2_tmp = new short[nSamplesOut]; resample_out = samplesOut2_tmp; resample_out_ptr = 0; } else { resample_out = samplesOut; resample_out_ptr = samplesOut_ptr; } if (delay_stack_alloc != 0) { samplesOut1_tmp_storage2 = new short[decControl.nChannelsInternal * (channel_state[0].frame_length + 2)]; Array.Copy(samplesOut, samplesOut_ptr, samplesOut1_tmp_storage2, 0, decControl.nChannelsInternal * (channel_state[0].frame_length + 2)); samplesOut_tmp = samplesOut1_tmp_storage2; samplesOut_tmp_ptrs[0] = 0; samplesOut_tmp_ptrs[1] = channel_state[0].frame_length + 2; } for (n = 0; n < Inlines.silk_min(decControl.nChannelsAPI, decControl.nChannelsInternal); n++) { /* Resample decoded signal to API_sampleRate */ ret += Resampler.silk_resampler(channel_state[n].resampler_state, resample_out, resample_out_ptr, samplesOut_tmp, samplesOut_tmp_ptrs[n] + 1, nSamplesOutDec.Val); /* Interleave if stereo output and stereo stream */ if (decControl.nChannelsAPI == 2) { int nptr = samplesOut_ptr + n; for (i = 0; i < nSamplesOut; i++) { samplesOut[nptr + 2 * i] = resample_out[resample_out_ptr + i]; } } } /* Create two channel output from mono stream */ if (decControl.nChannelsAPI == 2 && decControl.nChannelsInternal == 1) { if (stereo_to_mono != 0) { /* Resample right channel for newly collapsed stereo just in case we weren't doing collapsing when switching to mono */ ret += Resampler.silk_resampler(channel_state[1].resampler_state, resample_out, resample_out_ptr, samplesOut_tmp, samplesOut_tmp_ptrs[0] + 1, nSamplesOutDec.Val); for (i = 0; i < nSamplesOut; i++) { samplesOut[samplesOut_ptr + 1 + 2 * i] = resample_out[resample_out_ptr + i]; } } else { for (i = 0; i < nSamplesOut; i++) { samplesOut[samplesOut_ptr + 1 + 2 * i] = samplesOut[samplesOut_ptr + 2 * i]; } } } /* Export pitch lag, measured at 48 kHz sampling rate */ if (channel_state[0].prevSignalType == SilkConstants.TYPE_VOICED) { int[] mult_tab = { 6, 4, 3 }; decControl.prevPitchLag = channel_state[0].lagPrev * mult_tab[(channel_state[0].fs_kHz - 8) >> 2]; } else { decControl.prevPitchLag = 0; } if (lostFlag == DecoderAPIFlag.FLAG_PACKET_LOST) { /* On packet loss, remove the gain clamping to prevent having the energy "bounce back" if we lose packets when the energy is going down */ for (i = 0; i < psDec.nChannelsInternal; i++) psDec.channel_state[i].LastGainIndex = 10; } else { psDec.prev_decode_only_middle = decode_only_middle; } return ret; } } }
48.599567
198
0.499132
[ "MIT" ]
ActualMandM/VGAudio
src/VGAudio/Codecs/Opus/Silk/DecodeAPI.cs
21,994
C#
using System; using Android.App; using Android.Content; using Android.OS; using Android.Support.V7.App; using Android.Views; namespace Acr.UserDialogs.Fragments { public abstract class AbstractAppCompatDialogFragment<T> : AppCompatDialogFragment where T : class { public T Config { get; set; } public override void OnSaveInstanceState(Bundle bundle) { base.OnSaveInstanceState(bundle); ConfigStore.Instance.Store(bundle, this.Config); } public override Dialog OnCreateDialog(Bundle bundle) { if (this.Config == null) this.Config = ConfigStore.Instance.Pop<T>(bundle); var dialog = this.CreateDialog(this.Config); this.SetDialogDefaults(dialog); return dialog; } protected virtual void SetDialogDefaults(Dialog dialog) { dialog.Window.SetSoftInputMode(SoftInput.StateVisible); dialog.SetCancelable(false); dialog.SetCanceledOnTouchOutside(false); dialog.KeyPress += this.OnKeyPress; // TODO: fix for immersive mode - http://stackoverflow.com/questions/22794049/how-to-maintain-the-immersive-mode-in-dialogs/23207365#23207365 //dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); } public override void OnDetach() { base.OnDetach(); if (this.Dialog != null) this.Dialog.KeyPress -= this.OnKeyPress; } protected virtual void OnKeyPress(object sender, DialogKeyEventArgs args) { } protected abstract Dialog CreateDialog(T config); protected AppCompatActivity AppCompatActivity => this.Activity as AppCompatActivity; } public abstract class AbstractDialogFragment<T> : DialogFragment where T : class { public T Config { get; set; } public override void OnSaveInstanceState(Bundle bundle) { base.OnSaveInstanceState(bundle); ConfigStore.Instance.Store(bundle, this.Config); } public override Dialog OnCreateDialog(Bundle bundle) { if (this.Config == null) this.Config = ConfigStore.Instance.Pop<T>(bundle); var dialog = this.CreateDialog(this.Config); this.SetDialogDefaults(dialog); return dialog; } public override void OnDetach() { base.OnDetach(); if (this.Dialog != null) this.Dialog.KeyPress -= this.OnKeyPress; } protected virtual void SetDialogDefaults(Dialog dialog) { dialog.Window.SetSoftInputMode(SoftInput.StateVisible); dialog.SetCancelable(false); dialog.SetCanceledOnTouchOutside(false); dialog.KeyPress += this.OnKeyPress; } protected virtual void OnKeyPress(object sender, DialogKeyEventArgs args) { } protected abstract Dialog CreateDialog(T config); } }
28.369369
153
0.622737
[ "MIT" ]
srxp10/userdialogs
src/Acr.UserDialogs.Android/Fragments/AbstractDialogFragment.cs
3,149
C#
using System; using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using J = Newtonsoft.Json.JsonPropertyAttribute; using R = Newtonsoft.Json.Required; using N = Newtonsoft.Json.NullValueHandling; using System.IO; using System.Diagnostics; using System.Net; using System.Linq; using System.Threading.Tasks; namespace PrismarineDataGenerator { public class Program { public static void Main(string[] args) { Console.WriteLine("Press Enter to Generate CS files, P + Enter generates MC-data files"); string s = Console.ReadLine(); if (s == "P") UpdatePrismarine(); else if (s == "") GenerateFiles(); else throw new ArgumentException(); } private static void GenerateFiles() { throw new NotImplementedException(); } private static void UpdatePrismarine() { GetServerReports(out Dictionary<string, MinecraftBlock> Blocks, out Dictionary<string, Item> Items); GetLatestPrismarine(out List<PrismarineBlock> PrismarineBlocks, out List<PrismarineItem> PrismarineItems); List<PrismarineBlock> newBlocks = new List<PrismarineBlock>(); List<PrismarineItem> newItems = new List<PrismarineItem>(); foreach (var block in Blocks) { var pb = PrismarineBlocks.First(x => x.name == block.Key); newBlocks.Add(new PrismarineBlock() { BlockId = block.Key, boundingBox = pb.boundingBox, Diggable = pb.Diggable, displayName = pb.displayName, Drops = null, //TODO: Add Linking EmitLight = pb.EmitLight, FilterLight = pb.FilterLight, Hardness = pb.Hardness, Properties = MakePBProperties(block.Value.Properties), States = block.Value.States, Transparent = pb.Transparent }); } foreach (var item in Items) { } } private static Dictionary<String, PrismarineType> MakePBProperties(Dictionary<String, String[]> properties) { var res = new Dictionary<string, PrismarineType>(); foreach (var v in properties) { res.Add(v.Key, GetPrismarineType(v.Value)); } return res; } private static PrismarineType GetPrismarineType(String[] value) { if (value.All(x => Int32.TryParse(x, out int no))) return PrismarineType.int32; if (value.All(x => Boolean.TryParse(x, out bool no))) return PrismarineType.Bool; return PrismarineType.Enum; } private static void GetLatestPrismarine(out List<PrismarineBlock> prismarineBlocks, out List<PrismarineItem> prismarineItems) { throw new NotImplementedException(); } private static void GetServerReports(out Dictionary<String, MinecraftBlock> blocks, out Dictionary<String, Item> items) { Console.WriteLine("Loading..."); var ResourcesPath = Path.GetFullPath("./Resources"); while (Directory.Exists(ResourcesPath)) try { Directory.Delete(ResourcesPath, true); } catch { } Directory.CreateDirectory(ResourcesPath); Console.WriteLine("Downloading Original Server....."); Console.WriteLine("=> This is needed to Get the Blocks"); SaveServerToFile(ResourcesPath + "/server.jar"); Console.WriteLine("Downloaded Server, Running Generator"); //Server shoud generate reports Process process = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.FileName = "cmd.exe"; startInfo.Arguments = $"/C cd {ResourcesPath}/ && java -cp server.jar net.minecraft.data.Main --reports"; process.StartInfo = startInfo; Console.WriteLine("----------------[START OF ORIGINAL SERVER CONSOLE]----------------"); process.Start(); Task.Delay(25 * 1000).Wait(); // ... Not nice, but .WaitForExit() isnt working anymore for some reason Console.WriteLine("-----------------[END OF ORIGINAL SERVER CONSOLE]-----------------"); Console.WriteLine("Copying Files"); foreach (string file in Directory.EnumerateFiles(ResourcesPath + "/generated/reports/")) { File.Move(file, ResourcesPath + "/" + Path.GetFileName(file)); } Console.WriteLine("Deleting Cache"); while (Directory.Exists(ResourcesPath + "/generated/")) try { Directory.Delete(ResourcesPath + "/generated/", true); } catch { } while (Directory.Exists(ResourcesPath + "/logs/")) try { Directory.Delete(ResourcesPath + "/logs/", true); } catch { } Console.WriteLine("Done Loading! We got the Files"); blocks = Converters.BlocksFromJson(File.ReadAllText($"{ResourcesPath}/blocks.json")); items = Converters.ItemsFromJson(File.ReadAllText($"{ResourcesPath}/items.json")); } private const string ServerURL = "https://launcher.mojang.com/mc/game/18w22c/server/d66173b86e26e6835e36c63eb2828652186a4698/server.jar"; public static void SaveServerToFile(string path) { var p = Path.GetFullPath(path); using (var c = new WebClient()) { c.DownloadFile(ServerURL, p); } } public class PrismarineItem { [J("id")] public int ProtocolId { get; set; } [J("displayName")] public string DisplayName { get; set; } [J("stackSize")] public int StackSize { get; set; } [J("name")] public string Name { get; set; } } public class PrismarineBlock { [J("id")] public string BlockId { get; set; } [J("displayName")] public string displayName { get; set; } // there is no name, only used for back-porting [J("name", DefaultValueHandling = DefaultValueHandling.Ignore)] public string name { get; set; } [J("hardness")] public int Hardness { get; set; } // Such a thing as stack size is simply not a thing. replaced by Item [J("diggable")] public bool Diggable { get; set; } [J("boundingBox")] public string boundingBox { get; set; } [J("drops")] public string Drops { get; set; } [J("transparent")] public bool Transparent { get; set; } [J("emitLight")] public int EmitLight { get; set; } [J("filterLight")] public int FilterLight { get; set; } [J("properties")] public Dictionary<string, PrismarineType> Properties { get; set; } [J("states")] public BlockSubState[] States { get; set; } } public enum PrismarineType { Enum, int32, Bool, } public partial class BlockSubState { [J("properties")] public Dictionary<string, string> Properties { get; set; } [J("id")] public long Id { get; set; } [J("default", NullValueHandling = N.Include)] public bool Default { get; set; } } public partial class MinecraftBlock { [J("states")] public BlockSubState[] States { get; set; } [J("properties")] public Dictionary<string, string[]> Properties { get; set; } } public partial class Converters { public static Dictionary<string, MinecraftBlock> BlocksFromJson(string json) => JsonConvert.DeserializeObject<Dictionary<string, MinecraftBlock>>(json, Converter.Settings); public static Dictionary<string, Item> ItemsFromJson(string json) => JsonConvert.DeserializeObject<Dictionary<string, Item>>(json, Converter.Settings); } public class Item { [J("protocol_id")] public int Id { get; set; } } public static class Converter { public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore, DateParseHandling = DateParseHandling.None, Converters = { new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } }, }; } } }
40.408889
184
0.563792
[ "MIT" ]
SharpenedMinecraft/SM1
PrismarineDataGenerator/Program.cs
9,094
C#
using fyiReporting.RDL; /* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. 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. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Collections.Generic; using System.ComponentModel; // need this for the properties metadata using System.Drawing.Design; using System.Globalization; using System.Windows.Forms; using System.Windows.Forms.Design; using System.Xml; namespace fyiReporting.RdlDesign { /// <summary> /// PropertyImage - The Image specific Properties /// </summary> internal class PropertyImage : PropertyReportItem { internal PropertyImage(DesignXmlDraw d, DesignCtl dc, List<XmlNode> ris) : base(d, dc, ris) { } [LocalizedCategory("Image")] [LocalizedDisplayName("Image_Image")] [LocalizedDescription("Image_Image")] public PropertyImageI Image { get { return new PropertyImageI(this); } } } [TypeConverter(typeof(PropertyImageConverter))] [Editor(typeof(PropertyImageUIEditor), typeof(System.Drawing.Design.UITypeEditor))] internal class PropertyImageI : IReportItem { PropertyImage _pi; internal PropertyImageI(PropertyImage pi) { _pi = pi; } [RefreshProperties(RefreshProperties.Repaint)] [TypeConverter(typeof(ImageSourceConverter))] [LocalizedDisplayName("ImageI_Source")] [LocalizedDescription("ImageI_Source")] public string Source { get { return _pi.GetValue("Source", "External"); } set { _pi.SetValue("Source", value); } } [RefreshProperties(RefreshProperties.Repaint)] [LocalizedDisplayName("ImageI_Value")] [LocalizedDescription("ImageI_Value")] public PropertyExpr Value { get { return new PropertyExpr(_pi.GetValue("Value", "")); } set { _pi.SetValue("Value", value.Expression); } } [RefreshProperties(RefreshProperties.Repaint)] [TypeConverter(typeof(ImageMIMETypeConverter))] [LocalizedDisplayName("ImageI_MIMEType")] [LocalizedDescription("ImageI_MIMEType")] public string MIMEType { get { return _pi.GetValue("MIMEType", ""); } set { if (string.Compare(this.Source.Trim(), "database", true) == 0) throw new ArgumentException("MIMEType isn't relevent when Source isn't Database."); _pi.SetValue("MIMEType", value); } } [LocalizedDisplayName("ImageI_Sizing")] [LocalizedDescription("ImageI_Sizing")] public ImageSizingEnum Sizing { get { string s = _pi.GetValue("Sizing", "AutoSize"); return ImageSizing.GetStyle(s); } set { _pi.SetValue("Sizing", value.ToString()); } } public override string ToString() { string s = this.Source; string v = ""; if (s.ToLower().Trim() != "none") v = this.Value.Expression; return string.Format("{0} {1}", s, v); } #region IReportItem Members public PropertyReportItem GetPRI() { return this._pi; } #endregion } #region ImageConverter internal class PropertyImageConverter : ExpandableObjectConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(PropertyImageI)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is PropertyImage) { PropertyImageI pi = value as PropertyImageI; return pi.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } #endregion #region UIEditor internal class PropertyImageUIEditor : UITypeEditor { internal PropertyImageUIEditor() { } public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if ((context == null) || (provider == null)) return base.EditValue(context, provider, value); // Access the Property Browser's UI display service IWindowsFormsEditorService editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (editorService == null) return base.EditValue(context, provider, value); // Create an instance of the UI editor form IReportItem iri = context.Instance as IReportItem; if (iri == null) return base.EditValue(context, provider, value); PropertyImage pre = iri.GetPRI() as PropertyImage; PropertyImageI pbi = value as PropertyImageI; if (pbi == null) return base.EditValue(context, provider, value); using (SingleCtlDialog scd = new SingleCtlDialog(pre.DesignCtl, pre.Draw, pre.Nodes, SingleCtlTypeEnum.ImageCtl, null)) { /////// // Display the UI editor dialog if (editorService.ShowDialog(scd) == DialogResult.OK) { // Return the new property value from the UI editor form return new PropertyImageI(pre); } return base.EditValue(context, provider, value); } } } #endregion }
30.945148
103
0.578266
[ "Apache-2.0" ]
Art8m/My-FyiReporting
RdlDesign/RdlProperties/PropertyImage.cs
7,334
C#
//Copyright 2014 Spin Services Limited //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 SS.Integration.Adapter.Diagnostics.Model.Service.Model.Interface; namespace SS.Integration.Adapter.Diagnostics.Model.Service.Interface { public interface ISupervisorStreamingService { void OnSportUpdate(ISportDetails sport); void OnFixtureUpdate(IFixtureDetails fixture); void OnAdapterUpdate(IAdapterStatus adapter); void OnError(IProcessingEntryError update); } }
33.466667
74
0.763944
[ "Apache-2.0" ]
ChrisL89/SS.Integration.Adapter
SS.Integration.Adapter.Diagnostics.Model/Service/Interface/ISupervisorStreamingService.cs
1,006
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Tilemaps; using System.Threading; using System.Threading.Tasks; using UnityEngine.UI; using UnityEngine.Networking; using System.Collections.Concurrent; using System; using System.Linq; using LiteDB; using System.IO; public class WorldManager : NetworkBehaviour { public WorldDataConst.WorldData worldData; public WorldDataConst.WorldData newWorldData_Generate; public int[] generationList = null; bool isNewMapAppered = false; public bool isReady = false; public string current_uuid; public void Update() { if ((worldData != null) && (isNewMapAppered)) { if (worldData.mapPicture == null) { worldData.mapPicture = WorldGenerator.createMapPicture(worldData); } foreach (KeyValuePair<NetworkInstanceId,NetworkIdentity> dict in ClientScene.objects) { NetworkIdentity networkIdentity = dict.Value; PlayerController playerCtr=networkIdentity.GetComponent<PlayerController>(); if (playerCtr!=null) { playerCtr.BroadcastNewMap(worldData.width, worldData.height); } } isNewMapAppered = false; } } public void storeNemMap(string name) { newWorldData_Generate.name = name; WorldDataUtility.storeNemMap(newWorldData_Generate, name); current_uuid = newWorldData_Generate.uuid; } public List<PlayerController.MapElement> loadExistMapList() { return WorldDataUtility.loadExistMapList(); } public void loadExistMapDatas(PlayerController.MapElement element) { worldData = WorldDataUtility.loadExistMapDatas(element); preNotifyNewMap(); current_uuid = element.pathName; } public void loadNewMapDatas() { if (newWorldData_Generate != null) { worldData = newWorldData_Generate; preNotifyNewMap(); } } //サーバでの世界データ作成 [Server] public async void Cmd_Generate_Async(string name, string seeds, int width, int height) { var context = SynchronizationContext.Current; await Task.Run(() => { worldData = WorldGenerator.GenerateMap(name,seeds,width,height); newWorldData_Generate = worldData; preNotifyNewMap(); current_uuid = newWorldData_Generate.uuid; Debug.Log("Generate End!"); }); } public void preNotifyNewMap() { int[] generationList_tmp = Enumerable.Repeat(0, (worldData.width / PlayerController.TransferSize) * (worldData.height / PlayerController.TransferSize)).ToArray(); generationList = generationList_tmp; isNewMapAppered = true; } public void setReadyToStart() { isReady = true; newWorldData_Generate = null; foreach (KeyValuePair<NetworkInstanceId, NetworkIdentity> dict in ClientScene.objects) { NetworkIdentity networkIdentity = dict.Value; PlayerController playerCtr = networkIdentity.GetComponent<PlayerController>(); if (playerCtr != null) { playerCtr.TargetDispTopMenuPanel(playerCtr.connectionToClient); playerCtr.Target_CloseInformationPanel(playerCtr.connectionToClient); } } } }
31.160714
170
0.645559
[ "Apache-2.0" ]
MypaceEngine/GreedPlanet
Assets/Scripts/WorldManager.cs
3,516
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace _02.SimpleWebFormsApp.Account { public partial class Confirm { /// <summary> /// successPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder successPanel; /// <summary> /// login control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.HyperLink login; /// <summary> /// errorPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder errorPanel; } }
32.409091
84
0.509116
[ "MIT" ]
ni4ka7a/TelerikAcademyHomeworks
ASP.NET-WebForms/02.WebFormsIntro/02.SimpleWebFormsApp/Account/Confirm.aspx.designer.cs
1,428
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace craftersmine.Valknut.Launcher.Wpf { public sealed class ServerHelper { } }
16.538462
43
0.75814
[ "MIT" ]
craftersmine/Valknut
craftersmine.Valknut.Launcher.Wpf/ServerHelper.cs
217
C#
using System.Linq; using System.Xml.Linq; using clempaul.Dreamhost.ResponseData; using System.Collections.Generic; namespace clempaul.Dreamhost { public class AccountRequests { DreamhostAPI api = null; internal AccountRequests(DreamhostAPI api) { this.api = api; } #region account-domain_usage public IEnumerable<DomainUsage> DomainUsage() { XDocument response = api.SendCommand("account-domain_usage"); // Handle Response return from data in response.Element("dreamhost").Elements("data") select new DomainUsage { domain = data.Element("domain").AsString(), type = data.Element("type").AsString(), bw = data.Element("bw").AsInt() }; } #endregion #region account-status public IEnumerable<KeyValuePair<string,XElement>> Status() { XDocument response = api.SendCommand("account-status"); // Handle Response return from data in response.Element("dreamhost").Elements("data") select new KeyValuePair<string, XElement> (data.Element("key").AsString(), data.Element("value")); } #endregion #region account-user_usage public IEnumerable<UserUsage> UserUsage() { XDocument response = api.SendCommand("account-user_usage"); // Handle Response return from data in response.Element("dreamhost").Elements("data") select new UserUsage { user = data.Element("user").AsString(), disk = data.Element("disk").AsDouble(), disk_as_of = data.Element("disk_as_of").AsDateTime(), bw = data.Element("bw").AsDouble() }; } #endregion } }
29.236111
80
0.512589
[ "BSD-2-Clause" ]
clempaul/dreamhost-api-net
DreamhostAPI/Account/AccountRequests.cs
2,107
C#
namespace Cavity.Collections { using System; using Xunit; public sealed class LevenshteinComparerFacts { [Fact] public void a_definition() { Assert.True(new TypeExpectations<LevenshteinComparer>() .DerivesFrom<NormalityComparer>() .IsConcreteClass() .IsUnsealed() .HasDefaultConstructor() .IsNotDecorated() .Result); } [Fact] public void ctor() { Assert.NotNull(new LevenshteinComparer()); } [Fact] public void ctor_int() { Assert.NotNull(new LevenshteinComparer(1)); } [Fact] public void ctor_int0() { Assert.Throws<ArgumentOutOfRangeException>(() => new LevenshteinComparer(0)); } [Fact] public void op_Equals_string_string() { Assert.False(new LevenshteinComparer().Equals("abc", "xyz")); } [Fact] public void op_Equals_string_string_whenAboveThreshold() { Assert.False(new LevenshteinComparer().Equals("00000000", "00xxxx00")); } [Fact] public void op_Equals_string_string_whenBelowThreshold() { Assert.True(new LevenshteinComparer().Equals("00000000", "000xx000")); } [Fact] public void op_Equals_string_string_whenEqual() { Assert.True(new LevenshteinComparer().Equals("00000000", "00000000")); } [Fact] public void op_Equals_string_string_whenEqualIgnoreCase() { var obj = new LevenshteinComparer { Comparison = StringComparison.OrdinalIgnoreCase }; Assert.True(obj.Equals("abc", "ABC")); } [Fact] public void op_Normalize_stringEmpty() { var expected = string.Empty; var actual = new LevenshteinComparer().Normalize(expected); Assert.Equal(expected, actual); } [Fact] public void op_Normalize_stringNull() { Assert.Null(new LevenshteinComparer().Normalize(null)); } [Fact] public void op_Normalize_string_whenIgnoreCase() { var obj = new LevenshteinComparer { Comparison = StringComparison.OrdinalIgnoreCase }; const string expected = "ABC"; var actual = obj.Normalize("abc"); Assert.Equal(expected, actual); } [Fact] public void prop_Threshold() { Assert.True(new PropertyExpectations<LevenshteinComparer>(x => x.Threshold) .TypeIs<int>() .DefaultValueIs(3) .IsNotDecorated() .Result); } } }
28.153153
89
0.49568
[ "MIT" ]
cavity-project/domain
src/Class Libraries/Domain.Facts/Collections/LevenshteinComparer.Facts.cs
3,127
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; namespace System.Linq.Expressions.Tests { public abstract class ParameterExpressionTests { private static IEnumerable<Type> ValidElementTypes { get { return new[] { typeof(bool), typeof(byte), typeof(char), typeof(DateTime), typeof(decimal), typeof(double), typeof(short), typeof(int), typeof(long), typeof(object), typeof(sbyte), typeof(float), typeof(string), typeof(ushort), typeof(uint), typeof(ulong), typeof(ParameterExpressionTests), typeof(ExpressionType), typeof(Uri), typeof(DateTimeOffset), typeof(Exception), typeof(InvalidOperationException) }; } } private static IEnumerable<Type> ValidTypes { get { return ValidElementTypes.Concat(ValidElementTypes.Select(i => i.MakeArrayType())); } } private static IEnumerable<Type> ByRefTypes { get { return ValidTypes.Select(i => i.MakeByRefType()); } } public static IEnumerable<object[]> ValidTypeData() { return ValidTypes.Select(i => new object[] { i }); } public static IEnumerable<object[]> ByRefTypeData() { return ByRefTypes.Select(i => new object[] { i }); } private static IEnumerable<object> Values { get { return new object[] { true, false, (byte)3, '!', DateTime.MinValue, 23, 23m, 23.0, 23U, new object(), 23L, DateTimeOffset.MaxValue, new Uri("http://example.net"), "1Q84", ExpressionType.Parameter }; } } public static IEnumerable<object[]> ValueData() { return Values.Select(i => new object[] { i }); } } }
32.057143
129
0.540553
[ "MIT" ]
OceanYan/corefx
src/System.Linq.Expressions/tests/Variables/ParameterExpressionTests.cs
2,244
C#
using System.Collections.Generic; using System.Data; using System.Threading.Tasks; using Polly; using Polly.Registry; using Stoolball.Caching; using Stoolball.Statistics; namespace Stoolball.Data.Cache { public class CachedPlayerDataSource : IPlayerDataSource { private readonly IReadOnlyPolicyRegistry<string> _policyRegistry; private readonly ICacheablePlayerDataSource _playerDataSource; private readonly IPlayerFilterSerializer _playerFilterSerializer; public CachedPlayerDataSource(IReadOnlyPolicyRegistry<string> policyRegistry, ICacheablePlayerDataSource playerDataSource, IPlayerFilterSerializer playerFilterSerializer) { _policyRegistry = policyRegistry ?? throw new System.ArgumentNullException(nameof(policyRegistry)); _playerDataSource = playerDataSource ?? throw new System.ArgumentNullException(nameof(playerDataSource)); _playerFilterSerializer = playerFilterSerializer ?? throw new System.ArgumentNullException(nameof(playerFilterSerializer)); } public async Task<Player> ReadPlayerByRoute(string route) { var cachePolicy = _policyRegistry.Get<IAsyncPolicy>(CacheConstants.StatisticsPolicy); return await cachePolicy.ExecuteAsync(async context => await _playerDataSource.ReadPlayerByRoute(route).ConfigureAwait(false), new Context(nameof(ReadPlayerByRoute) + route)); } public async Task<List<PlayerIdentity>> ReadPlayerIdentities(PlayerFilter filter) { return await _playerDataSource.ReadPlayerIdentities(filter).ConfigureAwait(false); } public async Task<List<Player>> ReadPlayers(PlayerFilter filter) { var cachePolicy = _policyRegistry.Get<IAsyncPolicy>(CacheConstants.StatisticsPolicy); return await cachePolicy.ExecuteAsync(async context => await _playerDataSource.ReadPlayers(filter).ConfigureAwait(false), new Context(nameof(ReadPlayers) + _playerFilterSerializer.Serialize(filter))); } public async Task<List<Player>> ReadPlayers(PlayerFilter filter, IDbConnection connection) { var cachePolicy = _policyRegistry.Get<IAsyncPolicy>(CacheConstants.StatisticsPolicy); return await cachePolicy.ExecuteAsync(async context => await _playerDataSource.ReadPlayers(filter, connection).ConfigureAwait(false), new Context(nameof(ReadPlayers) + _playerFilterSerializer.Serialize(filter))); } } }
51.916667
224
0.753612
[ "Apache-2.0" ]
stoolball-england/stoolball-org-uk
Stoolball.Data.Cache/CachedPlayerDataSource.cs
2,494
C#
 using Bonsai.Core; using Bonsai.Designer; /// <summary> /// Always returns running. /// </summary> [NodeEditorProperties("Tasks/", "Hourglass")] public class Idle : Task { public override BehaviourNode.Status Run() { return Status.Running; } }
16.75
46
0.656716
[ "MIT" ]
luis-l/UnityAssets
Assets/Plugins/BonsaiBT/Standard/Tasks/Idle.cs
270
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using GitLabApiClient.Internal.Paths; using GitLabApiClient.Models.Discussions.Responses; using GitLabApiClient.Models.Issues.Requests; using GitLabApiClient.Models.Issues.Responses; using GitLabApiClient.Models.Notes.Requests; using GitLabApiClient.Models.Notes.Responses; namespace GitLabApiClient { public interface IIssuesClient { /// <summary> /// Retrieves issues. /// By default retrieves opened issues from all users. The more specific setting win (if both project and group are set, only project issues will be retrieved). /// </summary> /// <example> /// <code> /// /* Get all issues */ /// var client = new GitLabClient("https://gitlab.com", "PRIVATE-TOKEN"); /// var allIssues = await client.Issues.GetAllAsync(); /// </code> /// <code> /// /* Get project issues */ /// var client = new GitLabClient("https://gitlab.com", "PRIVATE-TOKEN"); /// string projectPath = "dev/group/project-1"; /// var allIssues = await client.Issues.GetAllAsync(projectId: projectPath); /// // OR /// int projectId = 55; /// var allIssues = await client.Issues.GetAllAsync(projectId: projectId); /// // OR - Group ID is skipped, project ID is more specific /// int projectId = 55; /// int groupId = 181; /// var allIssues = await client.Issues.GetAllAsync(projectId: projectId, groupId: groupId); /// </code> /// <code> /// /* Get group issues */ /// var client = new GitLabClient("https://gitlab.com", "PRIVATE-TOKEN"); /// string groupPath = "dev/group1/subgroup-1"; /// var allIssues = await client.Issues.GetAllAsync(groupId: groupPath); /// // OR /// int groupId = 55; /// var allIssues = await client.Issues.GetAllAsync(groupId: groupId); /// </code> /// </example> /// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param> /// <param name="groupId">The ID, path or <see cref="Group"/> of the group.</param> /// <param name="options">Issues retrieval options.</param> /// <returns>Issues satisfying options.</returns> Task<IList<Issue>> GetAllAsync(ProjectId projectId = null, GroupId groupId = null, Action<IssuesQueryOptions> options = null); /// <summary> /// Retrieves project issue. /// </summary> Task<Issue> GetAsync(ProjectId projectId, int issueId); /// <summary> /// Retrieves issues from a project. /// By default retrieves opened issues from all users. /// </summary> /// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param> /// <param name="options">Issues retrieval options.</param> /// <returns>Issues satisfying options.</returns> [Obsolete("Use GetAllAsync instead")] Task<IList<Issue>> GetAsync(ProjectId projectId, Action<IssuesQueryOptions> options = null); /// <summary> /// Retrieves issues from all projects. /// By default retrieves opened issues from all users. /// </summary> /// <param name="options">Issues retrieval options.</param> /// <returns>Issues satisfying options.</returns> [Obsolete("Use GetAllAsync instead")] Task<IList<Issue>> GetAsync(Action<IssuesQueryOptions> options = null); /// <summary> /// Retrieves project issue note. /// </summary> /// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param> /// <param name="issueIid">Iid of the issue.</param> /// <param name="noteId">Id of the note.</param> /// <returns>Issues satisfying options.</returns> Task<Note> GetNoteAsync(ProjectId projectId, int issueIid, int noteId); /// <summary> /// Retrieves notes (comments) of an issue. /// </summary> /// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param> /// <param name="issueIid">Iid of the issue.</param> /// <param name="options">IssueNotes retrieval options.</param> /// <returns>Issues satisfying options.</returns> Task<IList<Note>> GetNotesAsync(ProjectId projectId, int issueIid, Action<NotesQueryOptions> options = null); /// <summary> /// Creates new issue. /// </summary> /// <returns>The newly created issue.</returns> /// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param> /// <param name="request">Create issue request.</param> Task<Issue> CreateAsync(ProjectId projectId, CreateIssueRequest request); /// <summary> /// Creates a new note (comment) to a single project issue. /// </summary> /// <returns>The newly created issue note.</returns> /// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param> /// <param name="issueIid">The IID of an issue.</param> /// <param name="request">Create issue note request.</param> Task<Note> CreateNoteAsync(ProjectId projectId, int issueIid, CreateNoteRequest request); /// <summary> /// Moves an issues to a new project /// </summary> /// <returns>The newly created issue note.</returns> /// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param> /// <param name="issueIid">The IID of an issue.</param> /// <param name="request">Create issue note request.</param> Task<Issue> MoveIssueAsync(ProjectId projectId, int issueIid, MoveIssueRequest request); /// <summary> /// Updated existing issue. /// </summary> /// <returns>The updated issue.</returns> /// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param> /// <param name="issueIid">The IID of an issue.</param> /// <param name="request">Update issue request.</param> Task<Issue> UpdateAsync(ProjectId projectId, int issueIid, UpdateIssueRequest request); /// <summary> /// Modify existing note (comment) of an issue. /// </summary> /// <returns>The updated issue note.</returns> /// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param> /// <param name="issueIid">The IID of an issue.</param> /// <param name="noteId">The ID of a note.</param> /// <param name="request">Update issue note request.</param> Task<Note> UpdateNoteAsync(ProjectId projectId, int issueIid, int noteId, UpdateIssueNoteRequest request); /// <summary> /// Deletes an existing note (comment) of an issue. /// </summary> /// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param> /// <param name="issueIid">The IID of an issue.</param> /// <param name="noteId">The ID of a note.</param> Task DeleteNoteAsync(ProjectId projectId, int issueIid, int noteId); /// <summary> /// Creates a new discussuion and a note (comment) to a single project issue. /// </summary> /// <returns>The newly created discussion.</returns> /// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param> /// <param name="issueIid">The IID of an issue.</param> /// <param name="request">Create issue note request.</param> Task<Discussion> CreateDiscussionAsync(ProjectId projectId, int issueIid, CreateNoteRequest request); /// <summary> /// Adds a new note to an existing discussuion to a single project issue. /// </summary> /// <returns>The new note.</returns> /// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param> /// <param name="issueIid">The IID of an issue.</param> /// <param name="discussionId">The ID of the disussion.</param> /// <param name="request">Create issue note request.</param> Task<Note> AddDiscussionNoteAsync(ProjectId projectId, int issueIid, string discussionId, CreateNoteRequest request); /// <summary> /// Updates an existing note in an existing discussuion of a single project issue. /// </summary> /// <returns>The existing note.</returns> /// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param> /// <param name="issueIid">The IID of an issue.</param> /// <param name="discussionId">The ID of the disussion.</param> /// <param name="noteId">The ID of a note.</param> /// <param name="request">Update issue note request.</param> Task<Note> UpdateDiscussionNoteAsync(ProjectId projectId, int issueIid, string discussionId, int noteId, UpdateIssueNoteRequest request); /// <summary> /// Retrieves discussuions and notes (comment) from a single project issue. /// </summary> /// <returns>The issue discussions and notes.</returns> /// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param> /// <param name="issueIid">The IID of an issue.</param> Task<IList<Discussion>> GetDiscussionsAsync(ProjectId projectId, int issueIid); } }
50.829787
168
0.616681
[ "MIT" ]
mhobl/GitLabApiClient
src/GitLabApiClient/IIssuesClient.cs
9,556
C#
namespace SunceSlobode.Prototype { /// <summary> /// Представляет обновляемый объект. /// </summary> public interface IUpdate { void Update(); } }
16.363636
40
0.583333
[ "Apache-2.0" ]
sunce-slobode/PrototypeOne
src/IUpdate.cs
211
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSLibrary.Tools { #region BT CRC public static class Crc { static readonly ushort[] crc_lookup_table = new ushort[]{ 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78}; public static ushort ComputeChecksum(byte[] dataIn) { ushort checksum = 0; for (int i = 0; i < (dataIn[2] + 8); i++) { if (i != 6 && i != 7) { int index = (checksum ^ ((byte)dataIn[i] & 0x0FF)) & 0x0FF; checksum = (ushort)((checksum >> 8) ^ crc_lookup_table[index]); } } return checksum; } } #endregion }
50.492537
84
0.566361
[ "MIT" ]
cslrfid/CS108-Mobile-CSharp-App
CSLibrary/CSLibrary/Tools/ClassCRC16.cs
3,385
C#
// This file is part of CycloneDX Tool for .NET // // 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. // // SPDX-License-Identifier: Apache-2.0 // Copyright (c) OWASP Foundation. All Rights Reserved. using System.Collections.Generic; using CycloneDX.Core.Models; namespace CycloneDX.Services { public interface IProjectAssetsFileService { HashSet<NugetPackage> GetNugetPackages(string projectAssetsFilePath, bool IsTestProject); } }
34.142857
97
0.753138
[ "Apache-2.0" ]
rajeshkumer/cyclonedx-dotnet
CycloneDX.Core/Services/IProjectAssetsFileService.cs
964
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.SharePoint.Client; using System.Management.Automation; using Transformation.PowerShell.Base; namespace Transformation.PowerShell.MasterPage { [Cmdlet(VerbsCommon.Set, "MasterPageSiteCollectionLevel")] public class UpdateMasterPageSiteCollectionLevel : TrasnformationPowerShellCmdlet { [Parameter(Mandatory = true, Position = 0)] public string InputFolder; [Parameter(Mandatory = true, Position = 1)] public string SiteCollectionUrl; [Parameter(Mandatory = true, Position = 2)] public string New_MasterPageURL; [Parameter(Position = 3)] public string Old_MasterPageURL; [Parameter(Position = 4)] public bool CustomMasterUrlStatus; [Parameter(Position = 5)] public bool MasterUrlStatus; [Parameter(Mandatory = true, Position = 6)] public string SharePointOnline_OR_OnPremise; [Parameter(Mandatory = true, Position = 7)] public string UserName; [Parameter(Mandatory = true, Position = 8)] public string Password; [Parameter(Mandatory = true, Position = 9)] public string Domain; protected override void ProcessRecord() { MasterPageHelper objMasterHelper = new MasterPageHelper(); objMasterHelper.ChangeMasterPageForSiteCollection(InputFolder,SiteCollectionUrl, New_MasterPageURL, Old_MasterPageURL,CustomMasterUrlStatus,MasterUrlStatus,SharePointOnline_OR_OnPremise,UserName,Password,Domain); } } }
37.044444
226
0.704259
[ "MIT" ]
ashwani2711/MyBucket
SP.Tools/SP.Tools/Src/Transformation.PowerShell/MasterPage/UpdateMasterPage-SiteCollection.cs
1,669
C#
using System; using System.Collections.Generic; public class Person { private string name; private decimal money; private List<Product> products; public string Name { get => this.name; private set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Name cannot be empty"); } this.name = value; } } public decimal Money { get => this.money; private set { if (value < 0) { throw new ArgumentException("Money cannot be negative"); } this.money = value; } } public IReadOnlyCollection<Product> Products => products; public Person(string name, decimal money) { Name = name; Money = money; products = new List<Product>(); } public void BuyProduct(Product product) { if (money >= product.Price) { money -= product.Price; products.Add(product); Console.WriteLine($"{name} bought {product.Name}"); } else { Console.WriteLine($"{name} can't afford {product.Name}"); } } }
21
72
0.505556
[ "MIT" ]
vesopk/C-DBAdvanced
EncapsulationAndValidation/ShoppingSpree/Person.cs
1,262
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using Microsoft.Data.Entity.FunctionalTests; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.Data.Entity.Sqlite.FunctionalTests { public class AutoincrementTest : IDisposable { private readonly DbContextOptions _options; private readonly IServiceProvider _provider; private readonly SqliteTestStore _testStore; [Fact] public void Autoincrement_prevents_reusing_rowid() { using (var context = CreateContext()) { context.Database.EnsureCreated(); context.People.Add(new Person { Name = "Bruce" }); context.SaveChanges(); var hero = context.People.First(p => p.Id == 1); context.People.Remove(hero); context.SaveChanges(); context.People.Add(new Person { Name = "Batman" }); context.SaveChanges(); var gone = context.People.FirstOrDefault(p => p.Id == 1); var begins = context.People.FirstOrDefault(p => p.Id == 2); Assert.Null(gone); Assert.NotNull(begins); } } [Fact] public void Identity_metadata_not_on_text_is_ignored() { using (var context = new JokerContext(_provider, _options)) { context.Database.EnsureCreated(); } } public AutoincrementTest() { _testStore = SqliteTestStore.CreateScratch(); var builder = new DbContextOptionsBuilder(); builder.UseSqlite(_testStore.Connection); _options = builder.Options; _provider = new ServiceCollection() .AddEntityFramework() .AddSqlite() .AddDbContext<BatContext>() .ServiceCollection() .BuildServiceProvider(); } private BatContext CreateContext() => new BatContext(_provider, _options); public void Dispose() { _testStore?.Dispose(); } } public class JokerContext : DbContext { public JokerContext(IServiceProvider serviceProvider, DbContextOptions options) : base(serviceProvider, options) { } public DbSet<Person> People { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Person>(b => { b.ToSqliteTable("People2"); b.Key(t => t.Name); b.Property(t => t.Name).ValueGeneratedOnAdd(); }); } } public class BatContext : DbContext { public BatContext(IServiceProvider serviceProvider, DbContextOptions options) : base(serviceProvider, options) { } public DbSet<Person> People { get; set; } } public class Person { public int Id { get; set; } public string Name { get; set; } } }
30.245455
111
0.570484
[ "Apache-2.0" ]
suryasnath/csharp
test/EntityFramework.Sqlite.FunctionalTests/AutoincrementTest.cs
3,329
C#
using SecurityAPITest.SecurityAPICommons.commons; using NUnit.Framework; using SecurityAPICommons.Keys; using GeneXusJWT.GenexusComons; using GeneXusJWT.GenexusJWTClaims; using GeneXusJWT.GenexusJWTUtils; using GeneXusJWT.GenexusJWT; using SecurityAPICommons.Utils; namespace SecurityAPITest.Jwt.Other { [TestFixture] public class TestIssue81664: SecurityAPITestObject { private static CertificateX509 cert; private static PrivateKeyManager key; private static JWTOptions options; private static PrivateClaims claims; private static string token; private static string expected; private static DateUtil du; private static JWTCreator jwt; [SetUp] public virtual void SetUp() { cert = new CertificateX509(); key = new PrivateKeyManager(); options = new JWTOptions(); claims = new PrivateClaims(); du = new DateUtil(); jwt = new JWTCreator(); cert.Load(BASE_PATH + "dummycerts\\RSA_sha256_1024\\sha256_cert.crt"); options.SetCertificate(cert); key.Load(BASE_PATH + "dummycerts\\RSA_sha256_1024\\sha256d_key.pem"); options.SetPrivateKey(key); // // carga de privateClaim (es parte del Payload) claims.setClaim("GeneXus", "Viglia"); // Carga de Registered Claims options.AddRegisteredClaim("iss", "Martin"); options.AddRegisteredClaim("sub", "Martin1"); options.AddRegisteredClaim("aud", "martivigliadoocebbooyo.docebosaas.com"); options.AddCustomTimeValidationClaim("iat", du.GetCurrentDate(), "20"); options.AddCustomTimeValidationClaim("exp", du.CurrentPlusSeconds(3600), "20"); options.AddPublicClaim("client_id", "Martin"); token = jwt.DoCreate("RS256", claims, options); expected = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}"; } [Test] public void Test_algorithm() { string header = jwt.GetHeader(token); Assert.IsTrue(SecurityUtils.compareStrings(header, expected)); } } }
27.550725
82
0.73172
[ "Apache-2.0" ]
genexuslabs/DotNet-SecurityApi-Module
test/dotnetframework/SecurityAPITest/Jwt/Other/TestIssue81664.cs
1,903
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; struct BooleanButtonInfos { public BooleanButton button; public Vector3 startPosition; } public class BooleanUI : MonoBehaviour { private BooleanButtonInfos _selected; private BooleanButtonInfos _deselected; private Dictionary<BooleanTool.BooleanOperation, BooleanButtonInfos> _operationButtonsMap = new Dictionary<BooleanTool.BooleanOperation, BooleanButtonInfos>(); private Coroutine placeRoutine = null; private Coroutine replaceRoutine = null; [SerializeField] private float _selectionYOffset; [SerializeField] private float _animationDuration; void Start () { CreateOperationButtonsMap(); _operationButtonsMap[BooleanTool.BooleanOperation.Merge].button.Select(null); } private void OnDisable() { if (placeRoutine != null) StopCoroutine(placeRoutine); if (replaceRoutine != null) StopCoroutine(replaceRoutine); if (_selected.button != null) _selected.button.transform.localPosition = new Vector3(_selected.startPosition.x, _selected.startPosition.y + _selectionYOffset, _selected.startPosition.z); if (_deselected.button != null) _deselected.button.transform.localPosition = _deselected.startPosition; } public void SelectOperation(BooleanTool.BooleanOperation operationType) { BooleanButtonInfos selection = _operationButtonsMap[operationType]; placeRoutine = StartCoroutine(MoveButton(selection, _selectionYOffset)); if (_selected.button != null) { replaceRoutine = StartCoroutine(MoveButton(_selected, -_selectionYOffset)); _deselected = _selected; _deselected.button.Deselect(); } _selected = _operationButtonsMap[operationType]; } IEnumerator MoveButton(BooleanButtonInfos button, float yOffset) { Vector3 startPos = button.startPosition; float targetY = startPos.y + yOffset; float timer = 0; float y; while (timer < _animationDuration) { y = Mathf.Lerp(startPos.y, targetY, timer / _animationDuration); button.button.transform.localPosition = new Vector3(button.button.transform.localPosition.x, y, button.button.transform.localPosition.z); timer += Time.deltaTime; yield return null; } yield return null; } private void CreateOperationButtonsMap() { BooleanButton booleanButtonScript; foreach (Transform child in transform) { if ((booleanButtonScript = child.GetComponent<BooleanButton>()) != null) { _operationButtonsMap.Add(booleanButtonScript.CurrentOperation, new BooleanButtonInfos() { button = booleanButtonScript, startPosition = child.localPosition }); } } } }
35.807229
179
0.677995
[ "MIT" ]
ErwanLeGoffic/Tectrid
TectridVR/Assets/Resources/UI/Scripts/BooleanUI.cs
2,974
C#
using Microsoft.CodeAnalysis.CSharp.Syntax; using SourceMapper.Generator.Info; using Space.SourceGenerator.Client; namespace SourceMapper.Generator { public class MapFactoryVariable : IParameter { public MapFactoryVariable(string name, ExpressionSyntax expression, TypeInfo type) { Name = name; Expression = expression; Type = type; } public string Name { get; } public ExpressionSyntax Expression { get; } public TypeInfo Type { get; } public override string ToString() { return Name; } public ExpressionSyntax GetDefaultSyntax() { return Expression; } } }
22.875
90
0.605191
[ "MIT" ]
GerardSmit/SourceMapper
src/SourceMapper.Generator/Mappings/MapFactoryVariable.cs
734
C#
namespace EncompassRest.Company.Users.Rights { /// <summary> /// TPOOrganizationSettingsContactsRights /// </summary> public sealed class TPOOrganizationSettingsContactsRights : ParentAccessRights { private DirtyValue<bool?> _editTPOContacts; /// <summary> /// TPOOrganizationSettingsContactsRights EditTPOContacts /// </summary> public bool? EditTPOContacts { get => _editTPOContacts; set => SetField(ref _editTPOContacts, value); } } }
33.466667
111
0.687251
[ "MIT" ]
PLoftis02/EncompassRest
src/EncompassRest/Company/Users/Rights/TPOOrganizationSettingsContactsRights.cs
502
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V6301 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="RCMR_MT030101UK06.PertinentInformation02", Namespace="urn:hl7-org:v3")] [System.Xml.Serialization.XmlRootAttribute("RCMR_MT030101UK06.PertinentInformation02", Namespace="urn:hl7-org:v3")] public partial class RCMR_MT030101UK06PertinentInformation02 { private INT sequenceNumberField; private RCMR_MT030101UK06Annotation pertinentAnnotationField; private string typeField; private string typeCodeField; private string[] typeIDField; private string[] realmCodeField; private string nullFlavorField; private static System.Xml.Serialization.XmlSerializer serializer; public RCMR_MT030101UK06PertinentInformation02() { this.typeField = "ActRelationship"; this.typeCodeField = "PERT"; } public INT sequenceNumber { get { return this.sequenceNumberField; } set { this.sequenceNumberField = value; } } public RCMR_MT030101UK06Annotation pertinentAnnotation { get { return this.pertinentAnnotationField; } set { this.pertinentAnnotationField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string type { get { return this.typeField; } set { this.typeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string typeCode { get { return this.typeCodeField; } set { this.typeCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string[] typeID { get { return this.typeIDField; } set { this.typeIDField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string[] realmCode { get { return this.realmCodeField; } set { this.realmCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string nullFlavor { get { return this.nullFlavorField; } set { this.nullFlavorField = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(RCMR_MT030101UK06PertinentInformation02)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current RCMR_MT030101UK06PertinentInformation02 object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an RCMR_MT030101UK06PertinentInformation02 object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output RCMR_MT030101UK06PertinentInformation02 object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out RCMR_MT030101UK06PertinentInformation02 obj, out System.Exception exception) { exception = null; obj = default(RCMR_MT030101UK06PertinentInformation02); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out RCMR_MT030101UK06PertinentInformation02 obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static RCMR_MT030101UK06PertinentInformation02 Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((RCMR_MT030101UK06PertinentInformation02)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current RCMR_MT030101UK06PertinentInformation02 object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an RCMR_MT030101UK06PertinentInformation02 object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output RCMR_MT030101UK06PertinentInformation02 object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out RCMR_MT030101UK06PertinentInformation02 obj, out System.Exception exception) { exception = null; obj = default(RCMR_MT030101UK06PertinentInformation02); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out RCMR_MT030101UK06PertinentInformation02 obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static RCMR_MT030101UK06PertinentInformation02 LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this RCMR_MT030101UK06PertinentInformation02 object /// </summary> public virtual RCMR_MT030101UK06PertinentInformation02 Clone() { return ((RCMR_MT030101UK06PertinentInformation02)(this.MemberwiseClone())); } #endregion } }
41.888087
1,358
0.582867
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V6301/Generated/RCMR_MT030101UK06PertinentInformation02.cs
11,603
C#
#region License // Copyright 2014 Elton FAN (eltonfan@live.cn, http://elton.io) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System.Text; using System.Runtime.Serialization; namespace Elton.OAuth2 { public interface IToken { /// <summary> /// 访问令牌 cf. RFC6749 /// </summary> /// <value>访问令牌 cf. RFC6749</value> string AccessToken { get; set; } /// <summary> /// 设备的名字 cf. RFC6749 /// </summary> /// <value>设备的名字 cf. RFC6749</value> string TokenType { get; set; } /// <summary> /// 刷新令牌 cf. RFC6749 /// </summary> /// <value>刷新令牌 cf. RFC6749</value> string RefreshToken { get; set; } /// <summary> /// 几秒后过期 cf. RFC6749 /// </summary> /// <value>几秒后过期 cf. RFC6749</value> int? ExpiresIn { get; set; } /// <summary> /// 授权用户的唯一标识 /// </summary> /// <value></value> string OpenId { get; set; } /// <summary> /// 取值为任意字符串,认证服务器将原样返回该参数 /// </summary> /// <value></value> string State { get; set; } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> string ToJson(); void CopyFrom(IToken target); } }
27.478873
77
0.570989
[ "Apache-2.0" ]
eltonfan/OAuth2
src/OAuth2/Elton.OAuth2/IToken.cs
2,085
C#
using System; using System.Text; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using SecurePass.DotNet.Class.APIClass; using SecurePass.DotNet.Class.PlainObject; namespace UnitTests.Tests { /// <summary> /// Summary description for AppsAPITest /// </summary> [TestClass] public class AppsAPITest { public AppsAPITest() { // // TODO: Add constructor logic here // } private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } private static AppsAPI _appsApi; private static SecurePassRestAPI _securePassRestApi; [ClassInitialize()] public static void InitializeTestClass(TestContext context) { _appsApi = new AppsAPI(); _securePassRestApi = new SecurePassRestAPI(SecurePassTestAuth.SecurePassAppID, SecurePassTestAuth.SecurePassAppSecret, SecurePassTestAuth.SecurePassUsername, SecurePassTestAuth.SecurePassSecret); } #region Additional test attributes // // You can use the following additional attributes as you write your tests: // // Use ClassInitialize to run code before running the first test in the class // [ClassInitialize()] // public static void MyClassInitialize(TestContext testContext) { } // // Use ClassCleanup to run code after all tests in a class have run // [ClassCleanup()] // public static void MyClassCleanup() { } // // Use TestInitialize to run code before running each test // [TestInitialize()] // public void MyTestInitialize() { } // // Use TestCleanup to run code after each test has run // [TestCleanup()] // public void MyTestCleanup() { } // #endregion [TestMethod] public void TestAppsDelete() { var request = TestUtility.AppsAddReq(); AppsAddDataResp appsAddDataResp = _appsApi.addApps(request); String appId = appsAddDataResp.app_id; AppsDeleteReq appsDeleteReq = new AppsDeleteReq(); appsDeleteReq.APP_ID = appId; var jsonBaseDataResponse = _appsApi.deleteApps(appsDeleteReq); bool checkIfResponseIsOk = TestUtility.checkIFResponseIsOK(jsonBaseDataResponse.rc); Assert.IsTrue(checkIfResponseIsOk); } [TestMethod] public void TestAppsAdd() { var request = TestUtility.AppsAddReq(); AppsAddDataResp appsAddDataResp = _appsApi.addApps(request); Assert.IsTrue(appsAddDataResp.rc == "0"); } [TestMethod] public void TestAppsInfo() { var request = TestUtility.AppsAddReq(); AppsAddDataResp appsAddDataResp = _appsApi.addApps(request); String appId = appsAddDataResp.app_id; AppsInfoReq appsInfoReq = new AppsInfoReq(); appsInfoReq.APP_ID = appId; var appsInfoResp = _appsApi.info(appsInfoReq); Assert.IsTrue(appsInfoResp.rc == "0"); Assert.IsTrue(appsInfoResp.LABEL == TestUtility.appName); } } }
31.350427
96
0.6006
[ "MIT" ]
garlsecurity/securepass-dotnet
UnitTests/Tests/AppsAPITest.cs
3,670
C#
//--------------------------------------------------------- // <auto-generated> // This code was generated by a tool. Changes to this // file may cause incorrect behavior and will be lost // if the code is regenerated. // // Generated on 2020 October 09 05:04:27 UTC // </auto-generated> //--------------------------------------------------------- using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; #nullable enable namespace go { public static partial class syscall_package { [GeneratedCode("go2cs", "0.1.0.0")] public partial struct Cmsghdr { // Constructors public Cmsghdr(NilType _) { this.Len = default; this.Level = default; this.Type = default; } public Cmsghdr(ulong Len = default, int Level = default, int Type = default) { this.Len = Len; this.Level = Level; this.Type = Type; } // Enable comparisons between nil and Cmsghdr struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Cmsghdr value, NilType nil) => value.Equals(default(Cmsghdr)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Cmsghdr value, NilType nil) => !(value == nil); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NilType nil, Cmsghdr value) => value == nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NilType nil, Cmsghdr value) => value != nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Cmsghdr(NilType nil) => default(Cmsghdr); } [GeneratedCode("go2cs", "0.1.0.0")] public static Cmsghdr Cmsghdr_cast(dynamic value) { return new Cmsghdr(value.Len, value.Level, value.Type); } } }
33.703125
105
0.569309
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/syscall/ztypes_linux_arm64_CmsghdrStruct.cs
2,157
C#
using System; using System.Collections.Generic; using System.IO; using Hec.Dss; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DSSUnitTests { [TestClass] public class LimitsTest { [Ignore] [TestMethod] public void LargePartF() {// #define MAX_PART_SIZE 65, want to increase to 150 string fn = "large_F_part.dss"; File.Delete(fn); using (DssWriter w = new DssWriter(fn)) { int size = 60; do { var F = size.ToString().PadRight(size, 'a'); DssPath path = new DssPath("/feature/increase-part-f/FLOW//1day/" + F + "/"); var d = CreateDoubles(10); int status = w.Write(new TimeSeries(path, d, DateTime.Now.Date, "cfs", "INST-VAL")); if (status != 0) break; var s = w.GetTimeSeries(path); if (s == null || s.Count != 10) break; Console.WriteLine(size + ", " + path); size++; } while (size < 1000); } } /// <summary> /// 7.99 GB file with 5000 series and 10^7 points each. /// </summary> [Ignore] [TestMethod] public void V6() { string fn = "crash_me6.dss"; File.Delete(fn); Hec.Dss.Native.DSS.ZSet("DSSV", "", 6); using (DssWriter w = new DssWriter(fn)) { for (int pn = 0; pn < 7000; pn++) { var d = CreateDoubles((int)Math.Pow(10, 7)); string path = "/dss-test/csharp/series" + pn + "//1day/file-size-test/"; TimeSeries ts = new TimeSeries(path, d, DateTime.Now.Date, "cfs", "INST-VAL"); //int status = w.StoreTimeSeriesRegular(path, d, 0, DateTime.Now.Date, "cfs", "INST-VAL"); w.Write(ts); if (pn % 10 == 0) { FileInfo fi = new FileInfo(fn); var s = pn + " " + BytesToString(fi.Length); Console.WriteLine(s); } } } } /// <summary> /// https://stackoverflow.com/questions/281640/how-do-i-get-a-human-readable-file-size-in-bytes-abbreviation-using-net /// </summary> /// <param name="byteCount"></param> /// <returns></returns> static String BytesToString(long byteCount) { string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB if (byteCount == 0) return "0" + suf[0]; long bytes = Math.Abs(byteCount); int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024))); double num = Math.Round(bytes / Math.Pow(1024, place), 1); return (Math.Sign(byteCount) * num).ToString() + suf[place]; } private static double[] CreateDoubles(int size) { double[] d = new double[size]; for (int i = 0; i < size; i++) { d[i] = i; } return d; } } }
27.419048
122
0.52414
[ "MIT" ]
HydrologicEngineeringCenter/hec-dss
dotnet/DotNetTests/LimitsTest.cs
2,881
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.Web.V20210201.Outputs { /// <summary> /// The plan object in Azure Resource Manager, represents a marketplace plan. /// </summary> [OutputType] public sealed class ArmPlanResponse { /// <summary> /// The name. /// </summary> public readonly string? Name; /// <summary> /// The product. /// </summary> public readonly string? Product; /// <summary> /// The promotion code. /// </summary> public readonly string? PromotionCode; /// <summary> /// The publisher. /// </summary> public readonly string? Publisher; /// <summary> /// Version of product. /// </summary> public readonly string? Version; [OutputConstructor] private ArmPlanResponse( string? name, string? product, string? promotionCode, string? publisher, string? version) { Name = name; Product = product; PromotionCode = promotionCode; Publisher = publisher; Version = version; } } }
25.283333
81
0.558339
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Web/V20210201/Outputs/ArmPlanResponse.cs
1,517
C#
using System; namespace Voltaic.Serialization { public class SerializationException : Exception { public SerializationException() : base("Serialization failed") { } public SerializationException(string message) : base(message) { } } }
18.882353
53
0.576324
[ "MIT" ]
RogueException/Voltaic.Serialization
src/Voltaic.Serialization/SerializationException.cs
323
C#
/********************************************************************++ * Copyright (c) Microsoft Corporation. All rights reserved. * --********************************************************************/ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Management.Automation.Tracing; using Microsoft.PowerShell.Commands; using Microsoft.Win32; using System.Reflection; using System.IO; using System.Xml; using System.Globalization; using System.Diagnostics.CodeAnalysis; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; using Dbg = System.Management.Automation.Diagnostics; using System.Collections; namespace System.Management.Automation.Remoting { /// <summary> /// This struct is used to represent contents from configuration xml. The /// XML is passed to plugins by WSMan API. /// This helper does not validate XML content as it is already validated /// by WSMan. /// </summary> internal class ConfigurationDataFromXML { #region Config XML Constants internal const string INITPARAMETERSTOKEN = "InitializationParameters"; internal const string PARAMTOKEN = "Param"; internal const string NAMETOKEN = "Name"; internal const string VALUETOKEN = "Value"; internal const string APPBASETOKEN = "applicationbase"; internal const string ASSEMBLYTOKEN = "assemblyname"; internal const string SHELLCONFIGTYPETOKEN = "pssessionconfigurationtypename"; internal const string STARTUPSCRIPTTOKEN = "startupscript"; internal const string MAXRCVDOBJSIZETOKEN = "psmaximumreceivedobjectsizemb"; internal const string MAXRCVDOBJSIZETOKEN_CamelCase = "PSMaximumReceivedObjectSizeMB"; internal const string MAXRCVDCMDSIZETOKEN = "psmaximumreceiveddatasizepercommandmb"; internal const string MAXRCVDCMDSIZETOKEN_CamelCase = "PSMaximumReceivedDataSizePerCommandMB"; internal const string THREADOPTIONSTOKEN = "pssessionthreadoptions"; #if !CORECLR // No ApartmentState In CoreCLR internal const string THREADAPTSTATETOKEN = "pssessionthreadapartmentstate"; #endif internal const string SESSIONCONFIGTOKEN = "sessionconfigurationdata"; internal const string PSVERSIONTOKEN = "PSVersion"; internal const string MAXPSVERSIONTOKEN = "MaxPSVersion"; internal const string MODULESTOIMPORT = "ModulesToImport"; internal const string HOSTMODE = "hostmode"; internal const string ENDPOINTCONFIGURATIONTYPE = "sessiontype"; internal const string WORKFLOWCOREASSEMBLY = "Microsoft.PowerShell.Workflow.ServiceCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"; internal const string WORKFLOWCORETYPENAME = "Microsoft.PowerShell.Workflow.PSWorkflowSessionConfiguration"; internal const string PSWORKFLOWMODULE = "%windir%\\system32\\windowspowershell\\v1.0\\Modules\\PSWorkflow"; internal const string CONFIGFILEPATH = "configfilepath"; internal const string CONFIGFILEPATH_CamelCase = "ConfigFilePath"; #endregion internal string StartupScript; // this field is used only by an Out-Of-Process (IPC) server process internal string InitializationScriptForOutOfProcessRunspace; internal string ApplicationBase; internal string AssemblyName; internal string EndPointConfigurationTypeName; internal Type EndPointConfigurationType; internal Nullable<int> MaxReceivedObjectSizeMB; internal Nullable<int> MaxReceivedCommandSizeMB; // Used to set properties on the RunspacePool created for this shell. internal Nullable<PSThreadOptions> ShellThreadOptions; #if !CORECLR // No ApartmentState In CoreCLR internal Nullable<System.Threading.ApartmentState> ShellThreadApartmentState; #endif internal PSSessionConfigurationData SessionConfigurationData; internal string ConfigFilePath; /// <summary> /// Using optionName and optionValue updates the current object /// </summary> /// <param name="optionName"></param> /// <param name="optionValue"></param> /// <exception cref="ArgumentException"> /// 1. "optionName" is not valid in "InitializationParameters" section. /// 2. "startupscript" must specify a PowerShell script file that ends with extension ".ps1". /// </exception> private void Update(string optionName, string optionValue) { switch (optionName.ToLowerInvariant()) { case APPBASETOKEN: AssertValueNotAssigned(APPBASETOKEN, ApplicationBase); // this is a folder pointing to application base of the plugin shell // allow the folder path to use environment variables. ApplicationBase = Environment.ExpandEnvironmentVariables(optionValue); break; case ASSEMBLYTOKEN: AssertValueNotAssigned(ASSEMBLYTOKEN, AssemblyName); AssemblyName = optionValue; break; case SHELLCONFIGTYPETOKEN: AssertValueNotAssigned(SHELLCONFIGTYPETOKEN, EndPointConfigurationTypeName); EndPointConfigurationTypeName = optionValue; break; case STARTUPSCRIPTTOKEN: AssertValueNotAssigned(STARTUPSCRIPTTOKEN, StartupScript); if (!optionValue.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) { throw PSTraceSource.NewArgumentException(STARTUPSCRIPTTOKEN, RemotingErrorIdStrings.StartupScriptNotCorrect, STARTUPSCRIPTTOKEN); } // allow the script file to exist in any path..and support // environment variable expansion. StartupScript = Environment.ExpandEnvironmentVariables(optionValue); break; case MAXRCVDOBJSIZETOKEN: AssertValueNotAssigned(MAXRCVDOBJSIZETOKEN, MaxReceivedObjectSizeMB); MaxReceivedObjectSizeMB = GetIntValueInBytes(optionValue); break; case MAXRCVDCMDSIZETOKEN: AssertValueNotAssigned(MAXRCVDCMDSIZETOKEN, MaxReceivedCommandSizeMB); MaxReceivedCommandSizeMB = GetIntValueInBytes(optionValue); break; case THREADOPTIONSTOKEN: AssertValueNotAssigned(THREADOPTIONSTOKEN, ShellThreadOptions); ShellThreadOptions = (PSThreadOptions)LanguagePrimitives.ConvertTo( optionValue, typeof(PSThreadOptions), CultureInfo.InvariantCulture); break; #if !CORECLR // No ApartmentState In CoreCLR case THREADAPTSTATETOKEN: AssertValueNotAssigned(THREADAPTSTATETOKEN, ShellThreadApartmentState); ShellThreadApartmentState = (System.Threading.ApartmentState)LanguagePrimitives.ConvertTo( optionValue, typeof(System.Threading.ApartmentState), CultureInfo.InvariantCulture); break; #endif case SESSIONCONFIGTOKEN: { AssertValueNotAssigned(SESSIONCONFIGTOKEN, SessionConfigurationData); SessionConfigurationData = PSSessionConfigurationData.Create(optionValue); } break; case CONFIGFILEPATH: { AssertValueNotAssigned(CONFIGFILEPATH, ConfigFilePath); ConfigFilePath = optionValue.ToString(); } break; default: // we dont need to evaluate PSVersion and other custom authz // related tokens break; } } /// <summary> /// Checks if the originalValue is empty. If not throws an exception /// </summary> /// <param name="optionName"></param> /// <param name="originalValue"></param> /// <exception cref="ArgumentException"> /// 1. "optionName" is already defined /// </exception> private void AssertValueNotAssigned(string optionName, object originalValue) { if (originalValue != null) { throw PSTraceSource.NewArgumentException(optionName, RemotingErrorIdStrings.DuplicateInitializationParameterFound, optionName, INITPARAMETERSTOKEN); } } /// <summary> /// Converts the value specified by <paramref name="optionValue"/> to int. /// Multiplies the value by 1MB (1024*1024) to get the number in bytes. /// </summary> /// <param name="optionValueInMB"></param> /// <returns> /// If value is specified, specified value as int . otherwise null. /// </returns> private static Nullable<int> GetIntValueInBytes(string optionValueInMB) { Nullable<int> result = null; try { double variableValue = (double)LanguagePrimitives.ConvertTo(optionValueInMB, typeof(double), System.Globalization.CultureInfo.InvariantCulture); result = unchecked((int)(variableValue * 1024 * 1024)); // Multiply by 1MB } catch (InvalidCastException) { } if (result < 0) { result = null; } return result; } /// <summary> /// Creates the struct from initialization parameters xml. /// </summary> /// <param name="initializationParameters"> /// Initialization Parameters xml passed by WSMan API. This data is read from the config /// xml and is in the following format: /// </param> /// <returns></returns> /// <exception cref="ArgumentException"> /// 1. "optionName" is already defined /// </exception> /* <InitializationParameters> <Param Name="PSVersion" Value="2.0" /> <Param Name="ApplicationBase" Value="<folder path>" /> ... </InitializationParameters> */ /* The following extensions have been added in V3 providing the user * the ability to pass data to the session configuration for initialization * <Param Name="SessionConfigurationData" Value="<SessionConfigurationData with XML escaping>" /> * * The session configuration data blob can be defined as under <SessionConfigurationData> <Param Name="ModulesToImport" Value="<folder path>" /> <Param Name="PrivateData" /> <PrivateData> ... </PrivateData> </Param> </SessionConfigurationData> */ internal static ConfigurationDataFromXML Create(string initializationParameters) { ConfigurationDataFromXML result = new ConfigurationDataFromXML(); if (string.IsNullOrEmpty(initializationParameters)) { return result; } XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.CheckCharacters = false; readerSettings.IgnoreComments = true; readerSettings.IgnoreProcessingInstructions = true; readerSettings.MaxCharactersInDocument = 10000; readerSettings.ConformanceLevel = ConformanceLevel.Fragment; #if !CORECLR // No XmlReaderSettings.XmlResolver in CoreCLR readerSettings.XmlResolver = null; #endif using (XmlReader reader = XmlReader.Create(new StringReader(initializationParameters), readerSettings)) { // read the header <InitializationParameters> if (reader.ReadToFollowing(INITPARAMETERSTOKEN)) { bool isParamFound = reader.ReadToDescendant(PARAMTOKEN); while (isParamFound) { if (!reader.MoveToAttribute(NAMETOKEN)) { throw PSTraceSource.NewArgumentException(initializationParameters, RemotingErrorIdStrings.NoAttributesFoundForParamElement, NAMETOKEN, VALUETOKEN, PARAMTOKEN); } string optionName = reader.Value; if (!reader.MoveToAttribute(VALUETOKEN)) { throw PSTraceSource.NewArgumentException(initializationParameters, RemotingErrorIdStrings.NoAttributesFoundForParamElement, NAMETOKEN, VALUETOKEN, PARAMTOKEN); } string optionValue = reader.Value; result.Update(optionName, optionValue); // move to next Param token. isParamFound = reader.ReadToFollowing(PARAMTOKEN); } } } // assign defaults after parsing the xml content. if (null == result.MaxReceivedObjectSizeMB) { result.MaxReceivedObjectSizeMB = BaseTransportManager.MaximumReceivedObjectSize; } if (null == result.MaxReceivedCommandSizeMB) { result.MaxReceivedCommandSizeMB = BaseTransportManager.MaximumReceivedDataSize; } return result; } /// <summary> /// /// </summary> /// <returns></returns> /// <exception cref="ArgumentException"> /// 1. Unable to load type "{0}" specified in "InitializationParameters" section. /// </exception> internal PSSessionConfiguration CreateEndPointConfigurationInstance() { try { return (PSSessionConfiguration)Activator.CreateInstance(EndPointConfigurationType); } catch (TypeLoadException) { } catch (ArgumentException) { } catch (MissingMethodException) { } catch (InvalidCastException) { } catch (TargetInvocationException) { } // if we are here, that means we are unble to load the type specified // in the config xml.. notify the same. throw PSTraceSource.NewArgumentException("typeToLoad", RemotingErrorIdStrings.UnableToLoadType, EndPointConfigurationTypeName, ConfigurationDataFromXML.INITPARAMETERSTOKEN); } } /// <summary> /// InitialSessionStateProvider is used by 3rd parties to provide shell configurtion /// on the remote server. /// </summary> public abstract class PSSessionConfiguration : IDisposable { #region tracer /// <summary> /// Tracer for Server Remote session /// </summary> [TraceSourceAttribute("ServerRemoteSession", "ServerRemoteSession")] private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("ServerRemoteSession", "ServerRemoteSession"); #endregion tracer #region public interfaces /// <summary> /// Derived classes must override this to supply an InitialSesionState /// to be used to construct a Runspace for the user /// </summary> /// <param name="senderInfo"> /// User Identity for which this information is requested /// </param> /// <returns></returns> public abstract InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo); /// <summary> /// /// </summary> /// <param name="sessionConfigurationData"></param> /// <param name="senderInfo"></param> /// <param name="configProviderId"></param> /// <returns></returns> public virtual InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId) { throw new NotImplementedException(); } /// <summary> /// Maximum size (in bytes) of a deserialized object received from a remote machine. /// If null, then the size is unlimited. Default is 10MB. /// </summary> /// <param name="senderInfo"> /// User Identity for which this information is requested /// </param> /// <returns></returns> public virtual Nullable<int> GetMaximumReceivedObjectSize(PSSenderInfo senderInfo) { return BaseTransportManager.MaximumReceivedObjectSize; } /// <summary> /// Total data (in bytes) that can be received from a remote machine /// targeted towards a command. If null, then the size is unlimited. /// Default is 50MB. /// </summary> /// <param name="senderInfo"> /// User Identity for which this information is requested /// </param> /// <returns></returns> public virtual Nullable<int> GetMaximumReceivedDataSizePerCommand(PSSenderInfo senderInfo) { return BaseTransportManager.MaximumReceivedDataSize; } /// <summary> /// Derived classes can override this method to provide application private data /// that is going to be sent to the client and exposed via /// <see cref="System.Management.Automation.Runspaces.PSSession.ApplicationPrivateData"/>, /// <see cref="System.Management.Automation.Runspaces.Runspace.GetApplicationPrivateData"/> and /// <see cref="System.Management.Automation.Runspaces.RunspacePool.GetApplicationPrivateData"/> /// </summary> /// <param name="senderInfo"> /// User Identity for which this information is requested /// </param> /// <returns>Application private data or <c>null</c></returns> public virtual PSPrimitiveDictionary GetApplicationPrivateData(PSSenderInfo senderInfo) { return null; } #endregion #region IDisposable Overrides /// <summary> /// Disose this configuration object. This will be called when a Runspace/RunspacePool /// created using InitialSessionState from this object is Closed. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// /// </summary> /// <param name="isDisposing"></param> protected virtual void Dispose(bool isDisposing) { } #endregion #region GetInitialSessionState from 3rd party shell ids /// <summary> /// /// </summary> /// <param name="shellId"></param> /// <param name="initializationParameters"> /// Initialization Parameters xml passed by WSMan API. This data is read from the config /// xml and is in the following format: /// </param> /// <returns></returns> /// <exception cref="InvalidOperationException"> /// 1. Non existent InitialSessionState provider for the shellID /// </exception> /* <InitializationParameters> <Param Name="PSVersion" Value="2.0" /> <Param Name="ApplicationBase" Value="<folder path>" /> ... </InitializationParameters> */ internal static ConfigurationDataFromXML LoadEndPointConfiguration(string shellId, string initializationParameters) { ConfigurationDataFromXML configData = null; if (!s_ssnStateProviders.ContainsKey(initializationParameters)) { LoadRSConfigProvider(shellId, initializationParameters); } lock (s_syncObject) { if (!s_ssnStateProviders.TryGetValue(initializationParameters, out configData)) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.NonExistentInitialSessionStateProvider, shellId); } } return configData; } private static void LoadRSConfigProvider(string shellId, string initializationParameters) { ConfigurationDataFromXML configData = ConfigurationDataFromXML.Create(initializationParameters); Type endPointConfigType = LoadAndAnalyzeAssembly(shellId, configData.ApplicationBase, configData.AssemblyName, configData.EndPointConfigurationTypeName); Dbg.Assert(endPointConfigType != null, "EndPointConfiguration type cannot be null"); configData.EndPointConfigurationType = endPointConfigType; lock (s_syncObject) { if (!s_ssnStateProviders.ContainsKey(initializationParameters)) { s_ssnStateProviders.Add(initializationParameters, configData); } } } /// <summary> /// /// </summary> /// <param name="shellId"> /// shellId for which the assembly is getting loaded /// </param> /// <param name="applicationBase"></param> /// <param name="assemblyName"></param> /// <param name="typeToLoad"> /// type which is supplying the configuration. /// </param> /// <exception cref="InvalidOperationException"> /// </exception> /// <returns> /// Type instance representing the EndPointConfiguration to load. /// This Type can be instantiated when needed. /// </returns> private static Type LoadAndAnalyzeAssembly(string shellId, string applicationBase, string assemblyName, string typeToLoad) { if ((string.IsNullOrEmpty(assemblyName) && !string.IsNullOrEmpty(typeToLoad)) || (!string.IsNullOrEmpty(assemblyName) && string.IsNullOrEmpty(typeToLoad))) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.TypeNeedsAssembly, ConfigurationDataFromXML.ASSEMBLYTOKEN, ConfigurationDataFromXML.SHELLCONFIGTYPETOKEN, ConfigurationDataFromXML.INITPARAMETERSTOKEN); } Assembly assembly = null; if (!string.IsNullOrEmpty(assemblyName)) { PSEtwLog.LogAnalyticVerbose(PSEventId.LoadingPSCustomShellAssembly, PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, assemblyName, shellId); assembly = LoadSsnStateProviderAssembly(applicationBase, assemblyName); if (null == assembly) { throw PSTraceSource.NewArgumentException("assemblyName", RemotingErrorIdStrings.UnableToLoadAssembly, assemblyName, ConfigurationDataFromXML.INITPARAMETERSTOKEN); } } // configuration xml specified an assembly and typetoload. if (null != assembly) { try { PSEtwLog.LogAnalyticVerbose(PSEventId.LoadingPSCustomShellType, PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, typeToLoad, shellId); Type type = assembly.GetType(typeToLoad, true, true); if (null == type) { throw PSTraceSource.NewArgumentException("typeToLoad", RemotingErrorIdStrings.UnableToLoadType, typeToLoad, ConfigurationDataFromXML.INITPARAMETERSTOKEN); } return type; } catch (ReflectionTypeLoadException) { } catch (TypeLoadException) { } catch (ArgumentException) { } catch (MissingMethodException) { } catch (InvalidCastException) { } catch (TargetInvocationException) { } // if we are here, that means we are unble to load the type specified // in the config xml.. notify the same. throw PSTraceSource.NewArgumentException("typeToLoad", RemotingErrorIdStrings.UnableToLoadType, typeToLoad, ConfigurationDataFromXML.INITPARAMETERSTOKEN); } // load the default PowerShell since plugin config // did not specify a typename to load. return typeof(DefaultRemotePowerShellConfiguration); } /// <summary> /// Sets the application's current working directory to <paramref name="applicationBase"/> and /// loads the assembly <paramref name="assemblyName"/>. Once the assembly is loaded, the application's /// current working directory is set back to the orginal value. /// </summary> /// <param name="applicationBase"></param> /// <param name="assemblyName"></param> /// <returns></returns> // TODO: Send the exception message back to the client. [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")] private static Assembly LoadSsnStateProviderAssembly(string applicationBase, string assemblyName) { Dbg.Assert(!string.IsNullOrEmpty(assemblyName), "AssemblyName cannot be null."); string originalDirectory = string.Empty; if (!string.IsNullOrEmpty(applicationBase)) { // changing current working directory allows CLR loader to load dependent assemblies try { originalDirectory = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory(applicationBase); } catch (ArgumentException e) { s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", applicationBase, e.Message); } catch (PathTooLongException e) { s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", applicationBase, e.Message); } catch (FileNotFoundException e) { s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", applicationBase, e.Message); } catch (IOException e) { s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", applicationBase, e.Message); } catch (System.Security.SecurityException e) { s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", applicationBase, e.Message); } catch (UnauthorizedAccessException e) { s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", applicationBase, e.Message); } } // Even if there is erro changing current working directory..try to load the assembly // This is to allow assembly loading from GAC Assembly result = null; try { try { result = Assembly.Load(new AssemblyName(assemblyName)); } catch (FileLoadException e) { s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); } catch (BadImageFormatException e) { s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); } catch (FileNotFoundException e) { s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); } if (null != result) { return result; } s_tracer.WriteLine("Loading assembly from path {0}", applicationBase); try { String assemblyPath; if (!Path.IsPathRooted(assemblyName)) { if (!String.IsNullOrEmpty(applicationBase) && Directory.Exists(applicationBase)) { assemblyPath = Path.Combine(applicationBase, assemblyName); } else { assemblyPath = Path.Combine(Directory.GetCurrentDirectory(), assemblyName); } } else { //Rooted path of dll is provided. assemblyPath = assemblyName; } result = ClrFacade.LoadFrom(assemblyPath); } catch (FileLoadException e) { s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); } catch (BadImageFormatException e) { s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); } catch (FileNotFoundException e) { s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); } } finally { if (!string.IsNullOrEmpty(applicationBase)) { // set the application's directory back to the original directory Directory.SetCurrentDirectory(originalDirectory); } } return result; } // TODO: I think this should be moved to Utils..this way all versioning related // logic will be in one place. private static RegistryKey GetConfigurationProvidersRegistryKey() { try { RegistryKey monadRootKey = PSSnapInReader.GetMonadRootKey(); RegistryKey versionRoot = PSSnapInReader.GetVersionRootKey(monadRootKey, Utils.GetCurrentMajorVersion()); RegistryKey configProviderKey = versionRoot.OpenSubKey(configProvidersKeyName); return configProviderKey; } catch (ArgumentException) { } catch (System.Security.SecurityException) { } return null; } /// <summary> /// Read value from the property <paramref name="name"/> for registry <paramref name="registryKey"/> /// as string. /// </summary> /// <param name="registryKey"> /// Registry key from which the value is read. /// Caller should make sure this is not null. /// </param> /// <param name="name"> /// Name of the property. /// Caller should make sure this is not null. /// </param> /// <param name="mandatory"> /// True, if the property should exist. /// False, otherwise. /// </param> /// <returns> /// Value of the property. /// </returns> /// <exception cref="ArgumentException"> /// </exception> /// <exception cref="System.Security.SecurityException"> /// </exception> private static string ReadStringValue(RegistryKey registryKey, string name, bool mandatory) { Dbg.Assert(!string.IsNullOrEmpty(name), "caller should validate the name parameter"); Dbg.Assert(registryKey != null, "Caller should validate the registryKey parameter"); object value = registryKey.GetValue(name); if (value == null && mandatory == true) { s_tracer.TraceError("Mandatory property {0} not specified for registry key {1}", name, registryKey.Name); throw PSTraceSource.NewArgumentException("name", RemotingErrorIdStrings.MandatoryValueNotPresent, name, registryKey.Name); } string s = value as string; if (string.IsNullOrEmpty(s) && mandatory == true) { s_tracer.TraceError("Value is null or empty for mandatory property {0} in {1}", name, registryKey.Name); throw PSTraceSource.NewArgumentException("name", RemotingErrorIdStrings.MandatoryValueNotInCorrectFormat, name, registryKey.Name); } return s; } private const string configProvidersKeyName = "PSConfigurationProviders"; private const string configProviderApplicationBaseKeyName = "ApplicationBase"; private const string configProviderAssemblyNameKeyName = "AssemblyName"; private static Dictionary<string, ConfigurationDataFromXML> s_ssnStateProviders = new Dictionary<string, ConfigurationDataFromXML>(StringComparer.OrdinalIgnoreCase); private static object s_syncObject = new object(); #endregion } /// <summary> /// Provides Default InitialSessionState. /// </summary> internal sealed class DefaultRemotePowerShellConfiguration : PSSessionConfiguration { /// <summary> /// /// </summary> /// <param name="senderInfo"></param> /// <returns></returns> public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo) { InitialSessionState result = InitialSessionState.CreateDefault2(); // TODO: Remove this after RDS moved to $using if (senderInfo.ConnectionString != null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8")) { PSSessionConfigurationData.IsServerManager = true; } return result; } public override InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId) { if (sessionConfigurationData == null) throw new ArgumentNullException("sessionConfigurationData"); if (senderInfo == null) throw new ArgumentNullException("senderInfo"); if (configProviderId == null) throw new ArgumentNullException("configProviderId"); InitialSessionState sessionState = InitialSessionState.CreateDefault2(); // now get all the modules in the specified path and import the same if (sessionConfigurationData != null && sessionConfigurationData.ModulesToImportInternal != null) { foreach (var module in sessionConfigurationData.ModulesToImportInternal) { var moduleName = module as string; if (moduleName != null) { moduleName = Environment.ExpandEnvironmentVariables(moduleName); sessionState.ImportPSModule(new[] { moduleName }); } else { var moduleSpec = module as ModuleSpecification; if (moduleSpec != null) { var modulesToImport = new Collection<ModuleSpecification> { moduleSpec }; sessionState.ImportPSModule(modulesToImport); } } } } // TODO: Remove this after RDS moved to $using if (senderInfo.ConnectionString != null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8")) { PSSessionConfigurationData.IsServerManager = true; } return sessionState; } } #region Declarative Initial Session Configuration /// <summary> /// Specifies type of initial session state to use. Valid values are Empty and Default. /// </summary> public enum SessionType { /// <summary> /// Empty session state /// </summary> Empty, /// <summary> /// Restricted remote server /// </summary> RestrictedRemoteServer, /// <summary> /// Default session state /// </summary> Default } /// <summary> /// Configuration type entry /// </summary> internal class ConfigTypeEntry { internal delegate bool TypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path); internal string Key; internal TypeValidationCallback ValidationCallback; /// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="callback"></param> internal ConfigTypeEntry(string key, TypeValidationCallback callback) { this.Key = key; this.ValidationCallback = callback; } } /// <summary> /// Configuration file constants /// </summary> internal static class ConfigFileConstants { internal static readonly string AliasDefinitions = "AliasDefinitions"; internal static readonly string AliasDescriptionToken = "Description"; internal static readonly string AliasNameToken = "Name"; internal static readonly string AliasOptionsToken = "Options"; internal static readonly string AliasValueToken = "Value"; internal static readonly string AssembliesToLoad = "AssembliesToLoad"; internal static readonly string Author = "Author"; internal static readonly string CompanyName = "CompanyName"; internal static readonly string Copyright = "Copyright"; internal static readonly string Description = "Description"; internal static readonly string EnforceInputParameterValidation = "EnforceInputParameterValidation"; internal static readonly string EnvironmentVariables = "EnvironmentVariables"; internal static readonly string ExecutionPolicy = "ExecutionPolicy"; internal static readonly string FormatsToProcess = "FormatsToProcess"; internal static readonly string FunctionDefinitions = "FunctionDefinitions"; internal static readonly string FunctionNameToken = "Name"; internal static readonly string FunctionOptionsToken = "Options"; internal static readonly string FunctionValueToken = "ScriptBlock"; internal static readonly string GMSAAccount = "GroupManagedServiceAccount"; internal static readonly string Guid = "GUID"; internal static readonly string LanguageMode = "LanguageMode"; internal static readonly string ModulesToImport = "ModulesToImport"; internal static readonly string MountUserDrive = "MountUserDrive"; internal static readonly string PowerShellVersion = "PowerShellVersion"; internal static readonly string RequiredGroups = "RequiredGroups"; internal static readonly string RoleDefinitions = "RoleDefinitions"; internal static readonly string SchemaVersion = "SchemaVersion"; internal static readonly string ScriptsToProcess = "ScriptsToProcess"; internal static readonly string SessionType = "SessionType"; internal static readonly string RoleCapabilities = "RoleCapabilities"; internal static readonly string RunAsVirtualAccount = "RunAsVirtualAccount"; internal static readonly string RunAsVirtualAccountGroups = "RunAsVirtualAccountGroups"; internal static readonly string TranscriptDirectory = "TranscriptDirectory"; internal static readonly string TypesToProcess = "TypesToProcess"; internal static readonly string UserDriveMaxSize = "UserDriveMaximumSize"; internal static readonly string VariableDefinitions = "VariableDefinitions"; internal static readonly string VariableNameToken = "Name"; internal static readonly string VariableValueToken = "Value"; internal static readonly string VisibleAliases = "VisibleAliases"; internal static readonly string VisibleCmdlets = "VisibleCmdlets"; internal static readonly string VisibleFunctions = "VisibleFunctions"; internal static readonly string VisibleProviders = "VisibleProviders"; internal static readonly string VisibleExternalCommands = "VisibleExternalCommands"; internal static ConfigTypeEntry[] ConfigFileKeys = new ConfigTypeEntry[] { new ConfigTypeEntry(AliasDefinitions, new ConfigTypeEntry.TypeValidationCallback(AliasDefinitionsTypeValidationCallback)), new ConfigTypeEntry(AssembliesToLoad, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), new ConfigTypeEntry(Author, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), new ConfigTypeEntry(CompanyName, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), new ConfigTypeEntry(Copyright, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), new ConfigTypeEntry(Description, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), new ConfigTypeEntry(EnforceInputParameterValidation,new ConfigTypeEntry.TypeValidationCallback(BooleanTypeValidationCallback)), new ConfigTypeEntry(EnvironmentVariables, new ConfigTypeEntry.TypeValidationCallback(HashtableTypeValiationCallback)), new ConfigTypeEntry(ExecutionPolicy, new ConfigTypeEntry.TypeValidationCallback(ExecutionPolicyValidationCallback)), new ConfigTypeEntry(FormatsToProcess, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), new ConfigTypeEntry(FunctionDefinitions, new ConfigTypeEntry.TypeValidationCallback(FunctionDefinitionsTypeValidationCallback)), new ConfigTypeEntry(GMSAAccount, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), new ConfigTypeEntry(Guid, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), new ConfigTypeEntry(LanguageMode, new ConfigTypeEntry.TypeValidationCallback(LanugageModeValidationCallback)), new ConfigTypeEntry(ModulesToImport, new ConfigTypeEntry.TypeValidationCallback(StringOrHashtableArrayTypeValidationCallback)), new ConfigTypeEntry(MountUserDrive, new ConfigTypeEntry.TypeValidationCallback(BooleanTypeValidationCallback)), new ConfigTypeEntry(PowerShellVersion, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), new ConfigTypeEntry(RequiredGroups, new ConfigTypeEntry.TypeValidationCallback(HashtableTypeValiationCallback)), new ConfigTypeEntry(RoleCapabilities, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), new ConfigTypeEntry(RoleDefinitions, new ConfigTypeEntry.TypeValidationCallback(HashtableTypeValiationCallback)), new ConfigTypeEntry(RunAsVirtualAccount, new ConfigTypeEntry.TypeValidationCallback(BooleanTypeValidationCallback)), new ConfigTypeEntry(RunAsVirtualAccountGroups, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), new ConfigTypeEntry(SchemaVersion, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), new ConfigTypeEntry(ScriptsToProcess, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), new ConfigTypeEntry(SessionType, new ConfigTypeEntry.TypeValidationCallback(ISSValidationCallback)), new ConfigTypeEntry(TranscriptDirectory, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), new ConfigTypeEntry(TypesToProcess, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), new ConfigTypeEntry(UserDriveMaxSize, new ConfigTypeEntry.TypeValidationCallback(IntegerTypeValidationCallback)), new ConfigTypeEntry(VariableDefinitions, new ConfigTypeEntry.TypeValidationCallback(VariableDefinitionsTypeValidationCallback)), new ConfigTypeEntry(VisibleAliases, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), new ConfigTypeEntry(VisibleCmdlets, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), new ConfigTypeEntry(VisibleFunctions, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), new ConfigTypeEntry(VisibleProviders, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), new ConfigTypeEntry(VisibleExternalCommands, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), }; /// <summary> /// Checks if the given key is a valid key /// </summary> /// <param name="de"></param> /// <param name="cmdlet"></param> /// <param name="path"></param> /// <returns></returns> internal static bool IsValidKey(DictionaryEntry de, PSCmdlet cmdlet, string path) { bool validKey = false; foreach (ConfigTypeEntry configEntry in ConfigFileKeys) { if (String.Equals(configEntry.Key, de.Key.ToString(), StringComparison.OrdinalIgnoreCase)) { validKey = true; if (configEntry.ValidationCallback(de.Key.ToString(), de.Value, cmdlet, path)) { return true; } } } if (!validKey) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCInvalidKey, de.Key.ToString(), path)); } return false; } /// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="obj"></param> /// <param name="cmdlet"></param> /// <param name="path"></param> /// <returns></returns> private static bool ISSValidationCallback(string key, object obj, PSCmdlet cmdlet, string path) { string value = obj as string; if (!String.IsNullOrEmpty(value)) { try { Enum.Parse(typeof(SessionType), value, true); return true; } catch (ArgumentException) { // Do nothing here } } cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeValidEnum, key, typeof(SessionType).FullName, LanguagePrimitives.EnumSingleTypeConverter.EnumValues(typeof(SessionType)), path)); return false; } /// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="obj"></param> /// <param name="cmdlet"></param> /// <param name="path"></param> /// <returns></returns> private static bool LanugageModeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path) { string value = obj as string; if (!String.IsNullOrEmpty(value)) { try { Enum.Parse(typeof(PSLanguageMode), value, true); return true; } catch (ArgumentException) { // Do nothing here } } cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeValidEnum, key, typeof(PSLanguageMode).FullName, LanguagePrimitives.EnumSingleTypeConverter.EnumValues(typeof(PSLanguageMode)), path)); return false; } /// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="obj"></param> /// <param name="cmdlet"></param> /// <param name="path"></param> /// <returns></returns> private static bool ExecutionPolicyValidationCallback(string key, object obj, PSCmdlet cmdlet, string path) { string value = obj as string; if (!String.IsNullOrEmpty(value)) { try { Enum.Parse(DISCUtils.ExecutionPolicyType, value, true); return true; } catch (ArgumentException) { // Do nothing here } } cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeValidEnum, key, DISCUtils.ExecutionPolicyType.FullName, LanguagePrimitives.EnumSingleTypeConverter.EnumValues(DISCUtils.ExecutionPolicyType), path)); return false; } /// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="obj"></param> /// <param name="cmdlet"></param> /// <param name="path"></param> /// <returns></returns> private static bool HashtableTypeValiationCallback(string key, object obj, PSCmdlet cmdlet, string path) { Hashtable hash = obj as Hashtable; if (hash == null) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtable, key, path)); return false; } return true; } /// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="obj"></param> /// <param name="cmdlet"></param> /// <param name="path"></param> /// <returns></returns> private static bool AliasDefinitionsTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path) { Hashtable[] hashtables = DISCPowerShellConfiguration.TryGetHashtableArray(obj); if (hashtables == null) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, key, path)); return false; } foreach (Hashtable hashtable in hashtables) { if (!hashtable.ContainsKey(AliasNameToken)) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, key, AliasNameToken, path)); return false; } if (!hashtable.ContainsKey(AliasValueToken)) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, key, AliasValueToken, path)); return false; } foreach (string aliasKey in hashtable.Keys) { if (!String.Equals(aliasKey, AliasNameToken, StringComparison.OrdinalIgnoreCase) && !String.Equals(aliasKey, AliasValueToken, StringComparison.OrdinalIgnoreCase) && !String.Equals(aliasKey, AliasDescriptionToken, StringComparison.OrdinalIgnoreCase) && !String.Equals(aliasKey, AliasOptionsToken, StringComparison.OrdinalIgnoreCase)) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, aliasKey, key, path)); return false; } } } return true; } /// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="obj"></param> /// <param name="cmdlet"></param> /// <param name="path"></param> /// <returns></returns> private static bool FunctionDefinitionsTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path) { Hashtable[] hashtables = DISCPowerShellConfiguration.TryGetHashtableArray(obj); if (hashtables == null) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, key, path)); return false; } foreach (Hashtable hashtable in hashtables) { if (!hashtable.ContainsKey(FunctionNameToken)) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, key, FunctionNameToken, path)); return false; } if (!hashtable.ContainsKey(FunctionValueToken)) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, key, FunctionValueToken, path)); return false; } if ((hashtable[FunctionValueToken] as ScriptBlock) == null) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCKeyMustBeScriptBlock, FunctionValueToken, key, path)); return false; } foreach (string functionKey in hashtable.Keys) { if (!String.Equals(functionKey, FunctionNameToken, StringComparison.OrdinalIgnoreCase) && !String.Equals(functionKey, FunctionValueToken, StringComparison.OrdinalIgnoreCase) && !String.Equals(functionKey, FunctionOptionsToken, StringComparison.OrdinalIgnoreCase)) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, functionKey, key, path)); return false; } } } return true; } /// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="obj"></param> /// <param name="cmdlet"></param> /// <param name="path"></param> /// <returns></returns> private static bool VariableDefinitionsTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path) { Hashtable[] hashtables = DISCPowerShellConfiguration.TryGetHashtableArray(obj); if (hashtables == null) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, key, path)); return false; } foreach (Hashtable hashtable in hashtables) { if (!hashtable.ContainsKey(VariableNameToken)) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, key, VariableNameToken, path)); return false; } if (!hashtable.ContainsKey(VariableValueToken)) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, key, VariableValueToken, path)); return false; } foreach (string variableKey in hashtable.Keys) { if (!String.Equals(variableKey, VariableNameToken, StringComparison.OrdinalIgnoreCase) && !String.Equals(variableKey, VariableValueToken, StringComparison.OrdinalIgnoreCase)) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, variableKey, key, path)); return false; } } } return true; } /// <summary> /// Verifies a string type /// </summary> /// <param name="obj"></param> /// <param name="cmdlet"></param> /// <param name="key"></param> /// <param name="path"></param> /// <returns></returns> private static bool StringTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path) { if (!(obj is string)) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeString, key, path)); return false; } return true; } /// <summary> /// Verifies a string array type /// </summary> /// <param name="obj"></param> /// <param name="cmdlet"></param> /// <param name="key"></param> /// <param name="path"></param> /// <returns></returns> private static bool StringArrayTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path) { if (DISCPowerShellConfiguration.TryGetStringArray(obj) == null) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringArray, key, path)); return false; } return true; } private static bool BooleanTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path) { if (!(obj is bool)) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeBoolean, key, path)); return false; } return true; } private static bool IntegerTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path) { if (!(obj is int) && !(obj is long)) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeInteger, key, path)); return false; } return true; } /// <summary> /// Verifies that an array contains only string or hashtable elements /// </summary> /// <param name="obj"></param> /// <param name="cmdlet"></param> /// <param name="key"></param> /// <param name="path"></param> /// <returns></returns> private static bool StringOrHashtableArrayTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path) { if (DISCPowerShellConfiguration.TryGetObjectsOfType<object>(obj, new Type[] { typeof(string), typeof(Hashtable) }) == null) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArrayInFile, key, path)); return false; } return true; } } #region DISC Utilities /// <summary> /// DISC utilities /// </summary> internal static class DISCUtils { #region Private data internal static Type ExecutionPolicyType = null; /// <summary> /// !! NOTE that this list MUST be updated when new capability session configuration properties are added. /// </summary> private static readonly HashSet<string> s_allowedRoleCapabilityKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "RoleCapabilities", "ModulesToImport", "VisibleAliases", "VisibleCmdlets", "VisibleFunctions", "VisibleExternalCommands", "VisibleProviders", "ScriptsToProcess", "AliasDefinitions", "FunctionDefinitions", "VariableDefinitions", "EnvironmentVariables", "TypesToProcess", "FormatsToProcess", "AssembliesToLoad" }; #endregion /// <summary> /// Create an ExternalScriptInfo object from a file path. /// </summary> /// <param name="context">execution context</param> /// <param name="fileName">The path to the file</param> /// <param name="scriptName">The base name of the script</param> /// <returns>The ExternalScriptInfo object.</returns> internal static ExternalScriptInfo GetScriptInfoForFile(ExecutionContext context, string fileName, out string scriptName) { scriptName = Path.GetFileName(fileName); ExternalScriptInfo scriptInfo = new ExternalScriptInfo(scriptName, fileName, context); // Skip ShouldRun check for .psd1 files. // Use ValidateScriptInfo() for explicitly validating the checkpolicy for psd1 file. // if (!scriptName.EndsWith(".psd1", StringComparison.OrdinalIgnoreCase)) { context.AuthorizationManager.ShouldRunInternal(scriptInfo, CommandOrigin.Internal, context.EngineHostInterface); // Verify that the PSversion is correct... CommandDiscovery.VerifyPSVersion(scriptInfo); // If we got this far, the check succeeded and we don't need to check again. scriptInfo.SignatureChecked = true; } return scriptInfo; } /// <summary> /// Loads the configuration file into a hashtable /// </summary> /// <param name="context">execution context</param> /// <param name="scriptInfo">the ExternalScriptInfo object</param> /// <returns>configuration hashtable</returns> internal static Hashtable LoadConfigFile(ExecutionContext context, ExternalScriptInfo scriptInfo) { object result; object oldPSScriptRoot = context.GetVariableValue(SpecialVariables.PSScriptRootVarPath); object oldPSCommandPath = context.GetVariableValue(SpecialVariables.PSCommandPathVarPath); try { // Set the PSScriptRoot variable in the modules session state context.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(scriptInfo.Definition)); context.SetVariable(SpecialVariables.PSCommandPathVarPath, scriptInfo.Definition); result = PSObject.Base(scriptInfo.ScriptBlock.InvokeReturnAsIs()); } finally { context.SetVariable(SpecialVariables.PSScriptRootVarPath, oldPSScriptRoot); context.SetVariable(SpecialVariables.PSCommandPathVarPath, oldPSCommandPath); } return result as Hashtable; } /// <summary> /// Verifies the configuration hashtable /// </summary> /// <param name="table">configuration hashtable</param> /// <param name="cmdlet"></param> /// <param name="path"></param> /// <returns>true if valid, false otherwise</returns> internal static bool VerifyConfigTable(Hashtable table, PSCmdlet cmdlet, string path) { bool hasSchemaVersion = false; foreach (DictionaryEntry de in table) { if (!ConfigFileConstants.IsValidKey(de, cmdlet, path)) { return false; } if (de.Key.ToString().Equals(ConfigFileConstants.SchemaVersion, StringComparison.OrdinalIgnoreCase)) { hasSchemaVersion = true; } } if (!hasSchemaVersion) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCMissingSchemaVersion, path)); return false; } try { ValidateAbsolutePaths(cmdlet.SessionState, table, path); ValidateExtensions(table, path); } catch (InvalidOperationException e) { cmdlet.WriteVerbose(e.Message); return false; } return true; } /// <summary> /// /// </summary> private static void ValidatePS1XMLExtension(string key, string[] paths, string filePath) { if (paths == null) { return; } foreach (string path in paths) { try { string ext = System.IO.Path.GetExtension(path); if (!ext.Equals(".ps1xml", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCInvalidExtension, key, ext, ".ps1xml")); } } catch (ArgumentException argumentException) { throw new InvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.ErrorParsingTheKeyInPSSessionConfigurationFile, key, filePath), argumentException); } } } /// <summary> /// /// </summary> private static void ValidatePS1OrPSM1Extension(string key, string[] paths, string filePath) { if (paths == null) { return; } foreach (string path in paths) { try { string ext = System.IO.Path.GetExtension(path); if (!ext.Equals(StringLiterals.PowerShellScriptFileExtension, StringComparison.OrdinalIgnoreCase) && !ext.Equals(StringLiterals.PowerShellModuleFileExtension, StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCInvalidExtension, key, ext, String.Join(", ", StringLiterals.PowerShellScriptFileExtension, StringLiterals.PowerShellModuleFileExtension))); } } catch (ArgumentException argumentException) { throw new InvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.ErrorParsingTheKeyInPSSessionConfigurationFile, key, filePath), argumentException); } } } /// <summary> /// /// </summary> /// <param name="table"></param> /// <param name="filePath"></param> internal static void ValidateExtensions(Hashtable table, string filePath) { if (table.ContainsKey(ConfigFileConstants.TypesToProcess)) { ValidatePS1XMLExtension(ConfigFileConstants.TypesToProcess, DISCPowerShellConfiguration.TryGetStringArray(table[ConfigFileConstants.TypesToProcess]), filePath); } if (table.ContainsKey(ConfigFileConstants.FormatsToProcess)) { ValidatePS1XMLExtension(ConfigFileConstants.FormatsToProcess, DISCPowerShellConfiguration.TryGetStringArray(table[ConfigFileConstants.FormatsToProcess]), filePath); } if (table.ContainsKey(ConfigFileConstants.ScriptsToProcess)) { ValidatePS1OrPSM1Extension(ConfigFileConstants.ScriptsToProcess, DISCPowerShellConfiguration.TryGetStringArray(table[ConfigFileConstants.ScriptsToProcess]), filePath); } } /// <summary> /// Checks if all paths are absolute paths /// </summary> /// <param name="state"></param> /// <param name="table"></param> /// <param name="filePath"></param> internal static void ValidateAbsolutePaths(SessionState state, Hashtable table, string filePath) { if (table.ContainsKey(ConfigFileConstants.TypesToProcess)) { ValidateAbsolutePath(state, ConfigFileConstants.TypesToProcess, DISCPowerShellConfiguration.TryGetStringArray(table[ConfigFileConstants.TypesToProcess]), filePath); } if (table.ContainsKey(ConfigFileConstants.FormatsToProcess)) { ValidateAbsolutePath(state, ConfigFileConstants.FormatsToProcess, DISCPowerShellConfiguration.TryGetStringArray(table[ConfigFileConstants.FormatsToProcess]), filePath); } if (table.ContainsKey(ConfigFileConstants.ScriptsToProcess)) { ValidateAbsolutePath(state, ConfigFileConstants.ScriptsToProcess, DISCPowerShellConfiguration.TryGetStringArray(table[ConfigFileConstants.ScriptsToProcess]), filePath); } } /// <summary> /// Checks if a path is an absolute path /// </summary> /// <param name="key"></param> /// <param name="state"></param> /// <param name="paths"></param> /// <param name="filePath"></param> internal static void ValidateAbsolutePath(SessionState state, string key, string[] paths, string filePath) { if (paths == null) { return; } string driveName; foreach (string path in paths) { if (!state.Path.IsPSAbsolute(path, out driveName)) { throw new InvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCPathsMustBeAbsolute, key, path, filePath)); } } } /// <summary> /// Validates Role Definition hash entries /// /// RoleDefinitions = @{ /// 'Everyone' = @{ /// 'RoIeCapabilities' = 'Basic' }; /// 'Administrators' = @{ /// 'VisibleCmdlets' = 'Get-Process','Get-Location'; 'VisibleFunctions = 'TabExpansion2' } } /// </summary> /// <param name="roleDefinitions"></param> internal static void ValidateRoleDefinitions(IDictionary roleDefinitions) { foreach (var roleKey in roleDefinitions.Keys) { if (!(roleKey is string)) { var invalidOperationEx = new PSInvalidOperationException( string.Format(RemotingErrorIdStrings.InvalidRoleKeyType, roleKey.GetType().FullName)); invalidOperationEx.SetErrorId("InvalidRoleKeyType"); throw invalidOperationEx; } // // Each role capability in the role definition item should contain a hash table with allowed role capability key. // IDictionary roleDefinition = roleDefinitions[roleKey] as IDictionary; if (roleDefinition == null) { var invalidOperationEx = new PSInvalidOperationException( StringUtil.Format(RemotingErrorIdStrings.InvalidRoleValue, roleKey)); invalidOperationEx.SetErrorId("InvalidRoleEntryNotHashtable"); throw invalidOperationEx; } foreach (var key in roleDefinition.Keys) { // Ensure each role capability key is valid. string roleCapabilityKey = key as string; if (roleCapabilityKey == null) { var invalidOperationEx = new PSInvalidOperationException( string.Format(RemotingErrorIdStrings.InvalidRoleCapabilityKeyType, key.GetType().FullName)); invalidOperationEx.SetErrorId("InvalidRoleCapabilityKeyType"); throw invalidOperationEx; } if (!s_allowedRoleCapabilityKeys.Contains(roleCapabilityKey)) { var invalidOperationEx = new PSInvalidOperationException( string.Format(RemotingErrorIdStrings.InvalidRoleCapabilityKey, roleCapabilityKey)); invalidOperationEx.SetErrorId("InvalidRoleCapabilityKey"); throw invalidOperationEx; } } } } } #endregion /// <summary> /// Creates an initial session state based on the configuration language for PSSC files /// </summary> internal sealed class DISCPowerShellConfiguration : PSSessionConfiguration { private string _configFile; private Hashtable _configHash; /// <summary> /// Gets the configuration hashtable that results from parsing the specified configuration file /// </summary> internal Hashtable ConfigHash { get { return _configHash; } } /// <summary> /// Creates a new instance of a Declarative Initial Session State Configuration /// </summary> /// <param name="configFile">The path to the .pssc file representing the initial session state</param> /// <param name="roleVerifier"> /// The verifier that PowerShell should call to determine if groups in the Role entry apply to the /// target session. If you have a WindowsPrincipal for a user, for example, create a Function that /// checks windowsPrincipal.IsInRole(). /// </param> internal DISCPowerShellConfiguration(string configFile, Func<string, bool> roleVerifier) { _configFile = configFile; if (roleVerifier == null) { roleVerifier = (role) => false; } Runspace backupRunspace = Runspace.DefaultRunspace; try { Runspace.DefaultRunspace = RunspaceFactory.CreateRunspace(); Runspace.DefaultRunspace.Open(); string scriptName; ExternalScriptInfo script = DISCUtils.GetScriptInfoForFile(Runspace.DefaultRunspace.ExecutionContext, configFile, out scriptName); _configHash = DISCUtils.LoadConfigFile(Runspace.DefaultRunspace.ExecutionContext, script); MergeRoleRulesIntoConfigHash(roleVerifier); MergeRoleCapabilitiesIntoConfigHash(); Runspace.DefaultRunspace.Close(); } catch (PSSecurityException e) { string message = StringUtil.Format(RemotingErrorIdStrings.InvalidPSSessionConfigurationFilePath, configFile); PSInvalidOperationException ioe = new PSInvalidOperationException(message, e); ioe.SetErrorId("InvalidPSSessionConfigurationFilePath"); throw ioe; } finally { Runspace.DefaultRunspace = backupRunspace; } } // Takes the "Roles" node in the config hash, and merges all that apply into the base configuration. private void MergeRoleRulesIntoConfigHash(Func<string, bool> roleVerifier) { if (_configHash.ContainsKey(ConfigFileConstants.RoleDefinitions)) { // Extract the 'Roles' hashtable IDictionary roleEntry = _configHash[ConfigFileConstants.RoleDefinitions] as IDictionary; if (roleEntry == null) { string message = StringUtil.Format(RemotingErrorIdStrings.InvalidRoleEntry, _configHash["Roles"].GetType().FullName); PSInvalidOperationException ioe = new PSInvalidOperationException(message); ioe.SetErrorId("InvalidRoleDefinitionNotHashtable"); throw ioe; } // Ensure that role definitions contain valid entries. DISCUtils.ValidateRoleDefinitions(roleEntry); // Go through the Roles hashtable foreach (Object role in roleEntry.Keys) { // Check if this role applies to the connected user if (roleVerifier(role.ToString())) { // Extract their specific configuration IDictionary roleCustomizations = roleEntry[role] as IDictionary; if (roleCustomizations == null) { string message = StringUtil.Format(RemotingErrorIdStrings.InvalidRoleValue, role.ToString()); PSInvalidOperationException ioe = new PSInvalidOperationException(message); ioe.SetErrorId("InvalidRoleValueNotHashtable"); throw ioe; } MergeConfigHashIntoConfigHash(roleCustomizations); } } } } // Takes the "RoleCapabilities" node in the config hash, and merges its values into the base configuration. private void MergeRoleCapabilitiesIntoConfigHash() { if (_configHash.ContainsKey(ConfigFileConstants.RoleCapabilities)) { string[] roleCapabilities = TryGetStringArray(_configHash[ConfigFileConstants.RoleCapabilities]); if (roleCapabilities != null) { foreach (string roleCapability in roleCapabilities) { string roleCapabilityPath = GetRoleCapabilityPath(roleCapability); if (String.IsNullOrEmpty(roleCapabilityPath)) { string message = StringUtil.Format(RemotingErrorIdStrings.CouldNotFindRoleCapability, roleCapability, roleCapability + ".psrc"); PSInvalidOperationException ioe = new PSInvalidOperationException(message); ioe.SetErrorId("CouldNotFindRoleCapability"); throw ioe; } DISCPowerShellConfiguration roleCapabilityConfiguration = new DISCPowerShellConfiguration(roleCapabilityPath, null); IDictionary roleCapabilityConfigurationItems = roleCapabilityConfiguration.ConfigHash; MergeConfigHashIntoConfigHash(roleCapabilityConfigurationItems); } } } } // Merge a role / role capability hashtable into the master configuration hashtable private void MergeConfigHashIntoConfigHash(IDictionary childConfigHash) { foreach (Object customization in childConfigHash.Keys) { string customizationString = customization.ToString(); ArrayList customizationValue = new ArrayList(); // First, take all values from the master config table if (_configHash.ContainsKey(customizationString)) { IEnumerable existingValueAsCollection = LanguagePrimitives.GetEnumerable(_configHash[customization]); if (existingValueAsCollection != null) { foreach (Object value in existingValueAsCollection) { customizationValue.Add(value); } } else { customizationValue.Add(_configHash[customization]); } } // Then add the current role's values IEnumerable newValueAsCollection = LanguagePrimitives.GetEnumerable(childConfigHash[customization]); if (newValueAsCollection != null) { foreach (Object value in newValueAsCollection) { customizationValue.Add(value); } } else { customizationValue.Add(childConfigHash[customization]); } // Now update the config table for this role. _configHash[customization] = customizationValue.ToArray(); } } private string GetRoleCapabilityPath(string roleCapability) { string moduleName = "*"; if (roleCapability.IndexOf('\\') != -1) { string[] components = roleCapability.Split(Utils.Separators.Backslash, 2); moduleName = components[0]; roleCapability = components[1]; } // Go through each directory in the module path string[] modulePaths = ModuleIntrinsics.GetModulePath().Split(Utils.Separators.PathSeparator); foreach (string path in modulePaths) { try { // And then each module in that directory foreach (string directory in Directory.EnumerateDirectories(path, moduleName)) { string roleCapabilitiesPath = Path.Combine(directory, "RoleCapabilities"); if (Directory.Exists(roleCapabilitiesPath)) { // If the role capabilities directory exists, look for .psrc files with the role capability name foreach (string roleCapabilityPath in Directory.EnumerateFiles(roleCapabilitiesPath, roleCapability + ".psrc")) { return roleCapabilityPath; } } } } catch (IOException) { // Could not enumerate the directories for a broken module path element. Just try the next. } catch (UnauthorizedAccessException) { // Could not enumerate the directories for a broken module path element. Just try the next. } } return null; } /// <summary> /// Creates an initial session state from a configuration file (DISC) /// </summary> /// <param name="senderInfo"></param> /// <returns></returns> public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo) { InitialSessionState iss = null; // Create the initial session state string initialSessionState = TryGetValue(_configHash, ConfigFileConstants.SessionType); SessionType sessionType = SessionType.Default; bool cmdletVisibilityApplied = IsNonDefaultVisibiltySpecified(ConfigFileConstants.VisibleCmdlets); bool functionVisiblityApplied = IsNonDefaultVisibiltySpecified(ConfigFileConstants.VisibleFunctions); bool aliasVisibilityApplied = IsNonDefaultVisibiltySpecified(ConfigFileConstants.VisibleAliases); bool providerVisibiltyApplied = IsNonDefaultVisibiltySpecified(ConfigFileConstants.VisibleProviders); bool processDefaultSessionStateVisibility = false; if (!String.IsNullOrEmpty(initialSessionState)) { sessionType = (SessionType)Enum.Parse(typeof(SessionType), initialSessionState, true); if (sessionType == SessionType.Empty) { iss = InitialSessionState.Create(); } else if (sessionType == SessionType.RestrictedRemoteServer) { iss = InitialSessionState.CreateRestricted(SessionCapabilities.RemoteServer); } else { iss = InitialSessionState.CreateDefault2(); processDefaultSessionStateVisibility = true; } } else { iss = InitialSessionState.CreateDefault2(); processDefaultSessionStateVisibility = true; } if (cmdletVisibilityApplied || functionVisiblityApplied || aliasVisibilityApplied || providerVisibiltyApplied || IsNonDefaultVisibiltySpecified(ConfigFileConstants.VisibleExternalCommands)) { iss.DefaultCommandVisibility = SessionStateEntryVisibility.Private; // If visibility is applied on a default runspace then set initial ISS // commands visibility to private. if (processDefaultSessionStateVisibility) { foreach (var cmd in iss.Commands) { cmd.Visibility = iss.DefaultCommandVisibility; } } } // Add providers if (providerVisibiltyApplied) { string[] providers = TryGetStringArray(_configHash[ConfigFileConstants.VisibleProviders]); if (providers != null) { System.Collections.Generic.HashSet<string> addedProviders = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (string provider in providers) { if (!String.IsNullOrEmpty(provider)) { // Look up providers from provider name including wildcards. var providersFound = iss.Providers.LookUpByName(provider); foreach (var providerFound in providersFound) { if (!addedProviders.Contains(providerFound.Name)) { addedProviders.Add(providerFound.Name); providerFound.Visibility = SessionStateEntryVisibility.Public; } } } } } } // Add assemblies and modules); if (_configHash.ContainsKey(ConfigFileConstants.AssembliesToLoad)) { string[] assemblies = TryGetStringArray(_configHash[ConfigFileConstants.AssembliesToLoad]); if (assemblies != null) { foreach (string assembly in assemblies) { iss.Assemblies.Add(new SessionStateAssemblyEntry(assembly)); } } } if (_configHash.ContainsKey(ConfigFileConstants.ModulesToImport)) { object[] modules = TryGetObjectsOfType<object>(_configHash[ConfigFileConstants.ModulesToImport], new Type[] { typeof(string), typeof(Hashtable) }); if ((_configHash[ConfigFileConstants.ModulesToImport] != null) && (modules == null)) { string message = StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray, ConfigFileConstants.ModulesToImport); PSInvalidOperationException ioe = new PSInvalidOperationException(message); ioe.SetErrorId("InvalidModulesToImportKeyEntries"); throw ioe; } if (null != modules) { Collection<ModuleSpecification> modulesToImport = new Collection<ModuleSpecification>(); foreach (object module in modules) { ModuleSpecification moduleSpec = null; string moduleName = module as string; if (!string.IsNullOrEmpty(moduleName)) { moduleSpec = new ModuleSpecification(moduleName); } else { Hashtable moduleHash = module as Hashtable; if (null != moduleHash) { moduleSpec = new ModuleSpecification(moduleHash); } } // Now add the moduleSpec to modulesToImport if (null != moduleSpec) { if (string.Equals(InitialSessionState.CoreModule, moduleSpec.Name, StringComparison.OrdinalIgnoreCase)) { if (sessionType == SessionType.Empty) { // Win8: 627752 Cannot load microsoft.powershell.core module as part of DISC // Convert Microsoft.PowerShell.Core module -> Microsoft.PowerShell.Core snapin. // Doing this Import only in SessionType.Empty case, because other cases already do this. // In V3, Micorosft.PowerShell.Core module is not installed externally. iss.ImportCorePSSnapIn(); } // silently ignore Microsoft.PowerShell.Core for other cases ie., SessionType.RestrictedRemoteServer && SessionType.Default } else { modulesToImport.Add(moduleSpec); } } } iss.ImportPSModule(modulesToImport); } } // Define members if (_configHash.ContainsKey(ConfigFileConstants.VisibleCmdlets)) { object[] cmdlets = TryGetObjectsOfType<object>(_configHash[ConfigFileConstants.VisibleCmdlets], new Type[] { typeof(string), typeof(Hashtable) }); if (cmdlets == null) { string message = StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray, ConfigFileConstants.VisibleCmdlets); PSInvalidOperationException ioe = new PSInvalidOperationException(message); ioe.SetErrorId("InvalidVisibleCmdletsKeyEntries"); throw ioe; } ProcessVisibleCommands(iss, cmdlets); } if (_configHash.ContainsKey(ConfigFileConstants.AliasDefinitions)) { Hashtable[] aliases = TryGetHashtableArray(_configHash[ConfigFileConstants.AliasDefinitions]); if (aliases != null) { foreach (Hashtable alias in aliases) { SessionStateAliasEntry entry = CreateSessionStateAliasEntry(alias, aliasVisibilityApplied); if (entry != null) { // Indexing iss.Commands with a command that does not exist returns 'null', rather // than some sort of KeyNotFound exception. if (iss.Commands[entry.Name] != null) { iss.Commands.Remove(entry.Name, typeof(SessionStateAliasEntry)); } iss.Commands.Add(entry); } } } } if (_configHash.ContainsKey(ConfigFileConstants.VisibleAliases)) { string[] aliases = DISCPowerShellConfiguration.TryGetStringArray(_configHash[ConfigFileConstants.VisibleAliases]); if (aliases != null) { foreach (string alias in aliases) { if (!String.IsNullOrEmpty(alias)) { bool found = false; // Look up aliases using alias name including wildcards. Collection<SessionStateCommandEntry> existingEntries = iss.Commands.LookUpByName(alias); foreach (SessionStateCommandEntry existingEntry in existingEntries) { if (existingEntry.CommandType == CommandTypes.Alias) { existingEntry.Visibility = SessionStateEntryVisibility.Public; found = true; } } if (!found || WildcardPattern.ContainsWildcardCharacters(alias)) { iss.UnresolvedCommandsToExpose.Add(alias); } } } } } if (_configHash.ContainsKey(ConfigFileConstants.FunctionDefinitions)) { Hashtable[] functions = TryGetHashtableArray(_configHash[ConfigFileConstants.FunctionDefinitions]); if (functions != null) { foreach (Hashtable function in functions) { SessionStateFunctionEntry entry = CreateSessionStateFunctionEntry(function, functionVisiblityApplied); if (entry != null) { iss.Commands.Add(entry); } } } } if (_configHash.ContainsKey(ConfigFileConstants.VisibleFunctions)) { object[] functions = TryGetObjectsOfType<object>(_configHash[ConfigFileConstants.VisibleFunctions], new Type[] { typeof(string), typeof(Hashtable) }); if (functions == null) { string message = StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray, ConfigFileConstants.VisibleFunctions); PSInvalidOperationException ioe = new PSInvalidOperationException(message); ioe.SetErrorId("InvalidVisibleFunctionsKeyEntries"); throw ioe; } ProcessVisibleCommands(iss, functions); } if (_configHash.ContainsKey(ConfigFileConstants.VariableDefinitions)) { Hashtable[] variables = TryGetHashtableArray(_configHash[ConfigFileConstants.VariableDefinitions]); if (variables != null) { foreach (Hashtable variable in variables) { if (variable.ContainsKey(ConfigFileConstants.VariableValueToken) && ((variable[ConfigFileConstants.VariableValueToken] as ScriptBlock) != null)) { iss.DynamicVariablesToDefine.Add(variable); continue; } SessionStateVariableEntry entry = CreateSessionStateVariableEntry(variable, iss.LanguageMode); if (entry != null) { iss.Variables.Add(entry); } } } } if (_configHash.ContainsKey(ConfigFileConstants.EnvironmentVariables)) { Hashtable[] variablesList = TryGetHashtableArray(_configHash[ConfigFileConstants.EnvironmentVariables]); if (variablesList != null) { foreach (Hashtable variables in variablesList) { foreach (DictionaryEntry variable in variables) { SessionStateVariableEntry entry = new SessionStateVariableEntry(variable.Key.ToString(), variable.Value.ToString(), null); iss.EnvironmentVariables.Add(entry); } } } } // Update type data if (_configHash.ContainsKey(ConfigFileConstants.TypesToProcess)) { string[] types = DISCPowerShellConfiguration.TryGetStringArray(_configHash[ConfigFileConstants.TypesToProcess]); if (types != null) { foreach (string type in types) { if (!String.IsNullOrEmpty(type)) { iss.Types.Add(new SessionStateTypeEntry(type)); } } } } // Update format data if (_configHash.ContainsKey(ConfigFileConstants.FormatsToProcess)) { string[] formats = DISCPowerShellConfiguration.TryGetStringArray(_configHash[ConfigFileConstants.FormatsToProcess]); if (formats != null) { foreach (string format in formats) { if (!String.IsNullOrEmpty(format)) { iss.Formats.Add(new SessionStateFormatEntry(format)); } } } } // Add external commands if (_configHash.ContainsKey(ConfigFileConstants.VisibleExternalCommands)) { string[] externalCommands = TryGetStringArray(_configHash[ConfigFileConstants.VisibleExternalCommands]); if (externalCommands != null) { foreach (string command in externalCommands) { if (command.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) { iss.Commands.Add( new SessionStateScriptEntry(command, SessionStateEntryVisibility.Public)); } else { if (command == "*") { iss.Commands.Add( new SessionStateScriptEntry(command, SessionStateEntryVisibility.Public)); } iss.Commands.Add( new SessionStateApplicationEntry(command, SessionStateEntryVisibility.Public)); } } } } // Register startup scripts if (_configHash.ContainsKey(ConfigFileConstants.ScriptsToProcess)) { string[] startupScripts = DISCPowerShellConfiguration.TryGetStringArray(_configHash[ConfigFileConstants.ScriptsToProcess]); if (startupScripts != null) { foreach (string script in startupScripts) { if (!String.IsNullOrEmpty(script)) { iss.StartupScripts.Add(script); } } } } // Now apply visibilty logic if (cmdletVisibilityApplied || functionVisiblityApplied || aliasVisibilityApplied || providerVisibiltyApplied) { if (sessionType == SessionType.Default) { // autoloading preference is none, so modules cannot be autoloaded. Since the session type is default, // load PowerShell default modules iss.ImportPSCoreModule(InitialSessionState.EngineModules.ToArray()); } if (cmdletVisibilityApplied) { // Import-Module is needed for internal *required modules* processing, so make visibility private. var importModuleEntry = iss.Commands["Import-Module"]; if (importModuleEntry.Count == 1) { importModuleEntry[0].Visibility = SessionStateEntryVisibility.Private; } } if (aliasVisibilityApplied) { // Import-Module is needed for internal *required modules* processing, so make visibility private. var importModuleAliasEntry = iss.Commands["ipmo"]; if (importModuleAliasEntry.Count == 1) { importModuleAliasEntry[0].Visibility = SessionStateEntryVisibility.Private; } } iss.DefaultCommandVisibility = SessionStateEntryVisibility.Private; iss.Variables.Add(new SessionStateVariableEntry(SpecialVariables.PSModuleAutoLoading, PSModuleAutoLoadingPreference.None, string.Empty, ScopedItemOptions.None)); } // Set the execution policy if (_configHash.ContainsKey(ConfigFileConstants.ExecutionPolicy)) { Microsoft.PowerShell.ExecutionPolicy executionPolicy = (Microsoft.PowerShell.ExecutionPolicy)Enum.Parse( typeof(Microsoft.PowerShell.ExecutionPolicy), _configHash[ConfigFileConstants.ExecutionPolicy].ToString(), true); iss.ExecutionPolicy = executionPolicy; } // Set the language mode if (_configHash.ContainsKey(ConfigFileConstants.LanguageMode)) { System.Management.Automation.PSLanguageMode languageMode = (System.Management.Automation.PSLanguageMode)Enum.Parse( typeof(System.Management.Automation.PSLanguageMode), _configHash[ConfigFileConstants.LanguageMode].ToString(), true); iss.LanguageMode = languageMode; } // Set the transcript directory if (_configHash.ContainsKey(ConfigFileConstants.TranscriptDirectory)) { iss.TranscriptDirectory = _configHash[ConfigFileConstants.TranscriptDirectory].ToString(); } // Process User Drive if (_configHash.ContainsKey(ConfigFileConstants.MountUserDrive)) { if (Convert.ToBoolean(_configHash[ConfigFileConstants.MountUserDrive], CultureInfo.InvariantCulture) == true) { iss.UserDriveEnabled = true; iss.UserDriveUserName = (senderInfo != null) ? senderInfo.UserInfo.Identity.Name : null; // Set user drive max drive if provided. if (_configHash.ContainsKey(ConfigFileConstants.UserDriveMaxSize)) { long userDriveMaxSize = Convert.ToInt64(_configHash[ConfigFileConstants.UserDriveMaxSize]); if (userDriveMaxSize > 0) { iss.UserDriveMaximumSize = userDriveMaxSize; } } // Input parameter validation enforcement is always true when a User drive is created. iss.EnforceInputParameterValidation = true; // Add function definitions for Copy-Item support. ProcessCopyItemFunctionDefinitions(iss); } } return iss; } // Adds Copy-Item remote session helper functions to the ISS. private static void ProcessCopyItemFunctionDefinitions(InitialSessionState iss) { // Copy file to remote helper functions. foreach (var copyToRemoteFn in CopyFileRemoteUtils.GetAllCopyToRemoteScriptFunctions()) { var functionEntry = new SessionStateFunctionEntry( copyToRemoteFn["Name"] as string, copyToRemoteFn["Definition"] as string); iss.Commands.Add(functionEntry); } // Copy file from remote helper functions. foreach (var copyFromRemoteFn in CopyFileRemoteUtils.GetAllCopyFromRemoteScriptFunctions()) { var functionEntry = new SessionStateFunctionEntry( copyFromRemoteFn["Name"] as string, copyFromRemoteFn["Definition"] as string); iss.Commands.Add(functionEntry); } } private static void ProcessVisibleCommands(InitialSessionState iss, object[] commands) { // A dictionary of: function name -> Parameters // Parameters = A dictionary of parameter names -> Modifications // Modifications = A dictionary of modification types (ValidatePattern, ValidateSet) to the interim value // for that attribute, as a HashSet of strings. For ValidateSet, this will be used as a collection of strings // directly during proxy generation. For For ValidatePattern, it will be combined into a regex // like: '^(Pattern1|Pattern2|Pattern3)$' during proxy generation. Dictionary<string, Hashtable> commandModifications = new Dictionary<string, Hashtable>(StringComparer.OrdinalIgnoreCase); // Create a hash set of current modules to import so that fully qualified commands can include their // module if needed. HashSet<string> commandModuleNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var moduleSpec in iss.ModuleSpecificationsToImport) { commandModuleNames.Add(moduleSpec.Name); } foreach (Object commandObject in commands) { if (commandObject == null) { continue; } // If it's just a string, this is a visible command String command = commandObject as String; if (!String.IsNullOrEmpty(command)) { ProcessVisibleCommand(iss, command, commandModuleNames); } else { // If it's a hashtable, it represents a customization to a cmdlet. // (I.e.: Exposed parameter with ValidateSet and / or ValidatePattern) // Collect these so that we can post-process them. IDictionary commandModification = commandObject as IDictionary; if (commandModification != null) { ProcessCommandModification(commandModifications, commandModification); } } } // Now, save the commandModifications table for post-processing during runspace creation, // where we have the command info foreach (var pair in commandModifications) { iss.CommandModifications.Add(pair.Key, pair.Value); } } private static void ProcessCommandModification(Dictionary<string, Hashtable> commandModifications, IDictionary commandModification) { string commandName = commandModification["Name"] as string; Hashtable[] parameters = null; if (commandModification.Contains("Parameters")) { parameters = TryGetHashtableArray(commandModification["Parameters"]); if (parameters != null) { // Validate that the parameter restriction has the right keys foreach (Hashtable parameter in parameters) { if (!parameter.ContainsKey("Name")) { parameters = null; break; } } } } // Validate that we got the Name and Parameters keys if ((commandName == null) || (parameters == null)) { string hashtableKey = commandName; if (String.IsNullOrEmpty(hashtableKey)) { IEnumerator errorKey = commandModification.Keys.GetEnumerator(); errorKey.MoveNext(); hashtableKey = errorKey.Current.ToString(); } string message = StringUtil.Format(RemotingErrorIdStrings.DISCCommandModificationSyntax, hashtableKey); PSInvalidOperationException ioe = new PSInvalidOperationException(message); ioe.SetErrorId("InvalidVisibleCommandKeyEntries"); throw ioe; } // Ensure we have the hashtable representing the current command being modified Hashtable parameterModifications; if (!commandModifications.TryGetValue(commandName, out parameterModifications)) { parameterModifications = new Hashtable(StringComparer.OrdinalIgnoreCase); commandModifications[commandName] = parameterModifications; } foreach (IDictionary parameter in parameters) { // Ensure we have the hashtable representing the current parameter being modified string parameterName = parameter["Name"].ToString(); Hashtable currentParameterModification = parameterModifications[parameterName] as Hashtable; if (currentParameterModification == null) { currentParameterModification = new Hashtable(StringComparer.OrdinalIgnoreCase); parameterModifications[parameterName] = currentParameterModification; } foreach (string parameterModification in parameter.Keys) { if (String.Equals("Name", parameterModification, StringComparison.OrdinalIgnoreCase)) { continue; } // Go through the keys, adding them to the current parameter modification if (!currentParameterModification.Contains(parameterModification)) { currentParameterModification[parameterModification] = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } HashSet<string> currentParameterModificationValue = (HashSet<string>)currentParameterModification[parameterModification]; foreach (string parameterModificationValue in TryGetStringArray(parameter[parameterModification])) { if (!String.IsNullOrEmpty(parameterModificationValue)) { currentParameterModificationValue.Add(parameterModificationValue); } } } } } private static void ProcessVisibleCommand(InitialSessionState iss, string command, HashSet<string> moduleNames) { bool found = false; // Defer module restricted command processing to runspace bind time. // Module restricted command names are fully qualified with the module name: // <ModuleName>\<CommandName>, e.g., PSScheduledJob\*JobTrigger* if (command.IndexOf('\\') < 0) { // Look up commands from command name including wildcards. Collection<SessionStateCommandEntry> existingEntries = iss.Commands.LookUpByName(command); foreach (SessionStateCommandEntry existingEntry in existingEntries) { if ((existingEntry.CommandType == CommandTypes.Cmdlet) || (existingEntry.CommandType == CommandTypes.Function)) { existingEntry.Visibility = SessionStateEntryVisibility.Public; found = true; } } } else { // Extract the module name and ensure it is part of the ISS modules to process list. string moduleName; Utils.ParseCommandName(command, out moduleName); if (!string.IsNullOrEmpty(moduleName) && !moduleNames.Contains(moduleName)) { moduleNames.Add(moduleName); iss.ImportPSModule(new string[] { moduleName }); } } if (!found || WildcardPattern.ContainsWildcardCharacters(command)) { iss.UnresolvedCommandsToExpose.Add(command); } } /// <summary> /// Creates an alias entry /// </summary> private SessionStateAliasEntry CreateSessionStateAliasEntry(Hashtable alias, bool isAliasVisibilityDefined) { string name = TryGetValue(alias, ConfigFileConstants.AliasNameToken); if (String.IsNullOrEmpty(name)) { return null; } string value = TryGetValue(alias, ConfigFileConstants.AliasValueToken); if (String.IsNullOrEmpty(value)) { return null; } string description = TryGetValue(alias, ConfigFileConstants.AliasDescriptionToken); ScopedItemOptions options = ScopedItemOptions.None; string optionsString = TryGetValue(alias, ConfigFileConstants.AliasOptionsToken); if (!String.IsNullOrEmpty(optionsString)) { options = (ScopedItemOptions)Enum.Parse(typeof(ScopedItemOptions), optionsString, true); } SessionStateEntryVisibility visibility = SessionStateEntryVisibility.Private; if (!isAliasVisibilityDefined) { visibility = SessionStateEntryVisibility.Public; } return new SessionStateAliasEntry(name, value, description, options, visibility); } /// <summary> /// Creates a function entry /// </summary> /// <returns></returns> private SessionStateFunctionEntry CreateSessionStateFunctionEntry(Hashtable function, bool isFunctionVisibilityDefined) { string name = TryGetValue(function, ConfigFileConstants.FunctionNameToken); if (String.IsNullOrEmpty(name)) { return null; } string value = TryGetValue(function, ConfigFileConstants.FunctionValueToken); if (String.IsNullOrEmpty(value)) { return null; } ScopedItemOptions options = ScopedItemOptions.None; string optionsString = TryGetValue(function, ConfigFileConstants.FunctionOptionsToken); if (!String.IsNullOrEmpty(optionsString)) { options = (ScopedItemOptions)Enum.Parse(typeof(ScopedItemOptions), optionsString, true); } ScriptBlock newFunction = ScriptBlock.Create(value); newFunction.LanguageMode = PSLanguageMode.FullLanguage; SessionStateEntryVisibility functionVisibility = SessionStateEntryVisibility.Private; if (!isFunctionVisibilityDefined) { functionVisibility = SessionStateEntryVisibility.Public; } return new SessionStateFunctionEntry(name, value, options, functionVisibility, newFunction, null); } /// <summary> /// Creates a variable entry /// </summary> private SessionStateVariableEntry CreateSessionStateVariableEntry(Hashtable variable, PSLanguageMode languageMode) { string name = TryGetValue(variable, ConfigFileConstants.VariableNameToken); if (String.IsNullOrEmpty(name)) { return null; } string value = TryGetValue(variable, ConfigFileConstants.VariableValueToken); if (String.IsNullOrEmpty(value)) { return null; } string description = TryGetValue(variable, ConfigFileConstants.AliasDescriptionToken); ScopedItemOptions options = ScopedItemOptions.None; string optionsString = TryGetValue(variable, ConfigFileConstants.AliasOptionsToken); if (!String.IsNullOrEmpty(optionsString)) { options = (ScopedItemOptions)Enum.Parse(typeof(ScopedItemOptions), optionsString, true); } SessionStateEntryVisibility visibility = SessionStateEntryVisibility.Private; if (languageMode == PSLanguageMode.FullLanguage) { visibility = SessionStateEntryVisibility.Public; } return new SessionStateVariableEntry(name, value, description, options, new Collections.ObjectModel.Collection<Attribute>(), visibility); } /// <summary> /// Applies the command (cmdlet/function/alias) visibility settings to the <paramref name="iss"/> /// </summary> /// <param name="configFileKey"></param> /// <returns></returns> private bool IsNonDefaultVisibiltySpecified(string configFileKey) { if (_configHash.ContainsKey(configFileKey)) { string[] commands = DISCPowerShellConfiguration.TryGetStringArray(_configHash[configFileKey]); if ((commands == null) || (commands.Length == 0)) { return false; } return true; } return false; } /// <summary> /// Attempts to get a value from a hashtable /// </summary> /// <param name="table"></param> /// <param name="key"></param> /// <returns></returns> internal static string TryGetValue(Hashtable table, string key) { if (table.ContainsKey(key)) { return table[key].ToString(); } return String.Empty; } /// <summary> /// Attempts to get a hastable array from an object /// </summary> /// <param name="hashObj"></param> /// <returns></returns> internal static Hashtable[] TryGetHashtableArray(object hashObj) { // Scalar case Hashtable hashtable = hashObj as Hashtable; if (hashtable != null) { return new[] { hashtable }; } // 1. Direct conversion Hashtable[] hashArray = hashObj as Hashtable[]; if (hashArray == null) { // 2. Convert from object array object[] objArray = hashObj as object[]; if (objArray != null) { hashArray = new Hashtable[objArray.Length]; for (int i = 0; i < hashArray.Length; i++) { Hashtable hash = objArray[i] as Hashtable; if (hash == null) { return null; } hashArray[i] = hash; } } } return hashArray; } /// <summary> /// Attemps to get a string array from a hashtable /// </summary> /// <param name="hashObj"></param> /// <returns></returns> internal static string[] TryGetStringArray(object hashObj) { object[] objs = hashObj as object[]; if (objs == null) { // Scalar case object obj = hashObj as object; if (obj != null) { return new string[] { obj.ToString() }; } else { return null; } } string[] result = new string[objs.Length]; for (int i = 0; i < objs.Length; i++) { result[i] = objs[i].ToString(); } return result; } internal static T[] TryGetObjectsOfType<T>(object hashObj, IEnumerable<Type> types) where T : class { object[] objs = hashObj as object[]; if (objs == null) { // Scalar case object obj = hashObj; if (obj != null) { foreach (Type type in types) { if (obj.GetType().Equals(type)) { return new T[] { obj as T }; } } } return null; } T[] result = new T[objs.Length]; for (int i = 0; i < objs.Length; i++) { int i1 = i; if (types.Any(type => objs[i1].GetType().Equals(type))) { result[i] = objs[i] as T; } else { return null; } } return result; } } #endregion }
43.29242
192
0.560851
[ "Apache-2.0", "MIT" ]
HydAu/PowerShell
src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs
124,509
C#
using xLiAd.CodeMonkey.Entities; using xLiAd.CodeMonkey.Entities.Dtos; using xLiAd.CodeMonkey.Entities.QueryDtos; using xLiAd.CodeMonkey.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace xLiAd.CodeMonkey.WebApp.Controllers { //[Authorize] public class AuthRoleController : Controller { private readonly IAuthRoleService authRoleService; public AuthRoleController(IAuthRoleService authRoleService) { this.authRoleService = authRoleService; } public IActionResult Index() { return View(); } [HttpPost] public IApiResultModel Add(AuthRole authRole) { return authRoleService.Add(authRole); } [HttpPost] public IApiResultModel Edit(AuthRole authRole) { return authRoleService.Edit(authRole); } [HttpPost] public IApiResultModel Delete(int id) { return authRoleService.Delete(id); } [HttpPost] public IApiResultModel GetListData(PageQueryDto queryDto) { var result = authRoleService.GetPageList(queryDto); return result; } } }
25.055556
67
0.645233
[ "Apache-2.0" ]
zl33842901/CodeMonkey
xLiAd.CodeMonkey.WebApp/Controllers/AuthRoleController.cs
1,355
C#
using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using Xunit; namespace MartinCl2.Text.Json.Serialization.Tests { public class EnumerableTests { [Fact] public async Task ArrayTest() { int[] payload = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; await TestUtil.AssertJsonIsIdentical(payload); } [Fact] public async Task ValueTypeEnumeratorTest() { HashSet<int> payload = new HashSet<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; await TestUtil.AssertJsonIsIdentical(payload); } [Fact] public async Task ListTest() { List<int> payload = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; await TestUtil.AssertJsonIsIdentical(payload); } [Fact] public async Task IEnumerableTest() { IEnumerable<int> payload = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; await TestUtil.AssertJsonIsIdentical(payload); } [Fact] public async Task IListTest() { IList<int> payload = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; await TestUtil.AssertJsonIsIdentical(payload); } [Fact] public async Task IReadOnlyListTest() { IReadOnlyList<int> payload = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; await TestUtil.AssertJsonIsIdentical(payload); } public class IEnumerableTestPayload : IEnumerable<int> { private IEnumerable<int> Generate() { yield return 0; yield return 1; yield return 2; yield return 3; yield return 4; yield return 5; yield return 6; yield return 7; yield return 8; yield return 9; } IEnumerator<int> IEnumerable<int>.GetEnumerator() { IEnumerable<int> generator = Generate(); return generator.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { IEnumerable<int> generator = Generate(); return generator.GetEnumerator(); } } [Fact] public async Task CustomEnumerableTest() => await TestUtil.TestSerializationWithDefaultProperties<IEnumerableTestPayload>(); } }
29.344444
133
0.499053
[ "MIT" ]
Martin1994/JsonJitSerializer
tests/MartinCl2/Text/Json/Serialization/Tests/EnumerableTests.cs
2,641
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 forecast-2018-06-26.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.ForecastService.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ForecastService.Model.Internal.MarshallTransformations { /// <summary> /// DataDestination Marshaller /// </summary> public class DataDestinationMarshaller : IRequestMarshaller<DataDestination, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(DataDestination requestObject, JsonMarshallerContext context) { if(requestObject.IsSetS3Config()) { context.Writer.WritePropertyName("S3Config"); context.Writer.WriteObjectStart(); var marshaller = S3ConfigMarshaller.Instance; marshaller.Marshall(requestObject.S3Config, context); context.Writer.WriteObjectEnd(); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static DataDestinationMarshaller Instance = new DataDestinationMarshaller(); } }
33.164179
106
0.679568
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/ForecastService/Generated/Model/Internal/MarshallTransformations/DataDestinationMarshaller.cs
2,222
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using RVTR.Lodging.Domain.Abstracts; using RVTR.Lodging.Domain.Attributes; namespace RVTR.Lodging.Domain.Models { /// <summary> /// Represents the _Lodging_ model /// </summary> public class LodgingModel : AEntity, IValidatableObject { /// <summary> /// Address id of the lodging's location /// </summary> /// <value></value> public int AddressId { get; set; } /// <summary> /// Address property of the lodging model (required) /// </summary> /// <value></value> public AddressModel Address { get; set; } /// <summary> /// Name of the lodging (required) /// </summary> /// <value></value> [Required(ErrorMessage = "Name is required")] [MaxLength(100, ErrorMessage = "Max length is 100 characters")] public string Name { get; set; } /// <summary> /// Number of bathrooms at the lodging has to be one can have as any amount /// </summary> /// <value></value> [FacilitiesAttribute] public int Bathrooms { get; set; } /// <summary> /// Rental list of the lodging /// </summary> /// <value></value> public IEnumerable<RentalModel> Rentals { get; set; } = new List<RentalModel>(); /// <summary> /// Review list for the lodging /// </summary> /// <value></value> public IEnumerable<ReviewModel> Reviews { get; set; } = new List<ReviewModel>(); /// <summary> /// Review list for the images /// </summary> /// <value></value> public IEnumerable<ImageModel> Images { get; set; } = new List<ImageModel>(); /// <summary> /// Represents the _Lodging_ `Validate` model /// </summary> /// <param name="validationContext"></param> /// <returns></returns> public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) => new List<ValidationResult>(); } }
28.880597
119
0.623773
[ "MIT" ]
Jasonw679/rvtrx-api-lodging
aspnet/RVTR.Lodging.Domain/Models/LodgingModel.cs
1,935
C#
 using Terraria; using Terraria.ID; using Terraria.Audio; using Terraria.ModLoader; namespace GoldensMisc.Projectiles { public class UndyingSpear : ModProjectile { public override bool IsLoadingEnabled(Mod mod) { return ModContent.GetInstance<ServerConfig>().SpearofJustice; } public override void SetDefaults() { Projectile.scale = 1.3f; Projectile.width = 14; Projectile.height = 14; Projectile.aiStyle = 1; Projectile.friendly = true; Projectile.penetrate = 3; Projectile.DamageType = DamageClass.Magic; Projectile.ignoreWater = true; Projectile.glowMask = MiscGlowMasks.UndyingSpearProjectile; AIType = ProjectileID.JavelinFriendly; } public override void OnHitNPC(NPC target, int damage, float knockback, bool crit) { int type = Main.rand.Next(2) == 0 ? ModContent.ProjectileType<MagicSpearMini>() : ModContent.ProjectileType<MagicSpearMiniAlt>(); switch(Main.rand.Next(4)) { case 0: //Shoot right Projectile.NewProjectile(Projectile.GetProjectileSource_FromThis(), target.Left.X - 100, target.Left.Y, 5f, 0f, type, Projectile.damage / 2, 1f, Projectile.owner, 1, 1); return; case 1: //Shoot down Projectile.NewProjectile(Projectile.GetProjectileSource_FromThis(), target.Top.X, target.Top.Y - 100, 0f, 5f, type, Projectile.damage / 2, 1f, Projectile.owner, 1, 1); return; case 2: //Shoot left Projectile.NewProjectile(Projectile.GetProjectileSource_FromThis(), target.Right.X + 100, target.Right.Y, -5f, 0f, type, Projectile.damage / 2, 1f, Projectile.owner, 1, 1); return; case 3: //Shoot up Projectile.NewProjectile(Projectile.GetProjectileSource_FromThis(), target.Bottom.X, target.Bottom.Y + 100, 0f, -5f, type, Projectile.damage / 2, 1f, Projectile.owner, 1, 1); return; } } public override void Kill(int timeLeft) { SoundEngine.PlaySound(SoundID.Item, Projectile.position, 10); for (int i = 0; i < 5; i++) { int dust = Dust.NewDust(Projectile.position, Projectile.width, Projectile.height, DustID.BlueTorch, Projectile.velocity.X, Projectile.velocity.Y); Main.dust[dust].scale = 1.5f; } } } }
34.935484
179
0.710988
[ "MIT" ]
gardenappl/Miscellania
Projectiles/UndyingSpear.cs
2,168
C#
using Catalog.API.Entities; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Catalog.API.Data { public class CatalogContextSeed { public static void SeedData(IMongoCollection<Product> productCollection) { bool existProduct = productCollection.Find(a => true).Any(); if(!existProduct) { productCollection.InsertManyAsync(GetConfiguredProducts()); } } private static IEnumerable<Product> GetConfiguredProducts() { return new List<Product>() { new Product() { Id = "602d2149e773f2a3990b47f5", Name = "IPhone X", Summary = "This phone is the company's biggest change to its flagship smartphone in years. It includes a borderless.", Description = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.", ImageFile = "product-1.png", Price = 950.00M, Category = "Smart Phone" }, new Product() { Id = "602d2149e773f2a3990b47f6", Name = "Samsung 10", Summary = "This phone is the company's biggest change to its flagship smartphone in years. It includes a borderless.", Description = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.", ImageFile = "product-2.png", Price = 840.00M, Category = "Smart Phone" }, new Product() { Id = "602d2149e773f2a3990b47f7", Name = "Huawei Plus", Summary = "This phone is the company's biggest change to its flagship smartphone in years. It includes a borderless.", Description = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.", ImageFile = "product-3.png", Price = 650.00M, Category = "White Appliances" }, new Product() { Id = "602d2149e773f2a3990b47f8", Name = "Xiaomi Mi 9", Summary = "This phone is the company's biggest change to its flagship smartphone in years. It includes a borderless.", Description = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.", ImageFile = "product-4.png", Price = 470.00M, Category = "White Appliances" }, new Product() { Id = "602d2149e773f2a3990b47f9", Name = "HTC U11+ Plus", Summary = "This phone is the company's biggest change to its flagship smartphone in years. It includes a borderless.", Description = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.", ImageFile = "product-5.png", Price = 380.00M, Category = "Smart Phone" }, new Product() { Id = "602d2149e773f2a3990b47fa", Name = "LG G7 ThinQ", Summary = "This phone is the company's biggest change to its flagship smartphone in years. It includes a borderless.", Description = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.", ImageFile = "product-6.png", Price = 240.00M, Category = "Home Kitchen" } }; } } }
67.640449
468
0.631894
[ "MIT" ]
Raddmou/AspnetMicroservices
src/Services/Catalog/Catalog.API/Data/CatalogContextSeed.cs
6,022
C#
using System; using System.Collections.Generic; namespace _04_LongestSubsequenceOfEqualNumbers { class Program { static void Main(string[] args) { List<int> numbers = new List<int>{ 1, 2, 2, 3, 3, 3, 5, 7, 10, 10, 13 }; List<int> longestSubsequence = new List<int>(); List<int> currentSubsequence = new List<int>(); currentSubsequence.Add(numbers[0]); for (int i = 1; i < numbers.Count; i++) { if (numbers[i] == currentSubsequence[0]) { currentSubsequence.Add(numbers[i]); } else { if (currentSubsequence.Count > longestSubsequence.Count) { longestSubsequence.Clear(); longestSubsequence.AddRange(currentSubsequence); } currentSubsequence = new List<int>(); currentSubsequence.Add(numbers[i]); } } if (currentSubsequence.Count > longestSubsequence.Count) { longestSubsequence.Clear(); longestSubsequence.AddRange(currentSubsequence); } Console.WriteLine(string.Join(" ", longestSubsequence)); } } }
32.547619
84
0.492319
[ "MIT" ]
SophiaKiryakova/TelerikAcademyAlpha
Module II/01. DSA/02. Linear-Data-Structures/04_LongestSubsequenceOfEqualNumbers/Program.cs
1,369
C#
using Microsoft.AspNetCore.Mvc; namespace OrleansPoc.Api.SiloHost.Controllers { [ApiController] [Route("[controller]")] public class HealthController: ControllerBase { [HttpGet] public IActionResult Get() { return Ok(); } } }
16.1875
47
0.671815
[ "MIT" ]
rjygraham/DurableEventProcessing
src/OrleansPoc.Api.SiloHost/Controllers/HealthController.cs
261
C#
namespace Dn6Poc.DocuMgmtPortal.Models { public class LoginViewModel { public string Username { get; init; } = string.Empty; public string Password { get; init; } = string.Empty; } }
23.555556
61
0.641509
[ "MIT" ]
ongzhixian/dc6Poc
Dn6Poc.DocuMgmtPortal/Models/LoginViewModel.cs
214
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Szlem.Persistence.EF; namespace Szlem.Persistence.EF.Migrations { [DbContext(typeof(AppDbContext))] [Migration("20200114103323_UserIdAsGuid")] partial class UserIdAsGuid { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.0"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("ClaimType") .HasColumnType("TEXT"); b.Property<string>("ClaimValue") .HasColumnType("TEXT"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("ClaimType") .HasColumnType("TEXT"); b.Property<string>("ClaimValue") .HasColumnType("TEXT"); b.Property<string>("UserId") .IsRequired() .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b => { b.Property<string>("LoginProvider") .HasColumnType("TEXT"); b.Property<string>("ProviderKey") .HasColumnType("TEXT"); b.Property<string>("ProviderDisplayName") .HasColumnType("TEXT"); b.Property<string>("UserId") .IsRequired() .HasColumnType("TEXT"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b => { b.Property<string>("UserId") .HasColumnType("TEXT"); b.Property<string>("RoleId") .HasColumnType("TEXT"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b => { b.Property<string>("UserId") .HasColumnType("TEXT"); b.Property<string>("LoginProvider") .HasColumnType("TEXT"); b.Property<string>("Name") .HasColumnType("TEXT"); b.Property<string>("Value") .HasColumnType("TEXT"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Szlem.Models.Editions.Edition", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("CumulativeStatistics") .HasColumnType("TEXT"); b.Property<DateTime>("EndDate") .HasColumnType("TEXT"); b.Property<string>("Name") .HasColumnType("TEXT"); b.Property<DateTime>("StartDate") .HasColumnType("TEXT"); b.Property<string>("ThisEditionStatistics") .HasColumnType("TEXT"); b.HasKey("ID"); b.ToTable("Edition"); }); modelBuilder.Entity("Szlem.Models.Schools.ContactPerson", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Email") .HasColumnType("TEXT"); b.Property<string>("Name") .HasColumnType("TEXT"); b.Property<string>("PhoneNumber") .HasColumnType("TEXT"); b.Property<string>("Position") .HasColumnType("TEXT"); b.Property<int?>("SchoolID") .HasColumnType("INTEGER"); b.HasKey("ID"); b.HasIndex("SchoolID"); b.ToTable("ContactPerson"); }); modelBuilder.Entity("Szlem.Models.Schools.School", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Address") .HasColumnType("TEXT"); b.Property<string>("City") .HasColumnType("TEXT"); b.Property<string>("ContactPhoneNumber") .HasColumnType("TEXT"); b.Property<string>("Email") .HasColumnType("TEXT"); b.Property<string>("Name") .HasColumnType("TEXT"); b.Property<string>("Website") .HasColumnType("TEXT"); b.HasKey("ID"); b.ToTable("School"); }); modelBuilder.Entity("Szlem.Models.Schools.Timetable", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnName("ID") .HasColumnType("INTEGER"); b.Property<string>("Lessons") .HasColumnType("TEXT"); b.Property<int?>("SchoolID") .HasColumnType("INTEGER"); b.Property<string>("TimeSlots") .HasColumnType("TEXT"); b.Property<DateTime>("ValidFrom") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("SchoolID"); b.ToTable("Timetable"); }); modelBuilder.Entity("Szlem.Models.Users.ApplicationIdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("TEXT"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("TEXT"); b.Property<string>("Description") .HasColumnType("TEXT"); b.Property<string>("Name") .HasColumnType("TEXT") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasColumnType("TEXT") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Szlem.Models.Users.ApplicationUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("TEXT"); b.Property<int>("AccessFailedCount") .HasColumnType("INTEGER"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("TEXT"); b.Property<string>("Email") .HasColumnType("TEXT") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .HasColumnType("INTEGER"); b.Property<bool>("LockoutEnabled") .HasColumnType("INTEGER"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("TEXT"); b.Property<string>("NormalizedEmail") .HasColumnType("TEXT") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasColumnType("TEXT") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnType("TEXT"); b.Property<string>("PhoneNumber") .HasColumnType("TEXT"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("INTEGER"); b.Property<string>("SecurityStamp") .HasColumnType("TEXT"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("INTEGER"); b.Property<string>("UserName") .HasColumnType("TEXT") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b => { b.HasOne("Szlem.Models.Users.ApplicationIdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b => { b.HasOne("Szlem.Models.Users.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b => { b.HasOne("Szlem.Models.Users.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b => { b.HasOne("Szlem.Models.Users.ApplicationIdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Szlem.Models.Users.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b => { b.HasOne("Szlem.Models.Users.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Szlem.Models.Schools.ContactPerson", b => { b.HasOne("Szlem.Models.Schools.School", null) .WithMany("ContactPersons") .HasForeignKey("SchoolID"); }); modelBuilder.Entity("Szlem.Models.Schools.Timetable", b => { b.HasOne("Szlem.Models.Schools.School", "School") .WithMany("Timetables") .HasForeignKey("SchoolID"); }); #pragma warning restore 612, 618 } } }
34.63038
100
0.434535
[ "MIT" ]
Yaevh/fcc-net50-bug-repro
src/Szlem.Persistence.EF/Migrations/20200114103323_UserIdAsGuid.Designer.cs
13,681
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; using Facebook.Unity; namespace States { public class LoginState : BaseState { #region Public Behaviour public LoginState (object parent) : base(parent) { } public override void Enter () { base.Enter(); loginScreenController.Show(); } public void OnFacebookButtonClickEvent (object sender, EventArgs e) { FB.Init(() => PlayerService.LoginWithFacebook().Then(() => OnLoginSuccess())); loginScreenController.Hide(); mainMenuScreenController.Load(); } public void OnGuestButtonClickEvent (object sender, EventArgs e) { PlayerService.LoginWithCustomID(Config.deviceId).Then(() => OnLoginSuccess()); loginScreenController.Hide(); mainMenuScreenController.Load(); } public void OnLoginSuccess () { PlayerService.GetPlayer().Then((player) => { app.SetPlayer(player); app.player.data.IncreaseGamesCount(); DataService.SetPlayerData(app.player.data); mainController.ToMainMenuState(); }).Catch(error => Debug.Log(error.Message)); // Maybe there should be an error screen here. DataService.GetAppData().Then((appData) => { app.SetInfo(appData); footerController.Show(app.data); }); if (FB.IsLoggedIn) PlayerService.GetFacebookPictureURL().Then(result => PlayerService.UpdatePlayerAvatarURL(result)); } #endregion #region Protected Behaviour protected override void AddListeners () { LoginScreenController.FacebookButtonClickEvent += OnFacebookButtonClickEvent; LoginScreenController.GuestButtonClickEvent += OnGuestButtonClickEvent; } protected override void RemoveListeners () { LoginScreenController.FacebookButtonClickEvent -= OnFacebookButtonClickEvent; LoginScreenController.GuestButtonClickEvent -= OnGuestButtonClickEvent; } #endregion } }
33.742424
114
0.629996
[ "MIT" ]
gonzaloiv/playfabground
Assets/Scripts/Controllers/States/LoginState.cs
2,229
C#
using System; using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.IE; using OpenQA.Selenium.Edge; using OpenQA.Selenium.Firefox; using Protractor.Samples.PageObjects.Support; namespace Protractor.Samples.PageObjects { /* * E2E testing against the AngularJS tutorial Step 7 sample: * http://docs.angularjs.org/tutorial/step_07 */ [TestFixture] public class PageObjectsTests { private IWebDriver driver; [SetUp] public void SetUp() { // Using PhantomJS //driver = new PhantomJSDriver(); // Using Chrome driver = new ChromeDriver(TestContext.CurrentContext.TestDirectory); // Using Internet Explorer //var options = new InternetExplorerOptions() { IntroduceInstabilityByIgnoringProtectedModeSettings = true }; //driver = new InternetExplorerDriver(options); // Using Microsoft Edge //driver = new EdgeDriver(); // Using Firefox //driver = new FirefoxDriver(); // Required for TestForAngular and WaitForAngular scripts driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(5); } [TearDown] public void TearDown() { driver.Quit(); } [Test(Description = "Should filter the phone list as user types into the search box")] public void ShouldFilter() { var step5Page = new TutorialStep7Page(driver, "http://angular.github.io/angular-phonecat/step-7/app/"); Assert.AreEqual(20, step5Page.GetResultsCount()); step5Page.SearchFor("Motorola"); Assert.AreEqual(8, step5Page.GetResultsCount()); step5Page.SearchFor("Nexus"); Assert.AreEqual(1, step5Page.GetResultsCount()); } [Test(Description = "Should be possible to control phone order via the drop down select box")] public void ShouldSort() { var step5Page = new TutorialStep7Page(driver, "http://angular.github.io/angular-phonecat/step-7/app/"); step5Page.SearchFor("tablet"); Assert.AreEqual(2, step5Page.GetResultsCount()); step5Page.SortByAge(); Assert.AreEqual("Motorola XOOM™ with Wi-Fi", step5Page.GetResultsPhoneName(0)); Assert.AreEqual("MOTOROLA XOOM™", step5Page.GetResultsPhoneName(1)); step5Page.SortByName(); Assert.AreEqual("MOTOROLA XOOM™", step5Page.GetResultsPhoneName(0)); Assert.AreEqual("Motorola XOOM™ with Wi-Fi", step5Page.GetResultsPhoneName(1)); } } }
32.783133
121
0.626608
[ "MIT" ]
qubidt/protractor-net
examples/Protractor.Samples/PageObjects/PageObjectsTests.cs
2,731
C#
using DevExtreme.AspNet.Data.Aggregation; using DevExtreme.AspNet.Data.ResponseModel; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace DevExtreme.AspNet.Data.Tests { public class AggregateCalculatorTests { [Fact] public void Minimal() { var data = new[] { new Group { items = new object[] { 1, 5 } }, new Group { items = new object[] { 7 } } }; var calculator = new AggregateCalculator<int>(data, new DefaultAccessor<int>(), new[] { new SummaryInfo { Selector = "this", SummaryType = "sum" } }, new[] { new SummaryInfo { Selector = "this", SummaryType = "sum" } } ); var totals = calculator.Run(); Assert.Equal(13M, totals[0]); Assert.Equal(6M, data[0].summary[0]); Assert.Equal(7M, data[1].summary[0]); } void AssertCalculation(object[] data, object expectedSum, object expectedMin, object expectedMax, object expectedAvg, object expectedCount) { /* SQL script to validate drop table if exists t1; #create table t1 (a int); #insert into t1 (a) values (1), (3), (5); #create table t1 (a varchar(32)); #insert into t1 (a) values ('a'), ('z'); #insert into t1 (a) values (null); select concat( " sum=", coalesce(sum(a), 'N'), " min=", coalesce(min(a), 'N'), " max=", coalesce(max(a), 'N'), " avg=", coalesce(avg(a), 'N'), " count=", coalesce(count(*), 'N') ) from t1; */ var summaries = new[] { new SummaryInfo { Selector = "this", SummaryType = "sum" }, new SummaryInfo { Selector = "this", SummaryType = "min" }, new SummaryInfo { Selector = "this", SummaryType = "max" }, new SummaryInfo { Selector = "this", SummaryType = "avg" }, new SummaryInfo { SummaryType = "count" }, }; var totals = new AggregateCalculator<object>(data, new DefaultAccessor<object>(), summaries, null).Run(); Assert.Equal(expectedSum, totals[0]); Assert.Equal(expectedMin, totals[1]); Assert.Equal(expectedMax, totals[2]); Assert.Equal(expectedAvg, totals[3]); Assert.Equal(expectedCount, totals[4]); } [Fact] public void Calculation_Empty() { AssertCalculation( new object[0], // SQL: sum=N min=N max=N avg=N count=0 expectedSum: null, expectedMin: null, expectedMax: null, expectedAvg: null, expectedCount: 0 ); } [Fact] public void Calculation_NoNulls() { AssertCalculation( new object[] { 1, 3, 5 }, // SQL: sum=9 min=1 max=5 avg=3.0000 count=3 expectedSum: 9M, expectedMin: 1, expectedMax: 5, expectedAvg: 3M, expectedCount: 3 ); } [Fact] public void Calculation_Nulls() { // "Summaries of the count type do not skip empty values regardless of the skipEmptyValues" // http://js.devexpress.com/Documentation/ApiReference/UI_Widgets/dxDataGrid/Configuration/summary/totalItems/?version=15_2#skipEmptyValues AssertCalculation( new object[] { null }, // SQL: sum=N min=N max=N avg=N count=1 expectedSum: null, expectedMin: null, expectedMax: null, expectedAvg: null, expectedCount: 1 ); AssertCalculation( new object[] { 1, 3, 5, null }, // SQL: sum=9 min=1 max=5 avg=3.0000 count=4 expectedSum: 9M, expectedMin: 1, expectedMax: 5, expectedAvg: 3M, expectedCount: 4 ); } [Fact] public void Calculation_Strings() { AssertCalculation( new object[] { "a", "z", null }, // SQL: sum=0 min=a max=z avg=0 count=3 expectedSum: 0M, expectedMin: "a", expectedMax: "z", expectedAvg: 0M, expectedCount: 3 ); } [Fact] public void Calculation_NonComparable() { AssertCalculation( new[] { new object() }, // NOTE sum and avg by analogy with strings case expectedSum: 0M, expectedMin: null, expectedMax: null, expectedAvg: 0M, expectedCount: 1 ); } [Fact] public void NestedGroups() { var data = new[] { new Group { items = new[] { new Group { items = new object[] { 1, 5 } } } } }; var calculator = new AggregateCalculator<int>(data, new DefaultAccessor<int>(), null, new[] { new SummaryInfo { Selector = "this", SummaryType = "sum" } }); var totals = calculator.Run(); Assert.Null(totals); Assert.Equal(6M, data[0].summary[0]); Assert.Equal(6M, (data[0].items[0] as Group).summary[0]); } [Fact] public void IgnoreGroupSummaryIfNoGroups() { var data = new object[] { 1 }; var calculator = new AggregateCalculator<int>(data, new DefaultAccessor<int>(), null, new[] { new SummaryInfo { Selector = "ignore me", SummaryType = "ignore me" } }); calculator.Run(); } [Fact] public void Issue147() { var data = Enumerable.Repeat(Double.MaxValue / 3, 2); var calculator = new AggregateCalculator<double>(data, new DefaultAccessor<double>(), new[] { new SummaryInfo { Selector = "this", SummaryType = "sum" }, new SummaryInfo { Selector = "this", SummaryType = "avg" } }, null ); var totals = calculator.Run(); Assert.Equal(data.Sum(), totals[0]); Assert.Equal(data.Average(), totals[1]); } [Fact] public void TimeSpanType() { var data = new[] { TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(3) }; var calculator = new AggregateCalculator<TimeSpan>(data, new DefaultAccessor<TimeSpan>(), new[] { new SummaryInfo { Selector = "this", SummaryType = "min" }, new SummaryInfo { Selector = "this", SummaryType = "max" }, new SummaryInfo { Selector = "this", SummaryType = "sum" }, new SummaryInfo { Selector = "this", SummaryType = "avg" } }, null ); Assert.Equal( new object[] { TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(3), TimeSpan.FromMinutes(4), TimeSpan.FromMinutes(2) }, calculator.Run() ); } } }
32.430328
151
0.464173
[ "MIT" ]
olegbevz/DevExtreme.AspNet.Data
net/DevExtreme.AspNet.Data.Tests/AggregateCalculatorTests.cs
7,915
C#
using System.Collections.Generic; using DateExpressions.Generated.Ordinals; namespace DateExpressions.Generated.PeriodSelectors { internal class OrdinalPeriodsSelector<TPeriod> : IPeriodsSelector<TPeriod> { private readonly IOrdinals _ordinal; public OrdinalPeriodsSelector(IOrdinals ordinal) { _ordinal = ordinal; } public IEnumerable<TPeriod> Pick(IEnumerable<TPeriod> periods) => _ordinal.Pick(periods); } }
27.222222
78
0.697959
[ "MIT" ]
damian-krychowski/date-expressions
DateExpressions/DateExpressions.Generated/PeriodSelectors/OrdinalPeriodsSelector.cs
492
C#
using System.Collections.Generic; using System.Threading.Tasks; namespace Citrina { public interface IStatsApi { /// <summary> /// Returns statistics of a community or an application. /// </summary> Task<ApiRequest<IEnumerable<StatsPeriod>>> Get(UserAccessToken accessToken, int? groupId = null, int? appId = null, string dateFrom = null, string dateTo = null); Task<ApiRequest<bool?>> TrackVisitor(UserAccessToken accessToken); /// <summary> /// Returns stats for a wall post. /// </summary> Task<ApiRequest<IEnumerable<StatsWallpostStat>>> GetPostReach(UserAccessToken accessToken, int? ownerId = null, int? postId = null); } }
37.684211
170
0.667598
[ "MIT" ]
khrabrovart/Citrina
src/Citrina/Api/Contracts/IStatsApi.cs
718
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace eu.operando.core.ldb.Model { public class DataAccessLog { public const string AccessDeniedTitle = "Access denied"; public const string AccessGrantedTitle = "Access granted"; public DateTime logDate; public string requesterType; public string requesterId; public string logPriority; public string logLevel; public string title; public string description; public string logType; public string affectedUserId; public string ospId; public string[] arrayRequestedFields; public string[] arrayGrantedFields; } }
27.107143
66
0.685112
[ "MIT" ]
OPERANDOH2020/op-webui
G2C/Operando-AdministrationConsole/eu.operando.core.ldb/Model/DataAccessLog.cs
761
C#
// CS0281: Friend access was granted to `cs0281, PublicKeyToken=27576a8182a18822', but the output assembly is named `cs0281, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Try adding a reference to `cs0281, PublicKeyToken=27576a8182a18822' or change the output assembly name to match it // Line: 0 // Compiler options: -r:CSFriendAssembly-lib.dll using System; public class Test { static void Main () { FriendClass.MyMethod (); } }
29.933333
295
0.755011
[ "Apache-2.0" ]
121468615/mono
mcs/errors/cs0281.cs
449
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using static Interop; namespace System.Windows.Forms { /// <summary> /// Control's IME feature. /// </summary> public partial class Control { /// <summary> /// Constants starting/ending the WM_CHAR messages to ignore count. See ImeWmCharsToIgnore property. /// </summary> private const int ImeCharsToIgnoreDisabled = -1; private const int ImeCharsToIgnoreEnabled = 0; /// <summary> /// The ImeMode value for controls with ImeMode = ImeMode.NoControl. See PropagatingImeMode property. /// </summary> private static ImeMode propagatingImeMode = ImeMode.Inherit; // Inherit means uninitialized. /// <summary> /// This flag prevents resetting ImeMode value of the focused control. See IgnoreWmImeNotify property. /// </summary> private static bool ignoreWmImeNotify; /// <summary> /// The ImeMode in the property store. /// </summary> internal ImeMode CachedImeMode { get { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_CachedImeMode(), this = " + this); Debug.Indent(); // Get the ImeMode from the property store // ImeMode cachedImeMode = (ImeMode)Properties.GetInteger(s_imeModeProperty, out bool found); if (!found) { cachedImeMode = DefaultImeMode; Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "using DefaultImeMode == " + cachedImeMode); } else { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "using property store ImeMode == " + cachedImeMode); } // If inherited, get the mode from this control's parent // if (cachedImeMode == ImeMode.Inherit) { Control? parent = ParentInternal; if (parent is not null) { cachedImeMode = parent.CachedImeMode; Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "inherited from parent = " + parent.GetType()); } else { cachedImeMode = ImeMode.NoControl; } } Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "returning CachedImeMode == " + cachedImeMode); Debug.Unindent(); return cachedImeMode; } set { // When the control is in restricted mode (!CanEnableIme) the CachedImeMode should be changed only programatically, // calls generated by user interaction should be wrapped with a check for CanEnableIme. Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside set_CachedImeMode(), this = " + this); Debug.Indent(); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Warning, "Setting cached Ime == " + value); Properties.SetInteger(s_imeModeProperty, (int)value); Debug.Unindent(); } } /// <summary> /// Specifies whether the ImeMode property value can be changed to an active value. /// Added to support Password &amp; ReadOnly (and maybe other) properties, which when set, should force disabling /// the IME if using one. /// </summary> protected virtual bool CanEnableIme { get { // Note: If overriding this property make sure to add the Debug tracing code and call this method (base.CanEnableIme). Debug.Indent(); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format(CultureInfo.CurrentCulture, "Inside get_CanEnableIme(), value = {0}, this = {1}", ImeSupported, this)); Debug.Unindent(); return ImeSupported; } } /// <summary> /// Gets the current IME context mode. If no IME associated, ImeMode.Inherit is returned. /// </summary> internal ImeMode CurrentImeContextMode { get { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_CurrentImeContextMode(), this = " + this); if (IsHandleCreated) { return ImeContext.GetImeMode(Handle); } else { // window is not yet created hence no IME associated yet. return ImeMode.Inherit; } } } protected virtual ImeMode DefaultImeMode { get { return ImeMode.Inherit; } } /// <summary> /// Flag used to avoid re-entrancy during WM_IME_NOTFIY message processing - see WmImeNotify(). /// Also to avoid raising the ImeModeChanged event more than once during the process of changing the ImeMode. /// </summary> internal int DisableImeModeChangedCount { get { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_DisableImeModeChangedCount()"); Debug.Indent(); int val = (int)Properties.GetInteger(s_disableImeModeChangedCountProperty, out bool dummy); Debug.Assert(val >= 0, "Counter underflow."); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value: " + val); Debug.Unindent(); return val; } set { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside set_DisableImeModeChangedCount(): " + value); Properties.SetInteger(s_disableImeModeChangedCountProperty, value); } } /// <summary> /// Flag used to prevent setting ImeMode in focused control when losing focus and hosted in a non-Form shell. /// See WmImeKillFocus() for more info. /// </summary> private static bool IgnoreWmImeNotify { get { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_IgnoreWmImeNotify()"); Debug.Indent(); bool val = Control.ignoreWmImeNotify; Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value: " + val); Debug.Unindent(); return val; } set { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside set_IgnoreWmImeNotify(): " + value); Control.ignoreWmImeNotify = value; } } /// <summary> /// Specifies a value that determines the IME (Input Method Editor) status of the /// object when that object is selected. /// </summary> [SRCategory(nameof(SR.CatBehavior))] [Localizable(true)] [AmbientValue(ImeMode.Inherit)] [SRDescription(nameof(SR.ControlIMEModeDescr))] public ImeMode ImeMode { get { ImeMode imeMode = ImeModeBase; if (imeMode == ImeMode.OnHalf) // This is for compatibility. See QFE#4448. { imeMode = ImeMode.On; } return imeMode; } set { ImeModeBase = value; } } /// <summary> /// Internal version of ImeMode property. This is provided for controls that override CanEnableIme and that /// return ImeMode.Disable for the ImeMode property when CanEnableIme is false - See TextBoxBase controls. /// </summary> protected virtual ImeMode ImeModeBase { get { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_ImeModeBase(), this = " + this); Debug.Indent(); ImeMode imeMode = CachedImeMode; Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value = " + imeMode); Debug.Unindent(); return imeMode; } set { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format(CultureInfo.CurrentCulture, "Inside set_ImeModeBase({0}), this = {1}", value, this)); Debug.Indent(); //valid values are -1 to 0xb SourceGenerated.EnumValidator.Validate(value); ImeMode oldImeMode = CachedImeMode; CachedImeMode = value; if (oldImeMode != value) { // Cache current value to determine whether we need to raise the ImeModeChanged. Control? ctl = null; if (!DesignMode && ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable) { // Set the context to the new value if control is focused. if (Focused) { ctl = this; } else if (ContainsFocus) { ctl = FromChildHandle(User32.GetFocus()); } if (ctl is not null && ctl.CanEnableIme) { // Block ImeModeChanged since we are checking for it below. DisableImeModeChangedCount++; try { ctl.UpdateImeContextMode(); } finally { DisableImeModeChangedCount--; } } } VerifyImeModeChanged(oldImeMode, CachedImeMode); } ImeContext.TraceImeStatus(this); Debug.Unindent(); } } /// <summary> /// Determines whether the Control supports IME handling by default. /// </summary> private bool ImeSupported { get { return DefaultImeMode != ImeMode.Disable; } } [WinCategory("Behavior")] [SRDescription(nameof(SR.ControlOnImeModeChangedDescr))] public event EventHandler ImeModeChanged { add => Events.AddHandler(s_imeModeChangedEvent, value); remove => Events.RemoveHandler(s_imeModeChangedEvent, value); } /// <summary> /// Returns the current number of WM_CHAR messages to ignore after processing corresponding WM_IME_CHAR msgs. /// </summary> internal int ImeWmCharsToIgnore { // The IME sends WM_IME_CHAR messages for each character in the composition string, and then // after all messages are sent, corresponding WM_CHAR messages are also sent. (in non-unicode // windows two WM_CHAR messages are sent per char in the IME). We need to keep a counter // not to process each character twice or more. get { return Properties.GetInteger(s_imeWmCharsToIgnoreProperty); } set { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format(CultureInfo.CurrentCulture, "Inside set_ImeWmCharToIgnore(value={0}), this = {1}", value, this)); Debug.Indent(); // WM_CHAR is not send after WM_IME_CHAR when the composition has been closed by either, changing the conversion mode or // dissasociating the IME (for instance when loosing focus and conversion is forced to complete). if (ImeWmCharsToIgnore != ImeCharsToIgnoreDisabled) { Properties.SetInteger(s_imeWmCharsToIgnoreProperty, value); } Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImeWmCharsToIgnore on leaving setter: " + ImeWmCharsToIgnore); Debug.Unindent(); } } /// <summary> /// Gets the last value CanEnableIme property when it was last checked for ensuring IME context restriction mode. /// This is used by controls that implement some sort of IME restriction mode (like TextBox on Password/ReadOnly mode). /// See the VerifyImeRestrictedModeChanged() method. /// </summary> private bool LastCanEnableIme { get { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_LastCanEnableIme()"); Debug.Indent(); int val = (int)Properties.GetInteger(s_lastCanEnableImeProperty, out bool valueFound); if (valueFound) { valueFound = val == 1; } else { valueFound = true; } Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value: " + valueFound); Debug.Unindent(); return valueFound; } set { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside set_LastCanEnableIme(): " + value); Properties.SetInteger(s_lastCanEnableImeProperty, value ? 1 : 0); } } /// <summary> /// Represents the internal ImeMode value for controls with ImeMode = ImeMode.NoControl. This property is changed /// only by user interaction and is required to set the IME context appropriately while keeping the ImeMode property /// unchanged. /// </summary> protected static ImeMode PropagatingImeMode { get { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_PropagatingImeMode()"); Debug.Indent(); if (Control.propagatingImeMode == ImeMode.Inherit) { // Initialize the propagating IME mode to the value the IME associated to the focused window currently has, // this enables propagating the IME mode from/to unmanaged applications hosting winforms controls. Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "Initializing PropagatingImeMode"); ImeMode imeMode = ImeMode.Inherit; IntPtr focusHandle = User32.GetFocus(); if (focusHandle != IntPtr.Zero) { imeMode = ImeContext.GetImeMode(focusHandle); // If focused control is disabled we won't be able to get the app ime context mode, try the top window. // this is the case of a disabled winforms control hosted in a non-Form shell. if (imeMode == ImeMode.Disable) { focusHandle = User32.GetAncestor(focusHandle, User32.GA.ROOT); if (focusHandle != IntPtr.Zero) { imeMode = ImeContext.GetImeMode(focusHandle); } } } // If IME is disabled the PropagatingImeMode will not be initialized, see property setter below. PropagatingImeMode = imeMode; } Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "Value: " + Control.propagatingImeMode); Debug.Unindent(); return Control.propagatingImeMode; } private set { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside set_PropagatingImeMode()"); Debug.Indent(); if (Control.propagatingImeMode != value) { switch (value) { case ImeMode.NoControl: case ImeMode.Disable: // Cannot set propagating ImeMode to one of these values. Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "Cannot change PropagatingImeMode to " + value); return; default: Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Warning, string.Format(CultureInfo.CurrentCulture, "Setting PropagatingImeMode: Current value = {0}, New value = {1}", propagatingImeMode, value)); Control.propagatingImeMode = value; break; } } Debug.Unindent(); } } /// <summary> /// Sets the IME context to the appropriate ImeMode according to the control's ImeMode state. /// This method is commonly used when attaching the IME to the control's window. /// </summary> internal void UpdateImeContextMode() { ImeMode[] inputLanguageTable = ImeModeConversion.InputLanguageTable; if (!DesignMode && (inputLanguageTable != ImeModeConversion.UnsupportedTable) && Focused) { // Note: CHN IME won't send WM_IME_NOTIFY msg when getting associated, setting the IME context mode // forces the message to be sent as a side effect. Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside UpdateImeContextMode(), this = " + this); Debug.Indent(); // If the value is not supported by the Ime, it will be mapped to a corresponding one, we need // to update the cached ImeMode to the actual value. ImeMode newImeContextMode = ImeMode.Disable; ImeMode currentImeMode = CachedImeMode; if (ImeSupported && CanEnableIme) { newImeContextMode = currentImeMode == ImeMode.NoControl ? PropagatingImeMode : currentImeMode; } // If PropagatingImeMode has not been initialized it will return ImeMode.Inherit above, need to check newImeContextMode for this. if (CurrentImeContextMode != newImeContextMode && newImeContextMode != ImeMode.Inherit) { // If the context changes the window will receive one or more WM_IME_NOTIFY messages and as part of its // processing it will raise the ImeModeChanged event if needed. We need to prevent the event from been // raised here from here. DisableImeModeChangedCount++; // Setting IME status to Disable will first close the IME and then disable it. For CHN IME, the first action will // update the PropagatingImeMode to ImeMode.Close which is incorrect. We need to save the PropagatingImeMode in // this case and restore it after the context has been changed. // Also this call here is very important since it will initialize the PropagatingImeMode if not already initialized // before setting the IME context to the control's ImeMode value which could be different from the propagating value. ImeMode savedPropagatingImeMode = PropagatingImeMode; try { ImeContext.SetImeStatus(newImeContextMode, Handle); } finally { DisableImeModeChangedCount--; if (newImeContextMode == ImeMode.Disable && inputLanguageTable == ImeModeConversion.ChineseTable) { // Restore saved propagating mode. PropagatingImeMode = savedPropagatingImeMode; } } // Get mapped value from the context. if (currentImeMode == ImeMode.NoControl) { if (CanEnableIme) { PropagatingImeMode = CurrentImeContextMode; } } else { if (CanEnableIme) { CachedImeMode = CurrentImeContextMode; } // Need to raise the ImeModeChanged event? VerifyImeModeChanged(newImeContextMode, CachedImeMode); } } ImeContext.TraceImeStatus(this); Debug.Unindent(); } } /// <summary> /// Checks if specified ImeMode values are different and raise the event if true. /// </summary> private void VerifyImeModeChanged(ImeMode oldMode, ImeMode newMode) { if (ImeSupported && (DisableImeModeChangedCount == 0) && (newMode != ImeMode.NoControl)) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format(CultureInfo.CurrentCulture, "Inside VerifyImeModeChanged(oldMode={0}, newMode={1}), this = {2}", oldMode, newMode, this)); Debug.Indent(); if (oldMode != newMode) { OnImeModeChanged(EventArgs.Empty); } Debug.Unindent(); } } /// <summary> /// Verifies whether the IME context mode is correct based on the control's Ime restriction mode (CanEnableIme) /// and updates the IME context if needed. /// </summary> internal void VerifyImeRestrictedModeChanged() { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside VerifyImeRestrictedModeChanged(), this = " + this); Debug.Indent(); bool currentCanEnableIme = CanEnableIme; if (LastCanEnableIme != currentCanEnableIme) { if (Focused) { // Disable ImeModeChanged from the following call since we'll raise it here if needed. DisableImeModeChangedCount++; try { UpdateImeContextMode(); } finally { DisableImeModeChangedCount--; } } // Assume for a moment the control is getting restricted; ImeMode oldImeMode = CachedImeMode; ImeMode newImeMode = ImeMode.Disable; if (currentCanEnableIme) { // Control is actually getting unrestricted, swap values. newImeMode = oldImeMode; oldImeMode = ImeMode.Disable; } // Do we need to raise the ImeModeChanged event? VerifyImeModeChanged(oldImeMode, newImeMode); // Finally update the saved CanEnableIme value. LastCanEnableIme = currentCanEnableIme; } Debug.Unindent(); } /// <summary> /// Update internal ImeMode properties (PropagatingImeMode/CachedImeMode) with actual IME context mode if needed. /// This method can be used with a child control when the IME mode is more relevant to it than to the control itself, /// for instance ComboBox and its native ListBox/Edit controls. /// </summary> internal void OnImeContextStatusChanged(IntPtr handle) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside OnImeContextStatusChanged(), this = " + this); Debug.Indent(); Debug.Assert(ImeSupported, "WARNING: Attempting to update ImeMode properties on IME-Unaware control!"); Debug.Assert(!DesignMode, "Shouldn't be updating cached ime mode at design-time"); ImeMode fromContext = ImeContext.GetImeMode(handle); if (fromContext != ImeMode.Inherit) { ImeMode oldImeMode = CachedImeMode; if (CanEnableIme) { // Cache or Propagating ImeMode should not be updated by interaction when the control is in restricted mode. if (oldImeMode != ImeMode.NoControl) { CachedImeMode = fromContext; // This could end up in the same value due to ImeMode language mapping. // ImeMode may be changing by user interaction. VerifyImeModeChanged(oldImeMode, CachedImeMode); } else { PropagatingImeMode = fromContext; } } } Debug.Unindent(); } /// <summary> /// Raises the <see cref='OnImeModeChanged'/> /// event. /// </summary> protected virtual void OnImeModeChanged(EventArgs e) { Debug.Assert(ImeSupported, "ImeModeChanged should not be raised on an Ime-Unaware control."); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside OnImeModeChanged(), this = " + this); ((EventHandler?)Events[s_imeModeChangedEvent])?.Invoke(this, e); } /// <summary> /// Resets the Ime mode. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public void ResetImeMode() { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside ResetImeMode(), this = " + this); ImeMode = DefaultImeMode; } /// <summary> /// Returns true if the ImeMode should be persisted in code gen. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] internal virtual bool ShouldSerializeImeMode() { // This method is for designer support. If the ImeMode has not been changed or it is the same as the // default value it should not be serialized. int imeMode = Properties.GetInteger(s_imeModeProperty, out bool found); return (found && imeMode != (int)DefaultImeMode); } /// <summary> /// Handles the WM_INPUTLANGCHANGE message /// </summary> private void WmInputLangChange(ref Message m) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside WmInputLangChange(), this = " + this); Debug.Indent(); // Make sure the IME context is associated with the correct (mapped) mode. UpdateImeContextMode(); // If detaching IME (setting to English) reset propagating IME mode so when reattaching the IME is set to direct input again. if (ImeModeConversion.InputLanguageTable == ImeModeConversion.UnsupportedTable) { PropagatingImeMode = ImeMode.Off; } Form form = FindForm(); if (form is not null) { InputLanguageChangedEventArgs e = InputLanguage.CreateInputLanguageChangedEventArgs(m); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Culture=" + e.Culture); form.PerformOnInputLanguageChanged(e); } DefWndProc(ref m); ImeContext.TraceImeStatus(this); Debug.Unindent(); } /// <summary> /// Handles the WM_INPUTLANGCHANGEREQUEST message /// </summary> private void WmInputLangChangeRequest(ref Message m) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside WmInputLangChangeRequest(), this=" + this); Debug.Indent(); InputLanguageChangingEventArgs e = InputLanguage.CreateInputLanguageChangingEventArgs(m); Form form = FindForm(); if (form is not null) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Culture=" + e.Culture); form.PerformOnInputLanguageChanging(e); } if (!e.Cancel) { DefWndProc(ref m); } else { m.Result = IntPtr.Zero; } Debug.Unindent(); } /// <summary> /// Handles the WM_IME_CHAR message /// </summary> private void WmImeChar(ref Message m) { if (ProcessKeyEventArgs(ref m)) { return; } DefWndProc(ref m); } /// <summary> /// Handles the WM_IME_ENDCOMPOSITION message /// </summary> private void WmImeEndComposition(ref Message m) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside WmImeEndComposition() - Disabling ImeWmCharToIgnore, this=" + this); ImeWmCharsToIgnore = ImeCharsToIgnoreDisabled; DefWndProc(ref m); } /// <summary> /// Handles the WM_IME_NOTIFY message /// </summary> private void WmImeNotify(ref Message m) { if (ImeSupported && ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable && !IgnoreWmImeNotify) { int wparam = (int)m.WParam; // The WM_IME_NOTIFY message is not consistent across the different IMEs, particularly the notification type // we care about (IMN_SETCONVERSIONMODE & IMN_SETOPENSTATUS). // The IMN_SETOPENSTATUS command is sent when the open status of the input context is updated. // The IMN_SETCONVERSIONMODE command is sent when the conversion mode of the input context is updated. // - The Korean IME sents both msg notifications when changing the conversion mode (From/To Hangul/Alpha). // - The Chinese IMEs sends the IMN_SETCONVERSIONMODE when changing mode (On/Close, Full Shape/Half Shape) // and IMN_SETOPENSTATUS when getting disabled/enabled or closing/opening as well, but it does not send any // WM_IME_NOTIFY when associating an IME to the app for the first time; setting the IME mode to direct input // during WM_INPUTLANGCHANGED forces the IMN_SETOPENSTATUS message to be sent. // - The Japanese IME sends IMN_SETCONVERSIONMODE when changing from Off to one of the active modes (Katakana..) // and IMN_SETOPENSTATUS when changing beteween the active modes or when enabling/disabling the IME. // In any case we update the cache. // Warning: // Attempting to change the IME mode from here will cause re-entrancy - WM_IME_NOTIFY is resent. // We guard against re-entrancy since the ImeModeChanged event can be raised and any changes from the handler could // lead to another WM_IME_NOTIFY loop. if (wparam == (int)Imm32.IMN.SETCONVERSIONMODE || wparam == (int)Imm32.IMN.SETOPENSTATUS) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format(CultureInfo.CurrentCulture, "Inside WmImeNotify(m.wparam=[{0}]), this={1}", m.WParam, this)); Debug.Indent(); // Synchronize internal properties with the IME context mode. OnImeContextStatusChanged(Handle); Debug.Unindent(); } } DefWndProc(ref m); } /// <summary> /// Handles the WM_SETFOCUS message for IME related stuff. /// </summary> internal void WmImeSetFocus() { if (ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside WmImeSetFocus(), this=" + this); Debug.Indent(); // Make sure the IME context is set to the correct value. // Consider - Perf improvement: ContainerControl controls should update the IME context only when they don't contain // a focusable control since it will be updated by that control. UpdateImeContextMode(); Debug.Unindent(); } } /// <summary> /// Handles the WM_IME_STARTCOMPOSITION message /// </summary> private void WmImeStartComposition(ref Message m) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside WmImeStartComposition() - Enabling ImeWmCharToIgnore, this=" + this); // Need to call the property store directly because the WmImeCharsToIgnore property is locked when ImeCharsToIgnoreDisabled. Properties.SetInteger(s_imeWmCharsToIgnoreProperty, ImeCharsToIgnoreEnabled); DefWndProc(ref m); } /// <summary> /// Handles the WM_KILLFOCUS message /// </summary> private void WmImeKillFocus() { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside WmImeKillFocus(), this=" + this); Debug.Indent(); Control topMostWinformsParent = TopMostParent; Form? appForm = topMostWinformsParent as Form; if ((appForm is null || appForm.Modal) && !topMostWinformsParent.ContainsFocus) { // This means the winforms component container is not a WinForms host and it is no longer focused. // Or it is not the main app host. Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Unfocused TopMostParent = " + topMostWinformsParent); // We need to reset the PropagatingImeMode to force reinitialization when the winforms component gets focused again; // this enables inheritting the propagating mode from an unmanaged application hosting a winforms component. // But before leaving the winforms container we need to set the IME to the propagating IME mode since the focused control // may not support IME which would leave the IME disabled. // See the PropagatingImeMode property // Note: We need to check the static field here directly to avoid initialization of the property. if (Control.propagatingImeMode != ImeMode.Inherit) { // Setting the ime context of the top window will generate a WM_IME_NOTIFY on the focused control which will // update its ImeMode, we need to prevent this temporarily. IgnoreWmImeNotify = true; try { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "Setting IME context to PropagatingImeMode (leaving Winforms container). this = " + this); ImeContext.SetImeStatus(PropagatingImeMode, topMostWinformsParent.Handle); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "Resetting PropagatingImeMode. this = " + this); PropagatingImeMode = ImeMode.Inherit; } finally { IgnoreWmImeNotify = false; } } } Debug.Unindent(); } } // end class Control ///////////////////////////////////////////////////////// ImeContext class ///////////////////////////////////////////////////////// /// <summary> /// Represents the native IME context. /// </summary> public static class ImeContext { /// <summary> /// The IME context handle obtained when first associating an IME. /// </summary> private static IntPtr originalImeContext; /// <summary> /// Disable the IME /// </summary> public static void Disable(IntPtr handle) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside ImeContext.Disable(" + handle + ")"); Debug.Indent(); if (ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable) { // Close the IME if necessary // if (ImeContext.IsOpen(handle)) { ImeContext.SetOpenStatus(false, handle); } // Disable the IME by disassociating the context from the window. // Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmAssociateContext(" + handle + ", null)"); IntPtr oldContext = Imm32.ImmAssociateContext(handle, IntPtr.Zero); if (oldContext != IntPtr.Zero) { originalImeContext = oldContext; } } ImeContext.TraceImeStatus(handle); Debug.Unindent(); } /// <summary> /// Enable the IME /// </summary> public static void Enable(IntPtr handle) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside ImeContext.Enable(" + handle + ")"); Debug.Indent(); if (ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetContext(" + handle + ")"); IntPtr inputContext = Imm32.ImmGetContext(handle); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "context = " + inputContext); // Enable IME by associating the IME context to the window. if (inputContext == IntPtr.Zero) { if (originalImeContext == IntPtr.Zero) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmCreateContext()"); inputContext = Imm32.ImmCreateContext(); if (inputContext != IntPtr.Zero) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmAssociateContext(" + handle + ", " + inputContext + ")"); Imm32.ImmAssociateContext(handle, inputContext); } } else { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmAssociateContext()"); Imm32.ImmAssociateContext(handle, originalImeContext); } } else { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmReleaseContext(" + handle + ", " + inputContext + ")"); Imm32.ImmReleaseContext(handle, inputContext); } // Make sure the IME is opened. if (!ImeContext.IsOpen(handle)) { ImeContext.SetOpenStatus(true, handle); } } ImeContext.TraceImeStatus(handle); Debug.Unindent(); } /// <summary> /// Gets the ImeMode that corresponds to ImeMode.Disable based on the current input language ImeMode table. /// </summary> public static ImeMode GetImeMode(IntPtr handle) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Insise ImeContext.GetImeMode(" + handle + ")"); Debug.Indent(); IntPtr inputContext = IntPtr.Zero; ImeMode retval = ImeMode.NoControl; // Get the right table for the current keyboard layout // ImeMode[] countryTable = ImeModeConversion.InputLanguageTable; if (countryTable == ImeModeConversion.UnsupportedTable) { // No IME associated with current culture. retval = ImeMode.Inherit; goto cleanup; } Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetContext(" + handle + ")"); inputContext = Imm32.ImmGetContext(handle); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "context = " + inputContext); if (inputContext == IntPtr.Zero) { // No IME context attached - The Ime has been disabled. retval = ImeMode.Disable; goto cleanup; } if (!ImeContext.IsOpen(handle)) { // There's an IME associated with the window but is closed - the input is taken from the keyboard as is (English). retval = countryTable[ImeModeConversion.ImeClosed]; goto cleanup; } // Determine the IME mode from the conversion status Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetConversionStatus(" + inputContext + ", conversion, sentence)"); Imm32.ImmGetConversionStatus(inputContext, out Imm32.IME_CMODE conversion, out Imm32.IME_SMODE sentence); Debug.Assert(countryTable is not null, "countryTable is null"); if ((conversion & Imm32.IME_CMODE.NATIVE) != 0) { if ((conversion & Imm32.IME_CMODE.KATAKANA) != 0) { retval = ((conversion & Imm32.IME_CMODE.FULLSHAPE) != 0) ? countryTable[ImeModeConversion.ImeNativeFullKatakana] : countryTable[ImeModeConversion.ImeNativeHalfKatakana]; goto cleanup; } else { retval = ((conversion & Imm32.IME_CMODE.FULLSHAPE) != 0) ? countryTable[ImeModeConversion.ImeNativeFullHiragana] : countryTable[ImeModeConversion.ImeNativeHalfHiragana]; goto cleanup; } } else { retval = ((conversion & Imm32.IME_CMODE.FULLSHAPE) != 0) ? countryTable[ImeModeConversion.ImeAlphaFull] : countryTable[ImeModeConversion.ImeAlphaHalf]; } cleanup: if (inputContext != IntPtr.Zero) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmReleaseContext(" + handle + ", " + inputContext + ")"); Imm32.ImmReleaseContext(handle, inputContext); } ImeContext.TraceImeStatus(handle); Debug.Unindent(); return retval; } /// <summary> /// Get the actual IME status - This method is for debugging purposes only. /// </summary> [Conditional("DEBUG")] internal static void TraceImeStatus(Control ctl) { #if DEBUG if (ctl.IsHandleCreated) { TraceImeStatus(ctl.Handle); } #endif } [Conditional("DEBUG")] private static void TraceImeStatus(IntPtr handle) { #if DEBUG if (CompModSwitches.ImeMode.Level >= TraceLevel.Info) { string status = "?"; IntPtr inputContext = IntPtr.Zero; ImeMode[] countryTable = ImeModeConversion.InputLanguageTable; if (countryTable == ImeModeConversion.UnsupportedTable) { status = "IME not supported in current language."; goto cleanup; } inputContext = Imm32.ImmGetContext(handle); if (inputContext == IntPtr.Zero) { status = string.Format(CultureInfo.CurrentCulture, "No ime context for handle=[{0}]", handle); goto cleanup; } if (!Imm32.ImmGetOpenStatus(inputContext).IsTrue()) { status = string.Format(CultureInfo.CurrentCulture, "Ime closed for handle=[{0}]", handle); goto cleanup; } Imm32.ImmGetConversionStatus(inputContext, out Imm32.IME_CMODE conversion, out Imm32.IME_SMODE sentence); ImeMode retval; if ((conversion & Imm32.IME_CMODE.NATIVE) != 0) { if ((conversion & Imm32.IME_CMODE.KATAKANA) != 0) { retval = ((conversion & Imm32.IME_CMODE.FULLSHAPE) != 0) ? countryTable[ImeModeConversion.ImeNativeFullKatakana] : countryTable[ImeModeConversion.ImeNativeHalfKatakana]; } else { retval = ((conversion & Imm32.IME_CMODE.FULLSHAPE) != 0) ? countryTable[ImeModeConversion.ImeNativeFullHiragana] : countryTable[ImeModeConversion.ImeNativeHalfHiragana]; } } else { retval = ((conversion & Imm32.IME_CMODE.FULLSHAPE) != 0) ? countryTable[ImeModeConversion.ImeAlphaFull] : countryTable[ImeModeConversion.ImeAlphaHalf]; } status = string.Format(CultureInfo.CurrentCulture, "Ime conversion status mode for handle=[{0}]: {1}", handle, retval); cleanup: if (inputContext != IntPtr.Zero) { Imm32.ImmReleaseContext(handle, inputContext); } Debug.WriteLine(status); } #endif } /// <summary> /// Returns true if the IME is currently open /// </summary> public static bool IsOpen(IntPtr handle) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside ImeContext.IsOpen(" + handle + ")"); Debug.Indent(); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetContext(" + handle + ")"); IntPtr inputContext = Imm32.ImmGetContext(handle); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "context = " + inputContext); bool retval = false; if (inputContext != IntPtr.Zero) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetOpenStatus(" + inputContext + ")"); retval = Imm32.ImmGetOpenStatus(inputContext).IsTrue(); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmReleaseContext(" + handle + ", " + inputContext + ")"); Imm32.ImmReleaseContext(handle, inputContext); } Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, " IsOpen = " + retval); Debug.Unindent(); return retval; } /// <summary> /// Sets the actual IME context value. /// </summary> public static void SetImeStatus(ImeMode imeMode, IntPtr handle) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format(CultureInfo.CurrentCulture, "Inside ImeContext.SetImeStatus(ImeMode=[{0}, handle=[{1}])", imeMode, handle)); Debug.Indent(); Debug.Assert(imeMode != ImeMode.Inherit, "ImeMode.Inherit is an invalid argument to ImeContext.SetImeStatus"); if (imeMode == ImeMode.Inherit || imeMode == ImeMode.NoControl) { goto cleanup; // No action required } ImeMode[] inputLanguageTable = ImeModeConversion.InputLanguageTable; if (inputLanguageTable == ImeModeConversion.UnsupportedTable) { goto cleanup; // We only support Japanese, Korean and Chinese IME. } Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Warning, "\tSetting IME context to " + imeMode); if (imeMode == ImeMode.Disable) { ImeContext.Disable(handle); } else { // This will make sure the IME is opened. ImeContext.Enable(handle); } switch (imeMode) { case ImeMode.NoControl: case ImeMode.Disable: break; // No action required case ImeMode.On: // IME active mode (CHN = On, JPN = Hiragana, KOR = Hangul). // Setting ImeMode to Hiragana (or any other active value) will force the IME to get to an active value // independent on the language. imeMode = ImeMode.Hiragana; goto default; case ImeMode.Off: // IME direct input (CHN = Off, JPN = Off, KOR = Alpha). if (inputLanguageTable == ImeModeConversion.JapaneseTable) { // Japanese IME interprets Close as Off. goto case ImeMode.Close; } // CHN: to differentiate between Close and Off we set the ImeMode to Alpha. imeMode = ImeMode.Alpha; goto default; case ImeMode.Close: if (inputLanguageTable == ImeModeConversion.KoreanTable) { // Korean IME has no idea what Close means. imeMode = ImeMode.Alpha; goto default; } ImeContext.SetOpenStatus(false, handle); break; default: if (ImeModeConversion.ImeModeConversionBits.ContainsKey(imeMode)) { // Update the conversion status // ImeModeConversion conversionEntry = (ImeModeConversion)ImeModeConversion.ImeModeConversionBits[imeMode]; Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetContext(" + handle + ")"); IntPtr inputContext = Imm32.ImmGetContext(handle); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "context = " + inputContext); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetConversionStatus(" + inputContext + ", conversion, sentence)"); Imm32.ImmGetConversionStatus(inputContext, out Imm32.IME_CMODE conversion, out Imm32.IME_SMODE sentence); conversion |= conversionEntry.setBits; conversion &= ~conversionEntry.clearBits; Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmSetConversionStatus(" + inputContext + ", conversion, sentence)"); Imm32.ImmSetConversionStatus(inputContext, conversion, sentence); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmReleaseContext(" + handle + ", " + inputContext + ")"); Imm32.ImmReleaseContext(handle, inputContext); } break; } cleanup: ImeContext.TraceImeStatus(handle); Debug.Unindent(); } /// <summary> /// Opens or closes the IME context. /// </summary> public static void SetOpenStatus(bool open, IntPtr handle) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format(CultureInfo.CurrentCulture, "Inside SetOpenStatus(open=[{0}], handle=[{1}])", open, handle)); Debug.Indent(); if (ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetContext(" + handle + ")"); IntPtr inputContext = Imm32.ImmGetContext(handle); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "context = " + inputContext); if (inputContext != IntPtr.Zero) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmSetOpenStatus(" + inputContext + ", " + open + ")"); bool succeeded = Imm32.ImmSetOpenStatus(inputContext, open.ToBOOL()).IsTrue(); Debug.Assert(succeeded, "Could not set the IME open status."); if (succeeded) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmReleaseContext(" + handle + ", " + inputContext + ")"); succeeded = Imm32.ImmReleaseContext(handle, inputContext).IsTrue(); Debug.Assert(succeeded, "Could not release IME context."); } } } ImeContext.TraceImeStatus(handle); Debug.Unindent(); } }// end ImeContext class ///////////////////////////////////////////////////////// ImeModeConversion structure ///////////////////////////////////////////////////////// /// <summary> /// Helper class that provides information about IME convertion mode. Convertion mode refers to how IME interprets input like /// ALPHANUMERIC or HIRAGANA and depending on its value the IME enables/disables the IME convertion window appropriately. /// </summary> public struct ImeModeConversion { private static Dictionary<ImeMode, ImeModeConversion>? imeModeConversionBits; internal Imm32.IME_CMODE setBits; internal Imm32.IME_CMODE clearBits; // Tables of conversions from IME context bits to IME mode // //internal const int ImeNotAvailable = 0; internal const int ImeDisabled = 1; internal const int ImeDirectInput = 2; internal const int ImeClosed = 3; internal const int ImeNativeInput = 4; internal const int ImeNativeFullHiragana = 4; // Index of Native Input Mode. internal const int ImeNativeHalfHiragana = 5; internal const int ImeNativeFullKatakana = 6; internal const int ImeNativeHalfKatakana = 7; internal const int ImeAlphaFull = 8; internal const int ImeAlphaHalf = 9; /// <summary> /// Supported input language ImeMode tables. /// WARNING: Do not try to map 'active' IME modes from one table to another since they can have a different /// meaning depending on the language; for instance ImeMode.Off means 'disable' or 'alpha' to Chinese /// but to Japanese it is 'alpha' and to Korean it has no meaning. /// </summary> private static readonly ImeMode[] japaneseTable = { ImeMode.Inherit, ImeMode.Disable, ImeMode.Off, ImeMode.Off, ImeMode.Hiragana, ImeMode.Hiragana, ImeMode.Katakana, ImeMode.KatakanaHalf, ImeMode.AlphaFull, ImeMode.Alpha }; private static readonly ImeMode[] koreanTable = { ImeMode.Inherit, ImeMode.Disable, ImeMode.Alpha, ImeMode.Alpha, ImeMode.HangulFull, ImeMode.Hangul, ImeMode.HangulFull, ImeMode.Hangul, ImeMode.AlphaFull, ImeMode.Alpha }; private static readonly ImeMode[] chineseTable = { ImeMode.Inherit, ImeMode.Disable, ImeMode.Off, ImeMode.Close, ImeMode.On, ImeMode.OnHalf, ImeMode.On, ImeMode.OnHalf, ImeMode.Off, ImeMode.Off }; private static readonly ImeMode[] unsupportedTable = Array.Empty<ImeMode>(); internal static ImeMode[] ChineseTable { get { return chineseTable; } } internal static ImeMode[] JapaneseTable { get { return japaneseTable; } } internal static ImeMode[] KoreanTable { get { return koreanTable; } } internal static ImeMode[] UnsupportedTable { get { return unsupportedTable; } } /// <summary> /// Gets the ImeMode table of the current input language. /// Although this property is per-thread based we cannot cache it and share it among controls running in the same thread /// for two main reasons: we still have some controls that don't handle IME properly (TabControl, ComboBox, TreeView...) /// and would render it invalid and since the IME API is not public third party controls would not have a way to update /// the cached value. /// </summary> internal static ImeMode[] InputLanguageTable { get { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_InputLanguageTable(), Input Language = " + InputLanguage.CurrentInputLanguage.Culture.DisplayName + ", Thread = " + System.Threading.Thread.CurrentThread.ManagedThreadId); InputLanguage inputLanguage = InputLanguage.CurrentInputLanguage; int lcid = (int)((long)inputLanguage.Handle & (long)0xFFFF); switch (lcid) { case 0x0404: case 0x0804: case 0x0c04: case 0x1004: case 0x1404: return chineseTable; case 0x0412: // Korean case 0x0812: // Korean (Johab) return koreanTable; case 0x0411: // Japanese return japaneseTable; default: return unsupportedTable; } } } /// <summary> /// Dictionary of ImeMode and corresponding convertion flags. /// </summary> public static Dictionary<ImeMode, ImeModeConversion> ImeModeConversionBits { get { if (imeModeConversionBits is null) { // Create ImeModeConversionBits dictionary imeModeConversionBits = new Dictionary<ImeMode, ImeModeConversion>(7); ImeModeConversion conversion; // Hiragana, On // conversion.setBits = Imm32.IME_CMODE.FULLSHAPE | Imm32.IME_CMODE.NATIVE; conversion.clearBits = Imm32.IME_CMODE.KATAKANA; imeModeConversionBits.Add(ImeMode.Hiragana, conversion); // Katakana // conversion.setBits = Imm32.IME_CMODE.FULLSHAPE | Imm32.IME_CMODE.KATAKANA | Imm32.IME_CMODE.NATIVE; conversion.clearBits = 0; imeModeConversionBits.Add(ImeMode.Katakana, conversion); // KatakanaHalf // conversion.setBits = Imm32.IME_CMODE.KATAKANA | Imm32.IME_CMODE.NATIVE; conversion.clearBits = Imm32.IME_CMODE.FULLSHAPE; imeModeConversionBits.Add(ImeMode.KatakanaHalf, conversion); // AlphaFull // conversion.setBits = Imm32.IME_CMODE.FULLSHAPE; conversion.clearBits = Imm32.IME_CMODE.KATAKANA | Imm32.IME_CMODE.NATIVE; imeModeConversionBits.Add(ImeMode.AlphaFull, conversion); // Alpha // conversion.setBits = 0; conversion.clearBits = Imm32.IME_CMODE.FULLSHAPE | Imm32.IME_CMODE.KATAKANA | Imm32.IME_CMODE.NATIVE; imeModeConversionBits.Add(ImeMode.Alpha, conversion); // HangulFull // conversion.setBits = Imm32.IME_CMODE.FULLSHAPE | Imm32.IME_CMODE.NATIVE; conversion.clearBits = 0; imeModeConversionBits.Add(ImeMode.HangulFull, conversion); // Hangul // conversion.setBits = Imm32.IME_CMODE.NATIVE; conversion.clearBits = Imm32.IME_CMODE.FULLSHAPE; imeModeConversionBits.Add(ImeMode.Hangul, conversion); // OnHalf // conversion.setBits = Imm32.IME_CMODE.NATIVE; conversion.clearBits = Imm32.IME_CMODE.KATAKANA | Imm32.IME_CMODE.FULLSHAPE; imeModeConversionBits.Add(ImeMode.OnHalf, conversion); } return imeModeConversionBits; } } public static bool IsCurrentConversionTableSupported { get { return InputLanguageTable != UnsupportedTable; } } }// end ImeModeConversion struct. } // end namespace System.Windows.Forms
42.425447
267
0.544361
[ "MIT" ]
adamsitnik/winforms
src/System.Windows.Forms/src/System/Windows/Forms/Control.Ime.cs
64,022
C#
using System.Collections.Generic; using Newtonsoft.Json; namespace Core.Models.Spotify.Tracks { public class PutTracks { [JsonProperty("ids")] public string Ids { get; set; } } }
18.818182
39
0.657005
[ "MIT" ]
ramosisw/dotnet-portify
src/Core/Models/Spotify/Tracks/PutTracks.cs
207
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace mkoIt.Asp { [AttributeUsage(AttributeTargets.Property, AllowMultiple=false, Inherited=true)] public class MapPropertyToColNameAttribute : System.Attribute { public MapPropertyToColNameAttribute(string ColName) { this.ColName = ColName; } public string ColName; } }
23.5
84
0.699764
[ "MIT" ]
mk-prg-net/mk-prg-net.lib
mko.Asp/Bo/MapPropertyToColNameAttribute.cs
425
C#
using UnityEngine; using System.Collections; using SvenFrankson.Game.SphereCraft; public class PlanetBrush : MonoBehaviour { public Material[] planetMaterials; public Material[] eraserMaterials; private PlanetSide planetSide = null; private int iPos = -1; private int jPos = -1; private int kPos = -1; private byte block = 0; private MeshFilter c_MeshFilter; private MeshFilter C_MeshFilter { get { if (c_MeshFilter == null) { c_MeshFilter = this.GetComponent<MeshFilter>(); } return c_MeshFilter; } } private Renderer c_Renderer; private Renderer C_Renderer { get { if (c_Renderer == null) { c_Renderer = this.GetComponent<Renderer>(); } return c_Renderer; } } public void Set(PlanetSide newPlanetSide, int newIPos, int newJPos, int newKPos, byte newBlock) { if ((newPlanetSide == this.planetSide) && (newIPos == this.iPos) && (newJPos == this.jPos) && (newKPos == this.kPos) && (newBlock == this.block)) { return; } this.planetSide = newPlanetSide; this.iPos = newIPos; this.jPos = newJPos; this.kPos = newKPos; this.block = newBlock; this.C_MeshFilter.sharedMesh = this.planetSide.planet.WorldPositionToBlockMesh(this.iPos, this.jPos, this.kPos, this.block); if (this.block == 0) { this.C_Renderer.sharedMaterials = this.eraserMaterials; } else { this.C_Renderer.sharedMaterials = this.planetMaterials; } this.transform.parent = newPlanetSide.transform; this.transform.localPosition = Vector3.zero; this.transform.localRotation = Quaternion.identity; } }
25.946667
132
0.570915
[ "MIT" ]
SvenFrankson/PlanetBuilder
Assets/PlanetBuilder/Scripts/Planet/PlanetBrush.cs
1,948
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("Zisa_Calorie_c")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Zisa_Calorie_c")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
42.428571
98
0.710017
[ "MIT" ]
Fjohora9333/C-Samples
Zisa_Calorie_c/Zisa_Calorie_c/Properties/AssemblyInfo.cs
2,379
C#
using EM.GIS.Symbology; using System.Collections.ObjectModel; namespace EM.GIS.Controls { /// <summary> /// 命令工厂 /// </summary> public interface ICommandFactory { /// <summary> /// 命令 /// </summary> ObservableCollection<IBaseCommand> Commands { get; } } }
19.5625
60
0.578275
[ "MIT" ]
chiraylu/EMap
EM.GIS.Controls/ICommandFactory.cs
327
C#
namespace Xunit { /// <summary> /// Internal helper class for remoting. /// </summary> public static class RemotingUtility { /// <summary> /// Unregisters any remoting channels. /// </summary> /// <remarks> /// If there are any registered remoting channels, then MarshalByRefObjects /// don't work. Based on bug #9749, it's clear that MSTest (at least through /// Visual Studio 2010) registers remoting channels when it runs but doesn't /// clean them up when it's done. Right now, the only way to reliably surface /// this issue is through MSBuild (as per the bug repro), so for the moment /// this work-around code is limited to the MSBuild runner. /// </remarks> public static void CleanUpRegisteredChannels() { #if NETFRAMEWORK foreach (var channel in System.Runtime.Remoting.Channels.ChannelServices.RegisteredChannels) System.Runtime.Remoting.Channels.ChannelServices.UnregisterChannel(channel); #endif } } }
38.571429
104
0.638889
[ "Apache-2.0" ]
0x0309/xunit
src/xunit.runner.utility/Utility/RemotingUtility.cs
1,082
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 codedeploy-2014-10-06.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CodeDeploy.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CodeDeploy.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DeleteResourcesByExternalId operation /// </summary> public class DeleteResourcesByExternalIdResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { DeleteResourcesByExternalIdResponse response = new DeleteResourcesByExternalIdResponse(); return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); return new AmazonCodeDeployException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static DeleteResourcesByExternalIdResponseUnmarshaller _instance = new DeleteResourcesByExternalIdResponseUnmarshaller(); internal static DeleteResourcesByExternalIdResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteResourcesByExternalIdResponseUnmarshaller Instance { get { return _instance; } } } }
35.5
165
0.690468
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/CodeDeploy/Generated/Model/Internal/MarshallTransformations/DeleteResourcesByExternalIdResponseUnmarshaller.cs
3,053
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace Microsoft.Data.Entity.Design.Model.Commands { using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Data.Entity.Design.Model.Mapping; internal class DeleteUnboundMappingsCommand : Command { protected override void InvokeInternal(CommandProcessorContext cpc) { var service = cpc.EditingContext.GetEFArtifactService(); var artifact = service.Artifact; Debug.Assert(null != artifact, "Null Artifact"); if (null == artifact) { return; } var mappingModel = artifact.MappingModel(); if (null == mappingModel) { return; } var ecm = mappingModel.FirstEntityContainerMapping; if (null == ecm) { return; } // loop over the EntitySetMappings looking for deleted EntityTypes // Note: have to convert to array first to prevent exceptions due to // editing the collection while iterating over it var entitySetMappings = ecm.EntitySetMappings().ToArray(); foreach (var esm in entitySetMappings) { RecursiveDeleteUnboundElements(cpc, esm); } // loop over the AssociationSetMappings looking for deleted Associations // Note: have to convert to array first to prevent exceptions due to // editing the collection while iterating over it var associationSetMappings = ecm.AssociationSetMappings().ToArray(); foreach (var asm in associationSetMappings) { RecursiveDeleteUnboundElements(cpc, asm); } // loop over the FunctionImportMappings looking for deleted Associations // Note: have to convert to array first to prevent exceptions due to // editing the collection while iterating over it var functionImportMappings = ecm.FunctionImportMappings().ToArray(); foreach (var fim in functionImportMappings) { RecursiveDeleteUnboundElements(cpc, fim); } } /// <summary> /// If this element has any children that have unresolved references /// or has itself an unresolved reference then Delete the element /// NB: Be warned this method is destructive. If you have unbound /// elements for whatever reason then those elements will be removed. /// </summary> private static void RecursiveDeleteUnboundElements(CommandProcessorContext cpc, EFElement efElement) { var mappingCondition = efElement as Condition; var queryView = efElement as QueryView; if (mappingCondition != null) { // A Mapping Condition is special because it will // only ever have 1 bound child out of 2 var children = efElement.Children.ToArray(); var anyOneOfChildrenIsBound = children.OfType<ItemBinding>().Any(itemBinding => itemBinding.Resolved); if (!anyOneOfChildrenIsBound) { DeleteEFElementCommand.DeleteInTransaction(cpc, efElement); } return; } else if (queryView != null) { // QueryView elements have a TypeName attribute, but it is optional and // so the QueryView should not be deleted even if the TypeName attribute // is not in a Resolved state return; } else { // cannot use IEnumerable directly as we are potentially // deleting from the returned collection var children = new List<EFObject>(efElement.Children); // remove any children which are optional (and hence not being resolved does not require a delete) var cp = efElement as ComplexProperty; if (cp != null) { // TypeName binding in ComplexProperty is optional and can be unresolved, so remove it from the check list children.Remove(cp.TypeName); } var mf = efElement as ModificationFunction; if (mf != null) { children.Remove(mf.RowsAffectedParameter); } // loop over children and recursively delete foreach (var child in children) { var efElementChild = child as EFElement; var itemBindingChild = child as ItemBinding; if (efElementChild != null) { RecursiveDeleteUnboundElements(cpc, efElementChild); } else if (itemBindingChild != null) { if (!itemBindingChild.Resolved) { DeleteEFElementCommand.DeleteInTransaction(cpc, efElement); return; } } } } } } }
40.903704
133
0.549439
[ "Apache-2.0" ]
CZEMacLeod/EntityFramework6
src/EFTools/EntityDesignModel/Commands/DeleteUnboundMappingsCommand.cs
5,524
C#
// <auto-generated/> #pragma warning disable 1591 namespace Microsoft.AspNetCore.Razor.Language.IntegrationTests.TestFiles { #line hidden public class TestFiles_IntegrationTests_CodeGenerationIntegrationTest_CodeBlock_DesignTime { #pragma warning disable 219 private void __RazorDirectiveTokenHelpers__() { } #pragma warning restore 219 #pragma warning disable 0414 private static System.Object __o = null; #pragma warning restore 0414 #pragma warning disable 1998 public async System.Threading.Tasks.Task ExecuteAsync() { #nullable restore #line 1 "TestFiles/IntegrationTests/CodeGenerationIntegrationTest/CodeBlock.cshtml" for(int i = 1; i <= 10; i++) { Output.Write("<p>Hello from C#, #" + i.ToString() + "</p>"); } #line default #line hidden #nullable disable } #pragma warning restore 1998 } } #pragma warning restore 1591
29.090909
94
0.683333
[ "Apache-2.0" ]
1175169074/aspnetcore
src/Razor/Microsoft.AspNetCore.Razor.Language/test/TestFiles/IntegrationTests/CodeGenerationIntegrationTest/CodeBlock_DesignTime.codegen.cs
960
C#
using System.Text.RegularExpressions; using DbUp.Reboot.Engine; namespace DbUp.Reboot.SQLite { /// <summary> /// This preprocessor makes adjustments to your sql to make it compatible with Sqlite /// </summary> public class SQLitePreprocessor : IScriptPreprocessor { /// <summary> /// Performs some preprocessing step on a SQLite script /// </summary> public string Process(string contents) => Regex.Replace(contents, @"n?varchar\s?\(max\)", "text", RegexOptions.IgnoreCase); } }
31.588235
131
0.668529
[ "Apache-2.0" ]
chriswill/DbUpReboot
source/DbUp.Reboot.Sqlite/SqlitePreprocessor.cs
539
C#
namespace AElf.Contracts.EconomicSystem.Tests { public static class ElectionContractConstants { public const int CitizenWelfareWeight = 1; public const int BackupSubsidyWeight = 1; public const int MinerRewardWeight = 3; public const int BasicMinerRewardWeight = 4; public const int VotesWeightRewardWeight = 1; public const int ReElectionRewardWeight = 1; } }
30.714286
53
0.688372
[ "MIT" ]
380086154/AElf
test/AElf.Contracts.EconomicSystem.Tests/ElectionContractConstants.cs
430
C#
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Xml.Linq; using Tridion.ExternalContentLibrary.V2; namespace SDL.ECommerce.Ecl { /// <summary> /// Base class for E-Commerce ECL providers. /// Each concrete implementation need to specify the following attribute: /// [AddIn("<ECL PROVIDER NAME>", Version = "<VERSION>")] /// </summary> public abstract class EclProvider : IContentLibrary { public static readonly XNamespace EcommerceEclNs = "http://sdl.com/ecl/ecommerce"; private static readonly string IconBasePath = Path.Combine(AddInFolder, "Themes"); internal static string MountPointId { get; private set; } public static IHostServices HostServices { get; private set; } public static ProductCatalog ProductCatalog { get; private set; } private static IDictionary<int, Category> rootCategoryMap = new Dictionary<int, Category>(); /// <summary> /// Get root category /// </summary> internal static Category GetRootCategory(int publicationId) { Category rootCategory; rootCategoryMap.TryGetValue(publicationId, out rootCategory); if (rootCategory == null ) { //lock ( EclProvider.EcommerceEclNs ) LOCK IS NOT NEEDED HERE, RIGHT? //{ rootCategory = ProductCatalog.GetAllCategories(publicationId); rootCategoryMap.Add(publicationId, rootCategory); //} } return rootCategory; } internal static string AddInFolder { get { string codeBase = Assembly.GetExecutingAssembly().CodeBase; UriBuilder uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); return Path.GetDirectoryName(path); } } /// <summary> /// Get a specific category by its identity /// </summary> /// <param name="categoryId"></param> /// <returns></returns> internal static Category GetCategory(string categoryId, int publicationId) { return FindCategoryById(GetRootCategory(publicationId), categoryId); } /// <summary> /// Get all available catagories in a flat list /// </summary> /// <returns></returns> internal static List<Category> GetAllCategories(int publicationId) { var allCategories = new List<Category>(); GetCategories(GetRootCategory(publicationId), allCategories); /* allCategories.Sort(delegate(Category x, Category y) { return x.Title.CompareTo(y.Title); }); */ return allCategories; } private static void GetCategories(Category category, List<Category> categories) { foreach (var subCategory in category.Categories) { categories.Add(subCategory); GetCategories(subCategory, categories); } } internal static List<string> GetAllCategoryIds(int publicationId) { List<string> allCategoryIds = new List<string>(); getCategoryIds(GetRootCategory(publicationId), allCategoryIds); allCategoryIds.Sort(); return allCategoryIds; } private static void getCategoryIds(Category category, List<string> categoryIds) { foreach ( var subCategory in category.Categories ) { categoryIds.Add(subCategory.CategoryId); getCategoryIds(subCategory, categoryIds); } } private static Category FindCategoryById(Category category, string categoryId) { foreach ( var subCategory in category.Categories ) { if (subCategory.CategoryId.Equals(categoryId)) return subCategory; else { var cat = FindCategoryById(subCategory, categoryId); if (cat != null) return cat; } } return null; } internal static byte[] GetIconImage(string iconIdentifier, int iconSize) { int actualSize; // get icon directly from default theme folder return HostServices.GetIcon(IconBasePath, "_Default", iconIdentifier, iconSize, out actualSize); } /// <summary> /// Initialize the ECL provider /// </summary> /// <param name="mountPointId"></param> /// <param name="configurationXmlElement"></param> /// <param name="hostServices"></param> public void Initialize(string mountPointId, string configurationXmlElement, IHostServices hostServices) { MountPointId = mountPointId; HostServices = hostServices; // read ExtenalContentLibrary.xml for this mountpoint XElement config = XElement.Parse(configurationXmlElement); // Initialize the product catalog with config // ProductCatalog = this.CreateProductCatalog(config); } /// <summary> /// Create a new instance of the product catalog. Needs to be implemented by concrete subclass. /// </summary> /// <param name="configuration"></param> /// <returns></returns> protected abstract ProductCatalog CreateProductCatalog(XElement configuration); public abstract IContentLibraryContext CreateContext(IEclSession tridionUser); public IList<IDisplayType> DisplayTypes { get { return new List<IDisplayType> { //HostServices.CreateDisplayType("type", "Catalog Type", EclItemTypes.Folder), HostServices.CreateDisplayType("category", "Product Category", EclItemTypes.Folder), HostServices.CreateDisplayType("category", "Product Category", EclItemTypes.File), HostServices.CreateDisplayType("product", "Product", EclItemTypes.File) }; } } public byte[] GetIconImage(string theme, string iconIdentifier, int iconSize) { return GetIconImage(iconIdentifier, iconSize); } public void Dispose() { } } }
35.695652
111
0.586784
[ "Apache-2.0" ]
erikssonorjan/ecommerce-framework
ecl/ecommerce-ecl-framework/ecommerce-ecl-framework/EclProvider.cs
6,570
C#
using System; using System.Collections.Generic; using NHapi.Base.Log; using NHapi.Model.V24.Group; using NHapi.Model.V24.Segment; using NHapi.Model.V24.Datatype; using NHapi.Base; using NHapi.Base.Parser; using NHapi.Base.Model; namespace NHapi.Model.V24.Message { ///<summary> /// Represents a ADT_A01 message structure (see chapter 3). This structure contains the /// following elements: ///<ol> ///<li>0: MSH (Message Header) </li> ///<li>1: EVN (Event Type) </li> ///<li>2: PID (Patient identification) </li> ///<li>3: PD1 (patient additional demographic) optional </li> ///<li>4: ROL (Role) optional repeating</li> ///<li>5: NK1 (Next of kin / associated parties) optional repeating</li> ///<li>6: PV1 (Patient visit) </li> ///<li>7: PV2 (Patient visit - additional information) optional </li> ///<li>8: ROL (Role) optional repeating</li> ///<li>9: DB1 (Disability) optional repeating</li> ///<li>10: OBX (Observation/Result) optional repeating</li> ///<li>11: AL1 (Patient allergy information) optional repeating</li> ///<li>12: DG1 (Diagnosis) optional repeating</li> ///<li>13: DRG (Diagnosis Related Group) optional </li> ///<li>14: ADT_A01_PROCEDURE (a Group object) optional repeating</li> ///<li>15: GT1 (Guarantor) optional repeating</li> ///<li>16: ADT_A01_INSURANCE (a Group object) optional repeating</li> ///<li>17: ACC (Accident) optional </li> ///<li>18: UB1 (UB82) optional </li> ///<li>19: UB2 (UB92 Data) optional </li> ///<li>20: PDA (Patient death and autopsy) optional </li> ///</ol> ///</summary> [Serializable] public class ADT_A01 : AbstractMessage { ///<summary> /// Creates a new ADT_A01 Group with custom IModelClassFactory. ///</summary> public ADT_A01(IModelClassFactory factory) : base(factory){ init(factory); } ///<summary> /// Creates a new ADT_A01 Group with DefaultModelClassFactory. ///</summary> public ADT_A01() : base(new DefaultModelClassFactory()) { init(new DefaultModelClassFactory()); } ///<summary> /// initalize method for ADT_A01. This does the segment setup for the message. ///</summary> private void init(IModelClassFactory factory) { try { this.add(typeof(MSH), true, false); this.add(typeof(EVN), true, false); this.add(typeof(PID), true, false); this.add(typeof(PD1), false, false); this.add(typeof(ROL), false, true); this.add(typeof(NK1), false, true); this.add(typeof(PV1), true, false); this.add(typeof(PV2), false, false); this.add(typeof(ROL), false, true); this.add(typeof(DB1), false, true); this.add(typeof(OBX), false, true); this.add(typeof(AL1), false, true); this.add(typeof(DG1), false, true); this.add(typeof(DRG), false, false); this.add(typeof(ADT_A01_PROCEDURE), false, true); this.add(typeof(GT1), false, true); this.add(typeof(ADT_A01_INSURANCE), false, true); this.add(typeof(ACC), false, false); this.add(typeof(UB1), false, false); this.add(typeof(UB2), false, false); this.add(typeof(PDA), false, false); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating ADT_A01 - this is probably a bug in the source code generator.", e); } } public override string Version { get{ return Constants.VERSION; } } ///<summary> /// Returns MSH (Message Header) - creates it if necessary ///</summary> public MSH MSH { get{ MSH ret = null; try { ret = (MSH)this.GetStructure("MSH"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns EVN (Event Type) - creates it if necessary ///</summary> public EVN EVN { get{ EVN ret = null; try { ret = (EVN)this.GetStructure("EVN"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns PID (Patient identification) - creates it if necessary ///</summary> public PID PID { get{ PID ret = null; try { ret = (PID)this.GetStructure("PID"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns PD1 (patient additional demographic) - creates it if necessary ///</summary> public PD1 PD1 { get{ PD1 ret = null; try { ret = (PD1)this.GetStructure("PD1"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of ROL (Role) - creates it if necessary ///</summary> public ROL GetROL() { ROL ret = null; try { ret = (ROL)this.GetStructure("ROL"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of ROL /// * (Role) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public ROL GetROL(int rep) { return (ROL)this.GetStructure("ROL", rep); } /** * Returns the number of existing repetitions of ROL */ public int ROLRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("ROL").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the ROL results */ public IEnumerable<ROL> ROLs { get { for (int rep = 0; rep < ROLRepetitionsUsed; rep++) { yield return (ROL)this.GetStructure("ROL", rep); } } } ///<summary> ///Adds a new ROL ///</summary> public ROL AddROL() { return this.AddStructure("ROL") as ROL; } ///<summary> ///Removes the given ROL ///</summary> public void RemoveROL(ROL toRemove) { this.RemoveStructure("ROL", toRemove); } ///<summary> ///Removes the ROL at the given index ///</summary> public void RemoveROLAt(int index) { this.RemoveRepetition("ROL", index); } ///<summary> /// Returns first repetition of NK1 (Next of kin / associated parties) - creates it if necessary ///</summary> public NK1 GetNK1() { NK1 ret = null; try { ret = (NK1)this.GetStructure("NK1"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of NK1 /// * (Next of kin / associated parties) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public NK1 GetNK1(int rep) { return (NK1)this.GetStructure("NK1", rep); } /** * Returns the number of existing repetitions of NK1 */ public int NK1RepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("NK1").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the NK1 results */ public IEnumerable<NK1> NK1s { get { for (int rep = 0; rep < NK1RepetitionsUsed; rep++) { yield return (NK1)this.GetStructure("NK1", rep); } } } ///<summary> ///Adds a new NK1 ///</summary> public NK1 AddNK1() { return this.AddStructure("NK1") as NK1; } ///<summary> ///Removes the given NK1 ///</summary> public void RemoveNK1(NK1 toRemove) { this.RemoveStructure("NK1", toRemove); } ///<summary> ///Removes the NK1 at the given index ///</summary> public void RemoveNK1At(int index) { this.RemoveRepetition("NK1", index); } ///<summary> /// Returns PV1 (Patient visit) - creates it if necessary ///</summary> public PV1 PV1 { get{ PV1 ret = null; try { ret = (PV1)this.GetStructure("PV1"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns PV2 (Patient visit - additional information) - creates it if necessary ///</summary> public PV2 PV2 { get{ PV2 ret = null; try { ret = (PV2)this.GetStructure("PV2"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of ROL2 (Role) - creates it if necessary ///</summary> public ROL GetROL2() { ROL ret = null; try { ret = (ROL)this.GetStructure("ROL2"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of ROL2 /// * (Role) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public ROL GetROL2(int rep) { return (ROL)this.GetStructure("ROL2", rep); } /** * Returns the number of existing repetitions of ROL2 */ public int ROL2RepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("ROL2").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the ROL results */ public IEnumerable<ROL> ROL2s { get { for (int rep = 0; rep < ROL2RepetitionsUsed; rep++) { yield return (ROL)this.GetStructure("ROL2", rep); } } } ///<summary> ///Adds a new ROL ///</summary> public ROL AddROL2() { return this.AddStructure("ROL2") as ROL; } ///<summary> ///Removes the given ROL ///</summary> public void RemoveROL2(ROL toRemove) { this.RemoveStructure("ROL2", toRemove); } ///<summary> ///Removes the ROL at the given index ///</summary> public void RemoveROL2At(int index) { this.RemoveRepetition("ROL2", index); } ///<summary> /// Returns first repetition of DB1 (Disability) - creates it if necessary ///</summary> public DB1 GetDB1() { DB1 ret = null; try { ret = (DB1)this.GetStructure("DB1"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of DB1 /// * (Disability) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public DB1 GetDB1(int rep) { return (DB1)this.GetStructure("DB1", rep); } /** * Returns the number of existing repetitions of DB1 */ public int DB1RepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("DB1").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the DB1 results */ public IEnumerable<DB1> DB1s { get { for (int rep = 0; rep < DB1RepetitionsUsed; rep++) { yield return (DB1)this.GetStructure("DB1", rep); } } } ///<summary> ///Adds a new DB1 ///</summary> public DB1 AddDB1() { return this.AddStructure("DB1") as DB1; } ///<summary> ///Removes the given DB1 ///</summary> public void RemoveDB1(DB1 toRemove) { this.RemoveStructure("DB1", toRemove); } ///<summary> ///Removes the DB1 at the given index ///</summary> public void RemoveDB1At(int index) { this.RemoveRepetition("DB1", index); } ///<summary> /// Returns first repetition of OBX (Observation/Result) - creates it if necessary ///</summary> public OBX GetOBX() { OBX ret = null; try { ret = (OBX)this.GetStructure("OBX"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of OBX /// * (Observation/Result) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public OBX GetOBX(int rep) { return (OBX)this.GetStructure("OBX", rep); } /** * Returns the number of existing repetitions of OBX */ public int OBXRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("OBX").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the OBX results */ public IEnumerable<OBX> OBXs { get { for (int rep = 0; rep < OBXRepetitionsUsed; rep++) { yield return (OBX)this.GetStructure("OBX", rep); } } } ///<summary> ///Adds a new OBX ///</summary> public OBX AddOBX() { return this.AddStructure("OBX") as OBX; } ///<summary> ///Removes the given OBX ///</summary> public void RemoveOBX(OBX toRemove) { this.RemoveStructure("OBX", toRemove); } ///<summary> ///Removes the OBX at the given index ///</summary> public void RemoveOBXAt(int index) { this.RemoveRepetition("OBX", index); } ///<summary> /// Returns first repetition of AL1 (Patient allergy information) - creates it if necessary ///</summary> public AL1 GetAL1() { AL1 ret = null; try { ret = (AL1)this.GetStructure("AL1"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of AL1 /// * (Patient allergy information) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public AL1 GetAL1(int rep) { return (AL1)this.GetStructure("AL1", rep); } /** * Returns the number of existing repetitions of AL1 */ public int AL1RepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("AL1").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the AL1 results */ public IEnumerable<AL1> AL1s { get { for (int rep = 0; rep < AL1RepetitionsUsed; rep++) { yield return (AL1)this.GetStructure("AL1", rep); } } } ///<summary> ///Adds a new AL1 ///</summary> public AL1 AddAL1() { return this.AddStructure("AL1") as AL1; } ///<summary> ///Removes the given AL1 ///</summary> public void RemoveAL1(AL1 toRemove) { this.RemoveStructure("AL1", toRemove); } ///<summary> ///Removes the AL1 at the given index ///</summary> public void RemoveAL1At(int index) { this.RemoveRepetition("AL1", index); } ///<summary> /// Returns first repetition of DG1 (Diagnosis) - creates it if necessary ///</summary> public DG1 GetDG1() { DG1 ret = null; try { ret = (DG1)this.GetStructure("DG1"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of DG1 /// * (Diagnosis) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public DG1 GetDG1(int rep) { return (DG1)this.GetStructure("DG1", rep); } /** * Returns the number of existing repetitions of DG1 */ public int DG1RepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("DG1").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the DG1 results */ public IEnumerable<DG1> DG1s { get { for (int rep = 0; rep < DG1RepetitionsUsed; rep++) { yield return (DG1)this.GetStructure("DG1", rep); } } } ///<summary> ///Adds a new DG1 ///</summary> public DG1 AddDG1() { return this.AddStructure("DG1") as DG1; } ///<summary> ///Removes the given DG1 ///</summary> public void RemoveDG1(DG1 toRemove) { this.RemoveStructure("DG1", toRemove); } ///<summary> ///Removes the DG1 at the given index ///</summary> public void RemoveDG1At(int index) { this.RemoveRepetition("DG1", index); } ///<summary> /// Returns DRG (Diagnosis Related Group) - creates it if necessary ///</summary> public DRG DRG { get{ DRG ret = null; try { ret = (DRG)this.GetStructure("DRG"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of ADT_A01_PROCEDURE (a Group object) - creates it if necessary ///</summary> public ADT_A01_PROCEDURE GetPROCEDURE() { ADT_A01_PROCEDURE ret = null; try { ret = (ADT_A01_PROCEDURE)this.GetStructure("PROCEDURE"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of ADT_A01_PROCEDURE /// * (a Group object) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public ADT_A01_PROCEDURE GetPROCEDURE(int rep) { return (ADT_A01_PROCEDURE)this.GetStructure("PROCEDURE", rep); } /** * Returns the number of existing repetitions of ADT_A01_PROCEDURE */ public int PROCEDURERepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("PROCEDURE").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the ADT_A01_PROCEDURE results */ public IEnumerable<ADT_A01_PROCEDURE> PROCEDUREs { get { for (int rep = 0; rep < PROCEDURERepetitionsUsed; rep++) { yield return (ADT_A01_PROCEDURE)this.GetStructure("PROCEDURE", rep); } } } ///<summary> ///Adds a new ADT_A01_PROCEDURE ///</summary> public ADT_A01_PROCEDURE AddPROCEDURE() { return this.AddStructure("PROCEDURE") as ADT_A01_PROCEDURE; } ///<summary> ///Removes the given ADT_A01_PROCEDURE ///</summary> public void RemovePROCEDURE(ADT_A01_PROCEDURE toRemove) { this.RemoveStructure("PROCEDURE", toRemove); } ///<summary> ///Removes the ADT_A01_PROCEDURE at the given index ///</summary> public void RemovePROCEDUREAt(int index) { this.RemoveRepetition("PROCEDURE", index); } ///<summary> /// Returns first repetition of GT1 (Guarantor) - creates it if necessary ///</summary> public GT1 GetGT1() { GT1 ret = null; try { ret = (GT1)this.GetStructure("GT1"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of GT1 /// * (Guarantor) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public GT1 GetGT1(int rep) { return (GT1)this.GetStructure("GT1", rep); } /** * Returns the number of existing repetitions of GT1 */ public int GT1RepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("GT1").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the GT1 results */ public IEnumerable<GT1> GT1s { get { for (int rep = 0; rep < GT1RepetitionsUsed; rep++) { yield return (GT1)this.GetStructure("GT1", rep); } } } ///<summary> ///Adds a new GT1 ///</summary> public GT1 AddGT1() { return this.AddStructure("GT1") as GT1; } ///<summary> ///Removes the given GT1 ///</summary> public void RemoveGT1(GT1 toRemove) { this.RemoveStructure("GT1", toRemove); } ///<summary> ///Removes the GT1 at the given index ///</summary> public void RemoveGT1At(int index) { this.RemoveRepetition("GT1", index); } ///<summary> /// Returns first repetition of ADT_A01_INSURANCE (a Group object) - creates it if necessary ///</summary> public ADT_A01_INSURANCE GetINSURANCE() { ADT_A01_INSURANCE ret = null; try { ret = (ADT_A01_INSURANCE)this.GetStructure("INSURANCE"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of ADT_A01_INSURANCE /// * (a Group object) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public ADT_A01_INSURANCE GetINSURANCE(int rep) { return (ADT_A01_INSURANCE)this.GetStructure("INSURANCE", rep); } /** * Returns the number of existing repetitions of ADT_A01_INSURANCE */ public int INSURANCERepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("INSURANCE").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the ADT_A01_INSURANCE results */ public IEnumerable<ADT_A01_INSURANCE> INSURANCEs { get { for (int rep = 0; rep < INSURANCERepetitionsUsed; rep++) { yield return (ADT_A01_INSURANCE)this.GetStructure("INSURANCE", rep); } } } ///<summary> ///Adds a new ADT_A01_INSURANCE ///</summary> public ADT_A01_INSURANCE AddINSURANCE() { return this.AddStructure("INSURANCE") as ADT_A01_INSURANCE; } ///<summary> ///Removes the given ADT_A01_INSURANCE ///</summary> public void RemoveINSURANCE(ADT_A01_INSURANCE toRemove) { this.RemoveStructure("INSURANCE", toRemove); } ///<summary> ///Removes the ADT_A01_INSURANCE at the given index ///</summary> public void RemoveINSURANCEAt(int index) { this.RemoveRepetition("INSURANCE", index); } ///<summary> /// Returns ACC (Accident) - creates it if necessary ///</summary> public ACC ACC { get{ ACC ret = null; try { ret = (ACC)this.GetStructure("ACC"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns UB1 (UB82) - creates it if necessary ///</summary> public UB1 UB1 { get{ UB1 ret = null; try { ret = (UB1)this.GetStructure("UB1"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns UB2 (UB92 Data) - creates it if necessary ///</summary> public UB2 UB2 { get{ UB2 ret = null; try { ret = (UB2)this.GetStructure("UB2"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns PDA (Patient death and autopsy) - creates it if necessary ///</summary> public PDA PDA { get{ PDA ret = null; try { ret = (PDA)this.GetStructure("PDA"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } } }
26.524436
145
0.646375
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AMCN41R/nHapi
src/NHapi.Model.V24/Message/ADT_A01.cs
28,222
C#
using System.Collections.Generic; using System.IO; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SuperSocket; using SuperSocket.ProtoBase; namespace Tests { public class RegularHostConfigurator : IHostConfigurator { public string WebSocketSchema => "ws"; public bool IsSecure => false; public ListenOptions Listener { get; private set; } public void Configurate(HostBuilderContext context, IServiceCollection services) { services.Configure<ServerOptions>((options) => { var listener = options.Listeners[0]; Listener = listener; }); } public ValueTask<Stream> GetClientStream(Socket socket) { return new ValueTask<Stream>(new NetworkStream(socket)); } } }
28
88
0.666023
[ "Apache-2.0" ]
CCCfreedom/SuperSocket
test/Test/RegularHostConfigurator.cs
1,036
C#
using System.Threading.Tasks; using MediatR; using NLog; using SFA.DAS.EmployerUsers.Application.Exceptions; using SFA.DAS.EmployerUsers.Application.Extensions; using SFA.DAS.EmployerUsers.Application.Services.Notification; using SFA.DAS.EmployerUsers.Application.Services.Password; using SFA.DAS.EmployerUsers.Application.Validation; using SFA.DAS.EmployerUsers.Domain; using SFA.DAS.EmployerUsers.Domain.Auditing; using SFA.DAS.EmployerUsers.Domain.Auditing.Login; using SFA.DAS.EmployerUsers.Domain.Data; namespace SFA.DAS.EmployerUsers.Application.Commands.PasswordReset { public class PasswordResetCommandHandler : IAsyncRequestHandler<PasswordResetCommand, PasswordResetResponse> { private readonly ILogger _logger; private readonly IAuditService _auditService; private readonly IUserRepository _userRepository; private readonly IValidator<PasswordResetCommand> _validator; private readonly ICommunicationService _communicationService; private readonly IPasswordService _passwordService; public PasswordResetCommandHandler( IUserRepository userRepository, IValidator<PasswordResetCommand> validator, ICommunicationService communicationService, IPasswordService passwordService, ILogger logger, IAuditService auditService) { _userRepository = userRepository; _validator = validator; _communicationService = communicationService; _passwordService = passwordService; _logger = logger; _auditService = auditService; } public async Task<PasswordResetResponse> Handle(PasswordResetCommand message) { _logger.Info($"Received PasswordResetCommand for email '{message.Email}'"); var user = await _userRepository.GetByEmailAddress(message.Email); message.User = user; var validationResult = await _validator.ValidateAsync(message); if (!validationResult.IsValid()) { throw new InvalidRequestException(validationResult.ValidationDictionary); } var resetCode = message.User?.SecurityCodes?.MatchSecurityCode(message.PasswordResetCode); var securedPassword = await _passwordService.GenerateAsync(message.Password); message.User.Password = securedPassword.HashedPassword; message.User.PasswordProfileId = securedPassword.ProfileId; message.User.Salt = securedPassword.Salt; message.User.IsActive = true; message.User.ExpireSecurityCodesOfType(SecurityCodeType.AccessCode); message.User.ExpireSecurityCodesOfType(SecurityCodeType.PasswordResetCode); await _auditService.WriteAudit(new PasswordResetAuditMessage(message.User)); await _userRepository.Update(message.User); _logger.Info($"Password changed for user id '{message.User.Id}'"); return new PasswordResetResponse { ResetCode = resetCode }; } } public class PasswordResetResponse { public SecurityCode ResetCode { get; set; } } }
40.1375
112
0.708813
[ "MIT" ]
SkillsFundingAgency/das-employerusers
src/SFA.DAS.EmployerUsers.Application/Commands/PasswordReset/PasswordResetCommandHandler.cs
3,213
C#
 namespace KSoft.Phoenix.Phx { public sealed class BWeaponType : Collections.BListAutoIdObject { #region Xml constants public static readonly XML.BListXmlParams kBListXmlParams = new XML.BListXmlParams("WeaponType") { DataName = "Name", Flags = XML.BCollectionXmlParamsFlags.UseElementForData }; public static readonly Engine.XmlFileInfo kXmlFileInfo = new Engine.XmlFileInfo { Directory = Engine.GameDirectory.Data, FileName = "WeaponTypes.xml", RootName = kBListXmlParams.RootName }; public static readonly Engine.ProtoDataXmlFileInfo kProtoFileInfo = new Engine.ProtoDataXmlFileInfo( Engine.XmlFilePriority.Lists, kXmlFileInfo); #endregion #region DeathAnimation string mDeathAnimation; public string DeathAnimation { get { return mDeathAnimation; } set { mDeathAnimation = value; } } #endregion public Collections.BTypeValues<BWeaponModifier> Modifiers { get; private set; } public BWeaponType() { Modifiers = new Collections.BTypeValues<BWeaponModifier>(BWeaponModifier.kBListParams); } #region BListObjectBase Members public override void Serialize<TDoc, TCursor>(IO.TagElementStream<TDoc, TCursor, string> s) { s.StreamElementOpt("DeathAnimation", ref mDeathAnimation, Predicates.IsNotNullOrEmpty); XML.XmlUtil.Serialize(s, Modifiers, BWeaponModifier.kBListXmlParams); } #endregion }; }
29.306122
103
0.736769
[ "MIT" ]
KornnerStudios/KSoft.Phoenix
KSoft.Phoenix/Phx/BWeaponType.cs
1,438
C#
using System; using System.Collections.Generic; namespace Lecture03.Models { public class Superhero { public int Id { get; set; } public string Name { get; set; } public string AlterEgo { get; set; } public string Occupation { get; set; } public int? CityId { get; set; } public Gender Gender { get; set; } public int FirstAppearance { get; set; } public ICollection<string> Powers { get; set; } public ICollection<Group> GroupAffiliations { get; set; } public override string ToString() => $"{Name} aka {AlterEgo} ({FirstAppearance})"; } public class Superhero2 { public string GivenName { get; set; } public string Surname { get; set; } public string AlterEgo { get; set; } public DateTime FirstAppearance { get; set; } public string City { get; set; } public override string ToString() { return $"{GivenName} {Surname} aka {AlterEgo}"; } } }
30.4
91
0.570489
[ "MIT" ]
ondfisk/BDSA2020
Lecture03/Lecture03/Models/Superhero.cs
1,066
C#
using System; using System.Threading.Tasks; using FluentAssertions; using Moq; using Orleans.TestKit; using TestGrains; using TestInterfaces; using Xunit; namespace Orleans.TestKit.Tests { public class GrainProbeTests : TestKitBase { [Fact] public async Task SetupProbe() { IPing grain = Silo.CreateGrain<PingGrain>(1); var pong = Silo.AddProbe<IPong>(22); await grain.Ping(); pong.Verify(p => p.Pong(), Times.Once); } [Fact] public void MissingProbe() { IPing grain = Silo.CreateGrain<PingGrain>(1); //There should not be an exception, since we are using loose grain generation grain.Invoking(p => p.Ping()).ShouldNotThrow(); } [Fact] public void InvalidProbe() { IPing grain = Silo.CreateGrain<PingGrain>(1); //This uses the wrong id for the IPong since this is hard coded within PingGrain var pong = Silo.AddProbe<IPong>(0); grain.Invoking(p => p.Ping()).ShouldNotThrow(); pong.Verify(p => p.Pong(), Times.Never); } [Fact] public void InvalidProbeType() { IPing grain = Silo.CreateGrain<PingGrain>(1); //This correct id, but a different grain type var pong = Silo.AddProbe<IPong2>(22); grain.Invoking(p => p.Ping()).ShouldNotThrow(); pong.Verify(p => p.Pong2(), Times.Never); } [Fact] public async Task GuidKeyProbe() { var probe = Silo.AddProbe<IGuidKeyGrain>(Guid.NewGuid()); var key = await probe.Object.GetKey(); probe.Should().NotBeNull(); key.Should().Be(Guid.Empty); } [Fact] public async Task IntKeyProbe() { var probe = Silo.AddProbe<IIntegerKeyGrain>(2); var key = await probe.Object.GetKey(); probe.Should().NotBeNull(); key.Should().Be(0); } [Fact] public async Task StringKeyProbe() { var probe = Silo.AddProbe<IStringKeyGrain>("ABC"); var key = await probe.Object.GetKey(); probe.Should().NotBeNull(); key.Should().BeNull(); } [Fact] public async Task FactoryProbe() { var pong = new Mock<IPong>(); this.Silo.AddProbe<IPong>(identity => pong); var grain = this.Silo.CreateGrain<PingGrain>(1); await grain.Ping(); pong.Verify(p => p.Pong(), Times.Once); } [Fact] public async Task ProbeWithClassPrefix() { Silo.AddProbe<IDevice>("Android", "TestGrains.DeviceAndroidGrain"); Silo.AddProbe<IDevice>("IOS", "TestGrains.DeviceIosGrain"); var managerGrain = this.Silo.CreateGrain<DeviceManagerGrain>(0); var iosGrain = await managerGrain.GetDeviceGrain("IOS"); var androidGrain = await managerGrain.GetDeviceGrain("Android"); (await iosGrain.GetDeviceType()).Should().Equals("IOS"); (await iosGrain.GetDeviceType()).Should().Equals("Android"); } } }
26.095238
92
0.551399
[ "MIT" ]
AdamWyzgol/OrleansTestKit
test/OrleansTestKit.Tests/Tests/GrainProbeTests.cs
3,290
C#
namespace Binance.Spot.Tests.Models { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Spot.Models; public class LoanDirectionTests { [TestMethod] public void ToString_Matches_Value() { LoanDirection model = LoanDirection.ADDITIONAL; model.ToString().Should().Be(model.Value); } } }
23.352941
59
0.644836
[ "MIT" ]
NonoElRobot/binance-connector-dotnet
test/Binance.Spot.Tests/Models/LoanDirectionTests.cs
397
C#
namespace PhilipsSignageDisplaySicp { public static class BooleanExtensions { public static byte ToByte(this bool source, byte trueValue = 1, byte falseValue = 0) { return source ? trueValue : falseValue; } } }
25.8
92
0.635659
[ "MIT" ]
aolde/philips-signage-display-sicp
PhilipsSignageDisplaySicp/Utils/BooleanExtensions.cs
258
C#
// See https://aka.ms/new-console-template for more information public interface IFooService { void Foo(); }
22.6
64
0.725664
[ "MIT" ]
Philippe-Laval/TestMapster
TestMapster/IFooService.cs
115
C#
/******************************************************************************* * Copyright 2012-2019 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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.Comprehend; using Amazon.Comprehend.Model; namespace Amazon.PowerShell.Cmdlets.COMP { /// <summary> /// Gets a list of the properties of all entity recognizers that you created, including /// recognizers currently in training. Allows you to filter the list of recognizers based /// on criteria such as status and submission time. This call returns up to 500 entity /// recognizers in the list, with a default number of 100 recognizers in the list. /// /// /// <para> /// The results of this list are not in any particular order. Please get the list and /// sort locally if needed. /// </para><br/><br/>This cmdlet automatically pages all available results to the pipeline - parameters related to iteration are only needed if you want to manually control the paginated output. To disable autopagination, use -NoAutoIteration. /// </summary> [Cmdlet("Get", "COMPEntityRecognizerList")] [OutputType("Amazon.Comprehend.Model.EntityRecognizerProperties")] [AWSCmdlet("Calls the Amazon Comprehend ListEntityRecognizers API operation.", Operation = new[] {"ListEntityRecognizers"}, SelectReturnType = typeof(Amazon.Comprehend.Model.ListEntityRecognizersResponse))] [AWSCmdletOutput("Amazon.Comprehend.Model.EntityRecognizerProperties or Amazon.Comprehend.Model.ListEntityRecognizersResponse", "This cmdlet returns a collection of Amazon.Comprehend.Model.EntityRecognizerProperties objects.", "The service call response (type Amazon.Comprehend.Model.ListEntityRecognizersResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class GetCOMPEntityRecognizerListCmdlet : AmazonComprehendClientCmdlet, IExecutor { #region Parameter Filter_Status /// <summary> /// <para> /// <para>The status of an entity recognizer.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] [AWSConstantClassSource("Amazon.Comprehend.ModelStatus")] public Amazon.Comprehend.ModelStatus Filter_Status { get; set; } #endregion #region Parameter Filter_SubmitTimeAfter /// <summary> /// <para> /// <para>Filters the list of entities based on the time that the list was submitted for processing. /// Returns only jobs submitted after the specified time. Jobs are returned in ascending /// order, oldest to newest.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.DateTime? Filter_SubmitTimeAfter { get; set; } #endregion #region Parameter Filter_SubmitTimeBefore /// <summary> /// <para> /// <para>Filters the list of entities based on the time that the list was submitted for processing. /// Returns only jobs submitted before the specified time. Jobs are returned in descending /// order, newest to oldest.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.DateTime? Filter_SubmitTimeBefore { get; set; } #endregion #region Parameter MaxResult /// <summary> /// <para> /// <para> The maximum number of results to return on each page. The default is 100.</para> /// </para> /// <para> /// <br/><b>Note:</b> In AWSPowerShell and AWSPowerShell.NetCore this parameter is used to limit the total number of items returned by the cmdlet. /// <br/>In AWS.Tools this parameter is simply passed to the service to specify how many items should be returned by each service call. /// <br/>Pipe the output of this cmdlet into Select-Object -First to terminate retrieving data pages early and control the number of items returned. /// </para> /// <para>If a value for this parameter is not specified the cmdlet will use a default value of '<b>500</b>'.</para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("MaxItems","MaxResults")] public int? MaxResult { get; set; } #endregion #region Parameter NextToken /// <summary> /// <para> /// <para>Identifies the next page of results to return.</para> /// </para> /// <para> /// <br/><b>Note:</b> This parameter is only used if you are manually controlling output pagination of the service API call. /// <br/>In order to manually control output pagination, use '-NextToken $null' for the first call and '-NextToken $AWSHistory.LastServiceResponse.NextToken' for subsequent calls. /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String NextToken { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'EntityRecognizerPropertiesList'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.Comprehend.Model.ListEntityRecognizersResponse). /// Specifying the name of a property of type Amazon.Comprehend.Model.ListEntityRecognizersResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "EntityRecognizerPropertiesList"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the Filter_Status parameter. /// The -PassThru parameter is deprecated, use -Select '^Filter_Status' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^Filter_Status' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter NoAutoIteration /// <summary> /// By default the cmdlet will auto-iterate and retrieve all results to the pipeline by performing multiple /// service calls. If set, the cmdlet will retrieve only the next 'page' of results using the value of NextToken /// as the start point. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter NoAutoIteration { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.Comprehend.Model.ListEntityRecognizersResponse, GetCOMPEntityRecognizerListCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.Filter_Status; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.Filter_Status = this.Filter_Status; context.Filter_SubmitTimeAfter = this.Filter_SubmitTimeAfter; context.Filter_SubmitTimeBefore = this.Filter_SubmitTimeBefore; context.MaxResult = this.MaxResult; #if MODULAR if (!ParameterWasBound(nameof(this.MaxResult))) { WriteVerbose("MaxResult parameter unset, using default value of '500'"); context.MaxResult = 500; } #endif #if !MODULAR if (ParameterWasBound(nameof(this.MaxResult)) && this.MaxResult.HasValue) { WriteWarning("AWSPowerShell and AWSPowerShell.NetCore use the MaxResult parameter to limit the total number of items returned by the cmdlet." + " This behavior is obsolete and will be removed in a future version of these modules. Pipe the output of this cmdlet into Select-Object -First to terminate" + " retrieving data pages early and control the number of items returned. AWS.Tools already implements the new behavior of simply passing MaxResult" + " to the service to specify how many items should be returned by each service call."); } #endif context.NextToken = this.NextToken; // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members #if MODULAR public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent; #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute // create request and set iteration invariants var request = new Amazon.Comprehend.Model.ListEntityRecognizersRequest(); // populate Filter var requestFilterIsNull = true; request.Filter = new Amazon.Comprehend.Model.EntityRecognizerFilter(); Amazon.Comprehend.ModelStatus requestFilter_filter_Status = null; if (cmdletContext.Filter_Status != null) { requestFilter_filter_Status = cmdletContext.Filter_Status; } if (requestFilter_filter_Status != null) { request.Filter.Status = requestFilter_filter_Status; requestFilterIsNull = false; } System.DateTime? requestFilter_filter_SubmitTimeAfter = null; if (cmdletContext.Filter_SubmitTimeAfter != null) { requestFilter_filter_SubmitTimeAfter = cmdletContext.Filter_SubmitTimeAfter.Value; } if (requestFilter_filter_SubmitTimeAfter != null) { request.Filter.SubmitTimeAfter = requestFilter_filter_SubmitTimeAfter.Value; requestFilterIsNull = false; } System.DateTime? requestFilter_filter_SubmitTimeBefore = null; if (cmdletContext.Filter_SubmitTimeBefore != null) { requestFilter_filter_SubmitTimeBefore = cmdletContext.Filter_SubmitTimeBefore.Value; } if (requestFilter_filter_SubmitTimeBefore != null) { request.Filter.SubmitTimeBefore = requestFilter_filter_SubmitTimeBefore.Value; requestFilterIsNull = false; } // determine if request.Filter should be set to null if (requestFilterIsNull) { request.Filter = null; } if (cmdletContext.MaxResult != null) { request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToServiceTypeInt32(cmdletContext.MaxResult.Value); } // Initialize loop variant and commence piping var _nextToken = cmdletContext.NextToken; var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken)); var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); do { request.NextToken = _nextToken; CmdletOutput output; try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; if (!useParameterSelect) { pipelineOutput = cmdletContext.Select(response, this); } output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; _nextToken = response.NextToken; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } ProcessOutput(output); } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken)); if (useParameterSelect) { WriteObject(cmdletContext.Select(null, this)); } return null; } #else public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent; // create request and set iteration invariants var request = new Amazon.Comprehend.Model.ListEntityRecognizersRequest(); // populate Filter var requestFilterIsNull = true; request.Filter = new Amazon.Comprehend.Model.EntityRecognizerFilter(); Amazon.Comprehend.ModelStatus requestFilter_filter_Status = null; if (cmdletContext.Filter_Status != null) { requestFilter_filter_Status = cmdletContext.Filter_Status; } if (requestFilter_filter_Status != null) { request.Filter.Status = requestFilter_filter_Status; requestFilterIsNull = false; } System.DateTime? requestFilter_filter_SubmitTimeAfter = null; if (cmdletContext.Filter_SubmitTimeAfter != null) { requestFilter_filter_SubmitTimeAfter = cmdletContext.Filter_SubmitTimeAfter.Value; } if (requestFilter_filter_SubmitTimeAfter != null) { request.Filter.SubmitTimeAfter = requestFilter_filter_SubmitTimeAfter.Value; requestFilterIsNull = false; } System.DateTime? requestFilter_filter_SubmitTimeBefore = null; if (cmdletContext.Filter_SubmitTimeBefore != null) { requestFilter_filter_SubmitTimeBefore = cmdletContext.Filter_SubmitTimeBefore.Value; } if (requestFilter_filter_SubmitTimeBefore != null) { request.Filter.SubmitTimeBefore = requestFilter_filter_SubmitTimeBefore.Value; requestFilterIsNull = false; } // determine if request.Filter should be set to null if (requestFilterIsNull) { request.Filter = null; } // Initialize loop variants and commence piping System.String _nextToken = null; int? _emitLimit = null; int _retrievedSoFar = 0; if (AutoIterationHelpers.HasValue(cmdletContext.NextToken)) { _nextToken = cmdletContext.NextToken; } if (cmdletContext.MaxResult.HasValue) { // The service has a maximum page size of 500. If the user has // asked for more items than page max, and there is no page size // configured, we rely on the service ignoring the set maximum // and giving us 500 items back. If a page size is set, that will // be used to configure the pagination. // We'll make further calls to satisfy the user's request. _emitLimit = cmdletContext.MaxResult; } var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken)); var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); do { request.NextToken = _nextToken; if (_emitLimit.HasValue) { int correctPageSize = Math.Min(500, _emitLimit.Value); request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToInt32(correctPageSize); } else if (!ParameterWasBound(nameof(this.MaxResult))) { request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToInt32(500); } CmdletOutput output; try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; if (!useParameterSelect) { pipelineOutput = cmdletContext.Select(response, this); } output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; int _receivedThisCall = response.EntityRecognizerPropertiesList.Count; _nextToken = response.NextToken; _retrievedSoFar += _receivedThisCall; if (_emitLimit.HasValue) { _emitLimit -= _receivedThisCall; } } catch (Exception e) { if (_retrievedSoFar == 0 || !_emitLimit.HasValue) { output = new CmdletOutput { ErrorResponse = e }; } else { break; } } ProcessOutput(output); } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken) && (!_emitLimit.HasValue || _emitLimit.Value >= 1)); if (useParameterSelect) { WriteObject(cmdletContext.Select(null, this)); } return null; } #endif public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.Comprehend.Model.ListEntityRecognizersResponse CallAWSServiceOperation(IAmazonComprehend client, Amazon.Comprehend.Model.ListEntityRecognizersRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Comprehend", "ListEntityRecognizers"); try { #if DESKTOP return client.ListEntityRecognizers(request); #elif CORECLR return client.ListEntityRecognizersAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public Amazon.Comprehend.ModelStatus Filter_Status { get; set; } public System.DateTime? Filter_SubmitTimeAfter { get; set; } public System.DateTime? Filter_SubmitTimeBefore { get; set; } public int? MaxResult { get; set; } public System.String NextToken { get; set; } public System.Func<Amazon.Comprehend.Model.ListEntityRecognizersResponse, GetCOMPEntityRecognizerListCmdlet, object> Select { get; set; } = (response, cmdlet) => response.EntityRecognizerPropertiesList; } } }
47.104938
247
0.591622
[ "Apache-2.0" ]
JekzVadaria/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/Comprehend/Basic/Get-COMPEntityRecognizerList-Cmdlet.cs
22,893
C#
using System; using Algorithms.Strings; using Xunit; namespace Algorithms.Test.Strings { public sealed class AlphabetTest { [Fact] public void Test_ThrowOn_Duplicates() { Assert.Throws<InvalidOperationException>(() => new Alphabet("AAB")); } [Fact] public void Test_Radix() { Alphabet alphabet = Alphabet.Binary; Assert.Equal(2, alphabet.Radix); } [Fact] public void Test_BinaryLogRadix() { Alphabet alphabet = Alphabet.Decimal; Assert.Equal(4, alphabet.BinaryLogRadix); } [Fact] public void Test_Contains() { Alphabet alphabet = Alphabet.Decimal; Assert.True(alphabet.Contains('9')); } [Fact] public void Test_NotContains() { Alphabet alphabet = Alphabet.Decimal; Assert.False(alphabet.Contains('A')); } [Fact] public void Test_ToIndex() { Alphabet alphabet = Alphabet.Decimal; Assert.Equal(9, alphabet.ToIndex('9')); } [Fact] public void Test_ToIndices() { Alphabet alphabet = Alphabet.Decimal; AssertUtilities.Sequence(new Int32[3] { 7, 8, 9 }, alphabet.ToIndices("789")); } [Fact] public void Test_ToChar() { Alphabet alphabet = Alphabet.Decimal; Assert.Equal('9', alphabet.ToChar(9)); } [Fact] public void Test_ToChars() { Alphabet alphabet = Alphabet.Decimal; AssertUtilities.Sequence(new Char[3] { '7', '8', '9' }, alphabet.ToChars(new Int32[3] { 7, 8, 9 })); } [Fact] public void Test_ToIndex_RadixConstructor() { Alphabet alphabet = new Alphabet(10); Assert.Equal(9, alphabet.ToIndex((Char)9)); } [Fact] public void Test_ToChar_RadixConstructor() { Alphabet alphabet = new Alphabet(10); Assert.Equal((Char)9, alphabet.ToChar(9)); } } }
22.739583
112
0.525424
[ "MIT" ]
gfurtadoalmeida/study-algorithms
book-01/Algorithms.Test/Strings/AlphabetTest.cs
2,185
C#
using System; using System.Collections.Generic; using System.Text; namespace P04_Hospital { public class Room { private int name; private List<string> pacients; public Room(int name) { this.Name = name; this.Pacients = new List<string>(); } public int Name { get => name; set => name = value; } public List<string> Pacients { get => pacients; set => pacients = value; } public bool freeRoom() { return this.Pacients.Count < 3; } public void AddPacient(string pacient) { if(freeRoom()) { this.pacients.Add(pacient); } } } }
18.5
47
0.459459
[ "MIT" ]
PavelRunchev/Dot.Net-Advanced
OOP - Basics/2. Working with Abstraction - Exercise/P04_Hospital/Room.cs
816
C#
// Released under the MIT License. // // Copyright (c) 2018 Ntreev Soft co., Ltd. // Copyright (c) 2020 Jeesu Choi // // 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. // // Forked from https://github.com/NtreevSoft/Crema // Namespaces and files starting with "Ntreev" have been renamed to "JSSoft". using JSSoft.Crema.Presentation.Home.Dialogs.ViewModels; using JSSoft.Crema.Presentation.Home.Properties; using JSSoft.Crema.Presentation.Home.Services.ViewModels; using JSSoft.ModernUI.Framework; using System.ComponentModel.Composition; namespace JSSoft.Crema.Presentation.Home.MenuItems { [Export(typeof(IMenuItem))] [ParentType(typeof(ConnectionItemViewModel))] class ConnectionItemCopyMenuItem : MenuItemBase { private readonly CremaAppHostViewModel cremaAppHost; [ImportingConstructor] public ConnectionItemCopyMenuItem(CremaAppHostViewModel cremaAppHost) { this.cremaAppHost = cremaAppHost; this.cremaAppHost.Opened += this.InvokeCanExecuteChangedEvent; this.cremaAppHost.Closed += this.InvokeCanExecuteChangedEvent; this.DisplayName = Resources.MenuItem_Copy; } protected override bool OnCanExecute(object parameter) { if (this.cremaAppHost.IsOpened == false && parameter is ConnectionItemViewModel) return true; return false; } protected async override void OnExecute(object parameter) { if (this.cremaAppHost.IsOpened == false && parameter is ConnectionItemViewModel connectionItem) { var dialog = new ConnectionItemEditViewModel(this.cremaAppHost) { DisplayName = Resources.Title_CopyConnectionItem, ConnectionInfo = connectionItem.Clone(), }; if (await dialog.ShowDialogAsync() == true) { this.cremaAppHost.ConnectionItems.Add(dialog.ConnectionInfo); } } } } }
44.608696
121
0.695906
[ "MIT" ]
s2quake/JSSoft.Crema
client/JSSoft.Crema.Presentation.Home/MenuItems/ConnectionItemCopyMenuItem.cs
3,080
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading; using System.Threading.Tasks; using Amazon.GameLift.Model; namespace AmazonGameLiftPlugin.Core.ApiGatewayManagement { public interface IAmazonGameLiftClientWrapper { Task<CreateGameSessionResponse> CreateGameSessionAsync( CreateGameSessionRequest request, CancellationToken cancellationToken = default ); Task<CreatePlayerSessionResponse> CreatePlayerSession(CreatePlayerSessionRequest request); Task<SearchGameSessionsResponse> SearchGameSessions(SearchGameSessionsRequest request); Task<DescribeGameSessionsResponse> DescribeGameSessions(DescribeGameSessionsRequest request); } }
33.666667
101
0.766089
[ "Apache-2.0" ]
aws/amazon-gamelift-plugin-unity
Runtime/Core/ApiGatewayManagement/IAmazonGameLiftClientWrapper.cs
808
C#
using DotNet.HighStock.Attributes; using DotNet.HighStock.Helpers; namespace DotNet.HighStock.Options { /// <summary> /// /// </summary> public class YAxisEvents { /// <summary> /// As opposed to the <code>setExtremes</code> event, this event fires after the final min and max values are computed and corrected for <code>minRange</code>. /// </summary> [JsonFormatter("{0}")] public string AfterSetExtremes { get; set; } /// <summary> /// <p>Fires when the minimum and maximum is set for the axis, either by calling the <code>.setExtremes()</code> method or by selecting an area in the chart. The <code>this</code> keyword refers to the axis object itself. One parameter, <code>event</code>, is passed to the function. This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highstock.</p><p>The new user set minimum and maximum values can be found by <code>event.min</code> and <code>event.max</code>. When an axis is zoomed all the way out from the 'Reset zoom' button, <code>event.min</code> and <code>event.max</code> are null, and the new extremes are set based on <code>this.dataMin</code> and <code>this.dataMax</code>.</p> /// </summary> [JsonFormatter("{0}")] public string SetExtremes { get; set; } } }
49.413793
765
0.652477
[ "MIT" ]
lisa3907/dotnet.highstock
DotNet.HighStock/Options/YAxisEvents.cs
1,433
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Game.Configuration; using Game.Framework; using Game.Server; using HarmonyLib; using IRSE.Managers; namespace IRSE.Modules.HarmonyPatches { /// <summary> /// This class is stopping the internal command hooks from creating handlers as i handle that to insert my own commands. /// </summary> [HarmonyPatch(typeof(SvCommands), "InitCommandHooks")] internal static class StopInternalServerCommandHooks { /* public static void InitCommandHooks() { SvCommands.m_commandSystem.SecurityHandler = new Func<object, int, bool>(SvCommands.i_securityHandler); SvCommands.m_commandSystem.OutputHandler += new EventHandler<string>(SvCommands.i_outputHandler); SvCommands.m_commandSystem.ErrorHandler += new CommandSystem.ErrorHandlerDelegate(SvCommands.i_errorHandler); SvCommands.m_commandSystem.InputHandler += new CommandSystem.InputDelegate(SvCommands.i_inputHandler); SvCommands.m_commandSystem.ExecuteHandler += new CommandSystem.ExecuteHandlerDelegate(SvCommands.i_executeHandler); } */ /// <summary> /// Disables SvCommands class hooks /// </summary> /// <returns></returns> private static bool Prefix() { return false; } } }
35.75
125
0.700699
[ "MIT" ]
InterstellarRiftCommunityTools/InterstellarRiftServerExtender
InterstellarRiftServerExtender/Modules/HarmonyPatches/CommandSystemPatch.cs
1,432
C#
using System; using UIKit; using CoreGraphics; using Kunicardus.Touch.Helpers.UI; using ZXing; namespace Kunicardus.Touch { public class CardForScanView : UIView { #region Variables private string _cardNumber; #endregion #region Properties public UIButton Close { get; set; } #endregion #region Ctors public CardForScanView (CGRect frame, string cardNumber) : base (frame) { _cardNumber = cardNumber; this.BackgroundColor = UIColor.Clear.FromHexString (Styles.Colors.HeaderGreen); Close = new UIButton (UIButtonType.RoundedRect); } #endregion public override void LayoutSubviews () { base.LayoutSubviews (); Close.SetImage (ImageHelper.MaxResizeImage (UIImage.FromBundle ("close"), 22, 0), UIControlState.Normal); Close.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; Close.VerticalAlignment = UIControlContentVerticalAlignment.Center; Close.BackgroundColor = UIColor.Clear; Close.SetTitleColor (UIColor.White, UIControlState.Normal); Close.TintColor = UIColor.White; Close.SizeToFit (); Close.Frame = new CGRect (Frame.Width - Close.Frame.Width - 20, 0, Close.Frame.Width + 20, Close.Frame.Height + 20); UIImageView card = new UIImageView ( (Screen.IsTall ? UIImage.FromBundle ("card_vertical_big") : UIImage.FromBundle ("card_vertical")) ); card.SizeToFit (); card.Frame = new CGRect ((Frame.Width - card.Frame.Width) / 2.0f, (Frame.Height - card.Frame.Height) / 2, card.Frame.Width, card.Frame.Height); UILabel cardNumber = new UILabel (); if (!string.IsNullOrWhiteSpace (_cardNumber)) { cardNumber.Text = _cardNumber.Insert (4, " ").Insert (9, " ").Insert (14, " "); } else { cardNumber.Text = "Virtual card not available"; } cardNumber.Transform = CGAffineTransform.MakeRotation ((nfloat)Math.PI / 2.0f); cardNumber.Font = UIFont.SystemFontOfSize (22); cardNumber.SizeToFit (); cardNumber.Frame = new CGRect ((Frame.Width - cardNumber.Frame.Width) / 2.0f + 5f, card.Frame.Top + (card.Frame.Height - (card.Frame.Height / 6.0f) - cardNumber.Frame.Height) / 2.0f, cardNumber.Frame.Width, cardNumber.Frame.Height); // barcode generation nfloat barcodeHeight = (card.Frame.Width - cardNumber.Frame.Width) / 2.0f - 40f; nfloat barcodeWidth = (card.Frame.Height - cardNumber.Frame.Height / 5.0f - 40f); var writer = new BarcodeWriter { Format = BarcodeFormat.CODE_128, Options = new ZXing.Common.EncodingOptions () { Width = (int)Math.Round (barcodeWidth), Height = (int)Math.Round (barcodeHeight), Margin = 0 } }; UIImage barCode = writer.Write (_cardNumber); UIImageView barCodeImageView = new UIImageView (barCode); barCodeImageView.SizeToFit (); UIView barcodeContainer = new UIView (); barcodeContainer.BackgroundColor = UIColor.White; barcodeContainer.Frame = new CGRect (0, 0, barCodeImageView.Frame.Width, barCodeImageView.Frame.Height + 10f); barCodeImageView.Frame = new CGRect (0, 5f, barCodeImageView.Frame.Width, barCodeImageView.Frame.Height); barcodeContainer.AddSubview (barCodeImageView); barcodeContainer.Transform = CGAffineTransform.MakeRotation ((nfloat)Math.PI / 2.0f); barcodeContainer.Frame = new CGRect (card.Frame.Left + 30, card.Frame.Top + 15, barcodeContainer.Frame.Width, barcodeContainer.Frame.Height); this.AddSubview (Close); this.AddSubview (card); this.AddSubview (cardNumber); this.AddSubview (barcodeContainer); } } }
33.439252
120
0.704304
[ "MIT" ]
nininea2/unicard_app_base
Kunicardus.Touch/Views/CardForScanView.cs
3,580
C#
using System.Text.Json.Serialization; namespace EcommerceDDD.Application.Customers; public record class CustomerViewModel { public Guid Id { get; set; } public string Email { get; set; } public string Name { get; set; } public string Password { get; set; } public string Token { get; set; } public ValidationResult ValidationResult { get; set; } = new ValidationResult(); [JsonIgnore] public bool LoginSucceeded { get; set; } }
27.294118
84
0.693966
[ "MIT" ]
CurlyBytes/EcommerceDDD
src/EcommerceDDD.Application/Customers/CustomerViewModel.cs
466
C#
using OpenQA.Selenium.Remote; using SKBKontur.SeleniumTesting.Controls; using SKBKontur.SeleniumTesting.Tests.AutoFill; namespace SKBKontur.SeleniumTesting.Tests.RadioGroupTests { [AutoFillControls] public class RadioGroupTestPage : PageBase { public RadioGroupTestPage(RemoteWebDriver webDriver) : base(webDriver) { } public RadioGroup SimpleRadioGroup { get; private set; } } }
25.555556
65
0.686957
[ "MIT" ]
ArkadiyVoronov/react-ui-testing
SeleniumTesting/Tests/RadioGroupTests/RadioGroupTestPage.cs
462
C#
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; namespace NetOffice.ExcelApi { /// <summary> /// DispatchInterface MenuItem /// SupportByVersion Excel, 9,10,11,12,14,15,16 /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] [EntityType(EntityType.IsDispatchInterface)] public class MenuItem : COMObject { #pragma warning disable #region Type Information /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(MenuItem); return _type; } } #endregion #region Ctor /// <param name="factory">current used factory core</param> /// <param name="parentObject">object there has created the proxy</param> /// <param name="proxyShare">proxy share instead if com proxy</param> public MenuItem(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public MenuItem(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public MenuItem(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public MenuItem(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public MenuItem(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public MenuItem(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public MenuItem() : base() { } /// <param name="progId">registered progID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public MenuItem(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public NetOffice.ExcelApi.Application Application { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Application>(this, "Application", NetOffice.ExcelApi.Application.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public NetOffice.ExcelApi.Enums.XlCreator Creator { get { return Factory.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCreator>(this, "Creator"); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16), ProxyResult] public object Parent { get { return Factory.ExecuteReferencePropertyGet(this, "Parent"); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public string Caption { get { return Factory.ExecuteStringPropertyGet(this, "Caption"); } set { Factory.ExecuteValuePropertySet(this, "Caption", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public bool Checked { get { return Factory.ExecuteBoolPropertyGet(this, "Checked"); } set { Factory.ExecuteValuePropertySet(this, "Checked", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public bool Enabled { get { return Factory.ExecuteBoolPropertyGet(this, "Enabled"); } set { Factory.ExecuteValuePropertySet(this, "Enabled", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public Int32 HelpContextID { get { return Factory.ExecuteInt32PropertyGet(this, "HelpContextID"); } set { Factory.ExecuteValuePropertySet(this, "HelpContextID", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public string HelpFile { get { return Factory.ExecuteStringPropertyGet(this, "HelpFile"); } set { Factory.ExecuteValuePropertySet(this, "HelpFile", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public Int32 Index { get { return Factory.ExecuteInt32PropertyGet(this, "Index"); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public string OnAction { get { return Factory.ExecuteStringPropertyGet(this, "OnAction"); } set { Factory.ExecuteValuePropertySet(this, "OnAction", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public string StatusBar { get { return Factory.ExecuteStringPropertyGet(this, "StatusBar"); } set { Factory.ExecuteValuePropertySet(this, "StatusBar", value); } } #endregion #region Methods /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public void Delete() { Factory.ExecuteMethod(this, "Delete"); } #endregion #pragma warning restore } }
25.586667
163
0.648515
[ "MIT" ]
DominikPalo/NetOffice
Source/Excel/DispatchInterfaces/MenuItem.cs
7,678
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Formats.Red.Records.Enums; namespace GameEstate.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class CMaterialBlockMathPower : CMaterialBlock { public CMaterialBlockMathPower(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CMaterialBlockMathPower(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
32.130435
135
0.752368
[ "MIT" ]
smorey2/GameEstate
src/GameEstate.Formats.Red/Formats/Red/W3/RTTIConvert/CMaterialBlockMathPower.cs
739
C#
using System; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; using UnityTest.UnitTestRunner; namespace UnityTest { public partial class UnitTestView { private void UpdateTestInfo(ITestResult result) { FindTestResult(result.Id).Update(result, false); m_FilterSettings.UpdateCounters(m_ResultList.Cast<ITestResult>()); } private UnitTestResult FindTestResult(string resultId) { var idx = m_ResultList.FindIndex(testResult => testResult.Id == resultId); if (idx == -1) { Debug.LogWarning("Id not found for test: " + resultId); return null; } return m_ResultList.ElementAt(idx); } private void RunTests() { var filter = new TestFilter(); var categories = m_FilterSettings.GetSelectedCategories(); if (categories != null && categories.Length > 0) filter.categories = categories; RunTests(filter); } private void RunTests(TestFilter filter) { if (m_Settings.runTestOnANewScene) { if (m_Settings.autoSaveSceneBeforeRun) EditorApplication.SaveScene(); if (!EditorApplication.SaveCurrentSceneIfUserWantsTo()) return; } string currentScene = null; int undoGroup = -1; if (m_Settings.runTestOnANewScene) currentScene = OpenNewScene(); else undoGroup = RegisterUndo(); StartTestRun(filter, new TestRunnerEventListener(UpdateTestInfo)); if (m_Settings.runTestOnANewScene) LoadPreviousScene(currentScene); else PerformUndo(undoGroup); } private string OpenNewScene() { var currentScene = EditorApplication.currentScene; if (m_Settings.runTestOnANewScene) EditorApplication.NewScene(); return currentScene; } private void LoadPreviousScene(string currentScene) { if (!string.IsNullOrEmpty(currentScene)) EditorApplication.OpenScene(currentScene); else EditorApplication.NewScene(); if (Event.current != null) GUIUtility.ExitGUI(); } public void StartTestRun(TestFilter filter, ITestRunnerCallback eventListener) { var callbackList = new TestRunnerCallbackList(); if (eventListener != null) callbackList.Add(eventListener); k_TestEngine.RunTests(filter, callbackList); } private static int RegisterUndo() { return Undo.GetCurrentGroup(); } private static void PerformUndo(int undoGroup) { EditorUtility.DisplayProgressBar("Undo", "Reverting changes to the scene", 0); var undoStartTime = DateTime.Now; Undo.RevertAllDownToGroup(undoGroup); if ((DateTime.Now - undoStartTime).Seconds > 1) Debug.LogWarning("Undo after unit test run took " + (DateTime.Now - undoStartTime).Seconds + " seconds. Consider running unit tests on a new scene for better performance."); EditorUtility.ClearProgressBar(); } public class TestRunnerEventListener : ITestRunnerCallback { private readonly Action<ITestResult> m_UpdateCallback; private int m_TestCount; public TestRunnerEventListener(Action<ITestResult> updateCallback) { m_UpdateCallback = updateCallback; } public void TestStarted(string fullName) { if(m_TestCount < 100) EditorUtility.DisplayProgressBar("Unit Tests Runner", fullName, 1); else EditorUtility.DisplayProgressBar("Unit Tests Runner", "Running unit tests...", 1); } public void TestFinished(ITestResult result) { m_UpdateCallback(result); } public void RunStarted(string suiteName, int testCount) { m_TestCount = testCount; } public void AllScenesFinished() { } public void RunFinished() { EditorUtility.ClearProgressBar(); } public void RunFinishedException(Exception exception) { RunFinished(); } } [MenuItem("Unity Test Tools/Unit Test Runner %#&u")] public static void ShowWindow() { GetWindow(typeof(UnitTestView)).Show(); } } public class TestFilter { public string[] names; public string[] categories; public object[] objects; public static TestFilter Empty = new TestFilter(); } }
31.26875
189
0.575854
[ "MIT" ]
SarenCurrie/the-tower
Assets/UnityTestTools/UnitTesting/Editor/TestRunner/TestRunner.cs
5,003
C#
using Merchant_Galaxy.Common; using Merchant_Galaxy.Interfaces; using System; using System.Text; namespace Merchant_Galaxy.Roman.ExpressionTypes { public class AliasQuestionExpressionType : IExpression { private AliasMapper aliasMap; private IDecimalConverter converter; private ExpressionValidationHelper helper; public AliasQuestionExpressionType(AliasMapper aliasMap, IDecimalConverter converter, ExpressionValidationHelper helper) { this.aliasMap = aliasMap; this.converter = converter; this.helper = helper; } public void Execute(string input) { //Remove question mark input = input.Substring(0, input.Length - 1); StringBuilder sb = new StringBuilder(); string[] parts = input.Split(new string[] { " is " }, StringSplitOptions.RemoveEmptyEntries); string[] words = parts[1].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string word in words) { if (!aliasMap.Exists(word)) { Console.WriteLine(String.Format("Error while processing this input: {0}", input)); return; } sb.Append(aliasMap.GetValueForAlias(word)); } Console.WriteLine(String.Format("{0} is {1}", parts[1], converter.ToDecimal(sb.ToString()))); } public bool Match(string input) { //Remove question mark from the last alias input = input.Substring(0, input.Length - 1); bool isQuestion = (input.StartsWith("how much", StringComparison.OrdinalIgnoreCase)); if (!isQuestion) return false; string[] parts = input.Split(new string[] { " is " }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) return false; string[] words = parts[1].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (words.Length < 1) return false; return helper.AreWordsValidAliases(words); } } }
39.111111
130
0.616477
[ "MIT" ]
AnandDhamane/Merchant-Galaxy
Merchant-Galaxy/Roman/ExpressionTypes/AliasQuestionExpressionType.cs
2,114
C#
//---------------------------------------------------------------------------- // Copyright (C) 2004-2013 by EMGU. All rights reserved. //---------------------------------------------------------------------------- using System; #if NETFX_CORE using Windows.UI; #else using System.Drawing; #endif namespace Emgu.CV { [AttributeUsage(AttributeTargets.Property)] internal sealed class DisplayColorAttribute : Attribute { public DisplayColorAttribute(int blue, int green, int red) { #if NETFX_CORE _displayColor = Color.FromArgb(255, (byte)red, (byte)green, (byte) blue); #else _displayColor = Color.FromArgb(red, green, blue); #endif } private Color _displayColor; public Color DisplayColor { get { return _displayColor; } set { _displayColor = value; } } } }
23.916667
82
0.53194
[ "Apache-2.0" ]
catbox56790/ChromePlusRecord
ScreenRecordPlusChrome/packages/emgucv2.4.10/Emgu.CV/Color/DisplayColorAttribute.cs
861
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 11.05.2021. using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.NotEqual.Complete.Guid.Guid{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Guid; using T_DATA2 =System.Guid; using T_DATA1_U=System.Guid; using T_DATA2_U=System.Guid; //////////////////////////////////////////////////////////////////////////////// //class TestSet_001__fields__01__VV public static class TestSet_001__fields__01__VV { private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2"; private const string c_NameOf__COL_DATA1 ="COL_EMULATE_GUID"; private const string c_NameOf__COL_DATA2 ="COL2_EMULATE_GUID"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA1)] public T_DATA1 COL_DATA1 { get; set; } [Column(c_NameOf__COL_DATA2)] public T_DATA2 COL_DATA2 { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- private static xdb.OleDbConnection Helper__CreateCn() { return LocalCnHelper.CreateCn("user_type_guid=*GUID*"); }//Helper__CreateCn //----------------------------------------------------------------------- [Test] public static void Test_001__less() { using(var cn=Helper__CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1_U c_value1=T_DATA1_U.Parse("D2C26678-562B-44D1-AB96-23D1775E0926"); T_DATA2_U c_value2=T_DATA2_U.Parse("D2C26679-562B-44D1-AB96-23D1775E0926"); System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => (r.COL_DATA1 /*OP{*/ != /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N("t",c_NameOf__COL_DATA1).T(" <> ").N("t",c_NameOf__COL_DATA2).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_001__less //----------------------------------------------------------------------- [Test] public static void Test_002__equal() { using(var cn=Helper__CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1_U c_value1=T_DATA1_U.Parse("D2C26679-562B-44D1-AB96-23D1775E0926"); T_DATA2_U c_value2=T_DATA2_U.Parse("D2C26679-562B-44D1-AB96-23D1775E0926"); System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => (r.COL_DATA1 /*OP{*/ != /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N("t",c_NameOf__COL_DATA1).T(" <> ").N("t",c_NameOf__COL_DATA2).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); }//using db tr.Rollback(); }//using tr }//using cn }//Test_002__equal //----------------------------------------------------------------------- [Test] public static void Test_003__greater() { using(var cn=Helper__CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1_U c_value1=T_DATA1_U.Parse("D2C26679-562B-44D1-AB96-23D1775E0926"); T_DATA2_U c_value2=T_DATA2_U.Parse("D2C26678-562B-44D1-AB96-23D1775E0926"); System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => (r.COL_DATA1 /*OP{*/ != /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N("t",c_NameOf__COL_DATA1).T(" <> ").N("t",c_NameOf__COL_DATA2).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_003__greater //Helper methods -------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA1 valueForColData1, T_DATA2 valueForColData2) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_DATA1 =valueForColData1; newRecord.COL_DATA2 =valueForColData2; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet_001__fields__01__VV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.NotEqual.Complete.Guid.Guid
29.582031
152
0.566618
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/NotEqual/Complete/Guid/Guid/TestSet_001__fields__01__VV.cs
7,575
C#
using System; using System.Globalization; /// <summary> /// SByte.System.IConvertible.ToInt16(IFormatProvider) /// </summary> public class SByteIConvertibleToInt16 { public static int Main() { SByteIConvertibleToInt16 sbyteIConToInt16 = new SByteIConvertibleToInt16(); TestLibrary.TestFramework.BeginTestCase("SByteIConvertibleToInt16"); if (sbyteIConToInt16.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; CultureInfo myculture = new CultureInfo("en-us"); IFormatProvider provider = myculture.NumberFormat; TestLibrary.TestFramework.BeginScenario("PosTest1:The sbyte MaxValue IConvertible To Int16"); try { sbyte sbyteVal = sbyte.MaxValue; IConvertible iConvert = (IConvertible)(sbyteVal); Int16 Int16Val = iConvert.ToInt16(provider); if (Int16Val != 127) { TestLibrary.TestFramework.LogError("001", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; CultureInfo myculture = new CultureInfo("el-GR"); IFormatProvider provider = myculture.NumberFormat; TestLibrary.TestFramework.BeginScenario("PosTest2:The sbyte MinValue IConvertible To Int16"); try { sbyte sbyteVal = sbyte.MinValue; IConvertible iConvert = (IConvertible)(sbyteVal); Int16 Int16Val = iConvert.ToInt16(provider); if (Int16Val != -128) { TestLibrary.TestFramework.LogError("003", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; CultureInfo myculture = new CultureInfo("el-GR"); IFormatProvider provider = myculture.NumberFormat; TestLibrary.TestFramework.BeginScenario("PosTest3:The random sbyte IConvertible To Int16 1"); try { sbyte sbyteVal = (sbyte)(this.GetInt32(0, 128)); IConvertible iConvert = (IConvertible)(sbyteVal); Int16 Int16Val = iConvert.ToInt16(provider); if (Int16Val != (Int16)(sbyteVal)) { TestLibrary.TestFramework.LogError("005", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; CultureInfo myculture = new CultureInfo("en-us"); IFormatProvider provider = myculture.NumberFormat; TestLibrary.TestFramework.BeginScenario("PosTest4:The random sbyte IConvertible To Int16 2"); try { sbyte sbyteVal = (sbyte)(this.GetInt32(0, 129) * (-1)); IConvertible iConvert = (IConvertible)(sbyteVal); Int16 Int16Val = iConvert.ToInt16(provider); if (Int16Val != (Int16)(sbyteVal)) { TestLibrary.TestFramework.LogError("007", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region HelpMethod private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
32.596154
102
0.562439
[ "MIT" ]
CyberSys/coreclr-mono
tests/src/CoreMangLib/cti/system/sbyte/sbyteiconvertibletoint16.cs
5,085
C#