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
sequence
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. namespace EFDesigner.FunctionalTests { using System; using EFDesignerTestInfrastructure; using EFDesignerTestInfrastructure.EFDesigner; using Microsoft.Data.Entity.Design.Extensibility; using Microsoft.Data.Entity.Design.Model; using Microsoft.Data.Entity.Design.Model.Commands; using Microsoft.Data.Entity.Design.VisualStudio; using Microsoft.Data.Entity.Design.VisualStudio.ModelWizard; using Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine; using Moq; using Xunit; using global::FunctionalTests.TestHelpers; public class UpdateModelFromDatabaseTests : IUseFixture<EdmPackageFixture> { /// <summary> /// Fixture that creates a mock package and sets PackageManager.Package /// </summary> /// <param name="packageFixture">Pacakge fixture</param> /// <remarks> /// The tests need PackageManager.Package to be set but don't need the /// package itself. Since it needs to be diposed IUseFixture seems fine. /// We don't need to set it - xUnit is keeping a reference to it and it /// will dispose it after test execution is completed. /// </remarks> public void SetFixture(EdmPackageFixture packageFixture) { } [Fact] public void SSpace_facets_not_propagated_to_CSpace_when_creating_new_model_form_non_SqlServer_database() { using (var artifactHelper = new MockEFArtifactHelper()) { // set up original artifact var uri = TestUtils.FileName2Uri(@"TestArtifacts\PropagateSSidePropertyFacetsToCSideOracle.edmx"); var artifact = (EntityDesignArtifact)artifactHelper.GetNewOrExistingArtifact(uri); var settings = SetupBaseModelBuilderSettings(artifact); var cp = ModelObjectItemWizard.PrepareCommandsAndIntegrityChecks(settings, artifact.GetEditingContext(), artifact); Assert.NotNull(cp); // One command for stored procedure expected Assert.Equal(1, cp.CommandCount); // No integrity checks expected - facet propagation should be disabled for non SqlServer databases Assert.Equal(0, cp.CommandProcessorContext.IntegrityChecks.Count); } } [Fact] public void SSpace_facets_propagated_to_CSpace_when_creating_new_model_form_SqlServer_database() { using (var artifactHelper = new MockEFArtifactHelper()) { // set up original artifact var uri = TestUtils.FileName2Uri(@"TestArtifacts\EmptyEdmx.edmx"); var artifact = (EntityDesignArtifact)artifactHelper.GetNewOrExistingArtifact(uri); var settings = SetupBaseModelBuilderSettings(artifact); CommandProcessor cp = null; try { cp = ModelObjectItemWizard.PrepareCommandsAndIntegrityChecks(settings, artifact.GetEditingContext(), artifact); Assert.NotNull(cp); // Facet propagation should be enabled SqlServer databases Assert.Equal(1, cp.CommandProcessorContext.IntegrityChecks.Count); } finally { if (cp != null) { cp.CommandProcessorContext.ClearIntegrityChecks(); } } } } private static ModelBuilderSettings SetupBaseModelBuilderSettings(EFArtifact artifact) { var settings = new ModelBuilderSettings { Artifact = artifact, GenerationOption = ModelGenerationOption.GenerateFromDatabase, SaveConnectionStringInAppConfig = false, VSApplicationType = VisualStudioProjectSystem.WindowsApplication, WizardKind = WizardKind.UpdateModel }; var hostContext = new Mock<ModelBuilderEngineHostContext>(); hostContext.Setup(hc => hc.LogMessage(It.IsAny<string>())).Callback(Console.WriteLine); hostContext.Setup(hc => hc.DispatchToModelGenerationExtensions()).Callback(() => { }); var modelBuilderEngine = new Mock<UpdateModelFromDatabaseModelBuilderEngine>(); settings.ModelBuilderEngine = modelBuilderEngine.Object; return settings; } } }
44.320755
145
0.631332
[ "MIT" ]
dotnet/ef6tools
test/EFTools/FunctionalTests/UpdateModelFromDatabaseTests.cs
4,700
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Iot.Device.Media { /// <summary> /// The connection settings of a sound device. /// </summary> public class SoundConnectionSettings { /// <summary> /// The playback device name of the sound device is connected to. /// </summary> public string PlaybackDeviceName { get; set; } = "default"; /// <summary> /// The recording device name of the sound device is connected to. /// </summary> public string RecordingDeviceName { get; set; } = "default"; /// <summary> /// The mixer device name of the sound device is connected to. /// </summary> public string MixerDeviceName { get; set; } = "default"; /// <summary> /// The sample rate of recording. /// </summary> public uint RecordingSampleRate { get; set; } = 8000; /// <summary> /// The channels of recording. /// </summary> public ushort RecordingChannels { get; set; } = 2; /// <summary> /// The bits per sample of recording. /// </summary> public ushort RecordingBitsPerSample { get; set; } = 16; } }
31.428571
74
0.575758
[ "MIT" ]
Manny27nyc/nanoFramework.IoT.Device
src/devices_generated/Media/SoundDevice/SoundConnectionSettings.cs
1,320
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Pro_Swapper.API; using System.Threading.Tasks; using CUE4Parse.FileProvider; namespace Pro_Swapper { public static class Swap { private static string PaksLocation = global.CurrentConfig.Paks; public static async Task SwapItem(api.Item item, bool Converting) { //global.CreateDir(PaksLocation + "\\Pro_Swapper"); //Load the exporter List<string> thesefiles = new List<string>(); foreach (var Asset in item.Asset) thesefiles.Add(Path.GetFileNameWithoutExtension(Asset.UcasFile)); List<string> UsingFiles = thesefiles.Distinct().ToList(); /* foreach (string file in UsingFiles) { string BaseFileName = $"{PaksLocation}\\Pro_Swapper\\{file}"; if (!File.Exists(BaseFileName + ".ucas")) { File.Copy($"{PaksLocation}\\{file}.sig", BaseFileName + ".sig", true); File.Copy($"{PaksLocation}\\{file}.utoc", BaseFileName + ".utoc", true); File.Copy($"{PaksLocation}\\{file}.pak", BaseFileName + ".pak", true); File.Copy($"{PaksLocation}\\{file}.ucas", BaseFileName + ".ucas", true); } }*/ // var Provider = new DefaultFileProvider($"{PaksLocation}\\Pro_Swapper", SearchOption.TopDirectoryOnly); var Provider = new DefaultFileProvider(PaksLocation, SearchOption.TopDirectoryOnly); Provider.Initialize(UsingFiles); if (api.fAesKey == null) api.fAesKey = api.AESKey; //Load all aes keys for required files, cleaner in linq than doing a loop Provider.UnloadedVfs.All(x => { Provider.SubmitKey(x.EncryptionKeyGuid, api.fAesKey);return true;}); List<FinalPastes> finalPastes = new List<FinalPastes>(); foreach (api.Asset asset in item.Asset) { // string ucasfile = $"{PaksLocation}\\Pro_Swapper\\{asset.UcasFile}"; string ucasfile = $"{PaksLocation}\\{asset.UcasFile}"; //Checking if file is readonly coz we wouldn't be able to do shit with it File.SetAttributes(ucasfile, global.RemoveAttribute(File.GetAttributes(ucasfile), FileAttributes.ReadOnly)); byte[] exportasset = Fortnite.FortniteExport.ExportAsset(Provider, asset.UcasFile, asset.AssetPath); #if DEBUG Directory.CreateDirectory("Exports"); string smallname = Path.GetFileName(asset.AssetPath); File.WriteAllBytes($"Exports\\Exported_{smallname}.pak", exportasset);//Just simple export // File.WriteAllBytes($"Exports\\RawExport_{smallname}.pak", RawExported);//Uncompress exported by CUE4Parse #endif //edit files and compress with oodle and replace byte[] edited = EditAsset(exportasset, asset, Converting, out bool Compress);//Compressed edited path if (!Compress)//File hasnt gotten any changes, no need to edit files that havent changed continue; byte[] towrite = Oodle.OodleClass.Compress(edited); #if DEBUG //Logging stuff for devs hehe File.WriteAllBytes($"Exports\\Edited_{smallname}.pak", edited);//Edited export File.WriteAllBytes($"Exports\\Compressed{smallname}.pak", towrite);//Compressed edited export #endif finalPastes.Add(new FinalPastes(ucasfile, towrite, Fortnite.FortniteExport.Offset)); } Provider.Dispose(); List<Task> tasklist = new List<Task>(); //Actually put into game files: foreach (FinalPastes pastes in finalPastes) tasklist.Add(Task.Run(() => PasteInLocationBytes(pastes))); await Task.WhenAll(tasklist); } public class FinalPastes { public string ucasfile { get; set; } public byte[] towrite { get; set; } public long Offset { get; set; } public FinalPastes(string Ucasfile, byte[] ToWrite, long offset) { ucasfile = Ucasfile; towrite = ToWrite; Offset = offset; } } //Edits a byte array in memory public static byte[] EditAsset(byte[] file, api.Asset asset, bool Converting, out bool Compress) { Compress = false; using (MemoryStream stream = new MemoryStream(file)) { int NumberOfReplaces = asset.Search.Length; for (int i = 0; i < NumberOfReplaces; i++) { byte[] searchB = ParseByteArray(asset.Search[i]); byte[] replaceB = ParseByteArray(asset.Replace[i]); byte[] RealReplace; int ReplaceIndex = 0, SearchIndex = 0; if (Converting) { //Search is in the byte array RealReplace = SameLength(searchB, replaceB); SearchIndex = IndexOfSequence(file, searchB); if (SearchIndex == -1)//replace cannot be found so that means it is already swapped so skip it. continue; } else { RealReplace = SameLength(replaceB, searchB); ReplaceIndex = IndexOfSequence(file, replaceB); if (ReplaceIndex == -1)//search cannot be found so that means it is already swapped so skip it. continue; } Compress = true;//Change has been made so compress it stream.Position = Math.Max(SearchIndex, ReplaceIndex); stream.Write(RealReplace, 0, RealReplace.Length); } return stream.ToArray(); } } public static byte[] SameLength(byte[] search, byte[] replace) { List<byte> result = new List<byte>(replace); int difference = search.Length - replace.Length; for (int i = 0; i < difference; i++) result.Add(0); return result.ToArray(); } public static byte[] SetLength(byte[] search, byte[] longerbyte) { List<byte> result = new List<byte>(search); int difference = longerbyte.Length - search.Length; for (int i = 0; i < difference; i++) result.Add(0); return result.ToArray(); } //private static byte[] OodleChar = global.HexToByte("8C"); public static void PasteInLocationBytes(FinalPastes finalpaste) { //Define our pak editor stream using (FileStream PakEditor = File.Open(finalpaste.ucasfile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { //Offset for "bothhave" for the general area of our bytes //int offset = (int)Algorithms.BoyerMoore.IndexOf(PakEditor, finalpaste.RawExported); //Offset is where Œ char is PakEditor.Position = finalpaste.Offset; PakEditor.Write(finalpaste.towrite, 0, finalpaste.towrite.Length); } } private static byte[] ParseByteArray(string encodedtxt) { if (encodedtxt.StartsWith("hex=")) return global.HexToByte(encodedtxt); else//eww using text but atleast we can read it return Encoding.Default.GetBytes(encodedtxt); } //Originally: https://stackoverflow.com/a/332667/12897035 private static int IndexOfSequence(byte[] buffer, byte[] pattern) { int i = Array.IndexOf(buffer, pattern[0], 0); while (i >= 0 && i <= buffer.Length - pattern.Length) { byte[] segment = new byte[pattern.Length]; Buffer.BlockCopy(buffer, i, segment, 0, pattern.Length); if (segment.SequenceEqual(pattern)) return i; i = Array.IndexOf(buffer, pattern[0], i + 1); } return -1; } } }
40.933649
131
0.547181
[ "MIT" ]
Tamely/ProSwapper
src/Classes/Swap.cs
8,640
C#
using Flowmaker.ViewModels; using Flowmaker.ViewModels.Mappers; using Flowmaker.ViewModels.Views; using Microsoft.AspNetCore.Mvc; namespace Flowmaker.Web.Components { public class Footer : ViewComponent { //public async Task<IViewComponentResult> InvokeAsync(int maxPriority, bool isDone) public IViewComponentResult Invoke() { return View(ViewData.Model as FlowmakerPageVm); } } }
25.882353
91
0.713636
[ "MIT" ]
mindmakr/flowmaker
src2/Flowmaker.Web/Components/Footer.cs
442
C#
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * Copyright (c) 2020 The Dotnetty-Span-Fork Project ([email protected]) All rights reserved. * * https://github.com/cuteant/dotnetty-span-fork * * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ namespace DotNetty.Codecs.Http2 { using System; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using DotNetty.Buffers; using DotNetty.Common; using DotNetty.Common.Utilities; using DotNetty.Transport.Channels; /// <summary> /// An HTTP/2 handler that creates child channels for each stream. This handler must be used in combination /// with <see cref="Http2FrameCodec"/>. /// /// <para>When a new stream is created, a new <see cref="IChannel"/> is created for it. Applications send and /// receive <see cref="IHttp2StreamFrame"/>s on the created channel. <see cref="IByteBuffer"/>s cannot be processed by the channel; /// all writes that reach the head of the pipeline must be an instance of <see cref="IHttp2StreamFrame"/>. Writes that reach /// the head of the pipeline are processed directly by this handler and cannot be intercepted.</para> /// /// <para>The child channel will be notified of user events that impact the stream, such as <see /// cref="IHttp2GoAwayFrame"/> and <see cref="IHttp2ResetFrame"/>, as soon as they occur. Although <see /// cref="IHttp2GoAwayFrame"/> and <see cref="IHttp2ResetFrame"/> signify that the remote is ignoring further /// communication, closing of the channel is delayed until any inbound queue is drained with <see /// cref="IChannel.Read()"/>, which follows the default behavior of channels in Netty. Applications are /// free to close the channel in response to such events if they don't have use for any queued /// messages. Any connection level events like <see cref="IHttp2SettingsFrame"/> and <see cref="IHttp2GoAwayFrame"/> /// will be processed internally and also propagated down the pipeline for other handlers to act on.</para> /// /// <para>Outbound streams are supported via the <see cref="Http2StreamChannelBootstrap"/>.</para> /// /// <para><see cref="IChannelConfiguration.MaxMessagesPerRead"/> and <see cref="IChannelConfiguration.IsAutoRead"/> are supported.</para> /// /// <h3>Reference Counting</h3> /// /// <para>Some <see cref="IHttp2StreamFrame"/>s implement the <see cref="IReferenceCounted"/> interface, as they carry /// reference counted objects (e.g. <see cref="IByteBuffer"/>s). The multiplex codec will call <see cref="IReferenceCounted.Retain()"/> /// before propagating a reference counted object through the pipeline, and thus an application handler needs to release /// such an object after having consumed it. For more information on reference counting take a look at /// https://netty.io/wiki/reference-counted-objects.html </para> /// /// <h3>Channel Events</h3> /// /// <para>A child channel becomes active as soon as it is registered to an <see cref="IEventLoop"/>. Therefore, an active channel /// does not map to an active HTTP/2 stream immediately. Only once a <see cref="IHttp2HeadersFrame"/> has been successfully sent /// or received, does the channel map to an active HTTP/2 stream. In case it is not possible to open a new HTTP/2 stream /// (i.e. due to the maximum number of active streams being exceeded), the child channel receives an exception /// indicating the cause and is closed immediately thereafter.</para> /// /// <h3>Writability and Flow Control</h3> /// /// <para>A child channel observes outbound/remote flow control via the channel's writability. A channel only becomes writable /// when it maps to an active HTTP/2 stream . A child channel does not know about the connection-level flow control /// window. <see cref="IChannelHandler"/>s are free to ignore the channel's writability, in which case the excessive writes will /// be buffered by the parent channel. It's important to note that only <see cref="IHttp2DataFrame"/>s are subject to /// HTTP/2 flow control.</para> /// </summary> public sealed class Http2MultiplexHandler : Http2ChannelDuplexHandler, IHasParentContext { internal static readonly Action<Task, object> RegisterDoneAction = (t, s) => RegisterDone(t, s); private readonly IChannelHandler _inboundStreamHandler; private readonly IChannelHandler _upgradeStreamHandler; private readonly MaxCapacityQueue<AbstractHttp2StreamChannel> _readCompletePendingQueue; private bool _parentReadInProgress; private int v_idCount; private int NextId => Interlocked.Increment(ref v_idCount); // Need to be volatile as accessed from within the Http2MultiplexHandlerStreamChannel in a multi-threaded fashion. private IChannelHandlerContext v_ctx; private IChannelHandlerContext InternalContext { get => Volatile.Read(ref v_ctx); set => Interlocked.Exchange(ref v_ctx, value); } IChannelHandlerContext IHasParentContext.Context => Volatile.Read(ref v_ctx); /// <summary>Creates a new instance</summary> /// <param name="inboundStreamHandler">the <see cref="IChannelHandler"/> that will be added to the <see cref="IChannelPipeline"/> of /// the <see cref="IChannel"/>s created for new inbound streams.</param> public Http2MultiplexHandler(IChannelHandler inboundStreamHandler) : this(inboundStreamHandler, null) { } /// <summary>Creates a new instance</summary> /// <param name="inboundStreamHandler">the <see cref="IChannelHandler"/> that will be added to the <see cref="IChannelPipeline"/> of /// the <see cref="IChannel"/>s created for new inbound streams.</param> /// <param name="upgradeStreamHandler">the <see cref="IChannelHandler"/> that will be added to the <see cref="IChannelPipeline"/> of the /// upgraded <see cref="IChannel"/>.</param> public Http2MultiplexHandler(IChannelHandler inboundStreamHandler, IChannelHandler upgradeStreamHandler) { if (inboundStreamHandler is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.inboundStreamHandler); } _readCompletePendingQueue = // Choose 100 which is what is used most of the times as default. new MaxCapacityQueue<AbstractHttp2StreamChannel>(Http2CodecUtil.SmallestMaxConcurrentStreams); _inboundStreamHandler = inboundStreamHandler; _upgradeStreamHandler = upgradeStreamHandler; } internal static void RegisterDone(Task future, object s) { // Handle any errors that occurred on the local thread while registering. Even though // failures can happen after this point, they will be handled by the channel by closing the // childChannel. if (!future.IsSuccess()) { var childChannel = (IChannel)s; if (childChannel.IsRegistered) { _ = childChannel.CloseAsync(); } else { childChannel.Unsafe.CloseForcibly(); } } } /// <inheritdoc /> protected override void HandlerAdded0(IChannelHandlerContext ctx) { if (ctx.Executor != ctx.Channel.EventLoop) { ThrowHelper.ThrowInvalidOperationException_EventExecutorMustBeEventLoopOfChannel(); } InternalContext = ctx; } /// <inheritdoc /> protected override void HandlerRemoved0(IChannelHandlerContext ctx) { _readCompletePendingQueue.Clear(); } /// <inheritdoc /> public override void ChannelRead(IChannelHandlerContext context, object msg) { _parentReadInProgress = true; switch (msg) { case IHttp2WindowUpdateFrame _: // We dont want to propagate update frames to the user return; case IHttp2StreamFrame streamFrame: DefaultHttp2FrameStream s = (DefaultHttp2FrameStream)streamFrame.Stream; AbstractHttp2StreamChannel channel = (AbstractHttp2StreamChannel)s.Attachment; if (msg is IHttp2ResetFrame) { // Reset frames needs to be propagated via user events as these are not flow-controlled and so // must not be controlled by suppressing channel.read() on the child channel. _ = channel.Pipeline.FireUserEventTriggered(msg); // RST frames will also trigger closing of the streams which then will call // AbstractHttp2StreamChannel.streamClosed() } else { channel.FireChildRead(streamFrame); } return; case IHttp2GoAwayFrame goAwayFrame: // goaway frames will also trigger closing of the streams which then will call // AbstractHttp2StreamChannel.streamClosed() OnHttp2GoAwayFrame(context, goAwayFrame); break; } // Send everything down the pipeline _ = context.FireChannelRead(msg); } /// <inheritdoc /> public override void ChannelWritabilityChanged(IChannelHandlerContext context) { if (context.Channel.IsWritable) { // While the writability state may change during iterating of the streams we just set all of the streams // to writable to not affect fairness. These will be "limited" by their own watermarks in any case. ForEachActiveStream(AbstractHttp2StreamChannel.WritableVisitor); } _ = context.FireChannelWritabilityChanged(); } /// <inheritdoc /> public override void UserEventTriggered(IChannelHandlerContext context, object evt) { if (!(evt is Http2FrameStreamEvent streamEvent)) { _ = context.FireUserEventTriggered(evt); return; } var stream = (DefaultHttp2FrameStream)streamEvent.Stream; if (streamEvent.Type != Http2FrameStreamEvent.EventType.State) { return; } switch (stream.State) { case Http2StreamState.HalfClosedLocal: if (stream.Id != Http2CodecUtil.HttpUpgradeStreamId) { // Ignore everything which was not caused by an upgrade break; } goto case Http2StreamState.Open; // fall-through case Http2StreamState.HalfClosedRemote: // fall-through case Http2StreamState.Open: if (stream.Attachment is object) { // ignore if child channel was already created. break; } AbstractHttp2StreamChannel ch; // We need to handle upgrades special when on the client side. if (stream.Id == Http2CodecUtil.HttpUpgradeStreamId && !IsServer(context)) { // We must have an upgrade handler or else we can't handle the stream if (_upgradeStreamHandler is null) { ThrowHelper.ThrowConnectionError_ClientIsMisconfiguredForUpgradeRequests(); } ch = new Http2MultiplexHandlerStreamChannel(this, stream, _upgradeStreamHandler) { OutboundClosed = true }; } else { ch = new Http2MultiplexHandlerStreamChannel(this, stream, _inboundStreamHandler); } var future = context.Channel.EventLoop.RegisterAsync(ch); if (future.IsCompleted) { RegisterDone(future, ch); } else { _ = future.ContinueWith(RegisterDoneAction, ch, TaskContinuationOptions.ExecuteSynchronously); } break; case Http2StreamState.Closed: if (stream.Attachment is AbstractHttp2StreamChannel channel) { channel.StreamClosed(); } break; default: // ignore for now break; } } // TODO: This is most likely not the best way to expose this, need to think more about it. internal IHttp2StreamChannel NewOutboundStream() { return new Http2MultiplexHandlerStreamChannel(this, (DefaultHttp2FrameStream)NewStream(), null); } /// <inheritdoc /> public override void ExceptionCaught(IChannelHandlerContext ctx, Exception exception) { if (exception is Http2FrameStreamException streamException) { var stream = streamException.Stream; var childChannel = (AbstractHttp2StreamChannel) ((DefaultHttp2FrameStream)stream).Attachment; try { _ = childChannel.Pipeline.FireExceptionCaught(exception.InnerException); } finally { childChannel.Unsafe.CloseForcibly(); } return; } _ = ctx.FireExceptionCaught(exception); } [MethodImpl(InlineMethod.AggressiveOptimization)] private static bool IsServer(IChannelHandlerContext ctx) { return ctx.Channel.Parent is IServerChannel; } private void OnHttp2GoAwayFrame(IChannelHandlerContext ctx, IHttp2GoAwayFrame goAwayFrame) { try { var server = IsServer(ctx); ForEachActiveStream(stream => InternalStreamVisitor(stream, goAwayFrame, server)); } catch (Http2Exception exc) { _ = ctx.FireExceptionCaught(exc); _ = ctx.CloseAsync(); } } private static bool InternalStreamVisitor(IHttp2FrameStream stream, IHttp2GoAwayFrame goAwayFrame, bool server) { int streamId = stream.Id; if (streamId > goAwayFrame.LastStreamId && Http2CodecUtil.IsStreamIdValid(streamId, server)) { var childChannel = (AbstractHttp2StreamChannel) ((DefaultHttp2FrameStream)stream).Attachment; _ = childChannel.Pipeline.FireUserEventTriggered(goAwayFrame.RetainedDuplicate()); } return true; } /// <summary> /// Notifies any child streams of the read completion. /// </summary> /// <param name="context"></param> public override void ChannelReadComplete(IChannelHandlerContext context) { ProcessPendingReadCompleteQueue(); _ = context.FireChannelReadComplete(); } private void ProcessPendingReadCompleteQueue() { _parentReadInProgress = true; // If we have many child channel we can optimize for the case when multiple call flush() in // channelReadComplete(...) callbacks and only do it once as otherwise we will end-up with multiple // write calls on the socket which is expensive. if (_readCompletePendingQueue.TryDequeue(out var childChannel)) { try { do { childChannel.FireChildReadComplete(); } while (_readCompletePendingQueue.TryDequeue(out childChannel)); } finally { _parentReadInProgress = false; _readCompletePendingQueue.Clear(); _ = InternalContext.Flush(); } } else { _parentReadInProgress = false; } } sealed class Http2MultiplexHandlerStreamChannel : AbstractHttp2StreamChannel { private readonly Http2MultiplexHandler _owner; public Http2MultiplexHandlerStreamChannel(Http2MultiplexHandler owner, DefaultHttp2FrameStream stream, IChannelHandler inboundHandler) : base(stream, owner.NextId, inboundHandler, owner) { _owner = owner; } protected override bool IsParentReadInProgress => _owner._parentReadInProgress; protected override void AddChannelToReadCompletePendingQueue() { var readCompletePendingQueue = _owner._readCompletePendingQueue; // If there is no space left in the queue, just keep on processing everything that is already // stored there and try again. while (!readCompletePendingQueue.TryEnqueue(this)) { _owner.ProcessPendingReadCompleteQueue(); } } protected override IChannelHandlerContext ParentContext => _owner.InternalContext; } } }
45.469586
146
0.601295
[ "MIT" ]
maksimkim/SpanNetty
src/DotNetty.Codecs.Http2/Http2MultiplexHandler.cs
18,690
C#
using System.Collections.Generic; using System.ComponentModel; namespace FormUI.Domain.BestStartGrantForms.Dto { public class ExistingChildren { public ExistingChildren() { Children = new List<ExistingChild>(); } [DisplayName("Do you have any children you're responsible for in your household?")] public bool? AnyExistingChildren { get; set; } public IList<ExistingChild> Children { get; set; } } }
27.777778
91
0.624
[ "MIT" ]
sg-deu/social-security-alpha-2
SgAlpha2/FormUI/Domain/BestStartGrantForms/Dto/ExistingChildren.cs
502
C#
using System.Data.Entity; using FarmerBazzar.Models; using FarmerBazzar.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CVAnalyzer.Repositories { public class RatingRepository { private AppContext _appContext; private ProductRepository _productRepository; public RatingRepository() { _appContext = new AppContext(); _productRepository = new ProductRepository(); } public int AddRating(Rating rating) { _appContext.Ratings.Add(rating); _appContext.SaveChanges(); return rating.RatingId; } public bool UpdateRating(Rating rating) { _appContext.Entry(rating).State=EntityState.Modified; return _appContext.SaveChanges() > 0; } public bool DeleteRating(Rating rating) { _appContext.Ratings.Remove(rating); return _appContext.SaveChanges() > 0; } public bool HasRated(int farmerId, int productId) { return _appContext.Ratings.Count(r => r.FarmerId.Equals(farmerId) && r.ProductId.Equals(productId)) > 0; } public double GetAverageRating(int productId) { if (_appContext.Ratings.Count(r => r.ProductId.Equals(productId)) == 0) return 0.0; return _appContext.Ratings.Where(r => r.ProductId.Equals(productId)).Average(r => r.Value); } public bool DeleteRating(int productId) { _appContext.Ratings.RemoveRange(_appContext.Ratings.Where(e => e.ProductId == productId)); return _appContext.SaveChanges() > 0; } } }
29.216667
115
0.615516
[ "Apache-2.0" ]
IITDU-Spartans/IITDU.SIUSC
CVAnalyzer/CVAnalyzer/Repositories/RatingRepository.cs
1,755
C#
using System; using Aop.Api.Domain; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: alipay.platform.userid.get /// </summary> public class AlipayPlatformUseridGetRequest : IAopRequest<AlipayPlatformUseridGetResponse> { /// <summary> /// 根据OpenId获取UserId /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.platform.userid.get"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.390909
94
0.603187
[ "MIT" ]
BJDIIL/DiiL
Sdk/AlipaySdk/Request/AlipayPlatformUseridGetRequest.cs
2,581
C#
// Dudi265 v1.0 [Example Usage] // By : VickyAziz // Version : 1.0 // Release : // --> v1.0 (13/10/2017) // - First Release "Dudi265 - StringCrypto" // - Simple UI, proof of concept algorithm // - Can only encrypt-decrypt string // - Example Usage // Library Used using System; using System.Windows.Forms; using Dudi265Lib; // add this library namespace EnryptDecryptDudi265 { public partial class MainForm : Form { // Main Form public MainForm() { InitializeComponent(); } // Button Pressed private void btnProcess_Click(object sender, EventArgs e) { // Local Variables string tempPlain = ""; string tempEncrypt = ""; string tempDecrypt = ""; // Process Grab Text from TextForm tempPlain = lblPlain.Text; // Process Encryption tempEncrypt = Dudi265.Encrypt(tempPlain); // Process Decryption tempDecrypt = Dudi265.Decrypt(tempEncrypt); // Display Label lblEncrypt.Text = tempEncrypt; lblDecrypt.Text = tempDecrypt; } } }
27.130435
66
0.540064
[ "MIT" ]
misagani/rijndael-dudi265
sources/EnryptDecryptDudi265/MainForm.cs
1,250
C#
namespace DNTFrameworkCore.Mapping { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; /// <summary> /// <see cref="IMapper{TSource, TDestination}"/> extension methods. /// </summary> public static class MapperExtensions { /// <summary> /// Maps the specified source object to a new object with a type of <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source object.</typeparam> /// <typeparam name="TDestination">The type of the destination object.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source object.</param> /// <returns>The mapped object of type <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper" /> or <paramref name="source" /> is /// <c>null</c>.</exception> public static TDestination Map<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, TSource source) where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = Factory<TDestination>.New(); mapper.Map(source, destination); return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSourceCollection">The type of the source collection.</typeparam> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="sourceCollection">The source collection.</param> /// <param name="destinationCollection">The destination collection.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="sourceCollection"/> is /// <c>null</c>.</exception> public static TDestination[] MapArray<TSourceCollection, TSource, TDestination>( this IMapper<TSource, TDestination> mapper, TSourceCollection sourceCollection, TDestination[] destinationCollection) where TSourceCollection : IEnumerable<TSource> where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (sourceCollection == null) { throw new ArgumentNullException(nameof(sourceCollection)); } var i = 0; foreach (var item in sourceCollection) { var destination = Factory<TDestination>.New(); mapper.Map(item, destination); destinationCollection[i] = destination; ++i; } return destinationCollection; } /// <summary> /// Maps the list of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static TDestination[] MapArray<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, List<TSource> source) where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new TDestination[source.Count]; for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.New(); mapper.Map(sourceItem, destinationItem); destination[i] = destinationItem; } return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static TDestination[] MapArray<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, Collection<TSource> source) where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new TDestination[source.Count]; for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.New(); mapper.Map(sourceItem, destinationItem); destination[i] = destinationItem; } return destination; } /// <summary> /// Maps the array of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static TDestination[] MapArray<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, TSource[] source) where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new TDestination[source.Length]; for (var i = 0; i < source.Length; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.New(); mapper.Map(sourceItem, destinationItem); destination[i] = destinationItem; } return destination; } /// <summary> /// Maps the enumerable of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static TDestination[] MapArray<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, IEnumerable<TSource> source) where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new TDestination[source.Count()]; var i = 0; foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.New(); mapper.Map(sourceItem, destinationItem); destination[i] = destinationItem; ++i; } return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource" /> into a collection of type /// <typeparamref name="TDestinationCollection" /> containing objects of type <typeparamref name="TDestination" />. /// </summary> /// <typeparam name="TSourceCollection">The type of the source collection.</typeparam> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestinationCollection">The type of the destination collection.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="sourceCollection">The source collection.</param> /// <param name="destinationCollection">The destination collection.</param> /// <returns>A collection of type <typeparamref name="TDestinationCollection"/> containing objects of type /// <typeparamref name="TDestination" />. /// </returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper" /> or <paramref name="sourceCollection" /> is /// <c>null</c>.</exception> public static TDestinationCollection MapCollection<TSourceCollection, TSource, TDestinationCollection, TDestination>( this IMapper<TSource, TDestination> mapper, TSourceCollection sourceCollection, TDestinationCollection destinationCollection) where TSourceCollection : IEnumerable<TSource> where TDestinationCollection : ICollection<TDestination> where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (sourceCollection == null) { throw new ArgumentNullException(nameof(sourceCollection)); } foreach (var item in sourceCollection) { var destination = Factory<TDestination>.New(); mapper.Map(item, destination); destinationCollection.Add(destination); } return destinationCollection; } /// <summary> /// Maps the list of <typeparamref name="TSource"/> into a collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>A collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static Collection<TDestination> MapCollection<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, List<TSource> source) where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new Collection<TDestination>(); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.New(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into a collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>A collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static Collection<TDestination> MapCollection<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, Collection<TSource> source) where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new Collection<TDestination>(); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.New(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the array of <typeparamref name="TSource"/> into a collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>A collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static Collection<TDestination> MapCollection<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, TSource[] source) where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new Collection<TDestination>(); for (var i = 0; i < source.Length; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.New(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the enumerable of <typeparamref name="TSource"/> into a collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>A collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static Collection<TDestination> MapCollection<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, IEnumerable<TSource> source) where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new Collection<TDestination>(); foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.New(); mapper.Map(sourceItem, destinationItem); destination.Add(destinationItem); } return destination; } /// <summary> /// Maps the list of <typeparamref name="TSource"/> into a list of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>A list of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static List<TDestination> MapList<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, List<TSource> source) where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new List<TDestination>(source.Count); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.New(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into a list of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>A list of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static List<TDestination> MapList<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, Collection<TSource> source) where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new List<TDestination>(source.Count); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.New(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the array of <typeparamref name="TSource"/> into a list of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>A list of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static List<TDestination> MapList<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, TSource[] source) where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new List<TDestination>(source.Length); for (var i = 0; i < source.Length; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.New(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the enumerable of <typeparamref name="TSource"/> into a list of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>A list of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static List<TDestination> MapList<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, IEnumerable<TSource> source) where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new List<TDestination>(source.Count()); foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.New(); mapper.Map(sourceItem, destinationItem); destination.Add(destinationItem); } return destination; } /// <summary> /// Maps the list of <typeparamref name="TSource"/> into an observable collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>An observable collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static ObservableCollection<TDestination> MapObservableCollection<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, List<TSource> source) where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new ObservableCollection<TDestination>(); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.New(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into an observable collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>An observable collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static ObservableCollection<TDestination> MapObservableCollection<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, Collection<TSource> source) where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new ObservableCollection<TDestination>(); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.New(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the array of <typeparamref name="TSource"/> into an observable collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>An observable collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static ObservableCollection<TDestination> MapObservableCollection<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, TSource[] source) where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new ObservableCollection<TDestination>(); for (var i = 0; i < source.Length; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.New(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the enumerable of <typeparamref name="TSource"/> into an observable collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>An observable collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static ObservableCollection<TDestination> MapObservableCollection<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, IEnumerable<TSource> source) where TDestination : new() { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new ObservableCollection<TDestination>(); foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.New(); mapper.Map(sourceItem, destinationItem); destination.Add(destinationItem); } return destination; } } }
42.165986
125
0.5635
[ "Apache-2.0" ]
amir-ashy/DNTFrameworkCore
src/DNTFrameworkCore/Mapping/MapperExtensions.cs
30,992
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/MsHTML.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop.Windows; /// <include file='IHTMLRect2.xml' path='doc/member[@name="IHTMLRect2"]/*' /> [Guid("3051076C-98B5-11CF-BB82-00AA00BDCE0B")] [NativeTypeName("struct IHTMLRect2 : IDispatch")] [NativeInheritance("IDispatch")] public unsafe partial struct IHTMLRect2 : IHTMLRect2.Interface { public void** lpVtbl; /// <inheritdoc cref="IUnknown.QueryInterface" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(0)] public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) { return ((delegate* unmanaged<IHTMLRect2*, Guid*, void**, int>)(lpVtbl[0]))((IHTMLRect2*)Unsafe.AsPointer(ref this), riid, ppvObject); } /// <inheritdoc cref="IUnknown.AddRef" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(1)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* unmanaged<IHTMLRect2*, uint>)(lpVtbl[1]))((IHTMLRect2*)Unsafe.AsPointer(ref this)); } /// <inheritdoc cref="IUnknown.Release" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(2)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* unmanaged<IHTMLRect2*, uint>)(lpVtbl[2]))((IHTMLRect2*)Unsafe.AsPointer(ref this)); } /// <inheritdoc cref="IDispatch.GetTypeInfoCount" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(3)] public HRESULT GetTypeInfoCount(uint* pctinfo) { return ((delegate* unmanaged<IHTMLRect2*, uint*, int>)(lpVtbl[3]))((IHTMLRect2*)Unsafe.AsPointer(ref this), pctinfo); } /// <inheritdoc cref="IDispatch.GetTypeInfo" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(4)] public HRESULT GetTypeInfo(uint iTInfo, [NativeTypeName("LCID")] uint lcid, ITypeInfo** ppTInfo) { return ((delegate* unmanaged<IHTMLRect2*, uint, uint, ITypeInfo**, int>)(lpVtbl[4]))((IHTMLRect2*)Unsafe.AsPointer(ref this), iTInfo, lcid, ppTInfo); } /// <inheritdoc cref="IDispatch.GetIDsOfNames" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(5)] public HRESULT GetIDsOfNames([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("LPOLESTR *")] ushort** rgszNames, uint cNames, [NativeTypeName("LCID")] uint lcid, [NativeTypeName("DISPID *")] int* rgDispId) { return ((delegate* unmanaged<IHTMLRect2*, Guid*, ushort**, uint, uint, int*, int>)(lpVtbl[5]))((IHTMLRect2*)Unsafe.AsPointer(ref this), riid, rgszNames, cNames, lcid, rgDispId); } /// <inheritdoc cref="IDispatch.Invoke" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(6)] public HRESULT Invoke([NativeTypeName("DISPID")] int dispIdMember, [NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("LCID")] uint lcid, [NativeTypeName("WORD")] ushort wFlags, DISPPARAMS* pDispParams, VARIANT* pVarResult, EXCEPINFO* pExcepInfo, uint* puArgErr) { return ((delegate* unmanaged<IHTMLRect2*, int, Guid*, uint, ushort, DISPPARAMS*, VARIANT*, EXCEPINFO*, uint*, int>)(lpVtbl[6]))((IHTMLRect2*)Unsafe.AsPointer(ref this), dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); } /// <include file='IHTMLRect2.xml' path='doc/member[@name="IHTMLRect2.get_width"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(7)] public HRESULT get_width(float* p) { return ((delegate* unmanaged<IHTMLRect2*, float*, int>)(lpVtbl[7]))((IHTMLRect2*)Unsafe.AsPointer(ref this), p); } /// <include file='IHTMLRect2.xml' path='doc/member[@name="IHTMLRect2.get_height"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(8)] public HRESULT get_height(float* p) { return ((delegate* unmanaged<IHTMLRect2*, float*, int>)(lpVtbl[8]))((IHTMLRect2*)Unsafe.AsPointer(ref this), p); } public interface Interface : IDispatch.Interface { [VtblIndex(7)] HRESULT get_width(float* p); [VtblIndex(8)] HRESULT get_height(float* p); } public partial struct Vtbl<TSelf> where TSelf : unmanaged, Interface { [NativeTypeName("HRESULT (const IID &, void **) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, Guid*, void**, int> QueryInterface; [NativeTypeName("ULONG () __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint> AddRef; [NativeTypeName("ULONG () __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint> Release; [NativeTypeName("HRESULT (UINT *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint*, int> GetTypeInfoCount; [NativeTypeName("HRESULT (UINT, LCID, ITypeInfo **) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint, uint, ITypeInfo**, int> GetTypeInfo; [NativeTypeName("HRESULT (const IID &, LPOLESTR *, UINT, LCID, DISPID *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, Guid*, ushort**, uint, uint, int*, int> GetIDsOfNames; [NativeTypeName("HRESULT (DISPID, const IID &, LCID, WORD, DISPPARAMS *, VARIANT *, EXCEPINFO *, UINT *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, int, Guid*, uint, ushort, DISPPARAMS*, VARIANT*, EXCEPINFO*, uint*, int> Invoke; [NativeTypeName("HRESULT (float *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, float*, int> get_width; [NativeTypeName("HRESULT (float *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, float*, int> get_height; } }
45.395522
275
0.681078
[ "MIT" ]
reflectronic/terrafx.interop.windows
sources/Interop/Windows/Windows/um/MsHTML/IHTMLRect2.cs
6,085
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using EventDrivenThinking.EventInference.Abstractions; using EventDrivenThinking.EventInference.Abstractions.Write; using EventDrivenThinking.EventInference.EventStore; using EventDrivenThinking.EventInference.Models; using EventDrivenThinking.EventInference.Schema; using EventDrivenThinking.Integrations.EventStore; using EventStore.Client; using Newtonsoft.Json; using EventData = EventStore.Client.EventData; using ILogger = Serilog.ILogger; namespace EventDrivenThinking.EventInference.EventStore { public class AggregateEventStream<TAggregate> : IAggregateEventStream<TAggregate> where TAggregate : IAggregate { private readonly IAggregateSchema<TAggregate> _aggregateSchema; private readonly ILogger _logger; private readonly IEventStoreFacade _connection; private readonly IEventConverter _eventConverter; private readonly IEventDataFactory _eventDataFactory; private readonly IEventMetadataFactory<TAggregate> _metadataFactory; public AggregateEventStream(IEventStoreFacade connection, IEventConverter eventConverter, IEventDataFactory eventDataFactory, IEventMetadataFactory<TAggregate> metadataFactory, IAggregateSchema<TAggregate> aggregateSchema, Serilog.ILogger logger) { _connection = connection; _eventConverter = eventConverter; _eventDataFactory = eventDataFactory; _metadataFactory = metadataFactory; _aggregateSchema = aggregateSchema; _logger = logger; } public async IAsyncEnumerable<IEvent> Get(Guid key) { var streamName = GetStreamName(key); await foreach (var e in _connection.ReadStreamAsync(Direction.Forwards, streamName, StreamRevision.Start, 100, resolveLinkTos: true)) { var eventType = _aggregateSchema.EventByName(e.Event.EventType); var (m, eventInstance) = _eventConverter.Convert(eventType.EventType, e); yield return eventInstance; } } public async Task<EventEnvelope[]> Append(Guid key, ulong version, Guid correlationId, IEnumerable<IEvent> published) { var streamName = GetStreamName(key); var publishedArray = published as IEvent[] ?? published.ToArray(); EventEnvelope[] data = new EventEnvelope[publishedArray.Length]; for (ulong i = 0; i < (ulong)publishedArray.Length; i++) { var ev = publishedArray[i]; data[i] = new EventEnvelope(ev, _metadataFactory.Create(key, correlationId, ev, version + i)); } var evData = data.Select(_eventDataFactory.Create); await _connection.AppendToStreamAsync(streamName, new StreamRevision(version), evData); _logger.Information("Writing event to stream {streamName} {eventNames}", streamName, publishedArray.Select(x => x.GetType().Name).ToArray()); return data; } public async Task<EventEnvelope[]> Append(Guid key, Guid correlationId, IEnumerable<IEvent> published) { var streamName = GetStreamName(key); var publishedArray = published as IEvent[] ?? published.ToArray(); EventEnvelope[] data = new EventEnvelope[publishedArray.Length]; for (int i = 0; i < publishedArray.Length; i++) { var ev = publishedArray[i]; data[i] = new EventEnvelope(ev, _metadataFactory.Create(key, correlationId, ev, (ulong)i)); } var evData = data.Select(_eventDataFactory.Create); await _connection.AppendToStreamAsync(streamName, AnyStreamRevision.NoStream, evData); return data; } public string GetStreamName<TKey>(TKey key) { var category = ServiceConventions.GetCategoryFromNamespace(typeof(TAggregate).Namespace); return $"{category}-{key.ToString()}"; } } }
40.533333
153
0.666118
[ "MIT" ]
eventmodeling/eventdriventhinking
EventDrivenThinking/EventInference/EventStore/AggregateEventStream.cs
4,258
C#
using System; using System.Collections.Generic; using System.Data; using System.Linq; using OpenTap.Tui.Views; using OpenTap.Tui.Windows; using Terminal.Gui; using Attribute = System.Attribute; namespace OpenTap.Tui.PropEditProviders { public class DataGridEditProvider : IPropEditProvider { public int Order { get; } = 15; (List<string> Headers, List<string> Columns, bool IsComplicatedType) getColumnNames(AnnotationCollection annotation, AnnotationCollection[] items) { var Columns = new List<string>(); var Headers = new List<string>(); bool isMultiColumns = items.Any(x => x.Get<IMembersAnnotation>() != null); if (isMultiColumns) { HashSet<string> names = new HashSet<string>(); Dictionary<string, double> orders = new Dictionary<string, double>(); Dictionary<string, string> realNames = new Dictionary<string, string>(); foreach (var mcol in items) { var aggregate = mcol.Get<IMembersAnnotation>(); if (aggregate != null) { foreach (var a in aggregate.Members) { var disp = a.Get<DisplayAttribute>(); var mem = a.Get<IMemberAnnotation>().Member; if (PropertiesView.FilterMember(mem) == false) continue; if (disp == null) continue; var name = disp.GetFullName() + mem.TypeDescriptor.Name; names.Add(name); realNames[name] = disp.GetFullName(); orders[name] = disp.Order; } } } foreach (var name in names.OrderBy(x => x).OrderBy(x => orders[x]).ToArray()) { Columns.Add(name); Headers.Add(realNames[name]); } } else { var name = annotation.ToString(); Columns.Add(name); Headers.Add(name); } // Check is complicated type bool isComplicatedType = false; var col = annotation.Get<ICollectionAnnotation>(); var type = col.NewElement().Get<IReflectionAnnotation>().ReflectionInfo; if (type != null) { if (type is TypeData cst) { if ((cst.DerivedTypes?.Count() ?? 0) > 0) { isComplicatedType = true; } }else if (type.CanCreateInstance == false) { isComplicatedType = true; } } return (Columns, Headers, isComplicatedType); } string calcMemberName(IMemberData member) { var disp = member.GetDisplayAttribute(); if (PropertiesView.FilterMember(member) == false) return null; if (disp == null) return null; var name = disp.GetFullName() + member.TypeDescriptor.Name; return name; } public View Edit(AnnotationCollection annotation) { var collectionAnnotation = annotation.Get<ICollectionAnnotation>(); if (collectionAnnotation == null) return null; if (annotation.Get<ReadOnlyMemberAnnotation>() != null) return null; var isReadOnly = annotation.Get<IAccessAnnotation>()?.IsReadOnly == true; var fixedSize = annotation.Get<IFixedSizeCollectionAnnotation>()?.IsFixedSize ?? false; if (fixedSize == false) fixedSize = annotation.Get<IMemberAnnotation>()?.Member.Attributes.Any(a => a is FixedSizeAttribute) ?? false; var items = collectionAnnotation.AnnotatedElements.ToArray(); bool placeholderElementAdded = false; // placeholder element is added just to do some reflection to figure out which columns to create. if (items.Length == 0) { placeholderElementAdded = true; items = new[] { collectionAnnotation.NewElement() }; collectionAnnotation.AnnotatedElements = items; if (items[0] == null) return null; } // Get headers and columns bool isComplicatedType = false; List<string> Headers = new List<string>(); List<string> Columns = new List<string>(); (Columns, Headers, isComplicatedType) = getColumnNames(annotation, items); // remove the added prototype element. if (placeholderElementAdded) { annotation.Read(); items = collectionAnnotation.AnnotatedElements.ToArray(); } var viewWrapper = new View(); var tableView = new TableView() { Height = Dim.Fill(1) }; viewWrapper.Add(tableView); var table = LoadTable(Headers, Columns, items); tableView.Table = table; tableView.CellActivated += args => { if (isReadOnly || args.Row > items.Length || args.Row < 0) return; var item = items[args.Row]; AnnotationCollection cell; var members = item.Get<IMembersAnnotation>()?.Members; // If the item does not have an IMembersAnnotation, it is a single value, and not a collection // This means we should edit the item directly if (members == null) cell = item; else cell = members.FirstOrDefault(x2 => calcMemberName(x2.Get<IMemberAnnotation>().Member) == Columns[args.Col]); if (cell == null) return; // Find edit provider var propEditor = PropEditProvider.GetProvider(cell, out var provider); if (propEditor == null) TUI.Log.Warning($"Cannot edit properties of type: {cell.Get<IMemberAnnotation>()?.ReflectionInfo.Name}"); else { var win = new EditWindow(cell.ToString()); win.Add(propEditor); Application.Run(win); } // Save values to reference object cell.Write(); cell.Read(); // Update table value var cellValue = cell.Get<IStringReadOnlyValueAnnotation>()?.Value ?? cell.Get<IObjectValueAnnotation>().Value?.ToString(); table.Rows[args.Row][args.Col] = cellValue; tableView.Update(); }; // Add helper buttons var helperButtons = new HelperButtons() { Y = Pos.Bottom(tableView) }; viewWrapper.Add(helperButtons); // Create action to create new and remove rows var actions = new List<MenuItem>(); actions.Add(new MenuItem("New Row", "", () => { var list = items.ToList(); if (isComplicatedType) { Type type = (annotation.Get<IReflectionAnnotation>().ReflectionInfo as TypeData).Load(); var win = new NewPluginWindow(TypeData.FromType(GetEnumerableElementType(type)), "Add Element"); Application.Run(win); if (win.PluginType == null) return; try { var instance = win.PluginType.CreateInstance(); list.Add(AnnotationCollection.Annotate(instance)); } catch { return; } } else { list.Add(collectionAnnotation.NewElement()); } collectionAnnotation.AnnotatedElements = list; annotation.Write(); annotation.Read(); items = collectionAnnotation.AnnotatedElements.ToArray(); (Columns, Headers, isComplicatedType) = getColumnNames(annotation, items); // Refresh table table = LoadTable(Headers, Columns, items); tableView.Table = table; tableView.Update(); helperButtons.SetActions(actions, viewWrapper); Application.Refresh(); }, () => fixedSize == false)); actions.Add(new MenuItem("Remove Row", "", () => { var index = tableView.SelectedRow; var list = items.ToList(); list.RemoveAt(index); collectionAnnotation.AnnotatedElements = list; items = collectionAnnotation.AnnotatedElements.ToArray(); // Refresh table table = LoadTable(Headers, Columns, items); tableView.Table = table; tableView.Update(); helperButtons.SetActions(actions, viewWrapper); Application.Refresh(); }, () => tableView.SelectedRow >= 0 && tableView.SelectedRow < items.Length && fixedSize == false)); helperButtons.SetActions(actions, viewWrapper); return viewWrapper; } DataTable LoadTable(List<string> Headers, List<string> Columns, AnnotationCollection[] items) { var table = new DataTable(); table.Columns.AddRange(Headers.Select(c => new DataColumn(c)).ToArray()); foreach (var item in items) { var row = table.NewRow(); for (int i = 0; i < Columns.Count; i++) { var members = item.Get<IMembersAnnotation>()?.Members; AnnotationCollection cell; if (members == null) cell = item; else cell = members.FirstOrDefault(x2 => calcMemberName(x2.Get<IMemberAnnotation>().Member) == Columns[i]); var cellValue = cell?.Get<IStringReadOnlyValueAnnotation>()?.Value ?? cell?.Get<IObjectValueAnnotation>().Value?.ToString(); if (string.IsNullOrEmpty(cellValue)) row[i] = DBNull.Value; else row[i] = cellValue; } table.Rows.Add(row); } return table; } public static Type GetEnumerableElementType(System.Type enumType) { if (enumType.IsArray) return enumType.GetElementType(); var ienumInterface = enumType.GetInterface("IEnumerable`1") ?? enumType; if (ienumInterface != null) return ienumInterface.GetGenericArguments().FirstOrDefault(); return typeof(object); } } public class FixedSizeAttribute : Attribute { } }
39.445205
154
0.500695
[ "MIT" ]
StefanHolst/opentap-tui
OpenTAP.TUI/PropEditProviders/DataGridEditProvider.cs
11,518
C#
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; /// <summary> /// Unity Editor Primitives creation menu items /// </summary> public class PrimitivesMenuItems { #region menu items methods /// <summary> /// Create Plane Primitive in Unity Editor /// </summary> [MenuItem("GameObject/Primivites/2D/Plane",false,-10)] private static void AddPlane() { GameObject gameObject = new GameObject() { name = "Plane" }; gameObject.AddComponent<PlaneMonoBehaviour>(); CenterAndSelectObject(gameObject); } #endregion #region helper methods /// <summary> /// Centers camera on created GameObject, and selects it /// </summary> /// <param name="go">GameObject to center on and select</param> private static void CenterAndSelectObject(GameObject go) { Selection.activeObject = SceneView.lastActiveSceneView; Vector3 position = SceneView.lastActiveSceneView.pivot; go.transform.position = position; Selection.activeGameObject = go; } #endregion }
23.958333
67
0.656522
[ "MIT" ]
HulioVRD/Creative-Coding-Unity
Assets/[CREATIVE CODING]/Scripts/Primitives/Menus/PrimitivesMenuItems.cs
1,152
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using MoviesAPI.Entities; using MoviesAPI.Filters; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace MoviesAPI.Controllers { [Route("api/genres")] [ApiController] public class GenresController: ControllerBase { private readonly ILogger<GenresController> logger; public GenresController(ILogger<GenresController> logger) { this.logger = logger; } [HttpGet] // api/genres public async Task<ActionResult<List<Genre>>> Get() { logger.LogInformation("Getting all the genres"); return new List<Genre>() { new Genre() { Id = 1, Name = "Comedy" } }; } [HttpGet("{Id:int}", Name = "getGenre")] // api/genres/example public ActionResult<Genre> Get(int Id) { throw new NotImplementedException(); } [HttpPost] public ActionResult Post([FromBody] Genre genre) { throw new NotImplementedException(); } [HttpPut] public ActionResult Put([FromBody] Genre genre) { throw new NotImplementedException(); } [HttpDelete] public ActionResult Delete() { throw new NotImplementedException(); } } }
25.181818
81
0.599278
[ "MIT" ]
mkotto/CinemaHub
MoviesAPI/MoviesAPI/Controllers/GenresController.cs
1,387
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Wire.PerfTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Wire.PerfTest")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("35352664-e867-48ec-a0b1-39013ca42fe0")] // 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")]
34.948718
84
0.738811
[ "Apache-2.0" ]
philiplaureano/Wire
Wire.PerfTest/Properties/AssemblyInfo.cs
1,366
C#
// Copyright (c) 2018 Daniel A Hill. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Text; namespace ApiActions.Swagger.Specification { public class SwaggerResponse : ICustomSwaggerJsonSerializable { public string Code { get; set; } public string Description { get; set; } public SwaggerReferenceLink Reference { get; set; } public void SerializeJson(StringBuilder builder, Action<object, StringBuilder, int> serializeChild, int recursionsLeft) { builder.Append('"'); builder.Append(Code); builder.Append("\":{"); if (!string.IsNullOrWhiteSpace(Description)) { builder.Append("\"description\":\""); builder.AppendJsonDelimited(Description); builder.Append("\","); } builder.Append("\"schema\":"); serializeChild(Reference, builder, recursionsLeft - 1); builder.Append("}"); } } }
33.510638
107
0.63746
[ "Apache-2.0" ]
DanielAHill/ApiActions
src/ApiActions.Swagger/Specification/SwaggerResponse.cs
1,575
C#
using System.Collections.Generic; using System.Linq; namespace Mallet.DataStructures.Geometric { // Ported from: https://github.com/evanw/csg.js/ // Copyright (c) 2011 Evan Wallace (http://madebyevan.com/) // MIT license public class CsgNode { private List<Polygon> Polygons { get; set; } private Plane Plane { get; set; } private CsgNode Front { get; set; } private CsgNode Back { get; set; } public CsgNode(CsgSolid solid) : this() { Build(solid.Polygons.ToList()); } private CsgNode() { Polygons = new List<Polygon>(); Front = null; Back = null; } private List<Polygon> ClipPolygons(IEnumerable<Polygon> polygons) { if (Plane == null) return polygons.ToList(); var pp = Plane.ToPrecisionPlane(); var front = new List<Polygon>(); var back = new List<Polygon>(); foreach (var polygon in polygons.Select(x => x.ToPrecisionPolygon())) { polygon.Split(pp, out var b, out var f, out var cb, out var cf); if (f != null) front.Add(f.ToStandardPolygon()); if (b != null) back.Add(b.ToStandardPolygon()); if (cf != null) front.Add(cf.ToStandardPolygon()); if (cb != null) back.Add(cb.ToStandardPolygon()); } if (Front != null) front = Front.ClipPolygons(front); back = Back != null ? Back.ClipPolygons(back) : new List<Polygon>(); return front.Concat(back).ToList(); } public void ClipTo(CsgNode bsp) { Polygons = bsp.ClipPolygons(Polygons); if (Front != null) Front.ClipTo(bsp); if (Back != null) Back.ClipTo(bsp); } public void Invert() { Polygons = Polygons.Select(x => x.Flip()).ToList(); Plane = new Plane(-Plane.Normal, Plane.PointOnPlane); if (Front != null) Front.Invert(); if (Back != null) Back.Invert(); var temp = Front; Front = Back; Back = temp; } public List<Polygon> AllPolygons() { var polygons = Polygons.ToList(); if (Front != null) polygons.AddRange(Front.AllPolygons()); if (Back != null) polygons.AddRange(Back.AllPolygons()); return polygons; } public void Build(List<Polygon> polygons) { if (polygons.Count == 0) return; if (Plane == null) Plane = polygons[0].Plane.Clone(); var pp = Plane.ToPrecisionPlane(); var front = new List<Polygon>(); var back = new List<Polygon>(); foreach (var polygon in polygons.Select(x => x.ToPrecisionPolygon())) { polygon.Split(pp, out var b, out var f, out var cb, out var cf); if (f != null) front.Add(f.ToStandardPolygon()); if (b != null) back.Add(b.ToStandardPolygon()); if (cf != null) front.Add(cf.ToStandardPolygon()); if (cb != null) back.Add(cb.ToStandardPolygon()); } if (front.Count > 0) { if (Front == null) Front = new CsgNode(); Front.Build(front); } if (back.Count > 0) { if (Back == null) Back = new CsgNode(); Back.Build(back); } } } }
35.29703
81
0.506872
[ "BSD-3-Clause" ]
jspicer-code/mallet
Mallet.DataStructures/Geometric/CsgNode.cs
3,567
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NGettext.Plural; using Translatable; namespace Translation { public class GettextPluralBuilder : IPluralBuilder { private readonly IPluralRule _pluralRule; public GettextPluralBuilder(IPluralRule pluralRule) { _pluralRule = pluralRule; } public int NumberOfPlurals => _pluralRule.NumPlurals; public string GetPlural(int number, IList<string> pluralForms) { return pluralForms[_pluralRule.Evaluate(number)]; } public string GetFormattedPlural(int number, IList<string> pluralForms) { return string.Format(GetPlural(number, pluralForms), number); } } }
25.666667
80
0.650531
[ "MIT" ]
pdfforge/translatable
Source/Translatable.NGettext/GettextPluralBuilder.cs
817
C#
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; namespace Microsoft.Azure.Subscriptions.Models { /// <summary> /// Tenant Id information /// </summary> public partial class TenantIdDescription { private string _id; /// <summary> /// Optional. Gets or sets Id /// </summary> public string Id { get { return this._id; } set { this._id = value; } } private string _tenantId; /// <summary> /// Optional. Gets or sets tenantId /// </summary> public string TenantId { get { return this._tenantId; } set { this._tenantId = value; } } /// <summary> /// Initializes a new instance of the TenantIdDescription class. /// </summary> public TenantIdDescription() { } } }
27.419355
76
0.604118
[ "Apache-2.0" ]
CerebralMischief/azure-sdk-for-net
src/ResourceManagement/Resource/ResourceManagement/Generated/Models/TenantIdDescription.cs
1,700
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Optimization; using System.Web.UI; namespace BookstoreWebForms { public class BundleConfig { // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkID=303951 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/WebFormsJs").Include( "~/Scripts/WebForms/WebForms.js", "~/Scripts/WebForms/WebUIValidation.js", "~/Scripts/WebForms/MenuStandards.js", "~/Scripts/WebForms/Focus.js", "~/Scripts/WebForms/GridView.js", "~/Scripts/WebForms/DetailsView.js", "~/Scripts/WebForms/TreeView.js", "~/Scripts/WebForms/WebParts.js")); // Order is very important for these files to work, they have explicit dependencies bundles.Add(new ScriptBundle("~/bundles/MsAjaxJs").Include( "~/Scripts/WebForms/MsAjax/MicrosoftAjax.js", "~/Scripts/WebForms/MsAjax/MicrosoftAjaxApplicationServices.js", "~/Scripts/WebForms/MsAjax/MicrosoftAjaxTimer.js", "~/Scripts/WebForms/MsAjax/MicrosoftAjaxWebForms.js")); // Use the Development version of Modernizr to develop with and learn from. Then, when you’re // ready for production, use the build tool at http://modernizr.com to pick only the tests you need bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); ScriptManager.ScriptResourceMapping.AddDefinition( "respond", new ScriptResourceDefinition { Path = "~/Scripts/respond.min.js", DebugPath = "~/Scripts/respond.js", }); } } }
45.23913
111
0.565113
[ "MIT" ]
PhilipYordanov/BookstoreService
BookstoreService/BookstoreWebForms/App_Start/BundleConfig.cs
2,085
C#
using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace PTR { public class CustomDataGridTextColumn : DataGridTextColumn { public CustomDataGridTextColumn() : base() { } protected override System.Windows.FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { var textBox = (TextBox)base.GenerateEditingElement(cell, dataItem); //textBox.GotFocus += TextBox_GotFocus; //// textBox.TextChanged += OnTextChanged; //textBox.PreviewMouseLeftButtonDown += TextBox_PreviewMouseLeftButtonDown; //textBox.GotKeyboardFocus += TextBox_GotKeyboardFocus; //textBox.MouseDoubleClick += TextBox_MouseDoubleClick; return base.GenerateElement(cell, dataItem); } private void TextBox_GotFocus(object sender, RoutedEventArgs e) { (sender as TextBox).SelectAll(); } private void TextBox_MouseDoubleClick(object sender, MouseButtonEventArgs e) { (sender as TextBox).SelectAll(); } private void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { (sender as TextBox).SelectAll(); } private void TextBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { (sender as TextBox).SelectAll(); } } }
28.678571
111
0.618306
[ "MIT" ]
tcd1nc/ProjectRep-PTR
Controls/CustomDataGridTextColumn.cs
1,608
C#
using PropertyChanged; using System.ComponentModel; using System.Runtime.CompilerServices; namespace XCalendarFormsSample.ViewModels { [AddINotifyPropertyChangedInterface] public abstract class BaseViewModel : INotifyPropertyChanged { #region Events public event PropertyChangedEventHandler PropertyChanged; #endregion #region Methods protected virtual void OnPropertyChanged([CallerMemberName] string PropertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName)); } #endregion } }
27.818182
95
0.720588
[ "MIT" ]
ME-MarvinE/XCalendar
XCalendarFormsSample/XCalendarFormsSample/ViewModels/BaseViewModel.cs
614
C#
using System; using System.Text; using System.Windows.Forms; namespace DevExpress.XtraCharts.Wizard.ChartAxesControls { public class AxisScaleOptionsControl : UserControl { } }
20.111111
58
0.80663
[ "Unlicense" ]
broteam168/QuizContest-broteam
DoAn_thitracnghiem/bin/Debug/vi/Sources/DevExpress.XtraCharts.Wizard/ChartAxesControls/AxisScaleOptionsControl.cs
181
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Serialization; namespace Workday.Staffing { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Certification_Qualification_Profile_Replacement_DataType : INotifyPropertyChanged { private CountryObjectType country_ReferenceField; private CertificationObjectType certification_ReferenceField; private string nameField; private string issuerField; private bool requiredField; private bool requiredFieldSpecified; private Specialty_Achievement_DataType[] specialty_Achievement_ReferenceField; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlElement(Order = 0)] public CountryObjectType Country_Reference { get { return this.country_ReferenceField; } set { this.country_ReferenceField = value; this.RaisePropertyChanged("Country_Reference"); } } [XmlElement(Order = 1)] public CertificationObjectType Certification_Reference { get { return this.certification_ReferenceField; } set { this.certification_ReferenceField = value; this.RaisePropertyChanged("Certification_Reference"); } } [XmlElement(Order = 2)] public string Name { get { return this.nameField; } set { this.nameField = value; this.RaisePropertyChanged("Name"); } } [XmlElement(Order = 3)] public string Issuer { get { return this.issuerField; } set { this.issuerField = value; this.RaisePropertyChanged("Issuer"); } } [XmlElement(Order = 4)] public bool Required { get { return this.requiredField; } set { this.requiredField = value; this.RaisePropertyChanged("Required"); } } [XmlIgnore] public bool RequiredSpecified { get { return this.requiredFieldSpecified; } set { this.requiredFieldSpecified = value; this.RaisePropertyChanged("RequiredSpecified"); } } [XmlElement("Specialty_Achievement_Reference", Order = 5)] public Specialty_Achievement_DataType[] Specialty_Achievement_Reference { get { return this.specialty_Achievement_ReferenceField; } set { this.specialty_Achievement_ReferenceField = value; this.RaisePropertyChanged("Specialty_Achievement_Reference"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
20.185714
136
0.721868
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.Staffing/Certification_Qualification_Profile_Replacement_DataType.cs
2,826
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace CELA_Tags_Service { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
24.375
99
0.591453
[ "MIT" ]
Bhaskers-Blu-Org2/CELA-Outlook-Tag-Management
CELA-Tags_Service/App_Start/RouteConfig.cs
587
C#
using System.Drawing; namespace SimpleDnsCrypt.Extensions { /// <summary> /// ColorConverterExtensions. /// </summary> /// <see cref="https://stackoverflow.com/a/37821008/1837988"/> public static class ColorConverterExtensions { public static string ToHexString(this Color c) => $"#{c.R:X2}{c.G:X2}{c.B:X2}"; public static string ToRgbString(this Color c) => $"RGB({c.R}, {c.G}, {c.B})"; } }
27.4375
87
0.621868
[ "MIT" ]
instantsc/SimpleDnsCrypt
SimpleDnsCrypt/Extensions/ColorConverterExtensions.cs
441
C#
namespace libwaifu2x { /// <summary> /// waifu2x processor /// </summary> public enum Waifu2xProcessors { /// <summary> /// CPU /// </summary> CPU = -1, /// <summary> /// AUTO /// </summary> AUTO = 0, /// <summary> /// GPU /// </summary> GPU = 1 } /// <summary> /// waifu2x model /// </summary> public enum Waifu2xModels { CUnet = 2, UpConv7Anime = 12, UpConv7Photo = 14 } /// <summary> /// waifu2x Image format /// </summary> public enum Waifu2xImageFormat { Png = 0, Jpg = 2 } }
14.486486
35
0.544776
[ "MIT" ]
Soju06/libwaifu2x
wrapper/csharp/Waifu2xEnums.cs
538
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityModel; using IdentityServer4.Models; using System.Collections.Generic; namespace MyIdentityServer.Configuration { public class Resources { public static IEnumerable<IdentityResource> GetIdentityResources() { return new[] { // some standard scopes from the OIDC spec new IdentityResources.OpenId(), new IdentityResources.Profile(), new IdentityResources.Email(), // custom identity resource with some consolidated claims new IdentityResource("custom.profile", new[] { JwtClaimTypes.Name, JwtClaimTypes.Email, "location" }) }; } public static IEnumerable<ApiResource> GetApiResources() { return new[] { // simple version with ctor new ApiResource("api1", "Some API 1") { // this is needed for introspection when using reference tokens ApiSecrets = { new Secret("secret".Sha256()) } }, // expanded version if more control is needed new ApiResource { Name = "api2", ApiSecrets = { new Secret("secret".Sha256()) }, UserClaims = { JwtClaimTypes.Name, JwtClaimTypes.Email }, Scopes = { new Scope() { Name = "api2.full_access", DisplayName = "Full access to API 2", }, new Scope { Name = "api2.read_only", DisplayName = "Read only access to API 2" } } } }; } } }
33.28169
118
0.427
[ "MIT" ]
carathorys/MyIdentity
Quickstart/Seed/Resources.cs
2,363
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using Azure.Core; using Azure.ResourceManager.Models; using Azure.ResourceManager.Workloads.Models; namespace Azure.ResourceManager.Workloads { /// <summary> A class representing the WordPressInstanceResource data model. </summary> public partial class WordPressInstanceResourceData : ResourceData { /// <summary> Initializes a new instance of WordPressInstanceResourceData. </summary> public WordPressInstanceResourceData() { } /// <summary> Initializes a new instance of WordPressInstanceResourceData. </summary> /// <param name="id"> The id. </param> /// <param name="name"> The name. </param> /// <param name="resourceType"> The resourceType. </param> /// <param name="systemData"> The systemData. </param> /// <param name="version"> Application version. </param> /// <param name="databaseName"> Database name used by the application. </param> /// <param name="databaseUser"> User name used by the application to connect to database. </param> /// <param name="siteUri"> Site Url to access the WordPress application. </param> /// <param name="provisioningState"> WordPress instance provisioning state. </param> internal WordPressInstanceResourceData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, WordPressVersion? version, string databaseName, string databaseUser, Uri siteUri, ApplicationProvisioningState? provisioningState) : base(id, name, resourceType, systemData) { Version = version; DatabaseName = databaseName; DatabaseUser = databaseUser; SiteUri = siteUri; ProvisioningState = provisioningState; } /// <summary> Application version. </summary> public WordPressVersion? Version { get; set; } /// <summary> Database name used by the application. </summary> public string DatabaseName { get; set; } /// <summary> User name used by the application to connect to database. </summary> public string DatabaseUser { get; set; } /// <summary> Site Url to access the WordPress application. </summary> public Uri SiteUri { get; } /// <summary> WordPress instance provisioning state. </summary> public ApplicationProvisioningState? ProvisioningState { get; } } }
47.259259
306
0.676332
[ "MIT" ]
damodaravadhani/azure-sdk-for-net
sdk/workloads/Azure.ResourceManager.Workloads/src/Generated/WordPressInstanceResourceData.cs
2,552
C#
// This file constitutes a part of the SharpMedia project, (c) 2007 by the SharpMedia team // and is licensed for your use under the conditions of the NDA or other legally binding contract // that you or a legal entity you represent has signed with the SharpMedia team. // In an event that you have received or obtained this file without such legally binding contract // in place, you MUST destroy all files and other content to which this lincese applies and // contact the SharpMedia team for further instructions at the internet mail address: // // [email protected] // using System; using System.Collections.Generic; using System.Text; namespace SharpMedia.Components { /// <summary> /// Publishing information. Any objects that are published should implement this /// </summary> public interface IPublishedInfo { /// <summary> /// Name of the publishing entity that has published the object /// </summary> string PublisherName { get; } /// <summary> /// Authors of the object /// </summary> string[] Authors { get; } } /// <summary> /// /// </summary> public interface IPublishedInfoAuthoring : IPublishedInfo { new string PublisherName { set; } new string[] Authors { set; } } }
32.268293
97
0.670446
[ "Apache-2.0" ]
zigaosolin/SharpMedia
SharpMedia/Components/IPublishedInfo.cs
1,323
C#
using Leak.Common; namespace Leak.Events { public class MetafileVerified { public FileHash Hash; public Metainfo Metainfo; public int Size; } }
14.076923
33
0.622951
[ "MIT" ]
amacal/leak
sources/Leak.Events/MetafileVerified.cs
185
C#
namespace Beacon.Sdk.Beacon.Permission { /// <summary> /// The threshold is not enforced on the dapp side. It's only as an information to the user /// </summary> public record Threshold(string Amount, string Timeframe) { /// <summary> /// The amount of mutez that can be spent within the timeframe /// </summary> public string Amount { get; } = Amount; /// <summary> /// The timeframe within which the spending will be summed up /// </summary> public string Timeframe { get; } = Timeframe; } }
33
99
0.587542
[ "MIT" ]
baking-bad/beacon-dotnet-sdk
Beacon.Sdk/Beacon/Permission/Threshold.cs
594
C#
namespace Mantle.Plugins.Caching.Redis { public static class LocalizableStrings { public static class Settings { public const string ConnectionString = "Mantle.Plugins.Caching.Redis/Settings.ConnectionString"; } } }
26.4
108
0.666667
[ "MIT" ]
gordon-matt/MantleCMS
Plugins/Mantle.Plugins.Caching.Redis/LocalizableStrings.cs
266
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 System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.PooledObjects; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class ParameterGenerator { public static ParameterListSyntax GenerateParameterList( ImmutableArray<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { return GenerateParameterList((IEnumerable<IParameterSymbol>)parameterDefinitions, isExplicit, options); } public static ParameterListSyntax GenerateParameterList( IEnumerable<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { var parameters = GetParameters(parameterDefinitions, isExplicit, options); return SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters)); } public static BracketedParameterListSyntax GenerateBracketedParameterList( ImmutableArray<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { return GenerateBracketedParameterList((IList<IParameterSymbol>)parameterDefinitions, isExplicit, options); } public static BracketedParameterListSyntax GenerateBracketedParameterList( IEnumerable<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { // Bracketed parameter lists come from indexers. Those don't have type parameters, so we // could never have a typeParameterMapping. var parameters = GetParameters(parameterDefinitions, isExplicit, options); return SyntaxFactory.BracketedParameterList( parameters: SyntaxFactory.SeparatedList(parameters)); } internal static ImmutableArray<ParameterSyntax> GetParameters( IEnumerable<IParameterSymbol> parameterDefinitions, bool isExplicit, CodeGenerationOptions options) { var result = ArrayBuilder<ParameterSyntax>.GetInstance(); var seenOptional = false; var isFirstParam = true; foreach (var p in parameterDefinitions) { var parameter = GetParameter(p, options, isExplicit, isFirstParam, seenOptional); result.Add(parameter); seenOptional = seenOptional || parameter.Default != null; isFirstParam = false; } return result.ToImmutableAndFree(); } internal static ParameterSyntax GetParameter(IParameterSymbol p, CodeGenerationOptions options, bool isExplicit, bool isFirstParam, bool seenOptional) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ParameterSyntax>(p, options); if (reusableSyntax != null) { return reusableSyntax; } return SyntaxFactory.Parameter(p.Name.ToIdentifierToken()) .WithAttributeLists(GenerateAttributes(p, isExplicit, options)) .WithModifiers(GenerateModifiers(p, isFirstParam)) .WithType(p.Type.WithNullability(p.NullableAnnotation).GenerateTypeSyntax()) .WithDefault(GenerateEqualsValueClause(p, isExplicit, seenOptional)); } private static SyntaxTokenList GenerateModifiers( IParameterSymbol parameter, bool isFirstParam) { var list = CSharpSyntaxGenerator.GetParameterModifiers(parameter.RefKind); if (isFirstParam && parameter.ContainingSymbol is IMethodSymbol methodSymbol && methodSymbol.IsExtensionMethod) { list = list.Add(SyntaxFactory.Token(SyntaxKind.ThisKeyword)); } if (parameter.IsParams) { list = list.Add(SyntaxFactory.Token(SyntaxKind.ParamsKeyword)); } return list; } private static EqualsValueClauseSyntax GenerateEqualsValueClause( IParameterSymbol parameter, bool isExplicit, bool seenOptional) { if (!parameter.IsParams && !isExplicit && !parameter.IsRefOrOut()) { if (parameter.HasExplicitDefaultValue || seenOptional) { var defaultValue = parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null; if (defaultValue is DateTime) { return null; } return SyntaxFactory.EqualsValueClause( GenerateEqualsValueClauseWorker(parameter, defaultValue)); } } return null; } private static ExpressionSyntax GenerateEqualsValueClauseWorker( IParameterSymbol parameter, object value) { return ExpressionGenerator.GenerateExpression(parameter.Type, value, canUseFieldReference: true); } private static SyntaxList<AttributeListSyntax> GenerateAttributes( IParameterSymbol parameter, bool isExplicit, CodeGenerationOptions options) { if (isExplicit) { return default; } var attributes = parameter.GetAttributes(); if (attributes.Length == 0) { return default; } return AttributeGenerator.GenerateAttributeLists(attributes, options); } } }
38.725
161
0.636217
[ "Apache-2.0" ]
20chan/roslyn
src/Workspaces/CSharp/Portable/CodeGeneration/ParameterGenerator.cs
6,198
C#
using System; namespace Assman { public interface IFinderExcluder { bool ShouldExclude(IResource resource); } }
15.666667
48
0.638298
[ "BSD-3-Clause" ]
muslumbozan27/demirbas
src/Assman/IFinderExcluder.cs
143
C#
using System; namespace Login { class Program { static void Main(string[] args) { string username = Console.ReadLine(); string password = string.Empty; for (int i = username.Length - 1; i >= 0; i--) { password += username[i]; } string passwordInput = Console.ReadLine(); int counter = 0; while (passwordInput != password) { counter++; if (counter == 4) { Console.WriteLine($"User {username} blocked!"); break; } Console.WriteLine("Incorrect password. Try again."); passwordInput = Console.ReadLine(); } if (passwordInput == password) { Console.WriteLine($"User {username} logged in."); } } } }
24
68
0.430208
[ "MIT" ]
Wa4e7o/C--Fundamentals
Basic Syntax, Conditional Statements and Loops - Exercise/Login/Program.cs
960
C#
using System.Linq; namespace Infrastructure.Ddd { public interface IFilter<TQueryable, TPredicate> { IQueryable<TQueryable> Filter(IQueryable<TQueryable> queryable, TPredicate predicate); } }
23.666667
94
0.737089
[ "MIT" ]
Aleksandr-Naumov/DotNext-Moscow-2020
infrastructure/Infrastructure/Ddd/IFilter.cs
215
C#
using WellEngineered.CruiseControl.Remote; namespace WellEngineered.CruiseControl.Core { /// <summary> /// Defines a mechanism for storing data from a project. /// </summary> public interface IDataStore { #region Public methods #region StoreProjectSnapshot() /// <summary> /// Stores a snapshot of a project build. /// </summary> /// <param name="result">The result that the snapshot is for.</param> /// <param name="snapshot">The project snapshot.</param> void StoreProjectSnapshot(IIntegrationResult result, ItemStatus snapshot); #endregion #region LoadProjectSnapshot() /// <summary> /// Loads the project snapshot for a build. /// </summary> /// <param name="project">The project.</param> /// <param name="buildName">Name of the build.</param> /// <returns>The project snapshot.</returns> ItemStatus LoadProjectSnapshot(IProject project, string buildName); #endregion #endregion } }
34.1875
83
0.604205
[ "MIT" ]
wellengineered-us/cruisecontrol
src/WellEngineered.CruiseControl.Core/IDataStore.cs
1,096
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Gooios.UserServiceHost.Models { public class VerifyCookAppPartnerLoginUserByAuthCodeModel { //[JsonProperty("authCode")] public string AuthorizationCode { get; set; } } }
22.066667
61
0.740181
[ "Apache-2.0" ]
hccoo/gooios
netcoremicroservices/Gooios.UserServiceHost/Models/VerifyCookAppPartnerLoginUserByAuthCodeModel.cs
333
C#
using System; namespace KyoshinMonitorLib.UrlGenerator { /// <summary> /// 長周期地震動モニタのURL生成器 /// </summary> public static class LpgmWebApiUrlGenerator { /// <summary> /// JsonEewのベースURL /// <para>0:時間</para> /// </summary> public const string JsonEewBase = "https://www.lmoni.bosai.go.jp/monitor/webservice/hypo/eew/{0}.json"; /// <summary> /// PsWaveImgのベースURL /// <para>0:日付</para> /// <para>1:時間</para> /// </summary> public const string PsWaveBase = "https://www.lmoni.bosai.go.jp/monitor/data/data/map_img/PSWaveImg/eew/{0}/{1}.eew.gif"; /// <summary> /// RealtimeImgのベースURL /// <para>0:タイプ</para> /// <para>1:地上(s)/地下(b)</para> /// <para>2:日付</para> /// <para>3:時間</para> /// </summary> public const string RealtimeBase = "https://smi.lmoniexp.bosai.go.jp/data/map_img/RealTimeImg/{0}_{1}/{2}/{3}.{0}_{1}.gif"; /// <summary> /// RealtimeImg(長周期地震動階級)のベースURL /// <para>0:タイプ</para> /// <para>1:日付</para> /// <para>2:時間</para> /// </summary> public const string LpgmRealtimeBase = "https://www.lmoni.bosai.go.jp/monitor/data/data/map_img/RealTimeImg/{0}_s/{1}/{2}.{0}_s.gif"; /// <summary> /// LongPeriodImg 長周期地震動の予測階級のベースURL /// <para>0:日付</para> /// <para>1:時間</para> /// </summary> public const string LongPeriodBase = "https://www.lmoni.bosai.go.jp/monitor/data/data/map_img/LongPeriodImg/eew/m2/{0}/{1}.eew_m2.abrspmx.gif"; /// <summary> /// 予想震度のベースURL /// <para>0:日付</para> /// <para>1:時間</para> /// </summary> public const string EstShindoBase = "https://smi.lmoniexp.bosai.go.jp/data/map_img/EstShindoImg/eew/{0}/{1}.eew.gif"; /// <summary> /// 与えられた値を使用してURLを生成します。 /// </summary> /// <param name="urlType">生成するURLのタイプ</param> /// <param name="datetime">生成するURLの時間</param> /// <param name="realtimeShindoType">(UrlType=RealtimeImg/LpgmRealtimeImgの際に使用)取得するリアルタイム情報の種類</param> /// <param name="isBerehole">(UrlType=RealtimeImgの際に使用)地中の情報を取得するかどうか</param> /// <returns></returns> public static string Generate(LpgmWebApiUrlType urlType, DateTime datetime, RealtimeDataType realtimeShindoType = RealtimeDataType.Shindo, bool isBerehole = false) => urlType switch { LpgmWebApiUrlType.RealtimeImg => string.Format(RealtimeBase, realtimeShindoType.ToUrlString(), isBerehole ? "b" : "s", datetime.ToString("yyyyMMdd"), datetime.ToString("yyyyMMddHHmmss")), LpgmWebApiUrlType.LpgmRealtimeImg => string.Format(LpgmRealtimeBase, realtimeShindoType.ToUrlString(), datetime.ToString("yyyyMMdd"), datetime.ToString("yyyyMMddHHmmss")), LpgmWebApiUrlType.EstShindo => string.Format(EstShindoBase, datetime.ToString("yyyyMMdd"), datetime.ToString("yyyyMMddHHmmss")), LpgmWebApiUrlType.PSWave => string.Format(PsWaveBase, datetime.ToString("yyyyMMdd"), datetime.ToString("yyyyMMddHHmmss")), LpgmWebApiUrlType.EewJson => string.Format(JsonEewBase, datetime.ToString("yyyyMMddHHmmss")), LpgmWebApiUrlType.LongPeriodImg => string.Format(LongPeriodBase, datetime.ToString("yyyyMMdd"), datetime.ToString("yyyyMMddHHmmss")), _ => throw new ArgumentException($"URLを生成できない{nameof(LpgmWebApiUrlType)}が指定されています", nameof(urlType)), }; } }
43.246575
190
0.699398
[ "MIT" ]
iedred7584/KyoshinMonitorLib
src/KyoshinMonitorLib/UrlGenerator/LpgmWebApiUrlGenerator.cs
3,519
C#
using DevExpress.Mvvm; using DevExpress.Mvvm.UI.Interactivity; using DevExpress.Xpf.Dialogs; using DevExpress.Xpf.Editors; using DevExpress.Xpf.Grid; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace DXVisualTestFixer.UI.Behaviors { public class BrowseDirBehavior : Behavior<ButtonEdit> { protected override void OnAttached() { base.OnAttached(); AssociatedObject.DefaultButtonClick += AssociatedObject_DefaultButtonClick; } protected override void OnDetaching() { AssociatedObject.DefaultButtonClick -= AssociatedObject_DefaultButtonClick; base.OnDetaching(); } void AssociatedObject_DefaultButtonClick(object sender, RoutedEventArgs e) { var dialog = new DXFolderBrowserDialog() { ShowNewFolderButton = false }; var result = dialog.ShowDialog(Application.Current.Windows.Cast<Window>().Last()); if(result.HasValue && (bool)result) AssociatedObject.EditValue = dialog.SelectedPath; } } }
35.727273
95
0.685327
[ "MIT" ]
Xarlot/DXVisualTestFixer
DXVisualTestFixer.UI/Behaviors/BrowseDirBehavior.cs
1,181
C#
using Quartz; using Quartz.Impl; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Wexflow.Core.Db; namespace Wexflow.Core { /// <summary> /// Database type /// </summary> public enum DbType { /// <summary> /// LiteDB /// </summary> LiteDB, /// <summary> /// MongoDB /// </summary> MongoDB, /// <summary> /// RavenDB /// </summary> RavenDB, /// <summary> /// PostgreSQL /// </summary> PostgreSQL, /// <summary> /// SQLServer /// </summary> SQLServer, /// <summary> /// MySQL /// </summary> MySQL, /// <summary> /// SQLite /// </summary> SQLite, /// <summary> /// Firebird /// </summary> Firebird, /// <summary> /// Oracle /// </summary> Oracle, /// <summary> /// MariaDB /// </summary> MariaDB } /// <summary> /// Wexflow engine. /// </summary> public class WexflowEngine { /// <summary> /// Records db folder name. /// </summary> public string DbFolderName { get; private set; } /// <summary> /// Super-admin user name. /// </summary> public string SuperAdminUsername { get; private set; } /// <summary> /// Settings file path. /// </summary> public string SettingsFile { get; private set; } /// <summary> /// Indicates whether workflows hot folder is enabled or not. /// </summary> public bool EnableWorkflowsHotFolder { get; private set; } /// <summary> /// Indicates whether email notifications are enabled or not. /// </summary> public bool EnableEmailNotifications { get; private set; } /// <summary> /// SMTP host. /// </summary> public string SmptHost { get; private set; } /// <summary> /// SMTP port. /// </summary> public int SmtpPort { get; private set; } /// <summary> /// Indicates whether to enable SMTP SSL or not. /// </summary> public bool SmtpEnableSsl { get; private set; } /// <summary> /// SMTP user. /// </summary> public string SmtpUser { get; private set; } /// <summary> /// SMTP password. /// </summary> public string SmtpPassword { get; private set; } /// <summary> /// SMTP from. /// </summary> public string SmtpFrom { get; private set; } /// <summary> /// Workflows hot folder path. /// </summary> public string WorkflowsFolder { get; private set; } /// <summary> /// Records folder path. /// </summary> public string RecordsFolder { get; private set; } /// <summary> /// Records hot folder path. /// </summary> public string RecordsHotFolder { get; private set; } /// <summary> /// Temp folder path. /// </summary> public string TempFolder { get; private set; } /// <summary> /// Workflows temp folder used for global variables parsing. /// </summary> public string RecordsTempFolder { get; private set; } /// <summary> /// Tasks folder path. /// </summary> public string TasksFolder { get; private set; } /// <summary> /// Approval folder path. /// </summary> public string ApprovalFolder { get; private set; } /// <summary> /// XSD path. /// </summary> public string XsdPath { get; private set; } /// <summary> /// Tasks names file path. /// </summary> public string TasksNamesFile { get; private set; } /// <summary> /// Tasks settings file path. /// </summary> public string TasksSettingsFile { get; private set; } /// <summary> /// List of the Workflows loaded by Wexflow engine. /// </summary> public IList<Workflow> Workflows { get; private set; } /// <summary> /// Database type. /// </summary> public DbType DbType { get; private set; } /// <summary> /// Database connection string. /// </summary> public string ConnectionString { get; private set; } /// <summary> /// Global variables file. /// </summary> public string GlobalVariablesFile { get; private set; } /// <summary> /// Global variables. /// </summary> public Variable[] GlobalVariables { get; private set; } /// <summary> /// Database /// </summary> public Db.Db Database { get; private set; } // // Quartz scheduler // private static readonly NameValueCollection QuartzProperties = new NameValueCollection { // JSON serialization is the one supported under .NET Core (binary isn't) //["quartz.serializer.type"] = "json" // "binary" is alias for "Quartz.Simpl.BinaryObjectSerializer, Quartz" ["quartz.serializer.type"] = "binary" }; private static readonly ISchedulerFactory SchedulerFactory = new StdSchedulerFactory(QuartzProperties); private static readonly IScheduler QuartzScheduler = SchedulerFactory.GetScheduler().Result; /// <summary> /// Creates a new instance of Wexflow engine. /// </summary> /// <param name="settingsFile">Settings file path.</param> /// <param name="enableWorkflowsHotFolder">Indicates whether workflows hot folder is enabled or not.</param> /// <param name="superAdminUsername">Super-admin username.</param> /// <param name="enableEmailNotifications"></param> /// <param name="smtpHost">SMTP host.</param> /// <param name="smtpPort">SMTP port.</param> /// <param name="smtpEnableSsl">SMTP enable ssl.</param> /// <param name="smtpUser">SMTP user.</param> /// <param name="smtpPassword">SMTP password.</param> /// <param name="smtpFrom">SMTP from.</param> public WexflowEngine(string settingsFile , bool enableWorkflowsHotFolder , string superAdminUsername , bool enableEmailNotifications , string smtpHost , int smtpPort , bool smtpEnableSsl , string smtpUser , string smtpPassword , string smtpFrom ) { log4net.Config.XmlConfigurator.Configure(); SettingsFile = settingsFile; EnableWorkflowsHotFolder = enableWorkflowsHotFolder; SuperAdminUsername = superAdminUsername; EnableEmailNotifications = enableEmailNotifications; SmptHost = smtpHost; SmtpPort = smtpPort; SmtpEnableSsl = smtpEnableSsl; SmtpUser = smtpUser; SmtpPassword = smtpPassword; SmtpFrom = smtpFrom; Workflows = new List<Workflow>(); Logger.Info(""); Logger.Info("Starting Wexflow Engine"); LoadSettings(); DbFolderName = DbType.ToString().ToLower(); switch (DbType) { case DbType.LiteDB: Database = new Db.LiteDB.Db(ConnectionString); break; case DbType.MongoDB: Database = new Db.MongoDB.Db(ConnectionString); break; case DbType.RavenDB: Database = new Db.RavenDB.Db(ConnectionString); break; case DbType.PostgreSQL: Database = new Db.PostgreSQL.Db(ConnectionString); break; case DbType.SQLServer: Database = new Db.SQLServer.Db(ConnectionString); break; case DbType.MySQL: Database = new Db.MySQL.Db(ConnectionString); break; case DbType.SQLite: Database = new Db.SQLite.Db(ConnectionString); break; case DbType.Firebird: Database = new Db.Firebird.Db(ConnectionString); break; case DbType.Oracle: Database = new Db.Oracle.Db(ConnectionString); break; case DbType.MariaDB: Database = new Db.MariaDB.Db(ConnectionString); break; } if (Database != null) { Database.Init(); } LoadGlobalVariables(); LoadWorkflows(); } /// <summary> /// Checks whether a cron expression is valid or not. /// </summary> /// <param name="expression">Cron expression</param> /// <returns></returns> public static bool IsCronExpressionValid(string expression) { bool res = CronExpression.IsValidExpression(expression); return res; } private void LoadSettings() { var xdoc = XDocument.Load(SettingsFile); WorkflowsFolder = GetWexflowSetting(xdoc, "workflowsFolder"); RecordsFolder = GetWexflowSetting(xdoc, "recordsFolder"); if (!Directory.Exists(RecordsFolder)) Directory.CreateDirectory(RecordsFolder); RecordsHotFolder = GetWexflowSetting(xdoc, "recordsHotFolder"); if (!Directory.Exists(RecordsHotFolder)) Directory.CreateDirectory(RecordsHotFolder); TempFolder = GetWexflowSetting(xdoc, "tempFolder"); TasksFolder = GetWexflowSetting(xdoc, "tasksFolder"); if (!Directory.Exists(TempFolder)) Directory.CreateDirectory(TempFolder); RecordsTempFolder = Path.Combine(TempFolder, "Records"); if (!Directory.Exists(RecordsTempFolder)) Directory.CreateDirectory(RecordsTempFolder); ApprovalFolder = GetWexflowSetting(xdoc, "approvalFolder"); XsdPath = GetWexflowSetting(xdoc, "xsd"); TasksNamesFile = GetWexflowSetting(xdoc, "tasksNamesFile"); TasksSettingsFile = GetWexflowSetting(xdoc, "tasksSettingsFile"); DbType = (DbType)Enum.Parse(typeof(DbType), GetWexflowSetting(xdoc, "dbType"), true); ConnectionString = GetWexflowSetting(xdoc, "connectionString"); GlobalVariablesFile = GetWexflowSetting(xdoc, "globalVariablesFile"); } private void LoadGlobalVariables() { List<Variable> variables = new List<Variable>(); XDocument xdoc = XDocument.Load(GlobalVariablesFile); foreach (var xvariable in xdoc.Descendants("Variable")) { Variable variable = new Variable { Key = xvariable.Attribute("name").Value, Value = xvariable.Attribute("value").Value }; variables.Add(variable); } GlobalVariables = variables.ToArray(); } private string GetWexflowSetting(XDocument xdoc, string name) { try { var xValue = xdoc.XPathSelectElement(string.Format("/Wexflow/Setting[@name='{0}']", name)).Attribute("value"); if (xValue == null) throw new Exception("Wexflow Setting Value attribute not found."); return xValue.Value; } catch (Exception e) { Logger.ErrorFormat("An error occured when reading Wexflow settings: Setting[@name='{0}']", e, name); return string.Empty; } } private void LoadWorkflows() { // Load workflows from db var workflows = Database.GetWorkflows(); foreach (var workflow in workflows) { var wf = LoadWorkflowFromDatabase(workflow); if (wf != null) { Workflows.Add(wf); } } } /// <summary> /// Stops cron jobs. /// </summary> /// <param name="workflowId">Workflow Id.</param> public void StopCronJobs(int workflowId) { string jobIdentity = "Workflow Job " + workflowId; var jobKey = new JobKey(jobIdentity); if (QuartzScheduler.CheckExists(jobKey).Result) { QuartzScheduler.DeleteJob(jobKey); } } private Workflow LoadWorkflowFromDatabase(Db.Workflow workflow) { try { var wf = new Workflow( this , 1 , new Dictionary<Guid, Workflow>() , workflow.GetDbId() , workflow.Xml , TempFolder , TasksFolder , ApprovalFolder , XsdPath , Database , GlobalVariables); Logger.InfoFormat("Workflow loaded: {0}", wf); return wf; } catch (Exception e) { Logger.ErrorFormat("An error occured while loading the workflow {0}. Please check the workflow configuration. Xml: {1}", e, workflow.GetDbId(), workflow.Xml); return null; } } /// <summary> /// Saves a workflow in the database. /// </summary> /// <param name="xml">XML of the workflow.</param> /// <param name="userId">User id.</param> /// <param name="userProfile">User profile.</param> /// <param name="schedule">Indicates whether to schedule the workflow or not.</param> /// <returns>Workflow db id.</returns> public string SaveWorkflow(string userId, UserProfile userProfile, string xml, bool schedule) { try { using (var xmlReader = XmlReader.Create(new StringReader(xml))) { XmlNamespaceManager xmlNamespaceManager = null; var xmlNameTable = xmlReader.NameTable; if (xmlNameTable != null) { xmlNamespaceManager = new XmlNamespaceManager(xmlNameTable); xmlNamespaceManager.AddNamespace("wf", "urn:wexflow-schema"); } var xdoc = XDocument.Parse(xml); var id = int.Parse(xdoc.XPathSelectElement("/wf:Workflow", xmlNamespaceManager).Attribute("id").Value); var workflow = Workflows.FirstOrDefault(w => w.Id == id); if (workflow == null) // insert { // check the workflow before to save it try { new Workflow( this , 1 , new Dictionary<Guid, Workflow>() , "-1" , xml , TempFolder , TasksFolder , ApprovalFolder , XsdPath , Database , GlobalVariables ); } catch (Exception e) { Logger.ErrorFormat("An error occured while saving the workflow {0}:", e, xml); return "-1"; } string dbId = Database.InsertWorkflow(new Db.Workflow { Xml = xml }); if (userProfile == UserProfile.Administrator) { InsertUserWorkflowRelation(userId, dbId); } var wfFromDb = Database.GetWorkflow(dbId); var newWorkflow = LoadWorkflowFromDatabase(wfFromDb); Logger.InfoFormat("New workflow {0} has been created. The workflow will be loaded.", newWorkflow.Name); Workflows.Add(newWorkflow); if (schedule) { ScheduleWorkflow(newWorkflow); } return dbId; } else // update { // check the workflow before to save it try { new Workflow( this , 1 , new Dictionary<Guid, Workflow>() , "-1" , xml , TempFolder , TasksFolder , ApprovalFolder , XsdPath , Database , GlobalVariables ); } catch (Exception e) { Logger.ErrorFormat("An error occured while saving the workflow {0}:", e, xml); return "-1"; } var workflowFromDb = Database.GetWorkflow(workflow.DbId); workflowFromDb.Xml = xml; Database.UpdateWorkflow(workflow.DbId, workflowFromDb); var changedWorkflow = Workflows.SingleOrDefault(wf => wf.DbId == workflowFromDb.GetDbId()); if (changedWorkflow != null) { changedWorkflow.Stop(SuperAdminUsername); StopCronJobs(changedWorkflow.Id); Workflows.Remove(changedWorkflow); Logger.InfoFormat("A change in the workflow {0} has been detected. The workflow will be reloaded.", changedWorkflow.Name); var updatedWorkflow = LoadWorkflowFromDatabase(workflowFromDb); Workflows.Add(updatedWorkflow); if (schedule) { ScheduleWorkflow(updatedWorkflow); } return changedWorkflow.DbId; } } } } catch (Exception e) { Logger.ErrorFormat("Error while saving a workflow: {0}", e.Message); } return "-1"; } /// <summary> /// Saves a workflow from its file /// </summary> /// <param name="userId">User Id</param> /// <param name="userProfile">User Profile</param> /// <param name="filePath">Workflow File Path</param> /// <param name="schedule">Indicates whether to schedule the workflow or not.</param> /// <returns>Workflow DB Id</returns> public string SaveWorkflowFromFile(string userId, UserProfile userProfile, string filePath, bool schedule) { try { var xml = File.ReadAllText(filePath); var id = SaveWorkflow(userId, userProfile, xml, schedule); var workflow = Workflows.First(w => w.DbId == id); workflow.FilePath = filePath; return id; } catch (IOException e) when ((e.HResult & 0x0000FFFF) == 32) { Logger.InfoFormat("There is a sharing violation for the file {0}.", filePath); } catch (Exception e) { Logger.ErrorFormat("Error while saving the workflow {0}", e, filePath); } return "-1"; } /// <summary> /// Deletes a workflow from the database. /// </summary> /// <param name="dbId">DB ID.</param> public void DeleteWorkflow(string dbId) { try { Database.DeleteWorkflow(dbId); Database.DeleteUserWorkflowRelationsByWorkflowId(dbId); var removedWorkflow = Workflows.SingleOrDefault(wf => wf.DbId == dbId); if (removedWorkflow != null) { Logger.InfoFormat("Workflow {0} is stopped and removed.", removedWorkflow.Name); removedWorkflow.Stop(SuperAdminUsername); StopCronJobs(removedWorkflow.Id); lock (Workflows) { Workflows.Remove(removedWorkflow); } if (EnableWorkflowsHotFolder) { if (!string.IsNullOrEmpty(removedWorkflow.FilePath) && File.Exists(removedWorkflow.FilePath)) { File.Delete(removedWorkflow.FilePath); Logger.InfoFormat("Workflow file {0} removed.", removedWorkflow.FilePath); } } } } catch (Exception e) { Logger.ErrorFormat("Error while deleting a workflow: {0}", e.Message); } } /// <summary> /// Deletes workflows from the database. /// </summary> /// <param name="dbIds">DB IDs</param> public bool DeleteWorkflows(string[] dbIds) { try { Database.DeleteWorkflows(dbIds); foreach (var dbId in dbIds) { var removedWorkflow = Workflows.SingleOrDefault(wf => wf.DbId == dbId); if (removedWorkflow != null) { Logger.InfoFormat("Workflow {0} is stopped and removed.", removedWorkflow.Name); removedWorkflow.Stop(SuperAdminUsername); StopCronJobs(removedWorkflow.Id); Workflows.Remove(removedWorkflow); Database.DeleteUserWorkflowRelationsByWorkflowId(removedWorkflow.DbId); if (EnableWorkflowsHotFolder) { if (!string.IsNullOrEmpty(removedWorkflow.FilePath) && File.Exists(removedWorkflow.FilePath)) { File.Delete(removedWorkflow.FilePath); Logger.InfoFormat("Workflow file {0} removed.", removedWorkflow.FilePath); } } } } return true; } catch (Exception e) { Logger.ErrorFormat("Error while deleting workflows: {0}", e.Message); return false; } } /// <summary> /// Inserts a user workflow relation in DB. /// </summary> /// <param name="userId">User DB ID.</param> /// <param name="workflowId">Workflow DB ID.</param> public void InsertUserWorkflowRelation(string userId, string workflowId) { try { Database.InsertUserWorkflowRelation(new UserWorkflow { UserId = userId, WorkflowId = workflowId }); } catch (Exception e) { Logger.ErrorFormat("Error while inserting user workflow relation: {0}", e.Message); } } /// <summary> /// Deletes user workflow relations. /// </summary> /// <param name="userId">User DB ID.</param> public void DeleteUserWorkflowRelations(string userId) { try { Database.DeleteUserWorkflowRelationsByUserId(userId); } catch (Exception e) { Logger.ErrorFormat("Error while deleting user workflow relations of user {0}: {1}", userId, e.Message); } } /// <summary> /// Returns user workflows. /// </summary> /// <param name="userId">User DB ID.</param> /// <returns>User worklofws.</returns> public Workflow[] GetUserWorkflows(string userId) { try { var userWorkflows = Database.GetUserWorkflows(userId).ToArray(); var workflows = Workflows.Where(w => userWorkflows.Contains(w.DbId)).ToArray(); return workflows; } catch (Exception e) { Logger.ErrorFormat("Error while retrieving user workflows of user {0}: {1}", userId, e.Message); return new Workflow[] { }; } } /// <summary> /// Checks whether a user have access to a workflow. /// </summary> /// <param name="userId">User id.</param> /// <param name="workflowId">Workflow db id.</param> /// <returns>true/false.</returns> public bool CheckUserWorkflow(string userId, string workflowId) { try { return Database.CheckUserWorkflow(userId, workflowId); } catch (Exception e) { Logger.ErrorFormat("Error while checking user workflows of user {0}: {1}", userId, e.Message); return false; } } /// <summary> /// Returns administrators search result. /// </summary> /// <param name="keyword">Keyword.</param> /// <param name="uo">User Order By.</param> /// <returns>Administrators search result.</returns> public User[] GetAdministrators(string keyword, UserOrderBy uo) { try { var admins = Database.GetAdministrators(keyword, uo); return admins.ToArray(); } catch (Exception e) { Logger.ErrorFormat("Error while retrieving administrators: {0}", e.Message); return new User[] { }; } } /// <summary> /// Returns non restricted users. /// </summary> /// <returns>Non restricted users.</returns> public User[] GetNonRestrictedUsers() { try { var users = Database.GetNonRestricedUsers(); return users.ToArray(); } catch (Exception e) { Logger.ErrorFormat("Error while retrieving administrators: {0}", e.Message); return new User[] { }; } } /// <summary> /// Starts Wexflow engine. /// </summary> public void Run() { if (EnableWorkflowsHotFolder) { Logger.InfoFormat("Loading workflows from hot folder {0} ...", WorkflowsFolder); var workflowFiles = Directory.GetFiles(WorkflowsFolder, "*.xml"); var admin = GetUser("admin"); foreach (var worlflowFile in workflowFiles) { SaveWorkflowFromFile(admin.GetDbId(), UserProfile.SuperAdministrator, worlflowFile, false); } Logger.InfoFormat("Loading workflows from hot folder {0} finished.", WorkflowsFolder); } Logger.InfoFormat("Scheduling {0} workflows...", Workflows.Count); foreach (Workflow workflow in Workflows) { ScheduleWorkflow(workflow); } if (!QuartzScheduler.IsStarted) { QuartzScheduler.Start().Wait(); } Logger.InfoFormat("Scheduling {0} workflows finished.", Workflows.Count); } private void ScheduleWorkflow(Workflow wf) { try { if (wf.IsEnabled) { if (wf.LaunchType == LaunchType.Startup) { wf.StartAsync(SuperAdminUsername); } else if (wf.LaunchType == LaunchType.Periodic) { IDictionary<string, object> map = new Dictionary<string, object> { { "workflow", wf } }; string jobIdentity = "Workflow Job " + wf.Id; IJobDetail jobDetail = JobBuilder.Create<WorkflowJob>() .WithIdentity(jobIdentity) .SetJobData(new JobDataMap(map)) .Build(); ITrigger trigger = TriggerBuilder.Create() .ForJob(jobDetail) .WithSimpleSchedule(x => x.WithInterval(wf.Period).RepeatForever()) .WithIdentity("Workflow Trigger " + wf.Id) .StartNow() .Build(); var jobKey = new JobKey(jobIdentity); if (QuartzScheduler.CheckExists(jobKey).Result) { QuartzScheduler.DeleteJob(jobKey); } QuartzScheduler.ScheduleJob(jobDetail, trigger).Wait(); } else if (wf.LaunchType == LaunchType.Cron) { IDictionary<string, object> map = new Dictionary<string, object> { { "workflow", wf } }; string jobIdentity = "Workflow Job " + wf.Id; IJobDetail jobDetail = JobBuilder.Create<WorkflowJob>() .WithIdentity(jobIdentity) .SetJobData(new JobDataMap(map)) .Build(); ITrigger trigger = TriggerBuilder.Create() .ForJob(jobDetail) .WithCronSchedule(wf.CronExpression) .WithIdentity("Workflow Trigger " + wf.Id) .StartNow() .Build(); var jobKey = new JobKey(jobIdentity); if (QuartzScheduler.CheckExists(jobKey).Result) { QuartzScheduler.DeleteJob(jobKey); } QuartzScheduler.ScheduleJob(jobDetail, trigger).Wait(); } } } catch (Exception e) { Logger.ErrorFormat("An error occured while scheduling the workflow {0}: ", e, wf); } } /// <summary> /// Stops Wexflow engine. /// </summary> /// <param name="stopQuartzScheduler">Tells if Quartz scheduler should be stopped or not.</param> /// <param name="clearStatusCountAndEntries">Indicates whether to clear statusCount and entries.</param> public void Stop(bool stopQuartzScheduler, bool clearStatusCountAndEntries) { if (stopQuartzScheduler) { QuartzScheduler.Shutdown().Wait(); } foreach (var workflow in Workflows) { var innerWorkflows = workflow.Jobs.Values.ToArray(); for (int i = innerWorkflows.Length - 1; i >= 0; i--) { var innerWorkflow = innerWorkflows[i]; if (innerWorkflow.IsRunning) { innerWorkflow.Stop(SuperAdminUsername); } } } Logger.Info("Workflows stopped."); if (clearStatusCountAndEntries) { Database.ClearStatusCount(); Database.ClearEntries(); Logger.Info("Status count and dashboard entries cleared."); } Database.Dispose(); Logger.Info("Database disposed."); } /// <summary> /// Gets a workflow. /// </summary> /// <param name="workflowId">Workflow Id.</param> /// <returns></returns> public Workflow GetWorkflow(int workflowId) { return Workflows.FirstOrDefault(wf => wf.Id == workflowId); } /// <summary> /// Starts a workflow. /// </summary> /// <param name="startedBy">Username of the user that started the workflow.</param> /// <param name="workflowId">Workflow Id.</param> public Guid StartWorkflow(string startedBy, int workflowId) { var wf = GetWorkflow(workflowId); if (wf == null) { Logger.ErrorFormat("Workflow {0} not found.", workflowId); } else { if (wf.IsEnabled) { var instanceId = wf.StartAsync(startedBy); return instanceId; } } return Guid.Empty; } /// <summary> /// Stops a workflow. /// </summary> /// <param name="workflowId">Workflow Id.</param> /// <param name="instanceId">Job instance Id.</param> /// <param name="stoppedBy">Username of the user who stopped the workflow.</param> /// <returns>Result.</returns> public bool StopWorkflow(int workflowId, Guid instanceId, string stoppedBy) { var wf = GetWorkflow(workflowId); if (wf == null) { Logger.ErrorFormat("Workflow {0} not found.", workflowId); } else { if (wf.IsEnabled) { var innerWf = wf.Jobs.Where(kvp => kvp.Key.Equals(instanceId)).Select(kvp => kvp.Value).FirstOrDefault(); if (innerWf == null) { Logger.ErrorFormat("Instance {0} not found.", instanceId); } else { return innerWf.Stop(stoppedBy); } } } return false; } /// <summary> /// Suspends a workflow. /// </summary> /// <param name="workflowId">Workflow Id.</param> /// <param name="instanceId">Job instance Id.</param> public bool SuspendWorkflow(int workflowId, Guid instanceId) { var wf = GetWorkflow(workflowId); if (wf == null) { Logger.ErrorFormat("Workflow {0} not found.", workflowId); } else { if (wf.IsEnabled) { var innerWf = wf.Jobs.Where(kvp => kvp.Key.Equals(instanceId)).Select(kvp => kvp.Value).FirstOrDefault(); if (innerWf == null) { Logger.ErrorFormat("Instance {0} not found.", instanceId); } else { return innerWf.Suspend(); } } } return false; } /// <summary> /// Resumes a workflow. /// </summary> /// <param name="workflowId">Workflow Id.</param> /// <param name="instanceId">Job instance Id.</param> public void ResumeWorkflow(int workflowId, Guid instanceId) { var wf = GetWorkflow(workflowId); if (wf == null) { Logger.ErrorFormat("Workflow {0} not found.", workflowId); } else { if (wf.IsEnabled) { var innerWf = wf.Jobs.Where(kvp => kvp.Key.Equals(instanceId)).Select(kvp => kvp.Value).FirstOrDefault(); if (innerWf == null) { Logger.ErrorFormat("Instance {0} not found.", instanceId); } else { innerWf.Resume(); } } } } /// <summary> /// Resumes a workflow. /// </summary> /// <param name="workflowId">Workflow Id.</param> /// <param name="instanceId">Job instance Id.</param> /// <param name="approvedBy">Username of the user who approved the workflow.</param> /// <returns>Result.</returns> public bool ApproveWorkflow(int workflowId, Guid instanceId, string approvedBy) { try { var wf = GetWorkflow(workflowId); if (wf == null) { Logger.ErrorFormat("Workflow {0} not found.", workflowId); return false; } if (wf.IsApproval) { if (wf.IsEnabled) { var innerWf = wf.Jobs.Where(kvp => kvp.Key.Equals(instanceId)).Select(kvp => kvp.Value).FirstOrDefault(); if (innerWf == null) { Logger.ErrorFormat("Instance {0} not found.", instanceId); } else { innerWf.Approve(approvedBy); return true; } } } return false; } catch (Exception e) { Logger.ErrorFormat("An error occured while approving the workflow {0}.", e, workflowId); return false; } } /// <summary> /// Resumes a workflow. /// </summary> /// <param name="workflowId">Workflow Id.</param> /// <param name="instanceId">Job instance Id.</param> /// <param name="rejectedBy">Username of the user who rejected the workflow.</param> /// <returns>Result.</returns> public bool RejectWorkflow(int workflowId, Guid instanceId, string rejectedBy) { try { var wf = GetWorkflow(workflowId); if (wf == null) { Logger.ErrorFormat("Workflow {0} not found.", workflowId); return false; } if (wf.IsApproval) { if (wf.IsEnabled) { var innerWf = wf.Jobs.Where(kvp => kvp.Key.Equals(instanceId)).Select(kvp => kvp.Value).FirstOrDefault(); if (innerWf == null) { Logger.ErrorFormat("Instance {0} not found.", instanceId); } else { innerWf.Reject(rejectedBy); return true; } } } return false; } catch (Exception e) { Logger.ErrorFormat("An error occured while approving the workflow {0}.", e, workflowId); return false; } } /// <summary> /// Returns status count /// </summary> /// <returns>Returns status count</returns> public StatusCount GetStatusCount() { return Database.GetStatusCount(); } /// <summary> /// Returns all the entries /// </summary> /// <returns>Returns all the entries</returns> public Entry[] GetEntries() { return Database.GetEntries().ToArray(); } /// <summary> /// Inserts a user. /// </summary> /// <param name="username">Username.</param> /// <param name="password">Password.</param> /// <param name="userProfile">User profile.</param> /// <param name="email">Email.</param> public void InsertUser(string username, string password, UserProfile userProfile, string email) { Database.InsertUser(new User { Username = username, Password = password, UserProfile = userProfile, Email = email }); } /// <summary> /// Updates a user. /// </summary> /// <param name="userId">User's id.</param> /// <param name="username">Username.</param> /// <param name="password">Password.</param> /// <param name="userProfile">User's profile.</param> /// <param name="email">User's email.</param> public void UpdateUser(string userId, string username, string password, UserProfile userProfile, string email) { var user = Database.GetUserById(userId); Database.UpdateUser(userId, new User { Username = username, Password = password, UserProfile = userProfile, Email = email, CreatedOn = user.CreatedOn }); } /// <summary> /// Updates username and email. /// </summary> /// <param name="userId">User Id.</param> /// <param name="username">New username.</param> /// <param name="email">New email.</param> /// <param name="up">User profile.</param> public void UpdateUsernameAndEmailAndUserProfile(string userId, string username, string email, int up) { Database.UpdateUsernameAndEmailAndUserProfile(userId, username, email, (UserProfile)up); } /// <summary> /// Deletes a user. /// </summary> /// <param name="username">Username.</param> /// <param name="password">Password.</param> public void DeleteUser(string username, string password) { var user = Database.GetUser(username); Database.DeleteUser(username, password); Database.DeleteUserWorkflowRelationsByUserId(user.GetDbId()); Database.DeleteApproversByUserId(user.GetDbId()); } /// <summary> /// Gets a user. /// </summary> /// <param name="username">Username.</param> /// <returns></returns> public User GetUser(string username) { return Database.GetUser(username); } /// <summary> /// Gets a user by Id. /// </summary> /// <param name="userId">User id.</param> /// <returns>User.</returns> public User GetUserById(string userId) { return Database.GetUserById(userId); } /// <summary> /// Gets a password. /// </summary> /// <param name="username">Username.</param> /// <returns></returns> public string GetPassword(string username) { return Database.GetPassword(username); } /// <summary> /// Returns all the users. /// </summary> /// <returns>All the users.</returns> public User[] GetUsers() { var q = Database.GetUsers(); if (q.Any()) { return q.ToArray(); } return new User[] { }; } /// <summary> /// Search for users. /// </summary> /// <returns>All the users.</returns> public User[] GetUsers(string keyword, UserOrderBy uo) { var q = Database.GetUsers(keyword, uo); if (q.Any()) { return q.ToArray(); } return new User[] { }; } /// <summary> /// Updates user password. /// </summary> /// <param name="username">Username.</param> /// <param name="password">Password.</param> public void UpdatePassword(string username, string password) { Database.UpdatePassword(username, password); } /// <summary> /// Returns all the entries. /// </summary> /// <returns>Returns all the entries</returns> public HistoryEntry[] GetHistoryEntries() { return Database.GetHistoryEntries().ToArray(); } /// <summary> /// Returns the entries by a keyword. /// </summary> /// <param name="keyword">Search keyword.</param> /// <returns>Returns all the entries</returns> public HistoryEntry[] GetHistoryEntries(string keyword) { return Database.GetHistoryEntries(keyword).ToArray(); } /// <summary> /// Returns the entries by a keyword. /// </summary> /// <param name="keyword">Search keyword.</param> /// <param name="page">Page number.</param> /// <param name="entriesCount">Number of entries.</param> /// <returns>Returns all the entries</returns> public HistoryEntry[] GetHistoryEntries(string keyword, int page, int entriesCount) { return Database.GetHistoryEntries(keyword, page, entriesCount).ToArray(); } /// <summary> /// Returns the entries by a keyword. /// </summary> /// <param name="keyword">Search keyword.</param> /// <param name="from">Date From.</param> /// <param name="to">Date To.</param> /// <param name="page">Page number.</param> /// <param name="entriesCount">Number of entries.</param> /// <param name="heo">EntryOrderBy</param> /// <returns>Returns all the entries</returns> public HistoryEntry[] GetHistoryEntries(string keyword, DateTime from, DateTime to, int page, int entriesCount, EntryOrderBy heo) { var col = Database.GetHistoryEntries(keyword, from, to, page, entriesCount, heo); if (!col.Any()) { return new HistoryEntry[] { }; } else { return col.ToArray(); } } /// <summary> /// Returns the entries by a keyword. /// </summary> /// <param name="keyword">Search keyword.</param> /// <param name="from">Date From.</param> /// <param name="to">Date To.</param> /// <param name="page">Page number.</param> /// <param name="entriesCount">Number of entries.</param> /// <param name="heo">EntryOrderBy</param> /// <returns>Returns all the entries</returns> public Entry[] GetEntries(string keyword, DateTime from, DateTime to, int page, int entriesCount, EntryOrderBy heo) { var col = Database.GetEntries(keyword, from, to, page, entriesCount, heo); if (!col.Any()) { return new Entry[] { }; } else { return col.ToArray(); } } /// <summary> /// Gets the number of history entries by search keyword. /// </summary> /// <param name="keyword">Search keyword.</param> /// <returns>The number of history entries by search keyword.</returns> public long GetHistoryEntriesCount(string keyword) { return Database.GetHistoryEntriesCount(keyword); } /// <summary> /// Gets the number of history entries by search keyword and date filter. /// </summary> /// <param name="keyword">Search keyword.</param> /// <param name="from">Date from.</param> /// <param name="to">Date to.</param> /// <returns></returns> public long GetHistoryEntriesCount(string keyword, DateTime from, DateTime to) { return Database.GetHistoryEntriesCount(keyword, from, to); } /// <summary> /// Gets the number of entries by search keyword and date filter. /// </summary> /// <param name="keyword">Search keyword.</param> /// <param name="from">Date from.</param> /// <param name="to">Date to.</param> /// <returns></returns> public long GetEntriesCount(string keyword, DateTime from, DateTime to) { return Database.GetEntriesCount(keyword, from, to); } /// <summary> /// Returns Status Date Min value. /// </summary> /// <returns>Status Date Min value.</returns> public DateTime GetHistoryEntryStatusDateMin() { return Database.GetHistoryEntryStatusDateMin(); } /// <summary> /// Returns Status Date Max value. /// </summary> /// <returns>Status Date Max value.</returns> public DateTime GetHistoryEntryStatusDateMax() { return Database.GetHistoryEntryStatusDateMax(); } /// <summary> /// Returns Status Date Min value. /// </summary> /// <returns>Status Date Min value.</returns> public DateTime GetEntryStatusDateMin() { return Database.GetEntryStatusDateMin(); } /// <summary> /// Returns Status Date Max value. /// </summary> /// <returns>Status Date Max value.</returns> public DateTime GetEntryStatusDateMax() { return Database.GetEntryStatusDateMax(); } /// <summary> /// Returns entry logs. /// </summary> /// <param name="entryId">Entry id.</param> /// <returns>Entry logs.</returns> public string GetEntryLogs(string entryId) { return Database.GetEntryLogs(entryId); } /// <summary> /// Returns entry logs. /// </summary> /// <param name="entryId">Entry id.</param> /// <returns>Entry logs.</returns> public string GetHistoryEntryLogs(string entryId) { return Database.GetHistoryEntryLogs(entryId); } /// <summary> /// Inserts a version in the database. /// </summary> /// <param name="version">Version.</param> /// <returns>Version id.</returns> public string SaveVersion(Db.Version version) { try { var versionId = Database.InsertVersion(version); return versionId; } catch (Exception e) { Logger.ErrorFormat("An error occured while saving the version {0}.", e, version.FilePath); return "-1"; } } /// <summary> /// Deletes versions. /// </summary> /// <param name="versionIds">Verions ids.</param> /// <returns>Result.</returns> public bool DeleteVersions(string[] versionIds) { try { Database.DeleteVersions(versionIds); return true; } catch (Exception e) { Logger.Error("An error occured while deleting versions.", e); return false; } } /// <summary> /// Checks if a directory is empty. /// </summary> /// <param name="path">Directory path.</param> /// <returns>Result.</returns> public bool IsDirectoryEmpty(string path) { return !Directory.EnumerateFileSystemEntries(path).Any(); } /// <summary> /// Checks if a path is a directory. /// </summary> /// <param name="path">Path.</param> /// <returns>Result.</returns> public bool IsDirectory(string path) { FileAttributes attr = File.GetAttributes(path); var isDir = attr.HasFlag(FileAttributes.Directory); return isDir; } /// <summary> /// Saves a record in the database. /// </summary> /// <param name="recordId">Record id.</param> /// <param name="record">Record.</param> /// <param name="versions">Version.</param> /// <returns></returns> public string SaveRecord(string recordId, Record record, List<Db.Version> versions) { try { if (recordId == "-1") // insert { var id = Database.InsertRecord(record); foreach (var version in versions) { var v = new Db.Version { RecordId = id, FilePath = version.FilePath, }; var versionId = Database.InsertVersion(v); // Move version file from temp folder to Records folder. if (version.FilePath.Contains(RecordsTempFolder)) { var fileName = Path.GetFileName(version.FilePath); var destDir = Path.Combine(RecordsFolder, DbFolderName, id, versionId); if (!Directory.Exists(destDir)) { Directory.CreateDirectory(destDir); } var destPath = Path.Combine(destDir, fileName); File.Move(version.FilePath, destPath); var parentDir = Path.GetDirectoryName(version.FilePath); if (IsDirectoryEmpty(parentDir)) { Directory.Delete(parentDir); var recordTempDir = Directory.GetParent(parentDir).FullName; if (IsDirectoryEmpty(recordTempDir)) { Directory.Delete(recordTempDir); } } // Update version. v.FilePath = destPath; Database.UpdateVersion(versionId, v); } } return id; } else // update { Database.UpdateRecord(recordId, record); var recordVersions = Database.GetVersions(recordId); List<string> versionsToDelete = new List<string>(); List<Db.Version> versionsToDeleteObjs = new List<Db.Version>(); foreach (var version in recordVersions) { if (!versions.Any(v => v.FilePath == version.FilePath)) { versionsToDelete.Add(version.GetDbId()); versionsToDeleteObjs.Add(version); } } Database.DeleteVersions(versionsToDelete.ToArray()); foreach (var version in versionsToDeleteObjs) { if (File.Exists(version.FilePath)) { File.Delete(version.FilePath); } var versionDir = Path.GetDirectoryName(version.FilePath); if (IsDirectoryEmpty(versionDir)) { Directory.Delete(versionDir); var recordDir = Directory.GetParent(versionDir).FullName; if (IsDirectoryEmpty(recordDir)) { Directory.Delete(recordDir); } } } foreach (var version in versions) { if (version.FilePath.Contains(RecordsTempFolder)) { var versionId = Database.InsertVersion(version); // Move version file from temp folder to Records folder. var fileName = Path.GetFileName(version.FilePath); var destDir = Path.Combine(RecordsFolder, DbFolderName, recordId, versionId); if (!Directory.Exists(destDir)) { Directory.CreateDirectory(destDir); } var destPath = Path.Combine(destDir, fileName); File.Move(version.FilePath, destPath); var parentDir = Path.GetDirectoryName(version.FilePath); if (IsDirectoryEmpty(parentDir)) { Directory.Delete(parentDir); var recordTempDir = Directory.GetParent(parentDir).FullName; if (IsDirectoryEmpty(recordTempDir)) { Directory.Delete(recordTempDir); } } // Update version. version.FilePath = destPath; Database.UpdateVersion(versionId, version); } } return recordId; } } catch (Exception e) { Logger.ErrorFormat("An error occured while saving the record {0}.", e, recordId); return "-1"; } } /// <summary> /// Saves a new record from a file. /// </summary> /// <param name="filePath">File path.</param> /// <param name="createdBy">Created by username.</param> /// <returns>Record Id.</returns> public string SaveRecordFromFile(string filePath, string createdBy) { var fileName = Path.GetFileName(filePath); var destDir = Path.Combine(RecordsTempFolder, DbFolderName, "-1", Guid.NewGuid().ToString()); if (!Directory.Exists(destDir)) { Directory.CreateDirectory(destDir); } var destPath = Path.Combine(destDir, fileName); File.Move(filePath, destPath); var parentDir = Path.GetDirectoryName(destPath); if (IsDirectoryEmpty(parentDir)) { Directory.Delete(parentDir); var recordTempDir = Directory.GetParent(parentDir).FullName; if (IsDirectoryEmpty(recordTempDir)) { Directory.Delete(recordTempDir); } } var admin = GetUser(createdBy); var record = new Record { Name = Path.GetFileNameWithoutExtension(fileName), CreatedBy = admin.GetDbId() }; var version = new Db.Version { FilePath = destPath }; List<Db.Version> versions = new List<Db.Version>() { version }; var recordId = SaveRecord("-1", record, versions); return recordId; } /// <summary> /// Deletes records. /// </summary> /// <param name="recordIds">Record ids.</param> /// <returns>Result.</returns> public bool DeleteRecords(string[] recordIds) { try { Database.DeleteRecords(recordIds); foreach (var recordId in recordIds) { var versions = Database.GetVersions(recordId); var versionIds = versions.Select(v => v.GetDbId()).ToArray(); Database.DeleteVersions(versionIds); foreach (var version in versions) { if (File.Exists(version.FilePath)) { File.Delete(version.FilePath); var versionDir = Path.GetDirectoryName(version.FilePath); if (IsDirectoryEmpty(versionDir)) { Directory.Delete(versionDir); var recordDir = Directory.GetParent(versionDir).FullName; if (IsDirectoryEmpty(recordDir)) { Directory.Delete(recordDir); } } } } Database.DeleteApproversByRecordId(recordId); } return true; } catch (Exception e) { Logger.Error("An error occured while deleting records.", e); return false; } } /// <summary> /// Returns records by keyword. /// </summary> /// <param name="keyword">Keyword.</param> /// <returns>Records by keyword</returns> public Record[] GetRecords(string keyword) { return Database.GetRecords(keyword).ToArray(); } /// <summary> /// Returns the records assigned to a user by keyword. /// </summary> /// <param name="createdBy">Created by user id.</param> /// <param name="assignedTo">Assigned to user id.</param> /// <param name="keyword">Keyword.</param> /// <returns>Records assigned to a user by keyword.</returns> public Record[] GetRecordsCreatedByOrAssignedTo(string createdBy, string assignedTo, string keyword) { return Database.GetRecordsCreatedByOrAssignedTo(createdBy, assignedTo, keyword).ToArray(); } /// <summary> /// Returns the records created by a user. /// </summary> /// <param name="createdBy">User id.</param> /// <returns>Records created by a user.</returns> public Record[] GetRecordsCreatedBy(string createdBy) { return Database.GetRecordsCreatedBy(createdBy).ToArray(); } /// <summary> /// returns record versions. /// </summary> /// <param name="recordId">Record id.</param> /// <returns>record versions.</returns> public Db.Version[] GetVersions(string recordId) { return Database.GetVersions(recordId).ToArray(); } /// <summary> /// returns the latest version of a record. /// </summary> /// <param name="recordId">Record id.</param> /// <returns>Latest version of a record.</returns> public Db.Version GetLatestVersion(string recordId) { return Database.GetLatestVersion(recordId); } /// <summary> /// Inserts a notification in the database. /// </summary> /// <param name="notification">Notification.</param> /// <returns>Notification id.</returns> public string InsertNotification(Notification notification) { try { var id = Database.InsertNotification(notification); return id; } catch (Exception e) { Logger.Error("An error occured while inserting a notification.", e); return "-1"; } } /// <summary> /// Marks notifications as read. /// </summary> /// <param name="notificationIds">Notification Ids.</param> public bool MarkNotificationsAsRead(string[] notificationIds) { try { Database.MarkNotificationsAsRead(notificationIds); return true; } catch (Exception e) { Logger.Error("An error occured while marking notifications as read.", e); return false; } } /// <summary> /// Marks notifications as unread. /// </summary> /// <param name="notificationIds">Notification Ids.</param> public bool MarkNotificationsAsUnread(string[] notificationIds) { try { Database.MarkNotificationsAsUnread(notificationIds); return true; } catch (Exception e) { Logger.Error("An error occured while marking notifications as read.", e); return false; } } /// <summary> /// Deletes notifications. /// </summary> /// <param name="notificationIds">Notification ids.</param> /// <returns>Result.</returns> public bool DeleteNotifications(string[] notificationIds) { try { Database.DeleteNotifications(notificationIds); return true; } catch (Exception e) { Logger.Error("An error occured while deleting notifications.", e); return false; } } /// <summary> /// Returns the notifications assigned to a user. /// </summary> /// <param name="assignedTo">User id.</param> /// <param name="keyword">Keyword.</param> /// <returns>Notifications assigned to a user.</returns> public Notification[] GetNotifications(string assignedTo, string keyword) { return Database.GetNotifications(assignedTo, keyword).ToArray(); } /// <summary> /// Indicates whether the user has notifications or not. /// </summary> /// <param name="assignedTo">Assigned to user id.</param> /// <returns></returns> public bool HasNotifications(string assignedTo) { return Database.HasNotifications(assignedTo); } /// <summary> /// Inserts an approver. /// </summary> /// <param name="approver">Approver.</param> /// <returns>Approver Id.</returns> public string InsertApprover(Approver approver) { try { var approverId = Database.InsertApprover(approver); return approverId; } catch (Exception e) { Logger.Error("An error occured while inserting an approver.", e); return "-1"; } } /// <summary> /// Inserts an approver. /// </summary> /// <param name="approverId">Approver Id.</param> /// <param name="approver">Approver.</param> /// <returns>Result.</returns> public bool UpdateApprover(string approverId, Approver approver) { try { Database.UpdateApprover(approverId, approver); return true; } catch (Exception e) { Logger.Error("An error occured while updating an approver.", e); return false; } } /// <summary> /// Deletes approved approvers of a record. /// </summary> /// <param name="recordId">Record Id.</param> /// <returns>Result.</returns> public bool DeleteApprovedApprovers(string recordId) { try { Database.DeleteApprovedApprovers(recordId); return true; } catch (Exception e) { Logger.ErrorFormat("An error occured while deleting approved approvers of the record {0}.", e, recordId); return false; } } /// <summary> /// Retrieves approvers by record Id. /// </summary> /// <param name="recordId">Record Id.</param> /// <returns>Approvers.</returns> public Approver[] GetApprovers(string recordId) { return Database.GetApprovers(recordId).ToArray(); } } }
35.84964
174
0.478584
[ "MIT" ]
janborup/Wexflow
src/net/Wexflow.Core/WexflowEngine.cs
69,622
C#
using System; using System.Collections.Generic; using System.Diagnostics; using CCLLC.Telemetry.DataContract; namespace CCLLC.Telemetry.Implementation { internal static class ExceptionConverter { public const int MaxParsedStackLength = 32768; internal static IExceptionDetails ConvertToExceptionDetails(Exception exception, IExceptionDetails parentExceptionDetails) { IExceptionDetails exceptionDetails = ExceptionDetails.CreateWithoutStackInfo(exception, parentExceptionDetails); var stack = new StackTrace(exception, true); var frames = stack.GetFrames(); Tuple<List<IStackFrame>, bool> sanitizedTuple = SanitizeStackFrame(frames, GetStackFrame, GetStackFrameLength); exceptionDetails.parsedStack = sanitizedTuple.Item1; exceptionDetails.hasFullStack = sanitizedTuple.Item2; return exceptionDetails; } /// <summary> /// Converts a System.Diagnostics.StackFrame to a Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryTypes.StackFrame. /// </summary> internal static IStackFrame GetStackFrame(System.Diagnostics.StackFrame stackFrame, int frameId) { var convertedStackFrame = new Telemetry.DataContract.StackFrame() { level = frameId }; var methodInfo = stackFrame.GetMethod(); string fullName; if (methodInfo.DeclaringType != null) { fullName = methodInfo.DeclaringType.FullName + "." + methodInfo.Name; } else { fullName = methodInfo.Name; } convertedStackFrame.method = fullName; convertedStackFrame.assembly = methodInfo.Module.Assembly.FullName; convertedStackFrame.fileName = stackFrame.GetFileName(); // 0 means it is unavailable int line = stackFrame.GetFileLineNumber(); if (line != 0) { convertedStackFrame.line = line; } return convertedStackFrame; } /// <summary> /// Gets the stack frame length for only the strings in the stack frame. /// </summary> internal static int GetStackFrameLength(IStackFrame stackFrame) { var stackFrameLength = (stackFrame.method == null ? 0 : stackFrame.method.Length) + (stackFrame.assembly == null ? 0 : stackFrame.assembly.Length) + (stackFrame.fileName == null ? 0 : stackFrame.fileName.Length); return stackFrameLength; } /// <summary> /// Sanitizing stack to 32k while selecting the initial and end stack trace. /// </summary> private static Tuple<List<TOutput>, bool> SanitizeStackFrame<TInput, TOutput>( IList<TInput> inputList, Func<TInput, int, TOutput> converter, Func<TOutput, int> lengthGetter) { List<TOutput> orderedStackTrace = new List<TOutput>(); bool hasFullStack = true; if (inputList != null && inputList.Count > 0) { int currentParsedStackLength = 0; for (int level = 0; level < inputList.Count; level++) { // Skip middle part of the stack int current = (level % 2 == 0) ? (inputList.Count - 1 - (level / 2)) : (level / 2); TOutput convertedStackFrame = converter(inputList[current], current); currentParsedStackLength += lengthGetter(convertedStackFrame); if (currentParsedStackLength > ExceptionConverter.MaxParsedStackLength) { hasFullStack = false; break; } orderedStackTrace.Insert(orderedStackTrace.Count / 2, convertedStackFrame); } } return new Tuple<List<TOutput>, bool>(orderedStackTrace, hasFullStack); } } }
39.771429
143
0.58501
[ "MIT" ]
ScottColson/CCLCC
Telemetry/Implementation/ExceptionConverter.cs
4,178
C#
using System; using UnityEngine; namespace AC { public class Singleton<T> : MonoBehaviour where T :MonoBehaviour { private static T _instance; public static T Instance { get { return _instance; } } private void Awake() { _instance = this as T; } } }
16.73913
68
0.480519
[ "Apache-2.0" ]
eighthoursleep/AirCraftCombat
Assets/Scripts/Utils/Singleton.cs
387
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Microsoft.EntityFrameworkCore; namespace test { public class NoBaseTypeContext : DbContext { public DbSet<CatTest1> Cats { get; set; } public DbSet<DogTest1> Dogs { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseInMemoryDatabase("test"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.CreateFluidNames(this); } } [NoBaseType] public class AnimalTest1 { [Key] public int Id {get;set;} } public class CatTest1: AnimalTest1 { public string CatName {get;set;} } public class DogTest1: AnimalTest1 { public string DogName {get;set;} } }
22.170732
85
0.641364
[ "MIT" ]
kolesnikovav/FluidNames
test/NoBaseTypeContext.cs
909
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Hangfire.HttpJob.Agent; using Hangfire.HttpJob.Agent.Attribute; using Microsoft.Extensions.Logging; namespace TestSqlserverHangfireAgent.Jobs { [HangJobUntilStop(true)] public class TestHangJob : JobAgent { private readonly ILogger<TestHangJob> _logger; public TestHangJob(ILogger<TestHangJob> logger) { _logger = logger; _logger.LogInformation($"Create {nameof(TestHangJob)} Instance Success"); } public override async Task OnStart(JobContext jobContext) { await Task.Delay(1000 * 10); _logger.LogWarning(nameof(OnStart) + (jobContext.Param ?? string.Empty)); } public override void OnStop(JobContext jobContext) { _logger.LogInformation("OnStop"); } public override void OnException(JobContext jobContext,Exception ex) { _logger.LogError(ex, nameof(OnException) + (ex.Data["Method"] ?? string.Empty)); } } }
28.075
92
0.646483
[ "MIT" ]
573000126/Hangfire.HttpJob
Test/TestSqlserverHangfireAgent/Jobs/TestHangJob.cs
1,125
C#
using System.Web.Http; using WebActivatorEx; using WebApplication2; using Swashbuckle.Application; [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")] namespace WebApplication2 { public class SwaggerConfig { public static void Register() { var thisAssembly = typeof(SwaggerConfig).Assembly; GlobalConfiguration.Configuration .EnableSwagger(c => { // By default, the service root url is inferred from the request used to access the docs. // However, there may be situations (e.g. proxy and load-balanced environments) where this does not // resolve correctly. You can workaround this by providing your own code to determine the root URL. // //c.RootUrl(req => GetRootUrlFromAppConfig()); // If schemes are not explicitly provided in a Swagger 2.0 document, then the scheme used to access // the docs is taken as the default. If your API supports multiple schemes and you want to be explicit // about them, you can use the "Schemes" option as shown below. // //c.Schemes(new[] { "http", "https" }); // Use "SingleApiVersion" to describe a single version API. Swagger 2.0 includes an "Info" object to // hold additional metadata for an API. Version and title are required but you can also provide // additional fields by chaining methods off SingleApiVersion. // c.SingleApiVersion("v1", "WebApplication2"); // If you want the output Swagger docs to be indented properly, enable the "PrettyPrint" option. // //c.PrettyPrint(); // If your API has multiple versions, use "MultipleApiVersions" instead of "SingleApiVersion". // In this case, you must provide a lambda that tells Swashbuckle which actions should be // included in the docs for a given API version. Like "SingleApiVersion", each call to "Version" // returns an "Info" builder so you can provide additional metadata per API version. // //c.MultipleApiVersions( // (apiDesc, targetApiVersion) => ResolveVersionSupportByRouteConstraint(apiDesc, targetApiVersion), // (vc) => // { // vc.Version("v2", "Swashbuckle Dummy API V2"); // vc.Version("v1", "Swashbuckle Dummy API V1"); // }); // You can use "BasicAuth", "ApiKey" or "OAuth2" options to describe security schemes for the API. // See https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md for more details. // NOTE: These only define the schemes and need to be coupled with a corresponding "security" property // at the document or operation level to indicate which schemes are required for an operation. To do this, // you'll need to implement a custom IDocumentFilter and/or IOperationFilter to set these properties // according to your specific authorization implementation // //c.BasicAuth("basic") // .Description("Basic HTTP Authentication"); // // NOTE: You must also configure 'EnableApiKeySupport' below in the SwaggerUI section //c.ApiKey("apiKey") // .Description("API Key Authentication") // .Name("apiKey") // .In("header"); // //c.OAuth2("oauth2") // .Description("OAuth2 Implicit Grant") // .Flow("implicit") // .AuthorizationUrl("http://petstore.swagger.wordnik.com/api/oauth/dialog") // //.TokenUrl("https://tempuri.org/token") // .Scopes(scopes => // { // scopes.Add("read", "Read access to protected resources"); // scopes.Add("write", "Write access to protected resources"); // }); // Set this flag to omit descriptions for any actions decorated with the Obsolete attribute //c.IgnoreObsoleteActions(); // Each operation be assigned one or more tags which are then used by consumers for various reasons. // For example, the swagger-ui groups operations according to the first tag of each operation. // By default, this will be controller name but you can use the "GroupActionsBy" option to // override with any value. // //c.GroupActionsBy(apiDesc => apiDesc.HttpMethod.ToString()); // You can also specify a custom sort order for groups (as defined by "GroupActionsBy") to dictate // the order in which operations are listed. For example, if the default grouping is in place // (controller name) and you specify a descending alphabetic sort order, then actions from a // ProductsController will be listed before those from a CustomersController. This is typically // used to customize the order of groupings in the swagger-ui. // //c.OrderActionGroupsBy(new DescendingAlphabeticComparer()); // If you annotate Controllers and API Types with // Xml comments (http://msdn.microsoft.com/en-us/library/b2s063f7(v=vs.110).aspx), you can incorporate // those comments into the generated docs and UI. You can enable this by providing the path to one or // more Xml comment files. // //c.IncludeXmlComments(GetXmlCommentsPath()); // Swashbuckle makes a best attempt at generating Swagger compliant JSON schemas for the various types // exposed in your API. However, there may be occasions when more control of the output is needed. // This is supported through the "MapType" and "SchemaFilter" options: // // Use the "MapType" option to override the Schema generation for a specific type. // It should be noted that the resulting Schema will be placed "inline" for any applicable Operations. // While Swagger 2.0 supports inline definitions for "all" Schema types, the swagger-ui tool does not. // It expects "complex" Schemas to be defined separately and referenced. For this reason, you should only // use the "MapType" option when the resulting Schema is a primitive or array type. If you need to alter a // complex Schema, use a Schema filter. // //c.MapType<ProductType>(() => new Schema { type = "integer", format = "int32" }); // If you want to post-modify "complex" Schemas once they've been generated, across the board or for a // specific type, you can wire up one or more Schema filters. // //c.SchemaFilter<ApplySchemaVendorExtensions>(); // In a Swagger 2.0 document, complex types are typically declared globally and referenced by unique // Schema Id. By default, Swashbuckle does NOT use the full type name in Schema Ids. In most cases, this // works well because it prevents the "implementation detail" of type namespaces from leaking into your // Swagger docs and UI. However, if you have multiple types in your API with the same class name, you'll // need to opt out of this behavior to avoid Schema Id conflicts. // //c.UseFullTypeNameInSchemaIds(); // Alternatively, you can provide your own custom strategy for inferring SchemaId's for // describing "complex" types in your API. // //c.SchemaId(t => t.FullName.Contains('`') ? t.FullName.Substring(0, t.FullName.IndexOf('`')) : t.FullName); // Set this flag to omit schema property descriptions for any type properties decorated with the // Obsolete attribute //c.IgnoreObsoleteProperties(); // In accordance with the built in JsonSerializer, Swashbuckle will, by default, describe enums as integers. // You can change the serializer behavior by configuring the StringToEnumConverter globally or for a given // enum type. Swashbuckle will honor this change out-of-the-box. However, if you use a different // approach to serialize enums as strings, you can also force Swashbuckle to describe them as strings. // //c.DescribeAllEnumsAsStrings(); // Similar to Schema filters, Swashbuckle also supports Operation and Document filters: // // Post-modify Operation descriptions once they've been generated by wiring up one or more // Operation filters. // //c.OperationFilter<AddDefaultResponse>(); // // If you've defined an OAuth2 flow as described above, you could use a custom filter // to inspect some attribute on each action and infer which (if any) OAuth2 scopes are required // to execute the operation // //c.OperationFilter<AssignOAuth2SecurityRequirements>(); // Post-modify the entire Swagger document by wiring up one or more Document filters. // This gives full control to modify the final SwaggerDocument. You should have a good understanding of // the Swagger 2.0 spec. - https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md // before using this option. // //c.DocumentFilter<ApplyDocumentVendorExtensions>(); // In contrast to WebApi, Swagger 2.0 does not include the query string component when mapping a URL // to an action. As a result, Swashbuckle will raise an exception if it encounters multiple actions // with the same path (sans query string) and HTTP method. You can workaround this by providing a // custom strategy to pick a winner or merge the descriptions for the purposes of the Swagger docs // //c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); // Wrap the default SwaggerGenerator with additional behavior (e.g. caching) or provide an // alternative implementation for ISwaggerProvider with the CustomProvider option. // //c.CustomProvider((defaultProvider) => new CachingSwaggerProvider(defaultProvider)); }) .EnableSwaggerUi(c => { // Use the "DocumentTitle" option to change the Document title. // Very helpful when you have multiple Swagger pages open, to tell them apart. // //c.DocumentTitle("My Swagger UI"); // Use the "InjectStylesheet" option to enrich the UI with one or more additional CSS stylesheets. // The file must be included in your project as an "Embedded Resource", and then the resource's // "Logical Name" is passed to the method as shown below. // //c.InjectStylesheet(containingAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testStyles1.css"); // Use the "InjectJavaScript" option to invoke one or more custom JavaScripts after the swagger-ui // has loaded. The file must be included in your project as an "Embedded Resource", and then the resource's // "Logical Name" is passed to the method as shown above. // //c.InjectJavaScript(thisAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testScript1.js"); // The swagger-ui renders boolean data types as a dropdown. By default, it provides "true" and "false" // strings as the possible choices. You can use this option to change these to something else, // for example 0 and 1. // //c.BooleanValues(new[] { "0", "1" }); // By default, swagger-ui will validate specs against swagger.io's online validator and display the result // in a badge at the bottom of the page. Use these options to set a different validator URL or to disable the // feature entirely. //c.SetValidatorUrl("http://localhost/validator"); //c.DisableValidator(); // Use this option to control how the Operation listing is displayed. // It can be set to "None" (default), "List" (shows operations for each resource), // or "Full" (fully expanded: shows operations and their details). // //c.DocExpansion(DocExpansion.List); // Specify which HTTP operations will have the 'Try it out!' option. An empty paramter list disables // it for all operations. // //c.SupportedSubmitMethods("GET", "HEAD"); // Use the CustomAsset option to provide your own version of assets used in the swagger-ui. // It's typically used to instruct Swashbuckle to return your version instead of the default // when a request is made for "index.html". As with all custom content, the file must be included // in your project as an "Embedded Resource", and then the resource's "Logical Name" is passed to // the method as shown below. // //c.CustomAsset("index", containingAssembly, "YourWebApiProject.SwaggerExtensions.index.html"); // If your API has multiple versions and you've applied the MultipleApiVersions setting // as described above, you can also enable a select box in the swagger-ui, that displays // a discovery URL for each version. This provides a convenient way for users to browse documentation // for different API versions. // //c.EnableDiscoveryUrlSelector(); // If your API supports the OAuth2 Implicit flow, and you've described it correctly, according to // the Swagger 2.0 specification, you can enable UI support as shown below. // //c.EnableOAuth2Support( // clientId: "test-client-id", // clientSecret: null, // realm: "test-realm", // appName: "Swagger UI" // //additionalQueryStringParams: new Dictionary<string, string>() { { "foo", "bar" } } //); // If your API supports ApiKey, you can override the default values. // "apiKeyIn" can either be "query" or "header" // //c.EnableApiKeySupport("apiKey", "header"); }); } } }
67.082031
133
0.533395
[ "MIT" ]
abenbrahim88/ficheperso
Application/WebApplication2/App_Start/SwaggerConfig.cs
17,173
C#
using System; using System.Diagnostics; using System.IO; namespace scg.Utils { public static class FileHelper { public static void OpenFile(string filename) { var pi = new ProcessStartInfo(Path.Combine(Environment.CurrentDirectory, filename)) { Arguments = Path.GetFileName(Path.Combine(Environment.CurrentDirectory, filename)), UseShellExecute = true, WorkingDirectory = Environment.CurrentDirectory, Verb = "OPEN" }; Process.Start(pi); } } }
27
99
0.592593
[ "MIT" ]
MadCowDevelopment/SoloChallengeGenerator
scg/Utils/FileHelper.cs
596
C#
namespace PIHidDotName_Csharp_Sample { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.BtnEnumerate = new System.Windows.Forms.Button(); this.CboDevices = new System.Windows.Forms.ComboBox(); this.LblSwitchPos = new System.Windows.Forms.Label(); this.listBox1 = new System.Windows.Forms.ListBox(); this.BtnUnitID = new System.Windows.Forms.Button(); this.TxtSetUnitID = new System.Windows.Forms.TextBox(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); this.BtnCallback = new System.Windows.Forms.Button(); this.LblUnitID = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.BtnBL = new System.Windows.Forms.Button(); this.label5 = new System.Windows.Forms.Label(); this.BtnPID2 = new System.Windows.Forms.Button(); this.BtnPID1 = new System.Windows.Forms.Button(); this.label7 = new System.Windows.Forms.Label(); this.BtnKBreflect = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.BtnJoyreflect = new System.Windows.Forms.Button(); this.textBox2 = new System.Windows.Forms.TextBox(); this.textBox3 = new System.Windows.Forms.TextBox(); this.textBox4 = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.textBox5 = new System.Windows.Forms.TextBox(); this.textBox6 = new System.Windows.Forms.TextBox(); this.label12 = new System.Windows.Forms.Label(); this.BtnTimeStamp = new System.Windows.Forms.Button(); this.label19 = new System.Windows.Forms.Label(); this.label20 = new System.Windows.Forms.Label(); this.label21 = new System.Windows.Forms.Label(); this.BtnDescriptor = new System.Windows.Forms.Button(); this.listBox2 = new System.Windows.Forms.ListBox(); this.label23 = new System.Windows.Forms.Label(); this.BtnSaveBL = new System.Windows.Forms.Button(); this.BtnBLToggle = new System.Windows.Forms.Button(); this.BtnTimeStampOn = new System.Windows.Forms.Button(); this.label13 = new System.Windows.Forms.Label(); this.ChkRedOnOff = new System.Windows.Forms.CheckBox(); this.ChkGreenOnOff = new System.Windows.Forms.CheckBox(); this.BtnSetFlash = new System.Windows.Forms.Button(); this.TxtFlashFreq = new System.Windows.Forms.TextBox(); this.ChkFRedLED = new System.Windows.Forms.CheckBox(); this.ChkFGreenLED = new System.Windows.Forms.CheckBox(); this.ChkRedLED = new System.Windows.Forms.CheckBox(); this.ChkGreenLED = new System.Windows.Forms.CheckBox(); this.ChkFlash = new System.Windows.Forms.CheckBox(); this.ChkBLOnOff = new System.Windows.Forms.CheckBox(); this.label6 = new System.Windows.Forms.Label(); this.label17 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); this.BtnGetDataNow = new System.Windows.Forms.Button(); this.Label18 = new System.Windows.Forms.Label(); this.label15 = new System.Windows.Forms.Label(); this.Label16 = new System.Windows.Forms.Label(); this.label27 = new System.Windows.Forms.Label(); this.textBox13 = new System.Windows.Forms.TextBox(); this.label26 = new System.Windows.Forms.Label(); this.textBox12 = new System.Windows.Forms.TextBox(); this.label22 = new System.Windows.Forms.Label(); this.textBox7 = new System.Windows.Forms.TextBox(); this.textBox8 = new System.Windows.Forms.TextBox(); this.textBox9 = new System.Windows.Forms.TextBox(); this.label24 = new System.Windows.Forms.Label(); this.label25 = new System.Windows.Forms.Label(); this.label28 = new System.Windows.Forms.Label(); this.textBox10 = new System.Windows.Forms.TextBox(); this.label29 = new System.Windows.Forms.Label(); this.label30 = new System.Windows.Forms.Label(); this.textBox11 = new System.Windows.Forms.TextBox(); this.label31 = new System.Windows.Forms.Label(); this.label32 = new System.Windows.Forms.Label(); this.label33 = new System.Windows.Forms.Label(); this.label34 = new System.Windows.Forms.Label(); this.textBox14 = new System.Windows.Forms.TextBox(); this.textBox15 = new System.Windows.Forms.TextBox(); this.textBox16 = new System.Windows.Forms.TextBox(); this.BtnMousereflect = new System.Windows.Forms.Button(); this.BtnEnable = new System.Windows.Forms.Button(); this.BtnDisable = new System.Windows.Forms.Button(); this.label35 = new System.Windows.Forms.Label(); this.BtnIncIntesity = new System.Windows.Forms.Button(); this.textBox17 = new System.Windows.Forms.TextBox(); this.label36 = new System.Windows.Forms.Label(); this.label37 = new System.Windows.Forms.Label(); this.label38 = new System.Windows.Forms.Label(); this.textBox18 = new System.Windows.Forms.TextBox(); this.CboColor = new System.Windows.Forms.ComboBox(); this.CboBL = new System.Windows.Forms.ComboBox(); this.LblSpecialKeys = new System.Windows.Forms.Label(); this.LblButtons = new System.Windows.Forms.Label(); this.LblJoyX = new System.Windows.Forms.Label(); this.LblJoyY = new System.Windows.Forms.Label(); this.LblJoyZ = new System.Windows.Forms.Label(); this.LblPassFail = new System.Windows.Forms.Label(); this.BtnCheckDongle = new System.Windows.Forms.Button(); this.BtnSetDongle = new System.Windows.Forms.Button(); this.label44 = new System.Windows.Forms.Label(); this.label41 = new System.Windows.Forms.Label(); this.LblVersion = new System.Windows.Forms.Label(); this.TxtVersion = new System.Windows.Forms.TextBox(); this.BtnVersion = new System.Windows.Forms.Button(); this.BtnCustom = new System.Windows.Forms.Button(); this.statusStrip1.SuspendLayout(); this.SuspendLayout(); // // BtnEnumerate // this.BtnEnumerate.Location = new System.Drawing.Point(9, 31); this.BtnEnumerate.Margin = new System.Windows.Forms.Padding(2); this.BtnEnumerate.Name = "BtnEnumerate"; this.BtnEnumerate.Size = new System.Drawing.Size(98, 22); this.BtnEnumerate.TabIndex = 0; this.BtnEnumerate.Text = "Enumerate"; this.BtnEnumerate.UseVisualStyleBackColor = true; this.BtnEnumerate.Click += new System.EventHandler(this.BtnEnumerate_Click); // // CboDevices // this.CboDevices.FormattingEnabled = true; this.CboDevices.Location = new System.Drawing.Point(116, 30); this.CboDevices.Margin = new System.Windows.Forms.Padding(2); this.CboDevices.Name = "CboDevices"; this.CboDevices.Size = new System.Drawing.Size(376, 21); this.CboDevices.TabIndex = 1; this.CboDevices.SelectedIndexChanged += new System.EventHandler(this.CboDevices_SelectedIndexChanged); // // LblSwitchPos // this.LblSwitchPos.Location = new System.Drawing.Point(11, 195); this.LblSwitchPos.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.LblSwitchPos.Name = "LblSwitchPos"; this.LblSwitchPos.Size = new System.Drawing.Size(104, 14); this.LblSwitchPos.TabIndex = 5; this.LblSwitchPos.Text = "Switch Position"; // // listBox1 // this.listBox1.FormattingEnabled = true; this.listBox1.HorizontalScrollbar = true; this.listBox1.Location = new System.Drawing.Point(9, 118); this.listBox1.Margin = new System.Windows.Forms.Padding(2); this.listBox1.Name = "listBox1"; this.listBox1.Size = new System.Drawing.Size(483, 69); this.listBox1.TabIndex = 6; // // BtnUnitID // this.BtnUnitID.Location = new System.Drawing.Point(9, 319); this.BtnUnitID.Margin = new System.Windows.Forms.Padding(2); this.BtnUnitID.Name = "BtnUnitID"; this.BtnUnitID.Size = new System.Drawing.Size(92, 22); this.BtnUnitID.TabIndex = 7; this.BtnUnitID.Text = "Write Unit ID"; this.BtnUnitID.UseVisualStyleBackColor = true; this.BtnUnitID.Click += new System.EventHandler(this.BtnUnitID_Click); // // TxtSetUnitID // this.TxtSetUnitID.Location = new System.Drawing.Point(115, 319); this.TxtSetUnitID.Margin = new System.Windows.Forms.Padding(2); this.TxtSetUnitID.Name = "TxtSetUnitID"; this.TxtSetUnitID.Size = new System.Drawing.Size(30, 20); this.TxtSetUnitID.TabIndex = 8; this.TxtSetUnitID.Text = "1"; // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripStatusLabel1}); this.statusStrip1.Location = new System.Drawing.Point(0, 639); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Padding = new System.Windows.Forms.Padding(1, 0, 10, 0); this.statusStrip1.Size = new System.Drawing.Size(965, 22); this.statusStrip1.TabIndex = 9; this.statusStrip1.Text = "statusStrip1"; // // toolStripStatusLabel1 // this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; this.toolStripStatusLabel1.Size = new System.Drawing.Size(118, 17); this.toolStripStatusLabel1.Text = "toolStripStatusLabel1"; // // BtnCallback // this.BtnCallback.Location = new System.Drawing.Point(9, 92); this.BtnCallback.Margin = new System.Windows.Forms.Padding(2); this.BtnCallback.Name = "BtnCallback"; this.BtnCallback.Size = new System.Drawing.Size(122, 22); this.BtnCallback.TabIndex = 10; this.BtnCallback.Text = "Setup for Callback"; this.BtnCallback.UseVisualStyleBackColor = true; this.BtnCallback.Click += new System.EventHandler(this.BtnCallback_Click); // // LblUnitID // this.LblUnitID.AutoSize = true; this.LblUnitID.Location = new System.Drawing.Point(158, 323); this.LblUnitID.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.LblUnitID.Name = "LblUnitID"; this.LblUnitID.Size = new System.Drawing.Size(38, 13); this.LblUnitID.TabIndex = 12; this.LblUnitID.Text = "unit ID"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(11, 9); this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(71, 13); this.label1.TabIndex = 16; this.label1.Text = "1. Do this first"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(11, 69); this.label2.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(270, 13); this.label2.TabIndex = 17; this.label2.Text = "2. Set for data callback and read data (displayed in hex)"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(11, 238); this.label3.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(76, 13); this.label3.TabIndex = 18; this.label3.Text = "3. LED Control"; // // button1 // this.button1.Location = new System.Drawing.Point(399, 92); this.button1.Margin = new System.Windows.Forms.Padding(2); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(93, 22); this.button1.TabIndex = 21; this.button1.Text = "Clear Listbox"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // BtnBL // this.BtnBL.Location = new System.Drawing.Point(203, 448); this.BtnBL.Margin = new System.Windows.Forms.Padding(2); this.BtnBL.Name = "BtnBL"; this.BtnBL.Size = new System.Drawing.Size(92, 22); this.BtnBL.TabIndex = 22; this.BtnBL.Text = "Set Intensity"; this.BtnBL.UseVisualStyleBackColor = true; this.BtnBL.Click += new System.EventHandler(this.BtnBL_Click); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(510, 552); this.label5.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(270, 13); this.label5.TabIndex = 23; this.label5.Text = "14. Change PID-must re-enumerate after changing PIDs"; // // BtnPID2 // this.BtnPID2.Location = new System.Drawing.Point(522, 598); this.BtnPID2.Margin = new System.Windows.Forms.Padding(2); this.BtnPID2.Name = "BtnPID2"; this.BtnPID2.Size = new System.Drawing.Size(99, 22); this.BtnPID2.TabIndex = 24; this.BtnPID2.Text = "To PID #2"; this.BtnPID2.UseVisualStyleBackColor = true; this.BtnPID2.Click += new System.EventHandler(this.BtnPID2_Click); // // BtnPID1 // this.BtnPID1.Location = new System.Drawing.Point(522, 573); this.BtnPID1.Margin = new System.Windows.Forms.Padding(2); this.BtnPID1.Name = "BtnPID1"; this.BtnPID1.Size = new System.Drawing.Size(99, 22); this.BtnPID1.TabIndex = 26; this.BtnPID1.Text = "To PID #1"; this.BtnPID1.UseVisualStyleBackColor = true; this.BtnPID1.Click += new System.EventHandler(this.BtnPID1_Click); // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(508, 7); this.label7.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(67, 13); this.label7.TabIndex = 30; this.label7.Text = "9. Reflectors"; // // BtnKBreflect // this.BtnKBreflect.Location = new System.Drawing.Point(523, 24); this.BtnKBreflect.Margin = new System.Windows.Forms.Padding(2); this.BtnKBreflect.Name = "BtnKBreflect"; this.BtnKBreflect.Size = new System.Drawing.Size(122, 22); this.BtnKBreflect.TabIndex = 31; this.BtnKBreflect.Text = "Keyboard Reflector"; this.BtnKBreflect.UseVisualStyleBackColor = true; this.BtnKBreflect.Click += new System.EventHandler(this.BtnKBreflect_Click); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(649, 25); this.textBox1.Margin = new System.Windows.Forms.Padding(2); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(191, 20); this.textBox1.TabIndex = 32; // // BtnJoyreflect // this.BtnJoyreflect.Location = new System.Drawing.Point(523, 64); this.BtnJoyreflect.Margin = new System.Windows.Forms.Padding(2); this.BtnJoyreflect.Name = "BtnJoyreflect"; this.BtnJoyreflect.Size = new System.Drawing.Size(122, 22); this.BtnJoyreflect.TabIndex = 33; this.BtnJoyreflect.Text = "Joystick Reflector*"; this.BtnJoyreflect.UseVisualStyleBackColor = true; this.BtnJoyreflect.Click += new System.EventHandler(this.BtnJoyreflect_Click); // // textBox2 // this.textBox2.Location = new System.Drawing.Point(666, 65); this.textBox2.Margin = new System.Windows.Forms.Padding(2); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(41, 20); this.textBox2.TabIndex = 34; this.textBox2.Text = "0"; // // textBox3 // this.textBox3.Location = new System.Drawing.Point(730, 64); this.textBox3.Margin = new System.Windows.Forms.Padding(2); this.textBox3.Name = "textBox3"; this.textBox3.Size = new System.Drawing.Size(41, 20); this.textBox3.TabIndex = 35; this.textBox3.Text = "0"; // // textBox4 // this.textBox4.Location = new System.Drawing.Point(801, 64); this.textBox4.Margin = new System.Windows.Forms.Padding(2); this.textBox4.Name = "textBox4"; this.textBox4.Size = new System.Drawing.Size(41, 20); this.textBox4.TabIndex = 36; this.textBox4.Text = "0"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(649, 67); this.label8.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(17, 13); this.label8.TabIndex = 37; this.label8.Text = "X:"; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(710, 67); this.label9.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(17, 13); this.label9.TabIndex = 38; this.label9.Text = "Y:"; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(780, 67); this.label10.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(17, 13); this.label10.TabIndex = 39; this.label10.Text = "Z:"; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(616, 118); this.label11.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(46, 13); this.label11.TabIndex = 40; this.label11.Text = "Buttons:"; // // textBox5 // this.textBox5.Location = new System.Drawing.Point(666, 113); this.textBox5.Margin = new System.Windows.Forms.Padding(2); this.textBox5.Name = "textBox5"; this.textBox5.Size = new System.Drawing.Size(41, 20); this.textBox5.TabIndex = 41; this.textBox5.Text = "0"; // // textBox6 // this.textBox6.Location = new System.Drawing.Point(666, 137); this.textBox6.Margin = new System.Windows.Forms.Padding(2); this.textBox6.Name = "textBox6"; this.textBox6.Size = new System.Drawing.Size(41, 20); this.textBox6.TabIndex = 42; this.textBox6.Text = "8"; // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(635, 139); this.label12.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(27, 13); this.label12.TabIndex = 43; this.label12.Text = "Hat:"; // // BtnTimeStamp // this.BtnTimeStamp.Location = new System.Drawing.Point(9, 528); this.BtnTimeStamp.Margin = new System.Windows.Forms.Padding(2); this.BtnTimeStamp.Name = "BtnTimeStamp"; this.BtnTimeStamp.Size = new System.Drawing.Size(92, 22); this.BtnTimeStamp.TabIndex = 58; this.BtnTimeStamp.Text = "Time Stamp Off"; this.BtnTimeStamp.UseVisualStyleBackColor = true; this.BtnTimeStamp.Click += new System.EventHandler(this.BtnTimeStamp_Click); // // label19 // this.label19.AutoSize = true; this.label19.Location = new System.Drawing.Point(225, 528); this.label19.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(69, 13); this.label19.TabIndex = 59; this.label19.Text = "absolute time"; // // label20 // this.label20.AutoSize = true; this.label20.Location = new System.Drawing.Point(225, 547); this.label20.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label20.Name = "label20"; this.label20.Size = new System.Drawing.Size(52, 13); this.label20.TabIndex = 60; this.label20.Text = "delta time"; // // label21 // this.label21.AutoSize = true; this.label21.Location = new System.Drawing.Point(508, 273); this.label21.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label21.Name = "label21"; this.label21.Size = new System.Drawing.Size(73, 13); this.label21.TabIndex = 61; this.label21.Text = "10. Descriptor"; // // BtnDescriptor // this.BtnDescriptor.Location = new System.Drawing.Point(523, 289); this.BtnDescriptor.Margin = new System.Windows.Forms.Padding(2); this.BtnDescriptor.Name = "BtnDescriptor"; this.BtnDescriptor.Size = new System.Drawing.Size(98, 22); this.BtnDescriptor.TabIndex = 62; this.BtnDescriptor.Text = "Descriptor"; this.BtnDescriptor.UseVisualStyleBackColor = true; this.BtnDescriptor.Click += new System.EventHandler(this.BtnDescriptor_Click); // // listBox2 // this.listBox2.FormattingEnabled = true; this.listBox2.Location = new System.Drawing.Point(631, 290); this.listBox2.Margin = new System.Windows.Forms.Padding(2); this.listBox2.Name = "listBox2"; this.listBox2.Size = new System.Drawing.Size(232, 82); this.listBox2.TabIndex = 63; // // label23 // this.label23.AutoSize = true; this.label23.Location = new System.Drawing.Point(10, 503); this.label23.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label23.Name = "label23"; this.label23.Size = new System.Drawing.Size(111, 13); this.label23.TabIndex = 67; this.label23.Text = "7. Enable Time Stamp"; // // BtnSaveBL // this.BtnSaveBL.Location = new System.Drawing.Point(336, 474); this.BtnSaveBL.Margin = new System.Windows.Forms.Padding(2); this.BtnSaveBL.Name = "BtnSaveBL"; this.BtnSaveBL.Size = new System.Drawing.Size(92, 22); this.BtnSaveBL.TabIndex = 68; this.BtnSaveBL.Text = "Save Backlights"; this.BtnSaveBL.UseVisualStyleBackColor = true; this.BtnSaveBL.Click += new System.EventHandler(this.BtnSaveBL_Click); // // BtnBLToggle // this.BtnBLToggle.Location = new System.Drawing.Point(142, 448); this.BtnBLToggle.Margin = new System.Windows.Forms.Padding(2); this.BtnBLToggle.Name = "BtnBLToggle"; this.BtnBLToggle.Size = new System.Drawing.Size(54, 22); this.BtnBLToggle.TabIndex = 70; this.BtnBLToggle.Text = "Toggle"; this.BtnBLToggle.UseVisualStyleBackColor = true; this.BtnBLToggle.Click += new System.EventHandler(this.BtnBLToggle_Click); // // BtnTimeStampOn // this.BtnTimeStampOn.Location = new System.Drawing.Point(115, 528); this.BtnTimeStampOn.Margin = new System.Windows.Forms.Padding(2); this.BtnTimeStampOn.Name = "BtnTimeStampOn"; this.BtnTimeStampOn.Size = new System.Drawing.Size(92, 22); this.BtnTimeStampOn.TabIndex = 71; this.BtnTimeStampOn.Text = "Time Stamp On"; this.BtnTimeStampOn.UseVisualStyleBackColor = true; this.BtnTimeStampOn.Click += new System.EventHandler(this.BtnTimeStampOn_Click); // // label13 // this.label13.AutoSize = true; this.label13.Location = new System.Drawing.Point(11, 294); this.label13.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(80, 13); this.label13.TabIndex = 87; this.label13.Text = "4. Write Unit ID"; // // ChkRedOnOff // this.ChkRedOnOff.AutoSize = true; this.ChkRedOnOff.Location = new System.Drawing.Point(371, 380); this.ChkRedOnOff.Margin = new System.Windows.Forms.Padding(2); this.ChkRedOnOff.Name = "ChkRedOnOff"; this.ChkRedOnOff.Size = new System.Drawing.Size(110, 17); this.ChkRedOnOff.TabIndex = 89; this.ChkRedOnOff.Text = "All Bank 2 On/Off"; this.ChkRedOnOff.UseVisualStyleBackColor = true; this.ChkRedOnOff.CheckedChanged += new System.EventHandler(this.ChkRedOnOff_CheckedChanged); // // ChkGreenOnOff // this.ChkGreenOnOff.AutoSize = true; this.ChkGreenOnOff.Location = new System.Drawing.Point(257, 380); this.ChkGreenOnOff.Margin = new System.Windows.Forms.Padding(2); this.ChkGreenOnOff.Name = "ChkGreenOnOff"; this.ChkGreenOnOff.Size = new System.Drawing.Size(110, 17); this.ChkGreenOnOff.TabIndex = 88; this.ChkGreenOnOff.Text = "All Bank 1 On/Off"; this.ChkGreenOnOff.UseVisualStyleBackColor = true; this.ChkGreenOnOff.CheckedChanged += new System.EventHandler(this.ChkGreenOnOff_CheckedChanged); // // BtnSetFlash // this.BtnSetFlash.Location = new System.Drawing.Point(9, 448); this.BtnSetFlash.Margin = new System.Windows.Forms.Padding(2); this.BtnSetFlash.Name = "BtnSetFlash"; this.BtnSetFlash.Size = new System.Drawing.Size(92, 22); this.BtnSetFlash.TabIndex = 91; this.BtnSetFlash.Text = "Set Flash Freq"; this.BtnSetFlash.UseVisualStyleBackColor = true; this.BtnSetFlash.Click += new System.EventHandler(this.BtnSetFlash_Click); // // TxtFlashFreq // this.TxtFlashFreq.Location = new System.Drawing.Point(105, 447); this.TxtFlashFreq.Margin = new System.Windows.Forms.Padding(2); this.TxtFlashFreq.Name = "TxtFlashFreq"; this.TxtFlashFreq.Size = new System.Drawing.Size(30, 20); this.TxtFlashFreq.TabIndex = 90; this.TxtFlashFreq.Text = "10"; // // ChkFRedLED // this.ChkFRedLED.AutoSize = true; this.ChkFRedLED.Location = new System.Drawing.Point(224, 263); this.ChkFRedLED.Margin = new System.Windows.Forms.Padding(2); this.ChkFRedLED.Name = "ChkFRedLED"; this.ChkFRedLED.Size = new System.Drawing.Size(98, 17); this.ChkFRedLED.TabIndex = 102; this.ChkFRedLED.Text = "Flash Red LED"; this.ChkFRedLED.UseVisualStyleBackColor = true; this.ChkFRedLED.CheckedChanged += new System.EventHandler(this.ChkFRedLED_CheckedChanged); // // ChkFGreenLED // this.ChkFGreenLED.AutoSize = true; this.ChkFGreenLED.Location = new System.Drawing.Point(137, 263); this.ChkFGreenLED.Margin = new System.Windows.Forms.Padding(2); this.ChkFGreenLED.Name = "ChkFGreenLED"; this.ChkFGreenLED.Size = new System.Drawing.Size(83, 17); this.ChkFGreenLED.TabIndex = 101; this.ChkFGreenLED.Text = "Flash Green"; this.ChkFGreenLED.UseVisualStyleBackColor = true; this.ChkFGreenLED.CheckedChanged += new System.EventHandler(this.ChkFGreenLED_CheckedChanged); // // ChkRedLED // this.ChkRedLED.AutoSize = true; this.ChkRedLED.Location = new System.Drawing.Point(79, 263); this.ChkRedLED.Margin = new System.Windows.Forms.Padding(2); this.ChkRedLED.Name = "ChkRedLED"; this.ChkRedLED.Size = new System.Drawing.Size(46, 17); this.ChkRedLED.TabIndex = 100; this.ChkRedLED.Text = "Red"; this.ChkRedLED.UseVisualStyleBackColor = true; this.ChkRedLED.CheckedChanged += new System.EventHandler(this.ChkRedLED_CheckedChanged); // // ChkGreenLED // this.ChkGreenLED.AutoSize = true; this.ChkGreenLED.Location = new System.Drawing.Point(12, 263); this.ChkGreenLED.Margin = new System.Windows.Forms.Padding(2); this.ChkGreenLED.Name = "ChkGreenLED"; this.ChkGreenLED.Size = new System.Drawing.Size(55, 17); this.ChkGreenLED.TabIndex = 99; this.ChkGreenLED.Text = "Green"; this.ChkGreenLED.UseVisualStyleBackColor = true; this.ChkGreenLED.CheckedChanged += new System.EventHandler(this.ChkGreenLED_CheckedChanged); // // ChkFlash // this.ChkFlash.AutoSize = true; this.ChkFlash.Location = new System.Drawing.Point(200, 380); this.ChkFlash.Margin = new System.Windows.Forms.Padding(2); this.ChkFlash.Name = "ChkFlash"; this.ChkFlash.Size = new System.Drawing.Size(51, 17); this.ChkFlash.TabIndex = 118; this.ChkFlash.Text = "Flash"; this.ChkFlash.UseVisualStyleBackColor = true; this.ChkFlash.CheckedChanged += new System.EventHandler(this.ChkFlash_CheckedChanged); // // ChkBLOnOff // this.ChkBLOnOff.AutoSize = true; this.ChkBLOnOff.Location = new System.Drawing.Point(137, 380); this.ChkBLOnOff.Margin = new System.Windows.Forms.Padding(2); this.ChkBLOnOff.Name = "ChkBLOnOff"; this.ChkBLOnOff.Size = new System.Drawing.Size(59, 17); this.ChkBLOnOff.TabIndex = 117; this.ChkBLOnOff.Text = "On/Off"; this.ChkBLOnOff.UseVisualStyleBackColor = true; this.ChkBLOnOff.CheckedChanged += new System.EventHandler(this.ChkBLOnOff_CheckedChanged); // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(11, 355); this.label6.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(153, 13); this.label6.TabIndex = 115; this.label6.Text = "5. Indivdual Backlight Features"; // // label17 // this.label17.AutoSize = true; this.label17.Location = new System.Drawing.Point(11, 423); this.label17.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(140, 13); this.label17.TabIndex = 119; this.label17.Text = "6. Global Backlight Features"; // // label14 // this.label14.AutoSize = true; this.label14.Location = new System.Drawing.Point(509, 379); this.label14.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(329, 13); this.label14.TabIndex = 120; this.label14.Text = "11. Stimulate a general incoming data report or a custom data report"; // // BtnGetDataNow // this.BtnGetDataNow.Location = new System.Drawing.Point(523, 396); this.BtnGetDataNow.Margin = new System.Windows.Forms.Padding(2); this.BtnGetDataNow.Name = "BtnGetDataNow"; this.BtnGetDataNow.Size = new System.Drawing.Size(98, 22); this.BtnGetDataNow.TabIndex = 121; this.BtnGetDataNow.Text = "Generate Data"; this.BtnGetDataNow.UseVisualStyleBackColor = true; this.BtnGetDataNow.Click += new System.EventHandler(this.BtnGetDataNow_Click); // // Label18 // this.Label18.AutoSize = true; this.Label18.Location = new System.Drawing.Point(711, 140); this.Label18.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.Label18.Name = "Label18"; this.Label18.Size = new System.Drawing.Size(22, 13); this.Label18.TabIndex = 128; this.Label18.Text = "0-8"; // // label15 // this.label15.AutoSize = true; this.label15.Location = new System.Drawing.Point(845, 66); this.label15.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(34, 13); this.label15.TabIndex = 127; this.label15.Text = "0-255"; // // Label16 // this.Label16.AutoSize = true; this.Label16.Location = new System.Drawing.Point(845, 118); this.Label16.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.Label16.Name = "Label16"; this.Label16.Size = new System.Drawing.Size(34, 13); this.Label16.TabIndex = 126; this.Label16.Text = "0-255"; // // label27 // this.label27.AutoSize = true; this.label27.Location = new System.Drawing.Point(761, 92); this.label27.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label27.Name = "label27"; this.label27.Size = new System.Drawing.Size(36, 13); this.label27.TabIndex = 132; this.label27.Text = "Slider:"; // // textBox13 // this.textBox13.Location = new System.Drawing.Point(801, 88); this.textBox13.Margin = new System.Windows.Forms.Padding(2); this.textBox13.Name = "textBox13"; this.textBox13.Size = new System.Drawing.Size(41, 20); this.textBox13.TabIndex = 131; this.textBox13.Text = "0"; // // label26 // this.label26.AutoSize = true; this.label26.Location = new System.Drawing.Point(630, 92); this.label26.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label26.Name = "label26"; this.label26.Size = new System.Drawing.Size(32, 13); this.label26.TabIndex = 130; this.label26.Text = "Z rot:"; // // textBox12 // this.textBox12.Location = new System.Drawing.Point(666, 89); this.textBox12.Margin = new System.Windows.Forms.Padding(2); this.textBox12.Name = "textBox12"; this.textBox12.Size = new System.Drawing.Size(41, 20); this.textBox12.TabIndex = 129; this.textBox12.Text = "0"; // // label22 // this.label22.AutoSize = true; this.label22.Location = new System.Drawing.Point(845, 90); this.label22.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label22.Name = "label22"; this.label22.Size = new System.Drawing.Size(34, 13); this.label22.TabIndex = 133; this.label22.Text = "0-255"; // // textBox7 // this.textBox7.Location = new System.Drawing.Point(711, 113); this.textBox7.Margin = new System.Windows.Forms.Padding(2); this.textBox7.Name = "textBox7"; this.textBox7.Size = new System.Drawing.Size(41, 20); this.textBox7.TabIndex = 134; this.textBox7.Text = "0"; // // textBox8 // this.textBox8.Location = new System.Drawing.Point(756, 113); this.textBox8.Margin = new System.Windows.Forms.Padding(2); this.textBox8.Name = "textBox8"; this.textBox8.Size = new System.Drawing.Size(41, 20); this.textBox8.TabIndex = 135; this.textBox8.Text = "0"; // // textBox9 // this.textBox9.Location = new System.Drawing.Point(801, 113); this.textBox9.Margin = new System.Windows.Forms.Padding(2); this.textBox9.Name = "textBox9"; this.textBox9.Size = new System.Drawing.Size(41, 20); this.textBox9.TabIndex = 136; this.textBox9.Text = "0"; // // label24 // this.label24.AutoSize = true; this.label24.Location = new System.Drawing.Point(509, 161); this.label24.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label24.Name = "label24"; this.label24.Size = new System.Drawing.Size(131, 13); this.label24.TabIndex = 137; this.label24.Text = "* Available for PID #1 only"; // // label25 // this.label25.AutoSize = true; this.label25.Location = new System.Drawing.Point(628, 603); this.label25.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label25.Name = "label25"; this.label25.Size = new System.Drawing.Size(229, 13); this.label25.TabIndex = 138; this.label25.Text = "Endpoints: Keyboard, Mouse, Input and Output"; // // label28 // this.label28.AutoSize = true; this.label28.Location = new System.Drawing.Point(628, 578); this.label28.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label28.Name = "label28"; this.label28.Size = new System.Drawing.Size(316, 13); this.label28.TabIndex = 139; this.label28.Text = "Endpoints: Keyboard, Joystick, Input and Output (Factory Default)"; // // textBox10 // this.textBox10.Location = new System.Drawing.Point(697, 216); this.textBox10.Margin = new System.Windows.Forms.Padding(2); this.textBox10.Name = "textBox10"; this.textBox10.Size = new System.Drawing.Size(41, 20); this.textBox10.TabIndex = 151; this.textBox10.Text = "0"; // // label29 // this.label29.Location = new System.Drawing.Point(509, 234); this.label29.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label29.Name = "label29"; this.label29.Size = new System.Drawing.Size(423, 29); this.label29.TabIndex = 150; this.label29.Text = "+Available for PID #2 only."; // // label30 // this.label30.AutoSize = true; this.label30.Location = new System.Drawing.Point(770, 216); this.label30.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label30.Name = "label30"; this.label30.Size = new System.Drawing.Size(51, 13); this.label30.TabIndex = 149; this.label30.Text = "Wheel Y:"; // // textBox11 // this.textBox11.Location = new System.Drawing.Point(823, 216); this.textBox11.Margin = new System.Windows.Forms.Padding(2); this.textBox11.Name = "textBox11"; this.textBox11.Size = new System.Drawing.Size(41, 20); this.textBox11.TabIndex = 148; this.textBox11.Text = "0"; // // label31 // this.label31.AutoSize = true; this.label31.Location = new System.Drawing.Point(646, 219); this.label31.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label31.Name = "label31"; this.label31.Size = new System.Drawing.Size(51, 13); this.label31.TabIndex = 147; this.label31.Text = "Wheel X:"; // // label32 // this.label32.AutoSize = true; this.label32.Location = new System.Drawing.Point(655, 195); this.label32.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label32.Name = "label32"; this.label32.Size = new System.Drawing.Size(41, 13); this.label32.TabIndex = 146; this.label32.Text = "Button:"; // // label33 // this.label33.AutoSize = true; this.label33.Location = new System.Drawing.Point(802, 193); this.label33.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label33.Name = "label33"; this.label33.Size = new System.Drawing.Size(17, 13); this.label33.TabIndex = 145; this.label33.Text = "Y:"; // // label34 // this.label34.AutoSize = true; this.label34.Location = new System.Drawing.Point(741, 194); this.label34.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label34.Name = "label34"; this.label34.Size = new System.Drawing.Size(17, 13); this.label34.TabIndex = 144; this.label34.Text = "X:"; // // textBox14 // this.textBox14.Location = new System.Drawing.Point(697, 192); this.textBox14.Margin = new System.Windows.Forms.Padding(2); this.textBox14.Name = "textBox14"; this.textBox14.Size = new System.Drawing.Size(41, 20); this.textBox14.TabIndex = 143; this.textBox14.Text = "0"; // // textBox15 // this.textBox15.Location = new System.Drawing.Point(823, 191); this.textBox15.Margin = new System.Windows.Forms.Padding(2); this.textBox15.Name = "textBox15"; this.textBox15.Size = new System.Drawing.Size(41, 20); this.textBox15.TabIndex = 142; this.textBox15.Text = "0"; // // textBox16 // this.textBox16.Location = new System.Drawing.Point(758, 192); this.textBox16.Margin = new System.Windows.Forms.Padding(2); this.textBox16.Name = "textBox16"; this.textBox16.Size = new System.Drawing.Size(41, 20); this.textBox16.TabIndex = 141; this.textBox16.Text = "0"; // // BtnMousereflect // this.BtnMousereflect.Location = new System.Drawing.Point(522, 190); this.BtnMousereflect.Margin = new System.Windows.Forms.Padding(2); this.BtnMousereflect.Name = "BtnMousereflect"; this.BtnMousereflect.Size = new System.Drawing.Size(122, 22); this.BtnMousereflect.TabIndex = 140; this.BtnMousereflect.Text = "Mouse Reflector"; this.BtnMousereflect.UseVisualStyleBackColor = true; this.BtnMousereflect.Click += new System.EventHandler(this.BtnMousereflect_Click); // // BtnEnable // this.BtnEnable.Location = new System.Drawing.Point(8, 590); this.BtnEnable.Margin = new System.Windows.Forms.Padding(2); this.BtnEnable.Name = "BtnEnable"; this.BtnEnable.Size = new System.Drawing.Size(92, 22); this.BtnEnable.TabIndex = 152; this.BtnEnable.Text = "Enable"; this.BtnEnable.UseVisualStyleBackColor = true; this.BtnEnable.Click += new System.EventHandler(this.BtnEnable_Click); // // BtnDisable // this.BtnDisable.Location = new System.Drawing.Point(114, 590); this.BtnDisable.Margin = new System.Windows.Forms.Padding(2); this.BtnDisable.Name = "BtnDisable"; this.BtnDisable.Size = new System.Drawing.Size(92, 22); this.BtnDisable.TabIndex = 153; this.BtnDisable.Text = "Disable"; this.BtnDisable.UseVisualStyleBackColor = true; this.BtnDisable.Click += new System.EventHandler(this.BtnDisable_Click); // // label35 // this.label35.AutoSize = true; this.label35.Location = new System.Drawing.Point(10, 566); this.label35.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label35.Name = "label35"; this.label35.Size = new System.Drawing.Size(232, 13); this.label35.TabIndex = 154; this.label35.Text = "8. Enable/Disable Native Joystick (PID #1 only)"; // // BtnIncIntesity // this.BtnIncIntesity.Location = new System.Drawing.Point(203, 474); this.BtnIncIntesity.Margin = new System.Windows.Forms.Padding(2); this.BtnIncIntesity.Name = "BtnIncIntesity"; this.BtnIncIntesity.Size = new System.Drawing.Size(129, 22); this.BtnIncIntesity.TabIndex = 155; this.BtnIncIntesity.Text = "Incremental Intensity"; this.BtnIncIntesity.UseVisualStyleBackColor = true; this.BtnIncIntesity.Click += new System.EventHandler(this.BtnIncIntesity_Click); // // textBox17 // this.textBox17.Location = new System.Drawing.Point(319, 450); this.textBox17.Margin = new System.Windows.Forms.Padding(2); this.textBox17.Name = "textBox17"; this.textBox17.Size = new System.Drawing.Size(30, 20); this.textBox17.TabIndex = 156; this.textBox17.Text = "255"; // // label36 // this.label36.AutoSize = true; this.label36.Location = new System.Drawing.Point(413, 452); this.label36.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label36.Name = "label36"; this.label36.Size = new System.Drawing.Size(34, 13); this.label36.TabIndex = 157; this.label36.Text = "0-255"; // // label37 // this.label37.AutoSize = true; this.label37.Location = new System.Drawing.Point(297, 453); this.label37.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label37.Name = "label37"; this.label37.Size = new System.Drawing.Size(22, 13); this.label37.TabIndex = 158; this.label37.Text = "b1:"; // // label38 // this.label38.AutoSize = true; this.label38.Location = new System.Drawing.Point(353, 453); this.label38.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label38.Name = "label38"; this.label38.Size = new System.Drawing.Size(22, 13); this.label38.TabIndex = 159; this.label38.Text = "b2:"; // // textBox18 // this.textBox18.Location = new System.Drawing.Point(379, 449); this.textBox18.Margin = new System.Windows.Forms.Padding(2); this.textBox18.Name = "textBox18"; this.textBox18.Size = new System.Drawing.Size(30, 20); this.textBox18.TabIndex = 160; this.textBox18.Text = "255"; // // CboColor // this.CboColor.FormattingEnabled = true; this.CboColor.Items.AddRange(new object[] { "Bank 1", "Bank 2"}); this.CboColor.Location = new System.Drawing.Point(64, 378); this.CboColor.Name = "CboColor"; this.CboColor.Size = new System.Drawing.Size(57, 21); this.CboColor.TabIndex = 162; // // CboBL // this.CboBL.FormattingEnabled = true; this.CboBL.Items.AddRange(new object[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79"}); this.CboBL.Location = new System.Drawing.Point(9, 378); this.CboBL.Name = "CboBL"; this.CboBL.Size = new System.Drawing.Size(45, 21); this.CboBL.TabIndex = 161; // // LblSpecialKeys // this.LblSpecialKeys.AutoSize = true; this.LblSpecialKeys.Location = new System.Drawing.Point(168, 196); this.LblSpecialKeys.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.LblSpecialKeys.Name = "LblSpecialKeys"; this.LblSpecialKeys.Size = new System.Drawing.Size(40, 13); this.LblSpecialKeys.TabIndex = 164; this.LblSpecialKeys.Text = "States:"; // // LblButtons // this.LblButtons.AutoSize = true; this.LblButtons.Location = new System.Drawing.Point(11, 209); this.LblButtons.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.LblButtons.Name = "LblButtons"; this.LblButtons.Size = new System.Drawing.Size(46, 13); this.LblButtons.TabIndex = 163; this.LblButtons.Text = "Buttons:"; // // LblJoyX // this.LblJoyX.AutoSize = true; this.LblJoyX.Location = new System.Drawing.Point(388, 198); this.LblJoyX.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.LblJoyX.Name = "LblJoyX"; this.LblJoyX.Size = new System.Drawing.Size(36, 13); this.LblJoyX.TabIndex = 165; this.LblJoyX.Text = "Joy X:"; // // LblJoyY // this.LblJoyY.AutoSize = true; this.LblJoyY.Location = new System.Drawing.Point(388, 211); this.LblJoyY.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.LblJoyY.Name = "LblJoyY"; this.LblJoyY.Size = new System.Drawing.Size(36, 13); this.LblJoyY.TabIndex = 166; this.LblJoyY.Text = "Joy Y:"; // // LblJoyZ // this.LblJoyZ.AutoSize = true; this.LblJoyZ.Location = new System.Drawing.Point(388, 223); this.LblJoyZ.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.LblJoyZ.Name = "LblJoyZ"; this.LblJoyZ.Size = new System.Drawing.Size(36, 13); this.LblJoyZ.TabIndex = 167; this.LblJoyZ.Text = "Joy Z:"; // // LblPassFail // this.LblPassFail.AutoSize = true; this.LblPassFail.Location = new System.Drawing.Point(749, 517); this.LblPassFail.Name = "LblPassFail"; this.LblPassFail.Size = new System.Drawing.Size(51, 13); this.LblPassFail.TabIndex = 313; this.LblPassFail.Text = "Pass/Fail"; // // BtnCheckDongle // this.BtnCheckDongle.Location = new System.Drawing.Point(632, 512); this.BtnCheckDongle.Margin = new System.Windows.Forms.Padding(2); this.BtnCheckDongle.Name = "BtnCheckDongle"; this.BtnCheckDongle.Size = new System.Drawing.Size(112, 22); this.BtnCheckDongle.TabIndex = 312; this.BtnCheckDongle.Text = "Check Dongle Key"; this.BtnCheckDongle.UseVisualStyleBackColor = true; this.BtnCheckDongle.Click += new System.EventHandler(this.BtnCheckDongle_Click); // // BtnSetDongle // this.BtnSetDongle.Location = new System.Drawing.Point(523, 512); this.BtnSetDongle.Margin = new System.Windows.Forms.Padding(2); this.BtnSetDongle.Name = "BtnSetDongle"; this.BtnSetDongle.Size = new System.Drawing.Size(98, 22); this.BtnSetDongle.TabIndex = 311; this.BtnSetDongle.Text = "Set Dongle Key"; this.BtnSetDongle.UseVisualStyleBackColor = true; this.BtnSetDongle.Click += new System.EventHandler(this.BtnSetDongle_Click); // // label44 // this.label44.AutoSize = true; this.label44.Location = new System.Drawing.Point(510, 494); this.label44.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label44.Name = "label44"; this.label44.Size = new System.Drawing.Size(147, 13); this.label44.TabIndex = 310; this.label44.Text = "13. Dongle, v5+ firmware only"; // // label41 // this.label41.AutoSize = true; this.label41.Location = new System.Drawing.Point(509, 431); this.label41.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label41.Name = "label41"; this.label41.Size = new System.Drawing.Size(301, 13); this.label41.TabIndex = 309; this.label41.Text = "12. Write Version (0-65535), reboot required, v5+ firmware only"; // // LblVersion // this.LblVersion.AutoSize = true; this.LblVersion.Location = new System.Drawing.Point(679, 459); this.LblVersion.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.LblVersion.Name = "LblVersion"; this.LblVersion.Size = new System.Drawing.Size(41, 13); this.LblVersion.TabIndex = 308; this.LblVersion.Text = "version"; // // TxtVersion // this.TxtVersion.Location = new System.Drawing.Point(625, 454); this.TxtVersion.Margin = new System.Windows.Forms.Padding(2); this.TxtVersion.Name = "TxtVersion"; this.TxtVersion.Size = new System.Drawing.Size(49, 20); this.TxtVersion.TabIndex = 307; this.TxtVersion.Text = "100"; // // BtnVersion // this.BtnVersion.Location = new System.Drawing.Point(523, 452); this.BtnVersion.Margin = new System.Windows.Forms.Padding(2); this.BtnVersion.Name = "BtnVersion"; this.BtnVersion.Size = new System.Drawing.Size(92, 22); this.BtnVersion.TabIndex = 306; this.BtnVersion.Text = "Write Version"; this.BtnVersion.UseVisualStyleBackColor = true; this.BtnVersion.Click += new System.EventHandler(this.BtnVersion_Click); // // BtnCustom // this.BtnCustom.Location = new System.Drawing.Point(635, 396); this.BtnCustom.Margin = new System.Windows.Forms.Padding(2); this.BtnCustom.Name = "BtnCustom"; this.BtnCustom.Size = new System.Drawing.Size(92, 22); this.BtnCustom.TabIndex = 314; this.BtnCustom.Text = "Custom Data"; this.BtnCustom.UseVisualStyleBackColor = true; this.BtnCustom.Click += new System.EventHandler(this.BtnCustom_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScroll = true; this.ClientSize = new System.Drawing.Size(965, 661); this.Controls.Add(this.BtnCustom); this.Controls.Add(this.LblPassFail); this.Controls.Add(this.BtnCheckDongle); this.Controls.Add(this.BtnSetDongle); this.Controls.Add(this.label44); this.Controls.Add(this.label41); this.Controls.Add(this.LblVersion); this.Controls.Add(this.TxtVersion); this.Controls.Add(this.BtnVersion); this.Controls.Add(this.LblJoyZ); this.Controls.Add(this.LblJoyY); this.Controls.Add(this.LblJoyX); this.Controls.Add(this.LblSpecialKeys); this.Controls.Add(this.LblButtons); this.Controls.Add(this.CboColor); this.Controls.Add(this.CboBL); this.Controls.Add(this.textBox18); this.Controls.Add(this.label38); this.Controls.Add(this.label37); this.Controls.Add(this.label36); this.Controls.Add(this.textBox17); this.Controls.Add(this.BtnIncIntesity); this.Controls.Add(this.label35); this.Controls.Add(this.BtnDisable); this.Controls.Add(this.BtnEnable); this.Controls.Add(this.textBox10); this.Controls.Add(this.label29); this.Controls.Add(this.label30); this.Controls.Add(this.textBox11); this.Controls.Add(this.label31); this.Controls.Add(this.label32); this.Controls.Add(this.label33); this.Controls.Add(this.label34); this.Controls.Add(this.textBox14); this.Controls.Add(this.textBox15); this.Controls.Add(this.textBox16); this.Controls.Add(this.BtnMousereflect); this.Controls.Add(this.label28); this.Controls.Add(this.label25); this.Controls.Add(this.label24); this.Controls.Add(this.textBox9); this.Controls.Add(this.textBox8); this.Controls.Add(this.textBox7); this.Controls.Add(this.label22); this.Controls.Add(this.label27); this.Controls.Add(this.textBox13); this.Controls.Add(this.label26); this.Controls.Add(this.textBox12); this.Controls.Add(this.Label18); this.Controls.Add(this.label15); this.Controls.Add(this.Label16); this.Controls.Add(this.BtnGetDataNow); this.Controls.Add(this.label14); this.Controls.Add(this.label17); this.Controls.Add(this.ChkFlash); this.Controls.Add(this.ChkBLOnOff); this.Controls.Add(this.label6); this.Controls.Add(this.ChkFRedLED); this.Controls.Add(this.ChkFGreenLED); this.Controls.Add(this.ChkRedLED); this.Controls.Add(this.ChkGreenLED); this.Controls.Add(this.BtnSetFlash); this.Controls.Add(this.TxtFlashFreq); this.Controls.Add(this.ChkRedOnOff); this.Controls.Add(this.ChkGreenOnOff); this.Controls.Add(this.label13); this.Controls.Add(this.BtnTimeStampOn); this.Controls.Add(this.BtnBLToggle); this.Controls.Add(this.BtnSaveBL); this.Controls.Add(this.label23); this.Controls.Add(this.listBox2); this.Controls.Add(this.BtnDescriptor); this.Controls.Add(this.label21); this.Controls.Add(this.label20); this.Controls.Add(this.label19); this.Controls.Add(this.BtnTimeStamp); this.Controls.Add(this.label12); this.Controls.Add(this.textBox6); this.Controls.Add(this.textBox5); this.Controls.Add(this.label11); this.Controls.Add(this.label10); this.Controls.Add(this.label9); this.Controls.Add(this.label8); this.Controls.Add(this.textBox4); this.Controls.Add(this.textBox3); this.Controls.Add(this.textBox2); this.Controls.Add(this.BtnJoyreflect); this.Controls.Add(this.textBox1); this.Controls.Add(this.BtnKBreflect); this.Controls.Add(this.label7); this.Controls.Add(this.BtnPID1); this.Controls.Add(this.BtnPID2); this.Controls.Add(this.label5); this.Controls.Add(this.BtnBL); this.Controls.Add(this.button1); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.LblUnitID); this.Controls.Add(this.BtnCallback); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.TxtSetUnitID); this.Controls.Add(this.BtnUnitID); this.Controls.Add(this.listBox1); this.Controls.Add(this.LblSwitchPos); this.Controls.Add(this.CboDevices); this.Controls.Add(this.BtnEnumerate); this.Margin = new System.Windows.Forms.Padding(2); this.Name = "Form1"; this.Text = "C# X-keys XK-68 Joystick"; this.Load += new System.EventHandler(this.Form1_Load); this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form1_FormClosed); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button BtnEnumerate; private System.Windows.Forms.ComboBox CboDevices; private System.Windows.Forms.Label LblSwitchPos; private System.Windows.Forms.ListBox listBox1; private System.Windows.Forms.Button BtnUnitID; private System.Windows.Forms.TextBox TxtSetUnitID; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; private System.Windows.Forms.Button BtnCallback; private System.Windows.Forms.Label LblUnitID; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button BtnBL; private System.Windows.Forms.Label label5; private System.Windows.Forms.Button BtnPID2; private System.Windows.Forms.Button BtnPID1; private System.Windows.Forms.Label label7; private System.Windows.Forms.Button BtnKBreflect; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button BtnJoyreflect; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.TextBox textBox4; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label11; private System.Windows.Forms.TextBox textBox5; private System.Windows.Forms.TextBox textBox6; private System.Windows.Forms.Label label12; private System.Windows.Forms.Button BtnTimeStamp; private System.Windows.Forms.Label label19; private System.Windows.Forms.Label label20; private System.Windows.Forms.Label label21; private System.Windows.Forms.Button BtnDescriptor; private System.Windows.Forms.ListBox listBox2; private System.Windows.Forms.Label label23; private System.Windows.Forms.Button BtnSaveBL; private System.Windows.Forms.Button BtnBLToggle; private System.Windows.Forms.Button BtnTimeStampOn; private System.Windows.Forms.Label label13; private System.Windows.Forms.CheckBox ChkRedOnOff; private System.Windows.Forms.CheckBox ChkGreenOnOff; private System.Windows.Forms.Button BtnSetFlash; private System.Windows.Forms.TextBox TxtFlashFreq; private System.Windows.Forms.CheckBox ChkFRedLED; private System.Windows.Forms.CheckBox ChkFGreenLED; private System.Windows.Forms.CheckBox ChkRedLED; private System.Windows.Forms.CheckBox ChkGreenLED; private System.Windows.Forms.CheckBox ChkFlash; private System.Windows.Forms.CheckBox ChkBLOnOff; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label17; private System.Windows.Forms.Label label14; private System.Windows.Forms.Button BtnGetDataNow; private System.Windows.Forms.Label Label18; private System.Windows.Forms.Label label15; private System.Windows.Forms.Label Label16; private System.Windows.Forms.Label label27; private System.Windows.Forms.TextBox textBox13; private System.Windows.Forms.Label label26; private System.Windows.Forms.TextBox textBox12; private System.Windows.Forms.Label label22; private System.Windows.Forms.TextBox textBox7; private System.Windows.Forms.TextBox textBox8; private System.Windows.Forms.TextBox textBox9; private System.Windows.Forms.Label label24; private System.Windows.Forms.Label label25; private System.Windows.Forms.Label label28; private System.Windows.Forms.TextBox textBox10; private System.Windows.Forms.Label label29; private System.Windows.Forms.Label label30; private System.Windows.Forms.TextBox textBox11; private System.Windows.Forms.Label label31; private System.Windows.Forms.Label label32; private System.Windows.Forms.Label label33; private System.Windows.Forms.Label label34; private System.Windows.Forms.TextBox textBox14; private System.Windows.Forms.TextBox textBox15; private System.Windows.Forms.TextBox textBox16; private System.Windows.Forms.Button BtnMousereflect; private System.Windows.Forms.Button BtnEnable; private System.Windows.Forms.Button BtnDisable; private System.Windows.Forms.Label label35; private System.Windows.Forms.Button BtnIncIntesity; private System.Windows.Forms.TextBox textBox17; private System.Windows.Forms.Label label36; private System.Windows.Forms.Label label37; private System.Windows.Forms.Label label38; private System.Windows.Forms.TextBox textBox18; private System.Windows.Forms.ComboBox CboColor; private System.Windows.Forms.ComboBox CboBL; private System.Windows.Forms.Label LblSpecialKeys; private System.Windows.Forms.Label LblButtons; private System.Windows.Forms.Label LblJoyX; private System.Windows.Forms.Label LblJoyY; private System.Windows.Forms.Label LblJoyZ; private System.Windows.Forms.Label LblPassFail; private System.Windows.Forms.Button BtnCheckDongle; private System.Windows.Forms.Button BtnSetDongle; private System.Windows.Forms.Label label44; private System.Windows.Forms.Label label41; private System.Windows.Forms.Label LblVersion; private System.Windows.Forms.TextBox TxtVersion; private System.Windows.Forms.Button BtnVersion; private System.Windows.Forms.Button BtnCustom; } }
46.998711
114
0.570108
[ "MIT" ]
cschaftenaar/ATEM_Switcher_Deluxe
PIEngineeringSDK(v1047)/XK-68 Joystick/C# Express/PIHidDotName Csharp Sample/Form1.Designer.cs
72,897
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Xunit; namespace JitTest_s_ldfld_mulovf_signed_cs { public class Test { private long _op1,_op2; private bool check(long product, bool overflow) { Console.Write("Multiplying {0} and {1}...", _op1, _op2); try { if (checked(_op1 * _op2) != product) return false; Console.WriteLine(); return !overflow; } catch (OverflowException) { Console.WriteLine("overflow."); return overflow; } } [Fact] public static int TestEntryPoint() { Test app = new Test(); app._op1 = 0x000000007fffffff; app._op2 = 0x000000007fffffff; if (!app.check(0x3fffffff00000001, false)) goto fail; app._op1 = 0x0000000100000000; app._op2 = 0x000000007fffffff; if (!app.check(0x7fffffff00000000, false)) goto fail; app._op1 = 0x0000000100000000; app._op2 = 0x0000000100000000; if (!app.check(0x0000000000000000, true)) goto fail; app._op1 = 0x3fffffffffffffff; app._op2 = 0x0000000000000002; if (!app.check(0x7ffffffffffffffe, false)) goto fail; app._op1 = unchecked((long)0xffffffffffffffff); app._op2 = unchecked((long)0xfffffffffffffffe); if (!app.check(2, false)) goto fail; app._op1 = 0x0000000000100000; app._op2 = 0x0000001000000000; if (!app.check(0x0100000000000000, false)) goto fail; app._op1 = unchecked((long)0xffffffffffffffff); app._op2 = unchecked((long)0x8000000000000001); if (!app.check(0x7fffffffffffffff, false)) goto fail; app._op1 = unchecked((long)0xfffffffffffffffe); app._op2 = unchecked((long)0x8000000000000001); if (!app.check(0, true)) goto fail; app._op1 = 2; app._op2 = unchecked((long)0x8000000000000001); if (!app.check(0, true)) goto fail; Console.WriteLine("Test passed"); return 100; fail: Console.WriteLine("Test failed"); return 1; } } }
33.333333
71
0.523846
[ "MIT" ]
Ali-YousefiTelori/runtime
src/tests/JIT/Methodical/int64/signed/s_ldfld_mulovf.cs
2,600
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** 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.Kubernetes.Types.Inputs.Pulumi.V1Alpha1 { /// <summary> /// StackStatus defines the observed state of Stack /// </summary> public class StackStatusArgs : Pulumi.ResourceArgs { /// <summary> /// LastUpdate contains details of the status of the last update. /// </summary> [Input("lastUpdate")] public Input<Pulumi.Kubernetes.Types.Inputs.Pulumi.V1Alpha1.StackStatusLastUpdateArgs>? LastUpdate { get; set; } [Input("outputs")] private InputMap<ImmutableDictionary<string, object>>? _outputs; /// <summary> /// Outputs contains the exported stack output variables resulting from a deployment. /// </summary> public InputMap<ImmutableDictionary<string, object>> Outputs { get => _outputs ?? (_outputs = new InputMap<ImmutableDictionary<string, object>>()); set => _outputs = value; } public StackStatusArgs() { } } }
31.585366
120
0.64556
[ "Apache-2.0" ]
eljoth/pulumi-kubernetes-operator
lib/dotnet/Pulumi/V1Alpha1/Inputs/StackStatusArgs.cs
1,295
C#
 namespace iTin.Core.ComponentModel.Patterns { using System.Diagnostics; /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> public class AndNotSpecification<T> : CompositeSpecification<T> { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly ISpecification<T> _left; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly ISpecification<T> _right; /// <summary> /// /// </summary> /// <param name="left"></param> /// <param name="right"></param> public AndNotSpecification(ISpecification<T> left, ISpecification<T> right) { _left = left; _right = right; } /// <summary> /// /// </summary> /// <param name="candidate"></param> /// <returns></returns> public override bool IsSatisfiedBy(T candidate) => _left.IsSatisfiedBy(candidate) && _right.IsSatisfiedBy(candidate) != true; } }
27.945946
133
0.577369
[ "MIT" ]
iAJTin/iCPUID
src/lib/net/iTin.Core/iTin.Core/ComponentModel/Patterns/Specification/AndNotSpecification.cs
1,036
C#
using System.Collections.Generic; namespace MessagePack.Tests.SharedTestItems.Successes.Collections { internal sealed class TestPopulatedStringList : SuccessTestItem<List<string>> { public TestPopulatedStringList() : base(new List<string> { "abc", "def" }) { } } }
31.777778
86
0.727273
[ "BSD-2-Clause" ]
ProductiveRage/MsgPack5.H5
Tests/SharedTestItems/Successes/Collections/TestPopulatedStringList.cs
288
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using VideoGameDBServices.Models; namespace VideoGameDBServices.Interfaces { public interface IRatingRepository { IEnumerable<Ratings> GetAll(); Task<Ratings> Find(int id); Task<bool> Exist(int id); } }
17.947368
40
0.709677
[ "MIT" ]
JoeEager/VideoGameDBServices
VideoGameDBServices/Interfaces/IRatingRepository.cs
343
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using System.Web; using NuGet.Services.Search.Models; using QueryInterceptor; namespace NuGetGallery { public static class SearchAdaptor { /// <summary> /// Determines the maximum number of packages returned in a single page of an OData result. /// </summary> internal const int MaxPageSize = 40; public static SearchFilter GetSearchFilter(string q, int page, string sortOrder) { var searchFilter = new SearchFilter { SearchTerm = q, Skip = (page - 1) * Constants.DefaultPackageListPageSize, // pages are 1-based. Take = Constants.DefaultPackageListPageSize, IncludePrerelease = true }; switch (sortOrder) { case Constants.AlphabeticSortOrder: searchFilter.SortOrder = SortOrder.TitleAscending; break; case Constants.RecentSortOrder: searchFilter.SortOrder = SortOrder.Published; break; default: searchFilter.SortOrder = SortOrder.Relevance; break; } return searchFilter; } public static async Task<IQueryable<Package>> GetResultsFromSearchService(ISearchService searchService, SearchFilter searchFilter) { var result = await searchService.Search(searchFilter); // For count queries, we can ask the SearchService to not filter the source results. This would avoid hitting the database and consequently make // it very fast. if (searchFilter.CountOnly) { // At this point, we already know what the total count is. We can have it return this value very quickly without doing any SQL. return result.Data.InterceptWith(new CountInterceptor(result.Hits)); } // For relevance search, Lucene returns us a paged\sorted list. OData tries to apply default ordering and Take \ Skip on top of this. // We avoid it by yanking these expressions out of out the tree. return result.Data.InterceptWith(new DisregardODataInterceptor()); } public static async Task<IQueryable<Package>> SearchCore( ISearchService searchService, HttpRequestBase request, IQueryable<Package> packages, string searchTerm, string targetFramework, bool includePrerelease, CuratedFeed curatedFeed) { SearchFilter searchFilter; // We can only use Lucene if the client queries for the latest versions (IsLatest \ IsLatestStable) versions of a package // and specific sort orders that we have in the index. if (TryReadSearchFilter(request.RawUrl, out searchFilter)) { searchFilter.SearchTerm = searchTerm; searchFilter.IncludePrerelease = includePrerelease; searchFilter.CuratedFeed = curatedFeed; Trace.WriteLine("TODO: use target framework parameter - see #856" + targetFramework); var results = await GetResultsFromSearchService(searchService, searchFilter); return results; } if (!includePrerelease) { packages = packages.Where(p => !p.IsPrerelease); } return packages.Search(searchTerm); } private static bool TryReadSearchFilter(string url, out SearchFilter searchFilter) { if (url == null) { searchFilter = null; return false; } int indexOfQuestionMark = url.IndexOf('?'); if (indexOfQuestionMark == -1) { searchFilter = null; return false; } string path = url.Substring(0, indexOfQuestionMark); string query = url.Substring(indexOfQuestionMark + 1); if (string.IsNullOrEmpty(query)) { searchFilter = null; return false; } searchFilter = new SearchFilter { // The way the default paging works is WCF attempts to read up to the MaxPageSize elements. If it finds as many, it'll assume there // are more elements to be paged and generate a continuation link. Consequently we'll always ask to pull MaxPageSize elements so WCF generates the // link for us and then allow it to do a Take on the results. The alternative to do is roll our IDataServicePagingProvider, but we run into // issues since we need to manage state over concurrent requests. This seems like an easier solution. Take = MaxPageSize, Skip = 0, CountOnly = path.EndsWith("$count", StringComparison.Ordinal) }; string[] props = query.Split('&'); IDictionary<string, string> queryTerms = new Dictionary<string, string>(); foreach (string prop in props) { string[] nameValue = prop.Split('='); if (nameValue.Length == 2) { queryTerms[nameValue[0]] = nameValue[1]; } } // We'll only use the index if we the query searches for latest \ latest-stable packages string filter; if (queryTerms.TryGetValue("$filter", out filter)) { if (!(filter.Equals("IsLatestVersion", StringComparison.Ordinal) || filter.Equals("IsAbsoluteLatestVersion", StringComparison.Ordinal))) { searchFilter = null; return false; } } else { searchFilter = null; return false; } string skip; if (queryTerms.TryGetValue("$skip", out skip)) { int result; if (int.TryParse(skip, out result)) { searchFilter.Skip = result; } } // only certain orderBy clauses are supported from the Lucene search string orderBy; if (queryTerms.TryGetValue("$orderby", out orderBy)) { if (string.IsNullOrEmpty(orderBy)) { searchFilter.SortOrder = SortOrder.Relevance; } else if (orderBy.StartsWith("DownloadCount", StringComparison.Ordinal)) { searchFilter.SortOrder = SortOrder.Relevance; } else if (orderBy.StartsWith("Published", StringComparison.Ordinal)) { searchFilter.SortOrder = SortOrder.Published; } else if (orderBy.StartsWith("LastEdited", StringComparison.Ordinal)) { searchFilter.SortOrder = SortOrder.LastEdited; } else if (orderBy.StartsWith("Id", StringComparison.Ordinal)) { searchFilter.SortOrder = SortOrder.TitleAscending; } else if (orderBy.StartsWith("concat", StringComparison.Ordinal)) { searchFilter.SortOrder = SortOrder.TitleAscending; if (orderBy.Contains("%20desc")) { searchFilter.SortOrder = SortOrder.TitleDescending; } } else { searchFilter = null; return false; } } else { searchFilter.SortOrder = SortOrder.Relevance; } return true; } } }
37.456621
163
0.539681
[ "ECL-2.0", "Apache-2.0" ]
rrudduck/NuGetGallery
src/NuGetGallery/DataServices/SearchAdaptor.cs
8,205
C#
// Copyright (c) IEvangelist. All rights reserved. // Licensed under the MIT License. using System; using System.IO; using Microsoft.Azure.CosmosRepository; using Newtonsoft.Json; namespace Microsoft.Azure.CosmosRepositoryTests.Stubs { public class TestItem : FullItem { public string Property { get; set; } = default!; } }
23.066667
56
0.725434
[ "MIT" ]
filipmhpersson/azure-cosmos-dotnet-repository
tests/Microsoft.Azure.CosmosRepositoryTests/Stubs/TestItem.cs
348
C#
// Copyright 2021 The NATS 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. using System; using System.Text; using NATS.Client; using NATS.Client.JetStream; namespace NATSExamples { /// <summary> /// This example will demonstrate JetStream publishing with options. /// </summary> internal static class JetStreamPublishWithOptionsUseCases { private const string Usage = "Usage: JetStreamPublishWithOptionsUseCases [-url url] [-creds file] [-stream stream] " + "[-subject subject]" + "\n\nDefault Values:" + "\n [-stream] pubopts-stream" + "\n [-subject] pubopts-subject"; public static void Main(string[] args) { ArgumentHelper helper = new ArgumentHelperBuilder("JetStream Publish With Options Use Cases", args, Usage) .DefaultStream("pubopts-stream") .DefaultSubject("pubopts-subject") .Build(); try { using (IConnection c = new ConnectionFactory().CreateConnection(helper.MakeOptions())) { // Create a JetStreamManagement context. IJetStreamManagement jsm = c.CreateJetStreamManagementContext(); // Use the utility to create a stream stored in memory. JsUtils.CreateStreamExitWhenExists(jsm, helper.Stream, helper.Subject); // get a regular context IJetStream js = c.CreateJetStreamContext(); PublishOptions.PublishOptionsBuilder builder = PublishOptions.Builder() .WithExpectedStream(helper.Stream) .WithMessageId("mid1"); PublishAck pa = js.Publish(helper.Subject, Encoding.ASCII.GetBytes("message1"), builder.Build()); Console.WriteLine("Published message on subject {0}, stream {1}, seqno {2}.", helper.Subject, pa.Stream, pa.Seq); // IMPORTANT! // You can reuse the builder in 2 ways. // 1. Manually set a field to null or to DefaultLastSequence if you want to clear it out. // 2. Use the clearExpected method to clear the expectedLastId, expectedLastSequence and messageId fields // Manual re-use 1. Clearing some fields builder .WithExpectedLastMsgId("mid1") .WithExpectedLastSequence(PublishOptions.DefaultLastSequence) .WithMessageId(null); pa = js.Publish(helper.Subject, Encoding.ASCII.GetBytes("message2"), builder.Build()); Console.WriteLine("Published message on subject {0}, stream {1}, seqno {2}.", helper.Subject, pa.Stream, pa.Seq); // Manual re-use 2. Setting all the expected fields again builder .WithExpectedLastMsgId(null) .WithExpectedLastSequence(PublishOptions.DefaultLastSequence) .WithMessageId("mid3"); pa = js.Publish(helper.Subject, Encoding.ASCII.GetBytes("message3"), builder.Build()); Console.WriteLine("Published message on subject {0}, stream {1}, seqno {2}.", helper.Subject, pa.Stream, pa.Seq); // reuse() method clears all the fields, then we set some fields. builder.ClearExpected() .WithExpectedLastSequence(pa.Seq) .WithMessageId("mid4"); pa = js.Publish(helper.Subject, Encoding.ASCII.GetBytes("message4"), builder.Build()); Console.WriteLine("Published message on subject {0}, stream {1}, seqno {2}.", helper.Subject, pa.Stream, pa.Seq); // exception when the expected stream does not match [10060] try { PublishOptions errOpts = PublishOptions.Builder().WithExpectedStream("wrongStream").Build(); js.Publish(helper.Subject, Encoding.ASCII.GetBytes("ex1"), errOpts); } catch (NATSJetStreamException e) { Console.WriteLine($"Exception was: '{e.ErrorDescription}'"); } // exception with wrong last msg ID [10070] try { PublishOptions errOpts = PublishOptions.Builder().WithExpectedLastMsgId("wrongId").Build(); js.Publish(helper.Subject, Encoding.ASCII.GetBytes("ex2"), errOpts); } catch (NATSJetStreamException e) { Console.WriteLine($"Exception was: '{e.ErrorDescription}'"); } // exception with wrong last sequence wrong last sequence: 4 [10071] try { PublishOptions errOpts = PublishOptions.Builder().WithExpectedLastSequence(999).Build(); js.Publish(helper.Subject, Encoding.ASCII.GetBytes("ex3"), errOpts); } catch (NATSJetStreamException e) { Console.WriteLine($"Exception was: '{e.ErrorDescription}'"); } // delete the stream since we are done with it. jsm.DeleteStream(helper.Stream); } } catch (Exception ex) { helper.ReportException(ex); } } } }
47.392593
125
0.539387
[ "Apache-2.0" ]
JohannesEH/nats.net
src/Samples/JetStreamPublishWithOptionsUseCases/JetStreamPublishWithOptionsUseCases.cs
6,400
C#
//***************************************************************************** //* Code Factory SDK //* Copyright (c) 2020 CodeFactory, LLC //***************************************************************************** using System; using System.Collections.Generic; namespace CodeFactory { /// <summary> /// Base implementation of a code factory model. All models will be derived from this base model definition. /// </summary> /// <typeparam name="TModelTypes">Enumeration of the model types that this model supports.</typeparam> public interface IModel<TModelTypes> where TModelTypes : struct, IComparable, IFormattable, IConvertible { /// <summary> /// Flag that determines if this model was able to load. /// </summary> bool IsLoaded { get; } /// <summary> /// Flag that determines if this model has errors. /// </summary> bool HasErrors { get; } /// <summary> /// List of all errors that occurred in this model. /// </summary> IReadOnlyList<ModelException<TModelTypes>> ModelErrors { get; } /// <summary> /// Determines the type of model that has been loaded. /// </summary> TModelTypes ModelType { get; } } }
32.846154
112
0.540203
[ "MIT" ]
CodeFactoryLLC/CodeFactory
src/CodeFactoryVisualStudio/CodeFactory/IModel.cs
1,283
C#
using ExtraOptions; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; using UnityEngine.UI; using Upgrade; public class StatsUI : MonoBehaviour { public static StatsUI Instance { get; private set; } private void Start() { Instance = this; } public void InitializeStatsPanel() { CategorySelected(GameObject.Find("UI/Panels/StatsPanel/Content/CategoriesPanel/DiceButton")); } public void CategorySelected(GameObject categoryGO) { ClearStatsView(); categoryGO.GetComponent<Image>().color = new Color(0, 0.5f, 1, 100f/256f); ShowViewSimple(categoryGO.GetComponentInChildren<Text>().text); } private void ShowViewSimple(string name) { Transform parentTransform = GameObject.Find("UI/Panels/StatsPanel/Content/ContentViewPanel").transform; string prefabPath = "Prefabs/MainMenu/Stats/" + name + "ViewPanel"; GameObject prefab = (GameObject)Resources.Load(prefabPath, typeof(GameObject)); //GameObject panel = Instantiate(prefab, parentTransform); } private void ClearStatsView() { Transform categoryTransform = GameObject.Find("UI/Panels/StatsPanel/Content/CategoriesPanel").transform; foreach (Transform transform in categoryTransform.transform) { transform.GetComponent<Image>().color = new Color(0, 0.5f, 1, 0); } Transform parentTransform = GameObject.Find("UI/Panels/StatsPanel/Content/ContentViewPanel").transform; foreach (Transform transform in parentTransform.transform) { Destroy(transform.gameObject); } } }
29.576271
112
0.686533
[ "MIT" ]
97saundersj/FlyCasual
Assets/Scripts/MainMenu/View/StatsUI.cs
1,747
C#
using System.Collections.Generic; using System.Linq; namespace Saquib.Utils.Naming { internal static class NameSplitter { private static readonly char[] SPLIT_CHARS = new[] { '_', '-' }; /// <summary> /// Splits a name into logical parts, lowercasing them. /// </summary> public static string[] Split( string name ) { return SplitInternal( name ).ToArray(); } private static IEnumerable<string> SplitInternal( string name ) { foreach ( var separated in SplitBySeparators( name ) ) { foreach ( var part in SplitByCapitalization( separated ) ) { yield return part.ToLower(); } } } private static IEnumerable<string> SplitBySeparators( string name ) { return name.Split( SPLIT_CHARS ); } private static IEnumerable<string> SplitByCapitalization( string name ) { int start = 0; for ( int i = 1; i < name.Length; ++i ) { if ( char.IsUpper( name[i - 1] ) && char.IsUpper( name[i] ) ) { // we went from 'A' to 'A', treat this as a part yield return name.Substring( start, i - start ); start = i; } else if ( !char.IsUpper( name[i - 1] ) && char.IsUpper( name[i] ) ) { // we went from 'a' to 'A', treat this as a part yield return name.Substring( start, i - start ); start = i; } } yield return name.Substring( start ); } } }
38.186047
87
0.51218
[ "MIT" ]
j3parker/Saquib.Utils.Naming
Saquib.Utils.Naming/NameSplitter.cs
1,642
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.UI; namespace WebAddressbookTests { public class ApplicationManager { protected IWebDriver driver; protected string baseURL; protected LoginHelper loginHelper; protected NavigationHelper navigator; protected GroupHelper groupHelper; protected ContactHelper contactHelper; private static ThreadLocal<ApplicationManager> app = new ThreadLocal<ApplicationManager>(); private ApplicationManager() { FirefoxOptions options = new FirefoxOptions(); options.BrowserExecutableLocation = @"d:\Program Files\Mozilla Firefox\firefox.exe"; options.UseLegacyImplementation = true; driver = new FirefoxDriver(options); baseURL = "http://localhost/"; loginHelper = new LoginHelper(this); navigator = new NavigationHelper(this); groupHelper = new GroupHelper(this); contactHelper = new ContactHelper(this); } ~ApplicationManager() { try { driver.Quit(); } catch (Exception) { // Ignore errors if unable to close the browser } } public static ApplicationManager GetInstance() { if (! app.IsValueCreated) { ApplicationManager newInstance = new ApplicationManager(); newInstance.Navigator.GoToHomePage(); app.Value = newInstance; } return app.Value; } public IWebDriver Driver { get { return driver; } } public string BaseURL { get { return baseURL; } } public LoginHelper Auth { get { return loginHelper; } } public NavigationHelper Navigator { get { return navigator; } } public GroupHelper Groups { get { return groupHelper; } } public ContactHelper Contacts { get { return contactHelper; } } } }
23.827273
99
0.514689
[ "Apache-2.0" ]
kiralyubimova/csharp_training
addressbook_web_tests/addressbook_web_tests/appmanager/ApplicationManager.cs
2,623
C#
using System.Collections.Specialized; using System.Globalization; using System.Linq; using Machine.Fakes; using Machine.Specifications; using Moolah.PayPal; namespace Moolah.Specs.PayPal { public abstract class PayPalRequestBuilderContext : WithFakes { Establish context = () => { Configuration = new PayPalConfiguration(PaymentEnvironment.Test, "testUser", "testpassword", "testsignature"); SUT = new PayPalRequestBuilder(Configuration); }; protected static PayPalRequestBuilder SUT; protected static NameValueCollection Request; protected static PayPalConfiguration Configuration; protected const string CancelUrl = "http://yoursite.com/paypalconfirm"; protected const string ConfirmationUrl = "http://yoursite.com/basket"; } [Behaviors] public class PayPalCommonRequestBehavior { It should_specify_api_version_78 = () => Request["VERSION"].ShouldEqual("78"); It should_specify_user_from_configuration = () => Request["USER"].ShouldEqual(Configuration.UserId); It should_specify_password_from_configuration = () => Request["PWD"].ShouldEqual(Configuration.Password); It should_specify_signature_from_configuration = () => Request["SIGNATURE"].ShouldEqual(Configuration.Signature); protected static NameValueCollection Request; protected static PayPalConfiguration Configuration; } [Behaviors] public class SetExpressCheckoutBehavior { It should_specify_correct_method = () => Request["METHOD"].ShouldEqual("SetExpressCheckout"); It should_specify_formatted_amount = () => Request["PAYMENTREQUEST_0_AMT"].ShouldEqual(Amount.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)); It should_specify_currency_code = () => Request["PAYMENTREQUEST_0_CURRENCYCODE"].ShouldEqual("GBP"); It should_specify_sale_payment_action = () => Request["PAYMENTREQUEST_0_PAYMENTACTION"].ShouldEqual("Sale"); It should_specify_cancel_url = () => Request["cancelUrl"].ShouldEqual(CancelUrl); It should_specify_return_url = () => Request["returnUrl"].ShouldEqual(ConfirmationUrl); protected static NameValueCollection Request; protected static decimal Amount; protected static string CancelUrl; protected static string ConfirmationUrl; } [Subject(typeof(PayPalRequestBuilder))] public class When_building_a_request_with_values_that_must_be_url_encoded { It should_url_encode_the_values_when_converted_to_a_string = () => request.ToString().ShouldNotContain('?'); Because of = () => request = SUT.SetExpressCheckout(1, CurrencyCodeType.GBP, "http://localhost/?something=2&somethingelse=1", "http://localhost/?something=2&somethingelse=1"); Establish context = () => SUT = new PayPalRequestBuilder(new PayPalConfiguration(PaymentEnvironment.Test)); static PayPalRequestBuilder SUT; static NameValueCollection request; } [Subject(typeof(PayPalRequestBuilder))] public class When_building_set_express_checkout_request_for_an_amount : PayPalRequestBuilderContext { Behaves_like<PayPalCommonRequestBehavior> a_paypal_nvp_request; Behaves_like<SetExpressCheckoutBehavior> set_express_checkout; Because of = () => Request = SUT.SetExpressCheckout(Amount, CurrencyCodeType.GBP, CancelUrl, ConfirmationUrl); protected const decimal Amount = 12.99m; } [Subject(typeof(PayPalRequestBuilder))] public class When_building_set_express_checkout_request_and_locale_code_is_set : PayPalRequestBuilderContext { Behaves_like<PayPalCommonRequestBehavior> a_paypal_nvp_request; Behaves_like<SetExpressCheckoutBehavior> set_express_checkout; It should_specify_the_paypal_locale_code = () => Request["LOCALECODE"].ShouldEqual(LocaleCode); Establish context = () => Configuration.LocaleCode = LocaleCode; Because of = () => Request = SUT.SetExpressCheckout(Amount, CurrencyCodeType.GBP, CancelUrl, ConfirmationUrl); protected const decimal Amount = 12.99m; const string LocaleCode = "GB"; } [Subject(typeof(PayPalRequestBuilder))] public class When_building_set_express_checkout_request_and_an_unsupported_locale_code_is_set : PayPalRequestBuilderContext { Behaves_like<PayPalCommonRequestBehavior> a_paypal_nvp_request; Behaves_like<SetExpressCheckoutBehavior> set_express_checkout; It should_not_specify_the_paypal_locale_code = () => Request["LOCALECODE"].ShouldBeNull(); Establish context = () => Configuration.LocaleCode = LocaleCode; Because of = () => Request = SUT.SetExpressCheckout(Amount, CurrencyCodeType.GBP, CancelUrl, ConfirmationUrl); protected const decimal Amount = 12.99m; const string LocaleCode = "dud"; } [Subject(typeof(PayPalRequestBuilder))] public class When_building_set_express_checkout_request_and_use_locale_from_current_culture_is_set_with_supported_culture : PayPalRequestBuilderContext { Behaves_like<PayPalCommonRequestBehavior> a_paypal_nvp_request; Behaves_like<SetExpressCheckoutBehavior> set_express_checkout; It should_specify_the_paypal_locale_code = () => Request["LOCALECODE"].ShouldEqual(LocaleCode); Establish context = () => { Configuration.UseLocaleFromCurrentCulture = true; Culture.Current = new CultureInfo("da-DK"); }; Because of = () => Request = SUT.SetExpressCheckout(Amount, CurrencyCodeType.GBP, CancelUrl, ConfirmationUrl); Cleanup after = () => Culture.Reset(); protected const decimal Amount = 12.99m; const string LocaleCode = "da_DK"; } [Subject(typeof(PayPalRequestBuilder))] public class When_building_set_express_checkout_request_and_use_locale_from_current_culture_is_set_with_unsupported_culture : PayPalRequestBuilderContext { Behaves_like<PayPalCommonRequestBehavior> a_paypal_nvp_request; Behaves_like<SetExpressCheckoutBehavior> set_express_checkout; It should_not_specify_the_paypal_locale_code = () => Request["LOCALECODE"].ShouldBeNull(); Establish context = () => { Configuration.UseLocaleFromCurrentCulture = true; Culture.Current = new CultureInfo("af-ZA"); }; Because of = () => Request = SUT.SetExpressCheckout(Amount, CurrencyCodeType.GBP, CancelUrl, ConfirmationUrl); Cleanup after = () => Culture.Reset(); protected const decimal Amount = 12.99m; } [Behaviors] public class OrderDetailsBehavior { It should_specify_noshipping_field = () => Request["NOSHIPPING"].ShouldEqual(((int)OrderDetails.DisplayShippingAddress).ToString()); It should_specify_the_tax_value_for_the_order = () => Request["PAYMENTREQUEST_0_TAXAMT"].ShouldEqual(OrderDetails.TaxTotal.AsPayPalFormatString()); It should_specify_the_shipping_total = () => Request["PAYMENTREQUEST_0_SHIPPINGAMT"].ShouldEqual(OrderDetails.ShippingTotal.AsPayPalFormatString()); It should_specify_the_shipping_discount = () => Request["PAYMENTREQUEST_0_SHIPDISCAMT"].ShouldEqual(OrderDetails.ShippingDiscount.AsPayPalFormatString()); It should_specify_the_order_total = () => Request["PAYMENTREQUEST_0_AMT"].ShouldEqual(OrderDetails.OrderTotal.AsPayPalFormatString()); It should_specify_the_order_description = () => Request["PAYMENTREQUEST_0_DESC"].ShouldEqual(OrderDetails.OrderDescription); It should_include_each_line_description = () => { Request["L_PAYMENTREQUEST_0_DESC0"].ShouldEqual(OrderDetails.Items.First().Description); Request["L_PAYMENTREQUEST_0_DESC1"].ShouldEqual(OrderDetails.Items.Last().Description); }; It should_include_each_line_name = () => { Request["L_PAYMENTREQUEST_0_NAME0"].ShouldEqual(OrderDetails.Items.First().Name); Request["L_PAYMENTREQUEST_0_NAME1"].ShouldEqual(OrderDetails.Items.Last().Name); }; It should_include_each_line_number = () => { Request["L_PAYMENTREQUEST_0_NUMBER0"].ShouldEqual(OrderDetails.Items.First().Number.ToString()); Request["L_PAYMENTREQUEST_0_NUMBER1"].ShouldEqual(OrderDetails.Items.Last().Number.ToString()); }; It should_include_item_url_for_lines_where_specified = () => Request["L_PAYMENTREQUEST_0_ITEMURL0"].ShouldEqual(OrderDetails.Items.First().ItemUrl); It should_not_include_item_url_for_lines_where_not_specified = () => Request["L_PAYMENTREQUEST_n_ITEMURL1"].ShouldBeNull(); protected static OrderDetails OrderDetails; protected static NameValueCollection Request; } [Subject(typeof(PayPalRequestBuilder))] public class When_building_set_express_checkout_request_with_order_details : PayPalRequestBuilderContext { Behaves_like<PayPalCommonRequestBehavior> a_paypal_nvp_request; Behaves_like<OrderDetailsBehavior> add_oder_details; Because of = () => Request = SUT.SetExpressCheckout(OrderDetails, CancelUrl, ConfirmationUrl); protected static readonly OrderDetails OrderDetails = new OrderDetails { OrderDescription = "Some order", OrderTotal = 100m, DisplayShippingAddress = PayPalNoShipping.Required, ShippingDiscount = -7.9m, ShippingTotal = 0.54m, TaxTotal = 5m, Items = new[] { new OrderDetailsItem { Description = "First Item", Name = "FIRST", Number = 1, ItemUrl = "http://localhost/product?123&navigationid=3" }, new OrderDetailsItem { Description = "Second Item", Name = "2ND", Number = 2 } } }; } [Subject(typeof(PayPalRequestBuilder))] public class When_specifying_line_unit_prices : PayPalRequestBuilderContext { It should_include_item_total_in_the_request = () => Request["PAYMENTREQUEST_0_ITEMAMT"].ShouldNotBeNull(); It should_sum_the_unit_price_and_quantity_to_get_the_item_total = () => Request["PAYMENTREQUEST_0_ITEMAMT"].ShouldEqual("28.97"); It should_include_each_line_quantity = () => { Request["L_PAYMENTREQUEST_0_QTY0"].ShouldEqual(OrderDetails.Items.First().Quantity.ToString()); Request["L_PAYMENTREQUEST_0_QTY1"].ShouldEqual(OrderDetails.Items.Last().Quantity.ToString()); }; It should_include_each_line_unit_price = () => { Request["L_PAYMENTREQUEST_0_AMT0"].ShouldEqual(OrderDetails.Items.First().UnitPrice.AsPayPalFormatString()); Request["L_PAYMENTREQUEST_0_AMT1"].ShouldEqual(OrderDetails.Items.Last().UnitPrice.AsPayPalFormatString()); }; It should_include_each_line_tax_amount = () => { Request["L_PAYMENTREQUEST_0_TAXAMT0"].ShouldEqual(OrderDetails.Items.First().Tax.AsPayPalFormatString()); Request["L_PAYMENTREQUEST_0_TAXAMT1"].ShouldEqual(OrderDetails.Items.Last().Tax.AsPayPalFormatString()); }; Because of = () => Request = SUT.SetExpressCheckout(OrderDetails, CancelUrl, ConfirmationUrl); Establish context = () => OrderDetails = new OrderDetails { Items = new[] { new OrderDetailsItem { Quantity = 3, UnitPrice = 5.99m, Tax = 1.19m }, new OrderDetailsItem { Quantity = 1, UnitPrice = 11m, Tax = 2m } } }; static OrderDetails OrderDetails; } [Subject(typeof(PayPalRequestBuilder))] public class When_specifying_allow_note_to_set_express_checkout : PayPalRequestBuilderContext { It should_include_it_in_the_request = () => Request["ALLOWNOTE"].ShouldEqual("1"); Because of = () => Request = SUT.SetExpressCheckout(new OrderDetails { AllowNote = true }, CancelUrl, ConfirmationUrl); } [Subject(typeof(PayPalRequestBuilder))] public class When_specifying_not_to_allow_note_to_set_express_checkout : PayPalRequestBuilderContext { It should_include_it_in_the_request = () => Request["ALLOWNOTE"].ShouldEqual("0"); Because of = () => Request = SUT.SetExpressCheckout(new OrderDetails { AllowNote = false }, CancelUrl, ConfirmationUrl); } [Subject(typeof(PayPalRequestBuilder))] public class When_specifying_enable_buyer_marketing_email_opt_in_to_set_express_checkout : PayPalRequestBuilderContext { It should_include_it_in_the_request = () => Request["BUYEREMAILOPTINENABLE"].ShouldEqual("1"); Because of = () => Request = SUT.SetExpressCheckout(new OrderDetails { EnableCustomerMarketingEmailOptIn = true }, CancelUrl, ConfirmationUrl); } [Subject(typeof(PayPalRequestBuilder))] public class When_specifying_not_to_enable_buyer_marketing_email_opt_in_to_set_express_checkout : PayPalRequestBuilderContext { It should_include_it_in_the_request = () => Request["BUYEREMAILOPTINENABLE"].ShouldEqual("0"); Because of = () => Request = SUT.SetExpressCheckout(new OrderDetails { EnableCustomerMarketingEmailOptIn = false }, CancelUrl, ConfirmationUrl); } [Subject(typeof(PayPalRequestBuilder))] public class When_specifying_custom_field_to_set_express_checkout : PayPalRequestBuilderContext { It should_include_it_in_the_request = () => Request["PAYMENTREQUEST_0_CUSTOM"].ShouldEqual("some custom value"); Because of = () => Request = SUT.SetExpressCheckout(new OrderDetails { CustomField = "some custom value" }, CancelUrl, ConfirmationUrl); } [Subject(typeof(PayPalRequestBuilder))] public class When_building_set_express_checkout_request_with_partial_order_details : PayPalRequestBuilderContext { Behaves_like<PayPalCommonRequestBehavior> a_paypal_nvp_request; It should_include_the_specified_values = () => Request["PAYMENTREQUEST_0_AMT"].ShouldEqual(PartialOrderDetails.OrderTotal.AsPayPalFormatString()); It should_not_include_unspecified_fields = () => Request.AllKeys.ShouldNotContain(new[] { "PAYMENTREQUEST_0_ITEMAMT", "PAYMENTREQUEST_0_TAXAMT", "PAYMENTREQUEST_0_SHIPPINGAMT", "PAYMENTREQUEST_0_SHIPDISCAMT", "ALLOWNOTE", "PAYMENTREQUEST_0_DESC" }); It should_not_include_details_for_unspecified_lines = () => Request.AllKeys.Any(x => x.StartsWith("L_PAYMENTREQUEST_0_")).ShouldBeFalse(); Because of = () => Request = SUT.SetExpressCheckout(PartialOrderDetails, CancelUrl, ConfirmationUrl); static readonly OrderDetails PartialOrderDetails = new OrderDetails { OrderTotal = 100m }; } [Subject(typeof(PayPalRequestBuilder))] public class When_building_get_express_checkout_details_request : PayPalRequestBuilderContext { Behaves_like<PayPalCommonRequestBehavior> a_paypal_nvp_request; It should_specify_correct_method = () => Request["METHOD"].ShouldEqual("GetExpressCheckoutDetails"); It should_specify_the_paypal_token = () => Request["TOKEN"].ShouldEqual(PayPalToken); Because of = () => Request = SUT.GetExpressCheckoutDetails(PayPalToken); const string PayPalToken = "tokenValue"; } [Behaviors] public class DoExpressCheckoutPaymentRequestBehavior { It should_specify_correct_method = () => Request["METHOD"].ShouldEqual("DoExpressCheckoutPayment"); It should_specify_the_paypal_token = () => Request["TOKEN"].ShouldEqual(PayPalToken); It should_specify_the_paypal_payer_id = () => Request["PAYERID"].ShouldEqual(PayPalPayerId); It should_specify_currency_code = () => Request["PAYMENTREQUEST_0_CURRENCYCODE"].ShouldEqual("GBP"); It should_specify_sale_payment_action = () => Request["PAYMENTREQUEST_0_PAYMENTACTION"].ShouldEqual("Sale"); protected static NameValueCollection Request; protected static string PayPalToken; protected static string PayPalPayerId; } [Subject(typeof(PayPalRequestBuilder))] public class When_building_do_express_checkout_payment_request : PayPalRequestBuilderContext { Behaves_like<PayPalCommonRequestBehavior> a_paypal_nvp_request; Behaves_like<DoExpressCheckoutPaymentRequestBehavior> do_express_checkout_payment_request; It should_specify_formatted_amount = () => Request["PAYMENTREQUEST_0_AMT"].ShouldEqual(Amount.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)); Because of = () => Request = SUT.DoExpressCheckoutPayment(Amount, CurrencyCodeType.GBP, PayPalToken, PayPalPayerId); protected const string PayPalToken = "tokenValue"; protected const string PayPalPayerId = "payerId"; protected const decimal Amount = 12.99m; } [Subject(typeof(PayPalRequestBuilder))] public class When_building_do_express_checkout_payment_request_with_order_details : PayPalRequestBuilderContext { Behaves_like<PayPalCommonRequestBehavior> a_paypal_nvp_request; Behaves_like<DoExpressCheckoutPaymentRequestBehavior> do_express_checkout_payment_request; Behaves_like<OrderDetailsBehavior> add_order_details; It should_specify_formatted_amount = () => Request["PAYMENTREQUEST_0_AMT"].ShouldEqual(OrderDetails.OrderTotal.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)); Establish context = () => { OrderDetails = new OrderDetails { OrderDescription = "Some order", OrderTotal = 100m, ShippingDiscount = -7.9m, ShippingTotal = 0.54m, TaxTotal = 5m, CurrencyCodeType = CurrencyCodeType.GBP, Items = new[] { new OrderDetailsItem { Description = "First Item", Name = "FIRST", Number = 1, ItemUrl = "http://localhost/product?123&navigationid=3" }, new OrderDetailsItem { Description = "Second Item", Name = "2ND", Number = 2 } } }; }; Because of = () => Request = SUT.DoExpressCheckoutPayment(OrderDetails, PayPalToken, PayPalPayerId); protected static OrderDetails OrderDetails; protected const string PayPalToken = "tokenValue"; protected const string PayPalPayerId = "payerId"; } [Subject(typeof(PayPalRequestBuilder))] public class When_building_an_express_checkout_request_with_discounts : PayPalRequestBuilderContext { It should_include_the_order_lines = () => { Request["L_PAYMENTREQUEST_0_QTY0"].ShouldEqual(OrderDetails.Items.First().Quantity.ToString()); Request["L_PAYMENTREQUEST_0_AMT0"].ShouldEqual(OrderDetails.Items.First().UnitPrice.AsPayPalFormatString()); }; It should_include_discounts_as_other_lines_in_the_order = () => { Request["L_PAYMENTREQUEST_0_QTY1"].ShouldEqual("3"); Request["L_PAYMENTREQUEST_0_AMT1"].ShouldEqual("-1.00"); Request["L_PAYMENTREQUEST_0_NAME1"].ShouldEqual("Multi-buy discount, -1 per item."); Request["L_PAYMENTREQUEST_0_NAME2"].ShouldEqual("Loyalty discount"); }; It should_always_pass_discount_as_a_negative_value = () => Request["L_PAYMENTREQUEST_0_AMT2"].ShouldEqual("-0.50"); It should_always_pass_discount_tax_as_a_negative_value = () => Request["L_PAYMENTREQUEST_0_TAXAMT2"].ShouldEqual("-0.10"); It should_not_include_discount_quantity_if_not_specified = () => Request["L_PAYMENTREQUEST_0_QTY2"].ShouldBeNull(); It should_not_include_discount_tax_if_not_specified = () => Request["L_PAYMENTREQUEST_0_TAXAMT1"].ShouldBeNull(); Because of = () => Request = SUT.SetExpressCheckout(OrderDetails, CancelUrl, ConfirmationUrl); Establish context = () => OrderDetails = new OrderDetails { Items = new[] { new OrderDetailsItem { Quantity = 3, UnitPrice = 5m } }, Discounts = new[] { new DiscountDetails { Description = "Multi-buy discount, -1 per item.", Quantity = 3, Amount = -1m }, new DiscountDetails { Description = "Loyalty discount", // Discount can be passed as either positive or negative. Amount = 0.5m, Tax = 0.1m } }, OrderTotal = (3 * 5m) + (3 * -1m) - 0.5m }; static OrderDetails OrderDetails; } }
43.402827
157
0.593666
[ "Apache-2.0" ]
davidduffett/Moolah
Moolah/Moolah.Specs/PayPal/PayPalRequestBuilderSpec.cs
24,568
C#
using System.Collections.Generic; using System.Threading.Tasks; using ResearchXBRL.Application.DTO.ReverseLookupAccountItems; namespace ResearchXBRL.Application.QueryServices.ReverseLookupAccountItems; public interface IReverseLookupQueryService { ValueTask<IReadOnlyCollection<ReverseLookupResult>> Lookup(FinancialReport financialReport); }
32.636364
97
0.846797
[ "MIT" ]
Seibi0928/ResearchXBRL
ResearchXBRL.Application/QueryServices/ReverseLookupAccountItems/IReverseLookupQueryService.cs
359
C#
using System.Drawing; using Reactive.Bindings; namespace MvvmTetris.Engine.ViewModels { /// <summary> /// セル描画用のモデルを提供します。 /// </summary> public class CellViewModel { #region 定数 /// <summary> /// 既定の色を表します。 /// </summary> public static readonly Color DefaultColor = System.Drawing.Color.WhiteSmoke; #endregion #region プロパティ /// <summary> /// 色を取得します。 /// </summary> public ReactivePropertySlim<Color> Color { get; } = new ReactivePropertySlim<Color>(DefaultColor); #endregion } }
20.896552
106
0.580858
[ "MIT" ]
xin9le/MvvmTetris
src/MvvmTetris.Engine/ViewModels/CellViewModel.cs
690
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 medialive-2017-10-14.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.MediaLive.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.MediaLive.Model.Internal.MarshallTransformations { /// <summary> /// AacSettings Marshaller /// </summary> public class AacSettingsMarshaller : IRequestMarshaller<AacSettings, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(AacSettings requestObject, JsonMarshallerContext context) { if(requestObject.IsSetBitrate()) { context.Writer.WritePropertyName("bitrate"); context.Writer.Write(requestObject.Bitrate); } if(requestObject.IsSetCodingMode()) { context.Writer.WritePropertyName("codingMode"); context.Writer.Write(requestObject.CodingMode); } if(requestObject.IsSetInputType()) { context.Writer.WritePropertyName("inputType"); context.Writer.Write(requestObject.InputType); } if(requestObject.IsSetProfile()) { context.Writer.WritePropertyName("profile"); context.Writer.Write(requestObject.Profile); } if(requestObject.IsSetRateControlMode()) { context.Writer.WritePropertyName("rateControlMode"); context.Writer.Write(requestObject.RateControlMode); } if(requestObject.IsSetRawFormat()) { context.Writer.WritePropertyName("rawFormat"); context.Writer.Write(requestObject.RawFormat); } if(requestObject.IsSetSampleRate()) { context.Writer.WritePropertyName("sampleRate"); context.Writer.Write(requestObject.SampleRate); } if(requestObject.IsSetSpec()) { context.Writer.WritePropertyName("spec"); context.Writer.Write(requestObject.Spec); } if(requestObject.IsSetVbrQuality()) { context.Writer.WritePropertyName("vbrQuality"); context.Writer.Write(requestObject.VbrQuality); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static AacSettingsMarshaller Instance = new AacSettingsMarshaller(); } }
34.027273
108
0.59845
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/MediaLive/Generated/Model/Internal/MarshallTransformations/AacSettingsMarshaller.cs
3,743
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Chiro.CiviSync.Logic.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Chiro.CiviSync.Logic.Test")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("62accd89-c540-41c9-85dc-a14c9d96f9a7")] // 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.444444
84
0.742052
[ "Apache-2.0" ]
Chirojeugd-Vlaanderen/gap
tools/Chiro.CiviSync/Chiro.CiviSync.Logic.Test/Properties/AssemblyInfo.cs
1,387
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18444 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CurveLock.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("True")] public bool IsFirstRun { get { return ((bool)(this["IsFirstRun"])); } set { this["IsFirstRun"] = value; } } } }
38.179487
151
0.568167
[ "MIT" ]
BuloZB/CurveLock
src/CurveLock/Properties/Settings.Designer.cs
1,491
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; public struct doublesStruct { public double f1; public double f2; public double f3; public double f4; } public class A { static bool foo(doublesStruct d1, doublesStruct d2, doublesStruct d3) { bool success = (d1.f1 == 1 && d1.f2 == 2 && d1.f3 == 3 && d1.f4 == 4 && d2.f1 == 11 && d2.f2 == 22 && d2.f3 == 33 && d2.f4 == 44 && d3.f1 == 111 && d3.f2 == 222 && d3.f3 == 333 && d3.f4 == 444); if (!success) { Console.WriteLine(string.Format("{0}, {1}, {2}, {3}", d1.f1, d1.f2, d1.f3, d1.f4)); Console.WriteLine(string.Format("{0}, {1}, {2}, {3}", d2.f1, d2.f2, d2.f3, d2.f4)); Console.WriteLine(string.Format("{0}, {1}, {2}, {3}", d3.f1, d3.f2, d3.f3, d3.f4)); } return success; } public static int Main(string[] args) { // Test that a function with HFA args gets the expected contents of the structs. var ds = new doublesStruct(); ds.f1 = 1; ds.f2 = 2; ds.f3 = 3; ds.f4 = 4; var ds2 = new doublesStruct(); ds2.f1 = 11; ds2.f2 = 22; ds2.f3 = 33; ds2.f4 = 44; var ds3 = new doublesStruct(); ds3.f1 = 111; ds3.f2 = 222; ds3.f3 = 333; ds3.f4 = 444; return (foo(ds, ds2, ds3) ? 100 : -1); } }
26.132353
95
0.435566
[ "MIT" ]
2m0nd/runtime
src/tests/JIT/Methodical/Invoke/hfa_params/hfa_params.cs
1,777
C#
namespace TailwindTraders.Mobile.Features.Product.Detail { public partial class ProductDetailPage { public ProductDetailPage(int productId) { InitializeComponent(); BindingContext = new ProductDetailViewModel(productId); } protected override void OnAppearing() { base.OnAppearing(); NavigationProxy.Inner = App.NavigationRoot.NavigationProxy; } } }
23.05
71
0.62256
[ "MIT" ]
Lazareena/TailwindTraders-Mobile
Source/TailwindTraders.Mobile/TailwindTraders.Mobile/Features/Product/Detail/ProductDetailPage.xaml.cs
463
C#
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using ICSharpCode.SharpDevelop.Dom; using ICSharpCode.UnitTesting; using NUnit.Framework; namespace UnitTesting.Tests.Utils.Tests { [TestFixture] public class MockFileServiceTestFixture { MockFileService fileService; [SetUp] public void Init() { fileService = new MockFileService(); } [Test] public void FileOpenedReturnsNullByDefault() { Assert.IsNull(fileService.FileOpened); } [Test] public void FileOpenedReturnsFileNamePassedToOpenFileMethod() { fileService.OpenFile("test.cs"); Assert.AreEqual("test.cs", fileService.FileOpened); } [Test] public void FilePositionsAreEqualWhenFileNameAndPositionAreEqual() { FilePosition lhs = new FilePosition("test.cs", 1, 2); FilePosition rhs = new FilePosition("test.cs", 1, 2); Assert.AreEqual(lhs, rhs); } [Test] public void FilePositionEqualsReturnsFalseWhenNullPassed() { FilePosition lhs = new FilePosition("test.cs", 1, 2); Assert.IsFalse(lhs.Equals(null)); } [Test] public void FilePositionsAreNotEqualWhenFileNamesAreNotEqual() { FilePosition lhs = new FilePosition("test1.cs", 1, 2); FilePosition rhs = new FilePosition("test2.cs", 1, 2); Assert.AreNotEqual(lhs, rhs); } [Test] public void FilePositionsAreNotEqualWhenLinesAreNotEqual() { FilePosition lhs = new FilePosition("test.cs", 500, 2); FilePosition rhs = new FilePosition("test.cs", 1, 2); Assert.AreNotEqual(lhs, rhs); } [Test] public void FilePositionsAreNotEqualWhenColumnsAreNotEqual() { FilePosition lhs = new FilePosition("test.cs", 1, 2000); FilePosition rhs = new FilePosition("test.cs", 1, 2); Assert.AreNotEqual(lhs, rhs); } [Test] public void FilePositionJumpedToIsNullByDefault() { Assert.IsNull(fileService.FilePositionJumpedTo); } [Test] public void FilePositionJumpedToReturnsParametersPassedToJumpToFilePositionMethod() { int line = 1; int col = 10; string fileName = "test.cs"; fileService.JumpToFilePosition(fileName, line, col); FilePosition expectedFilePos = new FilePosition(fileName, line, col); Assert.AreEqual(expectedFilePos, fileService.FilePositionJumpedTo); } } }
24.765306
103
0.71611
[ "MIT" ]
Plankankul/SharpDevelop-w-Framework
src/AddIns/Analysis/UnitTesting/Test/Utils/Tests/MockFileServiceTestFixture.cs
2,429
C#
// Rigidbody Follow|Utilities|90061 namespace VRTK { using UnityEngine; /// <summary> /// Changes one game object's rigidbody to follow another game object's rigidbody. /// </summary> [AddComponentMenu("VRTK/Scripts/Utilities/Object Follow/VRTK_RigidbodyFollow")] public class VRTK_RigidbodyFollow : VRTK_ObjectFollow { /// <summary> /// Specifies how to position and rotate the rigidbody. /// </summary> /// <param name="Set">Use <see cref="Rigidbody.position"/> and <see cref="Rigidbody.rotation"/>.</param> /// <param name="Move">Use <see cref="Rigidbody.MovePosition"/> and <see cref="Rigidbody.MoveRotation"/>.</param> /// <param name="Add">Use <see cref="Rigidbody.AddForce(Vector3)"/> and <see cref="Rigidbody.AddTorque(Vector3)"/>.</param> public enum MovementOption { Set, Move, Add } [Tooltip("Specifies how to position and rotate the rigidbody.")] public MovementOption movementOption = MovementOption.Set; protected Rigidbody rigidbodyToFollow; protected Rigidbody rigidbodyToChange; public override void Follow() { CacheRigidbodies(); base.Follow(); } protected virtual void OnDisable() { rigidbodyToFollow = null; rigidbodyToChange = null; } protected virtual void FixedUpdate() { Follow(); } protected override Vector3 GetPositionToFollow() { return rigidbodyToFollow.position; } protected override void SetPositionOnGameObject(Vector3 newPosition) { switch (movementOption) { case MovementOption.Set: rigidbodyToChange.position = newPosition; break; case MovementOption.Move: rigidbodyToChange.MovePosition(newPosition); break; case MovementOption.Add: // TODO: Test if this is correct rigidbodyToChange.AddForce(newPosition - rigidbodyToChange.position); break; } } protected override Quaternion GetRotationToFollow() { return rigidbodyToFollow.rotation; } protected override void SetRotationOnGameObject(Quaternion newRotation) { switch (movementOption) { case MovementOption.Set: rigidbodyToChange.rotation = newRotation; break; case MovementOption.Move: rigidbodyToChange.MoveRotation(newRotation); break; case MovementOption.Add: // TODO: Test if this is correct rigidbodyToChange.AddTorque(newRotation * Quaternion.Inverse(rigidbodyToChange.rotation).eulerAngles); break; } } protected override Vector3 GetScaleToFollow() { return rigidbodyToFollow.transform.localScale; } protected virtual void CacheRigidbodies() { if (gameObjectToFollow == null || gameObjectToChange == null || (rigidbodyToFollow != null && rigidbodyToChange != null)) { return; } rigidbodyToFollow = gameObjectToFollow.GetComponent<Rigidbody>(); rigidbodyToChange = gameObjectToChange.GetComponent<Rigidbody>(); } } }
34.458716
132
0.54819
[ "MIT" ]
AmrMKayid/Wheelchair-Waiter
Assets/VRTK/Scripts/Utilities/ObjectFollow/VRTK_RigidbodyFollow.cs
3,758
C#
using System; using System.Runtime.InteropServices; namespace LibGit2Sharp.Core { /// <summary> /// Structure for git_remote_callbacks /// </summary> [StructLayout(LayoutKind.Sequential)] internal struct GitRemoteCallbacks { internal uint version; internal NativeMethods.remote_progress_callback progress; internal NativeMethods.remote_completion_callback completion; internal NativeMethods.git_cred_acquire_cb acquire_credentials; internal NativeMethods.git_transport_certificate_check_cb certificate_check; internal NativeMethods.git_transfer_progress_callback download_progress; internal NativeMethods.remote_update_tips_callback update_tips; internal NativeMethods.git_packbuilder_progress pack_progress; internal NativeMethods.git_push_transfer_progress push_transfer_progress; internal NativeMethods.push_update_reference_callback push_update_reference; internal NativeMethods.push_negotiation_callback push_negotiation; internal IntPtr transport; private IntPtr padding; // TODO: add git_remote_ready_cb internal IntPtr payload; internal NativeMethods.url_resolve_callback resolve_url; } }
29.325581
84
0.768438
[ "MIT" ]
MikeTV/libgit2sharp
LibGit2Sharp/Core/GitRemoteCallbacks.cs
1,263
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 email-2010-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SimpleEmail.Model { /// <summary> /// Indicates that the TrackingOptions object you specified does not exist. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class TrackingOptionsDoesNotExistException : AmazonSimpleEmailServiceException { private string _configurationSetName; /// <summary> /// Constructs a new TrackingOptionsDoesNotExistException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public TrackingOptionsDoesNotExistException(string message) : base(message) {} /// <summary> /// Construct instance of TrackingOptionsDoesNotExistException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public TrackingOptionsDoesNotExistException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of TrackingOptionsDoesNotExistException /// </summary> /// <param name="innerException"></param> public TrackingOptionsDoesNotExistException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of TrackingOptionsDoesNotExistException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public TrackingOptionsDoesNotExistException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of TrackingOptionsDoesNotExistException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public TrackingOptionsDoesNotExistException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the TrackingOptionsDoesNotExistException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected TrackingOptionsDoesNotExistException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { this.ConfigurationSetName = (string)info.GetValue("ConfigurationSetName", typeof(string)); } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); info.AddValue("ConfigurationSetName", this.ConfigurationSetName); } #endif /// <summary> /// Gets and sets the property ConfigurationSetName. /// <para> /// Indicates that a TrackingOptions object does not exist in the specified configuration /// set. /// </para> /// </summary> public string ConfigurationSetName { get { return this._configurationSetName; } set { this._configurationSetName = value; } } // Check to see if ConfigurationSetName property is set internal bool IsSetConfigurationSetName() { return this._configurationSetName != null; } } }
48.027397
179
0.665573
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/SimpleEmail/Generated/Model/TrackingOptionsDoesNotExistException.cs
7,012
C#
/* --------------------------- * SharePoint Manager 2010 v2 * Created by Carsten Keutmann * --------------------------- */ using System; using Microsoft.SharePoint; using Microsoft.SharePoint.Administration; using SPM2.Framework; namespace SPM2.SharePoint.Model { [Title(PropertyName="DisplayName")] [Icon(Small="BULLET.GIF")][View(50)] [ExportToNode("SPM2.SharePoint.Model.SPServiceApplicationProxyCollectionNode")] public partial class SPServiceApplicationProxyNode { } }
22.136364
80
0.687885
[ "MIT" ]
keutmann/SPM
Libraries/SPM2.SharePoint/Model/Custom/SPServiceApplicationProxyNode.cs
487
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.SqlServer.Management.Assessment; namespace Microsoft.SqlTools.ServiceLayer.Migration.Contracts { /// <summary> /// Describes an item returned by SQL Assessment RPC methods /// </summary> public class MigrationAssessmentInfo { /// <summary> /// Gets or sets assessment ruleset version. /// </summary> public string RulesetVersion { get; set; } /// <summary> /// Gets or sets assessment ruleset name /// </summary> public string RulesetName { get; set; } /// <summary> /// Gets or sets assessment ruleset name /// </summary> public string RuleId { get; set; } /// <summary> /// Gets or sets the assessed object's name. /// </summary> public string TargetType { get; set; } /// <summary> /// Gets or sets the database name. /// </summary> public string DatabaseName { get; set; } /// <summary> /// Gets or sets the server name. /// </summary> public string ServerName { get; set; } /// <summary> /// Gets or sets check's ID. /// </summary> public string CheckId { get; set; } /// <summary> /// Gets or sets tags assigned to this item. /// </summary> public string[] Tags { get; set; } /// <summary> /// Gets or sets a display name for this item. /// </summary> public string DisplayName { get; set; } /// <summary> /// Gets or sets a brief description of the item's purpose. /// </summary> public string Description { get; set; } /// <summary> /// Gets or sets a <see cref="string"/> containing /// an link to a page providing detailed explanation /// of the best practice. /// </summary> public string HelpLink { get; set; } /// <summary> /// Gets or sets a <see cref="string"/> indicating /// severity level assigned to this items. /// Values are: "Information", "Warning", "Critical". /// </summary> public string Level { get; set; } public string Message { get; set; } public string AppliesToMigrationTargetPlatform { get; set; } public string IssueCategory { get; set; } public ImpactedObjectInfo[] ImpactedObjects { get; set; } /// <summary> /// This flag is set if the assessment result is a blocker for migration to Target Platform. /// </summary> public bool DatabaseRestoreFails { get; set; } } }
30.193548
101
0.560541
[ "MIT" ]
microsoft/sqltoolsservice
src/Microsoft.SqlTools.ServiceLayer/Migration/Contracts/MigrationAssessmentInfo.cs
2,808
C#
using System; using System.Collections.Generic; using System.Linq; using qcloudsms_csharp; using Shashlik.Kernel.Attributes; using Shashlik.Sms.Exceptions; using Shashlik.Sms.Options; using Shashlik.Utils.Extensions; namespace Shashlik.Sms.Domains { /// <summary> /// 手机短信 /// </summary> [ConditionOnProperty(typeof(bool), "Shashlik.Sms.Enable", true, DefaultValue = true)] public class TencentSms : ISmsDomain { public string SmsDomain => "tencent"; public void Send(SmsDomainConfig options, IEnumerable<string> phones, string subject, params string[] args) { var template = options.Templates.FirstOrDefault(r => r.Subject.EqualsIgnoreCase(subject)); var list = phones.ToList(); try { var res = new SmsMultiSender(options.AppId.ParseTo<int>(), options.AppKey) .sendWithParam(options.Region.IsNullOrWhiteSpace() ? "86" : options.Region, list.ToArray(), template!.TemplateId.ParseTo<int>(), args, template.Sign, "", ""); if (res.result != 0) throw new SmsDomainException($"tencent cloud sms send failed, error:{res.errMsg}, phone: {list.Join(",")}"); } catch (Exception ex) { throw new SmsDomainException($"tencent cloud sms send failed, phones: {list.Join(",")}", ex); } } } }
37.075
148
0.593392
[ "MIT" ]
dotnet-shashlik/shashlik
src/Shashlik.Sms/Domains/TencentSms.cs
1,493
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 Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.RazorPages; namespace Smallprogram.Server.Areas.Identity.Pages.Account { /// <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> [AllowAnonymous] public class ResetPasswordConfirmationModel : PageModel { /// <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 void OnGet() { } } }
36.346154
116
0.68254
[ "MIT" ]
smallprogram/Openiddict_Samples
ZhuSir_Openiddict_Samples/Smallprogram.Server/Areas/Identity/Pages/Account/ResetPasswordConfirmation.cshtml.cs
947
C#
using System.Collections.Generic; using System.Linq; using AuthorBookGraphQLAPI.Data; using AuthorBookGraphQLAPI.Models; namespace AuthorBookGraphQLAPI.Repositories { public class LibraryRepository : ILibraryRepository { private LibraryContext _context; public LibraryRepository(LibraryContext context) { _context = context; } public void AddAuthor(Author author) { _context.Authors.Add(author); // the repository fills the id (instead of using identity columns) if (!author.Books.Any()) return; foreach (var book in author.Books) { AddBookForAuthor(author.AuthorId, book); } } public void AddBookForAuthor(int authorId, Book book) { var author = GetAuthor(authorId); author?.Books.Add(book); } public bool AuthorExists(int authorId) { return _context.Authors.Any(a => a.AuthorId == authorId); } public void DeleteAuthor(Author author) { _context.Authors.Remove(author); } public void DeleteBook(Book book) { _context.Books.Remove(book); } public Author GetAuthor(int authorId) { return _context.Authors.FirstOrDefault(a => a.AuthorId == authorId); } public IEnumerable<Author> GetAuthors() { return _context.Authors.OrderBy(a => a.Name); } public IEnumerable<Author> GetAuthors(IEnumerable<int> authorIds) { return _context.Authors.Where(a => authorIds.Contains(a.AuthorId)) .OrderBy(a => a.Name) .ToList(); } public void UpdateAuthor(Author author) { _context.Update(author); _context.Entry(author).State = Microsoft.EntityFrameworkCore.EntityState.Modified; } public Book GetBookForAuthor(int authorId, int bookId) { return _context.Books.FirstOrDefault(b => b.AuthorId == authorId && b.BookId == bookId); } public IEnumerable<Book> GetBooksForAuthor(int authorId) { return _context.Books .Where(b => b.AuthorId == authorId).OrderBy(b => b.Title).ToList(); } public void UpdateBookForAuthor(Book book) { _context.Attach(book); _context.Entry(book).State = Microsoft.EntityFrameworkCore.EntityState.Modified; } public bool Save() { return (_context.SaveChanges() >= 0); } } }
28.273684
100
0.571482
[ "MIT" ]
gfawcett22/AuthorBookGraphQLAPI
Repositories/LibraryRepository.cs
2,688
C#
using BobTheBuilder.Syntax; using AutoFixture.Xunit2; using Xunit; namespace BobTheBuilder.Tests { public class ObjectLiteralSyntaxFacts { [Theory, AutoData] public void SetStringStateByNameUsingObjectLiteral(string Name) { var sut = A.BuilderFor<Person>(); sut.With(new { Name }); Person result = sut.Build(); Assert.Equal(Name, result.Name); } [Theory, AutoData] public void SetStringAndIntStateByNameUsingNamedArgument(string Name, int AgeInYears) { var sut = A.BuilderFor<Person>(); sut.With(new { Name, AgeInYears }); Person result = sut.Build(); var expected = new Person { Name = Name, AgeInYears = AgeInYears }; Assert.Equal(expected, result, new PersonEqualityComparer()); } [Fact] public void ThrowAnArgumentExceptionWhenMoreThanOneArgumentIsSuppliedForTheObjectLiteralSyntax() { var sut = A.BuilderFor<Person>(); var exception = Assert.Throws<ParseException>(() => sut.With(1, 2)); Assert.Contains("Expected a single object of an anonymous type, but was passed 2 arguments. Try replacing these arguments with an anonymous type composing the arguments.", exception.Message); } [Fact] public void ThrowAnArgumentExceptionWhenPassedSomethingOtherThanAnObjectLiteral() { var sut = A.BuilderFor<Person>(); var exception = Assert.Throws<ParseException>(() => sut.With(5)); Assert.Contains("Expected a single object of an anonymous type, but was passed an object of type System.Int32", exception.Message); } } }
33.615385
203
0.632151
[ "Apache-2.0" ]
alastairs/BobTheBuilder
BobTheBuilder.Tests/ObjectLiteralSyntaxFacts.cs
1,750
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace MovieApp.API.Models { public class MovieModel { [Key] public Guid Id { get; set; } [Required] public string Name { get; set; } public DateTime DateCreated { get; set; } public byte[] Picture { get; set; } public enum RatingType { Poor, Average, BlockBuster} public RatingType Rating { get; set; } [Required] public Guid GenreId { get; set; } [ForeignKey("GenreId")] public virtual GenreModel Genres { get; set; } [Required] public Guid SubGenreId { get; set; } [ForeignKey("SubGenreId")] public virtual SubGenreModel SubGenres { get; set; } public enum AudienceType { U, PG, TWELVEA, FIFTEEN, EIGHTEEN } public AudienceType Audience { get; set; } } }
30.757576
70
0.635468
[ "MIT" ]
Iamkemical/-MovieApp
MovieApp.API/Models/MovieModel.cs
1,017
C#
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace booksapi.Models { [NotMapped] public class AuthenticateModel { [Required] public string Email { get; set; } [Required] public string Password { get; set; } } }
19.875
51
0.663522
[ "MIT" ]
vimendes/NetCoreAngular
booksapi/Models/AuthenticateModel.cs
320
C#
#region License // Copyright (c) 2009, ClearCanvas Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of ClearCanvas Inc. nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. #endregion using System.Configuration; namespace ClearCanvas.Dicom.ServiceModel.Streaming { [SettingsGroupDescription("Provides streaming settings.")] internal sealed partial class StreamingSettings { private StreamingSettings() { } } }
43.477273
87
0.739676
[ "Apache-2.0" ]
econmed/ImageServer20
Dicom/ServiceModel/Streaming/StreamingSettings.cs
1,915
C#
namespace quotes.Areas.HelpPage.ModelDescriptions { public class KeyValuePairModelDescription : ModelDescription { public ModelDescription KeyModelDescription { get; set; } public ModelDescription ValueModelDescription { get; set; } } }
29.444444
67
0.739623
[ "Apache-2.0" ]
DonSchenck/quotes
quotes/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs
265
C#
using System; using System.Collections.Generic; namespace SKIT.FlurlHttpClient.Wechat.Api.Models { /// <summary> /// <para>表示 [POST] /customservice/kfaccount/del 接口的请求。</para> /// </summary> public class CustomServiceKfAccountDeleteRequest : WechatApiRequest { /// <summary> /// 获取或设置客服账号。 /// </summary> [Newtonsoft.Json.JsonProperty("kf_account")] [System.Text.Json.Serialization.JsonPropertyName("kf_account")] public string KfAccount { get; set; } = string.Empty; } }
28.736842
71
0.64652
[ "MIT" ]
KimMeng2015/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Models/CustomService/KfAccount/CustomServiceKfAccountDeleteRequest.cs
584
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace EnglishStartServer.Database.Models { public class Course { public Guid Id { get; set; } [Required] [MaxLength(40)] public string Name { get; set; } [Required] public string Description { get; set; } [Required] [Range(1, 6)] public int DiffictlyLevel { get; set; } public DateTime DateCreated { get; set; } public List<Article> Articles { get; set; } = new List<Article>(); public List<ApplicationUserCourse> UserCourses { get; set; } = new List<ApplicationUserCourse>(); } }
25.62963
105
0.621387
[ "MIT" ]
vladkolodka/english_start_server
EnglishStartServer.Database/Models/Course.cs
694
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 System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Roslyn.Utilities { internal static partial class AsyncEnumerable { public static IAsyncEnumerable<T> Concat<T>( this IAsyncEnumerable<T> first, IAsyncEnumerable<T> second) { return new ConcatAsyncEnumerable<T>(first, second); } private class ConcatAsyncEnumerable<T> : IAsyncEnumerable<T> { private readonly IAsyncEnumerable<T> _first; private readonly IAsyncEnumerable<T> _second; public ConcatAsyncEnumerable(IAsyncEnumerable<T> first, IAsyncEnumerable<T> second) { _first = first; _second = second; } public IAsyncEnumerator<T> GetEnumerator() { return new ConcatAsyncEnumerator<T>(_first.GetEnumerator(), _second.GetEnumerator()); } } private class ConcatAsyncEnumerator<T> : IAsyncEnumerator<T> { private readonly IAsyncEnumerator<T> _first; private readonly IAsyncEnumerator<T> _second; private IAsyncEnumerator<T> _currentEnumerator; public ConcatAsyncEnumerator(IAsyncEnumerator<T> first, IAsyncEnumerator<T> second) { _first = first; _second = second; _currentEnumerator = first; } public T Current { get; private set; } public async Task<bool> MoveNextAsync(CancellationToken cancellationToken) { while (true) { var currentEnumeratorMoveNext = await _currentEnumerator.MoveNextAsync(cancellationToken).ConfigureAwait(false); // The current enumerator moved forward successfully. Get it's current // value and store it, and return true to let the caller know we moved. if (currentEnumeratorMoveNext) { this.Current = _currentEnumerator.Current; return true; } // Current enumerator didn't move forward. If it's the second enumerator // then we're done. if (_currentEnumerator == _second) { this.Current = default(T); return false; } // The first enumerator finished. Set our current enumerator to the // second enumerator and then recurse. _currentEnumerator = _second; } } public void Dispose() { _first.Dispose(); _second.Dispose(); } } } }
34.153846
161
0.55148
[ "Apache-2.0" ]
DavidKarlas/roslyn
src/Workspaces/Core/Portable/Utilities/Async/AsyncEnumerable_Concat.cs
3,110
C#
// // Author: // Aaron Bockover <[email protected]> // // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows.Input; namespace Xamarin.Interactive.TreeModel { class TreeNode : INotifyPropertyChanged, INotifyPropertyChanging { public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangingEventHandler PropertyChanging; protected virtual void NotifyPropertyChanged ([CallerMemberName] string propertyName = null) => PropertyChanged?.Invoke (this, new PropertyChangedEventArgs (propertyName)); protected virtual void NotifyPropertyChanging ([CallerMemberName] string propertyName = null) => PropertyChanging?.Invoke (this, new PropertyChangingEventArgs (propertyName)); IReadOnlyList<TreeNode> children; public IReadOnlyList<TreeNode> Children { get { return children; } set { if (children != value) { NotifyPropertyChanging (); children = value; NotifyPropertyChanged (); } } } object representedObject; public virtual object RepresentedObject { get { return representedObject; } set { if (representedObject != value) { representedObject = value; NotifyPropertyChanged (); } } } string id; public string Id { get { return id; } set { if (id != value) { id = value; NotifyPropertyChanged (); } } } string iconName; public string IconName { get { return iconName; } set { if (iconName != value) { iconName = value; NotifyPropertyChanged (); } } } string name; public virtual string Name { get { return name; } set { if (name != value) { name = value; NotifyPropertyChanged (); } } } string toolTip; public string ToolTip { get { return toolTip; } set { if (toolTip != value) { toolTip = value; NotifyPropertyChanged (); } } } bool isExpanded; public bool IsExpanded { get { return isExpanded; } set { if (isExpanded != value) { isExpanded = value; NotifyPropertyChanged (); } } } bool isSelectable; public bool IsSelectable { get { return isSelectable; } set { if (isSelectable != value) { isSelectable = value; NotifyPropertyChanged (); NotifyPropertyChanged (nameof (IsSelected)); } } } bool isSelected; public bool IsSelected { get => isSelected && isSelectable; set { if (isSelected != value) { isSelected = value; NotifyPropertyChanged (); } } } bool isMouseOver; public bool IsMouseOver { get => isMouseOver; set { if (isMouseOver != value) { isMouseOver = value; NotifyPropertyChanged (); } } } bool isRenamable; public bool IsRenamable { get { return isRenamable; } set { if (isRenamable != value) { isRenamable = value; NotifyPropertyChanged (); } } } bool isEditing; public bool IsEditing { get { return isEditing; } set { if (isEditing != value) { isEditing = value; NotifyPropertyChanged (); } } } IReadOnlyList<ICommand> commands; public IReadOnlyList<ICommand> Commands { get { return commands; } set { if (commands != value) { commands = value; NotifyPropertyChanged (); } } } ICommand defaultCommand; public ICommand DefaultCommand { get { return defaultCommand; } set { if (defaultCommand != value) { defaultCommand = value; NotifyPropertyChanged (); } } } } }
28.236264
101
0.459039
[ "MIT" ]
Bhaskers-Blu-Org2/workbooks
Clients/Xamarin.Interactive.Client/TreeModel/TreeNode.cs
5,139
C#
using System.Collections.Generic; namespace GoogleMapsApiDotNet.GeocodingApi.Domain.Response { public class GeocodingResponse { public List<Result> Results { get; set; } public string Status { get; set; } } }
21.7
58
0.75576
[ "MIT" ]
UraPortuga/GoogleMapsApiDotNet
GoogleMapsApiDotNet/GoogleMapsApiDotNet.GeocodingApi/Domain/Response/GeocodingResponse.cs
219
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("StageOne.Domain")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("StageOne.Domain")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("fae866db-17f4-4d36-93f1-832c16033239")] // 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")]
37.783784
84
0.747496
[ "MIT" ]
DevlinLiles/PresentationMaterials
ObjectDesignBasics/StageOne.Domain/Properties/AssemblyInfo.cs
1,401
C#
using System.Web.Mvc; using DotNetNuke.Common; using Connect.DNN.Modules.Conference.Common; using Connect.Conference.Core.Repositories; using Connect.Conference.Core.Models.Conferences; using Connect.Conference.Core.Common; using System.Web; namespace Connect.DNN.Modules.Conference.Controllers { public class ConferenceController : ConferenceMvcController { private readonly IConferenceRepository _repository; public ConferenceController() : this(ConferenceRepository.Instance) { } public ConferenceController(IConferenceRepository repository) { Requires.NotNull(repository); _repository = repository; } [HttpGet] [ConferenceAuthorize(SecurityLevel = SecurityAccessLevel.ManageConference)] public ActionResult TracksLocationsSlots(int conferenceId) { var conference = _repository.GetConference(PortalSettings.PortalId, conferenceId); if (conference == null) { conference = new Connect.Conference.Core.Models.Conferences.Conference() { PortalId = PortalSettings.PortalId }; } DotNetNuke.Framework.ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); return View(conference); } [HttpGet] [ConferenceAuthorize(SecurityLevel = SecurityAccessLevel.ManageConference)] public ActionResult SessionsSpeakers(int conferenceId) { var conference = _repository.GetConference(PortalSettings.PortalId, conferenceId); if (conference == null) { conference = new Connect.Conference.Core.Models.Conferences.Conference() { PortalId = PortalSettings.PortalId }; } DotNetNuke.Framework.ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); return View(conference); } [HttpGet] [ConferenceAuthorize(SecurityLevel = SecurityAccessLevel.ManageConference)] public ActionResult Sessions(int conferenceId) { var conference = _repository.GetConference(PortalSettings.PortalId, conferenceId); if (conference == null) { conference = new Connect.Conference.Core.Models.Conferences.Conference() { PortalId = PortalSettings.PortalId }; } DotNetNuke.Framework.ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); return View(conference); } [HttpGet] [ConferenceAuthorize(SecurityLevel = SecurityAccessLevel.ManageConference)] public ActionResult Speakers(int conferenceId) { var conference = _repository.GetConference(PortalSettings.PortalId, conferenceId); if (conference == null) { conference = new Connect.Conference.Core.Models.Conferences.Conference() { PortalId = PortalSettings.PortalId }; } DotNetNuke.Framework.ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); return View(conference); } [HttpGet] [ConferenceAuthorize(SecurityLevel = SecurityAccessLevel.ManageConference)] public ActionResult Attendees(int conferenceId) { var conference = _repository.GetConference(PortalSettings.PortalId, conferenceId); if (conference == null) { conference = new Connect.Conference.Core.Models.Conferences.Conference() { PortalId = PortalSettings.PortalId }; } DotNetNuke.Framework.ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); return View(conference); } [HttpGet] public ActionResult View(int conferenceId) { DotNetNuke.Framework.ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); return View(_repository.GetConference(PortalSettings.PortalId, conferenceId)); } [HttpGet] [ConferenceAuthorize(SecurityLevel = SecurityAccessLevel.ManageConference)] public ActionResult Delete(int conferenceId) { var conference = _repository.GetConference(PortalSettings.PortalId, conferenceId); if (conference != null) { _repository.DeleteConference(conference.GetConferenceBase()); } return RedirectToDefaultRoute(); } [HttpGet] [ConferenceAuthorize(SecurityLevel = SecurityAccessLevel.ManageConference)] public ActionResult Manage(int conferenceId) { DotNetNuke.Framework.ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); return View(_repository.GetConference(PortalSettings.PortalId, conferenceId)); } [HttpGet] [ConferenceAuthorize(SecurityLevel = SecurityAccessLevel.ManageConference)] public ActionResult Schedule(int conferenceId) { DotNetNuke.Framework.ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); return View(_repository.GetConference(PortalSettings.PortalId, conferenceId)); } [HttpGet] [ConferenceAuthorize(SecurityLevel = SecurityAccessLevel.ManageConference)] public ActionResult Edit(int conferenceId) { var conference = _repository.GetConference(PortalSettings.PortalId, conferenceId); if (conference == null) { conference = new Connect.Conference.Core.Models.Conferences.Conference() { PortalId = PortalSettings.PortalId }; } DotNetNuke.Framework.ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); return View(conference.GetConferenceBase()); } [HttpPost] [ValidateAntiForgeryToken] [ConferenceAuthorize(SecurityLevel = SecurityAccessLevel.ManageConference)] public ActionResult Edit(ConferenceBase conference, HttpPostedFileBase image) { conference.Location = conference.Location.TrimSafeNull(); conference.MqttBroker = conference.MqttBroker.TrimSafeNull(); conference.MqttBrokerPassword = conference.MqttBrokerPassword.TrimSafeNull(); conference.MqttBrokerUsername = conference.MqttBrokerUsername.TrimSafeNull(); conference.Name = conference.Name.Trim(); conference.Url = conference.Url.TrimSafeNull(); if (conference.BaseTopicPath != null) conference.BaseTopicPath = conference.BaseTopicPath.TrimEnd('#').TrimEnd('/') + "/"; var previousRecord = _repository.GetConference(PortalSettings.PortalId, conference.ConferenceId); if (previousRecord == null) { conference.PortalId = PortalSettings.PortalId; _repository.AddConference(ref conference, User.UserID); } else { conference.CreatedOnDate = previousRecord.CreatedOnDate; conference.CreatedByUserID = previousRecord.CreatedByUserID; _repository.UpdateConference(conference, User.UserID); } if (image != null) { conference.SaveLogo(PortalSettings, image.InputStream, System.IO.Path.GetExtension(image.FileName)); } return RedirectToDefaultRoute(); } } }
47.56
152
0.683067
[ "BSD-3-Clause" ]
DNN-Connect/Conference
Server/Conference/Controllers/ConferenceController.cs
7,136
C#
#pragma checksum "C:\My Projects\ColdStart-Challenge-2021\challenges\challenge\ColdStartApp\ColdStart-UI\ColdStart-UI\Pages\Footer.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "ca30b37164fb35c5ac6dfe98dbf5d55833481dcc" // <auto-generated/> #pragma warning disable 1591 namespace ColdStart_UI.Pages { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #nullable restore #line 1 "C:\My Projects\ColdStart-Challenge-2021\challenges\challenge\ColdStartApp\ColdStart-UI\ColdStart-UI\_Imports.razor" using System.Net.Http; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\My Projects\ColdStart-Challenge-2021\challenges\challenge\ColdStartApp\ColdStart-UI\ColdStart-UI\_Imports.razor" using System.Net.Http.Json; #line default #line hidden #nullable disable #nullable restore #line 3 "C:\My Projects\ColdStart-Challenge-2021\challenges\challenge\ColdStartApp\ColdStart-UI\ColdStart-UI\_Imports.razor" using Microsoft.AspNetCore.Components.Forms; #line default #line hidden #nullable disable #nullable restore #line 4 "C:\My Projects\ColdStart-Challenge-2021\challenges\challenge\ColdStartApp\ColdStart-UI\ColdStart-UI\_Imports.razor" using Microsoft.AspNetCore.Components.Routing; #line default #line hidden #nullable disable #nullable restore #line 5 "C:\My Projects\ColdStart-Challenge-2021\challenges\challenge\ColdStartApp\ColdStart-UI\ColdStart-UI\_Imports.razor" using Microsoft.AspNetCore.Components.Web; #line default #line hidden #nullable disable #nullable restore #line 6 "C:\My Projects\ColdStart-Challenge-2021\challenges\challenge\ColdStartApp\ColdStart-UI\ColdStart-UI\_Imports.razor" using Microsoft.AspNetCore.Components.WebAssembly.Http; #line default #line hidden #nullable disable #nullable restore #line 7 "C:\My Projects\ColdStart-Challenge-2021\challenges\challenge\ColdStartApp\ColdStart-UI\ColdStart-UI\_Imports.razor" using Microsoft.JSInterop; #line default #line hidden #nullable disable #nullable restore #line 8 "C:\My Projects\ColdStart-Challenge-2021\challenges\challenge\ColdStartApp\ColdStart-UI\ColdStart-UI\_Imports.razor" using ColdStart_UI; #line default #line hidden #nullable disable #nullable restore #line 9 "C:\My Projects\ColdStart-Challenge-2021\challenges\challenge\ColdStartApp\ColdStart-UI\ColdStart-UI\_Imports.razor" using ColdStart_UI.Shared; #line default #line hidden #nullable disable #nullable restore #line 10 "C:\My Projects\ColdStart-Challenge-2021\challenges\challenge\ColdStartApp\ColdStart-UI\ColdStart-UI\_Imports.razor" using Blazored.Toast; #line default #line hidden #nullable disable #nullable restore #line 11 "C:\My Projects\ColdStart-Challenge-2021\challenges\challenge\ColdStartApp\ColdStart-UI\ColdStart-UI\_Imports.razor" using Blazored.Toast.Services; #line default #line hidden #nullable disable public partial class Footer : Microsoft.AspNetCore.Components.ComponentBase { #pragma warning disable 1998 protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) { __builder.AddMarkupContent(0, "<footer class=\"bg-white\">\r\n Theme by <a href=\"https://www.tailwindtoolbox.com/templates/landing-page\" class=\"text-gray-500\">tailwindtoolbox</a> &Aacute; Built by Sumit Kharche\r\n</footer>"); } #pragma warning restore 1998 } } #pragma warning restore 1591
35.08
245
0.798746
[ "MIT" ]
sumitkharche/ColdStart-Challenge-2021
challenges/challenge/ColdStartApp/ColdStart-UI/ColdStart-UI/obj/Debug/netstandard2.1/Razor/Pages/Footer.razor.g.cs
3,508
C#
namespace TimCodes.ApiAbstractions.Http.TestModels; public class TestResponse2 { public string? Response1 { get; set; } public int? Response2 { get; set; } }
21
52
0.720238
[ "MIT" ]
timcodesdotnet/api-abstractions
test/TimCodes.ApiAbstractions.Http.TestModels/TestResponse2.cs
170
C#
using System; using System.ComponentModel; using System.Collections; using System.Collections.Generic; using System.Text; using NUnit.Framework; using ASPNET_MVC_Store.ApplicationLogic; using ASPNET_MVC_Store.Model; using MVCSharp.Core; using MVCSharp.Core.Views; using MVCSharp.Core.Tasks; namespace Tests { [TestFixture] public class TestProductCategoriesController { private ProductCategoriesController controller; [SetUp] public void TestSetup() { controller = new ProductCategoriesController(); controller.Task = new MainTask(); controller.Task.Navigator = new StubNavigator(); controller.Task.Navigator.Task = controller.Task; } [Test] public void TestCategorySelected() { NorthwindDataSet.CategoriesRow cat = NorthwindDataSet.Instance.Categories.NewCategoriesRow(); controller.CategorySelected(cat); Assert.AreSame(cat, controller.Task.SelectedCategory); Assert.AreEqual(MainTask.Products, controller.Task.CurrViewName); } [Test] public void TestViewInitialization() { controller.View = new StubProductCategoriesView(); Assert.AreSame((NorthwindDataSet.Instance.Categories as IListSource) .GetList(), controller.View.CategoriesList); } class StubProductCategoriesView : IProductCategoriesView { private IList catList; public IList CategoriesList { get { return catList; } set { catList = value; } } } } }
28.032787
80
0.626901
[ "MIT" ]
zherar7ordoya/AP3
(CSharp)/3) MVP Pattern/MVCSharp/Examples/ASP.NET MVC Store/Tests/TestApplicationLogic/TestProductCategoriesController.cs
1,712
C#
using System; namespace Microsoft.Maui.Handlers { public partial class EntryHandler : AbstractViewHandler<IEntry, object> { protected override object CreateNativeView() => throw new NotImplementedException(); public static void MapText(IViewHandler handler, IEntry entry) { } public static void MapTextColor(IViewHandler handler, IEntry entry) { } public static void MapIsPassword(IViewHandler handler, IEntry entry) { } public static void MapHorizontalTextAlignment(IViewHandler handler, IEntry entry) { } public static void MapIsTextPredictionEnabled(IViewHandler handler, IEntry entry) { } public static void MapPlaceholder(IViewHandler handler, IEntry entry) { } public static void MapIsReadOnly(IViewHandler handler, IEntry entry) { } public static void MapFont(IViewHandler handler, IEntry entry) { } public static void MapReturnType(IViewHandler handler, IEntry entry) { } } }
47.842105
87
0.788779
[ "MIT" ]
JanNepras/maui
src/Core/src/Handlers/Entry/EntryHandler.Standard.cs
911
C#
using System.Collections.Generic; using Essensoft.AspNetCore.Payment.Alipay.Response; namespace Essensoft.AspNetCore.Payment.Alipay.Request { /// <summary> /// alipay.open.lottery.region.batchquery /// </summary> public class AlipayOpenLotteryRegionBatchqueryRequest : IAlipayRequest<AlipayOpenLotteryRegionBatchqueryResponse> { /// <summary> /// 天天抽奖-商家专区批量查询 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "alipay.open.lottery.region.batchquery"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
22.895161
117
0.55125
[ "MIT" ]
lzw316/payment
src/Essensoft.AspNetCore.Payment.Alipay/Request/AlipayOpenLotteryRegionBatchqueryRequest.cs
2,865
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WPFGraphics.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
35.16129
151
0.568807
[ "MIT" ]
Aptacode/Aptacode.TaskPlex
WPF/WPFGraphics/Properties/Settings.Designer.cs
1,092
C#
// <auto-generated /> using System; using BlindDateBot.Data.Contexts; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace BlindDateBot.Data.Migrations { [DbContext(typeof(SqlServerContext))] [Migration("20210205072901_UpdateMessageTableIdentityColumn")] partial class UpdateMessageTableIdentityColumn { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .UseIdentityColumns() .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.2"); modelBuilder.Entity("BlindDateBot.Domain.Models.DateModel", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int?>("FirstUserId") .HasColumnType("int"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<int?>("SecondUserId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("FirstUserId"); b.HasIndex("SecondUserId"); b.ToTable("Dates"); }); modelBuilder.Entity("BlindDateBot.Domain.Models.MessageModel", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("DateModelId") .HasColumnType("nvarchar(450)"); b.Property<int?>("FromId") .HasColumnType("int"); b.Property<string>("Text") .HasColumnType("nvarchar(max)"); b.Property<int?>("ToId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("DateModelId"); b.HasIndex("FromId"); b.HasIndex("ToId"); b.ToTable("Messages"); }); modelBuilder.Entity("BlindDateBot.Domain.Models.UserModel", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasColumnName("user_id") .UseIdentityColumn(); b.Property<int>("Gender") .HasColumnType("int") .HasColumnName("user_gender"); b.Property<int>("InterlocutorGender") .HasColumnType("int") .HasColumnName("interlocutor_gender"); b.Property<bool>("IsFree") .HasColumnType("bit") .HasColumnName("is_free"); b.Property<int>("TelegramId") .HasColumnType("int"); b.Property<string>("Username") .HasColumnType("nvarchar(max)") .HasColumnName("username"); b.HasKey("Id") .HasName("user_pkey"); b.ToTable("Users"); }); modelBuilder.Entity("BlindDateBot.Domain.Models.DateModel", b => { b.HasOne("BlindDateBot.Domain.Models.UserModel", "FirstUser") .WithMany() .HasForeignKey("FirstUserId"); b.HasOne("BlindDateBot.Domain.Models.UserModel", "SecondUser") .WithMany() .HasForeignKey("SecondUserId"); b.Navigation("FirstUser"); b.Navigation("SecondUser"); }); modelBuilder.Entity("BlindDateBot.Domain.Models.MessageModel", b => { b.HasOne("BlindDateBot.Domain.Models.DateModel", null) .WithMany("Messages") .HasForeignKey("DateModelId"); b.HasOne("BlindDateBot.Domain.Models.UserModel", "From") .WithMany() .HasForeignKey("FromId"); b.HasOne("BlindDateBot.Domain.Models.UserModel", "To") .WithMany() .HasForeignKey("ToId"); b.Navigation("From"); b.Navigation("To"); }); modelBuilder.Entity("BlindDateBot.Domain.Models.DateModel", b => { b.Navigation("Messages"); }); #pragma warning restore 612, 618 } } }
33.625
82
0.467032
[ "MIT" ]
Bardin08/Blind-Date-Bot
BlindDateBot.Data/Migrations/20210205072901_UpdateMessageTableIdentityColumn.Designer.cs
5,113
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Text; namespace ElectrumXClient.Request { public class RequestBase { [JsonProperty("id")] public int MessageId { get; set; } [JsonProperty("method")] public string Method { get; set; } [JsonProperty("params")] public object Parameters { get; set; } public byte[] GetRequestData<T>() { byte[] data = System.Text.Encoding.ASCII.GetBytes(ToJson<T>()); return data; } protected string ToJson<T>() { return JsonConvert.SerializeObject(this, Converter<T>.Settings) + "\n"; } } }
23.558824
83
0.611735
[ "MIT" ]
hashland/ElectrumXClient
src/ElectrumXClient/Request/RequestBase.cs
803
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Logic.Inputs { /// <summary> /// The integration account RosettaNet ProcessConfiguration activity settings. /// </summary> public sealed class RosettaNetPipActivitySettingsArgs : Pulumi.ResourceArgs { /// <summary> /// The RosettaNet ProcessConfiguration acknowledgement settings. /// </summary> [Input("acknowledgmentOfReceiptSettings", required: true)] public Input<Inputs.RosettaNetPipAcknowledgmentOfReceiptSettingsArgs> AcknowledgmentOfReceiptSettings { get; set; } = null!; /// <summary> /// The RosettaNet ProcessConfiguration activity behavior. /// </summary> [Input("activityBehavior", required: true)] public Input<Inputs.RosettaNetPipActivityBehaviorArgs> ActivityBehavior { get; set; } = null!; /// <summary> /// The RosettaNet ProcessConfiguration activity type. /// </summary> [Input("activityType", required: true)] public Input<Pulumi.AzureNextGen.Logic.RosettaNetPipActivityType> ActivityType { get; set; } = null!; public RosettaNetPipActivitySettingsArgs() { } } }
36.219512
132
0.684175
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Logic/Inputs/RosettaNetPipActivitySettingsArgs.cs
1,485
C#