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 System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Bender.Extensions { public static class DictionaryExtensions { /// <summary> /// Finds a value in the dictionary by the given key and concatenates it with the specified string values separating them with the specified separator. /// </summary> /// <typeparam name="TKey"></typeparam> /// <param name="dictionary">Should implements <see> /// <cref>IDictionary</cref> /// </see> /// </param> /// <param name="key"></param> /// <param name="values"></param> /// <param name="separator"></param> /// <param name="equalityComparer"></param> public static IDictionary<TKey, string> Extend<TKey>( this IDictionary<TKey, string> dictionary, TKey key, char separator, IEnumerable<string> values, IEqualityComparer<string>? equalityComparer = null ) { string? existingValue; dictionary.TryGetValue(key, out existingValue); dictionary[key] = (existingValue ?? string.Empty) .JoinDistinct( separator, values, equalityComparer, StringSplitOptions.RemoveEmptyEntries); return dictionary; } public static IDictionary<string, TValue> ToCaseInsensitiveDictionary<TValue>(this IReadOnlyDictionary<string, TValue> dictionary) { var destination = new Dictionary<string, TValue>(StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair<string, TValue> de in dictionary) { destination[de.Key] = de.Value; } return destination; } public static IReadOnlyDictionary<TKey, TValue> ToReadOnlyDictionary<TKey, TValue>(this IDictionary<TKey, TValue> dictionary) where TKey: notnull { return new ReadOnlyDictionary<TKey, TValue>(dictionary); } } }
36.866667
160
0.562839
[ "MIT" ]
ValentinLevitov/bender
Bender/Extensions/DictionaryExtensions.cs
2,155
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Serilog; using Serilog.Events; using Serilog.Sinks.SystemConsole.Themes; namespace AspNetCoreCertificateAuth { public class Program { public static int Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Override("Microsoft", LogEventLevel.Verbose) .MinimumLevel.Verbose() .Enrich.FromLogContext() .WriteTo.Console() .CreateLogger(); try { Log.Information("Starting web host"); CreateHostBuilder(args).Build().Run(); return 0; } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); return 1; } finally { Log.CloseAndFlush(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>() .UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration .ReadFrom.Configuration(hostingContext.Configuration) .MinimumLevel.Override("Microsoft", LogEventLevel.Verbose) .MinimumLevel.Verbose() .Enrich.FromLogContext() .WriteTo.File("../_clientLogs.txt") .WriteTo.Console(theme: AnsiConsoleTheme.Code) ); }); } }
33.542373
93
0.532592
[ "MIT" ]
JTOne123/AspNetCoreCertificates
examplesUsingCertificateAuthentication/AspNetCoreChained/AspNetCoreCertificateAuth/Program.cs
1,979
C#
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Test.CSharp9.ReadabilityRules { using StyleCop.Analyzers.Test.CSharp8.ReadabilityRules; public class SA1111CSharp9UnitTests : SA1111CSharp8UnitTests { } }
30.5
91
0.775956
[ "MIT" ]
AraHaan/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp9/ReadabilityRules/SA1111CSharp9UnitTests.cs
368
C#
using UnityEngine; using UnityEditor; [CustomEditor(typeof(SGT_GasGiant))] public class SGT_Inspector_GasGiant : SGT_Inspector<SGT_GasGiant> { public override void OnInspector() { SGT_EditorGUI.Separator(); SGT_EditorGUI.BeginGroup("Gas Giant"); { Target.GasGiantLightSource = SGT_EditorGUI.ObjectField("Light Source", "The GameObject that represents the light source for this gas giant.", Target.GasGiantLightSource, true); Target.GasGiantObserver = SGT_EditorGUI.ObjectField("Observer", "The camera that is rendering this gas giant.", Target.GasGiantObserver, true); Target.GasGiantLutSize = (SGT_SquareSize)SGT_EditorGUI.EnumField("LUT Size", "The texture look up table resolution. Use a higher value for smoother results, at the cost of GPU memory and texture sampling speed.", Target.GasGiantLutSize); Target.GasGiantMesh = SGT_EditorGUI.ObjectField("Mesh", "This should be an inside-out sphere with a radius of 1.", Target.GasGiantMesh, true); Target.GasGiantRenderQueue = SGT_EditorGUI.IntField("Render Queue", "The render queue used by the gas giant mesh.", Target.GasGiantRenderQueue); } SGT_EditorGUI.EndGroup(); SGT_EditorGUI.Separator(); SGT_EditorGUI.BeginGroup("Atmosphere"); { Target.AtmosphereRadius = SGT_EditorGUI.FloatField("Equatorial Radius", "This is the gas giant's radius around the equator.", Target.AtmosphereRadius); Target.AtmosphereOblateness = SGT_EditorGUI.FloatField("Oblateness", "This specifies how oblate/flat/round the gas giant is. A higher value means the polar radius will be lower than the equatorial radius. Large gas giants that spin are often quite oblate.", Target.AtmosphereOblateness, 0.0f, 1.0f); Target.AtmosphereDensity = SGT_EditorGUI.FloatField("Density", "This specifies how dense the gas giant's atmosphere is. A higher value means the atmosphere will be very hard to see though.", Target.AtmosphereDensity, 1.0f, 10.0f); Target.AtmosphereDensityFalloff = SGT_EditorGUI.FloatField("Density Falloff", "This specifies how much the gas giant's atmospheric density varies with altitude. A higher value means the upper atmosphere will be very thin compared to the centre, meaning the edges will be more transaprent.", Target.AtmosphereDensityFalloff, 1.0f, 10.0f); Target.AtmosphereLighting = SGT_EditorGUI.Field("Lighting", "This is the night-day brightness gradient. You can also give the day side a colour, to simulate starlght.", Target.AtmosphereLighting); Target.AtmosphereTwilightColour = SGT_EditorGUI.Field("Twilight Colour", "This is multiplied with the Lighting gradient. It allows you to easily set twilight/sunset colours without modifiying the lighting.", Target.AtmosphereTwilightColour); Target.AtmosphereLimbColour = SGT_EditorGUI.Field("Limb Colour", "This allows you to colour the edges of the gas giant, useful for simulating limb darkening.", Target.AtmosphereLimbColour); SGT_EditorGUI.Separator(); SGT_EditorGUI.BeginGroup("Texture"); { Target.AtmosphereTextureDay = SGT_EditorGUI.ObjectField("Day", "This is the gas giant's daytime surface texture.", Target.AtmosphereTextureDay, true); Target.AtmosphereTextureNight = SGT_EditorGUI.ObjectField("Night", "[Optional] This is the gas giant's nighttime surface texture.", Target.AtmosphereTextureNight); } SGT_EditorGUI.EndGroup(); } SGT_EditorGUI.EndGroup(); SGT_EditorGUI.Separator(); Target.Shadow = SGT_EditorGUI.BeginToggleGroup("Shadow", "Does this gas giant recieve shadow?", Target.Shadow); { SGT_EditorGUI.BeginGroup("Caster"); { Target.ShadowCasterType = (SGT_ShadowOccluder)SGT_EditorGUI.EnumField("Type", "Specify the type of object that is casting a shadow on this gas giant.", Target.ShadowCasterType); switch (Target.ShadowCasterType) { case SGT_ShadowOccluder.Ring: { Target.ShadowCasterAutoUpdate = SGT_EditorGUI.BoolField("Auto Update", null, Target.ShadowCasterAutoUpdate); SGT_EditorGUI.BeginFrozen(Target.ShadowCasterAutoUpdate == false); { Target.ShadowCasterRadius = SGT_EditorGUI.FloatField("Radius", "The inner radius of the ring.", Target.ShadowCasterRadius); Target.ShadowCasterWidth = SGT_EditorGUI.FloatField("Width", "The width of the ring.", Target.ShadowCasterWidth); } SGT_EditorGUI.EndFrozen(); } break; case SGT_ShadowOccluder.Planet: { Target.ShadowCasterGameObject = SGT_EditorGUI.ObjectField("Game Object", "The GameObject representing the planet that is casting a shadow on this gas giant.", Target.ShadowCasterGameObject, true); Target.ShadowCasterAutoUpdate = SGT_EditorGUI.BoolField("Auto Update", null, Target.ShadowCasterAutoUpdate); SGT_EditorGUI.BeginFrozen(Target.ShadowCasterAutoUpdate == false); { Target.ShadowCasterRadius = SGT_EditorGUI.FloatField("Radius", "The radius of the shadow caster.", Target.ShadowCasterRadius); } SGT_EditorGUI.EndFrozen(); Target.ShadowCasterWidth = SGT_EditorGUI.FloatField("Width", "The width of penumbra (soft shadow) region.", Target.ShadowCasterWidth); } break; } } SGT_EditorGUI.EndGroup(); SGT_EditorGUI.Separator(); Target.ShadowTexture = SGT_EditorGUI.ObjectField("Texture", "The shadow texture. Left = inner shadow. Right = outer shadow.", Target.ShadowTexture, true); } SGT_EditorGUI.EndToggleGroup(); SGT_EditorGUI.Separator(); } }
59.311828
340
0.750363
[ "EPL-1.0" ]
Vrixyz/Planet-Factory
Visualizer/Assets/SpaceGraphicsToolkit/Required/Scripts/Editor/SGT_Inspector_GasGiant.cs
5,516
C#
// * ************************************************************************** // * Copyright (c) McCreary, Veselka, Bragg & Allen, P.C. // * This source code is subject to terms and conditions of the MIT License. // * A copy of the license can be found in the License.txt file // * at the root of this distribution. // * By using this source code in any fashion, you are agreeing to be bound by // * the terms of the MIT License. // * You must not remove this notice from this software. // * ************************************************************************** using System; namespace FluentWebControls.Extensions { public static class DataColumnExtensions { public static DataColumn<T> AlignCenter<T>(this DataColumn<T> dataColumn) { dataColumn.Align = AlignAttribute.Center; return dataColumn; } public static DataColumn<T> AlignHeaderLeft<T>(this DataColumn<T> dataColumn) { dataColumn.HeaderAlign = AlignAttribute.Left; return dataColumn; } public static DataColumn<T> AlignHeaderRight<T>(this DataColumn<T> dataColumn) { dataColumn.HeaderAlign = AlignAttribute.Right; return dataColumn; } public static DataColumn<T> AlignRight<T>(this DataColumn<T> dataColumn) { dataColumn.Align = AlignAttribute.Right; return dataColumn; } public static DataColumn<T> AsCheckBox<T>(this DataColumn<T> dataColumn, Func<T, string> forId) { dataColumn.ColumnTextType = ColumnTextType.CheckBox; dataColumn.GetItemId = forId; return dataColumn; } public static DataColumn<T> AsCheckBox<T>(this DataColumn<T> dataColumn, string forId) { dataColumn.ColumnTextType = ColumnTextType.CheckBox; dataColumn.InputTextId = forId; return dataColumn; } public static DataColumn<T> AsHidden<T>(this DataColumn<T> dataColumn, Func<T, string> forId) { dataColumn.ColumnTextType = ColumnTextType.Hidden; dataColumn.GetItemId = forId; return dataColumn; } public static DataColumn<T> AsHidden<T>(this DataColumn<T> dataColumn, string forId) { dataColumn.ColumnTextType = ColumnTextType.Hidden; dataColumn.InputTextId = forId; return dataColumn; } public static DataColumn<T> AsSpan<T>(this DataColumn<T> dataColumn, Func<T, string> forId) { dataColumn.ColumnTextType = ColumnTextType.Span; dataColumn.GetItemId = forId; return dataColumn; } public static DataColumn<T> AsTextBox<T>(this DataColumn<T> dataColumn, Func<T, string> forId) { dataColumn.ColumnTextType = ColumnTextType.TextBox; dataColumn.GetItemId = forId; return dataColumn; } public static DataColumn<T> AsTextBox<T>(this DataColumn<T> dataColumn, string forId) { dataColumn.ColumnTextType = ColumnTextType.TextBox; dataColumn.InputTextId = forId; return dataColumn; } public static DataColumn<T> WithCssClass<T>(this DataColumn<T> dataColumn, string cssClass) { dataColumn.CssClass = cssClass; return dataColumn; } public static DataColumn<T> WithHeader<T>(this DataColumn<T> dataColumn, string header) { dataColumn.HeaderText = header; return dataColumn; } public static DataColumn<T> WithHeaderCssClass<T>(this DataColumn<T> dataColumn, string cssClass) { dataColumn.HeaderCssClass = cssClass; return dataColumn; } public static DataColumn<T> WithInputCssClass<T>(this DataColumn<T> dataColumn, string inputCssClass) { dataColumn.InputCssClass = inputCssClass; return dataColumn; } public static DataColumn<T> WithName<T>(this DataColumn<T> dataColumn, string name) { dataColumn.InputTextName = name; return dataColumn; } public static DataColumn<T> WithPrefix<T>(this DataColumn<T> dataColumn, string prefix) { dataColumn.Prefix = prefix; return dataColumn; } } }
29.896825
103
0.702947
[ "MIT" ]
mvbalaw/FluentWebControls
src/FluentWebControls/Extensions/DataColumnExtensions.cs
3,767
C#
// Copyright (c) MOSA Project. Licensed under the New BSD License. using Mosa.Compiler.Framework.Analysis; using Mosa.Compiler.Framework.IR; using Mosa.Compiler.Framework.Trace; using System; using System.Collections.Generic; using System.Diagnostics; namespace Mosa.Compiler.Framework.Stages { /// <summary> /// Sparse Conditional Constant Propagation Stage /// </summary> public class SparseConditionalConstantPropagationStage : BaseMethodCompilerStage { protected TraceLog trace; private readonly Counter ConstantCount = new Counter("SparseConditionalConstantPropagationStage.ConstantVariables"); private Counter ConditionalConstantPropagationCount = new Counter("SparseConditionalConstantPropagationStage.ConstantPropagations"); private readonly Counter DeadBlockCount = new Counter("SparseConditionalConstantPropagationStage.DeadBlocks"); private Counter InstructionsRemovedCount = new Counter("SparseConditionalConstantPropagationStage.IRInstructionRemoved"); protected bool changed = false; protected override void Initialize() { Register(ConstantCount); Register(ConditionalConstantPropagationCount); Register(DeadBlockCount); Register(InstructionsRemovedCount); } protected override void Setup() { trace = CreateTraceLog(); changed = false; } protected override void Run() { var analysis = new SparseConditionalConstantPropagation(BasicBlocks, this); var deadBlocks = analysis.GetDeadBlocked(); var constants = analysis.GetIntegerConstants(); RemoveDeadBlocks(deadBlocks); ReplaceVirtualRegistersWithConstants(constants); ConstantCount.Set(constants.Count); DeadBlockCount.Set(deadBlocks.Count); } protected override void Finish() { trace = null; } protected void ReplaceVirtualRegistersWithConstants(List<Tuple<Operand, ulong>> constantVirtualRegisters) { foreach (var value in constantVirtualRegisters) { ReplaceVirtualRegisterWithConstant(value.Item1, value.Item2); } } protected void ReplaceVirtualRegisterWithConstant(Operand target, ulong value) { trace?.Log($"{target} = {value.ToString()} Uses: {target.Uses.Count}"); if (target.Definitions.Count == 0) return; Debug.Assert(target.Definitions.Count == 1); if (target.Uses.Count != 0) { var constant = CreateConstant(target.Type, value); // for each statement T that uses operand, substituted c in statement T foreach (var node in target.Uses.ToArray()) { Debug.Assert(node.Instruction != IRInstruction.AddressOf); for (int i = 0; i < node.OperandCount; i++) { var operand = node.GetOperand(i); if (operand != target) continue; trace?.Log("*** ConditionalConstantPropagation"); trace?.Log($"BEFORE:\t{node}"); node.SetOperand(i, constant); ConditionalConstantPropagationCount++; trace?.Log($"AFTER: \t{node}"); changed = true; } } } Debug.Assert(target.Uses.Count == 0); if (target.Definitions.Count == 0) return; var defNode = target.Definitions[0]; trace?.Log($"REMOVED:\t{defNode}"); defNode.SetInstruction(IRInstruction.Nop); InstructionsRemovedCount++; } protected void RemoveDeadBlocks(List<BasicBlock> deadBlocks) { foreach (var block in deadBlocks) { RemoveBranchesToDeadBlocks(block); } //foreach (var block in deadBlocks) //{ // RemoveDeadBlock(block); //} } //protected void RemoveDeadBlock(BasicBlock deadBlock) //{ // trace?.Log("*** RemoveBlock: " + deadBlock); // var nextBlocks = deadBlock.NextBlocks.ToArray(); // EmptyBlockOfAllInstructions(deadBlock); // RemoveBlockFromPhiInstructions(deadBlock, nextBlocks); // Debug.Assert(deadBlock.NextBlocks.Count == 0); // Debug.Assert(deadBlock.PreviousBlocks.Count == 0); //} protected void RemoveBranchesToDeadBlocks(BasicBlock deadBlock) { foreach (var previous in deadBlock.PreviousBlocks.ToArray()) { // unable to handle more than two branch blocks // and if only one branch, then this block is dead as well if (previous.NextBlocks.Count != 2) return; var otherBlock = previous.NextBlocks[0] == deadBlock ? previous.NextBlocks[1] : previous.NextBlocks[0]; for (var node = previous.Last.Previous; !node.IsBlockStartInstruction; node = node.Previous) { if (node.IsEmptyOrNop) continue; if (node.BranchTargetsCount == 0) continue; if (node.Instruction == IRInstruction.CompareIntBranch32 || node.Instruction == IRInstruction.CompareIntBranch64) { trace?.Log("*** RemoveBranchesToDeadBlocks"); trace?.Log($"REMOVED:\t{node}"); node.SetInstruction(IRInstruction.Nop); InstructionsRemovedCount++; } else if (node.Instruction == IRInstruction.Jmp) { trace?.Log("*** RemoveBranchesToDeadBlocks"); trace?.Log($"BEFORE:\t{node}"); node.UpdateBranchTarget(0, otherBlock); trace?.Log($"AFTER: \t{node}"); } } } CheckAndClearEmptyBlock(deadBlock); } private void CheckAndClearEmptyBlock(BasicBlock block) { if (block.PreviousBlocks.Count != 0 || block.IsHeadBlock) return; trace?.Log($"*** RemoveBlock: {block}"); var nextBlocks = block.NextBlocks.ToArray(); EmptyBlockOfAllInstructions(block); _RemoveBlockFromPhiInstructions(block, nextBlocks); Debug.Assert(block.NextBlocks.Count == 0); Debug.Assert(block.PreviousBlocks.Count == 0); foreach (var next in nextBlocks) { CheckAndClearEmptyBlock(next); } } protected void _RemoveBlockFromPhiInstructions(BasicBlock removedBlock, BasicBlock[] nextBlocks) { foreach (var next in nextBlocks) { for (var node = next.AfterFirst; !node.IsBlockEndInstruction; node = node.Next) { if (node.IsEmptyOrNop) continue; if (IsSimpleIRMoveInstruction(node.Instruction)) continue; // sometimes PHI are converted to moves if (node.Instruction != IRInstruction.Phi) break; var sourceBlocks = node.PhiBlocks; int index = sourceBlocks.IndexOf(removedBlock); if (index < 0) continue; sourceBlocks.RemoveAt(index); for (int i = index; i < node.OperandCount - 1; i++) { node.SetOperand(i, node.GetOperand(i + 1)); } node.SetOperand(node.OperandCount - 1, null); node.OperandCount--; } } Debug.Assert(removedBlock.NextBlocks.Count == 0); } } }
26.681818
134
0.699241
[ "BSD-3-Clause" ]
marcelocaetano/MOSA-Project
Source/Mosa.Compiler.Framework/Stages/SparseConditionalConstantPropagationStage.cs
6,459
C#
namespace Das.Marketo.RestApiClient.Configuration { public class MarketoConfiguration { public virtual string ApiBaseUrl { get; set; } public virtual string ApiClientId { get; set; } public virtual string ApiClientSecret { get; set; } public virtual RegisterInterestProgramConfiguration RegisterInterestProgramConfiguration { get; set; } public virtual string ApiIdentityBaseUrl { get; set; } public virtual int ApiRetryCount { get; set; } public virtual int ApiRetryInitialBackOffSecs { get; set; } public virtual int ChunkSizeKB { get; set; } public virtual string ApiRestPrefix => "/rest/v1"; public virtual string ApiBulkImportPrefix => "/bulk/v1"; } public class RegisterInterestProgramConfiguration { public virtual string ProgramName { get; set; } public virtual string Source { get; set; } public virtual string LookupField { get; set; } public virtual string CitizenReason { get; set; } public virtual string EmployerReason { get; set; } } }
39.357143
110
0.676951
[ "MIT" ]
SkillsFundingAgency/das-campaign-functions
src/Das.Marketo.RestApiClient/Configuration/MarketoConfiguration.cs
1,104
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Newtonsoft.Json; using UniQode.Common.Extensions; using UniQode.Contracts.Services; using UniQode.Entities.Data; using UniQode.Entities.Enums; using UniQode.Models.Admin; using UniQode.Models.Shared; using UniQode.Web.Attributes; using UniQode.Web.Extensions; namespace UniQode.Web.Controllers { [Authorize] [RoutePrefix("mottos")] public class MottoController : Controller { public MottoController(IMultiTenantService<Motto, Guid> mottoService, IMultiTenantService<Employee, Guid> employeeService) { _mottoService = mottoService; _employeeService = employeeService; } private readonly IMultiTenantService<Motto, Guid> _mottoService; private readonly IMultiTenantService<Employee, Guid> _employeeService; /// <summary> /// Used in admin view, no caching /// </summary> /// <returns></returns> [ChildActionOnly] [HttpGet] public ActionResult List(string state = null) { var dtos = _mottoService.Secondary.List(true); var models = dtos.Select(MottoModel.FromDto).ToList(); MottoModel parsedModel = null; var parsedState = State.None; if (!string.IsNullOrEmpty(state) && !Enum.TryParse(state, out parsedState)) { parsedModel = JsonConvert.DeserializeObject<MottoModel>(state); } if (parsedModel != null && models.FirstOrDefault(m => m.Id == parsedModel.Id) != null) { for (var i = 0; i < models.Count; ++i) { if (models[i].Id == parsedModel.Id) { models[i] = parsedModel; } } } else if (parsedModel != null) { models.Add(parsedModel); } switch (parsedState) { case State.Adding: models.Add(new MottoModel { Id = Guid.NewGuid(), State = parsedState }); break; default: foreach (var model in models) { this.ValidateViewModel(model); } break; } return PartialView("Partials/Admin/_Mottos", models); } [HttpPost] public ActionResult Act(MottoModel model) { if (!ModelState.IsValid) { if (model.State == State.None) { switch (model.Action) { case AdminAction.Preview: case AdminAction.Publish: case AdminAction.Update: case AdminAction.Save: model.State = State.Updating; break; case AdminAction.Add: model.State = State.Adding; break; case AdminAction.Delete: model.State = State.Deleting; break; } } if(model.Action != AdminAction.Delete) return RedirectToAction("Index", "Admin", new { motto = JsonConvert.SerializeObject(model) }); } switch (model.Action) { case AdminAction.Delete: try { _mottoService.Primary.Delete(model.Id, User.Identity); } catch { // suppress since it could be missing in the primary schema (if not published yet) } _mottoService.Secondary.Delete(model.Id, User.Identity); break; case AdminAction.Save: _mottoService.Secondary.Update(model.ToDto(), User.Identity); break; case AdminAction.Preview: _mottoService.Secondary.Update(model.ToDto(), User.Identity); return RedirectToAction("Index", "Home", new { Preview = true }); case AdminAction.Publish: _mottoService.Primary.Update(model.ToDto(), User.Identity); _mottoService.Secondary.Update(model.ToDto(), User.Identity); return RedirectToAction("Index", "Home"); } return RedirectToAction("Index", "Admin"); } [AllowAnonymous] [ChildActionOnly] [HttpGet] public ActionResult Public(bool preview = false) { ICollection<Motto> mottoDtos = null; ICollection<Employee> employeeDtos = null; if (preview) { mottoDtos = _mottoService.Secondary.List(true); employeeDtos = _employeeService.Secondary.List(true); } else { mottoDtos = _mottoService.Primary.List(); employeeDtos = _employeeService.Primary.List(); } var mottoModels = mottoDtos.Select(MottoModel.FromDto).ToList(); var employeeModels = employeeDtos.Select(EmployeeModel.FromDto).Where(e => !string.IsNullOrWhiteSpace(e.ProfilePicture.OriginalUrl)).ToList(); employeeModels.Shuffle(); var model = Tuple.Create(mottoModels, employeeModels); return PartialView("Partials/_Mottos", model); } } }
34.95858
154
0.499661
[ "MIT" ]
uniQodeAB/uniqode-web
src/UniQode.Web/Controllers/MottoController.cs
5,910
C#
using System; using System.Collections; using LibSterileSSH.SecureShell; /* class LibSterileSSH.SshBase: This class is based on SharpSSH-1.1.1.13.src\SharpSSH\SshBase.cs . */ /* * SshBase.cs * * Copyright (c) 2006 Tamir Gal, http://www.tamirgal.com, All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. 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. * * 3. The names of the authors may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 AUTHOR * *OR ANY CONTRIBUTORS TO THIS SOFTWARE 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 LibSterileSSH { /// <summary> /// A wrapper class for JSch's SSH channel /// </summary> public abstract class SshBase { protected string m_host; protected string m_user; protected string m_pass; protected SshClient m_jsch; protected Session m_session; protected AChannel m_channel; /// <summary> /// Default TCP port of SSH protocol /// </summary> private static int SSH_TCP_PORT = 22; /// <summary> /// Constructs a new SSH instance /// </summary> /// <param name="sftpHost">The remote SSH host</param> /// <param name="user">The login username</param> /// <param name="password">The login password</param> public SshBase(string sftpHost, string user, string password) { this.m_host = sftpHost; this.m_user = user; this.Password = password; m_jsch = new SshClient(); } /// <summary> /// Constructs a new SSH instance /// </summary> /// <param name="sftpHost">The remote SSH host</param> /// <param name="user">The login username</param> public SshBase(string sftpHost, string user) : this(sftpHost, user, null) { } /// <summary> /// Adds identity file for publickey user authentication /// </summary> /// <param name="privateKeyFile">The path to the private key file</param> public virtual void AddIdentityFile(string privateKeyFile) { m_jsch.addIdentity(privateKeyFile); } /// <summary> /// Adds identity file for publickey user authentication /// </summary> /// <param name="privateKeyFile">The path to the private key file</param> /// <param name="passphrase">A passphrase for decrypting the private key file</param> public virtual void AddIdentityFile(string privateKeyFile, string passphrase) { m_jsch.addIdentity(privateKeyFile, passphrase); } protected abstract string ChannelType { get; } /// <summary> /// Connect to remote SSH server /// </summary> public virtual void Connect() { this.Connect(SSH_TCP_PORT); } /// <summary> /// Connect to remote SSH server /// </summary> /// <param name="tcpPort">The destination TCP port for this connection</param> public virtual void Connect(int tcpPort) { this.ConnectSession(tcpPort); this.ConnectChannel(); } protected virtual void ConnectSession(int tcpPort) { m_session = m_jsch.getSession(m_user, m_host, tcpPort); if (Password != null) m_session.setUserInfo(new KeyboardInteractiveUserInfo(Password)); Hashtable config = new Hashtable(); config.Add("StrictHostKeyChecking", "no"); m_session.setConfig(config); m_session.connect(); } protected virtual void ConnectChannel() { m_channel = m_session.openChannel(ChannelType); this.OnChannelReceived(); m_channel.connect(); this.OnConnected(); } protected virtual void OnConnected() { } protected virtual void OnChannelReceived() { } /// <summary> /// Closes the SSH subsystem /// </summary> public virtual void Close() { if (m_channel != null) { m_channel.disconnect(); m_channel = null; } if (m_session != null) { m_session.disconnect(); m_session = null; } } /// <summary> /// Return true if the SSH subsystem is connected /// </summary> public virtual bool Connected { get { if (m_session != null) return m_session.isConnected(); return false; } } /// <summary> /// Gets the Cipher algorithm name used in this SSH connection. /// </summary> public string Cipher { get { CheckConnected(); return m_session.getCipher(); } } /// <summary> /// Gets the MAC algorithm name used in this SSH connection. /// </summary> public string Mac { get { CheckConnected(); return m_session.getMac(); } } /// <summary> /// Gets the server SSH version string. /// </summary> public string ServerVersion { get { CheckConnected(); return m_session.getServerVersion(); } } /// <summary> /// Gets the client SSH version string. /// </summary> public string ClientVersion { get { CheckConnected(); return m_session.getClientVersion(); } } public string Host { get { CheckConnected(); return m_session.getHost(); } } public HostKey HostKey { get { CheckConnected(); return m_session.getHostKey(); } } public int Port { get { CheckConnected(); return m_session.getPort(); } } /// <summary> /// The password string of the SSH subsystem /// </summary> public string Password { get { return m_pass; } set { m_pass = value; } } public string Username { get { return m_user; } } public static Version Version { get { System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(typeof(LibSterileSSH.SshBase)); return asm.GetName().Version; } } private void CheckConnected() { if (!Connected) { throw new Exception("SSH session is not connected."); } } /// <summary> /// For password and KI auth modes /// </summary> protected class KeyboardInteractiveUserInfo : IUserInfo, IUIKeyboardInteractive { string _password; public KeyboardInteractiveUserInfo(string password) { _password = password; } #region UIKeyboardInteractive Members public string[] promptKeyboardInteractive(string destination, string name, string instruction, string[] prompt, bool[] echo) { return new string[] { _password }; } #endregion #region UserInfo Members public bool promptYesNo(string message) { return true; } public bool promptPassword(string message) { return true; } public string getPassword() { return _password; } public bool promptPassphrase(string message) { return true; } public string getPassphrase() { return null; } public void showMessage(string message) { } #endregion } } }
23.085714
128
0.641955
[ "BSD-3-Clause" ]
mickey-cube1/SterileSSH
SterileSSH/LibSterileSSH/SshBase.cs
8,080
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using UnityEngine; using UnityEngine.Events; using System.Collections.Concurrent; using System.Text; #if UNITY_WSA && !UNITY_EDITOR using global::Windows.UI.Core; using global::Windows.Foundation; using global::Windows.Media.Core; using global::Windows.Media.Capture; using global::Windows.ApplicationModel.Core; #endif namespace Microsoft.MixedReality.WebRTC.Unity { /// <summary> /// Enumeration of the different types of ICE servers. /// </summary> public enum IceType { /// <summary> /// Indicates there is no ICE information /// </summary> /// <remarks> /// Under normal use, this should not be used /// </remarks> None = 0, /// <summary> /// Indicates ICE information is of type STUN /// </summary> /// <remarks> /// https://en.wikipedia.org/wiki/STUN /// </remarks> Stun, /// <summary> /// Indicates ICE information is of type TURN /// </summary> /// <remarks> /// https://en.wikipedia.org/wiki/Traversal_Using_Relays_around_NAT /// </remarks> Turn } /// <summary> /// ICE server as a serializable data structure for the Unity inspector. /// </summary> [Serializable] public struct ConfigurableIceServer { /// <summary> /// The type of ICE server. /// </summary> [Tooltip("Type of ICE server")] public IceType Type; /// <summary> /// The unqualified URI of the server. /// </summary> /// <remarks> /// The URI must not have any <c>stun:</c> or <c>turn:</c> prefix. /// </remarks> [Tooltip("ICE server URI, without any stun: or turn: prefix.")] public string Uri; /// <summary> /// Convert the server to the representation the underlying implementation use. /// </summary> /// <returns>The stringified server information.</returns> public override string ToString() { return string.Format("{0}:{1}", Type.ToString().ToLowerInvariant(), Uri); } } /// <summary> /// A <a href="https://docs.unity3d.com/ScriptReference/Events.UnityEvent.html">UnityEvent</a> that represents a WebRTC error event. /// </summary> [Serializable] public class WebRTCErrorEvent : UnityEvent<string> { } /// <summary> /// Exception thrown when an invalid transceiver media kind was detected, generally when trying to pair a /// transceiver of one media kind with a media line of a different media kind. /// </summary> public class InvalidTransceiverMediaKindException : Exception { /// <inheritdoc/> public InvalidTransceiverMediaKindException() : base("Invalid transceiver kind.") { } /// <inheritdoc/> public InvalidTransceiverMediaKindException(string message) : base(message) { } /// <inheritdoc/> public InvalidTransceiverMediaKindException(string message, Exception inner) : base(message, inner) { } } /// <summary> /// Media line abstraction for a peer connection. /// /// This container binds together a sender component (<see cref="MediaSender"/>) and/or a receiver component /// (<see cref="MediaReceiver"/>) on one side, with a transceiver on the other side. The media line is a /// declarative representation of this association, which is then turned into a binding by the implementation /// during an SDP negotiation. This forms the core of the algorithm allowing automatic transceiver pairing /// between the two peers based on the declaration of intent of the user. /// /// Assigning Unity components to the <see cref="Sender"/> and <see cref="Receiver"/> fields serves /// as an indication of the user intent to send and/or receive media through the transceiver, and is /// used during the SDP exchange to derive the <see xref="WebRTC.Transceiver.Direction"/> to negotiate. /// After the SDP negotiation is completed, the <see cref="Transceiver"/> property refers to the transceiver /// associated with this media line, and which the sender and receiver will use. /// /// Users typically interact with this class through the peer connection transceiver collection in the Unity /// inspector window, though direct manipulation via code is also possible. /// </summary> [Serializable] public class MediaLine { /// <summary> /// Backing field to serialize the <see cref="Kind"/> property. /// </summary> /// <seealso cref="Kind"/> [SerializeField] private MediaKind _kind; /// <summary> /// Kind of media of the media line and its attached transceiver. /// /// This is assiged when the media line is created with <see cref="PeerConnection.AddMediaLine(MediaKind)"/> /// and is immutable for the lifetime of the peer connection. /// </summary> public MediaKind Kind => _kind; /// <summary> /// Backing field to serialize the <see cref="Sender"/> property. /// </summary> /// <seealso cref="Sender"/> [SerializeField] private MediaSender _sender; /// <summary> /// Media sender producing the media to send through the transceiver attached to this media line. /// This must be an instance of a class derived from <see cref="AudioSender"/> or <see cref="VideoSender"/> /// depending on whether <see cref="Kind"/> is <see xref="Microsoft.MixedReality.WebRTC.MediaKind.Audio"/> /// or <see xref="Microsoft.MixedReality.WebRTC.MediaKind.Video"/>, respectively. /// /// If this is non-<c>null</c> then the peer connection will negotiate sending some media, otherwise /// it will signal the remote peer that it does not wish to send (receive-only or inactive). /// /// If <see cref="Transceiver"/> is valid, that is a first session negotiation has already been completed, /// then changing this value raises a <see xref="WebRTC.PeerConnection.RenegotiationNeeded"/> event on the /// peer connection of <see cref="Transceiver"/>. /// </summary> public MediaSender Sender { get { return _sender; } set { if (_sender != value) { _sender = value; UpdateTransceiverDesiredDirection(); } } } /// <summary> /// Backing field to serialize the <see cref="Receiver"/> property. /// </summary> /// <seealso cref="Receiver"/> [SerializeField] private MediaReceiver _receiver; /// <summary> /// Media receiver consuming the media received through the transceiver attached to this media line. /// This must be an instance of a class derived from <see cref="AudioReceiver"/> or <see cref="VideoReceiver"/> /// depending on whether <see cref="Kind"/> is <see xref="Microsoft.MixedReality.WebRTC.MediaKind.Audio"/> /// or <see xref="Microsoft.MixedReality.WebRTC.MediaKind.Video"/>, respectively. /// /// If this is non-<c>null</c> then the peer connection will negotiate receiving some media, otherwise /// it will signal the remote peer that it does not wish to receive (send-only or inactive). /// /// If <see cref="Transceiver"/> is valid, that is a first session negotiation has already been conducted, /// then changing this value raises a <see xref="WebRTC.PeerConnection.RenegotiationNeeded"/> event on the /// peer connection of <see cref="Transceiver"/>. /// </summary> public MediaReceiver Receiver { get { return _receiver; } set { if (_receiver != value) { _receiver = value; UpdateTransceiverDesiredDirection(); } } } /// <summary> /// Transceiver attached with this media line. /// /// On the offering peer this changes during <see cref="PeerConnection.StartConnection"/>, while this is updated by /// <see cref="PeerConnection.HandleConnectionMessageAsync(string, string)"/> when receiving an offer on the answering peer. /// /// Because transceivers cannot be destroyed, once this property is assigned a non-<c>null</c> value it keeps that /// value until the peer connection owning the media line is closed. /// </summary> public Transceiver Transceiver { get; private set; } /// <summary> /// Sender actually attached during <see cref="PeerConnection.HandleConnectionMessageAsync(string, string)"/>. /// This is different from <see cref="Sender"/> until a negotiation is achieved. /// </summary> [NonSerialized] private MediaSender _attachedSender; /// <summary> /// Receiver actually paired during <see cref="PeerConnection.HandleConnectionMessageAsync(string, string)"/>. /// This is different from <see cref="Receiver"/> until a negotiation is achieved. /// </summary> [NonSerialized] private MediaReceiver _pairedReceiver; /// <param name="kind">Immutable value assigned to the <see cref="Kind"/> property on construction.</param> public MediaLine(MediaKind kind) { _kind = kind; } protected void UpdateTransceiverDesiredDirection() { if (Transceiver != null) { bool wantsSend = (_sender != null); bool wantsRecv = (_receiver != null); Transceiver.DesiredDirection = Transceiver.DirectionFromSendRecv(wantsSend, wantsRecv); } } internal async Task AttachTrackAsync() { Debug.Assert(Transceiver != null); Debug.Assert(Sender != null); Debug.Assert(_attachedSender == null); await Sender.AttachTrackAsync(); _attachedSender = Sender; } internal void DetachTrack() { Debug.Assert(Transceiver != null); Debug.Assert(Sender == null); Debug.Assert(_attachedSender != null); _attachedSender.DetachTrack(); _attachedSender = null; } internal void UpdateReceiver() { var transceiver = Transceiver; Debug.Assert(transceiver != null); bool wantsRecv = (Receiver != null); bool wasReceiving = (_pairedReceiver != null); bool isReceiving = (transceiver.RemoteTrack != null); // Note the extra "isReceiving" check, which ensures that when the remote track was // just removed by OnUnpaired(RemoteTrack) from the TrackRemoved event then it is not // immediately re-added by mistake. if (wantsRecv && isReceiving && !wasReceiving) { // Transceiver started receiving, and user actually wants to receive Receiver.OnPaired(transceiver.RemoteTrack); _pairedReceiver = Receiver; } else if (!isReceiving && wasReceiving) { // Transceiver stopped receiving (user intent does not matter here) Receiver.OnUnpaired(transceiver.RemoteTrack); _pairedReceiver = null; } } internal void OnUnpaired(RemoteAudioTrack track) { Debug.Assert(track != null); Debug.Assert(Kind == MediaKind.Audio); Debug.Assert(Transceiver != null); Debug.Assert(Transceiver.RemoteAudioTrack == null); // already removed // This is called by the TrackRemoved event, which can be fired sometimes even // though we did not have any opportunity yet to pair. So only unpair if we did. // In details, the case is the answering peer being in sendonly mode, yet created // automatically by the implementation during SetRemoteDescription() in recvonly // mode (per the WebRTC spec). So the SetDirection(sendonly) triggers the TrackRemoved // event, but the pairing was never done because SetDirection() is called before // the received is updated. if (_pairedReceiver != null) { var audioReceiver = (AudioReceiver)_pairedReceiver; audioReceiver.OnUnpaired(track); _pairedReceiver = null; } } internal void OnUnpaired(RemoteVideoTrack track) { Debug.Assert(track != null); Debug.Assert(Kind == MediaKind.Video); Debug.Assert(Transceiver != null); Debug.Assert(Transceiver.RemoteTrack == null); // already removed // This is called by the TrackRemoved event, which can be fired sometimes even // though we did not have any opportunity yet to pair. So only unpair if we did. // In details, the case is the answering peer being in sendonly mode, yet created // automatically by the implementation during SetRemoteDescription() in recvonly // mode (per the WebRTC spec). So the SetDirection(sendonly) triggers the TrackRemoved // event, but the pairing was never done because SetDirection() is called before // the received is updated. if (_pairedReceiver != null) { var videoReceiver = (VideoReceiver)_pairedReceiver; videoReceiver.OnUnpaired(track); _pairedReceiver = null; } } /// <summary> /// Pair the given transceiver with the current media line. /// </summary> /// <param name="tr">The transceiver to pair with.</param> /// <exception cref="InvalidTransceiverMediaKindException"> /// The transceiver associated in the offer with the same media line index as the current media line /// has a different media kind than the media line. This is generally a result of the two peers having /// mismatching media line configurations. /// </exception> internal void PairTransceiverOnFirstOffer(Transceiver tr) { Debug.Assert(tr != null); Debug.Assert((Transceiver == null) || (Transceiver == tr)); // Check consistency before assigning if (tr.MediaKind != Kind) { throw new InvalidTransceiverMediaKindException(); } Transceiver = tr; // Keep the transceiver direction in sync with Sender and Receiver. UpdateTransceiverDesiredDirection(); // Always do this even after first offer, because the sender and receiver // components can be assigned to the media line later, and therefore will // need to be updated on the next offer even if that is not the first one. bool wantsSend = (Sender != null); bool wantsRecv = (Receiver != null); if (Kind == MediaKind.Audio) { var audioTransceiver = Transceiver; if (wantsSend) { var audioSender = (AudioSender)Sender; audioSender.AttachToTransceiver(audioTransceiver); } if (wantsRecv) { var audioReceiver = (AudioReceiver)Receiver; audioReceiver.AttachToTransceiver(audioTransceiver); } } else if (Kind == MediaKind.Video) { var videoTransceiver = Transceiver; if (wantsSend) { var videoSender = (VideoSender)Sender; videoSender.AttachToTransceiver(videoTransceiver); } if (wantsRecv) { var videoReceiver = (VideoReceiver)Receiver; videoReceiver.AttachToTransceiver(videoTransceiver); } } } internal void UnpairTransceiver() { bool wantsSend = (Sender != null); bool wantsRecv = (Receiver != null); if (Kind == MediaKind.Audio) { var audioTransceiver = Transceiver; if (wantsSend) { var audioSender = (AudioSender)Sender; audioSender.DetachFromTransceiver(audioTransceiver); } if (wantsRecv) { var audioReceiver = (AudioReceiver)Receiver; audioReceiver.DetachFromTransceiver(audioTransceiver); } } else if (Kind == MediaKind.Video) { var videoTransceiver = Transceiver; if (wantsSend) { var videoSender = (VideoSender)Sender; videoSender.DetachFromTransceiver(videoTransceiver); } if (wantsRecv) { var videoReceiver = (VideoReceiver)Receiver; videoReceiver.DetachFromTransceiver(videoTransceiver); } } } /// <summary> /// Update the media line when about to create an SDP offer message. /// </summary> /// <param name="tr"> /// The transceiver associated in the offer with the same media line index as the current media line. /// </param> /// <returns>A task which completes when the update is done.</returns> /// <exception cref="InvalidTransceiverMediaKindException"> /// The transceiver associated in the offer with the same media line index as the current media line /// has a different media kind than the media line. This is generally a result of the two peers having /// mismatching media line configurations. /// </exception> internal async Task UpdateForCreateOfferAsync(Transceiver tr) { Debug.Assert(tr != null); PairTransceiverOnFirstOffer(tr); // Create the local sender track and attach it to the transceiver bool wantsSend = (Sender != null); bool wasSending = (_attachedSender != null); if (wantsSend && !wasSending) { await AttachTrackAsync(); } else if (!wantsSend && wasSending) { DetachTrack(); } // The remote track is only created when applying a description, so only attach // the transceiver for now (above) but do not try to pair remote tracks. } /// <summary> /// Update the media line when receiving an SDP offer message from the remote peer. /// </summary> /// <param name="tr"> /// The transceiver associated in the offer with the same media line index as the current media line. /// </param> /// <returns>A task which completes when the update is done.</returns> /// <exception cref="InvalidTransceiverMediaKindException"> /// The transceiver associated in the offer with the same media line index as the current media line /// has a different media kind than the media line. This is generally a result of the two peers having /// mismatching media line configurations. /// </exception> internal async Task UpdateOnReceiveOfferAsync(Transceiver tr) { Debug.Assert(tr != null); PairTransceiverOnFirstOffer(tr); bool wantsSend = (Sender != null); bool wasSending = (_attachedSender != null); if (wantsSend && !wasSending) { // If the offer doesn't allow to send then this will generate a renegotiation needed event, // which will be temporarily delayed since we are in the middle of a negotiation already. await AttachTrackAsync(); } else if (!wantsSend && wasSending) { DetachTrack(); } UpdateReceiver(); } internal void UpdateOnReceiveAnswer() { UpdateReceiver(); } } /// <summary> /// High-level wrapper for Unity WebRTC functionalities. /// This is the API entry point for establishing a connection with a remote peer. /// </summary> [AddComponentMenu("MixedReality-WebRTC/Peer Connection")] public class PeerConnection : MonoBehaviour { /// <summary> /// Retrieves the underlying peer connection object once initialized. /// </summary> /// <remarks> /// If <see cref="OnInitialized"/> has not fired, this will be <c>null</c>. /// </remarks> public WebRTC.PeerConnection Peer { get; private set; } = null; #region Behavior settings /// <summary> /// Initialize the peer connection on <a href="https://docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html">MonoBehaviour.Start()</a>. /// If this field is <c>false</c> then the user needs to call <see cref="InitializeAsync(CancellationToken)"/> /// to manually initialize the peer connection before it can be used for any purpose. /// </summary> [Tooltip("Automatically initialize the peer connection on Start().")] [Editor.ToggleLeft] public bool AutoInitializeOnStart = true; /// <summary> /// Automatically create a new offer whenever a renegotiation needed event is received. /// </summary> /// <remarks> /// Note that the renegotiation needed event may be dispatched asynchronously, so it is /// discourages to toggle this field ON and OFF. Instead, the user should choose an /// approach (manual or automatic) and stick to it. /// /// In particular, temporarily setting this to <c>false</c> during a batch of changes and /// setting it back to <c>true</c> right after the last change may or may not produce an /// automatic offer, depending on whether the negotiated event was dispatched while the /// property was still <c>false</c> or not. /// </remarks> [Tooltip("Automatically create a new offer when receiving a renegotiation needed event.")] [Editor.ToggleLeft] public bool AutoCreateOfferOnRenegotiationNeeded = true; /// <summary> /// Flag to log all errors to the Unity console automatically. /// </summary> [Tooltip("Automatically log all errors to the Unity console.")] [Editor.ToggleLeft] public bool AutoLogErrorsToUnityConsole = true; #endregion #region Interactive Connectivity Establishment (ICE) /// <summary> /// Set of ICE servers the WebRTC library will use to try to establish a connection. /// </summary> [Tooltip("Optional set of ICE servers (STUN and/or TURN)")] public List<ConfigurableIceServer> IceServers = new List<ConfigurableIceServer>() { new ConfigurableIceServer() { Type = IceType.Stun, Uri = "stun.l.google.com:19302" } }; /// <summary> /// Optional username for the ICE servers. /// </summary> [Tooltip("Optional username for the ICE servers")] public string IceUsername; /// <summary> /// Optional credential for the ICE servers. /// </summary> [Tooltip("Optional credential for the ICE servers")] public string IceCredential; #endregion #region Events /// <summary> /// Event fired after the peer connection is initialized and ready for use. /// </summary> [Tooltip("Event fired after the peer connection is initialized and ready for use")] public UnityEvent OnInitialized = new UnityEvent(); /// <summary> /// Event fired after the peer connection is shut down and cannot be used anymore. /// </summary> [Tooltip("Event fired after the peer connection is shut down and cannot be used anymore")] public UnityEvent OnShutdown = new UnityEvent(); /// <summary> /// Event that occurs when a WebRTC error occurs /// </summary> [Tooltip("Event that occurs when a WebRTC error occurs")] public WebRTCErrorEvent OnError = new WebRTCErrorEvent(); #endregion #region Private variables /// <summary> /// Internal queue used to marshal work back to the main Unity app thread where access /// to Unity objects is allowed. This is generally used to defer events/callbacks, which /// are free-threaded in the low-level implementation. /// </summary> private ConcurrentQueue<Action> _mainThreadWorkQueue = new ConcurrentQueue<Action>(); /// <summary> /// Underlying native peer connection wrapper. /// </summary> /// <remarks> /// Unlike the public <see cref="Peer"/> property, this is never <c>NULL</c>, /// but can be an uninitialized peer. /// </remarks> private WebRTC.PeerConnection _nativePeer = null; /// <summary> /// List of transceiver media lines and their associated media sender/receiver components. /// </summary> [SerializeField] private List<MediaLine> _mediaLines = new List<MediaLine>(); #endregion #region Public methods /// <summary> /// Enumerate the video capture devices available as a WebRTC local video feed source. /// </summary> /// <returns>The list of local video capture devices available to WebRTC.</returns> public static Task<List<VideoCaptureDevice>> GetVideoCaptureDevicesAsync() { return WebRTC.PeerConnection.GetVideoCaptureDevicesAsync(); } /// <summary> /// Initialize the underlying WebRTC peer connection. /// </summary> /// <remarks> /// This method must be called once before using the peer connection. If <see cref="AutoInitializeOnStart"/> /// is <c>true</c> then it is automatically called during <a href="https://docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html">MonoBehaviour.Start()</a>. /// /// This method is asynchronous and completes its task when the initializing completed. /// On successful completion, it also trigger the <see cref="OnInitialized"/> event. /// Note however that this completion is free-threaded and complete immediately when the /// underlying peer connection is initialized, whereas any <see cref="OnInitialized"/> /// event handler is invoked when control returns to the main Unity app thread. The former /// is faster, but does not allow accessing the underlying peer connection because it /// returns before <see cref="OnPostInitialize"/> executed. Therefore it is generally /// recommended to listen to the <see cref="OnInitialized"/> event, and ignore the returned /// <see xref="System.Threading.Tasks.Task"/> object. /// /// If the peer connection is already initialized, this method returns immediately with /// a <see xref="System.Threading.Tasks.Task.CompletedTask"/> object. The caller can check /// that the <see cref="Peer"/> property is non-<c>null</c> to confirm that the connection /// is in fact initialized. /// </remarks> public Task InitializeAsync(CancellationToken token = default(CancellationToken)) { // Check in case Awake() was called first if (_nativePeer == null) { CreateNativePeerConnection(); } // if the peer is already set, we refuse to initialize again. // Note: for multi-peer scenarios, use multiple WebRTC components. if (_nativePeer.Initialized) { return Task.CompletedTask; } #if UNITY_ANDROID AndroidJavaClass systemClass = new AndroidJavaClass("java.lang.System"); string libname = "jingle_peerconnection_so"; systemClass.CallStatic("loadLibrary", new object[1] { libname }); Debug.Log("loadLibrary loaded : " + libname); /* * Below is equivalent of this java code: * PeerConnectionFactory.InitializationOptions.Builder builder = * PeerConnectionFactory.InitializationOptions.builder(UnityPlayer.currentActivity); * PeerConnectionFactory.InitializationOptions options = * builder.createInitializationOptions(); * PeerConnectionFactory.initialize(options); */ AndroidJavaClass playerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject activity = playerClass.GetStatic<AndroidJavaObject>("currentActivity"); AndroidJavaClass webrtcClass = new AndroidJavaClass("org.webrtc.PeerConnectionFactory"); AndroidJavaClass initOptionsClass = new AndroidJavaClass("org.webrtc.PeerConnectionFactory$InitializationOptions"); AndroidJavaObject builder = initOptionsClass.CallStatic<AndroidJavaObject>("builder", new object[1] { activity }); AndroidJavaObject options = builder.Call<AndroidJavaObject>("createInitializationOptions"); if (webrtcClass != null) { webrtcClass.CallStatic("initialize", new object[1] { options }); } #endif #if UNITY_WSA && !UNITY_EDITOR if (UnityEngine.WSA.Application.RunningOnUIThread()) #endif { return RequestAccessAndInitAsync(token); } #if UNITY_WSA && !UNITY_EDITOR else { UnityEngine.WSA.Application.InvokeOnUIThread(() => RequestAccessAndInitAsync(token), waitUntilDone: true); return Task.CompletedTask; } #endif } /// <summary> /// Add a new media line of the given kind. /// /// This method creates a media line, which expresses an intent from the user to get a transceiver. /// The actual <see xref="WebRTC.Transceiver"/> object creation is delayed until a session /// negotiation is completed. /// /// Once the media line is created, the user can then assign its <see cref="MediaLine.Sender"/> and /// <see cref="MediaLine.Receiver"/> properties to express their intent to send and/or receive some media /// through the transceiver that will be associated with that media line once a session is negotiated. /// This information is used in subsequent negotiations to derive a /// <see xref="Microsoft.MixedReality.WebRTC.Transceiver.Direction"/> to negotiate. Therefore users /// should avoid modifying the <see cref="Transceiver.DesiredDirection"/> property manually when using /// the Unity library, and instead modify the <see cref="MediaLine.Sender"/> and /// <see cref="MediaLine.Receiver"/> properties. /// </summary> /// <param name="kind">The kind of media (audio or video) for the transceiver.</param> /// <returns>A newly created media line, which will be associated with a transceiver once the next session /// is negotiated.</returns> public MediaLine AddMediaLine(MediaKind kind) { var ml = new MediaLine(kind); _mediaLines.Add(ml); return ml; } /// <summary> /// Create a new connection offer, either for a first connection to the remote peer, or for /// renegotiating some new or removed transceivers. /// /// This method submits an internal task to create an SDP offer message. Once the message is /// created, the implementation raises the <see xref="Microsoft.MixedReality.WebRTC.PeerConnection.LocalSdpReadytoSend"/> /// event to allow the user to send the message via the chosen signaling solution to the remote /// peer. /// /// <div class="IMPORTANT alert alert-important"> /// <h5>IMPORTANT</h5> /// <p> /// This method is very similar to the <c>CreateOffer()</c> method available in the underlying C# library, /// and actually calls it. However it also performs additional work in order to pair the transceivers of /// the local and remote peer. Therefore Unity applications must call this method instead of the C# library /// one to ensure transceiver pairing works as intended. /// </p> /// </div> /// </summary> /// <returns> /// <c>true</c> if the offer creation task was submitted successfully, and <c>false</c> otherwise. /// The offer SDP message is always created asynchronously. /// </returns> public bool StartConnection() { if (Peer == null) { throw new InvalidOperationException("Cannot create an offer with an uninitialized peer."); } // Batch all changes into a single offer AutoCreateOfferOnRenegotiationNeeded = false; // Add all new transceivers for local tracks. Since transceivers are only paired by negotiated mid, // we need to know which peer sends the offer before adding the transceivers on the offering side only, // and then pair them on the receiving side. Otherwise they are duplicated, as the transceiver mid from // locally-created transceivers is not negotiated yet, so ApplyRemoteDescriptionAsync() won't be able // to find them and will re-create a new set of transceivers, leading to duplicates. // So we wait until we know this peer is the offering side, and add transceivers to it right before // creating an offer. The remote peer will then match the transceivers by index after it applied the offer, // then add any missing one. // Update all transceivers, whether previously existing or just created above var transceivers = _nativePeer.Transceivers; int index = 0; foreach (var mediaLine in _mediaLines) { // Ensure each media line has a transceiver Transceiver tr = mediaLine.Transceiver; if (tr != null) { // Media line already had a transceiver from a previous session negotiation Debug.Assert(tr.MlineIndex >= 0); // associated } else { // Create new transceivers for a media line added since last session negotiation. // Compute the transceiver desired direction based on what the local peer expects, both in terms // of sending and in terms of receiving. Note that this means the remote peer will not be able to // send any data if the local peer did not add a remote source first. // Tracks are not tested explicitly since the local track can be swapped on-the-fly without renegotiation, // and the remote track is generally not added yet at the beginning of the negotiation, but only when // the remote description is applied (so for the offering side, at the end of the exchange when the // answer is received). bool wantsSend = (mediaLine.Sender != null); bool wantsRecv = (mediaLine.Receiver != null); var wantsDir = Transceiver.DirectionFromSendRecv(wantsSend, wantsRecv); var settings = new TransceiverInitSettings { Name = $"mrsw#{index}", InitialDesiredDirection = wantsDir }; tr = _nativePeer.AddTransceiver(mediaLine.Kind, settings); } Debug.Assert(tr != null); Debug.Assert(transceivers[index++] == tr); // Update the transceiver try { //< FIXME - CreateOfferAsync() to use await instead of Wait() mediaLine.UpdateForCreateOfferAsync(tr).Wait(); } catch (Exception ex) { LogErrorOnMediaLineException(ex, mediaLine, tr); } } // Create the offer AutoCreateOfferOnRenegotiationNeeded = true; return _nativePeer.CreateOffer(); } /// <summary> /// Pass the given SDP description received from the remote peer via signaling to the /// underlying WebRTC implementation, which will parse and use it. /// /// This must be called by the signaler when receiving a message. Once this operation /// has completed, it is safe to call <see xref="WebRTC.PeerConnection.CreateAnswer"/>. /// /// <div class="IMPORTANT alert alert-important"> /// <h5>IMPORTANT</h5> /// <p> /// This method is very similar to the <c>SetRemoteDescriptionAsync()</c> method available in the /// underlying C# library, and actually calls it. However it also performs additional work in order /// to pair the transceivers of the local and remote peer. Therefore Unity applications must call /// this method instead of the C# library one to ensure transceiver pairing works as intended. /// </p> /// </div> /// </summary> /// <param name="type">The type of SDP message ("offer" or "answer")</param> /// <param name="sdp">The content of the SDP message</param> /// <returns>A task which completes once the remote description has been applied and transceivers /// have been updated.</returns> /// <exception xref="InvalidOperationException">The peer connection is not intialized.</exception> public async Task HandleConnectionMessageAsync(string type, string sdp) { // First apply the remote description await Peer.SetRemoteDescriptionAsync(type, sdp); // Sort associated transceiver by media line index. The media line index is not the index of // the transceiver, but they are both monotonically increasing, so sorting by one or the other // yields the same ordered collection, which allows pairing transceivers and media lines. // TODO - Ensure PeerConnection.Transceivers is already sorted var transceivers = new List<Transceiver>(_nativePeer.AssociatedTransceivers); transceivers.Sort((tr1, tr2) => (tr1.MlineIndex - tr2.MlineIndex)); int numAssociatedTransceivers = transceivers.Count; int numMatching = Math.Min(numAssociatedTransceivers, _mediaLines.Count); // Once applied, try to pair transceivers and remote tracks with the Unity receiver components if (type == "offer") { // Match transceivers with media line, in order for (int i = 0; i < numMatching; ++i) { var tr = transceivers[i]; var mediaLine = _mediaLines[i]; // Associate the transceiver with the media line, if not already done, and associate // the track components of the media line to the tracks of the transceiver. try { await mediaLine.UpdateOnReceiveOfferAsync(tr); } catch (Exception ex) { LogErrorOnMediaLineException(ex, mediaLine, tr); } // Check if the remote peer was planning to send something to this peer, but cannot. bool wantsRecv = (mediaLine.Receiver != null); if (!wantsRecv) { var desDir = tr.DesiredDirection; if (Transceiver.HasRecv(desDir)) { string peerName = name; int idx = i; _mainThreadWorkQueue.Enqueue(() => { LogWarningOnMissingReceiver(peerName, idx); }); } } } // Ignore extra transceivers without a registered component to attach if (numMatching < numAssociatedTransceivers) { string peerName = name; _mainThreadWorkQueue.Enqueue(() => { for (int i = numMatching; i < numAssociatedTransceivers; ++i) { LogWarningOnIgnoredTransceiver(peerName, i); } }); } } else if (type == "answer") { // Associate registered media senders/receivers with existing transceivers for (int i = 0; i < numMatching; ++i) { Transceiver tr = transceivers[i]; var mediaLine = _mediaLines[i]; Debug.Assert(mediaLine.Transceiver == transceivers[i]); mediaLine.UpdateOnReceiveAnswer(); } // Ignore extra transceivers without a registered component to attach if (numMatching < numAssociatedTransceivers) { string peerName = name; _mainThreadWorkQueue.Enqueue(() => { for (int i = numMatching; i < numAssociatedTransceivers; ++i) { LogWarningOnIgnoredTransceiver(peerName, i); } }); } } } /// <summary> /// Uninitialize the underlying WebRTC library, effectively cleaning up the allocated peer connection. /// </summary> /// <remarks> /// <see cref="Peer"/> will be <c>null</c> afterward. /// </remarks> public void Uninitialize() { if ((_nativePeer != null) && _nativePeer.Initialized) { // Fire signals before doing anything else to allow listeners to clean-up, // including un-registering any callback and remove any track from the connection. OnShutdown.Invoke(); // Prevent publicly accessing the native peer after it has been deinitialized. // This does not prevent systems caching a reference from accessing it, but it // is their responsibility to check that the peer is initialized. Peer = null; // Detach all transceivers. This prevents senders/receivers from trying to access // them during their clean-up sequence, as transceivers are about to be destroyed // by the native implementation. foreach (var mediaLine in _mediaLines) { mediaLine.UnpairTransceiver(); } // Close the connection and release native resources. _nativePeer.Dispose(); _nativePeer = null; } } #endregion #region Unity MonoBehaviour methods private void Awake() { // Check in case InitializeAsync() was called first. if (_nativePeer == null) { CreateNativePeerConnection(); } } /// <summary> /// Unity Engine Start() hook /// </summary> /// <remarks> /// See <see href="https://docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html"/> /// </remarks> private void Start() { if (AutoLogErrorsToUnityConsole) { OnError.AddListener(OnError_Listener); } if (AutoInitializeOnStart) { InitializeAsync(); } } /// <summary> /// Unity Engine Update() hook /// </summary> /// <remarks> /// https://docs.unity3d.com/ScriptReference/MonoBehaviour.Update.html /// </remarks> private void Update() { // Execute any pending work enqueued by background tasks while (_mainThreadWorkQueue.TryDequeue(out Action workload)) { workload(); } } /// <summary> /// Unity Engine OnDestroy() hook /// </summary> /// <remarks> /// https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnDestroy.html /// </remarks> private void OnDestroy() { Uninitialize(); OnError.RemoveListener(OnError_Listener); } #endregion #region Private implementation /// <summary> /// Create a new native peer connection and register event handlers to it. /// This does not initialize the peer connection yet. /// </summary> private void CreateNativePeerConnection() { // Create the peer connection managed wrapper and its native implementation _nativePeer = new WebRTC.PeerConnection(); // Register event handlers for remote tracks removed (media receivers). // Note that handling of tracks added is done in HandleConnectionMessageAsync rather than // in TrackAdded because when these are invoked the transceivers have not been // paired yet, so there's not much we can do with those events. _nativePeer.AudioTrackRemoved += Peer_AudioTrackRemoved; _nativePeer.VideoTrackRemoved += Peer_VideoTrackRemoved; // TODO uncomment when remote audio is played through AudioReceiver //_nativePeer.AudioTrackAdded += // (RemoteAudioTrack track) => // { // // Tracks will be rendered by AudioReceivers, so avoid rendering them twice. // track.RenderToDevice(false); // }; } /// <summary> /// Internal helper to ensure device access and continue initialization. /// </summary> /// <remarks> /// On UWP this must be called from the main UI thread. /// </remarks> private Task RequestAccessAndInitAsync(CancellationToken token) { #if UNITY_WSA && !UNITY_EDITOR // On UWP the app must have the "webcam" capability, and the user must allow webcam // access. So check that access before trying to initialize the WebRTC library, as this // may result in a popup window being displayed the first time, which needs to be accepted // before the camera can be accessed by WebRTC. var mediaAccessRequester = new MediaCapture(); var mediaSettings = new MediaCaptureInitializationSettings(); mediaSettings.AudioDeviceId = ""; mediaSettings.VideoDeviceId = ""; mediaSettings.StreamingCaptureMode = StreamingCaptureMode.AudioAndVideo; mediaSettings.PhotoCaptureSource = PhotoCaptureSource.VideoPreview; mediaSettings.SharingMode = MediaCaptureSharingMode.SharedReadOnly; // for MRC and lower res camera var accessTask = mediaAccessRequester.InitializeAsync(mediaSettings).AsTask(token); return accessTask.ContinueWith(prevTask => { token.ThrowIfCancellationRequested(); if (prevTask.Exception == null) { InitializePluginAsync(token); } else { var ex = prevTask.Exception; _mainThreadWorkQueue.Enqueue(() => { OnError.Invoke($"Audio/Video access failure: {ex.Message}."); }); } }, token); #else return InitializePluginAsync(token); #endif } /// <summary> /// Internal handler to actually initialize the plugin. /// </summary> private Task InitializePluginAsync(CancellationToken token) { Debug.Log("Initializing WebRTC plugin..."); var config = new PeerConnectionConfiguration(); foreach (var server in IceServers) { config.IceServers.Add(new IceServer { Urls = { server.ToString() }, TurnUserName = IceUsername, TurnPassword = IceCredential }); } return _nativePeer.InitializeAsync(config, token).ContinueWith((initTask) => { token.ThrowIfCancellationRequested(); Exception ex = initTask.Exception; if (ex != null) { _mainThreadWorkQueue.Enqueue(() => { var errorMessage = new StringBuilder(); errorMessage.Append("WebRTC plugin initializing failed. See full log for exception details.\n"); while (ex is AggregateException ae) { errorMessage.Append($"AggregationException: {ae.Message}\n"); ex = ae.InnerException; } errorMessage.Append($"Exception: {ex.Message}"); OnError.Invoke(errorMessage.ToString()); }); throw initTask.Exception; } _mainThreadWorkQueue.Enqueue(OnPostInitialize); }, token); } /// <summary> /// Callback fired on the main Unity app thread once the WebRTC plugin was initialized successfully. /// </summary> private void OnPostInitialize() { Debug.Log("WebRTC plugin initialized successfully."); if (AutoCreateOfferOnRenegotiationNeeded) { _nativePeer.RenegotiationNeeded += Peer_RenegotiationNeeded; } // Once the peer is initialized, it becomes publicly accessible. // This prevent scripts from accessing it before it is initialized, // or worse before it is constructed in Awake(). This happens because // some scripts try to access Peer in OnEnabled(), which won't work // if Unity decided to initialize that script before the current one. // However subsequent calls will (and should) work as expected. Peer = _nativePeer; OnInitialized.Invoke(); } private void Peer_AudioTrackRemoved(Transceiver transceiver, RemoteAudioTrack track) { Debug.Assert(track.Transceiver == null); // already removed // Note: if the transceiver was created by setting a remote description internally, but // the user did not add any MediaLine in the component, then the transceiver is ignored. // SetRemoteDescriptionAsync() already triggered a warning in this case, so be silent here. MediaLine mediaLine = _mediaLines.Find((MediaLine ml) => ml.Transceiver == transceiver); if (mediaLine != null) { Debug.Assert(mediaLine != null); Debug.Assert(mediaLine.Kind == MediaKind.Audio); mediaLine.OnUnpaired(track); } } private void Peer_VideoTrackRemoved(Transceiver transceiver, RemoteVideoTrack track) { Debug.Assert(track.Transceiver == null); // already removed // Note: if the transceiver was created by SetRemoteDescription() internally, but the user // did not add any MediaLine in the component, then the transceiver is ignored. // SetRemoteDescriptionAsync() already triggered a warning in this case, so be silent here. MediaLine mediaLine = _mediaLines.Find((MediaLine ml) => ml.Transceiver == transceiver); if (mediaLine != null) { Debug.Assert(mediaLine != null); Debug.Assert(mediaLine.Kind == MediaKind.Video); mediaLine.OnUnpaired(track); } } private void Peer_RenegotiationNeeded() { // If already connected, update the connection on the fly. // If not, wait for user action and don't automatically connect. if (AutoCreateOfferOnRenegotiationNeeded && _nativePeer.IsConnected) { // Defer to the main app thread, because this implementation likely will // again trigger the renegotiation needed event, which is not re-entrant. // This also allows accessing Unity objects, and makes it safer in general // for other objects. _mainThreadWorkQueue.Enqueue(() => StartConnection()); } } /// <summary> /// Internal handler for on-error, if <see cref="AutoLogErrorsToUnityConsole"/> is <c>true</c> /// </summary> /// <param name="error">The error message</param> private void OnError_Listener(string error) { Debug.LogError(error); } /// <summary> /// Log an error when receiving an exception related to a media line and transceiver pairing. /// </summary> /// <param name="ex">The exception to log.</param> /// <param name="mediaLine">The media line associated with the exception.</param> /// <param name="transceiver">The transceiver associated with the exception.</param> private void LogErrorOnMediaLineException(Exception ex, MediaLine mediaLine, Transceiver transceiver) { // Dispatch to main thread to access Unity objects to get their names _mainThreadWorkQueue.Enqueue(() => { string msg; if (ex is InvalidTransceiverMediaKindException) { msg = $"Peer connection \"{name}\" received {transceiver.MediaKind} transceiver #{transceiver.MlineIndex} \"{transceiver.Name}\", but local peer expected some {mediaLine.Kind} transceiver instead."; if (mediaLine.Sender != null) { msg += $" Sender \"{mediaLine.Sender.name}\" will be ignored."; } if (mediaLine.Receiver) { msg += $" Receiver \"{mediaLine.Receiver.name}\" will be ignored."; } } else { // Generic exception, log its message msg = ex.Message; } Debug.LogError(msg); }); } private void LogWarningOnMissingReceiver(string peerName, int trIndex) { Debug.LogWarning($"The remote peer connected to the local peer connection '{peerName}' offered to send some media" + $" through transceiver #{trIndex}, but the local peer connection '{peerName}' has no receiver component to" + " process this media. The remote peer's media will be ignored. To be able to receive that media, ensure that" + $" the local peer connection '{peerName}' has a receiver component associated with its transceiver #{trIndex}."); } private void LogWarningOnIgnoredTransceiver(string peerName, int trIndex) { Debug.LogWarning($"The remote peer connected to the local peer connection '{peerName}' has transceiver #{trIndex}," + " but the local peer connection doesn't have a local transceiver to pair with it. The remote peer's media for" + " this transceiver will be ignored. To be able to receive that media, ensure that the local peer connection" + $" '{peerName}' has transceiver #{trIndex} and a receiver component associated with it."); } #endregion } }
44.169349
218
0.581947
[ "MIT" ]
jongfeelkim-VIRNECT/MixedReality-WebRTC
libs/Microsoft.MixedReality.WebRTC.Unity/Assets/Microsoft.MixedReality.WebRTC.Unity/Scripts/PeerConnection.cs
57,641
C#
using FluentAssertions; using Microsoft.AspNetCore.Mvc; using NSubstitute; using Sfa.Tl.ResultsAndCertification.Common.Extensions; using Sfa.Tl.ResultsAndCertification.Tests.Common.Helpers; using Sfa.Tl.ResultsAndCertification.Web.Controllers; using Sfa.Tl.ResultsAndCertification.Web.ViewModel.Provider; using Sfa.Tl.ResultsAndCertification.Web.ViewModel.Provider.SelectProviderTlevels; using System.Collections.Generic; using System.Threading.Tasks; using Xunit; namespace Sfa.Tl.ResultsAndCertification.Web.UnitTests.Controllers.ProviderControllerTests.FindProviderGet { public class When_SearchResults_Found : When_FindProviderAsync_Post_Action_Is_Called { private Task<IActionResult> _selectProviderTlevelResult; private ProviderTlevelsViewModel _mockresult; private string _searchText = "Test College"; public override void Given() { var httpContext = new ClaimsIdentityBuilder<ProviderController>(Controller) .Add(CustomClaimTypes.Ukprn, Ukprn.ToString()) .Build() .HttpContext; HttpContextAccessor.HttpContext.Returns(httpContext); ProviderLoader.IsAnyProviderSetupCompletedAsync(Ukprn).Returns(true); _mockresult = new ProviderTlevelsViewModel { ProviderId = 1, DisplayName = _searchText, Ukprn = 10000111, IsAddTlevel = false, Tlevels = new List<ProviderTlevelViewModel> { new ProviderTlevelViewModel { TqAwardingOrganisationId = 1, TlProviderId = 1, TlevelTitle = "Route1: Pathway1" }, new ProviderTlevelViewModel { TqAwardingOrganisationId = 1, TlProviderId = 1, TlevelTitle = "Route1: Pathway1" } } }; ProviderLoader.GetSelectProviderTlevelsAsync(Arg.Any<long>(), Arg.Any<int>()).Returns(_mockresult); } public async override Task When() { _selectProviderTlevelResult = Controller.SelectProviderTlevelsAsync(1); Result = await Controller.FindProviderAsync(true); } [Fact] public void Then_Returns_Expected_Results() { Result.Should().BeOfType(typeof(ViewResult)); var viewResult = Result as ViewResult; viewResult.Model.Should().BeOfType(typeof(FindProviderViewModel)); var model = viewResult.Model as FindProviderViewModel; model.Should().NotBeNull(); model.Search.Should().Be(_searchText); } } }
39.074627
133
0.668067
[ "MIT" ]
SkillsFundingAgency/tl-result-and-certification
src/Tests/Sfa.Tl.ResultsAndCertification.Web.UnitTests/Controllers/ProviderControllerTests/FindProviderGet/When_SearchResults_Found.cs
2,620
C#
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Pipeline { using System.Threading.Tasks; public interface IPipe<in T> : IProbeSite where T : class, PipeContext { /// <summary> /// The base primitive, Send delivers the pipe context of T to the pipe. /// </summary> /// <param name="context">The pipe context of type T</param> /// <returns>A task which is completed once the pipe has processed the context</returns> Task Send(T context); } }
40.068966
97
0.666093
[ "Apache-2.0" ]
Johavale19/Johanna
src/MassTransit/Pipeline/IPipe.cs
1,162
C#
using System.Web.Http; using System.Web.Routing; namespace FieldEngineerLite.Service { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { WebApiConfig.Register(); } } }
20.461538
63
0.654135
[ "Apache-2.0" ]
mahizsas/FieldEngineerLite
FieldEngineerLite.Service/Global.asax.cs
268
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 Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal; using Xunit; namespace Microsoft.EntityFrameworkCore.Storage { public class SqlServerSqlGenerationHelperTest { [ConditionalFact] public void BatchSeparator_returns_separator() => Assert.Equal( "GO" + Environment.NewLine + Environment.NewLine, CreateSqlGenerationHelper().BatchTerminator ); private ISqlGenerationHelper CreateSqlGenerationHelper() => new SqlServerSqlGenerationHelper(new RelationalSqlGenerationHelperDependencies()); } }
35.818182
111
0.718274
[ "Apache-2.0" ]
belav/efcore
test/EFCore.SqlServer.Tests/Storage/SqlServerSqlGenerationHelperTest.cs
788
C#
using System; namespace Equinor.Lighthouse.Api.Domain.Exceptions; public class ConcurrencyException : Exception { public ConcurrencyException(string message) : base(message) { } public ConcurrencyException(string message, Exception innerException) : base(message, innerException) { } }
22.357143
105
0.744409
[ "MIT" ]
equinor/lighthouse-api
src/Equinor.Lighthouse.Api.Domain/Exceptions/ConcurrencyException.cs
315
C#
namespace DotNetInterview.Services.Data { using System; using System.Linq; using System.Threading.Tasks; using DotNetInterview.Common; using DotNetInterview.Data.Common.Repositories; using DotNetInterview.Data.Models; using DotNetInterview.Data.Models.Enums; using DotNetInterview.Services.Data.Extensions; using DotNetInterview.Web.ViewModels.Users; using DotNetInterview.Web.ViewModels.Users.DTO; public class UsersService : IUsersService { private readonly IDeletableEntityRepository<ApplicationUser> userRepository; private readonly INationalitiesService nationalitiesService; public UsersService( IDeletableEntityRepository<ApplicationUser> userRepository, INationalitiesService nationalitiesService) { this.userRepository = userRepository; this.nationalitiesService = nationalitiesService; } public DetailsUserVM Details(string userId, bool isLoggedInUser, bool isAdmin) { var userDTO = this.userRepository .All() .Where(u => u.Id == userId) .Select(u => new DetailsUserDTO { Id = u.Id, UserName = u.UserName, FirstName = u.FirstName, LastName = u.LastName, Nationality = u.UserNationality, Position = u.Position.ToString(), Description = u.Description, MemberSince = u.CreatedOn, DateOfBirth = u.DateOfBirth, Image = u.Image, Interviews = u.Interviews .OrderByDescending(i => i.CreatedOn) .Select(i => new DetailsUserInterviewsVM { InterviewId = i.Id, Title = i.PositionTitle.PositionTitleParser(), Seniority = i.Seniority.ToString(), Date = i.CreatedOn.ToString(GlobalConstants.FormatDate), Likes = i.Likes .Where(l => l.IsLiked) .Count(), Qns = i.Questions.Count, }) .ToList(), }) .FirstOrDefault(); if (userDTO == null) { return null; } return new DetailsUserVM { Id = userDTO.Id, UserName = userDTO.UserName, FullName = $"{userDTO.FirstName} {userDTO.LastName}", Position = userDTO.Position, Nationality = userDTO.Nationality != null ? userDTO.Nationality : GlobalConstants.NoInformation, MemberSince = userDTO.MemberSince.ToString(GlobalConstants.FormatDate), DateOfBirth = userDTO.DateOfBirth != null ? userDTO.DateOfBirth?.ToString(GlobalConstants.FormatDateShort) : GlobalConstants.NoInformation, Description = userDTO.Description != null ? userDTO.Description : GlobalConstants.NoInformation, Image = userDTO.Image, ShowEdit = isLoggedInUser ? string.Empty : GlobalConstants.Hidden, ShowDelete = isLoggedInUser || isAdmin ? string.Empty : GlobalConstants.Hidden, Interviews = userDTO.Interviews, }; } public async Task Update(ApplicationUser user, UpdateUserDTO formModel, IFileService fileService, string fileDirectory) { if (!int.TryParse(formModel.NationalityId, out var nationalityId)) { throw new ArgumentException($"Company nationality Id : '{formModel.NationalityId}' is invalid!"); } var nationality = await this.nationalitiesService.GetById(nationalityId); user.FirstName = formModel.FirstName; user.LastName = formModel.LastName; user.UserNationality = nationality?.CompanyNationality; user.Nationality = nationality; user.Position = Enum.Parse<WorkPosition>(formModel.Position.ToString()); user.DateOfBirth = formModel.DateOfBirth; user.Description = formModel.Description; user.NationalityId = nationality?.Id; user.Nationality = nationality; var savedFileName = await fileService.SaveFile(formModel.Image, fileDirectory); if (user.Image != null && !user.Image.Contains(GlobalConstants.DefaultFilePart)) { fileService.DeleteFile(fileDirectory, user.Image); } user.Image = savedFileName; this.userRepository.Update(user); await this.userRepository.SaveChangesAsync(); } public async Task Delete(string userId) { var user = await this.userRepository.GetByIdWithDeletedAsync(userId); if (user == null) { return; } this.userRepository.Delete(user); await this.userRepository.SaveChangesAsync(); } } }
40.206107
155
0.566546
[ "MIT" ]
TonyDimitrov/SharedDotNetInterview
Services/DotNetInterview.Services.Data/UsersService.cs
5,269
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901 { using static Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Extensions; /// <summary>AADProfile specifies attributes for Azure Active Directory integration.</summary> public partial class ManagedClusterAadProfile : Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.IManagedClusterAadProfile, Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.IManagedClusterAadProfileInternal { /// <summary>Backing field for <see cref="AdminGroupObjectID" /> property.</summary> private string[] _adminGroupObjectID; /// <summary>AAD group object IDs that will have admin role of the cluster.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Aks.Origin(Microsoft.Azure.PowerShell.Cmdlets.Aks.PropertyOrigin.Owned)] public string[] AdminGroupObjectID { get => this._adminGroupObjectID; set => this._adminGroupObjectID = value; } /// <summary>Backing field for <see cref="ClientAppId" /> property.</summary> private string _clientAppId; /// <summary>The client AAD application ID.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Aks.Origin(Microsoft.Azure.PowerShell.Cmdlets.Aks.PropertyOrigin.Owned)] public string ClientAppId { get => this._clientAppId; set => this._clientAppId = value; } /// <summary>Backing field for <see cref="EnableAzureRbac" /> property.</summary> private bool? _enableAzureRbac; /// <summary>Whether to enable Azure RBAC for Kubernetes authorization.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Aks.Origin(Microsoft.Azure.PowerShell.Cmdlets.Aks.PropertyOrigin.Owned)] public bool? EnableAzureRbac { get => this._enableAzureRbac; set => this._enableAzureRbac = value; } /// <summary>Backing field for <see cref="Managed" /> property.</summary> private bool? _managed; /// <summary>Whether to enable managed AAD.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Aks.Origin(Microsoft.Azure.PowerShell.Cmdlets.Aks.PropertyOrigin.Owned)] public bool? Managed { get => this._managed; set => this._managed = value; } /// <summary>Backing field for <see cref="ServerAppId" /> property.</summary> private string _serverAppId; /// <summary>The server AAD application ID.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Aks.Origin(Microsoft.Azure.PowerShell.Cmdlets.Aks.PropertyOrigin.Owned)] public string ServerAppId { get => this._serverAppId; set => this._serverAppId = value; } /// <summary>Backing field for <see cref="ServerAppSecret" /> property.</summary> private string _serverAppSecret; /// <summary>The server AAD application secret.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Aks.Origin(Microsoft.Azure.PowerShell.Cmdlets.Aks.PropertyOrigin.Owned)] public string ServerAppSecret { get => this._serverAppSecret; set => this._serverAppSecret = value; } /// <summary>Backing field for <see cref="TenantId" /> property.</summary> private string _tenantId; /// <summary> /// The AAD tenant ID to use for authentication. If not specified, will use the tenant of the deployment subscription. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.Aks.Origin(Microsoft.Azure.PowerShell.Cmdlets.Aks.PropertyOrigin.Owned)] public string TenantId { get => this._tenantId; set => this._tenantId = value; } /// <summary>Creates an new <see cref="ManagedClusterAadProfile" /> instance.</summary> public ManagedClusterAadProfile() { } } /// AADProfile specifies attributes for Azure Active Directory integration. public partial interface IManagedClusterAadProfile : Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.IJsonSerializable { /// <summary>AAD group object IDs that will have admin role of the cluster.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Info( Required = false, ReadOnly = false, Description = @"AAD group object IDs that will have admin role of the cluster.", SerializedName = @"adminGroupObjectIDs", PossibleTypes = new [] { typeof(string) })] string[] AdminGroupObjectID { get; set; } /// <summary>The client AAD application ID.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Info( Required = false, ReadOnly = false, Description = @"The client AAD application ID.", SerializedName = @"clientAppID", PossibleTypes = new [] { typeof(string) })] string ClientAppId { get; set; } /// <summary>Whether to enable Azure RBAC for Kubernetes authorization.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Info( Required = false, ReadOnly = false, Description = @"Whether to enable Azure RBAC for Kubernetes authorization.", SerializedName = @"enableAzureRBAC", PossibleTypes = new [] { typeof(bool) })] bool? EnableAzureRbac { get; set; } /// <summary>Whether to enable managed AAD.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Info( Required = false, ReadOnly = false, Description = @"Whether to enable managed AAD.", SerializedName = @"managed", PossibleTypes = new [] { typeof(bool) })] bool? Managed { get; set; } /// <summary>The server AAD application ID.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Info( Required = false, ReadOnly = false, Description = @"The server AAD application ID.", SerializedName = @"serverAppID", PossibleTypes = new [] { typeof(string) })] string ServerAppId { get; set; } /// <summary>The server AAD application secret.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Info( Required = false, ReadOnly = false, Description = @"The server AAD application secret.", SerializedName = @"serverAppSecret", PossibleTypes = new [] { typeof(string) })] string ServerAppSecret { get; set; } /// <summary> /// The AAD tenant ID to use for authentication. If not specified, will use the tenant of the deployment subscription. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Info( Required = false, ReadOnly = false, Description = @"The AAD tenant ID to use for authentication. If not specified, will use the tenant of the deployment subscription.", SerializedName = @"tenantID", PossibleTypes = new [] { typeof(string) })] string TenantId { get; set; } } /// AADProfile specifies attributes for Azure Active Directory integration. internal partial interface IManagedClusterAadProfileInternal { /// <summary>AAD group object IDs that will have admin role of the cluster.</summary> string[] AdminGroupObjectID { get; set; } /// <summary>The client AAD application ID.</summary> string ClientAppId { get; set; } /// <summary>Whether to enable Azure RBAC for Kubernetes authorization.</summary> bool? EnableAzureRbac { get; set; } /// <summary>Whether to enable managed AAD.</summary> bool? Managed { get; set; } /// <summary>The server AAD application ID.</summary> string ServerAppId { get; set; } /// <summary>The server AAD application secret.</summary> string ServerAppSecret { get; set; } /// <summary> /// The AAD tenant ID to use for authentication. If not specified, will use the tenant of the deployment subscription. /// </summary> string TenantId { get; set; } } }
52.465409
141
0.657756
[ "MIT" ]
Agazoth/azure-powershell
src/Aks/Aks.Autorest/generated/api/Models/Api20200901/ManagedClusterAadProfile.cs
8,184
C#
using System; using Newtonsoft.Json; namespace Alipay.AopSdk.Core.Domain { /// <summary> /// EduSourceInfo Data Structure. /// </summary> [Serializable] public class EduSourceInfo : AopObject { /// <summary> /// 供应商的LOGO /// </summary> [JsonProperty("logo")] public string Logo { get; set; } /// <summary> /// 供应商电话 /// </summary> [JsonProperty("mobile")] public string Mobile { get; set; } /// <summary> /// 供应商名字 /// </summary> [JsonProperty("name")] public string Name { get; set; } } }
18.166667
39
0.594495
[ "MIT" ]
ArcherTrister/LeXun.Alipay.AopSdk
src/Alipay.AopSdk.Core/Domain/EduSourceInfo.cs
573
C#
using System; using Orleans.Runtime; namespace Orleans.Configuration { /// <summary> /// Settings for cluster membership. /// </summary> public class ClusterMembershipOptions { /// <summary> /// The number of missed "I am alive" updates in the table from a silo that causes warning to be logged. Does not impact the liveness protocol. /// </summary> public int NumMissedTableIAmAliveLimit { get; set; } = DEFAULT_LIVENESS_NUM_TABLE_I_AM_ALIVE_LIMIT; public const int DEFAULT_LIVENESS_NUM_TABLE_I_AM_ALIVE_LIMIT = 2; /// <summary> /// Global switch to disable silo liveness protocol (should be used only for testing). /// The LivenessEnabled attribute, if provided and set to "false", suppresses liveness enforcement. /// If a silo is suspected to be dead, but this attribute is set to "false", the suspicions will not propagated to the system and enforced, /// This parameter is intended for use only for testing and troubleshooting. /// In production, liveness should always be enabled. /// Default is true (enabled) /// </summary> public bool LivenessEnabled { get; set; } = DEFAULT_LIVENESS_ENABLED; public const bool DEFAULT_LIVENESS_ENABLED = true; /// <summary> /// The number of seconds to periodically probe other silos for their liveness or for the silo to send "I am alive" heartbeat messages about itself. /// </summary> public TimeSpan ProbeTimeout { get; set; } = DEFAULT_LIVENESS_PROBE_TIMEOUT; public static readonly TimeSpan DEFAULT_LIVENESS_PROBE_TIMEOUT = TimeSpan.FromSeconds(5); /// <summary> /// The number of seconds to periodically fetch updates from the membership table. /// </summary> public TimeSpan TableRefreshTimeout { get; set; } = DEFAULT_LIVENESS_TABLE_REFRESH_TIMEOUT; public static readonly TimeSpan DEFAULT_LIVENESS_TABLE_REFRESH_TIMEOUT = TimeSpan.FromSeconds(60); /// <summary> /// Expiration time in seconds for death vote in the membership table. /// </summary> public TimeSpan DeathVoteExpirationTimeout { get; set; } = DEFAULT_LIVENESS_DEATH_VOTE_EXPIRATION_TIMEOUT; public static readonly TimeSpan DEFAULT_LIVENESS_DEATH_VOTE_EXPIRATION_TIMEOUT = TimeSpan.FromSeconds(120); /// <summary> /// The number of seconds to periodically write in the membership table that this silo is alive. Used only for diagnostics. /// </summary> public TimeSpan IAmAliveTablePublishTimeout { get; set; } = DEFAULT_LIVENESS_I_AM_ALIVE_TABLE_PUBLISH_TIMEOUT; public static readonly TimeSpan DEFAULT_LIVENESS_I_AM_ALIVE_TABLE_PUBLISH_TIMEOUT = TimeSpan.FromMinutes(5); /// <summary> /// The number of seconds to attempt to join a cluster of silos before giving up. /// </summary> public TimeSpan MaxJoinAttemptTime { get; set; } = DEFAULT_LIVENESS_MAX_JOIN_ATTEMPT_TIME; public static readonly TimeSpan DEFAULT_LIVENESS_MAX_JOIN_ATTEMPT_TIME = TimeSpan.FromMinutes(5); // 5 min /// <summary> /// Whether new silo that joins the cluster has to validate the initial connectivity with all other Active silos. /// </summary> public bool ValidateInitialConnectivity { get; set; } = DEFAULT_VALIDATE_INITIAL_CONNECTIVITY; public const bool DEFAULT_VALIDATE_INITIAL_CONNECTIVITY = true; /// <summary> /// Whether to use the gossip optimization to speed up spreading liveness information. /// </summary> public bool UseLivenessGossip { get; set; } = DEFAULT_LIVENESS_USE_LIVENESS_GOSSIP; public const bool DEFAULT_LIVENESS_USE_LIVENESS_GOSSIP = true; /// <summary> /// The number of silos each silo probes for liveness. /// </summary> public int NumProbedSilos { get; set; } = DEFAULT_LIVENESS_NUM_PROBED_SILOS; public const int DEFAULT_LIVENESS_NUM_PROBED_SILOS = 3; /// <summary> /// The number of missed "I am alive" heartbeat messages from a silo or number of un-replied probes that lead to suspecting this silo as dead. /// </summary> public int NumMissedProbesLimit { get; set; } = DEFAULT_LIVENESS_NUM_MISSED_PROBES_LIMIT; public const int DEFAULT_LIVENESS_NUM_MISSED_PROBES_LIMIT = 3; /// <summary> /// The number of non-expired votes that are needed to declare some silo as dead (should be at most NumMissedProbesLimit) /// </summary> public int NumVotesForDeathDeclaration { get; set; } = DEFAULT_LIVENESS_NUM_VOTES_FOR_DEATH_DECLARATION; public const int DEFAULT_LIVENESS_NUM_VOTES_FOR_DEATH_DECLARATION = 2; /// <summary> /// The period of time after which membership entries for defunct silos are eligible for removal. /// Valid only if <see cref="DefunctSiloCleanupPeriod"/> is not <see langword="null" />. /// </summary> public TimeSpan DefunctSiloExpiration { get; set; } = DEFAULT_DEFUNCT_SILO_EXPIRATION; public static readonly TimeSpan DEFAULT_DEFUNCT_SILO_EXPIRATION = TimeSpan.FromDays(7); /// <summary> /// The duration between membership table cleanup operations. When this period elapses, all defunct silo /// entries older than <see cref="DefunctSiloExpiration" /> are removed. This value is per-silo. /// </summary> public TimeSpan? DefunctSiloCleanupPeriod { get; set; } = DEFAULT_DEFUNCT_SILO_CLEANUP_PERIOD; public static readonly TimeSpan? DEFAULT_DEFUNCT_SILO_CLEANUP_PERIOD = null; /// <summary> /// TEST ONLY - Do not modify in production environments /// </summary> public bool IsRunningAsUnitTest { get; set; } = false; internal TimeSpan AllowedIAmAliveMissPeriod => this.IAmAliveTablePublishTimeout.Multiply(this.NumMissedTableIAmAliveLimit); } }
54.153153
157
0.693063
[ "MIT" ]
DamirAinullin/orleans
src/Orleans.Core/Configuration/Options/ClusterMembershipOptions.cs
6,011
C#
using System; using System.Threading; using System.Threading.Tasks; using Dfc.CourseDirectory.Core.DataStore.Sql; using Dfc.CourseDirectory.Core.DataStore.Sql.Queries; using Dfc.CourseDirectory.Core.Validation; using Dfc.CourseDirectory.WebV2.Security; using MediatR; using OneOf; using OneOf.Types; namespace Dfc.CourseDirectory.WebV2.Features.HidePassedNotification { using CommandResponse = OneOf<ModelWithErrors<CommandViewModel>, Success>; public class Command : IRequest<CommandResponse> { public Guid ProviderId { get; set; } } public class CommandViewModel : Command { } public class CommandHandler : IRequestHandler<Command, CommandResponse> { private readonly ISqlQueryDispatcher _sqlQueryDispatcher; private readonly ICurrentUserProvider _currentUserProvider; public CommandHandler( ISqlQueryDispatcher sqlQueryDispatcher, ICurrentUserProvider currentUserProvider) { _sqlQueryDispatcher = sqlQueryDispatcher; _currentUserProvider = currentUserProvider; } public async Task<CommandResponse> Handle( Command request, CancellationToken cancellationToken) { var currentUser = _currentUserProvider.GetCurrentUser(); if (currentUser.IsHelpdesk) { throw new NotAuthorizedException(); } var latestSubmission = await _sqlQueryDispatcher.ExecuteQuery( new GetLatestApprenticeshipQASubmissionForProvider() { ProviderId = request.ProviderId }); if (latestSubmission == null) { throw new InvalidStateException(InvalidStateReason.InvalidApprenticeshipQASubmission); } // Cannot hide passed notification if qa status is not passed if (latestSubmission.Passed != true) { throw new InvalidStateException(InvalidStateReason.InvalidApprenticeshipQAStatus); } // Cannot hide notification if it has already been hidden if (latestSubmission.HidePassedNotification) { throw new InvalidStateException(); } // Hide notification await _sqlQueryDispatcher.ExecuteQuery( new UpdateHidePassedNotification() { ApprenticeshipQASubmissionId = latestSubmission.ApprenticeshipQASubmissionId, HidePassedNotification = true }); return new Success(); } } }
32.240964
102
0.636024
[ "MIT" ]
uk-gov-mirror/SkillsFundingAgency.dfc-coursedirectory
src/Dfc.CourseDirectory.WebV2/Features/NewApprenticeshipProvider/HidePassedNotification.cs
2,678
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; namespace Bunit.Docs.Samples { public class UnmatchedParams : ComponentBase { [Parameter(CaptureUnmatchedValues = true)] public Dictionary<string, object> InputAttributes { get; set; } } }
25.466667
67
0.782723
[ "MIT" ]
Christian-Oleson/bUn
docs/samples/components/UnmatchedParams.cs
382
C#
using Xamarin.Forms.CustomAttributes; using Xamarin.Forms.Internals; #if UITEST using Xamarin.UITest; using NUnit.Framework; using Xamarin.Forms.Core.UITests; #endif namespace Xamarin.Forms.Controls.Issues { #if UITEST [Category(UITestCategories.Frame)] #endif [Preserve(AllMembers = true)] [Issue(IssueTracker.Github, 0, "[Bug] Frame Background not working", PlatformAffected.Android)] public partial class FrameBackgroundIssue : TestContentPage { public FrameBackgroundIssue() { #if APP InitializeComponent(); #endif } protected override void Init() { } } }
18.375
60
0.755102
[ "MIT" ]
AlleSchonWeg/Xamarin.Forms
Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/FrameBackgroundIssue.xaml.cs
590
C#
namespace PWOProtocol { public class Pokemon { public int Uid { get; private set; } public int PokedexId { get; private set; } public int Level { get; private set; } public int CurrentExperience { get; private set; } public int RequiredExperience { get; private set; } public int MaximumHealth { get; private set; } public int CurrentHealth { get; private set; } private string _status; public string Status { get { return CurrentHealth == 0 ? "KO" : _status; } set { _status = value; } } public string Name { get { return PokemonNamesManager.Instance.Names[PokedexId]; } } public string Health { get { return CurrentHealth + "/" + MaximumHealth; } } public string Experience { get { return CurrentExperience + "/" + RequiredExperience; } } public PokemonMove[] Moves { get; private set; } = new PokemonMove[4]; public Pokemon(string[] data) { Uid = int.Parse(data[0]); PokedexId = int.Parse(data[1]); Level = int.Parse(data[3]); Status = data[4]; MaximumHealth = int.Parse(data[5]); CurrentHealth = int.Parse(data[6]); CurrentExperience = int.Parse(data[42]); RequiredExperience = int.Parse(data[43]); Moves[0] = new PokemonMove(data, 7); Moves[1] = new PokemonMove(data, 14); Moves[2] = new PokemonMove(data, 21); Moves[3] = new PokemonMove(data, 28); } public void UpdateHealth(int max, int current) { MaximumHealth = max; CurrentHealth = current; } } }
28.57971
79
0.492901
[ "MIT" ]
Silv3rPRO/pwosparkle
PWOProtocol/Pokemon.cs
1,974
C#
namespace Microsoft.MOM.Test.Operations.MOMSP1Inst.MAUIDialogs { using Maui.Core; using Maui.Core.WinControls; using Maui.Core.Utilities; using System.ComponentModel; public class IncompleteInstallationDetectedDialogNotFoundException : Window.Exceptions.WindowNotFoundException { public IncompleteInstallationDetectedDialogNotFoundException(string message): base(message) { } } #region "IIncompleteInstallationDetectedDialogControls interface definition" [EditorBrowsable(EditorBrowsableState.Never)] internal interface IIncompleteInstallationDetectedDialogControls { Button ExitButton {get;} Button ContinueButton {get;} Button RebootButton {get;} TextBox PendingFileRenameInformationTextBox {get;} StaticControl PendingFileRenameInformationStaticControl {get;} StaticControl SetupDetectedThatThereArePendingFileRenameOperationsForMOMSDK01ELockedSystemFilesAreWaitingToBeReplaStaticControl {get;} } #endregion /// ----------------------------------------------------------------------------- /// Project : Maui /// Class : IncompleteInstallationDetectedDialog /// Copyright (C) 2002, oration /// ----------------------------------------------------------------------------- /// <summary> /// TODO: Add dialog functionality description here. /// </summary> /// <remarks></remarks> /// <history> /// [asttest] 8/13/2003 Created /// </history> /// ----------------------------------------------------------------------------- internal class IncompleteInstallationDetectedDialog : Dialog, IIncompleteInstallationDetectedDialogControls { #region "Strings" // TODO: Remove unused definitions. internal class Strings { internal const string DialogTitle = "Incomplete Installation Detected"; internal const string Exit = "&Exit"; internal const string Continue = "&Continue"; internal const string Reboot = "&Reboot"; internal const string PendingFileRenameInformation = "Pending File Rename Information"; internal const string SetupDetectedThatThereArePendingFileRenameOperationsForMOMSDK01ELockedSystemFilesAreWaitingToBeRepla = "Setup detected that there are Pending File Rename Operations for MOMSDK01E. Locke" + "d system files are waiting to be replaced on reboot, probably because a previous" + " installation program needed to replace a file that was locked. \r\n\r\nWe strongly" + " recommend tha"; } #endregion #region "Control IDs" internal class ControlIDs { internal const int ExitButton = 0x3; internal const int ContinueButton = 0x4; internal const int RebootButton = 0x5; internal const int PendingFileRenameInformationTextBox = 0x6; internal const int PendingFileRenameInformationStaticControl = 0x7; internal const int SetupDetectedThatThereArePendingFileRenameOperationsForMOMSDK01ELockedSystemFilesAreWaitingToBeReplaStaticControl = 0x8; } #endregion #region "Member Variables" protected Button m_cachedExitButton; protected Button m_cachedContinueButton; protected Button m_cachedRebootButton; protected TextBox m_cachedPendingFileRenameInformationTextBox; protected StaticControl m_cachedPendingFileRenameInformationStaticControl; protected StaticControl m_cachedSetupDetectedThatThereArePendingFileRenameOperationsForMOMSDK01ELockedSystemFilesAreWaitingToBeReplaStaticControl; #endregion #region "Constructor and Init function" /// ----------------------------------------------------------------------------- /// <summary> /// TODO: Add a description for your constructor. /// </summary> /// <param name="app">App object owning the dialog.</param> /// <history> /// [asttest] 8/13/2003 Created /// </history> /// ----------------------------------------------------------------------------- internal IncompleteInstallationDetectedDialog(App app) : base(app, Init(app)) { // TODO: Add Constructor logic here. } /// ----------------------------------------------------------------------------- /// <summary> /// This function will attempt to find a showing instance of the dialog. /// </summary> /// <returns>The dialog's Window</returns> /// <param name="app">App owning the dialog.</param>) /// <history> /// [asttest] 8/13/2003 Created /// </history> /// ----------------------------------------------------------------------------- private static Window Init(App app) { // First check if the dialog is already up. Window tempWindow = null; try { tempWindow = new Window(Strings.DialogTitle, StringMatchSyntax.ExactMatch, WindowClassNames.Alert, StringMatchSyntax.ExactMatch, app, 3000); } catch (Exceptions.WindowNotFoundException) { throw new IncompleteInstallationDetectedDialogNotFoundException("Incomplete Installation Detected Dialog not found"); } return tempWindow; } #endregion #region "Properties" /// ----------------------------------------------------------------------------- /// <summary> /// Exposes access to the raw controls for this dialog /// </summary> /// <value>An interface that groups all of the dialog's control properties together</value> /// <remarks></remarks> /// <history> /// [asttest] 8/13/2003 Created /// </history> /// ----------------------------------------------------------------------------- internal virtual IIncompleteInstallationDetectedDialogControls Controls { get { return this; } } /// ----------------------------------------------------------------------------- /// <summary> /// Routine to set/get the text in control PendingFileRenameInformation /// </summary> /// <remarks></remarks> /// <history> /// [asttest] 8/13/2003 Created /// </history> /// ----------------------------------------------------------------------------- internal virtual string PendingFileRenameInformationText { get { return Controls.PendingFileRenameInformationTextBox.Text; } set { Controls.PendingFileRenameInformationTextBox.Text = value; } } /// ----------------------------------------------------------------------------- /// <summary> /// Exposes access to the ExitButton control /// </summary> /// <value></value> /// <remarks></remarks> /// <history> /// [asttest] 8/13/2003 Created /// </history> /// ----------------------------------------------------------------------------- Button IIncompleteInstallationDetectedDialogControls.ExitButton { get { if ((m_cachedExitButton == null)) { m_cachedExitButton = new Button(this, ControlIDs.ExitButton); } return m_cachedExitButton; } } /// ----------------------------------------------------------------------------- /// <summary> /// Exposes access to the ContinueButton control /// </summary> /// <value></value> /// <remarks></remarks> /// <history> /// [asttest] 8/13/2003 Created /// </history> /// ----------------------------------------------------------------------------- Button IIncompleteInstallationDetectedDialogControls.ContinueButton { get { if ((m_cachedContinueButton == null)) { m_cachedContinueButton = new Button(this, ControlIDs.ContinueButton); } return m_cachedContinueButton; } } /// ----------------------------------------------------------------------------- /// <summary> /// Exposes access to the RebootButton control /// </summary> /// <value></value> /// <remarks></remarks> /// <history> /// [asttest] 8/13/2003 Created /// </history> /// ----------------------------------------------------------------------------- Button IIncompleteInstallationDetectedDialogControls.RebootButton { get { if ((m_cachedRebootButton == null)) { m_cachedRebootButton = new Button(this, ControlIDs.RebootButton); } return m_cachedRebootButton; } } /// ----------------------------------------------------------------------------- /// <summary> /// Exposes access to the PendingFileRenameInformationTextBox control /// </summary> /// <value></value> /// <remarks></remarks> /// <history> /// [asttest] 8/13/2003 Created /// </history> /// ----------------------------------------------------------------------------- TextBox IIncompleteInstallationDetectedDialogControls.PendingFileRenameInformationTextBox { get { if ((m_cachedPendingFileRenameInformationTextBox == null)) { m_cachedPendingFileRenameInformationTextBox = new TextBox(this, ControlIDs.PendingFileRenameInformationTextBox); } return m_cachedPendingFileRenameInformationTextBox; } } /// ----------------------------------------------------------------------------- /// <summary> /// Exposes access to the PendingFileRenameInformationStaticControl control /// </summary> /// <value></value> /// <remarks></remarks> /// <history> /// [asttest] 8/13/2003 Created /// </history> /// ----------------------------------------------------------------------------- StaticControl IIncompleteInstallationDetectedDialogControls.PendingFileRenameInformationStaticControl { get { if ((m_cachedPendingFileRenameInformationStaticControl == null)) { m_cachedPendingFileRenameInformationStaticControl = new StaticControl(this, ControlIDs.PendingFileRenameInformationStaticControl); } return m_cachedPendingFileRenameInformationStaticControl; } } /// ----------------------------------------------------------------------------- /// <summary> /// Exposes access to the SetupDetectedThatThereArePendingFileRenameOperationsForMOMSDK01ELockedSystemFilesAreWaitingToBeReplaStaticControl control /// </summary> /// <value></value> /// <remarks></remarks> /// <history> /// [asttest] 8/13/2003 Created /// </history> /// ----------------------------------------------------------------------------- StaticControl IIncompleteInstallationDetectedDialogControls.SetupDetectedThatThereArePendingFileRenameOperationsForMOMSDK01ELockedSystemFilesAreWaitingToBeReplaStaticControl { get { if ((m_cachedSetupDetectedThatThereArePendingFileRenameOperationsForMOMSDK01ELockedSystemFilesAreWaitingToBeReplaStaticControl == null)) { m_cachedSetupDetectedThatThereArePendingFileRenameOperationsForMOMSDK01ELockedSystemFilesAreWaitingToBeReplaStaticControl = new StaticControl(this, ControlIDs.SetupDetectedThatThereArePendingFileRenameOperationsForMOMSDK01ELockedSystemFilesAreWaitingToBeReplaStaticControl); } return m_cachedSetupDetectedThatThereArePendingFileRenameOperationsForMOMSDK01ELockedSystemFilesAreWaitingToBeReplaStaticControl; } } #endregion #region "Methods" /// ----------------------------------------------------------------------------- /// <summary> /// Routine to click on button Exit /// </summary> /// <remarks></remarks> /// <history> /// [asttest] 8/13/2003 Created /// </history> /// ----------------------------------------------------------------------------- internal virtual void ClickExit() { Controls.ExitButton.Click(); } /// ----------------------------------------------------------------------------- /// <summary> /// Routine to click on button Continue /// </summary> /// <remarks></remarks> /// <history> /// [asttest] 8/13/2003 Created /// </history> /// ----------------------------------------------------------------------------- internal virtual void ClickContinue() { Controls.ContinueButton.Click(); } /// ----------------------------------------------------------------------------- /// <summary> /// Routine to click on button Reboot /// </summary> /// <remarks></remarks> /// <history> /// [asttest] 8/13/2003 Created /// </history> /// ----------------------------------------------------------------------------- internal virtual void ClickReboot() { Controls.RebootButton.Click(); } #endregion } }
39.826331
294
0.490013
[ "MIT" ]
deusletum/MiyVeryOldCode
csharp/Inst_MOMSP1/MOMSP1Inst/IncompleteInstallationDetectedDialog.cs
14,218
C#
using System; using System.Collections.Generic; using Grynwald.ChangeLog.Git; using Octokit; using Xunit; namespace Grynwald.ChangeLog.Test.Git { /// <summary> /// Tests for <see cref="GitCommit"/> /// </summary> public class GitCommitTest : EqualityTest<GitCommit, GitCommitTest>, IEqualityTestDataProvider<GitCommit> { public IEnumerable<(GitCommit left, GitCommit right)> GetEqualTestCases() { yield return ( new GitCommit( TestGitIds.Id1, "Commit Message", new DateTime(2020, 01, 01), new GitAuthor("user", "user@example.com")), new GitCommit( TestGitIds.Id1, "Commit Message", new DateTime(2020, 01, 01), new GitAuthor("user", "user@example.com")) ); } public IEnumerable<(GitCommit left, GitCommit right)> GetUnequalTestCases() { yield return ( new GitCommit( TestGitIds.Id1, "Commit Message", new DateTime(2020, 01, 01), new GitAuthor("user", "user@example.com")), new GitCommit( TestGitIds.Id2, "Commit Message", new DateTime(2020, 01, 01), new GitAuthor("user", "user@example.com")) ); yield return ( new GitCommit( TestGitIds.Id1, "Commit Message", new DateTime(2020, 01, 01), new GitAuthor("user", "user@example.com")), new GitCommit( TestGitIds.Id1, "Some other Commit Message", new DateTime(2020, 01, 01), new GitAuthor("user", "user@example.com")) ); yield return ( new GitCommit( TestGitIds.Id1, "Commit Message", new DateTime(2020, 01, 01), new GitAuthor("user", "user@example.com")), new GitCommit( TestGitIds.Id1, "Commit Message", new DateTime(2019, 01, 01), new GitAuthor("user", "user@example.com")) ); yield return ( new GitCommit( TestGitIds.Id1, "Commit Message", new DateTime(2020, 01, 01), new GitAuthor("user", "user@example.com")), new GitCommit( TestGitIds.Id1, "Commit Message", new DateTime(2020, 01, 01), new GitAuthor("user2", "user@example.net")) ); } [Fact] public void Commit_id_must_not_be_null() { // ARRANGE var id = default(GitId); // ACT var ex = Record.Exception(() => new GitCommit(id, "Some Message", DateTime.Now, new GitAuthor("user", "user@example.com"))); // ASSERT Assert.NotNull(ex); var argumentException = Assert.IsType<ArgumentException>(ex); Assert.Equal("id", argumentException.ParamName); } } }
34.4
136
0.457267
[ "MIT" ]
ap0llo/changelo
src/ChangeLog.Test/Git/GitCommitTest.cs
3,442
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 ivs-2020-07-14.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.IVS.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.IVS.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for InternalServerException Object /// </summary> public class InternalServerExceptionUnmarshaller : IErrorResponseUnmarshaller<InternalServerException, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public InternalServerException Unmarshall(JsonUnmarshallerContext context) { return this.Unmarshall(context, new ErrorResponse()); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <param name="errorResponse"></param> /// <returns></returns> public InternalServerException Unmarshall(JsonUnmarshallerContext context, ErrorResponse errorResponse) { context.Read(); InternalServerException unmarshalledObject = new InternalServerException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("exceptionMessage", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ExceptionMessage = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static InternalServerExceptionUnmarshaller _instance = new InternalServerExceptionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static InternalServerExceptionUnmarshaller Instance { get { return _instance; } } } }
35.571429
137
0.655236
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/IVS/Generated/Model/Internal/MarshallTransformations/InternalServerExceptionUnmarshaller.cs
3,237
C#
using System.ComponentModel.DataAnnotations; using Yotalab.PlanningPoker.BlazorServerSide.Areas.Identity.Resources; namespace Yotalab.PlanningPoker.BlazorServerSide.Areas.Identity.Data { public class LoginInputModel { [Required(ErrorMessageResourceName = nameof(DataAnnotationResources.EmailRequired), ErrorMessageResourceType = typeof(DataAnnotationResources))] [EmailAddress(ErrorMessageResourceName = nameof(DataAnnotationResources.EmailInvalid), ErrorMessageResourceType = typeof(DataAnnotationResources))] [Display(Name = nameof(DataAnnotationResources.EmailLabel), ResourceType = typeof(DataAnnotationResources))] [DataType(DataType.EmailAddress)] public string Email { get; set; } [Required(ErrorMessageResourceName = nameof(DataAnnotationResources.PasswordRequired), ErrorMessageResourceType = typeof(DataAnnotationResources))] [Display(Name = nameof(DataAnnotationResources.PasswordLabel), ResourceType = typeof(DataAnnotationResources))] [DataType(DataType.Password)] public string Password { get; set; } [Display(Name = nameof(DataAnnotationResources.RememberMeLabel), ResourceType = typeof(DataAnnotationResources))] public bool RememberMe { get; set; } } }
53.217391
151
0.805556
[ "MIT" ]
DirectumCompany/Yotalab.PlanningPoker
Yotalab.PlanningPoker.BlazorServerSide/Areas/Identity/Data/LoginInputModel.cs
1,226
C#
using Elastic.Xunit.XunitPlumbing; using Nest; namespace Examples.Ml.AnomalyDetection.Apis { public class PutCalendarJobPage : ExampleBase { [U(Skip = "Example not implemented")] public void Line37() { // tag::1b2ab75d3c8064fac6ecc63104396c02[] var response0 = new SearchResponse<object>(); // end::1b2ab75d3c8064fac6ecc63104396c02[] response0.MatchesExample(@"PUT _ml/calendars/planned-outages/jobs/total-requests"); } } }
24.888889
86
0.745536
[ "Apache-2.0" ]
AnthAbou/elasticsearch-net
src/Examples/Examples/Ml/AnomalyDetection/Apis/PutCalendarJobPage.cs
448
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Luaan.AutoPoke { public class PageInfo { public long PageStart { get; set; } public long PageEnd { get; set; } } }
15.714286
37
0.722727
[ "MIT" ]
Luaancz/AutoPoke
AutoPoke/PageInfo.cs
222
C#
using System.Runtime.CompilerServices; using PowerUtils.Validations.Exceptions; namespace PowerUtils.Validations.GuardClauses { public static class GuardValidationUIntExtensions { /// <summary> /// Throws an <see cref="PropertyException" /> if <paramref name="value"/> is greater than. Error code 'MAX:{X}' /// </summary> /// <param name="_"></param> /// <param name="value">Value to validate</param> /// <param name="max">Max value</param> /// <param name="parameterName">If not defined, the name of the variable passed by the <paramref name="value"/> parameter will be used</param> /// <exception cref="PropertyException">Exception thrown when the value is greater than</exception> public static uint IfGreaterThan( this IGuardValidationClause _, uint value, uint max, [CallerArgumentExpression("value")] string parameterName = null ) { if(value > max) { throw new PropertyException(parameterName, ErrorCodes.GetMaxFormatted(max)); } return value; } /// <summary> /// Throws an <see cref="PropertyException" /> if <paramref name="value"/> is greater than. Error code 'MAX:{X}' /// </summary> /// <param name="_"></param> /// <param name="value">Value to validate</param> /// <param name="max">Max value</param> /// <param name="parameterName">If not defined, the name of the variable passed by the <paramref name="value"/> parameter will be used</param> /// <exception cref="PropertyException">Exception thrown when the value is greater than</exception> public static uint? IfGreaterThan( this IGuardValidationClause _, uint? value, uint max, [CallerArgumentExpression("value")] string parameterName = null ) { if(value > max) { throw new PropertyException(parameterName, ErrorCodes.GetMaxFormatted(max)); } return value; } /// <summary> /// Throws an <see cref="PropertyException" /> if <paramref name="value"/> is less than. Error code 'MIN:{X}' /// </summary> /// <param name="_"></param> /// <param name="value">Value to validate</param> /// <param name="min">Min value</param> /// <param name="parameterName">If not defined, the name of the variable passed by the <paramref name="value"/> parameter will be used</param> /// <exception cref="PropertyException">Exception thrown when value is less than</exception> public static uint IfLessThan( this IGuardValidationClause _, uint value, uint min, [CallerArgumentExpression("value")] string parameterName = null ) { if(value < min) { throw new PropertyException(parameterName, ErrorCodes.GetMinFormatted(min)); } return value; } /// <summary> /// Throws an <see cref="PropertyException" /> if <paramref name="value"/> is less than. Error code 'MIN:{X}' /// </summary> /// <param name="_"></param> /// <param name="value">Value to validate</param> /// <param name="min">Min value</param> /// <param name="parameterName">If not defined, the name of the variable passed by the <paramref name="value"/> parameter will be used</param> /// <exception cref="PropertyException">Exception thrown when value is less than</exception> public static uint? IfLessThan( this IGuardValidationClause _, uint? value, uint min, [CallerArgumentExpression("value")] string parameterName = null ) { if(value < min) { throw new PropertyException(parameterName, ErrorCodes.GetMinFormatted(min)); } return value; } /// <summary> /// Throws an <see cref="PropertyException" /> if <paramref name="value"/> is equals to other value. Error code 'INVALID' /// </summary> /// <param name="_"></param> /// <param name="value">Value to validate</param> /// <param name="otherValue">Reference value for comparison</param> /// <param name="parameterName">If not defined, the name of the variable passed by the <paramref name="value"/> parameter will be used</param> /// <exception cref="PropertyException">Exception thrown when value is equals to the other value</exception> public static uint? IfEquals( this IGuardValidationClause _, uint? value, uint otherValue, [CallerArgumentExpression("value")] string parameterName = null ) { if(value == otherValue) { throw new PropertyException(parameterName, ErrorCodes.INVALID); } return value; } /// <summary> /// Throws an <see cref="PropertyException" /> if <paramref name="value"/> is different to other value. Error code 'INVALID' /// </summary> /// <param name="_"></param> /// <param name="value">Value to validate</param> /// <param name="otherValue">Reference value for comparison</param> /// <param name="parameterName">If not defined, the name of the variable passed by the <paramref name="value"/> parameter will be used</param> /// <exception cref="PropertyException">Exception thrown when value is different to the other value</exception> public static uint? IfDifferent( this IGuardValidationClause _, uint? value, uint otherValue, [CallerArgumentExpression("value")] string parameterName = null ) { if(value != otherValue) { throw new PropertyException(parameterName, ErrorCodes.INVALID); } return value; } /// <summary> /// Throws an <see cref="PropertyException" /> if <paramref name="value"/> out of range. Error code 'MIN:{X}' or 'MAX:{X}' /// </summary> /// <param name="_"></param> /// <param name="value">Value to validate</param> /// <param name="min">Min value</param> /// <param name="max">Max value</param> /// <param name="parameterName">If not defined, the name of the variable passed by the <paramref name="value"/> parameter will be used</param> /// <exception cref="PropertyException">Exception thrown when the value is out of range</exception> public static float? IfOutOfRange( this IGuardValidationClause _, uint? value, uint min, uint max, [CallerArgumentExpression("value")] string parameterName = null ) { if(value < min) { throw new PropertyException(parameterName, ErrorCodes.GetMinFormatted(min)); } if(value > max) { throw new PropertyException(parameterName, ErrorCodes.GetMaxFormatted(max)); } return value; } } }
41.016667
150
0.577272
[ "MIT" ]
TechNobre/PowerUtils.GuardClauses.Validations
src/GuardClauses/GuardValidationUIntExtensions.cs
7,385
C#
#region Header Licence // --------------------------------------------------------------------- // // Copyright (c) 2009 Alexandre Mutel and Microsoft Corporation. // All rights reserved. // // This code module is part of NShader, a plugin for visual studio // to provide syntax highlighting for shader languages (hlsl, glsl, cg) // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://nshader.codeplex.com // // ------------------------------------------------------------------ #endregion using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Drawing; using EnvDTE80; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Package; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Formatting; using Microsoft.VisualStudio.TextManager.Interop; using Stride.VisualStudio.Classifiers; using Stride.VisualStudio.Commands; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; using VsShell = Microsoft.VisualStudio.Shell.VsShellUtilities; using Task = System.Threading.Tasks.Task; using EnvDTE; using Stride.VisualStudio; using Stride.VisualStudio.Commands.Shaders; namespace NShader { public class NShaderLanguageService : LanguageService { private VisualStudioThemeEngine themeEngine; private NShaderColorableItem[] m_colorableItems; private readonly ErrorListProvider errorListProvider; private LanguagePreferences m_preferences; private int lastChangeCount = -1; private readonly Stopwatch clock; private const int TriggerParsingDelayInMs = 1000; // Parse after 1s of inactivity and a change in source code public NShaderLanguageService(ErrorListProvider errorListProvider) { this.errorListProvider = errorListProvider; clock = new Stopwatch(); } public void InitializeColors() { // Check if already initialized if (m_colorableItems != null) return; // Initialize theme engine themeEngine = new VisualStudioThemeEngine(Site); themeEngine.OnThemeChanged += themeEngine_OnThemeChanged; var currentTheme = themeEngine.GetCurrentTheme(); m_colorableItems = new NShaderColorableItem[] { /*1*/ new NShaderColorableItem(currentTheme, "Stride.ShaderLanguage.Keyword", "Stride Shader Language - Keyword", COLORINDEX.CI_BLUE, COLORINDEX.CI_AQUAMARINE, COLORINDEX.CI_USERTEXT_BK, Color.Empty, Color.FromArgb(86, 156, 214), Color.Empty, FONTFLAGS.FF_DEFAULT), /*2*/ new NShaderColorableItem(currentTheme, "Stride.ShaderLanguage.Comment", "Stride Shader Language - Comment", COLORINDEX.CI_DARKGREEN, COLORINDEX.CI_GREEN, COLORINDEX.CI_USERTEXT_BK, Color.Empty, Color.FromArgb(87, 166, 74), Color.Empty, FONTFLAGS.FF_DEFAULT), /*3*/ new NShaderColorableItem(currentTheme, "Stride.ShaderLanguage.Identifier", "Stride Shader Language - Identifier", COLORINDEX.CI_SYSPLAINTEXT_FG, COLORINDEX.CI_SYSPLAINTEXT_FG, COLORINDEX.CI_USERTEXT_BK, FONTFLAGS.FF_DEFAULT), /*4*/ new NShaderColorableItem(currentTheme, "Stride.ShaderLanguage.String", "Stride Shader Language - String", COLORINDEX.CI_RED, COLORINDEX.CI_RED, COLORINDEX.CI_USERTEXT_BK, Color.Empty, Color.FromArgb(214, 157, 133), Color.Empty, FONTFLAGS.FF_DEFAULT), /*5*/ new NShaderColorableItem(currentTheme, "Stride.ShaderLanguage.Number", "Stride Shader Language - Number", COLORINDEX.CI_DARKBLUE, COLORINDEX.CI_BLUE, COLORINDEX.CI_USERTEXT_BK, Color.Empty, Color.FromArgb(181, 206, 168), Color.Empty, FONTFLAGS.FF_DEFAULT), /*6*/ new NShaderColorableItem(currentTheme, "Stride.ShaderLanguage.Intrinsic", "Stride Shader Language - Intrinsic", COLORINDEX.CI_MAROON, COLORINDEX.CI_CYAN, COLORINDEX.CI_USERTEXT_BK, Color.Empty, Color.FromArgb(239, 242, 132), Color.Empty, FONTFLAGS.FF_BOLD), /*7*/ new NShaderColorableItem(currentTheme, "Stride.ShaderLanguage.Special", "Stride Shader Language - Special", COLORINDEX.CI_AQUAMARINE, COLORINDEX.CI_MAGENTA, COLORINDEX.CI_USERTEXT_BK, Color.Empty, Color.FromArgb(78, 201, 176), Color.Empty, FONTFLAGS.FF_DEFAULT), /*8*/ new NShaderColorableItem(currentTheme, "Stride.ShaderLanguage.Preprocessor", "Stride Shader Language - Preprocessor", COLORINDEX.CI_DARKGRAY, COLORINDEX.CI_LIGHTGRAY, COLORINDEX.CI_USERTEXT_BK, Color.Empty, Color.FromArgb(155, 155, 155), Color.Empty, FONTFLAGS.FF_DEFAULT), }; } public override void Dispose() { themeEngine.OnThemeChanged -= themeEngine_OnThemeChanged; themeEngine.Dispose(); base.Dispose(); } public override ViewFilter CreateViewFilter(CodeWindowManager mgr, IVsTextView newView) { return new NShaderViewFilter(this, mgr, newView); } void themeEngine_OnThemeChanged(object sender, EventArgs e) { var colorUtilities = Site.GetService(typeof(SVsFontAndColorStorage)) as IVsFontAndColorUtilities; var currentTheme = themeEngine.GetCurrentTheme(); var isDarkTheme = currentTheme == VisualStudioTheme.Dark || currentTheme == VisualStudioTheme.UnknownDark; var store = Package.GetGlobalService(typeof(SVsFontAndColorStorage)) as IVsFontAndColorStorage; if (store == null) return; if (store.OpenCategory(DefGuidList.guidTextEditorFontCategory, (uint)(__FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_PROPAGATECHANGES)) != VSConstants.S_OK) return; try { // Update each colorable item foreach (var colorableItem in m_colorableItems) { string canonicalName; var colorInfos = new ColorableItemInfo[1]; if (colorableItem.GetCanonicalName(out canonicalName) == VSConstants.S_OK && store.GetItem(canonicalName, colorInfos) == VSConstants.S_OK) { // Get new color var hiColor = isDarkTheme ? colorableItem.HiForeColorDark : colorableItem.HiForeColorLight; var colorIndex = isDarkTheme ? colorableItem.ForeColorDark : colorableItem.ForeColorLight; if (hiColor != Color.Empty) colorInfos[0].crForeground = hiColor.R | ((uint)hiColor.G << 8) | ((uint)hiColor.B << 16); else colorUtilities.EncodeIndexedColor(colorIndex, out colorInfos[0].crForeground); // Update color in settings store.SetItem(canonicalName, colorInfos); } } } finally { store.CloseCategory(); } } public override int GetItemCount(out int count) { count = m_colorableItems.Length; return VSConstants.S_OK; } public override int GetColorableItem(int index, out IVsColorableItem item) { if (index < 1) { throw new ArgumentOutOfRangeException("index"); } item = m_colorableItems[index-1]; return VSConstants.S_OK; } public override LanguagePreferences GetLanguagePreferences() { if (m_preferences == null) { m_preferences = new LanguagePreferences(this.Site, typeof(NShaderLanguageService).GUID, this.Name); m_preferences.Init(); } return m_preferences; } public override IScanner GetScanner(IVsTextLines buffer) { string filePath = FilePathUtilities.GetFilePath(buffer); // Return dynamic scanner based on file extension return NShaderScannerFactory.GetShaderScanner(filePath); } public override Source CreateSource(IVsTextLines buffer) { return new NShaderSource(this, buffer, GetColorizer(buffer)); } public override Colorizer GetColorizer(IVsTextLines buffer) { // Clear font cache // http://social.msdn.microsoft.com/Forums/office/en-US/54064c52-727d-4015-af70-c72e44d116a7/vs2012-fontandcolors-text-editor-category-for-language-service-colors?forum=vsx IVsFontAndColorStorage storage; Guid textMgrIID = new Guid( //#if VISUALSTUDIO_11_0 "{E0187991-B458-4F7E-8CA9-42C9A573B56C}" /* 'Text Editor Language Services Items' category discovered in the registry. Resetting TextEditor has no effect. */ //#else // FontsAndColorsCategory.TextEditor //#endif ); if (null != (storage = GetService(typeof(IVsFontAndColorStorage)) as IVsFontAndColorStorage) && VSConstants.S_OK == storage.OpenCategory(ref textMgrIID, (uint)(__FCSTORAGEFLAGS.FCSF_READONLY | __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS))) { bool missingColor = false; try { ColorableItemInfo[] info = new ColorableItemInfo[1]; for (int i = 0; i < m_colorableItems.Length; ++i) { string colorName; m_colorableItems[i].GetDisplayName(out colorName); if (ErrorHandler.Failed(storage.GetItem(colorName, info))) { missingColor = true; break; } } } finally { storage.CloseCategory(); } if (missingColor) { IOleServiceProvider oleProvider; // The service and interface guids are different, so we need to go to the OLE layer to get the service Guid iid = typeof(IVsFontAndColorCacheManager).GUID; Guid sid = typeof(SVsFontAndColorCacheManager).GUID; IntPtr pCacheManager; if (null != (oleProvider = GetService(typeof(IOleServiceProvider)) as IOleServiceProvider) && VSConstants.S_OK == oleProvider.QueryService(ref sid, ref iid, out pCacheManager) && pCacheManager != IntPtr.Zero) { try { IVsFontAndColorCacheManager cacheManager = (IVsFontAndColorCacheManager)Marshal.GetObjectForIUnknown(pCacheManager); cacheManager.ClearCache(ref textMgrIID); } finally { Marshal.Release(pCacheManager); } } } } return base.GetColorizer(buffer); } public override async void OnIdle(bool periodic) { var source = GetCurrentNShaderSource(); if (source != null) { if (lastChangeCount != source.ChangeCount) { clock.Restart(); lastChangeCount = source.ChangeCount; } if (clock.IsRunning) { if (clock.ElapsedMilliseconds > TriggerParsingDelayInMs) { clock.Stop(); clock.Reset(); var text = source.GetText(); var sourcePath = source.GetFilePath(); var projectFile = LocateProject(sourcePath); Trace.WriteLine(string.Format("Parsing Change: {0} Time: {1}", source.ChangeCount, DateTime.Now)); try { var result = await Task.Run(() => AnalyzeAndGoToDefinition(projectFile, text, new RawSourceSpan(sourcePath, 1, 1))).ConfigureAwait(true); OutputAnalysisMessages(result, source); } catch (Exception ex) { lock (errorListProvider) { errorListProvider.Tasks.Add(new ErrorTask(ex.InnerException ?? ex)); } } } } } base.OnIdle(periodic); } public string LocateProject(string sourcePath) { // Try to locate containing project var dte = (DTE)GetService(typeof(DTE)); var projectItem = dte.Solution.FindProjectItem(sourcePath); string projectFile = null; if (projectItem != null && projectItem.ContainingProject != null && !string.IsNullOrEmpty(projectItem.ContainingProject.FileName)) { projectFile = projectItem.ContainingProject.FileName; } return projectFile; } public RawShaderNavigationResult AnalyzeAndGoToDefinition(string projectFile, string text, RawSourceSpan span) { return StrideCommandsProxy.GetProxy()?.AnalyzeAndGoToDefinition(projectFile, text, span) ?? new RawShaderNavigationResult(); } private NShaderSource GetCurrentNShaderSource() { IVsTextView vsTextView = this.LastActiveTextView; if (vsTextView == null) return null; return GetNShaderSource(vsTextView); } private NShaderSource GetNShaderSource(IVsTextView textView) { return this.GetSource(textView) as NShaderSource; } public override AuthoringScope ParseSource(ParseRequest req) { // req.FileName return new TestAuthoringScope(); } public override string GetFormatFilterList() { return ""; } public override string Name { get { return "Stride Shader Language"; } } public void OutputAnalysisAndGotoLocation(RawShaderNavigationResult result, IVsTextView textView) { if (result == null) throw new ArgumentNullException("result"); if (textView == null) throw new ArgumentNullException("textView"); var source = GetNShaderSource(textView); OutputAnalysisMessages(result, source); GoToLocation(result.DefinitionSpan, null, false); } private void OutputAnalysisMessages(RawShaderNavigationResult result, NShaderSource source = null) { lock (errorListProvider) { try { var taskProvider = source != null ? source.GetTaskProvider() : null; if (taskProvider != null) { taskProvider.Tasks.Clear(); } errorListProvider.Tasks.Clear(); // clear previously created foreach (var message in result.Messages) { var errorCategory = TaskErrorCategory.Message; if (message.Type == "warning") { errorCategory = TaskErrorCategory.Warning; } else if (message.Type == "error") { errorCategory = TaskErrorCategory.Error; } // Make sure that we won't pass nay null to VS as it will crash it var filePath = message.Span.File ?? string.Empty; var messageText = message.Text ?? string.Empty; if (taskProvider != null && errorCategory == TaskErrorCategory.Error) { var task = source.CreateErrorTaskItem(ConvertToTextSpan(message.Span), filePath, messageText, TaskPriority.High, TaskCategory.CodeSense, MARKERTYPE.MARKER_CODESENSE_ERROR, TaskErrorCategory.Error); taskProvider.Tasks.Add(task); } else { var newError = new ErrorTask() { ErrorCategory = errorCategory, Category = TaskCategory.BuildCompile, Text = messageText, Document = filePath, Line = Math.Max(0, message.Span.Line - 1), Column = Math.Max(0, message.Span.Column - 1), // HierarchyItem = hierarchyItem // TODO Add hierarchy the file is associated to }; // Install our navigate to source newError.Navigate += NavigateToSourceError; errorListProvider.Tasks.Add(newError); // add item } } if (result.Messages.Count > 0) { errorListProvider.Show(); // make sure it is visible } else { errorListProvider.Refresh(); } if (taskProvider != null) { taskProvider.Refresh(); } } catch (Exception ex) { errorListProvider.Tasks.Add(new ErrorTask(ex.InnerException ?? ex)); } } } private static TextSpan ConvertToTextSpan(RawSourceSpan span) { return new TextSpan() { iStartIndex = Math.Max(0, span.Column-1), iStartLine = Math.Max(0, span.Line-1), iEndIndex = Math.Max(0, span.EndColumn-1), iEndLine = Math.Max(0, span.EndLine-1) }; } private void NavigateToSourceError(object sender, EventArgs e) { var task = sender as TaskListItem; if (task != null) { GoToLocation(new RawSourceSpan(task.Document, task.Line + 1, task.Column + 1), null, false); } } private void GoToLocation(RawSourceSpan loc, string caption, bool asReadonly) { // Code taken from Nemerle https://github.com/rsdn/nemerle/blob/master/snippets/VS2010/Nemerle.VisualStudio/LanguageService/NemerleLanguageService.cs#L565 // TODO: Add licensing if (loc == null || loc.File == null) return; // Opens the document var span = new TextSpan { iStartLine = loc.Line - 1, iStartIndex = loc.Column - 1, iEndLine = loc.EndLine - 1, iEndIndex = loc.EndColumn - 1 }; uint itemID; IVsUIHierarchy hierarchy; IVsWindowFrame docFrame; IVsTextView textView; VsShell.OpenDocument(Site, loc.File, VSConstants.LOGVIEWID_Code, out hierarchy, out itemID, out docFrame, out textView); // If we need readonly, set the buffer to read-only if (asReadonly) { IVsTextLines buffer; ErrorHandler.ThrowOnFailure(textView.GetBuffer(out buffer)); var stream = (IVsTextStream)buffer; stream.SetStateFlags((uint)BUFFERSTATEFLAGS.BSF_USER_READONLY); } // Need to use a different caption? if (caption != null) { ErrorHandler.ThrowOnFailure(docFrame.SetProperty((int)__VSFPROPID.VSFPROPID_OwnerCaption, caption)); } // Show the frame ErrorHandler.ThrowOnFailure(docFrame.Show()); // Go to the specific location if (textView != null && loc.Line != 0) { try { ErrorHandler.ThrowOnFailure(textView.SetCaretPos(span.iStartLine, span.iStartIndex)); TextSpanHelper.MakePositive(ref span); //ErrorHandler.ThrowOnFailure(textView.SetSelection(span.iStartLine, span.iStartIndex, span.iEndLine, span.iEndIndex)); ErrorHandler.ThrowOnFailure(textView.EnsureSpanVisible(span)); } catch (Exception ex) { Trace.WriteLine(ex.Message); } } } internal class TestAuthoringScope : AuthoringScope { public override string GetDataTipText(int line, int col, out TextSpan span) { span = new TextSpan(); return null; } public override Declarations GetDeclarations(IVsTextView view, int line, int col, TokenInfo info, ParseReason reason) { return null; } public override Methods GetMethods(int line, int col, string name) { return null; } public override string Goto(VSConstants.VSStd97CmdID cmd, IVsTextView textView, int line, int col, out TextSpan span) { span = new TextSpan(); return null; } } } }
42.684411
319
0.553269
[ "MIT" ]
Artromskiy/stride
sources/tools/Stride.VisualStudio.Package/NShader/NShaderLanguageService.cs
22,452
C#
#region LICENSE /* MIT License Copyright (c) 2018 Software free CAS Sharp Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace CASSharp.Core.Exprs { [DebuggerDisplay("TypeExpr : {TypeExpr}")] public class ListExpr : Expr { public Expr[] TheList { get; } public ListExpr(IEnumerable<Expr> argList) : base(ETypeExpr.List) { TheList = argList.ToArray(); } public ListExpr(ListExpr e) : this(e.TheList) { } public override Expr Clone() => new ListExpr(this); public override string ToString() => "[ " + string.Join(",", TheList.Select(l => l.ToString())) + " ]"; } }
35.862745
111
0.706397
[ "MIT" ]
bugbit/CASSharp
CASSharp/CASSharp.Core/Exprs/ListExpr.cs
1,831
C#
using System; using Elasticsearch.Net; using FluentAssertions; using Nest; using Tests.Framework; using Tests.Framework.Integration; using Tests.Framework.ManagedElasticsearch.Clusters; using Xunit; namespace Tests.Cat.CatThreadPool { public class CatThreadPoolApiTests : ApiIntegrationTestBase<ReadOnlyCluster, ICatResponse<CatThreadPoolRecord>, ICatThreadPoolRequest, CatThreadPoolDescriptor, CatThreadPoolRequest> { public CatThreadPoolApiTests(ReadOnlyCluster cluster, EndpointUsage usage) : base(cluster, usage) { } protected override LazyResponses ClientUsage() => Calls( fluent: (client, f) => client.CatThreadPool(), fluentAsync: (client, f) => client.CatThreadPoolAsync(), request: (client, r) => client.CatThreadPool(r), requestAsync: (client, r) => client.CatThreadPoolAsync(r) ); protected override bool ExpectIsValid => true; protected override int ExpectStatusCode => 200; protected override HttpMethod HttpMethod => HttpMethod.GET; protected override string UrlPath => "/_cat/thread_pool"; } public class CatThreadPoolFullApiTests : ApiIntegrationTestBase<ReadOnlyCluster, ICatResponse<CatThreadPoolRecord>, ICatThreadPoolRequest, CatThreadPoolDescriptor, CatThreadPoolRequest> { public CatThreadPoolFullApiTests(ReadOnlyCluster cluster, EndpointUsage usage) : base(cluster, usage) { } protected override LazyResponses ClientUsage() => Calls( fluent: (client, f) => client.CatThreadPool(f), fluentAsync: (client, f) => client.CatThreadPoolAsync(f), request: (client, r) => client.CatThreadPool(r), requestAsync: (client, r) => client.CatThreadPoolAsync(r) ); protected override Func<CatThreadPoolDescriptor, ICatThreadPoolRequest> Fluent => f => f.Headers("*"); protected override CatThreadPoolRequest Initializer { get; } = new CatThreadPoolRequest { Headers = new[] { "*" } }; protected override bool ExpectIsValid => true; protected override int ExpectStatusCode => 200; protected override HttpMethod HttpMethod => HttpMethod.GET; protected override string UrlPath => "/_cat/thread_pool?h=%2A"; protected override void ExpectResponse(ICatResponse<CatThreadPoolRecord> response) { response.Records.Should().NotBeNull(); foreach (var r in response.Records) { r.EphemeralNodeId.Should().NotBeNullOrWhiteSpace(); r.Host.Should().NotBeNullOrWhiteSpace(); r.Ip.Should().NotBeNullOrWhiteSpace(); r.Maximum.Should().BeGreaterThan(0); r.Minimum.Should().BeGreaterThan(0); r.Name.Should().NotBeNullOrWhiteSpace(); r.NodeId.Should().NotBeNullOrWhiteSpace(); r.NodeName.Should().NotBeNullOrWhiteSpace(); r.Port.Should().BeGreaterThan(0); r.ProcessId.Should().BeGreaterThan(0); r.Type.Should().NotBeNullOrWhiteSpace(); } response.Records.Should().Contain(r => r.KeepAlive != null); } } }
37.368421
186
0.751408
[ "Apache-2.0" ]
Tchami/elasticsearch-net
src/Tests/Cat/CatThreadPool/CatThreadpoolApiTests.cs
2,842
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; using Aop.Api.Domain; namespace Aop.Api.Response { /// <summary> /// KoubeiMarketingCampaignMerchantActivityBatchqueryResponse. /// </summary> public class KoubeiMarketingCampaignMerchantActivityBatchqueryResponse : AopResponse { /// <summary> /// 活动详细信息 /// </summary> [XmlArray("activity_detail_info_list")] [XmlArrayItem("m_activity_detail_info")] public List<MActivityDetailInfo> ActivityDetailInfoList { get; set; } } }
28.47619
89
0.670569
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Response/KoubeiMarketingCampaignMerchantActivityBatchqueryResponse.cs
610
C#
using System; using System.Collections.Generic; using System.Text; namespace LiteDBTestLib.Modules { public class Customer { public int Id { get; set; } public string Name { get; set; } public string[] Phones { get; set; } public bool IsActive { get; set; } } }
20.533333
44
0.616883
[ "MIT" ]
li-rongcheng/CoreCmdPlayground
LiteDBTestLib/Modules/Customer.cs
310
C#
using System; namespace Equinor.ProCoSys.Preservation.Query.GetActionDetails { public class ActionDetailsDto { public ActionDetailsDto( int id, PersonDto createdBy, DateTime createdAt, string title, string description, DateTime? dueTimeUtc, bool isClosed, PersonDto closedBy, DateTime? closedAtUtc, int attachmentCount, PersonDto modifiedBy, DateTime? modifiedAt, string rowVersion) { Id = id; CreatedBy = createdBy; CreatedAtUtc = createdAt; Title = title; Description = description; DueTimeUtc = dueTimeUtc; IsClosed = isClosed; ClosedBy = closedBy; ClosedAtUtc = closedAtUtc; AttachmentCount = attachmentCount; ModifiedBy = modifiedBy; ModifiedAtUtc = modifiedAt; RowVersion = rowVersion; } public int Id { get; } public PersonDto CreatedBy { get; } public DateTime CreatedAtUtc { get; } public string Title { get; } public string Description { get; } public DateTime? DueTimeUtc { get; } public bool IsClosed { get; } public PersonDto ClosedBy { get; } public DateTime? ClosedAtUtc { get; } public int AttachmentCount { get; } public PersonDto ModifiedBy { get; } public DateTime? ModifiedAtUtc { get; } public string RowVersion { get; } } }
30.788462
62
0.557152
[ "MIT" ]
equinor/pcs-preservation-api
src/Equinor.ProCoSys.Preservation.Query/GetActionDetails/ActionDetailsDto.cs
1,603
C#
using System; using System.Collections.Generic; using System.Linq; namespace _04.Snowwhite { class Program { static void Main(string[] args) { var dwarfs = new Dictionary<string, int>(); string input = Console.ReadLine(); while (input != "Once upon a time") { string[] inputs = input.Split(new string[] { " <:> " }, StringSplitOptions.None); string name = inputs[0]; string color = inputs[1]; int physics = int.Parse(inputs[2]); string ID = name + ":" + color; if (!dwarfs.ContainsKey(ID)) { dwarfs.Add(ID, physics); } else { dwarfs[ID] = Math.Max(dwarfs[ID], physics); } input = Console.ReadLine(); } foreach (var dwarf in dwarfs .OrderByDescending(x => x.Value) .ThenByDescending(x => dwarfs.Where(y => y.Key.Split(':')[1] == x.Key.Split(':')[1]) .Count())) { Console.WriteLine("({0}) {1} <-> {2}", dwarf.Key.Split(':')[1], dwarf.Key.Split(':')[0], dwarf.Value); } } } }
30.977778
100
0.411047
[ "MIT" ]
anidz/softuni-cs-fundamentals
AssociativeArraysMoreExercise/04.Snowwhite/Program.cs
1,396
C#
using UCDArch.Core.DomainModel; namespace EligibilityList.Core.Domain { public class Title : DomainObjectWithTypedId<string> { public virtual string Name { get; set; } public virtual string AbbreviatedName { get; set; } } }
22.166667
60
0.657895
[ "MIT" ]
ucdavis/EligibilityList
EligibilityList.Core/Domain/Title.cs
268
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using DemoMvc.Data; using DemoMvc.Models; using Microsoft.AspNetCore.Authorization; namespace DemoMvc.Controllers { public class PeopleController : Controller { private readonly DemoDbContext _context; public PeopleController(DemoDbContext context) { _context = context; } // GET: People public async Task<IActionResult> Index() { var demoDbContext = _context.Persons.Include(p => p.Family); return View(await demoDbContext.ToListAsync()); } // GET: People/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var person = await _context.Persons .Include(p => p.Family) .FirstOrDefaultAsync(m => m.Id == id); if (person == null) { return NotFound(); } return View(person); } // GET: People/Create public IActionResult Create() { ViewData["FamilyId"] = new SelectList(_context.Families, "Id", "Name"); return View(); } // POST: People/Create // To protect from overposting attacks, enable the specific properties you want to bind to. // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,FirstName,LastName,DateOfBirth,FamilyId")] Person person) { if (ModelState.IsValid) { _context.Add(person); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } ViewData["FamilyId"] = new SelectList(_context.Families, "Id", "Name", person.FamilyId); return View(person); } // GET: People/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var person = await _context.Persons.FindAsync(id); if (person == null) { return NotFound(); } ViewData["FamilyId"] = new SelectList(_context.Families, "Id", "Name", person.FamilyId); return View(person); } // POST: People/Edit/5 // To protect from overposting attacks, enable the specific properties you want to bind to. // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("Id,FirstName,LastName,DateOfBirth,FamilyId")] Person person) { if (id != person.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(person); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PersonExists(person.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } ViewData["FamilyId"] = new SelectList(_context.Families, "Id", "Name", person.FamilyId); return View(person); } // GET: People/Delete/5 //[Authorize(Roles = "Adminsitrator")] public async Task<IActionResult> Delete(int? id) { if (!User.IsInRole("Administrator")) //return Forbid(); return NotFound(); if (id == null) { return NotFound(); } var person = await _context.Persons .Include(p => p.Family) .FirstOrDefaultAsync(m => m.Id == id); if (person == null) { return NotFound(); } return View(person); } // POST: People/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] // [Authorize(Roles = "Adminsitrator")] public async Task<IActionResult> DeleteConfirmed(int id) { if (!User.IsInRole("Administrator")) return NotFound(); var person = await _context.Persons.FindAsync(id); _context.Persons.Remove(person); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool PersonExists(int id) { return _context.Persons.Any(e => e.Id == id); } } }
30.51462
121
0.512074
[ "MIT" ]
DeltaVCode-Demo/cr-dotnet-401d5-mvc
DemoMvc/Controllers/PeopleController.cs
5,218
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d2d1effects_2.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop { public enum D2D1_EMBOSS_PROP : uint { D2D1_EMBOSS_PROP_HEIGHT = 0, D2D1_EMBOSS_PROP_DIRECTION = 1, D2D1_EMBOSS_PROP_FORCE_DWORD = 0xffffffff, } }
33.466667
145
0.733068
[ "MIT" ]
Ethereal77/terrafx.interop.windows
sources/Interop/Windows/um/d2d1effects_2/D2D1_EMBOSS_PROP.cs
504
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Framework; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation.Schema; using System; using System.Collections.Generic; using System.IO.Packaging; namespace DocumentFormat.OpenXml.Vml.Spreadsheet { /// <summary> /// <para>Attached Object Data.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:ClientData.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>MoveWithCells &lt;xvml:MoveWithCells></description></item> /// <item><description>ResizeWithCells &lt;xvml:SizeWithCells></description></item> /// <item><description>Anchor &lt;xvml:Anchor></description></item> /// <item><description>Locked &lt;xvml:Locked></description></item> /// <item><description>DefaultSize &lt;xvml:DefaultSize></description></item> /// <item><description>PrintObject &lt;xvml:PrintObject></description></item> /// <item><description>Disabled &lt;xvml:Disabled></description></item> /// <item><description>AutoFill &lt;xvml:AutoFill></description></item> /// <item><description>AutoLine &lt;xvml:AutoLine></description></item> /// <item><description>AutoSizePicture &lt;xvml:AutoPict></description></item> /// <item><description>FormulaMacro &lt;xvml:FmlaMacro></description></item> /// <item><description>HorizontalTextAlignment &lt;xvml:TextHAlign></description></item> /// <item><description>VerticalTextAlignment &lt;xvml:TextVAlign></description></item> /// <item><description>LockText &lt;xvml:LockText></description></item> /// <item><description>JustifyLastLine &lt;xvml:JustLastX></description></item> /// <item><description>SecretEdit &lt;xvml:SecretEdit></description></item> /// <item><description>DefaultButton &lt;xvml:Default></description></item> /// <item><description>HelpButton &lt;xvml:Help></description></item> /// <item><description>CancelButton &lt;xvml:Cancel></description></item> /// <item><description>DismissButton &lt;xvml:Dismiss></description></item> /// <item><description>AcceleratorPrimary &lt;xvml:Accel></description></item> /// <item><description>AcceleratorSecondary &lt;xvml:Accel2></description></item> /// <item><description>CommentRowTarget &lt;xvml:Row></description></item> /// <item><description>CommentColumnTarget &lt;xvml:Column></description></item> /// <item><description>Visible &lt;xvml:Visible></description></item> /// <item><description>RowHidden &lt;xvml:RowHidden></description></item> /// <item><description>ColumnHidden &lt;xvml:ColHidden></description></item> /// <item><description>InputValidationType &lt;xvml:VTEdit></description></item> /// <item><description>MultiLine &lt;xvml:MultiLine></description></item> /// <item><description>VerticalScrollBar &lt;xvml:VScroll></description></item> /// <item><description>ValidIds &lt;xvml:ValidIds></description></item> /// <item><description>FormulaRange &lt;xvml:FmlaRange></description></item> /// <item><description>MinDropDownWidth &lt;xvml:WidthMin></description></item> /// <item><description>SelectionEntry &lt;xvml:Sel></description></item> /// <item><description>Disable3DForListBoxAndDropDown &lt;xvml:NoThreeD2></description></item> /// <item><description>SelectionType &lt;xvml:SelType></description></item> /// <item><description>MultiSelections &lt;xvml:MultiSel></description></item> /// <item><description>ListBoxCallbackType &lt;xvml:LCT></description></item> /// <item><description>ListItem &lt;xvml:ListItem></description></item> /// <item><description>DropStyle &lt;xvml:DropStyle></description></item> /// <item><description>Colored &lt;xvml:Colored></description></item> /// <item><description>DropLines &lt;xvml:DropLines></description></item> /// <item><description>Checked &lt;xvml:Checked></description></item> /// <item><description>FormulaLink &lt;xvml:FmlaLink></description></item> /// <item><description>FormulaPicture &lt;xvml:FmlaPict></description></item> /// <item><description>Disable3D &lt;xvml:NoThreeD></description></item> /// <item><description>FirstButton &lt;xvml:FirstButton></description></item> /// <item><description>FormulaGroup &lt;xvml:FmlaGroup></description></item> /// <item><description>ScrollBarPosition &lt;xvml:Val></description></item> /// <item><description>ScrollBarMin &lt;xvml:Min></description></item> /// <item><description>ScrollBarMax &lt;xvml:Max></description></item> /// <item><description>ScrollBarIncrement &lt;xvml:Inc></description></item> /// <item><description>ScrollBarPageIncrement &lt;xvml:Page></description></item> /// <item><description>HorizontalScrollBar &lt;xvml:Horiz></description></item> /// <item><description>ScrollBarWidth &lt;xvml:Dx></description></item> /// <item><description>MapOcxControl &lt;xvml:MapOCX></description></item> /// <item><description>ClipboardFormat &lt;xvml:CF></description></item> /// <item><description>CameraObject &lt;xvml:Camera></description></item> /// <item><description>RecalculateAlways &lt;xvml:RecalcAlways></description></item> /// <item><description>AutoScaleFont &lt;xvml:AutoScale></description></item> /// <item><description>DdeObject &lt;xvml:DDE></description></item> /// <item><description>UIObject &lt;xvml:UIObj></description></item> /// <item><description>ScriptText &lt;xvml:ScriptText></description></item> /// <item><description>ScriptExtended &lt;xvml:ScriptExtended></description></item> /// <item><description>ScriptLanguage &lt;xvml:ScriptLanguage></description></item> /// <item><description>ScriptLocation &lt;xvml:ScriptLocation></description></item> /// <item><description>FormulaTextBox &lt;xvml:FmlaTxbx></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(MoveWithCells))] [ChildElementInfo(typeof(ResizeWithCells))] [ChildElementInfo(typeof(Anchor))] [ChildElementInfo(typeof(Locked))] [ChildElementInfo(typeof(DefaultSize))] [ChildElementInfo(typeof(PrintObject))] [ChildElementInfo(typeof(Disabled))] [ChildElementInfo(typeof(AutoFill))] [ChildElementInfo(typeof(AutoLine))] [ChildElementInfo(typeof(AutoSizePicture))] [ChildElementInfo(typeof(FormulaMacro))] [ChildElementInfo(typeof(HorizontalTextAlignment))] [ChildElementInfo(typeof(VerticalTextAlignment))] [ChildElementInfo(typeof(LockText))] [ChildElementInfo(typeof(JustifyLastLine))] [ChildElementInfo(typeof(SecretEdit))] [ChildElementInfo(typeof(DefaultButton))] [ChildElementInfo(typeof(HelpButton))] [ChildElementInfo(typeof(CancelButton))] [ChildElementInfo(typeof(DismissButton))] [ChildElementInfo(typeof(AcceleratorPrimary))] [ChildElementInfo(typeof(AcceleratorSecondary))] [ChildElementInfo(typeof(CommentRowTarget))] [ChildElementInfo(typeof(CommentColumnTarget))] [ChildElementInfo(typeof(Visible))] [ChildElementInfo(typeof(RowHidden))] [ChildElementInfo(typeof(ColumnHidden))] [ChildElementInfo(typeof(InputValidationType))] [ChildElementInfo(typeof(MultiLine))] [ChildElementInfo(typeof(VerticalScrollBar))] [ChildElementInfo(typeof(ValidIds))] [ChildElementInfo(typeof(FormulaRange))] [ChildElementInfo(typeof(MinDropDownWidth))] [ChildElementInfo(typeof(SelectionEntry))] [ChildElementInfo(typeof(Disable3DForListBoxAndDropDown))] [ChildElementInfo(typeof(SelectionType))] [ChildElementInfo(typeof(MultiSelections))] [ChildElementInfo(typeof(ListBoxCallbackType))] [ChildElementInfo(typeof(ListItem))] [ChildElementInfo(typeof(DropStyle))] [ChildElementInfo(typeof(Colored))] [ChildElementInfo(typeof(DropLines))] [ChildElementInfo(typeof(Checked))] [ChildElementInfo(typeof(FormulaLink))] [ChildElementInfo(typeof(FormulaPicture))] [ChildElementInfo(typeof(Disable3D))] [ChildElementInfo(typeof(FirstButton))] [ChildElementInfo(typeof(FormulaGroup))] [ChildElementInfo(typeof(ScrollBarPosition))] [ChildElementInfo(typeof(ScrollBarMin))] [ChildElementInfo(typeof(ScrollBarMax))] [ChildElementInfo(typeof(ScrollBarIncrement))] [ChildElementInfo(typeof(ScrollBarPageIncrement))] [ChildElementInfo(typeof(HorizontalScrollBar))] [ChildElementInfo(typeof(ScrollBarWidth))] [ChildElementInfo(typeof(MapOcxControl))] [ChildElementInfo(typeof(ClipboardFormat))] [ChildElementInfo(typeof(CameraObject))] [ChildElementInfo(typeof(RecalculateAlways))] [ChildElementInfo(typeof(AutoScaleFont))] [ChildElementInfo(typeof(DdeObject))] [ChildElementInfo(typeof(UIObject))] [ChildElementInfo(typeof(ScriptText))] [ChildElementInfo(typeof(ScriptExtended))] [ChildElementInfo(typeof(ScriptLanguage))] [ChildElementInfo(typeof(ScriptLocation))] [ChildElementInfo(typeof(FormulaTextBox))] [SchemaAttr(29, "ClientData")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ClientData : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the ClientData class. /// </summary> public ClientData() : base() { } /// <summary> /// Initializes a new instance of the ClientData class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ClientData(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ClientData class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ClientData(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ClientData class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public ClientData(string outerXml) : base(outerXml) { } /// <summary> /// <para>Object type</para> /// <para>Represents the following attribute in the schema: ObjectType</para> /// </summary> [RequiredValidator()] [SchemaAttr(0, "ObjectType")] [Index(0)] public EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.ObjectValues> ObjectType { get; set; } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Choice, 0, 0) { new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.MoveWithCells), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.ResizeWithCells), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.Anchor), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.Locked), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.DefaultSize), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.PrintObject), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.Disabled), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.AutoFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.AutoLine), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.AutoSizePicture), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.FormulaMacro), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.HorizontalTextAlignment), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.VerticalTextAlignment), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.LockText), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.JustifyLastLine), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.SecretEdit), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.DefaultButton), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.HelpButton), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.CancelButton), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.DismissButton), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.AcceleratorPrimary), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.AcceleratorSecondary), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.CommentRowTarget), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.CommentColumnTarget), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.Visible), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.RowHidden), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.ColumnHidden), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.InputValidationType), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.MultiLine), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.VerticalScrollBar), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.ValidIds), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.FormulaRange), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.MinDropDownWidth), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.SelectionEntry), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.Disable3DForListBoxAndDropDown), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.SelectionType), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.MultiSelections), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.ListBoxCallbackType), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.ListItem), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.DropStyle), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.Colored), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.DropLines), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.Checked), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.FormulaLink), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.FormulaPicture), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.Disable3D), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.FirstButton), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.FormulaGroup), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.ScrollBarPosition), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.ScrollBarMin), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.ScrollBarMax), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.ScrollBarIncrement), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.ScrollBarPageIncrement), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.HorizontalScrollBar), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.ScrollBarWidth), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.MapOcxControl), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.ClipboardFormat), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.CameraObject), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.RecalculateAlways), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.AutoScaleFont), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.DdeObject), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.UIObject), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.ScriptText), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.ScriptExtended), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.ScriptLanguage), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.ScriptLocation), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Vml.Spreadsheet.FormulaTextBox), 1, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ClientData>(deep); } /// <summary> /// <para>Move with Cells.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:MoveWithCells.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "MoveWithCells")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class MoveWithCells : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the MoveWithCells class. /// </summary> public MoveWithCells() : base() { } /// <summary> /// Initializes a new instance of the MoveWithCells class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public MoveWithCells(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<MoveWithCells>(deep); } /// <summary> /// <para>Resize with Cells.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:SizeWithCells.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "SizeWithCells")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ResizeWithCells : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ResizeWithCells class. /// </summary> public ResizeWithCells() : base() { } /// <summary> /// Initializes a new instance of the ResizeWithCells class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ResizeWithCells(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ResizeWithCells>(deep); } /// <summary> /// <para>Lock Toggle.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Locked.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "Locked")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class Locked : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Locked class. /// </summary> public Locked() : base() { } /// <summary> /// Initializes a new instance of the Locked class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Locked(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Locked>(deep); } /// <summary> /// <para>Default Size Toggle.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:DefaultSize.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "DefaultSize")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class DefaultSize : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the DefaultSize class. /// </summary> public DefaultSize() : base() { } /// <summary> /// Initializes a new instance of the DefaultSize class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public DefaultSize(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<DefaultSize>(deep); } /// <summary> /// <para>Print Toggle.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:PrintObject.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "PrintObject")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class PrintObject : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the PrintObject class. /// </summary> public PrintObject() : base() { } /// <summary> /// Initializes a new instance of the PrintObject class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public PrintObject(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<PrintObject>(deep); } /// <summary> /// <para>Macro Disable Toggle.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Disabled.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "Disabled")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class Disabled : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Disabled class. /// </summary> public Disabled() : base() { } /// <summary> /// Initializes a new instance of the Disabled class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Disabled(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Disabled>(deep); } /// <summary> /// <para>AutoFill.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:AutoFill.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "AutoFill")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class AutoFill : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the AutoFill class. /// </summary> public AutoFill() : base() { } /// <summary> /// Initializes a new instance of the AutoFill class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public AutoFill(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<AutoFill>(deep); } /// <summary> /// <para>AutoLine.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:AutoLine.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "AutoLine")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class AutoLine : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the AutoLine class. /// </summary> public AutoLine() : base() { } /// <summary> /// Initializes a new instance of the AutoLine class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public AutoLine(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<AutoLine>(deep); } /// <summary> /// <para>Automatically Size.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:AutoPict.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "AutoPict")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class AutoSizePicture : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the AutoSizePicture class. /// </summary> public AutoSizePicture() : base() { } /// <summary> /// Initializes a new instance of the AutoSizePicture class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public AutoSizePicture(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<AutoSizePicture>(deep); } /// <summary> /// <para>Text Lock.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:LockText.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "LockText")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class LockText : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the LockText class. /// </summary> public LockText() : base() { } /// <summary> /// Initializes a new instance of the LockText class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public LockText(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<LockText>(deep); } /// <summary> /// <para>East Asia Alignment Toggle.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:JustLastX.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "JustLastX")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class JustifyLastLine : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the JustifyLastLine class. /// </summary> public JustifyLastLine() : base() { } /// <summary> /// Initializes a new instance of the JustifyLastLine class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public JustifyLastLine(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<JustifyLastLine>(deep); } /// <summary> /// <para>Password Edit.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:SecretEdit.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "SecretEdit")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class SecretEdit : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the SecretEdit class. /// </summary> public SecretEdit() : base() { } /// <summary> /// Initializes a new instance of the SecretEdit class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public SecretEdit(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<SecretEdit>(deep); } /// <summary> /// <para>Default Button.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Default.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "Default")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class DefaultButton : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the DefaultButton class. /// </summary> public DefaultButton() : base() { } /// <summary> /// Initializes a new instance of the DefaultButton class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public DefaultButton(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<DefaultButton>(deep); } /// <summary> /// <para>Help Button.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Help.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "Help")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class HelpButton : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the HelpButton class. /// </summary> public HelpButton() : base() { } /// <summary> /// Initializes a new instance of the HelpButton class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public HelpButton(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<HelpButton>(deep); } /// <summary> /// <para>Cancel Button.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Cancel.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "Cancel")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class CancelButton : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the CancelButton class. /// </summary> public CancelButton() : base() { } /// <summary> /// Initializes a new instance of the CancelButton class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public CancelButton(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<CancelButton>(deep); } /// <summary> /// <para>Dismiss Button.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Dismiss.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "Dismiss")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class DismissButton : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the DismissButton class. /// </summary> public DismissButton() : base() { } /// <summary> /// Initializes a new instance of the DismissButton class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public DismissButton(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<DismissButton>(deep); } /// <summary> /// <para>Comment Visibility Toggle.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Visible.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "Visible")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class Visible : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Visible class. /// </summary> public Visible() : base() { } /// <summary> /// Initializes a new instance of the Visible class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Visible(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Visible>(deep); } /// <summary> /// <para>Comment's Row is Hidden.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:RowHidden.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "RowHidden")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class RowHidden : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the RowHidden class. /// </summary> public RowHidden() : base() { } /// <summary> /// Initializes a new instance of the RowHidden class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public RowHidden(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<RowHidden>(deep); } /// <summary> /// <para>Comment's Column is Hidden.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:ColHidden.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "ColHidden")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ColumnHidden : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ColumnHidden class. /// </summary> public ColumnHidden() : base() { } /// <summary> /// Initializes a new instance of the ColumnHidden class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ColumnHidden(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ColumnHidden>(deep); } /// <summary> /// <para>Multi-line.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:MultiLine.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "MultiLine")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class MultiLine : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the MultiLine class. /// </summary> public MultiLine() : base() { } /// <summary> /// Initializes a new instance of the MultiLine class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public MultiLine(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<MultiLine>(deep); } /// <summary> /// <para>Vertical Scroll.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:VScroll.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "VScroll")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class VerticalScrollBar : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the VerticalScrollBar class. /// </summary> public VerticalScrollBar() : base() { } /// <summary> /// Initializes a new instance of the VerticalScrollBar class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public VerticalScrollBar(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<VerticalScrollBar>(deep); } /// <summary> /// <para>Valid ID.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:ValidIds.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "ValidIds")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ValidIds : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ValidIds class. /// </summary> public ValidIds() : base() { } /// <summary> /// Initializes a new instance of the ValidIds class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ValidIds(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ValidIds>(deep); } /// <summary> /// <para>Disable 3D.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:NoThreeD2.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "NoThreeD2")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class Disable3DForListBoxAndDropDown : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Disable3DForListBoxAndDropDown class. /// </summary> public Disable3DForListBoxAndDropDown() : base() { } /// <summary> /// Initializes a new instance of the Disable3DForListBoxAndDropDown class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Disable3DForListBoxAndDropDown(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Disable3DForListBoxAndDropDown>(deep); } /// <summary> /// <para>Dropdown Color Toggle.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Colored.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "Colored")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class Colored : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Colored class. /// </summary> public Colored() : base() { } /// <summary> /// Initializes a new instance of the Colored class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Colored(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Colored>(deep); } /// <summary> /// <para>Disable 3D.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:NoThreeD.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "NoThreeD")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class Disable3D : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Disable3D class. /// </summary> public Disable3D() : base() { } /// <summary> /// Initializes a new instance of the Disable3D class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Disable3D(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Disable3D>(deep); } /// <summary> /// <para>First Radio Button.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:FirstButton.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "FirstButton")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class FirstButton : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the FirstButton class. /// </summary> public FirstButton() : base() { } /// <summary> /// Initializes a new instance of the FirstButton class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public FirstButton(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FirstButton>(deep); } /// <summary> /// <para>Scroll Bar Orientation.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Horiz.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "Horiz")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class HorizontalScrollBar : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the HorizontalScrollBar class. /// </summary> public HorizontalScrollBar() : base() { } /// <summary> /// Initializes a new instance of the HorizontalScrollBar class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public HorizontalScrollBar(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<HorizontalScrollBar>(deep); } /// <summary> /// <para>ActiveX Control.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:MapOCX.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "MapOCX")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class MapOcxControl : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the MapOcxControl class. /// </summary> public MapOcxControl() : base() { } /// <summary> /// Initializes a new instance of the MapOcxControl class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public MapOcxControl(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<MapOcxControl>(deep); } /// <summary> /// <para>Camera Tool.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Camera.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "Camera")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class CameraObject : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the CameraObject class. /// </summary> public CameraObject() : base() { } /// <summary> /// Initializes a new instance of the CameraObject class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public CameraObject(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<CameraObject>(deep); } /// <summary> /// <para>Recalculation Toggle.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:RecalcAlways.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "RecalcAlways")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class RecalculateAlways : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the RecalculateAlways class. /// </summary> public RecalculateAlways() : base() { } /// <summary> /// Initializes a new instance of the RecalculateAlways class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public RecalculateAlways(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<RecalculateAlways>(deep); } /// <summary> /// <para>Font AutoScale.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:AutoScale.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "AutoScale")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class AutoScaleFont : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the AutoScaleFont class. /// </summary> public AutoScaleFont() : base() { } /// <summary> /// Initializes a new instance of the AutoScaleFont class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public AutoScaleFont(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<AutoScaleFont>(deep); } /// <summary> /// <para>Dynamic Data Exchange.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:DDE.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "DDE")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class DdeObject : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the DdeObject class. /// </summary> public DdeObject() : base() { } /// <summary> /// Initializes a new instance of the DdeObject class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public DdeObject(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<DdeObject>(deep); } /// <summary> /// <para>UI Object Toggle.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:UIObj.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues>))] [SchemaAttr(29, "UIObj")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class UIObject : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the UIObject class. /// </summary> public UIObject() : base() { } /// <summary> /// Initializes a new instance of the UIObject class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public UIObject(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.BooleanEntryWithBlankValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<UIObject>(deep); } /// <summary> /// <para>Anchor.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Anchor.</para> /// </summary> [SchemaAttr(29, "Anchor")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class Anchor : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Anchor class. /// </summary> public Anchor() : base() { } /// <summary> /// Initializes a new instance of the Anchor class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Anchor(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Anchor>(deep); } /// <summary> /// <para>Horizontal Text Alignment.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:TextHAlign.</para> /// </summary> [SchemaAttr(29, "TextHAlign")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class HorizontalTextAlignment : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the HorizontalTextAlignment class. /// </summary> public HorizontalTextAlignment() : base() { } /// <summary> /// Initializes a new instance of the HorizontalTextAlignment class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public HorizontalTextAlignment(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<HorizontalTextAlignment>(deep); } /// <summary> /// <para>Vertical Text Alignment.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:TextVAlign.</para> /// </summary> [SchemaAttr(29, "TextVAlign")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class VerticalTextAlignment : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the VerticalTextAlignment class. /// </summary> public VerticalTextAlignment() : base() { } /// <summary> /// Initializes a new instance of the VerticalTextAlignment class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public VerticalTextAlignment(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<VerticalTextAlignment>(deep); } /// <summary> /// <para>List Items Source Range.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:FmlaRange.</para> /// </summary> [SchemaAttr(29, "FmlaRange")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class FormulaRange : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the FormulaRange class. /// </summary> public FormulaRange() : base() { } /// <summary> /// Initializes a new instance of the FormulaRange class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public FormulaRange(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FormulaRange>(deep); } /// <summary> /// <para>Selection Type.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:SelType.</para> /// </summary> [SchemaAttr(29, "SelType")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class SelectionType : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the SelectionType class. /// </summary> public SelectionType() : base() { } /// <summary> /// Initializes a new instance of the SelectionType class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public SelectionType(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<SelectionType>(deep); } /// <summary> /// <para>Multiple Selections.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:MultiSel.</para> /// </summary> [SchemaAttr(29, "MultiSel")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class MultiSelections : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the MultiSelections class. /// </summary> public MultiSelections() : base() { } /// <summary> /// Initializes a new instance of the MultiSelections class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public MultiSelections(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<MultiSelections>(deep); } /// <summary> /// <para>Callback Type.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:LCT.</para> /// </summary> [SchemaAttr(29, "LCT")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ListBoxCallbackType : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ListBoxCallbackType class. /// </summary> public ListBoxCallbackType() : base() { } /// <summary> /// Initializes a new instance of the ListBoxCallbackType class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ListBoxCallbackType(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ListBoxCallbackType>(deep); } /// <summary> /// <para>Non-linked List Item.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:ListItem.</para> /// </summary> [SchemaAttr(29, "ListItem")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ListItem : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ListItem class. /// </summary> public ListItem() : base() { } /// <summary> /// Initializes a new instance of the ListItem class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ListItem(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ListItem>(deep); } /// <summary> /// <para>Dropdown Style.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:DropStyle.</para> /// </summary> [SchemaAttr(29, "DropStyle")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class DropStyle : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the DropStyle class. /// </summary> public DropStyle() : base() { } /// <summary> /// Initializes a new instance of the DropStyle class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public DropStyle(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<DropStyle>(deep); } /// <summary> /// <para>Linked Formula.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:FmlaLink.</para> /// </summary> [SchemaAttr(29, "FmlaLink")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class FormulaLink : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the FormulaLink class. /// </summary> public FormulaLink() : base() { } /// <summary> /// Initializes a new instance of the FormulaLink class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public FormulaLink(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FormulaLink>(deep); } /// <summary> /// <para>Camera Source Range.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:FmlaPict.</para> /// </summary> [SchemaAttr(29, "FmlaPict")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class FormulaPicture : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the FormulaPicture class. /// </summary> public FormulaPicture() : base() { } /// <summary> /// Initializes a new instance of the FormulaPicture class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public FormulaPicture(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FormulaPicture>(deep); } /// <summary> /// <para>Linked Formula - Group Box.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:FmlaGroup.</para> /// </summary> [SchemaAttr(29, "FmlaGroup")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class FormulaGroup : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the FormulaGroup class. /// </summary> public FormulaGroup() : base() { } /// <summary> /// Initializes a new instance of the FormulaGroup class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public FormulaGroup(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FormulaGroup>(deep); } /// <summary> /// <para>HTML Script Text.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:ScriptText.</para> /// </summary> [SchemaAttr(29, "ScriptText")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ScriptText : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ScriptText class. /// </summary> public ScriptText() : base() { } /// <summary> /// Initializes a new instance of the ScriptText class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ScriptText(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ScriptText>(deep); } /// <summary> /// <para>HTML Script Attributes.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:ScriptExtended.</para> /// </summary> [SchemaAttr(29, "ScriptExtended")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ScriptExtended : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ScriptExtended class. /// </summary> public ScriptExtended() : base() { } /// <summary> /// Initializes a new instance of the ScriptExtended class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ScriptExtended(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ScriptExtended>(deep); } /// <summary> /// <para>Text Formula.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:FmlaTxbx.</para> /// </summary> [SchemaAttr(29, "FmlaTxbx")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class FormulaTextBox : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the FormulaTextBox class. /// </summary> public FormulaTextBox() : base() { } /// <summary> /// Initializes a new instance of the FormulaTextBox class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public FormulaTextBox(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FormulaTextBox>(deep); } /// <summary> /// <para>Reference to Custom Function.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:FmlaMacro.</para> /// </summary> [StringValidator(MinLength = 0L, MaxLength = 256L)] [SchemaAttr(29, "FmlaMacro")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class FormulaMacro : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the FormulaMacro class. /// </summary> public FormulaMacro() : base() { } /// <summary> /// Initializes a new instance of the FormulaMacro class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public FormulaMacro(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FormulaMacro>(deep); } /// <summary> /// <para>Primary Keyboard Accelerator.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Accel.</para> /// </summary> [NumberValidator(SimpleType = typeof(ByteValue))] [SchemaAttr(29, "Accel")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class AcceleratorPrimary : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the AcceleratorPrimary class. /// </summary> public AcceleratorPrimary() : base() { } /// <summary> /// Initializes a new instance of the AcceleratorPrimary class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public AcceleratorPrimary(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new ByteValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<AcceleratorPrimary>(deep); } /// <summary> /// <para>Secondary Keyboard Accelerator.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Accel2.</para> /// </summary> [NumberValidator(SimpleType = typeof(ByteValue))] [SchemaAttr(29, "Accel2")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class AcceleratorSecondary : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the AcceleratorSecondary class. /// </summary> public AcceleratorSecondary() : base() { } /// <summary> /// Initializes a new instance of the AcceleratorSecondary class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public AcceleratorSecondary(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new ByteValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<AcceleratorSecondary>(deep); } /// <summary> /// <para>Comment Row Target.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Row.</para> /// </summary> [NumberValidator(SimpleType = typeof(IntegerValue))] [SchemaAttr(29, "Row")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class CommentRowTarget : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the CommentRowTarget class. /// </summary> public CommentRowTarget() : base() { } /// <summary> /// Initializes a new instance of the CommentRowTarget class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public CommentRowTarget(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new IntegerValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<CommentRowTarget>(deep); } /// <summary> /// <para>Comment Column Target.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Column.</para> /// </summary> [NumberValidator(SimpleType = typeof(IntegerValue))] [SchemaAttr(29, "Column")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class CommentColumnTarget : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the CommentColumnTarget class. /// </summary> public CommentColumnTarget() : base() { } /// <summary> /// Initializes a new instance of the CommentColumnTarget class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public CommentColumnTarget(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new IntegerValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<CommentColumnTarget>(deep); } /// <summary> /// <para>Validation Type.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:VTEdit.</para> /// </summary> [NumberValidator(SimpleType = typeof(IntegerValue))] [SchemaAttr(29, "VTEdit")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class InputValidationType : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the InputValidationType class. /// </summary> public InputValidationType() : base() { } /// <summary> /// Initializes a new instance of the InputValidationType class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public InputValidationType(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new IntegerValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<InputValidationType>(deep); } /// <summary> /// <para>Minimum Width.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:WidthMin.</para> /// </summary> [NumberValidator(SimpleType = typeof(IntegerValue))] [SchemaAttr(29, "WidthMin")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class MinDropDownWidth : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the MinDropDownWidth class. /// </summary> public MinDropDownWidth() : base() { } /// <summary> /// Initializes a new instance of the MinDropDownWidth class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public MinDropDownWidth(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new IntegerValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<MinDropDownWidth>(deep); } /// <summary> /// <para>Selected Entry.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Sel.</para> /// </summary> [NumberValidator(SimpleType = typeof(IntegerValue))] [SchemaAttr(29, "Sel")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class SelectionEntry : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the SelectionEntry class. /// </summary> public SelectionEntry() : base() { } /// <summary> /// Initializes a new instance of the SelectionEntry class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public SelectionEntry(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new IntegerValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<SelectionEntry>(deep); } /// <summary> /// <para>Dropdown Maximum Lines.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:DropLines.</para> /// </summary> [NumberValidator(SimpleType = typeof(IntegerValue))] [SchemaAttr(29, "DropLines")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class DropLines : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the DropLines class. /// </summary> public DropLines() : base() { } /// <summary> /// Initializes a new instance of the DropLines class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public DropLines(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new IntegerValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<DropLines>(deep); } /// <summary> /// <para>Checked.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Checked.</para> /// </summary> [NumberValidator(SimpleType = typeof(IntegerValue))] [SchemaAttr(29, "Checked")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class Checked : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Checked class. /// </summary> public Checked() : base() { } /// <summary> /// Initializes a new instance of the Checked class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Checked(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new IntegerValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Checked>(deep); } /// <summary> /// <para>Scroll bar position.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Val.</para> /// </summary> [NumberValidator(SimpleType = typeof(IntegerValue))] [SchemaAttr(29, "Val")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ScrollBarPosition : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ScrollBarPosition class. /// </summary> public ScrollBarPosition() : base() { } /// <summary> /// Initializes a new instance of the ScrollBarPosition class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ScrollBarPosition(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new IntegerValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ScrollBarPosition>(deep); } /// <summary> /// <para>Scroll Bar Minimum.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Min.</para> /// </summary> [NumberValidator(SimpleType = typeof(IntegerValue))] [SchemaAttr(29, "Min")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ScrollBarMin : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ScrollBarMin class. /// </summary> public ScrollBarMin() : base() { } /// <summary> /// Initializes a new instance of the ScrollBarMin class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ScrollBarMin(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new IntegerValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ScrollBarMin>(deep); } /// <summary> /// <para>Scroll Bar Maximum.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Max.</para> /// </summary> [NumberValidator(SimpleType = typeof(IntegerValue))] [SchemaAttr(29, "Max")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ScrollBarMax : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ScrollBarMax class. /// </summary> public ScrollBarMax() : base() { } /// <summary> /// Initializes a new instance of the ScrollBarMax class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ScrollBarMax(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new IntegerValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ScrollBarMax>(deep); } /// <summary> /// <para>Scroll Bar Increment.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Inc.</para> /// </summary> [NumberValidator(SimpleType = typeof(IntegerValue))] [SchemaAttr(29, "Inc")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ScrollBarIncrement : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ScrollBarIncrement class. /// </summary> public ScrollBarIncrement() : base() { } /// <summary> /// Initializes a new instance of the ScrollBarIncrement class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ScrollBarIncrement(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new IntegerValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ScrollBarIncrement>(deep); } /// <summary> /// <para>Scroll Bar Page Increment.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Page.</para> /// </summary> [NumberValidator(SimpleType = typeof(IntegerValue))] [SchemaAttr(29, "Page")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ScrollBarPageIncrement : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ScrollBarPageIncrement class. /// </summary> public ScrollBarPageIncrement() : base() { } /// <summary> /// Initializes a new instance of the ScrollBarPageIncrement class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ScrollBarPageIncrement(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new IntegerValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ScrollBarPageIncrement>(deep); } /// <summary> /// <para>Scroll Bar Width.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:Dx.</para> /// </summary> [NumberValidator(SimpleType = typeof(IntegerValue))] [SchemaAttr(29, "Dx")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ScrollBarWidth : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ScrollBarWidth class. /// </summary> public ScrollBarWidth() : base() { } /// <summary> /// Initializes a new instance of the ScrollBarWidth class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ScrollBarWidth(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new IntegerValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ScrollBarWidth>(deep); } /// <summary> /// <para>Clipboard Format.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:CF.</para> /// </summary> [EnumValidator(SimpleType = typeof(EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.ClipboardFormatValues>))] [SchemaAttr(29, "CF")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ClipboardFormat : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ClipboardFormat class. /// </summary> public ClipboardFormat() : base() { } /// <summary> /// Initializes a new instance of the ClipboardFormat class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ClipboardFormat(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Vml.Spreadsheet.ClipboardFormatValues> { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ClipboardFormat>(deep); } /// <summary> /// <para>HTML Script Language.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:ScriptLanguage.</para> /// </summary> [NumberValidator(SimpleType = typeof(IntegerValue), IsNonNegative = true)] [SchemaAttr(29, "ScriptLanguage")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ScriptLanguage : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ScriptLanguage class. /// </summary> public ScriptLanguage() : base() { } /// <summary> /// Initializes a new instance of the ScriptLanguage class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ScriptLanguage(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new IntegerValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ScriptLanguage>(deep); } /// <summary> /// <para>HTML Script Location.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is xvml:ScriptLocation.</para> /// </summary> [NumberValidator(SimpleType = typeof(IntegerValue), IsNonNegative = true)] [SchemaAttr(29, "ScriptLocation")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ScriptLocation : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ScriptLocation class. /// </summary> public ScriptLocation() : base() { } /// <summary> /// Initializes a new instance of the ScriptLocation class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ScriptLocation(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new IntegerValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ScriptLocation>(deep); } /// <summary> /// Clipboard Format Type /// </summary> public enum ClipboardFormatValues { ///<summary> ///WMF. ///<para>When the item is serialized out as xml, its value is "PictOld".</para> ///</summary> [EnumString("PictOld")] PictureOld, ///<summary> ///EMF. ///<para>When the item is serialized out as xml, its value is "Pict".</para> ///</summary> [EnumString("Pict")] Picture, ///<summary> ///Bitmap. ///<para>When the item is serialized out as xml, its value is "Bitmap".</para> ///</summary> [EnumString("Bitmap")] Bitmap, ///<summary> ///Printer Picture. ///<para>When the item is serialized out as xml, its value is "PictPrint".</para> ///</summary> [EnumString("PictPrint")] PicturePrint, ///<summary> ///Screen Picture EMF. ///<para>When the item is serialized out as xml, its value is "PictScreen".</para> ///</summary> [EnumString("PictScreen")] PictureScreen, } /// <summary> /// Object Type /// </summary> public enum ObjectValues { ///<summary> ///Pushbutton. ///<para>When the item is serialized out as xml, its value is "Button".</para> ///</summary> [EnumString("Button")] Button, ///<summary> ///Checkbox. ///<para>When the item is serialized out as xml, its value is "Checkbox".</para> ///</summary> [EnumString("Checkbox")] Checkbox, ///<summary> ///Dialog. ///<para>When the item is serialized out as xml, its value is "Dialog".</para> ///</summary> [EnumString("Dialog")] Dialog, ///<summary> ///Dropdown Box. ///<para>When the item is serialized out as xml, its value is "Drop".</para> ///</summary> [EnumString("Drop")] Drop, ///<summary> ///Editable Text Field. ///<para>When the item is serialized out as xml, its value is "Edit".</para> ///</summary> [EnumString("Edit")] Edit, ///<summary> ///Group Box. ///<para>When the item is serialized out as xml, its value is "GBox".</para> ///</summary> [EnumString("GBox")] GroupBox, ///<summary> ///Label. ///<para>When the item is serialized out as xml, its value is "Label".</para> ///</summary> [EnumString("Label")] Label, ///<summary> ///Auditing Line. ///<para>When the item is serialized out as xml, its value is "LineA".</para> ///</summary> [EnumString("LineA")] AuditingLine, ///<summary> ///List Box. ///<para>When the item is serialized out as xml, its value is "List".</para> ///</summary> [EnumString("List")] List, ///<summary> ///Movie. ///<para>When the item is serialized out as xml, its value is "Movie".</para> ///</summary> [EnumString("Movie")] Movie, ///<summary> ///Comment. ///<para>When the item is serialized out as xml, its value is "Note".</para> ///</summary> [EnumString("Note")] Note, ///<summary> ///Image. ///<para>When the item is serialized out as xml, its value is "Pict".</para> ///</summary> [EnumString("Pict")] Picture, ///<summary> ///Radio Button. ///<para>When the item is serialized out as xml, its value is "Radio".</para> ///</summary> [EnumString("Radio")] Radio, ///<summary> ///Auditing Rectangle. ///<para>When the item is serialized out as xml, its value is "RectA".</para> ///</summary> [EnumString("RectA")] AuditingRectangle, ///<summary> ///Scroll Bar. ///<para>When the item is serialized out as xml, its value is "Scroll".</para> ///</summary> [EnumString("Scroll")] Scroll, ///<summary> ///Spin Button. ///<para>When the item is serialized out as xml, its value is "Spin".</para> ///</summary> [EnumString("Spin")] Spin, ///<summary> ///Plain Shape. ///<para>When the item is serialized out as xml, its value is "Shape".</para> ///</summary> [EnumString("Shape")] Shape, ///<summary> ///Group. ///<para>When the item is serialized out as xml, its value is "Group".</para> ///</summary> [EnumString("Group")] Group, ///<summary> ///Plain Rectangle. ///<para>When the item is serialized out as xml, its value is "Rect".</para> ///</summary> [EnumString("Rect")] Rectangle, } /// <summary> /// Boolean Value with Blank State /// </summary> public enum BooleanEntryWithBlankValues { ///<summary> ///Logical True. ///<para>When the item is serialized out as xml, its value is "True".</para> ///</summary> [EnumString("True")] True, ///<summary> ///Logical True. ///<para>When the item is serialized out as xml, its value is "t".</para> ///</summary> [EnumString("t")] T, ///<summary> ///Logical False. ///<para>When the item is serialized out as xml, its value is "False".</para> ///</summary> [EnumString("False")] False, ///<summary> ///Logical False. ///<para>When the item is serialized out as xml, its value is "f".</para> ///</summary> [EnumString("f")] F, ///<summary> ///Blank - Default Value. ///<para>When the item is serialized out as xml, its value is "".</para> ///</summary> [EnumString("")] Empty, } }
40.009137
122
0.634979
[ "MIT" ]
yangzhinong/Open-XML-SDK
src/DocumentFormat.OpenXml/GeneratedCode/schemas-microsoft-com_office_excel.g.cs
109,467
C#
namespace ChatApp.StockBot.MessageBroker { public class IntegrationEvent { } }
15
40
0.711111
[ "MIT" ]
guiportooo/chat-app
backend/src/ChatApp.StockBot/MessageBroker/IntegrationEvent.cs
90
C#
namespace MassTransit.Serialization { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Context; using Metadata; using Newtonsoft.Json; using Newtonsoft.Json.Linq; public class RawJsonConsumeContext : DeserializerConsumeContext { readonly JsonSerializer _deserializer; readonly JToken _messageToken; readonly IDictionary<Type, ConsumeContext> _messageTypes; public RawJsonConsumeContext(JsonSerializer deserializer, ReceiveContext receiveContext, JToken messageToken) : base(receiveContext) { _messageToken = messageToken ?? new JObject(); _deserializer = deserializer; _messageTypes = new Dictionary<Type, ConsumeContext>(); MessageId = receiveContext.GetMessageId(); CorrelationId = receiveContext.GetCorrelationId(); RequestId = receiveContext.GetRequestId(); } public override Guid? MessageId { get; } public override Guid? RequestId { get; } public override Guid? CorrelationId { get; } public override Guid? ConversationId { get; } = default; public override Guid? InitiatorId { get; } = default; public override DateTime? ExpirationTime => default; public override Uri SourceAddress { get; } = default; public override Uri DestinationAddress { get; } = default; public override Uri ResponseAddress { get; } = default; public override Uri FaultAddress { get; } = default; public override DateTime? SentTime => default; public override Headers Headers => new RawJsonHeaders(ReceiveContext.TransportHeaders); public override HostInfo Host => default; public override IEnumerable<string> SupportedMessageTypes => Enumerable.Empty<string>(); public override bool HasMessageType(Type messageType) { lock (_messageTypes) { if (_messageTypes.TryGetValue(messageType, out var existing)) return existing != null; } return false; } public override bool TryGetMessage<T>(out ConsumeContext<T> message) { lock (_messageTypes) { if (_messageTypes.TryGetValue(typeof(T), out var existing)) { message = existing as ConsumeContext<T>; return message != null; } if (typeof(T) == typeof(JToken)) { _messageTypes[typeof(T)] = message = new MessageConsumeContext<T>(this, _messageToken as T); return true; } try { object obj; var deserializeType = typeof(T); if (deserializeType.GetTypeInfo().IsInterface && TypeMetadataCache<T>.IsValidMessageType) deserializeType = TypeMetadataCache<T>.ImplementationType; using (var jsonReader = _messageToken.CreateReader()) { obj = _deserializer.Deserialize(jsonReader, deserializeType); } _messageTypes[typeof(T)] = message = new MessageConsumeContext<T>(this, (T)obj); return true; } catch (Exception) { _messageTypes[typeof(T)] = message = null; return false; } } } } }
33.90991
118
0.553401
[ "ECL-2.0", "Apache-2.0" ]
ThierrIO/MassTransit
src/MassTransit/Serialization/RawJsonConsumeContext.cs
3,764
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.DependencyInjection; namespace Squidex.Config.Authentication { public static class GithubAuthenticationServices { public static AuthenticationBuilder AddSquidexExternalGithubAuthentication(this AuthenticationBuilder authBuilder, MyIdentityOptions identityOptions) { if (identityOptions.IsGithubAuthConfigured()) { authBuilder.AddGitHub(options => { options.ClientId = identityOptions.GithubClient; options.ClientSecret = identityOptions.GithubSecret; options.Events = new GithubHandler(); }); } return authBuilder; } } }
37.193548
157
0.519514
[ "MIT" ]
BigHam/squidex
backend/src/Squidex/Config/Authentication/GithubAuthenticationServices.cs
1,156
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using NLog; using NLog.Web; namespace AspNetCoreNlog { public static class Program { public static void Main(string[] args) { var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try { logger.Debug("init main"); CreateHostBuilder(args).Build().Run(); } catch (Exception exception) { //NLog: catch setup errors logger.Error(exception, "Stopped program because of exception"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); }) .UseNLog(); // NLog: Setup NLog for Dependency injection } }
32.490196
128
0.56548
[ "MIT" ]
damienbod/AspNetCoreNlog
src/AspNetCoreNlog/Program.cs
1,659
C#
namespace _09.CollectionHierarchy.Interfaces { public interface IMyList : IAddRemoveCollection { } }
16.285714
51
0.72807
[ "MIT" ]
nikolaydechev/CSharp-OOP-Advanced
01 InterfacesAndAbstraction/09. CollectionHierarchy/Interfaces/IMyList.cs
116
C#
//----------------------------------------------------------------------- // <copyright file="VNode.cs" company="Breanos GmbH"> // Copyright Notice: // DAIPAN - This file, program or part of a program is considered part of the DAIPAN framework by Breanos GmbH for Industrie 4.0 // Published in 2018 by Gerhard Eder gerhard.eder@breanos.com and Achim Bernhard achim.bernhard@breanos.com // To the extent possible under law, the publishers have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. // You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // <date>Monday, December 3, 2018 3:34:35 PM</date> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace BreanosConnectors { namespace OpcUaConnector { /// <summary> /// Represents a group of nodes with differing Paths but same set of children /// </summary> [XmlRoot(ElementName = "VNode")] public class VNode : Node { [XmlArray] [XmlArrayItem(ElementName = "Path")] public string[] Paths { get; set; } private IEnumerable<string> GetSNodeRepresenatation() { var l = new List<string>(Paths); return l; } public override IEnumerable<string> GetPaths() { var a = new List<string>(); var b = GetSNodeRepresenatation(); if (IsLeaf) a.AddRange(GetSNodeRepresenatation()); else { var childPaths = new List<string>(); foreach (var child in Children) { childPaths.AddRange(child.GetPaths()); } a = (from self in b from other in childPaths select ($"{self}{Separator??"."}{other}")).ToList(); } return a; } public override IEnumerable<SNode> GetFlattenedStructure(string prePath, NodeConfiguration parentNodeConfiguration) { IEnumerable<string> localPrepaths; if (string.IsNullOrEmpty(prePath)) { localPrepaths = GetSNodeRepresenatation(); } else { localPrepaths = GetSNodeRepresenatation().Select(l => prePath + (Separator??".") + l); } var a = new List<SNode>(); if (IsLeaf) { a.AddRange(localPrepaths.Select(x => new SNode() { DeadbandType = DeadbandType, DeadbandValue = DeadbandValue, Path = x, Name=x, Separator = Separator, Config = this.Config != null ? this.Config : parentNodeConfiguration })); } else { foreach (var lpp in localPrepaths) { foreach (var child in Children) { a.AddRange(child.GetFlattenedStructure(lpp, this.Config != null ? this.Config : parentNodeConfiguration)); } } } return a; } } } }
40.836957
246
0.503593
[ "CC0-1.0" ]
BREANOS-ABE/daipan
MessagingQueue/BreanosConnectors/OpcUaConnector/OpcNodeXmlConfiguration/VNode.cs
3,759
C#
using System.Windows; namespace Clean_Randomizer { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
15.5
42
0.61828
[ "MIT" ]
STulling/Medabots-Randomizer
Clean_Randomizer/App.xaml.cs
188
C#
using Barista.Client.Level.UseCases; namespace Barista.Client.Level.Logic { public class LevelLogicViewUseCasesRepository { public IMovementInputPerformedUseCase MovementInputPerformedUseCase { get; } public IItemUIClickedUseCase ItemUIClickedUseCase { get; } public ISetupLevelUseCase SetupLevelUseCase { get; } public IExpectingHeroActionChangedUseCase ExpectingHeroActionChangedUseCase { get; } public IMoveHeroUseCase MoveHeroUseCase { get; } public IMoveEnemyUseCase MoveEnemyUseCase { get; } public IHeroGrabbedItemUseCase HeroGrabbedItemUseCase { get; } public IStartHeroItemTargetSelectionUseCase StartHeroItemTargetSelection { get; } public IHeroUsedItemUseCase HeroUsedItemUseCase { get; } public IHeroReceivedDamageUseCase HeroReceivedDamageUseCase { get; } public IEnemyDiedUseCase EnemyDiedUseCase { get; } public IEnemyClickedUseCase EnemyClickedUseCase { get; } public IScriptingScriptBeginsUseCase ScriptingScriptBeginsUseCase { get; } public IScriptingScriptEndsUseCase ScriptingScriptEndsUseCase { get; } public IScriptingActionPerformedUseCase ScriptingActionPerformedUseCase { get; } public IScriptingSharedBoolUseCase ScriptingSharedBoolUseCase { get; } public IScriptingSharedIntUseCase ScriptingSharedIntUseCase { get; } public IScriptingSharedFloatUseCase ScriptingSharedFloatUseCase { get; } public IScriptingSharedStringUseCase ScriptingSharedStringUseCase { get; } public IScriptingSharedHeroEntityUseCase ScriptingSharedHeroEntityUseCase { get; } public IScriptingSharedEnemyEntityUseCase ScriptingSharedEnemyEntityUseCase { get; } public LevelLogicViewUseCasesRepository( IMovementInputPerformedUseCase movementInputPerformedUseCase, IItemUIClickedUseCase itemUIClickedUseCase, ISetupLevelUseCase setupLevelUseCase, IExpectingHeroActionChangedUseCase expectingHeroActionChangedUseCase, IMoveHeroUseCase moveHeroUseCase, IMoveEnemyUseCase moveEnemyUseCase, IHeroGrabbedItemUseCase heroGrabbedItemUseCase, IStartHeroItemTargetSelectionUseCase startHeroItemTargetSelection, IHeroUsedItemUseCase heroUsedItemUseCase, IHeroReceivedDamageUseCase heroReceivedDamageUseCase, IEnemyDiedUseCase enemyDiedUseCase, IEnemyClickedUseCase enemyClickedUseCase, IScriptingScriptBeginsUseCase scriptingScriptBeginsUseCase, IScriptingScriptEndsUseCase scriptingScriptEndsUseCase, IScriptingActionPerformedUseCase scriptingActionPerformedUseCase, IScriptingSharedBoolUseCase scriptingSharedBoolUseCase, IScriptingSharedIntUseCase scriptingSharedIntUseCase, IScriptingSharedFloatUseCase scriptingSharedFloatUseCase, IScriptingSharedStringUseCase scriptingSharedStringUseCase, IScriptingSharedHeroEntityUseCase scriptingSharedHeroEntityUseCase, IScriptingSharedEnemyEntityUseCase scriptingSharedEnemyEntityUseCase ) { MovementInputPerformedUseCase = movementInputPerformedUseCase; ItemUIClickedUseCase = itemUIClickedUseCase; ExpectingHeroActionChangedUseCase = expectingHeroActionChangedUseCase; SetupLevelUseCase = setupLevelUseCase; MoveHeroUseCase = moveHeroUseCase; MoveEnemyUseCase = moveEnemyUseCase; HeroGrabbedItemUseCase = heroGrabbedItemUseCase; StartHeroItemTargetSelection = startHeroItemTargetSelection; HeroUsedItemUseCase = heroUsedItemUseCase; HeroReceivedDamageUseCase = heroReceivedDamageUseCase; EnemyDiedUseCase = enemyDiedUseCase; EnemyClickedUseCase = enemyClickedUseCase; ScriptingScriptBeginsUseCase = scriptingScriptBeginsUseCase; ScriptingScriptEndsUseCase = scriptingScriptEndsUseCase; ScriptingActionPerformedUseCase = scriptingActionPerformedUseCase; ScriptingSharedBoolUseCase = scriptingSharedBoolUseCase; ScriptingSharedIntUseCase = scriptingSharedIntUseCase; ScriptingSharedFloatUseCase = scriptingSharedFloatUseCase; ScriptingSharedStringUseCase = scriptingSharedStringUseCase; ScriptingSharedHeroEntityUseCase = scriptingSharedHeroEntityUseCase; ScriptingSharedEnemyEntityUseCase = scriptingSharedEnemyEntityUseCase; } } }
58.846154
92
0.757952
[ "MIT" ]
Guillemsc/Barista
Assets/Barista-Client/Runtime/Level/Logic/LevelLogicViewUseCasesRepository.cs
4,592
C#
using Xunit; using System.Collections.Generic; using EntityGraphQL.Schema; using System.Linq; using System; using EntityGraphQL.Extensions; namespace EntityGraphQL.Tests { public class FilteredFieldTests { [Fact] public void TestUseConstFilter() { var schema = SchemaBuilder.FromObject<TestDataContext>(); schema.ReplaceField("projects", new { search = (string)null }, (ctx, args) => ctx.Projects.OrderBy(p => p.Id), "List of projects"); Func<Task, bool> TaskFilter = t => t.IsActive == true; schema.Type<Project>().ReplaceField("tasks", p => p.Tasks.Where(TaskFilter), "Active tasks"); var gql = new QueryRequest { Query = @"query { projects { tasks { id } } }" }; var context = new TestDataContext { Projects = new List<Project> { new Project { Tasks = new List<Task> { new Task() }, } }, }; var res = schema.ExecuteRequest(gql, context, null, null); Assert.Null(res.Errors); dynamic project = Enumerable.ElementAt((dynamic)res.Data["projects"], 0); Type projectType = project.GetType(); Assert.Single(projectType.GetFields()); Assert.Equal("tasks", projectType.GetFields()[0].Name); } [Fact] public void TestWhereWhenOnNonRootField() { var schema = SchemaBuilder.FromObject<TestDataContext>(); schema.Type<Project>().ReplaceField("tasks", new { like = (string)null }, (project, args) => project.Tasks.WhereWhen(t => t.Name.Contains(args.like), !string.IsNullOrEmpty(args.like)), "List of project tasks"); var gql = new QueryRequest { Query = @"{ projects { tasks(like: ""h"") { name } } }" }; var context = new TestDataContext { Projects = new List<Project> { new Project { Tasks = new List<Task> { new Task { Name = "hello" }, new Task { Name = "world" }, }, Description = "Hello" } }, }; var res = schema.ExecuteRequest(gql, context, null, null); Assert.Null(res.Errors); dynamic project = Enumerable.First((dynamic)res.Data["projects"]); Type projectType = project.GetType(); Assert.Single(projectType.GetFields()); Assert.Equal("tasks", projectType.GetFields()[0].Name); } } }
30.465347
126
0.461163
[ "MIT" ]
EntityGraphQL/EntityGraphQL
src/tests/EntityGraphQL.Tests/QueryTests/FilteredFieldTests.cs
3,077
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 s3control-2018-08-20.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.S3Control.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using System.Xml; namespace Amazon.S3Control.Model.Internal.MarshallTransformations { /// <summary> /// GetAccessPointPolicy Request Marshaller /// </summary> public class GetAccessPointPolicyRequestMarshaller : IMarshaller<IRequest, GetAccessPointPolicyRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((GetAccessPointPolicyRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(GetAccessPointPolicyRequest publicRequest) { var request = new DefaultRequest(publicRequest, "Amazon.S3Control"); request.HttpMethod = "GET"; if (Arn.IsArn(publicRequest.Name)) { publicRequest.AccountId = Amazon.S3Control.Internal.S3ArnUtils.GetAccountIdBasedOnArn( publicRequest.AccountId, Arn.Parse(publicRequest.Name).AccountId ); } if(publicRequest.IsSetAccountId()) request.Headers["x-amz-account-id"] = publicRequest.AccountId; if (!publicRequest.IsSetName()) throw new AmazonS3ControlException("Request object does not have required field Name set"); request.AddPathResource("{name}", StringUtils.FromString(publicRequest.Name)); request.ResourcePath = "/v20180820/accesspoint/{name}/policy"; request.MarshallerVersion = 2; var hostPrefixLabels = new { AccountId = StringUtils.FromString(publicRequest.AccountId), }; if (!HostPrefixUtils.IsValidLabelValue(hostPrefixLabels.AccountId)) throw new AmazonS3ControlException("AccountId can only contain alphanumeric characters and dashes and must be between 1 and 63 characters long."); request.HostPrefix = $"{hostPrefixLabels.AccountId}."; return request; } private static GetAccessPointPolicyRequestMarshaller _instance = new GetAccessPointPolicyRequestMarshaller(); internal static GetAccessPointPolicyRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetAccessPointPolicyRequestMarshaller Instance { get { return _instance; } } } }
36.485981
170
0.642674
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/S3Control/Generated/Model/Internal/MarshallTransformations/GetAccessPointPolicyRequestMarshaller.cs
3,904
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Prism.CommonDialogPack { public class FileFilter { /// <summary> /// テキスト /// </summary> public string Text { get; set; } private List<string> extensions { get; } = new List<string>(); /// <summary> /// 拡張子リスト /// </summary> public IEnumerable<string> Extensions => this.extensions; public FileFilter(string text) { this.Text = text; } public FileFilter(string text, IEnumerable<string> extensions) : this(text) { this.extensions = new List<string>(extensions); } public FileFilter(string text, params string[] extensions) : this(text, (IEnumerable<string>)extensions) { } public void Add(string extension) { this.extensions.Add(extension); } public void AddRange(IEnumerable<string> extensions) { this.extensions.AddRange(extensions); } public void Remove(string extension) { this.extensions.Remove(extension); } public void Clear() { this.extensions.Clear(); } } }
23.160714
112
0.551272
[ "MIT" ]
Kuro4/Prism.CommonDialogPack
Prism.CommonDialogPack/FileFilter.cs
1,319
C#
using System; using System.Linq; using OfficeDevPnP.Core; namespace Microsoft.SharePoint.Client { /// <summary> /// Enables: Ratings / Likes functionality on list in publishing web. /// </summary> public static partial class ListRatingExtensions { /// TODO: Replace Logging throughout #region Rating Field private static readonly Guid RatingsFieldGuid_AverageRating = new Guid("5a14d1ab-1513-48c7-97b3-657a5ba6c742"); private static readonly Guid RatingsFieldGuid_RatingCount = new Guid("b1996002-9167-45e5-a4df-b2c41c6723c7"); private static readonly Guid RatingsFieldGuid_RatedBy = new Guid("4D64B067-08C3-43DC-A87B-8B8E01673313"); private static readonly Guid RatingsFieldGuid_Ratings = new Guid("434F51FB-FFD2-4A0E-A03B-CA3131AC67BA"); private static readonly Guid LikeFieldGuid_LikedBy = new Guid("2cdcd5eb-846d-4f4d-9aaf-73e8e73c7312"); private static readonly Guid LikeFieldGuid_LikeCount = new Guid("6e4d832b-f610-41a8-b3e0-239608efda41"); private static List _library; #endregion /// <summary> /// Enable Social Settings Likes/Ratings on list. /// Note: 1. Requires Publishing feature enabled on the web. /// 2. Defaults enable Ratings Experience on the List /// 3. When experience set to None, fields are not removed from the list since CSOM does not support removing hidden fields /// </summary> /// <param name="list">Current List</param> /// <param name="experience">Likes/Ratings</param> public static void SetRating(this List list, VotingExperience experience) { /* Validate if current web is publishing web * Add property to RootFolder of List/Library : key: Ratings_VotingExperience value:Likes * Add rating fields * Add fields to default view * */ _library = list; // only process publishing web if (!list.ParentWeb.IsPublishingWeb()) { ////_logger.WriteWarning("Is publishing site : No"); } // Add to property Root Folder of Pages Library SetProperty(experience); if (experience == VotingExperience.None) { RemoveViewFields(); } else { AddListFields(); // remove already existing fields from the default view to prevent duplicates RemoveViewFields(); AddViewFields(experience); } //_logger.WriteSuccess(string.Format("Enabled {0} on list/library {1}", experience, _library.Title)); } /// <summary> /// Removes the view fields associated with any rating type /// </summary> private static void RemoveViewFields() { _library.Context.Load(_library.DefaultView, p => p.ViewFields); _library.Context.ExecuteQueryRetry(); var defaultView = _library.DefaultView; if (defaultView.ViewFields.Contains("LikesCount")) defaultView.ViewFields.Remove("LikesCount"); if (defaultView.ViewFields.Contains("AverageRating")) defaultView.ViewFields.Remove("AverageRating"); defaultView.Update(); _library.Context.ExecuteQueryRetry(); } /// <summary> /// Add Ratings/Likes related fields to List from current Web /// </summary> private static void AddListFields() { EnsureField(_library, RatingsFieldGuid_RatingCount); EnsureField(_library, RatingsFieldGuid_RatedBy); EnsureField(_library, RatingsFieldGuid_Ratings); EnsureField(_library, RatingsFieldGuid_AverageRating); EnsureField(_library, LikeFieldGuid_LikedBy); EnsureField(_library, LikeFieldGuid_LikeCount); _library.Update(); _library.Context.ExecuteQueryRetry(); } /// <summary> /// Add/Remove Ratings/Likes field in default view depending on exerpeince selected /// </summary> /// <param name="experience"></param> private static void AddViewFields(VotingExperience experience) { // Add LikesCount and LikeBy (Explicit) to view fields _library.Context.Load(_library.DefaultView, p => p.ViewFields); _library.Context.ExecuteQueryRetry(); var defaultView = _library.DefaultView; switch (experience) { case VotingExperience.Ratings: // Remove Likes Fields if (defaultView.ViewFields.Contains("LikesCount")) defaultView.ViewFields.Remove("LikesCount"); defaultView.ViewFields.Add("AverageRating"); // Add Ratings related field break; case VotingExperience.Likes: // Remove Ratings Fields // Add Likes related field if (defaultView.ViewFields.Contains("AverageRating")) defaultView.ViewFields.Remove("AverageRating"); defaultView.ViewFields.Add("LikesCount"); break; default: throw new ArgumentOutOfRangeException("experience"); } defaultView.Update(); _library.Context.ExecuteQueryRetry(); //_logger.WriteSuccess("Ensured view-field."); } /// <summary> /// Removes a field from a list /// </summary> /// <param name="list"></param> /// <param name="fieldId"></param> private static void RemoveField(List list, Guid fieldId) { try { FieldCollection listFields = list.Fields; Field field = listFields.GetById(fieldId); field.DeleteObject(); _library.Context.ExecuteQueryRetry(); } catch (ArgumentException) { // Field does not exist } } /// <summary> /// Check for Ratings/Likes field and add to ListField if doesn't exists. /// </summary> /// <param name="list">List</param> /// <param name="fieldId">Field Id</param> /// <returns></returns> private static void EnsureField(List list, Guid fieldId) { FieldCollection fields = list.Fields; FieldCollection availableFields = list.ParentWeb.AvailableFields; Field field = availableFields.GetById(fieldId); _library.Context.Load(fields); _library.Context.Load(field, p => p.SchemaXmlWithResourceTokens, p => p.Id, p => p.InternalName, p => p.StaticName); _library.Context.ExecuteQueryRetry(); if (!fields.Any(p => p.Id == fieldId)) { fields.AddFieldAsXml(field.SchemaXmlWithResourceTokens, false, AddFieldOptions.AddFieldInternalNameHint | AddFieldOptions.AddToAllContentTypes); } } /// <summary> /// Add required key/value settings on List Root-Folder /// </summary> /// <param name="experience"></param> private static void SetProperty(VotingExperience experience) { _library.Context.Load(_library.RootFolder, p => p.Properties); _library.Context.ExecuteQueryRetry(); if (experience != VotingExperience.None) { _library.RootFolder.Properties["Ratings_VotingExperience"] = experience.ToString(); } else { _library.RootFolder.Properties["Ratings_VotingExperience"] = string.Empty; } _library.RootFolder.Update(); _library.Context.ExecuteQueryRetry(); //_logger.WriteSuccess(string.Format("Ensured {0} Property.", experience)); } } }
38.77619
160
0.585165
[ "MIT" ]
Sartor87/PnP-Sites-Core-cloned
Core/OfficeDevPnP.Core/AppModelExtensions/ListRatingExtensions.cs
8,143
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Irony.Parsing; namespace Irony.Samples { [Language("Clarion", "0.1", "Clarion grammar.")] public class ClarionGrammar : Grammar { //Special words - those that may not be used as proc names public readonly HashSet<string> SpecialWords; CommentTerminal _comment; public ClarionGrammar() : base(false) { //case insensitive base.GrammarComments = "Clarion grammar for parsing Clarion sources."; //Terminals var comment = new CommentTerminal("comment", "!", "\n"); this.NonGrammarTerminals.Add(comment); _comment = comment; var identifier = new IdentifierTerminal("identifier", ":", string.Empty); var label = new IdentifierTerminal("label", ":", string.Empty); label.ValidateToken += label_ValidateToken; label.Priority = TerminalPriority.High; //Clarion uses suffixes for identifying number base (bin, octal, hex) - unlike Irony's NumberLiteral which supports suffixes. // We treat all numbers as hexadecimal with optional sufffixes that don't mean anything. We "fix" the value in ValidateToken handler var number = new NumberLiteral("number"); number.Options = NumberOptions.Hex | NumberOptions.DisableQuickParse; number.AddSuffix("b", TypeCode.Int64); number.AddSuffix("o", TypeCode.Int64); number.AddSuffix("h", TypeCode.Int64); number.ValidateToken += number_ValidateToken; var string_lit = new StringLiteral("string_lit", "'", StringOptions.AllowsDoubledQuote | StringOptions.NoEscapes); var comma = ToTerm(","); var not = ToTerm("NOT"); //Non-terminals var source_file = new NonTerminal("source_file"); var main_file = new NonTerminal("main_file"); //whitespace - NewLine, Empty line, line with compiler directive, or line with end-tag of Compile(..) directive var wspace = new NonTerminal("wspace"); var ws_lines = new NonTerminal("ws_lines"); var ws_line = new NonTerminal("ws_line"); var compiler_dir = new NonTerminal("compiler_dir"); var compiler_dir_line = new NonTerminal("compiler_dir_line"); var cdir_compile_end_tag = new CustomTerminal("compile_end_tag", Match_compile_end_tag); var cdir_include = new NonTerminal("cdir_include"); var cdir_equate = new NonTerminal("cdir_equate"); var cdir_compile_omit = new NonTerminal("cdir_compile_omit"); var compile_or_omit = new NonTerminal("compile_or_omit"); var cdir_section = new NonTerminal("cdir_section"); var once_opt = new NonTerminal("once_opt"); var const_value = new NonTerminal("const_value"); var comma_expr_opt = new NonTerminal("comma_expr_opt"); var comma_string_lit_opt = new NonTerminal("comma_string_lit_opt"); var member_file = new NonTerminal("member_file"); var file_hearder = new NonTerminal("file_header"); var map = new NonTerminal("map"); var map_opt = new NonTerminal("map_opt"); var map_elem = new NonTerminal("map_elem"); var map_elem_list = new NonTerminal("map_elem_list"); var proc_decl_list = new NonTerminal("proc_decl_list"); var proc_decl = new NonTerminal("proc_decl"); var proc_impl_list = new NonTerminal("proc_impl_list"); var proc_impl = new NonTerminal("proc_impl"); var data_decl_list = new NonTerminal("data_decl_list"); var data_decl_list_opt = new NonTerminal("data_decl_list_opt"); var data_decl = new NonTerminal("data_decl"); var stmt_list = new NonTerminal("stmt_list"); var stmt_line = new NonTerminal("stmt_line"); var stmt = new NonTerminal("stmt"); var assign_stmt = new NonTerminal("assign_stmt"); var expr = new NonTerminal("expr"); var expr_opt = new NonTerminal("expr_opt"); var bin_expr = new NonTerminal("bin_expr"); var bin_op = new NonTerminal("bin_op"); var fun_call = new NonTerminal("fun_call"); var par_expr = new NonTerminal("par_expr"); var expr_list = new NonTerminal("expr_list"); var term = new NonTerminal("term"); var module_decl = new NonTerminal("module_decl"); var module_header = new NonTerminal("module_ref"); var data_type = new NonTerminal("data_type"); var param_init_opt = new NonTerminal("param_init_opt"); var type_args_opt = new NonTerminal("type_args_opt"); var type_arg_list = new NonTerminal("type_arg_list"); var type_arg = new NonTerminal("type_arg"); var label_opt = new NonTerminal("label_opt"); var param_list = new NonTerminal("param_list"); var param = new NonTerminal("param"); var param_list_par_opt = new NonTerminal("param_list_par_opt"); var attr_list_tail_opt = new NonTerminal("attr_list_tail_opt"); var attr_list = new NonTerminal("attr_list"); var attr_def = new NonTerminal("attr_def"); var return_line_opt = new NonTerminal("return_line_opt"); var end_line = new NonTerminal("end_line"); //Rules base.Root = source_file; source_file.Rule = main_file | member_file; //whitespace - includes compiler directives wspace.Rule = NewLine + ws_lines;// +ReduceHere(); ws_lines.Rule = MakeStarRule(ws_lines, ws_line); ws_line.Rule = compiler_dir | PreferShiftHere() + NewLine + ReduceHere(); //compiler_dir_line.Rule = compiler_dir; compiler_dir.Rule = cdir_include | cdir_equate | cdir_compile_omit | cdir_section | cdir_compile_end_tag; cdir_include.Rule = ToTerm("INCLUDE") + "(" + string_lit + comma_string_lit_opt + ")" + once_opt; comma_string_lit_opt.Rule = Empty | comma + string_lit; once_opt.Rule = comma + "ONCE" | Empty; cdir_equate.Rule = //ShiftIf("EQUATE").ComesBefore(NewLine) + label + "EQUATE" + "(" + const_value + ")"; const_value.Rule = number | string_lit; cdir_compile_omit.Rule = compile_or_omit + "(" + string_lit + comma_expr_opt + ")"; comma_expr_opt.Rule = Empty | comma + expr; cdir_section.Rule = ToTerm("SECTION") + "(" + string_lit + ")"; compile_or_omit.Rule = ToTerm("COMPILE") | "OMIT"; //File structure main_file.Rule = "PROGRAM" + wspace + map + data_decl_list_opt + wspace + "CODE" + wspace + stmt_list + return_line_opt + proc_impl_list; member_file.Rule = "MEMBER" + wspace + map_opt + data_decl_list + proc_impl_list; //map map_opt.Rule = map | Empty; map.Rule = "MAP" + wspace + map_elem_list + end_line; map_elem_list.Rule = MakeStarRule(map_elem_list, wspace, map_elem); map_elem.Rule = proc_decl | module_header; module_decl.Rule = module_header + proc_decl_list + end_line; module_header.Rule = ToTerm("MODULE") + "(" + string_lit + ")" + wspace; proc_decl_list.Rule = MakePlusRule(proc_decl_list, proc_decl); proc_decl.Rule = label + "PROCEDURE" + param_list_par_opt + attr_list_tail_opt + wspace; param_list_par_opt.Rule = Empty | "(" + param_list + ")"; param_list.Rule = MakePlusRule(param_list, comma, param); param.Rule = data_type + identifier + param_init_opt; param_init_opt.Rule = Empty | "=" + number; data_type.Rule = identifier + type_args_opt; type_args_opt.Rule = Empty | "(" + type_arg_list + ")"; type_arg_list.Rule = MakePlusRule(type_arg_list, comma, type_arg); type_arg.Rule = number | identifier; attr_list_tail_opt.Rule = Empty | comma + attr_list; attr_list.Rule = MakePlusRule(attr_list, comma, attr_def); attr_def.Rule = identifier + param_list_par_opt; data_decl_list.Rule = MakePlusRule(data_decl_list, data_decl); data_decl_list_opt.Rule = data_decl_list | Empty; data_decl.Rule = identifier + data_type + wspace; proc_impl_list.Rule = MakeStarRule(proc_impl_list, proc_impl); proc_impl.Rule = proc_decl + data_decl_list + "CODE" + wspace + stmt_list + return_line_opt + wspace; stmt_list.Rule = MakeStarRule(stmt_list, stmt_line); stmt_line.Rule = stmt + wspace; stmt.Rule = assign_stmt | fun_call; assign_stmt.Rule = identifier + "=" + expr; expr.Rule = fun_call | par_expr | bin_expr | term; par_expr.Rule = "(" + expr + ")"; bin_expr.Rule = expr + bin_op + expr; bin_op.Rule = ToTerm("+") | "-" | "*" | "/" | "^" | "%" | "&" | "=" | "<" | ">" | "~=" | "~<" | "~>" | not + "=" | not + "<" | not + ">" | "<>" | "<=" | "=<" | ">=" | "=>" | "~" | not | "AND" | "OR" | "XOR"; fun_call.Rule = identifier + "(" + expr_list + ")"; expr_list.Rule = MakeStarRule(expr_list, comma, expr); expr_opt.Rule = expr | Empty; term.Rule = identifier | number | string_lit; return_line_opt.Rule = "RETURN" + expr_opt | Empty; end_line.Rule = "END" + NewLine | "." + NewLine; //operator precedence RegisterOperators(10, "OR", "XOR"); RegisterOperators(20, "AND"); RegisterOperators(50, "=", "<", ">", "~=", "~<", "~>", "<>", "<=", "=<", ">=", "=>"); RegisterOperators(100, "+", "-"); RegisterOperators(110, "*", "/", "%", "&"); RegisterOperators(120, Associativity.Right, "^"); RegisterOperators(130, not); RegisterOperators(130, "~"); //punctuation, brace pairs, transient nodes MarkPunctuation("(", ")", ","); RegisterBracePair("(", ")"); //Reserved words and special words var resWordList = "ACCEPT AND BEGIN BREAK BY CASE CHOOSE COMPILE CYCLE DO ELSE ELSIF END EXECUTE EXIT FUNCTION GOTO IF INCLUDE LOOP" + " MEMBER NEW NOT NULL OF OMIT OR OROF PARENT PROCEDURE PROGRAM RETURN ROUTINE SECTION SELF THEN TIMES TO UNTIL WHILE XOR"; this.MarkReservedWords(resWordList.Split(' ')); var specialWordsList = "APPLICATION CLASS CODE DATA DETAIL FILE FOOTER FORM GROUP HEADER ITEM ITEMIZE JOIN MAP MENU MENUBAR" + " MODULE OLECONTROL OPTION QUEUE RECORD REPORT ROW SHEET TAB TABLE TOOLBAR VIEW WINDOW"; //Initialize special words list (words that cannot be used as proc names); we'll later use them for verifying proc names SpecialWords = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); SpecialWords.UnionWith(specialWordsList.Split(' ')); } #region Parsing event handlers Token Match_compile_end_tag(Terminal terminal, ParsingContext context, ISourceStream source) { if (source.MatchSymbol("__End")) { var p = source.Location.Position; var lineEnd = source.Text.IndexOf("\n", p); var text = source.Text.Substring(p, lineEnd - p + 1); return new Token(_comment, source.Location, text, text); } //otherwise return null return null; } //All numbers are treated as HEX initially; here we need to analyze suffix (if any) and convert the value void number_ValidateToken(object sender, ValidateTokenEventArgs e) { } void label_ValidateToken(object sender, ValidateTokenEventArgs e) { //check that token starts at position 0 if (e.Token.Location.Column > 0) //Column is 0-based e.RejectToken(); }//constructor #endregion }//class }
49.029536
147
0.642169
[ "MIT" ]
Color-Of-Code/Irony
Irony.Samples/Clarion.cs
11,622
C#
namespace SimpleBlog.Models { using Microsoft.AspNet.Identity.EntityFramework; using System.Data.Entity; // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class BlogDbContext : IdentityDbContext<ApplicationUser> { public BlogDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public virtual IDbSet<Article> Articles { get; set; } public static BlogDbContext Create() { return new BlogDbContext(); } } }
28.652174
176
0.660091
[ "MIT" ]
borisbotev/SimpleMVCBlog
SimpleBlog/SimpleBlog/Models/BlogDbContext.cs
661
C#
using System; namespace Zignificant.Models.Requests { public class HistoryUpdateRequest : HistoryCreateRequest { public int Id { get; set; } } }
15.272727
60
0.672619
[ "MIT" ]
ijac213/zignificant
Zignificant.Models/Requests/HistoryUpdateRequest.cs
170
C#
using ASP.NET_CORE_MongoDB.Contracts.Filters; using ASP.NET_CORE_MongoDB.Entities; using ASP.NET_CORE_MongoDB.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace ASP.NET_CORE_MongoDB.Builders { public class PeopleFilterBuilder : IBuildPeopleFilter { private readonly List<Expression<Func<People, bool>>> _filters; public PeopleFilterBuilder() { _filters = new List<Expression<Func<People, bool>>>(); } public Expression<Func<People, bool>> Build() => _filters.Any() ? _filters.ConcatWithAnd() : null; public IBuildPeopleFilter WithName(PeopleFilter filter) { if (!string.IsNullOrWhiteSpace(filter.Name)) _filters.Add(x => x.Name.Contains(filter.Name)); return this; } public IBuildPeopleFilter WithLastName(PeopleFilter filter) { if (!string.IsNullOrWhiteSpace(filter.LastName)) _filters.Add(x => x.LastName.Contains(filter.LastName)); return this; } public IBuildPeopleFilter WithGenre(PeopleFilter filter) { if (filter.Genre.HasValue) _filters.Add(x => x.Genre == filter.Genre); return this; } } }
28.208333
72
0.624815
[ "MIT" ]
dougglas1/ASP.NET_CORE_MongoDB
ASP.NET_CORE_MongoDB/Builders/PeopleFilterBuilder.cs
1,356
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 devicefarm-2015-06-23.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DeviceFarm.Model { /// <summary> /// Container for the parameters to the UpdateVPCEConfiguration operation. /// Updates information about an existing Amazon Virtual Private Cloud (VPC) endpoint /// configuration. /// </summary> public partial class UpdateVPCEConfigurationRequest : AmazonDeviceFarmRequest { private string _arn; private string _serviceDnsName; private string _vpceConfigurationDescription; private string _vpceConfigurationName; private string _vpceServiceName; /// <summary> /// Gets and sets the property Arn. /// <para> /// The Amazon Resource Name (ARN) of the VPC endpoint configuration you want to update. /// </para> /// </summary> [AWSProperty(Required=true, Min=32, Max=1011)] public string Arn { get { return this._arn; } set { this._arn = value; } } // Check to see if Arn property is set internal bool IsSetArn() { return this._arn != null; } /// <summary> /// Gets and sets the property ServiceDnsName. /// <para> /// The DNS (domain) name used to connect to your private service in your Amazon VPC. /// The DNS name must not already be in use on the Internet. /// </para> /// </summary> [AWSProperty(Min=0, Max=2048)] public string ServiceDnsName { get { return this._serviceDnsName; } set { this._serviceDnsName = value; } } // Check to see if ServiceDnsName property is set internal bool IsSetServiceDnsName() { return this._serviceDnsName != null; } /// <summary> /// Gets and sets the property VpceConfigurationDescription. /// <para> /// An optional description, providing more details about your VPC endpoint configuration. /// </para> /// </summary> [AWSProperty(Min=0, Max=2048)] public string VpceConfigurationDescription { get { return this._vpceConfigurationDescription; } set { this._vpceConfigurationDescription = value; } } // Check to see if VpceConfigurationDescription property is set internal bool IsSetVpceConfigurationDescription() { return this._vpceConfigurationDescription != null; } /// <summary> /// Gets and sets the property VpceConfigurationName. /// <para> /// The friendly name you give to your VPC endpoint configuration, to manage your configurations /// more easily. /// </para> /// </summary> [AWSProperty(Min=0, Max=1024)] public string VpceConfigurationName { get { return this._vpceConfigurationName; } set { this._vpceConfigurationName = value; } } // Check to see if VpceConfigurationName property is set internal bool IsSetVpceConfigurationName() { return this._vpceConfigurationName != null; } /// <summary> /// Gets and sets the property VpceServiceName. /// <para> /// The name of the VPC endpoint service running inside your AWS account that you want /// Device Farm to test. /// </para> /// </summary> [AWSProperty(Min=0, Max=2048)] public string VpceServiceName { get { return this._vpceServiceName; } set { this._vpceServiceName = value; } } // Check to see if VpceServiceName property is set internal bool IsSetVpceServiceName() { return this._vpceServiceName != null; } } }
33.084507
108
0.611963
[ "Apache-2.0" ]
TallyUpTeam/aws-sdk-net
sdk/src/Services/DeviceFarm/Generated/Model/UpdateVPCEConfigurationRequest.cs
4,698
C#
namespace MxM { public enum EEventWarpType { None, Snap, Linear, Dynamic }//End of class: EEventWarpType }//End of namespace: MxM
13.615385
35
0.553672
[ "MIT" ]
suweitao8/MotionMatchingTutorial
Assets/Plugins/MotionMatching/Code/MxM/Enumerations/EEventWarpType.cs
179
C#
namespace Classbook.Data.Configurations { using Classbook.Data.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; public class NoteConfiguration : IEntityTypeConfiguration<Note> { public void Configure(EntityTypeBuilder<Note> builder) { builder.HasKey(n => n.Id); builder.Property(n => n.Content) .IsRequired(true) .IsUnicode(true); builder.HasOne(n => n.Mark) .WithMany(m => m.Notes) .HasForeignKey(n => n.MarkId) .OnDelete(DeleteBehavior.Restrict); builder.HasOne(n => n.Student) .WithMany(s => s.Notes) .HasForeignKey(n => n.StudentId) .OnDelete(DeleteBehavior.Restrict); } } }
28.666667
67
0.568605
[ "MIT" ]
ivan-nikolov/Classbook
Src/Data/Classbook.Data/Configurations/NoteConfiguration.cs
862
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows.Forms; namespace ControlAgent { class Commands { public static List<String> RunCommand(Command command) { Logger logger = new Logger(); logger.LogCommand(command); switch (command) { case Command.Getproc: return GetProcessList(); case Command.Sleep: return SleepComputer(); case Command.Shutdown: return ShutdownComputer(); case Command.Restart: return RestartComputer(); default: //execution won't get here, b/c exception is thrown parsing the command enum if it is invalid return new List<string>() { "Command Not Found" }; } } /// <summary> /// Put the computer to sleep /// </summary> /// <returns>List with status</returns> private static List<String> SleepComputer() { Application.SetSuspendState(PowerState.Suspend, true, true); return new List<string>() { "Sleep Command Executed Successfully" }; } /// <summary> /// Shutdown the computer /// </summary> /// <returns>List with status</returns> private static List<String> ShutdownComputer() { Process.Start("timeout 3 > NUL && shutdown -s -t 0"); return new List<string>() { "Shutdown Command Executed Successfully" }; } /// <summary> /// Restart the computer /// </summary> /// <returns>List with status</returns> private static List<String> RestartComputer() { Process.Start("timeout 3 > NUL && shutdown -r -t 0"); return new List<string>() { "Restart Command Executed Successfully" }; } /// <summary> /// Get a list of all processes running on the computer /// </summary> /// <returns>List with status, and then process name and PID, delimited with a |</returns> private static List<string> GetProcessList() { List<string> processes = new List<string>() { "Getproc Command Executed Successfully" }; Process[] processArray = Process.GetProcesses(); foreach (Process proc in processArray) { processes.Add(proc.Id + "|" + proc.Handle); } return processes; //This list has only one item with spaces in it (status), so filter list in Swift for spaces (those without are processes) } public enum Command { Sleep, Shutdown, Restart, Getproc } } }
33.488372
134
0.534375
[ "MIT" ]
zzzanderw/ControlAgent_Windows
ControlAgent/Commands.cs
2,882
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 apigatewayv2-2018-11-29.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ApiGatewayV2.Model { /// <summary> /// An immutable representation of an API that can be called by users. A Deployment must /// be associated with a Stage for it to be callable over the internet. /// </summary> public partial class Deployment { private DateTime? _createdDate; private string _deploymentId; private DeploymentStatus _deploymentStatus; private string _deploymentStatusMessage; private string _description; /// <summary> /// Gets and sets the property CreatedDate. /// <para> /// The date and time when the Deployment resource was created. /// </para> /// </summary> public DateTime CreatedDate { get { return this._createdDate.GetValueOrDefault(); } set { this._createdDate = value; } } // Check to see if CreatedDate property is set internal bool IsSetCreatedDate() { return this._createdDate.HasValue; } /// <summary> /// Gets and sets the property DeploymentId. /// <para> /// The identifier for the deployment. /// </para> /// </summary> public string DeploymentId { get { return this._deploymentId; } set { this._deploymentId = value; } } // Check to see if DeploymentId property is set internal bool IsSetDeploymentId() { return this._deploymentId != null; } /// <summary> /// Gets and sets the property DeploymentStatus. /// <para> /// The status of the deployment: PENDING, FAILED, or SUCCEEDED. /// </para> /// </summary> public DeploymentStatus DeploymentStatus { get { return this._deploymentStatus; } set { this._deploymentStatus = value; } } // Check to see if DeploymentStatus property is set internal bool IsSetDeploymentStatus() { return this._deploymentStatus != null; } /// <summary> /// Gets and sets the property DeploymentStatusMessage. /// <para> /// May contain additional feedback on the status of an API deployment. /// </para> /// </summary> public string DeploymentStatusMessage { get { return this._deploymentStatusMessage; } set { this._deploymentStatusMessage = value; } } // Check to see if DeploymentStatusMessage property is set internal bool IsSetDeploymentStatusMessage() { return this._deploymentStatusMessage != null; } /// <summary> /// Gets and sets the property Description. /// <para> /// The description for the deployment. /// </para> /// </summary> public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } } }
30.887218
110
0.599562
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/ApiGatewayV2/Generated/Model/Deployment.cs
4,108
C#
using TechTalk.SpecFlow; using AppiumWebdriver.Activities; namespace AppiumWebdriver.Steps { [Binding] public class MainActivitySteps { // Given I am on the main activity [Given(@"I am on the main activity")] public void GivenIAmOnTheMainActivity() { MainActivity.Open(); } // When I send a message saying '<message>' [When(@"I send a message saying '(.*)'")] public void WhenISendAMessageSaying(string message) { MainActivity.SendMessage(message); } } }
24.083333
59
0.596886
[ "MIT" ]
kirbycope/cucumber-csharp
AppiumWebdriver/Steps/MainActivitySteps.cs
580
C#
using System; using System.IO; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Uno.Extensions.Hosting; namespace Uno.Extensions.Configuration { public static class HostBuilderExtensions { public const string ConfigurationFolderName = "config"; /// <summary> /// Makes the entire Configuration available to the app (required /// for use with IWritableOptions) /// </summary> /// <param name="hostBuilder"></param> /// <returns></returns> public static IHostBuilder UseConfiguration(this IHostBuilder hostBuilder) { return hostBuilder .ConfigureServices((ctx, s) => { s.TryAddSingleton<IConfiguration>(a => ctx.Configuration); s.TryAddSingleton<IConfigurationRoot>(a => (IConfigurationRoot)ctx.Configuration); s.TryAddSingleton<Reloader>(); s.TryAddSingleton<ReloadService>(); _ = s.AddHostedService<ReloadService>(sp => sp.GetRequiredService<ReloadService>()); s.AddSingleton<IStartupService>(sp => sp.GetRequiredService<ReloadService>()); }); } public static IHostBuilder UseAppSettings(this IHostBuilder hostBuilder, bool includeEnvironmentSettings = true) { return hostBuilder .UseConfiguration() .ConfigureAppConfiguration((ctx, b) => { b.AddAppSettings(ctx); if (includeEnvironmentSettings) { b.AddEnvironmentAppSettings(ctx); } }); } public static IHostBuilder UseEmbeddedAppSettings<TApplicationRoot>(this IHostBuilder hostBuilder, bool includeEnvironmentSettings = true) where TApplicationRoot : class { return hostBuilder .UseConfiguration() .ConfigureAppConfiguration((ctx, b) => { b.AddEmbeddedAppSettings<TApplicationRoot>(); if (includeEnvironmentSettings) { b.AddEmbeddedEnvironmentAppSettings<TApplicationRoot>(ctx); } }); } public static IHostBuilder UseSettings<TSettingsOptions>( this IHostBuilder hostBuilder, Func<HostBuilderContext, IConfigurationSection>? configSection = null) where TSettingsOptions : class, new() { if (configSection is null) { configSection = ctx => ctx.Configuration.GetSection(typeof(TSettingsOptions).Name); } static string FilePath(HostBuilderContext hctx) { var prefix = hctx.Configuration.GetValue(HostingConstants.AppSettingsPrefixKey, defaultValue: string.Empty); prefix = !string.IsNullOrWhiteSpace(prefix) ? $"{prefix}/" : prefix; var file = $"{prefix}{ConfigurationFolderName}/{AppSettings.AppSettingsFileName}.{typeof(TSettingsOptions).Name}.json"; var appData = (hctx.HostingEnvironment as IAppHostEnvironment)?.AppDataPath ?? string.Empty; var path = Path.Combine(appData, file); return path; } // This is consistent with HostBuilder, which defaults to Production return hostBuilder .UseConfiguration() .ConfigureAppConfiguration((ctx, b) => { var path = FilePath(ctx); Console.WriteLine($"iwrit Config path {path}"); b.AddJsonFile(path, optional: true, reloadOnChange: false); // In .NET6 we can enable this again because we can use polling }) .ConfigureServices((ctx, services) => { var section = configSection(ctx); services.ConfigureAsWritable<TSettingsOptions>(section, FilePath(ctx)); } ); } public static IHostBuilder UseConfiguration<TOptions>(this IHostBuilder hostBuilder, string? configurationSection = null) where TOptions : class { if (configurationSection is null) { configurationSection = typeof(TOptions).Name; } return hostBuilder .UseConfiguration() .ConfigureServices((ctx, services) => services.Configure<TOptions>(ctx.Configuration.GetSection(configurationSection))); } public static IHostBuilder AddConfigurationSectionFromEntity<TEntity>( this IHostBuilder hostBuilder, TEntity entity, string? sectionName = default) { return hostBuilder .ConfigureHostConfiguration( configurationBuilder => configurationBuilder.AddSectionFromEntity(entity, sectionName)); } } }
38.92126
147
0.613393
[ "Apache-2.0" ]
twins2020/uno.extensions
src/Uno.Extensions.Configuration/HostBuilderExtensions.cs
4,945
C#
using System; using System.Linq; using HotChocolate; using StrawberryShake.CodeGeneration.Descriptors.TypeDescriptors; namespace StrawberryShake.CodeGeneration.Extensions; public static class TypeDescriptorExtensions { public static bool IsLeaf(this ITypeDescriptor typeDescriptor) => typeDescriptor.Kind == TypeKind.Leaf; public static bool IsEntity(this ITypeDescriptor typeDescriptor) => typeDescriptor.Kind == TypeKind.Entity; public static bool IsData(this ITypeDescriptor typeDescriptor) => typeDescriptor.Kind == TypeKind.Data || typeDescriptor.Kind == TypeKind.AbstractData; public static bool ContainsEntity(this ITypeDescriptor typeDescriptor) { return typeDescriptor switch { ListTypeDescriptor listTypeDescriptor => listTypeDescriptor.InnerType.ContainsEntity(), ComplexTypeDescriptor namedTypeDescriptor => namedTypeDescriptor.Properties .Any(prop => prop.Type.IsEntity() || prop.Type.ContainsEntity()), NonNullTypeDescriptor nonNullTypeDescriptor => nonNullTypeDescriptor.InnerType.ContainsEntity(), _ => false }; } public static bool IsOrContainsEntity(this ITypeDescriptor typeDescriptor) { return typeDescriptor switch { ListTypeDescriptor d => d.InnerType.IsOrContainsEntity(), InterfaceTypeDescriptor d => d.IsEntity() || d.Properties.Any(p => p.Type.IsEntity() || p.Type.IsOrContainsEntity()) || d.ImplementedBy.Any(x => x.IsOrContainsEntity()), ComplexTypeDescriptor d => d.IsEntity() || d.Properties.Any(p => p.Type.IsEntity() || p.Type.IsOrContainsEntity()), NonNullTypeDescriptor d => d.InnerType.IsOrContainsEntity(), _ => false }; } public static bool IsInterface(this ITypeDescriptor typeDescriptor) => typeDescriptor is InterfaceTypeDescriptor; public static bool IsNullable(this ITypeDescriptor typeDescriptor) => typeDescriptor is not NonNullTypeDescriptor; public static bool IsNonNull(this ITypeDescriptor typeDescriptor) => typeDescriptor is NonNullTypeDescriptor; public static bool IsList(this ITypeDescriptor typeDescriptor) => typeDescriptor is ListTypeDescriptor || typeDescriptor is NonNullTypeDescriptor { InnerType: ListTypeDescriptor }; public static ITypeDescriptor InnerType(this ITypeDescriptor typeDescriptor) { if (typeDescriptor is NonNullTypeDescriptor n) { return n.InnerType; } if (typeDescriptor is ListTypeDescriptor l) { return l.InnerType; } return typeDescriptor; } public static ITypeDescriptor NamedType(this ITypeDescriptor typeDescriptor) { return typeDescriptor .InnerType() .InnerType() .InnerType() .InnerType() .InnerType() .InnerType(); } public static NameString GetName(this ITypeDescriptor typeDescriptor) { if (typeDescriptor.NamedType() is INamedTypeDescriptor namedType) { return namedType.Name; } throw new InvalidOperationException("Invalid type structure."); } public static RuntimeTypeInfo GetRuntimeType(this ITypeDescriptor typeDescriptor) { if (typeDescriptor.NamedType() is INamedTypeDescriptor namedType) { return namedType.RuntimeType; } throw new InvalidOperationException("Invalid type structure."); } }
32.353448
88
0.651745
[ "MIT" ]
ChilliCream/prometheus
src/StrawberryShake/CodeGeneration/src/CodeGeneration/Extensions/TypeDescriptorExtensions.cs
3,753
C#
// Copyright 2015-2017 Xamarin Inc. All rights reserved. using System; using System.Linq; using Mono.Linker; using Mono.Tuner; using Mono.Cecil; using Mono.Cecil.Cil; #if MTOUCH using MonoTouch; using MonoTouch.Tuner; using Xamarin.Bundler; #elif MMP || MMP_TEST using MonoMac; using MonoMac.Tuner; using Xamarin.Bundler; #else using ObjCRuntime; #endif namespace Xamarin.Linker.Steps { public class CoreHttpMessageHandler : ExceptionalSubStep { public CoreHttpMessageHandler () { } public override SubStepTargets Targets { get { return SubStepTargets.Type; } } protected override string Name { get; } = "Default HttpMessageHandler setter"; protected override int ErrorCode { get; } = 2040; Application App { get { return LinkContext.App; } } public override bool IsActiveFor (AssemblyDefinition assembly) { switch (assembly.Name.Name) { #if MONOMAC case "Xamarin.Mac": return context.Annotations.GetAction (assembly) == AssemblyAction.Link; #else case "Xamarin.iOS": case "Xamarin.TVOS": case "Xamarin.WatchOS": return context.Annotations.GetAction (assembly) == AssemblyAction.Link; #endif default: return false; } } protected override void Process (TypeDefinition type) { if (!type.Is ("ObjCRuntime", "RuntimeOptions")) return; MethodDefinition method = type.Methods.First (x => x.Name == "GetHttpMessageHandler" && !x.HasParameters); AssemblyDefinition systemNetHTTPAssembly = context.GetAssemblies ().First (x => x.Name.Name == "System.Net.Http"); TypeDefinition handler = RuntimeOptions.GetHttpMessageHandler (App, LinkContext.Target.LinkerOptions.RuntimeOptions, systemNetHTTPAssembly.MainModule, type.Module); MethodReference handler_ctor = handler.Methods.First (x => x.IsConstructor && !x.HasParameters && !x.IsStatic); // HttpClientHandler is defined in System.Net.Http.dll so we need to import if (handler.Name.Contains ("HttpClientHandler")) handler_ctor = type.Module.ImportReference (handler_ctor); var body = new MethodBody (method); var il = body.GetILProcessor (); il.Emit (OpCodes.Newobj, handler_ctor); il.Emit (OpCodes.Ret); method.Body = body; } } }
26.626506
167
0.727602
[ "BSD-3-Clause" ]
NormanChiflen/xamarin-all-IOS
tools/linker/CoreHttpMessageHandler.cs
2,210
C#
namespace VolleyManagement.Domain.TeamsAggregate { public class TeamTournamentDto { public int TeamId { get; set; } public string TeamName { get; set; } public int DivisionId { get; set; } public string DivisionName { get; set; } public int GroupId { get; set; } public string GroupName { get; set; } } }
20.611111
49
0.603774
[ "MIT" ]
VolleyManagement/volley-management
archive/src/VolleyManagement.Backend/VolleyManagement.Domain/TeamsAggregate/TeamTournamentDto.cs
373
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Raygun4Net2.0")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Raygun")] [assembly: AssemblyProduct("Raygun4Net")] [assembly: AssemblyCopyright("Copyright © Raygun 2014-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("abb6f683-a923-44b8-afc9-7e8441770789")]
41.75
84
0.776447
[ "MIT" ]
totalkyos/ray-gun
Mindscape.Raygun4Net2/Properties/AssemblyInfo.cs
1,005
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.PooledObjects; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class LocalDeclarationRewriter { internal static BoundStatement Rewrite( CSharpCompilation compilation, EENamedTypeSymbol container, HashSet<LocalSymbol> declaredLocals, BoundStatement node, ImmutableArray<LocalSymbol> declaredLocalsArray, DiagnosticBag diagnostics) { var builder = ArrayBuilder<BoundStatement>.GetInstance(); foreach (var local in declaredLocalsArray) { CreateLocal(compilation, declaredLocals, builder, local, node.Syntax, diagnostics); } // Rewrite top-level declarations only. switch (node.Kind) { case BoundKind.LocalDeclaration: Debug.Assert(declaredLocals.Contains(((BoundLocalDeclaration)node).LocalSymbol)); RewriteLocalDeclaration(builder, (BoundLocalDeclaration)node); break; case BoundKind.MultipleLocalDeclarations: foreach (var declaration in ((BoundMultipleLocalDeclarations)node).LocalDeclarations) { Debug.Assert(declaredLocals.Contains(declaration.LocalSymbol)); RewriteLocalDeclaration(builder, declaration); } break; default: if (builder.Count == 0) { builder.Free(); return node; } builder.Add(node); break; } return BoundBlock.SynthesizedNoLocals(node.Syntax, builder.ToImmutableAndFree()); } private static void RewriteLocalDeclaration( ArrayBuilder<BoundStatement> statements, BoundLocalDeclaration node) { Debug.Assert(node.ArgumentsOpt.IsDefault); var initializer = node.InitializerOpt; if (initializer != null) { var local = node.LocalSymbol; var syntax = node.Syntax; // Generate assignment to local. The assignment will // be rewritten in PlaceholderLocalRewriter. var type = local.Type.TypeSymbol; var assignment = new BoundAssignmentOperator( syntax, new BoundLocal(syntax, local, constantValueOpt: null, type: type), initializer, false, type); statements.Add(new BoundExpressionStatement(syntax, assignment)); } } private static void CreateLocal( CSharpCompilation compilation, HashSet<LocalSymbol> declaredLocals, ArrayBuilder<BoundStatement> statements, LocalSymbol local, SyntaxNode syntax, DiagnosticBag diagnostics) { // CreateVariable(Type type, string name) var method = PlaceholderLocalSymbol.GetIntrinsicMethod(compilation, ExpressionCompilerConstants.CreateVariableMethodName); if ((object)method == null) { diagnostics.Add(ErrorCode.ERR_DeclarationExpressionNotPermitted, local.Locations[0]); return; } declaredLocals.Add(local); var typeType = compilation.GetWellKnownType(WellKnownType.System_Type); var stringType = compilation.GetSpecialType(SpecialType.System_String); var guidConstructor = (MethodSymbol)compilation.GetWellKnownTypeMember(WellKnownMember.System_Guid__ctor); var type = new BoundTypeOfOperator(syntax, new BoundTypeExpression(syntax, aliasOpt: null, type: local.Type.TypeSymbol), null, typeType); var name = new BoundLiteral(syntax, ConstantValue.Create(local.Name), stringType); bool hasCustomTypeInfoPayload; var customTypeInfoPayload = GetCustomTypeInfoPayload(local, syntax, compilation, out hasCustomTypeInfoPayload); var customTypeInfoPayloadId = GetCustomTypeInfoPayloadId(syntax, guidConstructor, hasCustomTypeInfoPayload); var call = BoundCall.Synthesized( syntax, receiverOpt: null, method: method, arguments: ImmutableArray.Create(type, name, customTypeInfoPayloadId, customTypeInfoPayload)); statements.Add(new BoundExpressionStatement(syntax, call)); } private static BoundExpression GetCustomTypeInfoPayloadId(SyntaxNode syntax, MethodSymbol guidConstructor, bool hasCustomTypeInfoPayload) { if (!hasCustomTypeInfoPayload) { return new BoundDefaultExpression(syntax, guidConstructor.ContainingType); } var value = ConstantValue.Create(CustomTypeInfo.PayloadTypeId.ToString()); return new BoundObjectCreationExpression( syntax, guidConstructor, null, new BoundLiteral(syntax, value, guidConstructor.ContainingType)); } private static BoundExpression GetCustomTypeInfoPayload(LocalSymbol local, SyntaxNode syntax, CSharpCompilation compilation, out bool hasCustomTypeInfoPayload) { var byteArrayType = ArrayTypeSymbol.CreateSZArray( compilation.Assembly, TypeSymbolWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Byte))); var bytes = compilation.GetCustomTypeInfoPayload(local.Type.TypeSymbol, customModifiersCount: 0, refKind: RefKind.None); hasCustomTypeInfoPayload = bytes != null; if (!hasCustomTypeInfoPayload) { return new BoundLiteral(syntax, ConstantValue.Null, byteArrayType); } var byteType = byteArrayType.ElementType.TypeSymbol; var intType = compilation.GetSpecialType(SpecialType.System_Int32); var numBytes = bytes.Count; var initializerExprs = ArrayBuilder<BoundExpression>.GetInstance(numBytes); foreach (var b in bytes) { initializerExprs.Add(new BoundLiteral(syntax, ConstantValue.Create(b), byteType)); } var lengthExpr = new BoundLiteral(syntax, ConstantValue.Create(numBytes), intType); return new BoundArrayCreation( syntax, ImmutableArray.Create<BoundExpression>(lengthExpr), new BoundArrayInitialization(syntax, initializerExprs.ToImmutableAndFree()), byteArrayType); } } }
43.542169
167
0.621334
[ "Apache-2.0" ]
Ashera138/roslyn
src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/LocalDeclarationRewriter.cs
7,230
C#
using System; using System.Collections.Generic; namespace CarShop { class Program { static void Main(string[] args) { IEnumerable<Car> cars = new CarRepository().GetAll(); CarsView view = new CarsView(cars); view.Render(); Console.Write("Press ENTER to exit..."); Console.ReadLine(); } } }
18.619048
65
0.542199
[ "CC0-1.0" ]
rajeeshckr/javascript-practical-design-patterns
managing-responsibilities/6-tactical-design-patterns-dotnet-managing-responsibilities-m6-exercise-files/1 CarShop Basic/CarShop/Program.cs
393
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DirectorySvgConverterSample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DirectorySvgConverterSample")] [assembly: AssemblyCopyright("Copyright © 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6143fde5-85b1-4375-90f4-7ddfe7e2272d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.567568
84
0.750526
[ "BSD-3-Clause" ]
yavor87/sharpvectors
Samples/SharpVectorsSamples/DirectorySvgConverterSample/Properties/AssemblyInfo.cs
1,430
C#
using System; using System.Globalization; using System.Linq; using System.Windows.Data; namespace Cobalt.Common.UI.Converters { public class HumanReadableTimeSpanConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var duration = value as TimeSpan? ?? new TimeSpan(); return string.Join("", new[] { duration.Days != 0 ? $" {duration.Days}d" : "", duration.Hours != 0 ? $" {duration.Hours}h" : "", duration.Minutes != 0 ? $" {duration.Minutes}m" : "", duration.Seconds != 0 ? $" {duration.Seconds}s" : "", duration.Milliseconds != 0 ? $" {duration.Milliseconds:00}ms" : "" } .Where(x => !string.IsNullOrWhiteSpace(x)) .Take(2)); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
36.8
103
0.548007
[ "MIT" ]
Enigmatrix/Cobalt
Cobalt.Common.UI/Converters/HumanReadableTimeSpanConverter.cs
1,106
C#
using FluentValidation; using MediatR; using Microsoft.Extensions.DependencyInjection; using Ordering.Application.Behaviours; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Ordering.Application { public static class ApplicationServiceRegistration { public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services.AddAutoMapper(Assembly.GetExecutingAssembly()); services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly()); services.AddMediatR(Assembly.GetExecutingAssembly()); services.AddTransient(typeof(IPipelineBehavior<,>), typeof(UnhandeledExeptionBehavior<,>)); services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>)); return services; } } }
32.275862
103
0.742521
[ "MIT" ]
sarasn93/AspnetMicroservicesTest
src/Services/Ordering/Ordering.Application/ApplicationServiceRegistration.cs
938
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Management.Automation.Runspaces; using System.Collections; using Microsoft.SharePoint.Client; namespace PnP.PowerShell.Tests.Lists { [TestClass] public class GetListItemTests { private static string listTitle; private static PSTestScope scope; private static int itemId; #region Setup [ClassInitialize] public static void Initialize(TestContext testContext) { scope = new PSTestScope(); listTitle = $"TempList {Guid.NewGuid()}"; var values = new Hashtable(); values.Add("Title", "Test Item"); scope.ExecuteCommand("New-PnPList", new CommandParameter("Title", listTitle), new CommandParameter("Template", ListTemplateType.GenericList) ); var results = scope.ExecuteCommand("Add-PnPListItem", new CommandParameter("List", listTitle), new CommandParameter("Values", values)); if (results.Count > 0) { itemId = ((ListItem)results[0].BaseObject).Id; } } [ClassCleanup] public static void Cleanup() { scope.ExecuteCommand("Remove-PnPList", new CommandParameter("Identity", listTitle), new CommandParameter("Force")); scope.Dispose(); } #endregion #region Scaffolded Cmdlet Tests [TestMethod] public void GetPnPListItemTest() { var results = scope.ExecuteCommand("Get-PnPListItem", new CommandParameter("List", listTitle), new CommandParameter("Id", itemId)); Assert.AreEqual(results.Count, 1); } #endregion } }
28.707692
74
0.57985
[ "MIT" ]
tom-daly/powershell
src/Tests/Lists/GetPnPListItemTests.cs
1,866
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.SDK.Cms20190101.Models { public class PutMonitorGroupDynamicRuleResponse : TeaModel { [NameInMap("RequestId")] [Validation(Required=true)] public string RequestId { get; set; } [NameInMap("Success")] [Validation(Required=true)] public bool? Success { get; set; } [NameInMap("Code")] [Validation(Required=true)] public int? Code { get; set; } [NameInMap("Message")] [Validation(Required=true)] public string Message { get; set; } } }
22.548387
64
0.62804
[ "Apache-2.0" ]
atptro/alibabacloud-sdk
cms-20190101/csharp/core/Models/PutMonitorGroupDynamicRuleResponse.cs
699
C#
using System; namespace Tacto { public class HttpConnectionManager: ConnectionManager { public const string UrlGMapsSearch = "http://www.google.com/maps/search/"; public HttpConnectionManager(string url) : base( url ) { this.URL = this.URL.Replace( 'º', ' ' ) .Replace( 'ª', ' ' ) .Replace( '\\', ' ' ) .Replace( ',', ' ' ); } public override void Open() { OpenDocument( Protocol.Http, this.URL ); } } }
20.590909
76
0.598234
[ "MIT" ]
Baltasarq/Tacto
Core/HttpConnectionManager.cs
455
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Powershell - Network Resource Manager")] [assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)] [assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)] [assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] [assembly: Guid("be2ca022-590c-48ba-b465-9ab61d6e2ea0")] [assembly: AssemblyVersion("3.2.0")] [assembly: AssemblyFileVersion("3.2.0")] #if !SIGN [assembly: InternalsVisibleTo("Microsoft.Azure.PowerShell.Cmdlets.Network.Test")] #endif
48.151515
104
0.696035
[ "MIT" ]
GossiTheDog/azure-powershell
src/Network/Network/Properties/AssemblyInfo.cs
1,557
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityCollectionResponse.cs.tt namespace Microsoft.Graph { using System.Collections.Generic; using System.Text.Json.Serialization; /// <summary> /// The type AccessPackageAssignmentAccessPackageAssignmentResourceRolesCollectionResponse. /// </summary> public class AccessPackageAssignmentAccessPackageAssignmentResourceRolesCollectionResponse { /// <summary> /// Gets or sets the <see cref="IAccessPackageAssignmentAccessPackageAssignmentResourceRolesCollectionPage"/> value. /// </summary> [JsonPropertyName("value")] public IAccessPackageAssignmentAccessPackageAssignmentResourceRolesCollectionPage Value { get; set; } /// <summary> /// Gets or sets the nextLink string value. /// </summary> [JsonPropertyName("@odata.nextLink")] [JsonConverter(typeof(NextLinkConverter))] public string NextLink { get; set; } /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData] public IDictionary<string, object> AdditionalData { get; set; } } }
40.25641
153
0.619108
[ "MIT" ]
ScriptBox99/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/AccessPackageAssignmentAccessPackageAssignmentResourceRolesCollectionResponse.cs
1,570
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using FASTER.core; using NUnit.Framework; namespace FASTER.test { [TestFixture] internal class BlittableLogCompactionTests { private FasterKV<KeyStruct, ValueStruct> fht; private IDevice log; [SetUp] public void Setup() { TestUtils.DeleteDirectory(TestUtils.MethodTestDir, wait:true); log = Devices.CreateLogDevice(TestUtils.MethodTestDir + "/BlittableLogCompactionTests.log", deleteOnClose: true); fht = new FasterKV<KeyStruct, ValueStruct> (1L << 20, new LogSettings { LogDevice = log, MemorySizeBits = 15, PageSizeBits = 9 }); } [TearDown] public void TearDown() { fht?.Dispose(); fht = null; log?.Dispose(); log = null; TestUtils.DeleteDirectory(TestUtils.MethodTestDir); } [Test] [Category("FasterKV")] [Category("Compaction")] [Category("Smoke")] public void BlittableLogCompactionTest1([Values] CompactionType compactionType) { using var session = fht.For(new FunctionsCompaction()).NewSession<FunctionsCompaction>(); InputStruct input = default; const int totalRecords = 2000; var start = fht.Log.TailAddress; long compactUntil = 0; for (int i = 0; i < totalRecords; i++) { if (i == 1000) compactUntil = fht.Log.TailAddress; var key1 = new KeyStruct { kfield1 = i, kfield2 = i + 1 }; var value = new ValueStruct { vfield1 = i, vfield2 = i + 1 }; session.Upsert(ref key1, ref value, 0, 0); } compactUntil = session.Compact(compactUntil, compactionType); fht.Log.Truncate(); Assert.AreEqual(compactUntil, fht.Log.BeginAddress); // Read 2000 keys - all should be present for (int i = 0; i < totalRecords; i++) { OutputStruct output = default; var key1 = new KeyStruct { kfield1 = i, kfield2 = i + 1 }; var value = new ValueStruct { vfield1 = i, vfield2 = i + 1 }; var status = session.Read(ref key1, ref input, ref output, 0, 0); if (status.IsPending) session.CompletePending(true); else { Assert.IsTrue(status.Found); Assert.AreEqual(value.vfield1, output.value.vfield1); Assert.AreEqual(value.vfield2, output.value.vfield2); } } } [Test] [Category("FasterKV")] [Category("Compaction")] public void BlittableLogCompactionTest2([Values] CompactionType compactionType) { using var session = fht.For(new FunctionsCompaction()).NewSession<FunctionsCompaction>(); InputStruct input = default; const int totalRecords = 2000; var start = fht.Log.TailAddress; long compactUntil = 0; for (int i = 0; i < totalRecords; i++) { if (i == 1000) compactUntil = fht.Log.TailAddress; var key1 = new KeyStruct { kfield1 = i, kfield2 = i + 1 }; var value = new ValueStruct { vfield1 = i, vfield2 = i + 1 }; session.Upsert(ref key1, ref value, 0, 0); } // Put fresh entries for 1000 records for (int i = 0; i < 1000; i++) { var key1 = new KeyStruct { kfield1 = i, kfield2 = i + 1 }; var value = new ValueStruct { vfield1 = i, vfield2 = i + 1 }; session.Upsert(ref key1, ref value, 0, 0); } fht.Log.Flush(true); var tail = fht.Log.TailAddress; compactUntil = session.Compact(compactUntil, compactionType); fht.Log.Truncate(); Assert.AreEqual(compactUntil, fht.Log.BeginAddress); Assert.AreEqual(tail, fht.Log.TailAddress); // Read 2000 keys - all should be present for (int i = 0; i < totalRecords; i++) { OutputStruct output = default; var key1 = new KeyStruct { kfield1 = i, kfield2 = i + 1 }; var value = new ValueStruct { vfield1 = i, vfield2 = i + 1 }; var status = session.Read(ref key1, ref input, ref output, 0, 0); if (status.IsPending) session.CompletePending(true); else { Assert.IsTrue(status.Found); Assert.AreEqual(value.vfield1, output.value.vfield1); Assert.AreEqual(value.vfield2, output.value.vfield2); } } } [Test] [Category("FasterKV")] [Category("Compaction")] public void BlittableLogCompactionTest3([Values] CompactionType compactionType) { using var session = fht.For(new FunctionsCompaction()).NewSession<FunctionsCompaction>(); InputStruct input = default; const int totalRecords = 2000; var start = fht.Log.TailAddress; long compactUntil = 0; for (int i = 0; i < totalRecords; i++) { if (i == totalRecords / 2) compactUntil = fht.Log.TailAddress; var key1 = new KeyStruct { kfield1 = i, kfield2 = i + 1 }; var value = new ValueStruct { vfield1 = i, vfield2 = i + 1 }; session.Upsert(ref key1, ref value, 0, 0); if (i % 8 == 0) { int j = i / 4; key1 = new KeyStruct { kfield1 = j, kfield2 = j + 1 }; session.Delete(ref key1, 0, 0); } } var tail = fht.Log.TailAddress; compactUntil = session.Compact(compactUntil, compactionType); fht.Log.Truncate(); Assert.AreEqual(compactUntil, fht.Log.BeginAddress); // Read 2000 keys - all should be present for (int i = 0; i < totalRecords; i++) { OutputStruct output = default; var key1 = new KeyStruct { kfield1 = i, kfield2 = i + 1 }; var value = new ValueStruct { vfield1 = i, vfield2 = i + 1 }; int ctx = ((i < 500) && (i % 2 == 0)) ? 1 : 0; var status = session.Read(ref key1, ref input, ref output, ctx, 0); if (status.IsPending) session.CompletePending(true); else { if (ctx == 0) { Assert.IsTrue(status.Found); Assert.AreEqual(value.vfield1, output.value.vfield1); Assert.AreEqual(value.vfield2, output.value.vfield2); } else { Assert.IsFalse(status.Found); } } } } [Test] [Category("FasterKV")] [Category("Compaction")] [Category("Smoke")] public void BlittableLogCompactionCustomFunctionsTest1([Values] CompactionType compactionType) { using var session = fht.For(new FunctionsCompaction()).NewSession<FunctionsCompaction>(); InputStruct input = default; const int totalRecords = 2000; var start = fht.Log.TailAddress; var compactUntil = 0L; for (var i = 0; i < totalRecords; i++) { if (i == totalRecords / 2) compactUntil = fht.Log.TailAddress; var key1 = new KeyStruct { kfield1 = i, kfield2 = i + 1 }; var value = new ValueStruct { vfield1 = i, vfield2 = i + 1 }; session.Upsert(ref key1, ref value, 0, 0); } var tail = fht.Log.TailAddress; // Only leave records with even vfield1 compactUntil = session.Compact(compactUntil, compactionType, default(EvenCompactionFunctions)); fht.Log.Truncate(); Assert.AreEqual(compactUntil, fht.Log.BeginAddress); // Read 2000 keys - all should be present for (var i = 0; i < totalRecords; i++) { OutputStruct output = default; var key1 = new KeyStruct { kfield1 = i, kfield2 = i + 1 }; var value = new ValueStruct { vfield1 = i, vfield2 = i + 1 }; var ctx = (i < (totalRecords / 2) && (i % 2 != 0)) ? 1 : 0; var status = session.Read(ref key1, ref input, ref output, ctx, 0); if (status.IsPending) { session.CompletePending(true); } else { if (ctx == 0) { Assert.IsTrue(status.Found); Assert.AreEqual(value.vfield1, output.value.vfield1); Assert.AreEqual(value.vfield2, output.value.vfield2); } else { Assert.IsFalse(status.Found); } } } } [Test] [Category("FasterKV")] [Category("Compaction")] public void BlittableLogCompactionCustomFunctionsTest2([Values] CompactionType compactionType) { // Update: irrelevant as session compaction no longer uses Copy/CopyInPlace // This test checks if CopyInPlace returning false triggers call to Copy using var session = fht.For(new FunctionsCompaction()).NewSession<FunctionsCompaction>(); var key = new KeyStruct { kfield1 = 100, kfield2 = 101 }; var value = new ValueStruct { vfield1 = 10, vfield2 = 20 }; session.Upsert(ref key, ref value, 0, 0); fht.Log.Flush(true); value = new ValueStruct { vfield1 = 11, vfield2 = 21 }; session.Upsert(ref key, ref value, 0, 0); fht.Log.Flush(true); var compactUntil = session.Compact(fht.Log.TailAddress, compactionType); fht.Log.Truncate(); var input = default(InputStruct); var output = default(OutputStruct); var status = session.Read(ref key, ref input, ref output, 0, 0); if (status.IsPending) { session.CompletePending(true); } else { Assert.IsTrue(status.Found); Assert.AreEqual(value.vfield1, output.value.vfield1); Assert.AreEqual(value.vfield2, output.value.vfield2); } } private struct EvenCompactionFunctions : ICompactionFunctions<KeyStruct, ValueStruct> { public bool IsDeleted(ref KeyStruct key, ref ValueStruct value) => value.vfield1 % 2 != 0; } } }
36.063492
125
0.506778
[ "MIT" ]
ColdwindY/FASTER
cs/test/BlittableLogCompactionTests.cs
11,362
C#
namespace Idone.DAL.DTO { using System.Collections.Generic; using LanguageExt; /// <summary> /// DTO права доступа для роли. /// </summary> public class DtoLinkRolePermissions : Record<DtoLinkRolePermissions> { /// <summary> /// Конструктор по умолчанию. /// </summary> /// <param name="roleId"> Идентификатор роли. </param> /// <param name="permissionIds"> Идентификаторы прав.</param> public DtoLinkRolePermissions(int roleId, IEnumerable<int> permissionIds) { RoleId = roleId; PermissionIds = permissionIds; } /// <summary> /// Идентификаторы прав. /// </summary> public IEnumerable<int> PermissionIds { get; } /// <summary> /// Идентификатор роли. /// </summary> public int RoleId { get; } } }
26.848485
81
0.563205
[ "MIT" ]
GregoryGhost/idone
Idone/Idone.DAL/DTO/DtoLinkRolePermissions.cs
999
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable disable using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace MVCSample.Areas.Identity.Pages.Account.Manage { public class TwoFactorAuthenticationModel : PageModel { private readonly UserManager<IdentityUser> _userManager; private readonly SignInManager<IdentityUser> _signInManager; private readonly ILogger<TwoFactorAuthenticationModel> _logger; public TwoFactorAuthenticationModel( UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager, ILogger<TwoFactorAuthenticationModel> logger) { _userManager = userManager; _signInManager = signInManager; _logger = logger; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public bool HasAuthenticator { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public int RecoveryCodesLeft { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [BindProperty] public bool Is2faEnabled { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public bool IsMachineRemembered { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [TempData] public string StatusMessage { get; set; } public async Task<IActionResult> OnGetAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } HasAuthenticator = await _userManager.GetAuthenticatorKeyAsync(user) != null; Is2faEnabled = await _userManager.GetTwoFactorEnabledAsync(user); IsMachineRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user); RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user); return Page(); } public async Task<IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } await _signInManager.ForgetTwoFactorClientAsync(); StatusMessage = "The current browser has been forgotten. When you login again from this browser you will be prompted for your 2fa code."; return RedirectToPage(); } } }
42.277778
149
0.648883
[ "MIT" ]
christiannagel/ProfessionalCSharp2021
3_Web/RazorAndMVC/MVCSample/Areas/Identity/Pages/Account/Manage/TwoFactorAuthentication.cshtml.cs
3,807
C#
/* * Written by James Leahy (c) 2017 DeFunc Art. */ using UnityEngine; [CreateAssetMenu(fileName = "New LevelData", menuName = "LevelData", order = 1000)] public class LevelData : ScriptableObject { public int levelIndex; public int numberOfPlayerLives; public bool isTimed; public float timeLimit; public override string ToString () { return string.Format("[LevelData:levelIndex={0}, numberOfPlayerLives={1}, isTimed={2}, timeLimit={3}]", levelIndex, numberOfPlayerLives, isTimed, timeLimit); } }
25.85
106
0.733075
[ "MIT" ]
LifeIsJourney/50-unity-tips
#08-ScriptableObjects/LevelData.cs
519
C#
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using NUnit.Framework; using Spring.Collections; using Spring.Objects.Factory.Config; namespace Spring.Objects.Factory.Support { [TestFixture] public class ManagedSetTests { [Test] public void MergeSunnyDay() { ManagedSet parent = new ManagedSet(); parent.Add("one"); parent.Add("two"); ManagedSet child = new ManagedSet(); child.Add("three"); child.MergeEnabled = true; ISet mergedList = (ISet) child.Merge(parent); Assert.AreEqual(3, mergedList.Count); } [Test] public void MergeWithNullParent() { ManagedSet child = new ManagedSet(); child.Add("one"); child.MergeEnabled = true; Assert.AreSame(child, child.Merge(null)); } [Test] public void MergeNotAllowedWhenMergeNotEnabled() { ManagedSet child = new ManagedSet(); Assert.Throws<InvalidOperationException>(() => child.Merge(null), "Not allowed to merge when the 'MergeEnabled' property is set to 'false'"); } [Test] public void MergeWithNonCompatibleParentType() { ManagedSet child = new ManagedSet(); child.Add("one"); child.MergeEnabled = true; Assert.Throws<InvalidOperationException>(() => child.Merge("hello")); } [Test] public void MergeEmptyChild() { ManagedSet parent = new ManagedSet(); parent.Add("one"); parent.Add("two"); ManagedSet child = new ManagedSet(); child.MergeEnabled = true; ISet mergedSet = (ISet) child.Merge(parent); Assert.AreEqual(2, mergedSet.Count); } [Test] public void MergeChildValueOverrideTheParents() { ManagedSet parent = new ManagedSet(); parent.Add("one"); parent.Add("two"); ManagedSet child = new ManagedSet(); child.Add("one"); child.MergeEnabled = true; ISet mergedList = (ISet) child.Merge(parent); Assert.AreEqual(2, mergedList.Count); } } }
31.705263
154
0.573041
[ "Apache-2.0" ]
Magicianred/spring-net
test/Spring/Spring.Core.Tests/Objects/Factory/Support/ManagedSetTests.cs
3,012
C#
#if UNITY_EDITOR using UnityEngine; namespace O3DWB { public interface IPivotPointRenderer { #region Interface Methods void Render(Vector3 pivotPoint, Color fillColor, Color borderLineColor, float sizeInPixels); #endregion } } #endif
20.846154
100
0.708487
[ "MIT" ]
AestheticalZ/Faithful-SCP-Unity
Assets/Octave3D World Builder/Scripts/Rendering/Objects/Object Pivot Points/IPivotPointRenderer.cs
273
C#
namespace FlexProviders.Roles { public interface IFlexRoleProvider { bool IsUserInRole(string username, string roleName, string license = null); string[] GetRolesForUser(string username, string license = null); void CreateRole(string roleName); bool DeleteRole(string roleName, bool throwOnPopulatedRole); bool RoleExists(string roleName); void AddUsersToRoles(string[] usernames, string[] roleNames, string license = null); void RemoveUsersFromRoles(string[] usernames, string[] roleNames, string license = null); string[] GetUsersInRole(string roleName, string license = null); string[] GetAllUsersInRole(string roleName); string[] GetAllRoles(); } }
47.0625
98
0.693227
[ "MIT" ]
OdeToCode/Memflex
src/FlexProviders/Roles/IFlexRoleProvider.cs
753
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ten_Thousand { class Game { private Player[] players; private int currentPlayer; private Die[] Dice; private Random generator; private int[][] sets; private int currentTurnScore; private int rollNum; private bool availableMove; private bool[] scoredAtRoundBegining; //An array containg which dice were scored at the begining of the round private int holdingCurrentTurnScore; private bool endGameActive; private bool gameActiveState; private const int TEN_THOUSAND = 10000; public Game(string[] names) { players = new Player[names.Length]; for (int i = 0; i < names.Length; i++) players[i] = new Player(names[i]); Dice = new Die[5] { new Die(), new Die(), new Die(), new Die(), new Die() }; currentPlayer = 0; generator = new Random(); sets = new int[7][]; scoredAtRoundBegining = new bool[5]; rollNum = 0; currentTurnScore = 0; holdingCurrentTurnScore = 0; endGameActive = false; gameActiveState = true; } /// <summary> /// Returns the current players name and score /// </summary> /// <returns>Array in which first item is player name and second item it player score</returns> public string[] currentPlayerInfo() { return new string[] { players[currentPlayer].getName(), Convert.ToString(players[currentPlayer].getScore()), Convert.ToString(currentTurnScore) }; } /// <summary> /// Returns the score of the current turn /// </summary> /// <returns>Current Turn Score</returns> public int getTurnScore() { return currentTurnScore; } /// <summary> /// Randomly sets the values of the rollable die /// </summary> public void rollEm() { if (!gameActiveState) return; if (checkAllScored()) { foreach (Die dice in Dice) { dice.setRollable(true); dice.unlockValue(); } holdingCurrentTurnScore = currentTurnScore; } for (int i = 0; i < Dice.Length; i++) { scoredAtRoundBegining[i] = Dice[i].isRollable(); if (Dice[i].isRollable()) { Dice[i].SetValue(generator.Next(6) + 1); Dice[i].setRollNum(rollNum); } else { Dice[i].ageValue(); Dice[i].lockValue(); } } rollNum++; checkScorable(); calculateScore(); checkForAvailableMoves(); } /// <summary> /// Figures out which die are scoreable and sets the values in the array scorable /// </summary> private void checkScorable() { //If the number is 1 or 5, the number is always scorable for (int i = 0; i < Dice.Length; i++) if ((Dice[i].GetValue() == 5 || Dice[i].GetValue() == 1) && !Dice[i].isLocked()) Dice[i].setScorable(true); List<int> tempLocations; for (int i = 1; i < 7; i++)//One iteration for each possible die value { tempLocations = new List<int>(); for (int die = 0; die < Dice.Length; die++) // One iteration for each die if (Dice[die].GetValue() == i) //If the die is equal to the value we are checking for this iteration, add the die location to teh array tempLocations.Add(die); sets[i] = tempLocations.ToArray(); // Add the array to the sets array } for (int i = 1; i < sets.Length; i++) //One iteration for each possible die value if (sets[i].Length > 2)//If there are 3 or more of that value in the die... { //Check if any of them are old values bool allNew = true; foreach (int location in sets[i]) { if (!Dice[location].isNewValue()) allNew = false; } if(allNew)//If all the values are new foreach (int location in sets[i]) //Go through each of the locations where that value occurs Dice[location].setScorable(true); //Set that location's scorable status to true else//If some of the values are new foreach (int location in sets[i]) //Go through each of the locations where that value occurs if(!Dice[location].isNewValue())//Find the locations where the value isn't new Dice[location].setScorable(true); //Set that location's scorable status to true } } /// <summary> /// Toggles the status of die at die Number if it is scorable /// </summary> /// <param name="dieNumber">The die to toggle (first die is 0)</param> /// <returns>Whether the Die was toggled</returns> public void dieClick(int dieNumber) { if (Dice[dieNumber].isScorable() && !Dice[dieNumber].isLocked()) { if (Dice[dieNumber].GetValue() == 1 || Dice[dieNumber].GetValue() == 5) Dice[dieNumber].toggleRollable(); else foreach (int location in sets[Dice[dieNumber].GetValue()]) //Go through each of the locations where that value occurs if (Dice[location].isScorable())//Make sure that Dice is scorable Dice[location].toggleRollable();//Toggle that location's rollable status } calculateScore(); Dice[dieNumber].isScorable(); checkForAvailableMoves(); } /// <summary> /// Returns an array of bool, indicating which are rollable /// </summary> /// <returns>Array of booleans indicating which are rollable</returns> public bool[] getRollable() { bool[] rollable = new bool[5]; for (int i = 0; i < Dice.Length; i++) { rollable[i] = Dice[i].isRollable(); } return rollable; } /// <summary> /// Returns and array of int, indicating the values of the die /// </summary> /// <returns>An array of ints indicating the values of the die</returns> public int[] getDieValues() { int[] dieValue = new int[5]; for (int i = 0; i < Dice.Length; i++) { dieValue[i] = Dice[i].GetValue(); } return dieValue; } /// <summary> /// Updates the current turn score /// </summary> private void calculateScore() { currentTurnScore = 0; currentTurnScore += holdingCurrentTurnScore; int[][] scoredSets = new int[7][]; for (int i = 1; i < scoredSets.Length; i++)//One iteration for each possible die value { List<int> localSet = new List<int>(); for (int dieNumber = 0; dieNumber < Dice.Length; dieNumber++) //Check every die... if (Dice[dieNumber].GetValue() == i && !Dice[dieNumber].isRollable()) //If it matches the number we are currently checkint and that it is scored localSet.Add(dieNumber); //Than add it to a local set of all scored die locations for that value scoredSets[i] = localSet.ToArray(); //Add the list to the scored sets } for (int i = 2; i < scoredSets.Length; i++) //For every die value from 2 to 6 { if (i == 5) //Skip 5, we handle it seperately continue; if (scoredSets[i].Length == 3) currentTurnScore += 100 * i; if (scoredSets[i].Length == 4) currentTurnScore += 3000; if (scoredSets[i].Length == 5) currentTurnScore += 10000; } //How to score the number 5 if (scoredSets[5].Length == 3) { bool allSameAge = true; for (int i = 1; i < scoredSets[5].Length; i++) if (Dice[scoredSets[5][0]].getRollNum() != Dice[scoredSets[5][i]].getRollNum()) allSameAge = false; if (allSameAge) currentTurnScore += 750; else currentTurnScore += 50 * scoredSets[5].Length; } else if (scoredSets[5].Length == 4) { bool allSameAge = true; for (int i = 1; i < scoredSets[5].Length; i++) if (Dice[scoredSets[5][0]].getRollNum() != Dice[scoredSets[5][i]].getRollNum()) allSameAge = false; int[] ages = new int[4]; for (int i = 0; i < scoredSets[5].Length; i++) ages[i] = Dice[scoredSets[5][i]].getRollNum(); var dict = new Dictionary<int, int>(); foreach (int d in ages) if (dict.ContainsKey(d)) dict[d]++; else dict.Add(d, 1); bool setOfThree = false; foreach (KeyValuePair<int, int> kvp in dict) if (kvp.Value == 3) setOfThree = true; if (allSameAge) currentTurnScore += 3000; else if (setOfThree) currentTurnScore += 800; else currentTurnScore += 50 * scoredSets[5].Length; } else if (scoredSets[5].Length == 5) { bool allSameAge = true; for (int i = 1; i < scoredSets[5].Length; i++) if (Dice[scoredSets[5][0]].getRollNum() != Dice[scoredSets[5][i]].getRollNum()) allSameAge = false; int[] ages = new int[5]; for (int i = 0; i < scoredSets[5].Length; i++) ages[i] = Dice[scoredSets[5][i]].getRollNum(); var dict = new Dictionary<int, int>(); foreach (int d in ages) if (dict.ContainsKey(d)) dict[d]++; else dict.Add(d, 1); bool setOfThree = false; foreach (KeyValuePair<int, int> kvp in dict) if (kvp.Value == 3) setOfThree = true; bool setofFour = false; foreach (KeyValuePair<int, int> kvp in dict) if (kvp.Value == 4) setofFour = true; if (allSameAge) currentTurnScore += 10000; else if (setofFour) currentTurnScore += 3050; else if (setOfThree) currentTurnScore += 850; else currentTurnScore += 50 * scoredSets[5].Length; } else if (scoredSets[5].Length < 3) currentTurnScore += 50 * scoredSets[5].Length; //Scoring the die value 1 if (scoredSets[1].Length == 3) { bool allSameAge = true; for (int i = 1; i < scoredSets[1].Length; i++) if (Dice[scoredSets[1][0]].getRollNum() != Dice[scoredSets[1][i]].getRollNum()) allSameAge = false; if (allSameAge) currentTurnScore += 1000; else currentTurnScore += 100 * scoredSets[1].Length; } else if (scoredSets[1].Length == 4) { bool allSameAge = true; for (int i = 1; i < scoredSets[1].Length; i++) if (Dice[scoredSets[1][0]].getRollNum() != Dice[scoredSets[1][i]].getRollNum()) allSameAge = false; int[] ages = new int[4]; for (int i = 0; i < scoredSets[1].Length; i++) ages[i] = Dice[scoredSets[1][i]].getRollNum(); var dict = new Dictionary<int, int>(); foreach (int d in ages) if (dict.ContainsKey(d)) dict[d]++; else dict.Add(d, 1); bool setOfThree = false; foreach (KeyValuePair<int, int> kvp in dict) if (kvp.Value == 3) setOfThree = true; if (allSameAge) currentTurnScore += 3000; else if(setOfThree) currentTurnScore += 1100; else currentTurnScore += 100 * scoredSets[1].Length; } else if (scoredSets[1].Length == 5) { bool allSameAge = true; for (int i = 1; i < scoredSets[1].Length; i++) if (Dice[scoredSets[1][0]].getRollNum() != Dice[scoredSets[1][i]].getRollNum()) allSameAge = false; int[] ages = new int[5]; for (int i = 0; i < scoredSets[1].Length; i++) ages[i] = Dice[scoredSets[1][i]].getRollNum(); var dict = new Dictionary<int, int>(); foreach (int d in ages) if (dict.ContainsKey(d)) dict[d]++; else dict.Add(d, 1); bool setOfThree = false; foreach (KeyValuePair<int, int> kvp in dict) if (kvp.Value == 3) setOfThree = true; bool setofFour = false; foreach (KeyValuePair<int, int> kvp in dict) if (kvp.Value == 4) setofFour = true; if (allSameAge) currentTurnScore += 10000; else if (setofFour) currentTurnScore += 3100; else if (setOfThree) currentTurnScore += 1200; else currentTurnScore += 100 * scoredSets[1].Length; } else if (scoredSets[1].Length < 3) currentTurnScore += 100 * scoredSets[1].Length; } public void endTurn() { if (players[currentPlayer].getScore() == 0 && currentTurnScore >= 500) players[currentPlayer].setScore(currentTurnScore); else if (players[currentPlayer].getScore() != 0) players[currentPlayer].addScore(currentTurnScore); currentTurnScore = 0; holdingCurrentTurnScore = 0; foreach (Die dice in Dice) { dice.setRollable(true); dice.setScorable(false); dice.unlockValue(); } if (players[currentPlayer].getScore() > TEN_THOUSAND) endGameActive = true; if (++currentPlayer == players.Length) currentPlayer = 0; if (endGameActive && players[currentPlayer].getScore() > TEN_THOUSAND) gameActiveState = false; rollEm(); } /// <summary> /// Checks if there are any die that are rollable and scorable and updates the avaiable move based on that /// </summary> private void checkForAvailableMoves() { availableMove = false; foreach (Die dice in Dice) if (dice.isRollable() && dice.isScorable()) availableMove = true; } /// <summary> /// Returns whether there were moves avaiable. /// </summary> /// <returns>Wherther there were moves available at the begining of the round</returns> public bool getAvaialableMove() { return availableMove; } /// <summary> /// Returns a Dictionary with Player Names as Keys and Their Score as the value /// </summary> /// <returns>A dictionary with player names as keys and their scores as the values</returns> public Dictionary<string, int> getScores() { Dictionary<string, int> scores = new Dictionary<string, int>(); foreach (Player player in players) scores.Add(player.getName(), player.getScore()); return scores; } public bool readyForNextMove() { if(checkAllScored()) return true; //Make sure atleast one die is scorable bool oneScored = false; for (int i = 0; i < Dice.Length; i++) if (!Dice[i].isRollable()) oneScored = true; if(!oneScored) return false; //Check to see if any of the values have changed bool ready = false; for (int i = 0; i < Dice.Length; i++) if (Dice[i].isRollable() != scoredAtRoundBegining[i]) ready = true; return ready; } private void allDieSelected() { holdingCurrentTurnScore += currentTurnScore; foreach (Die dice in Dice) { dice.setRollable(true); dice.setScorable(false); } } /// <summary> /// Checks if all dice are scored /// </summary> /// <returns>If all die are scored return true, otherwise returns false</returns> private bool checkAllScored() { bool allScored = true; foreach (Die dice in Dice) if (dice.isRollable()) allScored = false; return allScored; } /// <summary> /// Whether the game is active /// </summary> public bool gameActive { get { return gameActiveState; } } } }
38.039761
172
0.469217
[ "MIT" ]
pkshah2017/Ten-Thousand
Ten Thousand/Ten Thousand/Game.cs
19,136
C#
// // DO NOT MODIFY! THIS IS AUTOGENERATED FILE! // namespace Xilium.CefGlue { using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Xilium.CefGlue.Interop; // Role: PROXY public sealed unsafe partial class CefXmlReader : IDisposable { internal static CefXmlReader FromNative(cef_xml_reader_t* ptr) { return new CefXmlReader(ptr); } internal static CefXmlReader FromNativeOrNull(cef_xml_reader_t* ptr) { if (ptr == null) return null; return new CefXmlReader(ptr); } private cef_xml_reader_t* _self; private CefXmlReader(cef_xml_reader_t* ptr) { if (ptr == null) throw new ArgumentNullException("ptr"); _self = ptr; } ~CefXmlReader() { if (_self != null) { Release(); _self = null; } } public void Dispose() { if (_self != null) { Release(); _self = null; } GC.SuppressFinalize(this); } internal void AddRef() { cef_xml_reader_t.add_ref(_self); } internal bool Release() { return cef_xml_reader_t.release(_self) != 0; } internal bool HasOneRef { get { return cef_xml_reader_t.has_one_ref(_self) != 0; } } internal bool HasAtLeastOneRef { get { return cef_xml_reader_t.has_at_least_one_ref(_self) != 0; } } internal cef_xml_reader_t* ToNative() { AddRef(); return _self; } } }
23.725
77
0.491043
[ "MIT" ]
stefan2410/ServiceStack.CefGlue
src/ServiceStack.CefGlue/CefGlue/Classes.g/CefXmlReader.g.cs
1,898
C#
using System; using WindowsAzure.Messaging; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Plugin.AzurePushNotifications; namespace Gcm.Client { [Preserve(AllMembers = true)] public abstract class GcmServiceBase : IntentService { private const string WakelockKey = "GCM_LIB"; private const int MaxBackoffMs = 3600000; //1 hour private const string ExtraToken = "token"; private static PowerManager.WakeLock sWakeLock; private static readonly object Lock = new object(); private static int serviceId = 1; protected static NotificationHub Hub; private readonly Random sRandom = new Random(); private readonly string token = ""; /// <summary> /// The GCM Sender Ids to use. Set by the constructor taking parameters but not by the one that doesn't. Be very /// careful changing this value, preferably only set it in your constructor and only once. /// </summary> protected string[] SenderIds; protected GcmServiceBase() { SenderIds = new[] {PushNotificationCredentials.GoogleApiSenderId}; } public GcmServiceBase(params string[] senderIds) : base("GCMIntentService-" + serviceId++) { SenderIds = senderIds; } protected virtual void OnMessage(Context context, Intent intent) { } protected virtual void OnDeletedMessages(Context context, int total) { } protected virtual bool OnRecoverableError(Context context, string errorId) { return true; } protected virtual void OnError(Context context, string errorId) { } protected virtual void OnRegistered(Context context, string registrationId) { Hub = new NotificationHub(PushNotificationCredentials.AzureNotificationHubName, PushNotificationCredentials.AzureListenConnectionString, context); try { Hub.UnregisterAll(registrationId); } catch(Exception ex) { //Log.Error(PushNotificationsBroadcastReceiver.Tag, ex.Message); } try { var hubRegistration = Hub.Register(registrationId, PushNotificationCredentials.Tags); } catch(Exception ex) { //Log.Error(PushNotificationsBroadcastReceiver.Tag, ex.Message); } } protected virtual void OnUnRegistered(Context context, string registrationId) { Hub?.Unregister(); } protected override void OnHandleIntent(Intent intent) { try { var context = ApplicationContext; var action = intent.Action; if(action.Equals(Constants.IntentFromGcmRegistrationCallback)) { HandleRegistration(context, intent); } else if(action.Equals(Constants.IntentFromGcmMessage)) { // checks for special messages var messageType = intent.GetStringExtra(Constants.ExtraSpecialMessage); if(messageType != null) { if(messageType.Equals(Constants.ValueDeletedMessages)) { var sTotal = intent.GetStringExtra(Constants.ExtraTotalDeleted); if(!string.IsNullOrEmpty(sTotal)) { var nTotal = 0; if(int.TryParse(sTotal, out nTotal)) { //Logger.Debug("Received deleted messages notification: " + nTotal); OnDeletedMessages(context, nTotal); } } } } else { OnMessage(context, intent); } } else if(action.Equals(Constants.IntentFromGcmLibraryRetry)) { var token = intent.GetStringExtra(ExtraToken); if(!string.IsNullOrEmpty(token) && !this.token.Equals(token)) { // make sure intent was generated by this class, not by a // malicious app. //Logger.Debug("Received invalid token: " + token); return; } // retry last call if(GcmClient.IsRegistered(context)) { GcmClient.InternalUnRegister(context); } else { GcmClient.InternalRegister(context, SenderIds); } } } finally { // Release the power lock, so phone can get back to sleep. // The lock is reference-counted by default, so multiple // messages are ok. // If OnMessage() needs to spawn a thread or do something else, // it should use its own lock. lock(Lock) { //Sanity check for null as this is a public method if(sWakeLock != null) { //Logger.Debug("Releasing Wakelock"); sWakeLock.Release(); } } } } internal static void RunIntentInService(Context context, Intent intent, Type classType) { lock(Lock) { if(sWakeLock == null) { // This is called from BroadcastReceiver, there is no init. var pm = PowerManager.FromContext(context); sWakeLock = pm.NewWakeLock(WakeLockFlags.Partial, WakelockKey); } } //Logger.Debug("Acquiring wakelock"); sWakeLock.Acquire(); //intent.SetClassName(context, className); intent.SetClass(context, classType); context.StartService(intent); } private void HandleRegistration(Context context, Intent intent) { var registrationId = intent.GetStringExtra(Constants.ExtraRegistrationId); var error = intent.GetStringExtra(Constants.ExtraError); var unregistered = intent.GetStringExtra(Constants.ExtraUnregistered); //Logger.Debug("handleRegistration: registrationId = " + registrationId + ", error = " + error + ", unregistered = " + unregistered); // registration succeeded if(registrationId != null) { GcmClient.ResetBackoff(context); GcmClient.SetRegistrationId(context, registrationId); OnRegistered(context, registrationId); return; } // unregistration succeeded if(unregistered != null) { // Remember we are unregistered GcmClient.ResetBackoff(context); var oldRegistrationId = GcmClient.ClearRegistrationId(context); OnUnRegistered(context, oldRegistrationId); return; } // last operation (registration or unregistration) returned an error; //Logger.Debug("Registration error: " + error); // Registration failed if(Constants.ErrorServiceNotAvailable.Equals(error)) { var retry = OnRecoverableError(context, error); if(retry) { var backoffTimeMs = GcmClient.GetBackoff(context); var nextAttempt = backoffTimeMs/2 + sRandom.Next(backoffTimeMs); //Logger.Debug("Scheduling registration retry, backoff = " + nextAttempt + " (" + backoffTimeMs + ")"); var retryIntent = new Intent(Constants.IntentFromGcmLibraryRetry); retryIntent.PutExtra(ExtraToken, token); var retryPendingIntent = PendingIntent.GetBroadcast(context, 0, retryIntent, PendingIntentFlags.OneShot); var am = AlarmManager.FromContext(context); am.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + nextAttempt, retryPendingIntent); // Next retry should wait longer. if(backoffTimeMs < MaxBackoffMs) { GcmClient.SetBackoff(context, backoffTimeMs*2); } } } else { // Unrecoverable error, notify app OnError(context, error); } } } }
36.511905
158
0.516466
[ "MIT" ]
KSemenenko/AzurePushNotificationsForXamarinForms
Plugin.AzurePushNotifications/Plugin.AzurePushNotifications.Android/GCM/GcmServiceBase.cs
9,201
C#
using System; using System.Linq; using System.Net.Http.Formatting; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Web.Actions; using Umbraco.Web.Models.Trees; using Umbraco.Web.WebApi.Filters; namespace Umbraco.Web.Trees { [UmbracoTreeAuthorize(Constants.Trees.Dictionary)] [Mvc.PluginController("UmbracoTrees")] [CoreTree(TreeGroup = Constants.Trees.Groups.Settings)] [Tree(Constants.Applications.Translation, Constants.Trees.Dictionary, null)] public class DictionaryTreeController : TreeController { protected override TreeNode CreateRootNode(FormDataCollection queryStrings) { var root = base.CreateRootNode(queryStrings); // the default section is settings, falling back to this if we can't // figure out where we are from the querystring parameters var section = Constants.Applications.Translation; if (queryStrings["application"] != null) section = queryStrings["application"]; // this will load in a custom UI instead of the dashboard for the root node root.RoutePath = $"{section}/{Constants.Trees.Dictionary}/list"; return root; } /// <summary> /// The method called to render the contents of the tree structure /// </summary> /// <param name="id">The id of the tree item</param> /// <param name="queryStrings"> /// All of the query string parameters passed from jsTree /// </param> /// <remarks> /// We are allowing an arbitrary number of query strings to be pased in so that developers are able to persist custom data from the front-end /// to the back end to be used in the query for model data. /// </remarks> protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings) { var intId = id.TryConvertTo<int>(); if (intId == false) throw new InvalidOperationException("Id must be an integer"); var nodes = new TreeNodeCollection(); Func<IDictionaryItem, string> ItemSort() => item => item.ItemKey; if (id == Constants.System.Root.ToInvariantString()) { nodes.AddRange( Services.LocalizationService.GetRootDictionaryItems().OrderBy(ItemSort()).Select( x => CreateTreeNode( x.Id.ToInvariantString(), id, queryStrings, x.ItemKey, "icon-book-alt", Services.LocalizationService.GetDictionaryItemChildren(x.Key).Any()))); } else { // maybe we should use the guid as url param to avoid the extra call for getting dictionary item var parentDictionary = Services.LocalizationService.GetDictionaryItemById(intId.Result); if (parentDictionary == null) return nodes; nodes.AddRange(Services.LocalizationService.GetDictionaryItemChildren(parentDictionary.Key).ToList().OrderBy(ItemSort()).Select( x => CreateTreeNode( x.Id.ToInvariantString(), id, queryStrings, x.ItemKey, "icon-book-alt", Services.LocalizationService.GetDictionaryItemChildren(x.Key).Any()))); } return nodes; } /// <summary> /// Returns the menu structure for the node /// </summary> /// <param name="id">The id of the tree item</param> /// <param name="queryStrings"> /// All of the query string parameters passed from jsTree /// </param> /// <returns></returns> protected override MenuItemCollection GetMenuForNode(string id, FormDataCollection queryStrings) { var menu = new MenuItemCollection(); menu.Items.Add<ActionNew>(Services.TextService, opensDialog: true); if (id != Constants.System.Root.ToInvariantString()) menu.Items.Add<ActionDelete>(Services.TextService, true, opensDialog: true); menu.Items.Add(new RefreshNode(Services.TextService, true)); return menu; } } }
40.342342
149
0.585529
[ "MIT" ]
bharanijayasuri/umbraco8
src/Umbraco.Web/Trees/DictionaryTreeController.cs
4,480
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Codecs.Http.Tests.Multipart { using DotNetty.Codecs.Http.Multipart; using Xunit; public sealed class DiskFileUploadTest { [Fact] public void DiskFileUploadEquals() { var f2 = new DiskFileUpload("d1", "d1", "application/json", null, null, 100); Assert.Equal(f2, f2); } } }
27.421053
101
0.644914
[ "MIT" ]
15000775075/DotNetty
test/DotNetty.Codecs.Http.Tests/Multipart/DiskFileUploadTest.cs
523
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.Build.Tasks; using Xunit; using Xunit.Abstractions; #nullable disable namespace Microsoft.Build.UnitTests { sealed public class ResolveNonMSBuildProjectOutput_Tests { private const string attributeProject = "Project"; private readonly ITestOutputHelper _output; public ResolveNonMSBuildProjectOutput_Tests(ITestOutputHelper output) { _output = output; } static internal ITaskItem CreateReferenceItem(string itemSpec, string projectGuid, string package, string name) { TaskItem reference = new TaskItem(itemSpec); if (projectGuid != null) reference.SetMetadata(attributeProject, projectGuid); if (package != null) reference.SetMetadata("Package", package); if (name != null) reference.SetMetadata("Name", name); return reference; } private void TestVerifyReferenceAttributesHelper(string itemSpec, string projectGuid, string package, string name, bool expectedResult, string expectedMissingAttribute) { ITaskItem reference = CreateReferenceItem(itemSpec, projectGuid, package, name); ResolveNonMSBuildProjectOutput rvpo = new ResolveNonMSBuildProjectOutput(); string missingAttr; bool result = rvpo.VerifyReferenceAttributes(reference, out missingAttr); string message = string.Format("Reference \"{0}\" [project \"{1}\", package \"{2}\", name \"{3}\"], " + "expected result \"{4}\", actual result \"{5}\", expected missing attr \"{6}\", actual missing attr \"{7}\".", itemSpec, projectGuid, package, name, expectedResult, result, expectedMissingAttribute, missingAttr); Assert.Equal(result, expectedResult); if (!result) { Assert.Equal(missingAttr, expectedMissingAttribute); } else { Assert.Null(missingAttr); } } [Fact] public void TestVerifyReferenceAttributes() { // a correct reference TestVerifyReferenceAttributesHelper("proj1.csproj", "{CFF438C3-51D1-4E61-BECD-D7D3A6193DF7}", "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", "CSDep", true, null); // incorrect project guid - should not work TestVerifyReferenceAttributesHelper("proj1.csproj", "{invalid guid}", "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", "CSDep", false, "Project"); } static internal string CreatePregeneratedPathDoc(IDictionary projectOutputs) { string xmlString = "<VSIDEResolvedNonMSBuildProjectOutputs>"; foreach (DictionaryEntry entry in projectOutputs) { xmlString += string.Format("<ProjectRef Project=\"{0}\">{1}</ProjectRef>", entry.Key, entry.Value); } xmlString += "</VSIDEResolvedNonMSBuildProjectOutputs>"; return xmlString; } private void TestResolveHelper(string itemSpec, string projectGuid, string package, string name, Hashtable pregenOutputs, bool expectedResult, string expectedPath) { ITaskItem reference = CreateReferenceItem(itemSpec, projectGuid, package, name); string xmlString = CreatePregeneratedPathDoc(pregenOutputs); ITaskItem resolvedPath; ResolveNonMSBuildProjectOutput rvpo = new ResolveNonMSBuildProjectOutput(); rvpo.CacheProjectElementsFromXml(xmlString); bool result = rvpo.ResolveProject(reference, out resolvedPath); string message = string.Format("Reference \"{0}\" [project \"{1}\", package \"{2}\", name \"{3}\"] Pregen Xml string : \"{4}\"" + "expected result \"{5}\", actual result \"{6}\", expected path \"{7}\", actual path \"{8}\".", itemSpec, projectGuid, package, name, xmlString, expectedResult, result, expectedPath, resolvedPath); Assert.Equal(result, expectedResult); if (result) { Assert.Equal(resolvedPath.ItemSpec, expectedPath); } else { Assert.Null(resolvedPath); } } [Fact] [Trait("Category", "mono-osx-failing")] public void TestResolve() { // empty pre-generated string Hashtable projectOutputs = new Hashtable(); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, false, null); // non matching project in string projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, false, null); // matching project in string projectOutputs = new Hashtable(); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", Path.Combine("obj", "correct.dll")); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, true, Path.Combine("obj", "correct.dll")); // multiple non matching projects in string projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", Path.Combine("obj", "wrong2.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", Path.Combine("obj", "wrong3.dll")); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, false, null); // multiple non matching projects in string, one matching projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", Path.Combine("obj", "wrong2.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", Path.Combine("obj", "wrong3.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", Path.Combine("obj", "correct.dll")); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, true, Path.Combine("obj", "correct.dll")); } private void TestUnresolvedReferencesHelper(ArrayList projectRefs, Hashtable pregenOutputs, out Hashtable unresolvedOutputs, out Hashtable resolvedOutputs) { TestUnresolvedReferencesHelper(projectRefs, pregenOutputs, null, out unresolvedOutputs, out resolvedOutputs); } private void TestUnresolvedReferencesHelper(ArrayList projectRefs, Hashtable pregenOutputs, Func<string, bool> isManaged, out Hashtable unresolvedOutputs, out Hashtable resolvedOutputs) { ResolveNonMSBuildProjectOutput.GetAssemblyNameDelegate pretendGetAssemblyName = path => { if (isManaged != null && isManaged(path)) { return null; // just don't throw an exception } else { throw new BadImageFormatException(); // the hint that the caller takes for an unmanaged binary. } }; string xmlString = CreatePregeneratedPathDoc(pregenOutputs); MockEngine engine = new MockEngine(_output); ResolveNonMSBuildProjectOutput rvpo = new ResolveNonMSBuildProjectOutput(); rvpo.GetAssemblyName = pretendGetAssemblyName; rvpo.BuildEngine = engine; rvpo.PreresolvedProjectOutputs = xmlString; rvpo.ProjectReferences = (ITaskItem[])projectRefs.ToArray(typeof(ITaskItem)); bool result = rvpo.Execute(); unresolvedOutputs = new Hashtable(); for (int i = 0; i < rvpo.UnresolvedProjectReferences.Length; i++) { unresolvedOutputs[rvpo.UnresolvedProjectReferences[i].ItemSpec] = rvpo.UnresolvedProjectReferences[i]; } resolvedOutputs = new Hashtable(); for (int i = 0; i < rvpo.ResolvedOutputPaths.Length; i++) { resolvedOutputs[rvpo.ResolvedOutputPaths[i].ItemSpec] = rvpo.ResolvedOutputPaths[i]; } } [Fact] [Trait("Category", "mono-osx-failing")] public void TestManagedCheck() { Hashtable unresolvedOutputs = null; Hashtable resolvedOutputs = null; Hashtable projectOutputs = null; ArrayList projectRefs = new ArrayList(); projectRefs.Add(CreateReferenceItem("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-000000000000}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1")); projectRefs.Add(CreateReferenceItem("MCDep2.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep2")); // 1. multiple project refs, none resolvable projectOutputs = new Hashtable(); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-000000000000}", Path.Combine("obj", "managed.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", Path.Combine("obj", "unmanaged.dll")); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, path => (path == Path.Combine("obj", "managed.dll")), out unresolvedOutputs, out resolvedOutputs); Assert.NotNull(resolvedOutputs); Assert.True(resolvedOutputs.Contains(Path.Combine("obj", "managed.dll"))); Assert.True(resolvedOutputs.Contains(Path.Combine("obj", "unmanaged.dll"))); Assert.Equal("true", ((ITaskItem)resolvedOutputs[Path.Combine("obj", "managed.dll")]).GetMetadata("ManagedAssembly")); Assert.NotEqual("true", ((ITaskItem)resolvedOutputs[Path.Combine("obj", "unmanaged.dll")]).GetMetadata("ManagedAssembly")); } /// <summary> /// Verifies that the UnresolvedProjectReferences output parameter is populated correctly. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestUnresolvedReferences() { ArrayList projectRefs = new ArrayList(); projectRefs.Add(CreateReferenceItem("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-000000000000}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1")); projectRefs.Add(CreateReferenceItem("MCDep2.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep2")); // 1. multiple project refs, none resolvable Hashtable projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", Path.Combine("obj", "wrong2.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", Path.Combine("obj", "wrong3.dll")); Hashtable unresolvedOutputs; Hashtable resolvedOutputs; TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Empty(resolvedOutputs); // "No resolved refs expected for case 1" Assert.Equal(2, unresolvedOutputs.Count); // "Two unresolved refs expected for case 1" Assert.Equal(unresolvedOutputs["MCDep1.vcproj"], projectRefs[0]); Assert.Equal(unresolvedOutputs["MCDep2.vcproj"], projectRefs[1]); // 2. multiple project refs, one resolvable projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", Path.Combine("obj", "wrong2.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", Path.Combine("obj", "wrong3.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", Path.Combine("obj", "correct.dll")); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Single(resolvedOutputs); // "One resolved ref expected for case 2" Assert.True(resolvedOutputs.ContainsKey(Path.Combine("obj", "correct.dll"))); Assert.Single(unresolvedOutputs); // "One unresolved ref expected for case 2" Assert.Equal(unresolvedOutputs["MCDep1.vcproj"], projectRefs[0]); // 3. multiple project refs, all resolvable projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", Path.Combine("obj", "wrong2.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", Path.Combine("obj", "wrong3.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", Path.Combine("obj", "correct.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-000000000000}", Path.Combine("obj", "correct2.dll")); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Equal(2, resolvedOutputs.Count); // "Two resolved refs expected for case 3" Assert.True(resolvedOutputs.ContainsKey(Path.Combine("obj", "correct.dll"))); Assert.True(resolvedOutputs.ContainsKey(Path.Combine("obj", "correct2.dll"))); Assert.Empty(unresolvedOutputs); // "No unresolved refs expected for case 3" // 4. multiple project refs, all failed to resolve projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", Path.Combine("obj", "wrong2.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", Path.Combine("obj", "wrong3.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", @""); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-000000000000}", @""); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Empty(resolvedOutputs); // "No resolved refs expected for case 4" Assert.Empty(unresolvedOutputs); // "No unresolved refs expected for case 4" // 5. multiple project refs, one resolvable, one failed to resolve projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", Path.Combine("obj", "wrong2.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", Path.Combine("obj", "wrong3.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", Path.Combine("obj", "correct.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-000000000000}", @""); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Single(resolvedOutputs); // "One resolved ref expected for case 5" Assert.True(resolvedOutputs.ContainsKey(Path.Combine("obj", "correct.dll"))); Assert.Empty(unresolvedOutputs); // "No unresolved refs expected for case 5" // 6. multiple project refs, one unresolvable, one failed to resolve projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", Path.Combine("obj", "wrong.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", Path.Combine("obj", "wrong2.dll")); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", Path.Combine("obj", "wrong3.dll")); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-000000000000}", @""); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Empty(resolvedOutputs); // "No resolved refs expected for case 6" Assert.Single(unresolvedOutputs); // "One unresolved ref expected for case 6" Assert.Equal(unresolvedOutputs["MCDep2.vcproj"], projectRefs[1]); } [Fact] public void TestVerifyProjectReferenceItem() { ResolveNonMSBuildProjectOutput rvpo = new ResolveNonMSBuildProjectOutput(); ITaskItem[] taskItems = new ITaskItem[1]; // bad GUID - this reference is invalid taskItems[0] = new TaskItem("projectReference"); taskItems[0].SetMetadata(attributeProject, "{invalid guid}"); MockEngine engine = new MockEngine(_output); rvpo.BuildEngine = engine; Assert.True(rvpo.VerifyProjectReferenceItems(taskItems, false /* treat problems as warnings */)); Assert.Equal(1, engine.Warnings); Assert.Equal(0, engine.Errors); engine.AssertLogContains("MSB3107"); engine = new MockEngine(_output); rvpo.BuildEngine = engine; Assert.False(rvpo.VerifyProjectReferenceItems(taskItems, true /* treat problems as errors */)); Assert.Equal(0, engine.Warnings); Assert.Equal(1, engine.Errors); engine.AssertLogContains("MSB3107"); } } }
52.694915
170
0.637397
[ "MIT" ]
AlexanderSemenyak/msbuild
src/Tasks.UnitTests/ResolveNonMSBuildProjectOutput_Tests.cs
18,654
C#
namespace Cave.Progress { /// <summary>Provides an interface for progress tracking.</summary> public interface IProgress { #region Properties /// <summary>Gets a value indicating whether the progress is completed or not.</summary> bool Completed { get; } /// <summary>Gets the identifier (creation number) of this progress instance.</summary> int Identifier { get; } /// <summary>Gets the current text.</summary> string Text { get; } /// <summary>Gets the current value (0..1).</summary> float Value { get; } #endregion #region Members /// <summary>Completes the progress.</summary> /// <remarks> /// This can only be called once and sets the <see cref="Value" /> property to 1.0f and <see cref="Completed" /> property to true. /// After the properties are set <see cref="ProgressManager.Updated" /> will be invoked for the falst time with this progress instance. It is /// then removed from the <see cref="ProgressManager.Items" /> enumeration. /// </remarks> void Complete(); /// <summary>Updates the progress to a higher value (0..1) and optionally sets a new text.</summary> /// <param name="value">The new value (higher or equal to the current <see cref="Value" />).</param> /// <param name="message">The progress text.</param> void Update(float value, string message = null); #endregion } }
37.675
149
0.619111
[ "MIT" ]
CaveSystems/cave-io
Cave.IO/Progress/IProgress.cs
1,509
C#
/* * Copyright 2017 pi.pe gmbh . * * 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. * */ // Modified by Andrés Leone Gámez /** * * @author tim */ namespace SIPSorcery.Net.Sctp { public class StateCookie : KnownParam { public StateCookie() : base(7, "StateCookie") { } public StateCookie(int t, string n) : base(t, n) { } } }
27.125
75
0.687788
[ "MIT" ]
GB28181/GB28181.Platform2016
sipsorcery/src/net/SCTP/messages/params/StateCookie.cs
870
C#
 namespace EqualSums { using System; using System.Linq; public class Program { public static void Main(string[] args) { int[] input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); int previousElement = 0; int sum = 0; for (int i = 0; i < input.Length; i++) { int curentElement = input[i]; sum += curentElement; } bool check = false; for (int i = 0; i < input.Length; i++) { int curentElement = input[i]; previousElement += curentElement; if ((sum - previousElement) == previousElement - curentElement) { check = true; Console.WriteLine(i); } } if (check == false) { Console.WriteLine("no"); } } } }
22.355556
84
0.412525
[ "MIT" ]
stoyantodorovbg/Programming-Fundamentals
ArraysExarcise/EqualSums/Program.cs
1,008
C#
// Copyright (c) 2020 Flucto Team and others. Licensed under the MIT Licence. // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Runtime.CompilerServices; using flucto.Graphics.Primitives; using osuTK; namespace flucto.Graphics { public static class Vector2Extensions { /// <summary>Transform a Position by the given Matrix</summary> /// <param name="pos">The position to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed position</returns> public static Vector2 Transform(Vector2 pos, Matrix3 mat) { Transform(ref pos, ref mat, out Vector2 result); return result; } /// <summary>Transform a Position by the given Matrix</summary> /// <param name="pos">The position to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed vector</param> public static void Transform(ref Vector2 pos, ref Matrix3 mat, out Vector2 result) { result.X = mat.Row0.X * pos.X + mat.Row1.X * pos.Y + mat.Row2.X; result.Y = mat.Row0.Y * pos.X + mat.Row1.Y * pos.Y + mat.Row2.Y; } /// <summary> /// Compute the euclidean distance between two vectors. /// </summary> /// <param name="vec1">The first vector</param> /// <param name="vec2">The second vector</param> /// <returns>The distance</returns> public static float Distance(Vector2 vec1, Vector2 vec2) { Distance(ref vec1, ref vec2, out float result); return result; } /// <summary> /// Compute the euclidean distance between two vectors. /// </summary> /// <param name="vec1">The first vector</param> /// <param name="vec2">The second vector</param> /// <param name="result">The distance</param> public static void Distance(ref Vector2 vec1, ref Vector2 vec2, out float result) { result = MathF.Sqrt((vec2.X - vec1.X) * (vec2.X - vec1.X) + (vec2.Y - vec1.Y) * (vec2.Y - vec1.Y)); } /// <summary> /// Compute the squared euclidean distance between two vectors. /// </summary> /// <param name="vec1">The first vector</param> /// <param name="vec2">The second vector</param> /// <returns>The squared distance</returns> public static float DistanceSquared(Vector2 vec1, Vector2 vec2) { DistanceSquared(ref vec1, ref vec2, out float result); return result; } /// <summary> /// Compute the squared euclidean distance between two vectors. /// </summary> /// <param name="vec1">The first vector</param> /// <param name="vec2">The second vector</param> /// <param name="result">The squared distance</param> public static void DistanceSquared(ref Vector2 vec1, ref Vector2 vec2, out float result) { result = (vec2.X - vec1.X) * (vec2.X - vec1.X) + (vec2.Y - vec1.Y) * (vec2.Y - vec1.Y); } /// <summary> /// Retrieves the orientation of a set of vertices using the Shoelace formula (https://en.wikipedia.org/wiki/Shoelace_formula) /// </summary> /// <param name="vertices">The vertices.</param> /// <returns>Twice the area enclosed by the vertices. /// The vertices are clockwise-oriented if the value is positive. /// The vertices are counter-clockwise-oriented if the value is negative.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float GetOrientation(in ReadOnlySpan<Vector2> vertices) { if (vertices.Length == 0) return 0; float rotation = 0; for (int i = 0; i < vertices.Length - 1; ++i) rotation += (vertices[i + 1].X - vertices[i].X) * (vertices[i + 1].Y + vertices[i].Y); rotation += (vertices[0].X - vertices[vertices.Length - 1].X) * (vertices[0].Y + vertices[vertices.Length - 1].Y); return rotation; } /// <summary> /// Determines whether a point is within the right half-plane of a line. /// </summary> /// <param name="line">The line.</param> /// <param name="point">The point.</param> /// <returns>Whether <paramref name="point"/> is in the right half-plane of <paramref name="line"/>. /// If the point is colinear to the line, it is said to be in the right half-plane of the line. /// </returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool InRightHalfPlaneOf(this Vector2 point, in Line line) => (line.EndPoint.X - line.StartPoint.X) * (point.Y - line.StartPoint.Y) - (line.EndPoint.Y - line.StartPoint.Y) * (point.X - line.StartPoint.X) <= 0; } }
44.068966
134
0.595462
[ "MIT" ]
flucto/flucto
flucto/Graphics/Vector2Extensions.cs
5,114
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.Compute.Inputs { /// <summary> /// Describes the public IP Sku /// </summary> public sealed class PublicIPAddressSkuArgs : Pulumi.ResourceArgs { /// <summary> /// Specify public IP sku name /// </summary> [Input("name")] public InputUnion<string, Pulumi.AzureNative.Compute.PublicIPAddressSkuName>? Name { get; set; } /// <summary> /// Specify public IP sku tier /// </summary> [Input("tier")] public InputUnion<string, Pulumi.AzureNative.Compute.PublicIPAddressSkuTier>? Tier { get; set; } public PublicIPAddressSkuArgs() { } } }
28.285714
104
0.638384
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Compute/Inputs/PublicIPAddressSkuArgs.cs
990
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Shooter.Factories { public class PlayerBulletFactory { public IList<Bullet> bullets = new List<Bullet>(); private SoundEffect sound; private double elapsedTime = 0; Texture2D texture, textureSpecial; public PlayerBulletFactory() { texture = null; } public void Update(GameTime gameTime, Player p1) { elapsedTime += gameTime.ElapsedGameTime.TotalSeconds; for (int i = 0; i < bullets.Count(); i++) { bullets[i].Update(gameTime); if (!bullets[i].isVisible) { bullets.RemoveAt(i); i--; } } } public void Shoot(Player p1) { if (elapsedTime > 0.15) { Bullet newBullet = new Bullet(texture); newBullet.position = new Vector2(p1.position.X + 25 - newBullet.texture.Width/2, p1.position.Y - 5); newBullet.isVisible = true; bullets.Add(newBullet); SpeacialBullers(p1); elapsedTime = 0; } } private void SpeacialBullers(Player p1) { if (p1.points >= 300) { SpecialBullet newBullet = new SpecialBullet(2, textureSpecial); newBullet.position = new Vector2(p1.position.X + 25 - newBullet.texture.Width/2, p1.position.Y - 5); newBullet.isVisible = true; bullets.Add(newBullet); newBullet = new SpecialBullet(1, textureSpecial); newBullet.position = new Vector2(p1.position.X + 35 - newBullet.texture.Width/2, p1.position.Y - 5); newBullet.isVisible = true; bullets.Add(newBullet); } if (p1.points >= 900) { SpecialBullet newBullet = new SpecialBullet(0, textureSpecial); newBullet.position = new Vector2(p1.position.X + 35 - newBullet.texture.Width/2, p1.position.Y - 5); newBullet.isVisible = true; bullets.Add(newBullet); newBullet = new SpecialBullet(3, textureSpecial); newBullet.position = new Vector2(p1.position.X + 25 - newBullet.texture.Width/2, p1.position.Y - 5); newBullet.isVisible = true; bullets.Add(newBullet); } } // Draw public void Draw(SpriteBatch spriteBatch) { foreach (Bullet b in bullets) { b.Draw(spriteBatch); } } // Load Content public virtual void LoadContent(ContentManager content) { texture = content.Load<Texture2D>("Player/specialBullet"); textureSpecial = content.Load<Texture2D>("Player/specialBullet"); sound = content.Load<SoundEffect>("Sound/laser"); } } }
28.513043
116
0.537054
[ "MIT" ]
GuiCarneiro/BulletHell
Shooter/Shooter/Factories/PlayerBulletFactory.cs
3,281
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace ExcelNumberFormat { static internal class Formatter { static public string Format(object value, string formatString, CultureInfo culture) { var format = new NumberFormat(formatString); if (!format.IsValid) return CompatibleConvert.ToString(value, culture); var section = Evaluator.GetSection(format.Sections, value); if (section == null) return CompatibleConvert.ToString(value, culture); return Format(value, section, culture); } static public string Format(object value, Section node, CultureInfo culture) { switch (node.Type) { case SectionType.Number: // Hide sign under certain conditions and section index var number = Convert.ToDouble(value, culture); if ((node.SectionIndex == 0 && node.Condition != null) || node.SectionIndex == 1) number = Math.Abs(number); return FormatNumber(number, node.Number, culture); case SectionType.Date: return FormatDate(Convert.ToDateTime(value, culture), node.GeneralTextDateDurationParts, culture); case SectionType.Duration: return FormatTimeSpan((TimeSpan)value, node.GeneralTextDateDurationParts, culture); case SectionType.General: case SectionType.Text: return FormatGeneralText(CompatibleConvert.ToString(value, culture), node.GeneralTextDateDurationParts); case SectionType.Exponential: return FormatExponential(Convert.ToDouble(value, culture), node, culture); case SectionType.Fraction: return FormatFraction(Convert.ToDouble(value, culture), node, culture); default: throw new InvalidOperationException("Unknown number format section"); } } static string FormatGeneralText(string text, List<string> tokens) { var result = new StringBuilder(); for (var i = 0; i < tokens.Count; i++) { var token = tokens[i]; if (Token.IsGeneral(token) || token == "@") { result.Append(text); } else { FormatLiteral(token, result); } } return result.ToString(); } private static string FormatTimeSpan(TimeSpan timeSpan, List<string> tokens, CultureInfo culture) { // NOTE/TODO: assumes there is exactly one [hh], [mm] or [ss] using the integer part of TimeSpan.TotalXXX when formatting. // The timeSpan input is then truncated to the remainder fraction, which is used to format mm and/or ss. var result = new StringBuilder(); var containsMilliseconds = false; for (var i = tokens.Count - 1; i >= 0; i--) { if (tokens[i].StartsWith(".0")) { containsMilliseconds = true; break; } } for (var i = 0; i < tokens.Count; i++) { var token = tokens[i]; if (token.StartsWith("m", StringComparison.OrdinalIgnoreCase)) { var value = timeSpan.Minutes; var digits = token.Length; result.Append(value.ToString("D" + digits)); } else if (token.StartsWith("s", StringComparison.OrdinalIgnoreCase)) { // If format does not include ms, then include ms in seconds and round before printing var formatMs = containsMilliseconds ? 0 : timeSpan.Milliseconds / 1000D; var value = (int)Math.Round(timeSpan.Seconds + formatMs, 0, MidpointRounding.AwayFromZero); var digits = token.Length; result.Append(value.ToString("D" + digits)); } else if (token.StartsWith("[h", StringComparison.OrdinalIgnoreCase)) { var value = (int)timeSpan.TotalHours; var digits = token.Length - 2; result.Append(value.ToString("D" + digits)); timeSpan = new TimeSpan(0, 0, Math.Abs(timeSpan.Minutes), Math.Abs(timeSpan.Seconds), Math.Abs(timeSpan.Milliseconds)); } else if (token.StartsWith("[m", StringComparison.OrdinalIgnoreCase)) { var value = (int)timeSpan.TotalMinutes; var digits = token.Length - 2; result.Append(value.ToString("D" + digits)); timeSpan = new TimeSpan(0, 0, 0, Math.Abs(timeSpan.Seconds), Math.Abs(timeSpan.Milliseconds)); } else if (token.StartsWith("[s", StringComparison.OrdinalIgnoreCase)) { var value = (int)timeSpan.TotalSeconds; var digits = token.Length - 2; result.Append(value.ToString("D" + digits)); timeSpan = new TimeSpan(0, 0, 0, 0, Math.Abs(timeSpan.Milliseconds)); } else if (token.StartsWith(".0")) { var value = timeSpan.Milliseconds; var digits = token.Length - 1; result.Append("." + value.ToString("D" + digits)); } else { FormatLiteral(token, result); } } return result.ToString(); } private static string FormatDate(DateTime date, List<string> tokens, CultureInfo culture) { var containsAmPm = ContainsAmPm(tokens); var result = new StringBuilder(); for (var i = 0; i < tokens.Count; i++) { var token = tokens[i]; if (token.StartsWith("y", StringComparison.OrdinalIgnoreCase)) { // year var digits = token.Length; if (digits < 2) digits = 2; if (digits == 3) digits = 4; var year = date.Year; if (digits == 2) year = year % 100; result.Append(year.ToString("D" + digits)); } else if (token.StartsWith("m", StringComparison.OrdinalIgnoreCase)) { // If "m" or "mm" code is used immediately after the "h" or "hh" code (for hours) or immediately before // the "ss" code (for seconds), the application shall display minutes instead of the month. if (LookBackDatePart(tokens, i - 1, "h") || LookAheadDatePart(tokens, i + 1, "s")) { var digits = token.Length; result.Append(date.Minute.ToString("D" + digits)); } else { var digits = token.Length; if (digits == 3) { result.Append(culture.DateTimeFormat.AbbreviatedMonthNames[date.Month - 1]); } else if (digits == 4) { result.Append(culture.DateTimeFormat.MonthNames[date.Month - 1]); } else if (digits == 5) { result.Append(culture.DateTimeFormat.MonthNames[date.Month - 1][0]); } else { result.Append(date.Month.ToString("D" + digits)); } } } else if (token.StartsWith("d", StringComparison.OrdinalIgnoreCase)) { var digits = token.Length; if (digits == 3) { // Sun-Sat result.Append(culture.DateTimeFormat.AbbreviatedDayNames[(int)date.DayOfWeek]); } else if (digits == 4) { // Sunday-Saturday result.Append(culture.DateTimeFormat.DayNames[(int)date.DayOfWeek]); } else { result.Append(date.Day.ToString("D" + digits)); } } else if (token.StartsWith("h", StringComparison.OrdinalIgnoreCase)) { var digits = token.Length; if (containsAmPm) result.Append(((date.Hour + 11) % 12 + 1).ToString("D" + digits)); else result.Append(date.Hour.ToString("D" + digits)); } else if (token.StartsWith("s", StringComparison.OrdinalIgnoreCase)) { var digits = token.Length; result.Append(date.Second.ToString("D" + digits)); } else if (token.StartsWith("g", StringComparison.OrdinalIgnoreCase)) { var era = culture.DateTimeFormat.Calendar.GetEra(date); var digits = token.Length; if (digits < 3) { result.Append(culture.DateTimeFormat.GetAbbreviatedEraName(era)); } else { result.Append(culture.DateTimeFormat.GetEraName(era)); } } else if (string.Compare(token, "am/pm", StringComparison.OrdinalIgnoreCase) == 0) { var ampm = date.ToString("tt", CultureInfo.InvariantCulture); result.Append(ampm.ToUpperInvariant()); } else if (string.Compare(token, "a/p", StringComparison.OrdinalIgnoreCase) == 0) { var ampm = date.ToString("%t", CultureInfo.InvariantCulture); if (char.IsUpper(token[0])) { result.Append(ampm.ToUpperInvariant()); } else { result.Append(ampm.ToLowerInvariant()); } } else if (token.StartsWith(".0")) { var value = date.Millisecond; var digits = token.Length - 1; result.Append("." + value.ToString("D" + digits)); } else if (token == "/") { #if NETSTANDARD1_0 result.Append(DateTime.MaxValue.ToString("/d", culture)[0]); #else result.Append(culture.DateTimeFormat.DateSeparator); #endif } else if (token == ",") { while (i < tokens.Count - 1 && tokens[i + 1] == ",") { i++; } result.Append(","); } else { FormatLiteral(token, result); } } return result.ToString(); } private static bool LookAheadDatePart(List<string> tokens, int fromIndex, string startsWith) { for (var i = fromIndex; i < tokens.Count; i++) { var token = tokens[i]; if (token.StartsWith(startsWith, StringComparison.OrdinalIgnoreCase)) return true; if (Token.IsDatePart(token)) return false; } return false; } private static bool LookBackDatePart(List<string> tokens, int fromIndex, string startsWith) { for (var i = fromIndex; i >= 0; i--) { var token = tokens[i]; if (token.StartsWith(startsWith, StringComparison.OrdinalIgnoreCase)) return true; if (Token.IsDatePart(token)) return false; } return false; } private static bool ContainsAmPm(List<string> tokens) { foreach (var token in tokens) { if (string.Compare(token, "am/pm", StringComparison.OrdinalIgnoreCase) == 0) { return true; } if (string.Compare(token, "a/p", StringComparison.OrdinalIgnoreCase) == 0) { return true; } } return false; } static string FormatNumber(double value, DecimalSection format, CultureInfo culture) { bool thousandSeparator = format.ThousandSeparator; value = value / format.ThousandDivisor; value = value * format.PercentMultiplier; var result = new StringBuilder(); FormatNumber(value, format.BeforeDecimal, format.DecimalSeparator, format.AfterDecimal, thousandSeparator, culture, result); return result.ToString(); } static void FormatNumber(double value, List<string> beforeDecimal, bool decimalSeparator, List<string> afterDecimal, bool thousandSeparator, CultureInfo culture, StringBuilder result) { int signitificantDigits = 0; if (afterDecimal != null) signitificantDigits = GetDigitCount(afterDecimal); var valueString = Math.Abs(value).ToString("F" + signitificantDigits, CultureInfo.InvariantCulture); var valueStrings = valueString.Split('.'); var thousandsString = valueStrings[0]; var decimalString = valueStrings.Length > 1 ? valueStrings[1].TrimEnd('0') : ""; if (value < 0) { result.Append("-"); } if (beforeDecimal != null) { FormatThousands(thousandsString, thousandSeparator, false, beforeDecimal, culture, result); } if (decimalSeparator) { result.Append(culture.NumberFormat.NumberDecimalSeparator); } if (afterDecimal != null) { FormatDecimals(decimalString, afterDecimal, result); } } /// <summary> /// Prints right-aligned, left-padded integer before the decimal separator. With optional most-significant zero. /// </summary> public static void FormatThousands(string valueString, bool thousandSeparator, bool significantZero, List<string> tokens, CultureInfo culture, StringBuilder result) { var significant = false; var formatDigits = GetDigitCount(tokens); valueString = valueString.PadLeft(formatDigits, '0'); // Print literals occurring before any placeholders var tokenIndex = 0; for (; tokenIndex < tokens.Count; tokenIndex++) { var token = tokens[tokenIndex]; if (Token.IsPlaceholder(token)) break; else FormatLiteral(token, result); } // Print value digits until there are as many digits remaining as there are placeholders var digitIndex = 0; for (; digitIndex < (valueString.Length - formatDigits); digitIndex++) { significant = true; result.Append(valueString[digitIndex]); if (thousandSeparator) FormatThousandSeparator(valueString, digitIndex, culture, result); } // Print remaining value digits and format literals for (; tokenIndex < tokens.Count; ++tokenIndex) { var token = tokens[tokenIndex]; if (Token.IsPlaceholder(token)) { var c = valueString[digitIndex]; if (c != '0' || (significantZero && digitIndex == valueString.Length - 1)) significant = true; FormatPlaceholder(token, c, significant, result); if (thousandSeparator && (significant || token.Equals("0"))) FormatThousandSeparator(valueString, digitIndex, culture, result); digitIndex++; } else { FormatLiteral(token, result); } } } static void FormatThousandSeparator(string valueString, int digit, CultureInfo culture, StringBuilder result) { var positionInTens = valueString.Length - 1 - digit; if (positionInTens > 0 && (positionInTens % 3) == 0) { result.Append(culture.NumberFormat.NumberGroupSeparator); } } /// <summary> /// Prints left-aligned, right-padded integer after the decimal separator. Does not print significant zero. /// </summary> public static void FormatDecimals(string valueString, List<string> tokens, StringBuilder result) { var significant = true; var unpaddedDigits = valueString.Length; var formatDigits = GetDigitCount(tokens); valueString = valueString.PadRight(formatDigits, '0'); // Print all format digits var valueIndex = 0; for (var tokenIndex = 0; tokenIndex < tokens.Count; ++tokenIndex) { var token = tokens[tokenIndex]; if (Token.IsPlaceholder(token)) { var c = valueString[valueIndex]; significant = valueIndex < unpaddedDigits; FormatPlaceholder(token, c, significant, result); valueIndex++; } else { FormatLiteral(token, result); } } } static string FormatExponential(double value, Section format, CultureInfo culture) { // The application shall display a number to the right of // the "E" symbol that corresponds to the number of places that // the decimal point was moved. var baseDigits = 0; if (format.Exponential.BeforeDecimal != null) { baseDigits = GetDigitCount(format.Exponential.BeforeDecimal); } var exponent = (int)Math.Floor(Math.Log10(Math.Abs(value))); var mantissa = value / Math.Pow(10, exponent); var shift = Math.Abs(exponent) % baseDigits; if (shift > 0) { if (exponent < 0) shift = (baseDigits - shift); mantissa *= Math.Pow(10, shift); exponent -= shift; } var result = new StringBuilder(); FormatNumber(mantissa, format.Exponential.BeforeDecimal, format.Exponential.DecimalSeparator, format.Exponential.AfterDecimal, false, culture, result); result.Append(format.Exponential.ExponentialToken[0]); if (format.Exponential.ExponentialToken[1] == '+' && exponent >= 0) { result.Append("+"); } else if (exponent < 0) { result.Append("-"); } FormatThousands(Math.Abs(exponent).ToString(CultureInfo.InvariantCulture), false, false, format.Exponential.Power, culture, result); return result.ToString(); } static string FormatFraction(double value, Section format, CultureInfo culture) { int integral = 0; int numerator, denominator; bool sign = value < 0; if (format.Fraction.IntegerPart != null) { integral = (int)Math.Truncate(value); value = Math.Abs(value - integral); } if (format.Fraction.DenominatorConstant != 0) { denominator = format.Fraction.DenominatorConstant; var rr = Math.Round(value * denominator); var b = Math.Floor(rr / denominator); numerator = (int)(rr - b * denominator); } else { var denominatorDigits = Math.Min(GetDigitCount(format.Fraction.Denominator), 7); GetFraction(value, (int)Math.Pow(10, denominatorDigits) - 1, out numerator, out denominator); } // Don't hide fraction if at least one zero in the numerator format var numeratorZeros = GetZeroCount(format.Fraction.Numerator); var hideFraction = (format.Fraction.IntegerPart != null && numerator == 0 && numeratorZeros == 0); var result = new StringBuilder(); if (sign) result.Append("-"); // Print integer part with significant zero if fraction part is hidden if (format.Fraction.IntegerPart != null) FormatThousands(Math.Abs(integral).ToString("F0", CultureInfo.InvariantCulture), false, hideFraction, format.Fraction.IntegerPart, culture, result); var numeratorString = Math.Abs(numerator).ToString("F0", CultureInfo.InvariantCulture); var denominatorString = denominator.ToString("F0", CultureInfo.InvariantCulture); var fraction = new StringBuilder(); FormatThousands(numeratorString, false, true, format.Fraction.Numerator, culture, fraction); fraction.Append("/"); if (format.Fraction.DenominatorPrefix != null) FormatThousands("", false, false, format.Fraction.DenominatorPrefix, culture, fraction); if (format.Fraction.DenominatorConstant != 0) fraction.Append(format.Fraction.DenominatorConstant.ToString()); else FormatDenominator(denominatorString, format.Fraction.Denominator, fraction); if (format.Fraction.DenominatorSuffix != null) FormatThousands("", false, false, format.Fraction.DenominatorSuffix, culture, fraction); if (hideFraction) result.Append(new string(' ', fraction.ToString().Length)); else result.Append(fraction.ToString()); if (format.Fraction.FractionSuffix != null) FormatThousands("", false, false, format.Fraction.FractionSuffix, culture, result); return result.ToString(); } // Adapted from ssf.js 'frac()' helper static void GetFraction(double x, int D, out int nom, out int den) { var sgn = x < 0 ? -1 : 1; var B = x * sgn; var P_2 = 0.0; var P_1 = 1.0; var P = 0.0; var Q_2 = 1.0; var Q_1 = 0.0; var Q = 0.0; var A = Math.Floor(B); while (Q_1 < D) { A = Math.Floor(B); P = A * P_1 + P_2; Q = A * Q_1 + Q_2; if ((B - A) < 0.00000005) break; B = 1 / (B - A); P_2 = P_1; P_1 = P; Q_2 = Q_1; Q_1 = Q; } if (Q > D) { if (Q_1 > D) { Q = Q_2; P = P_2; } else { Q = Q_1; P = P_1; } } nom = (int)(sgn * P); den = (int)Q; } /// <summary> /// Prints left-aligned, left-padded fraction integer denominator. /// Assumes tokens contain only placeholders, valueString has fewer or equal number of digits as tokens. /// </summary> public static void FormatDenominator(string valueString, List<string> tokens, StringBuilder result) { var formatDigits = GetDigitCount(tokens); valueString = valueString.PadLeft(formatDigits, '0'); bool significant = false; var valueIndex = 0; for (var tokenIndex = 0; tokenIndex < tokens.Count; ++tokenIndex) { var token = tokens[tokenIndex]; char c; if (valueIndex < valueString.Length) { c = GetLeftAlignedValueDigit(token, valueString, valueIndex, significant, out valueIndex); if (c != '0') significant = true; } else { c = '0'; significant = false; } FormatPlaceholder(token, c, significant, result); } } /// <summary> /// Returns the first digit from valueString. If the token is '?' /// returns the first significant digit from valueString, or '0' if there are no significant digits. /// The out valueIndex parameter contains the offset to the next digit in valueString. /// </summary> static char GetLeftAlignedValueDigit(string token, string valueString, int startIndex, bool significant, out int valueIndex) { char c; valueIndex = startIndex; if (valueIndex < valueString.Length) { c = valueString[valueIndex]; valueIndex++; if (c != '0') significant = true; if (token == "?" && !significant) { // Eat insignificant zeros to left align denominator while (valueIndex < valueString.Length) { c = valueString[valueIndex]; valueIndex++; if (c != '0') { significant = true; break; } } } } else { c = '0'; significant = false; } return c; } static void FormatPlaceholder(string token, char c, bool significant, StringBuilder result) { if (token == "0") { if (significant) result.Append(c); else result.Append("0"); } else if (token == "#") { if (significant) result.Append(c); } else if (token == "?") { if (significant) result.Append(c); else result.Append(" "); } } static int GetDigitCount(List<string> tokens) { var counter = 0; foreach (var token in tokens) { if (Token.IsPlaceholder(token)) { counter++; } } return counter; } static int GetZeroCount(List<string> tokens) { var counter = 0; foreach (var token in tokens) { if (token == "0") { counter++; } } return counter; } static void FormatLiteral(string token, StringBuilder result) { string literal = string.Empty; if (token == ",") { ; // skip commas } else if (token.Length == 2 && (token[0] == '*' || token[0] == '\\')) { // TODO: * = repeat to fill cell literal = token[1].ToString(); } else if (token.Length == 2 && token[0] == '_') { literal = " "; } else if (token.StartsWith("\"")) { literal = token.Substring(1, token.Length - 2); } else { literal = token; } result.Append(literal); } } }
38.13834
191
0.484403
[ "MIT" ]
asdobson/ExcelNumberFormat
src/ExcelNumberFormat/Formatter.cs
28,949
C#
using System; using System.Threading.Tasks; using Bit.Owin.Contracts; using Microsoft.Owin; namespace Bit.Owin.Implementations { public class DefaultOwinActionFilterMiddleware : OwinMiddleware, IOwinActionFilter { public DefaultOwinActionFilterMiddleware() : base(null) { } public DefaultOwinActionFilterMiddleware(OwinMiddleware next) : base(next) { } public override async Task Invoke(IOwinContext context) { try { await OnActionExecutingAsync(context); if (Next != null) await Next.Invoke(context); } catch (Exception ex) { await OnExceptionAsync(context, ex); throw; } finally { await OnActionExecutedAsync(context); } } public virtual Task OnActionExecutedAsync(IOwinContext owinContext) { return Task.CompletedTask; } public virtual Task OnActionExecutingAsync(IOwinContext owinContext) { return Task.CompletedTask; } public virtual Task OnExceptionAsync(IOwinContext owinContext, Exception ex) { return Task.CompletedTask; } } }
24.017544
86
0.55515
[ "MIT" ]
Jaguel/bit-framework
src/Server/Bit.Owin/Implementations/DefaultOwinActionFilterMiddleware.cs
1,371
C#
using System; using Acr.UserDialogs; using Android.App; using Android.Content.PM; using Android.OS; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; namespace Samples.Droid { [Activity( Label = "User Dialogs", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation )] public class MainActivity : FormsAppCompatActivity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Forms.Init(this, bundle); FormsAppCompatActivity.TabLayoutResource = Resource.Layout.tabs; UserDialogs.Init(this); this.LoadApplication(new App()); } } }
22.588235
83
0.647135
[ "MIT" ]
emclient/userdialogs
src/Samples/Samples.Droid/MainActivity.cs
770
C#