content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Copyright © Conatus Creative, Inc. All rights reserved. // Licensed under the Apache 2.0 License. See LICENSE.md in the project root for license terms. using System; namespace Pixel3D.Audio { public delegate float GetSingle(IDisposable owner); }
31.375
95
0.772908
[ "Apache-2.0" ]
caogtaa/Pixel3D
src/Pixel3D.Audio/GetSingle.cs
254
C#
// ----------------------------------------------------------------------------------- // // GRABCASTER LTD CONFIDENTIAL // ___________________________ // // Copyright © 2013 - 2016 GrabCaster Ltd. All rights reserved. // This work is registered with the UK Copyright Service: Registration No:284701085 // // // NOTICE: All information contained herein is, and remains // the property of GrabCaster Ltd and its suppliers, // if any. The intellectual and technical concepts contained // herein are proprietary to GrabCaster Ltd // and its suppliers and may be covered by UK and Foreign Patents, // patents in process, and are protected by trade secret or copyright law. // Dissemination of this information or reproduction of this material // is strictly forbidden unless prior written permission is obtained // from GrabCaster Ltd. // // ----------------------------------------------------------------------------------- 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("GrabCaster.Framework.EmbeddedEvent")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GrabCaster.Framework.EmbeddedEvent")] [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("81b7eadc-9555-40c3-9b1a-f3ee4faa3bea")] // 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")]
41.578947
87
0.700844
[ "MIT" ]
debiaggi/GrabCaster
Events/EmbeddedEvent/Properties/AssemblyInfo.cs
2,374
C#
using System; using Microsoft.Maui.Graphics; using Microsoft.Maui.Graphics.Android; using Android.Runtime; using Android.Content; using Android.Views; using Android.Widget; using GraphicsTester.Scenarios; using Microsoft.Maui.Graphics.Native; namespace GraphicsTester.Android { public class MainView : LinearLayout { private readonly ListView _listView; private readonly NativeGraphicsView _graphicsView; public MainView (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) { } public MainView (Context context) : base (context) { Orientation = Orientation.Horizontal; _listView = new ListView (context); _listView.LayoutParameters = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.MatchParent, 2.5f); base.AddView (_listView); _graphicsView = new NativeGraphicsView (context); _graphicsView.BackgroundColor = Colors.White; _graphicsView.LayoutParameters = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.MatchParent, 1); base.AddView (_graphicsView); var adapter = new ArrayAdapter (context, Resource.Layout.ListViewItem, ScenarioList.Scenarios); _listView.Adapter = adapter; _listView.ItemClick += (sender, e) => { var scenario = ScenarioList.Scenarios[e.Position]; _graphicsView.Drawable = scenario; }; } } }
27.403846
102
0.761404
[ "MIT" ]
JimBobSquarePants/Microsoft.Maui.Graphics
samples/GraphicsTester.Android/MainView.cs
1,425
C#
using UnityEngine; using System.Collections; public class Fish : MonoBehaviour { public Vector3 destination; // Use this for initialization void Start () { // after 0 seconds, it will randomize its destination every 5 sec. InvokeRepeating( "RandomizeDestination", 0f, 5f); } void RandomizeDestination () { destination = Random.insideUnitSphere * 10f; } void FixedUpdate () { // always move toward "destination" rigidbody.AddForce ( Vector3.Normalize(destination - transform.position) ); } void Update () { // always look the direction you're moving transform.rotation = Quaternion.LookRotation (rigidbody.velocity); } }
21.933333
77
0.721884
[ "MIT" ]
radiatoryang/buildingworlds_spring2014
buildingworlds_week06/Assets/scripts/Fish.cs
660
C#
namespace DXDecompiler.Decompiler.IR.ResourceDefinitions { public enum IrResourceClass { SRV = 0, UAV, CBuffer, Sampler, Invalid } }
12.25
57
0.714286
[ "MIT" ]
lanyizi/DXDecompiler
src/DXDecompiler/Decompiler/IR/ResourceDefinitions/IrResourceClass.cs
149
C#
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using SmartHead.Essentials.Abstractions.Behaviour; using SmartHead.Essentials.Abstractions.Ddd.Interfaces; using SmartHead.Essentials.Extensions; namespace SmartHead.Essentials.Implementation.UoW { public class UnitOfWork : IUnitOfWork { protected readonly DbContext Context; public UnitOfWork(DbContext context) { Context = context; } public virtual bool Commit() { CreationTimeCommit(); ModificationTimeCommit(); return Context.SaveChanges() > 0; } public virtual async Task<bool> CommitAsync(CancellationToken ct = default) { CreationTimeCommit(); ModificationTimeCommit(); return await Context.SaveChangesAsync(ct) > 0; } protected virtual void CreationTimeCommit() => Context.ChangeTracker.Entries() .Where(x => x.State == EntityState.Added && x.Entity is IHasCreationTime) .ForEach(x => { if (x.Entity is IHasCreationTime entity) entity.CreationTime = DateTime.UtcNow; }); protected virtual void ModificationTimeCommit() => Context.ChangeTracker.Entries() .Where(x => x.State == EntityState.Modified && x.Entity is IHasModificationTime) .ForEach(x => { if (x.Entity is IHasModificationTime entity) entity.LastModificationTime = DateTime.UtcNow; }); } }
31.327273
96
0.592571
[ "Apache-2.0" ]
neonbones/SmartHead.Essentials
src/SmartHead.Essentials.Implementation/UoW/UnitOfWork.cs
1,725
C#
using System; using System.Collections.Generic; using System.Net; using Microsoft.AspNetCore.Mvc; using NBitcoin; using NLog; using Stratis.Bitcoin.Features.Interop.Models; using Stratis.Bitcoin.Utilities.JsonErrors; using Stratis.Features.FederatedPeg.Conversion; namespace Stratis.Bitcoin.Features.Interop.Controllers { [ApiVersion("1")] [Route("api/[controller]")] public class InteropController : Controller { private readonly Network network; private readonly IConversionRequestRepository conversionRequestRepository; private readonly IInteropTransactionManager interopTransactionManager; private readonly ILogger logger; public InteropController(Network network, IConversionRequestRepository conversionRequestRepository, IInteropTransactionManager interopTransactionManager) { this.network = network; this.conversionRequestRepository = conversionRequestRepository; this.interopTransactionManager = interopTransactionManager; this.logger = LogManager.GetCurrentClassLogger(); } [Route("status")] [HttpGet] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public IActionResult InteropStatus() { try { var response = new InteropStatusResponseModel(); var mintRequests = new List<ConversionRequestModel>(); foreach (ConversionRequest request in this.conversionRequestRepository.GetAllMint(false)) { mintRequests.Add(new ConversionRequestModel() { RequestId = request.RequestId, RequestType = request.RequestType, RequestStatus = request.RequestStatus, BlockHeight = request.BlockHeight, DestinationAddress = request.DestinationAddress, Amount = request.Amount, Processed = request.Processed }); } response.MintRequests = mintRequests; var burnRequests = new List<ConversionRequestModel>(); foreach (ConversionRequest request in this.conversionRequestRepository.GetAllBurn(false)) { burnRequests.Add(new ConversionRequestModel() { RequestId = request.RequestId, RequestType = request.RequestType, RequestStatus = request.RequestStatus, BlockHeight = request.BlockHeight, DestinationAddress = request.DestinationAddress, Amount = request.Amount, Processed = request.Processed }); } response.MintRequests = burnRequests; var receivedVotes = new Dictionary<string, List<string>>(); foreach ((string requestId, HashSet<PubKey> pubKeys) in this.interopTransactionManager.GetStatus()) { var pubKeyList = new List<string>(); foreach (PubKey pubKey in pubKeys) { pubKeyList.Add(pubKey.ToHex()); } receivedVotes.Add(requestId, pubKeyList); } response.ReceivedVotes = receivedVotes; return this.Json(response); } catch (Exception e) { this.logger.Error("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()); } } } }
37.415094
161
0.581694
[ "MIT" ]
Amazastrophic/StratisFullNode
src/Stratis.Bitcoin.Features.Interop/Controllers/InteropController.cs
3,968
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the datasync-2018-11-09.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.DataSync.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DataSync.Model.Internal.MarshallTransformations { /// <summary> /// UpdateTask Request Marshaller /// </summary> public class UpdateTaskRequestMarshaller : IMarshaller<IRequest, UpdateTaskRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((UpdateTaskRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(UpdateTaskRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.DataSync"); string target = "FmrsService.UpdateTask"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-11-09"; request.HttpMethod = "POST"; string uriResourcePath = "/"; request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetCloudWatchLogGroupArn()) { context.Writer.WritePropertyName("CloudWatchLogGroupArn"); context.Writer.Write(publicRequest.CloudWatchLogGroupArn); } if(publicRequest.IsSetExcludes()) { context.Writer.WritePropertyName("Excludes"); context.Writer.WriteArrayStart(); foreach(var publicRequestExcludesListValue in publicRequest.Excludes) { context.Writer.WriteObjectStart(); var marshaller = FilterRuleMarshaller.Instance; marshaller.Marshall(publicRequestExcludesListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetName()) { context.Writer.WritePropertyName("Name"); context.Writer.Write(publicRequest.Name); } if(publicRequest.IsSetOptions()) { context.Writer.WritePropertyName("Options"); context.Writer.WriteObjectStart(); var marshaller = OptionsMarshaller.Instance; marshaller.Marshall(publicRequest.Options, context); context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetTaskArn()) { context.Writer.WritePropertyName("TaskArn"); context.Writer.Write(publicRequest.TaskArn); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static UpdateTaskRequestMarshaller _instance = new UpdateTaskRequestMarshaller(); internal static UpdateTaskRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UpdateTaskRequestMarshaller Instance { get { return _instance; } } } }
35.9375
135
0.589372
[ "Apache-2.0" ]
costleya/aws-sdk-net
sdk/src/Services/DataSync/Generated/Model/Internal/MarshallTransformations/UpdateTaskRequestMarshaller.cs
5,175
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.JSLS; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Intel = Microsoft.VisualStudio.Language.Intellisense; namespace MadsKristensen.EditorExtensions.JavaScript { [Export(typeof(IWpfTextViewConnectionListener))] [ContentType("javascript")] [ContentType("node.js")] [TextViewRole(PredefinedTextViewRoles.Interactive)] internal sealed class JsTextViewCreationListener : IWpfTextViewConnectionListener { [Import] ICompletionBroker CompletionBroker = null; [Import] IStandardClassificationService _standardClassifications = null; [Import] internal IVsEditorAdaptersFactoryService EditorAdaptersFactoryService { get; set; } public async void SubjectBuffersConnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers) { if (textView.Properties.ContainsProperty("JsCommandFilter")) return; if (!subjectBuffers.Any(b => b.ContentType.IsOfType("JavaScript"))) return; var adapter = EditorAdaptersFactoryService.GetViewAdapter(textView); var filter = textView.Properties.GetOrCreateSingletonProperty<JsCommandFilter>("JsCommandFilter", () => new JsCommandFilter(textView, CompletionBroker, _standardClassifications)); int tries = 0; // Ugly ugly hack // Keep trying to register our filter until after the JSLS CommandFilter // is added so we can catch completion before JSLS swallows all of them. // To confirm this, click Debug, New Breakpoint, Break at Function, type // Microsoft.VisualStudio.JSLS.TextView.TextView.CreateCommandFilter, // then make sure that our last filter is added after that runs. while (true) { IOleCommandTarget next; adapter.AddCommandFilter(filter, out next); filter.Next = next; if (IsJSLSInstalled(next) || ++tries > 10) return; await Task.Delay(500); adapter.RemoveCommandFilter(filter); // Remove the too-early filter and try again. } } ///<summary>Attempts to figure out whether the JSLS language service has been installed yet.</summary> [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.VisualStudio.OLE.Interop.IOleCommandTarget.QueryStatus(System.Guid@,System.UInt32,Microsoft.VisualStudio.OLE.Interop.OLECMD[],System.IntPtr)")] static bool IsJSLSInstalled(IOleCommandTarget next) { Guid cmdGroup = VSConstants.VSStd2K; var cmds = new[] { new OLECMD { cmdID = (uint)VSConstants.VSStd2KCmdID.AUTOCOMPLETE } }; try { next.QueryStatus(ref cmdGroup, 1, cmds, IntPtr.Zero); return cmds[0].cmdf == 3; } catch { return false; } } public void SubjectBuffersDisconnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers) { } } internal sealed class JsCommandFilter : IOleCommandTarget { private readonly IStandardClassificationService _standardClassifications; private ICompletionSession _currentSession; static readonly Type jsTaggerType = typeof(JavaScriptLanguageService).Assembly.GetType("Microsoft.VisualStudio.JSLS.Classification.Tagger"); public IWpfTextView TextView { get; private set; } public ICompletionBroker Broker { get; private set; } public IOleCommandTarget Next { get; set; } private static char GetTypeChar(IntPtr pvaIn) { return (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn); } public JsCommandFilter(IWpfTextView textView, ICompletionBroker CompletionBroker, IStandardClassificationService standardClassifications) { TextView = textView; Broker = CompletionBroker; _standardClassifications = standardClassifications; } IEnumerable<IClassificationType> GetCaretClassifications() { var buffers = TextView.BufferGraph.GetTextBuffers(b => b.ContentType.IsOfType("JavaScript") && TextView.GetSelection("JavaScript").HasValue && TextView.GetSelection("JavaScript").Value.Snapshot.TextBuffer == b); if (!buffers.Any()) return Enumerable.Empty<IClassificationType>(); var tagger = buffers.First().Properties.GetProperty<ITagger<ClassificationTag>>(jsTaggerType); return tagger.GetTags(new NormalizedSnapshotSpanCollection(new SnapshotSpan(TextView.Caret.Position.BufferPosition, 0))) .Select(s => s.Tag.ClassificationType); } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (pguidCmdGroup != VSConstants.VSStd2K || !IsValidTextBuffer()) return Next.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); // This filter should only have do anything inside a string literal, or when opening a string literal. var classifications = GetCaretClassifications(); bool isInString = classifications.Contains(_standardClassifications.StringLiteral); bool isInComment = classifications.Contains(_standardClassifications.Comment); var command = (VSConstants.VSStd2KCmdID)nCmdID; if (!isInString && !isInComment) { if (command != VSConstants.VSStd2KCmdID.TYPECHAR) return Next.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); char ch = GetTypeChar(pvaIn); if (ch != '"' && ch != '\'' && ch != '@') return Next.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } bool closedCompletion = false; bool handled = false; // 1. Pre-process switch (command) { case VSConstants.VSStd2KCmdID.TYPECHAR: char ch = GetTypeChar(pvaIn); if (ch == '"' || ch == '\'' && _currentSession != null) { // If the user commits a completion from a closing quote, do // not immediately re-open the completion window below. closedCompletion = _currentSession != null; // If the user typed a closing quote, remove any trailing semicolon to match if (_currentSession != null) { var s = _currentSession.SelectedCompletionSet.SelectionStatus; if (s.IsSelected && s.Completion.InsertionText.EndsWith(ch + ";", StringComparison.Ordinal)) s.Completion.InsertionText = s.Completion.InsertionText.TrimEnd(';'); } var c = Complete(force: false, dontAdvance: true); // If the completion inserted a quote, don't add another one handled = c != null && c.InsertionText.EndsWith(ch.ToString(), StringComparison.Ordinal); } else if (ch == '/') { var c = Complete(force: false, dontAdvance: true); // If the completion inserted a slash, don't add another one. handled = c != null && c.InsertionText.EndsWith("/", StringComparison.Ordinal); // We will re-open completion after handling the keypress, to // show completions for this folder. } else if (isInComment && ch == '@') { var c = Complete(force: false, dontAdvance: true); handled = c != null; // We will re-open completion after handling the keypress, to // show completions for this folder. } break; case VSConstants.VSStd2KCmdID.AUTOCOMPLETE: case VSConstants.VSStd2KCmdID.SHOWMEMBERLIST: case VSConstants.VSStd2KCmdID.COMPLETEWORD: // Never handle this command; we always want JSLS to try too. StartSession(); break; case VSConstants.VSStd2KCmdID.RETURN: handled = Complete(false) != null; break; case VSConstants.VSStd2KCmdID.TAB: handled = Complete(true) != null; break; case VSConstants.VSStd2KCmdID.CANCEL: handled = Cancel(); break; } int hresult = VSConstants.S_OK; if (!handled) hresult = Next.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); if (!ErrorHandler.Succeeded(hresult)) return hresult; switch (command) { case VSConstants.VSStd2KCmdID.TYPECHAR: char ch = GetTypeChar(pvaIn); if (ch == ':' || ch == ' ') Cancel(); else if (ch == '"' || ch == '\'' || ch == '/' || ch == '.' || ch == '@' || (!char.IsPunctuation(ch) && !char.IsControl(ch))) { if (!closedCompletion) StartSession(); } else if (_currentSession != null) Filter(); break; case VSConstants.VSStd2KCmdID.DELETE: case VSConstants.VSStd2KCmdID.DELETEWORDLEFT: case VSConstants.VSStd2KCmdID.DELETEWORDRIGHT: case VSConstants.VSStd2KCmdID.BACKSPACE: if (_currentSession == null) StartSession(); else { var p = _currentSession.GetTriggerPoint(TextView.TextBuffer.CurrentSnapshot); if (p != null && (p.Value.Position >= p.Value.Snapshot.Length || p.Value.GetChar() != _currentSession.CompletionSets[0].Completions[0].InsertionText[0]) ) Cancel(); } Filter(); break; } return hresult; } private bool IsValidTextBuffer() { if (TextView.TextBuffer.ContentType.IsOfType("javascript")) return true; var projection = TextView.TextBuffer as IProjectionBuffer; if (projection != null) { var snapshotPoint = TextView.Caret.Position.BufferPosition; var buffers = projection.SourceBuffers.Where(s => s.ContentType.IsOfType("htmlx")); foreach (ITextBuffer buffer in buffers) { SnapshotPoint? point = TextView.BufferGraph.MapDownToBuffer(snapshotPoint, PointTrackingMode.Negative, buffer, PositionAffinity.Predecessor); if (point.HasValue) return false; } } return true; } private void Filter() { if (_currentSession == null) return; _currentSession.SelectedCompletionSet.SelectBestMatch(); _currentSession.SelectedCompletionSet.Recalculate(); } bool Cancel() { if (_currentSession == null) return false; _currentSession.Dismiss(); return true; } Intel.Completion Complete(bool force, bool dontAdvance = false) { if (_currentSession == null) return null; if (!_currentSession.SelectedCompletionSet.SelectionStatus.IsSelected && !force) { _currentSession.Dismiss(); return null; } else { var positionNullable = _currentSession.GetTriggerPoint(TextView.TextBuffer.CurrentSnapshot); var completion = _currentSession.SelectedCompletionSet.SelectionStatus.Completion; // After this line, _currentSession will be null. Do not use it. _currentSession.Commit(); if (positionNullable == null) return null; var position = positionNullable.Value; if (position.Position == TextView.TextBuffer.CurrentSnapshot.Length) return completion; // If the cursor is at the end of the document, don't choke // If applicable, move the cursor to the end of the function call. // Unless the user is in completing a deeper Node.js require path, // in which case we should stay inside the string. if (dontAdvance || completion.InsertionText.EndsWith("/", StringComparison.Ordinal)) return completion; // If the user completed a Node require path (which won't have any // quotes in the completion, move past any existing closing quote. // Other completions will include the closing quote themselves, so // we don't need to move if (!completion.InsertionText.EndsWith("'", StringComparison.Ordinal) && !completion.InsertionText.EndsWith("\"", StringComparison.Ordinal) && (position.GetChar() == '"' || position.GetChar() == '\'')) TextView.Caret.MoveToNextCaretPosition(); // In either case, if there is a closing parenthesis, move past it var prevChar = position.GetChar(); if ((prevChar == '"' || prevChar == '\'') && TextView.Caret.Position.BufferPosition < TextView.TextBuffer.CurrentSnapshot.Length && TextView.Caret.Position.BufferPosition.GetChar() == ')') TextView.Caret.MoveToNextCaretPosition(); return completion; } } bool StartSession() { if (_currentSession != null) return false; SnapshotPoint caret = TextView.Caret.Position.BufferPosition; ITextSnapshot snapshot = caret.Snapshot; if (!Broker.IsCompletionActive(TextView)) { _currentSession = Broker.CreateCompletionSession(TextView, snapshot.CreateTrackingPoint(caret, PointTrackingMode.Positive), true); } else { _currentSession = Broker.GetSessions(TextView)[0]; } _currentSession.Dismissed += (sender, args) => _currentSession = null; if (!_currentSession.IsStarted) _currentSession.Start(); return true; } public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { if (pguidCmdGroup == VSConstants.VSStd2K) { switch ((VSConstants.VSStd2KCmdID)prgCmds[0].cmdID) { case VSConstants.VSStd2KCmdID.AUTOCOMPLETE: case VSConstants.VSStd2KCmdID.SHOWMEMBERLIST: case VSConstants.VSStd2KCmdID.COMPLETEWORD: prgCmds[0].cmdf = (uint)OLECMDF.OLECMDF_ENABLED | (uint)OLECMDF.OLECMDF_SUPPORTED; return VSConstants.S_OK; } } return Next.QueryStatus(pguidCmdGroup, cCmds, prgCmds, pCmdText); } } }
43.826425
245
0.574629
[ "Apache-2.0" ]
DotNetSparky/WebEssentials2013
EditorExtensions/JavaScript/Completion/JavaScriptCompletionController.cs
16,919
C#
/* MIT License Copyright (c) 2017 Saied Zarrinmehr Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using SpatialAnalysis.CellularEnvironment; using System.Runtime.InteropServices; using System.Windows.Interop; using Jace; using SpatialAnalysis.Miscellaneous; namespace SpatialAnalysis.Data.Visualization { /// <summary> /// Interaction logic for AddDataField.xaml /// </summary> public partial class AddDataField : Window { #region Hiding the close button private const int GWL_STYLE = -16; private const int WS_SYSMENU = 0x80000; [DllImport("user32.dll", SetLastError = true)] private static extern int GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll")] private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); void AddData_Loaded(object sender, RoutedEventArgs e) { var hwnd = new WindowInteropHelper(this).Handle; SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU); } #endregion /// <summary> /// Initializes a new instance of the <see cref="AddDataField"/> class. /// </summary> public AddDataField() { InitializeComponent(); this.Loaded += AddData_Loaded; } private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { System.Diagnostics.Process.Start("https://github.com/pieterderycke/Jace/wiki"); } private void TextBlock_MouseEnter(object sender, MouseEventArgs e) { this.Cursor = Cursors.Hand; } private void TextBlock_MouseLeave(object sender, MouseEventArgs e) { this.Cursor = Cursors.Arrow; } /// <summary> /// Gets or sets the interpolation function. /// </summary> /// <value>The interpolation function.</value> public Func<double, double> InterpolationFunction { get; set; } /// <summary> /// Loads the interpolation function. /// </summary> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> public bool LoadFunction() { try { CalculationEngine engine = new CalculationEngine(); this.InterpolationFunction = (Func<double, double>)engine.Formula(this.main.Text) .Parameter("X", Jace.DataType.FloatingPoint) .Result(Jace.DataType.FloatingPoint) .Build(); for (int i = 0; i < 100; i++) { this.InterpolationFunction(((double)i) / 3); } } catch (Exception error) { MessageBox.Show("Wrong formula!\n" + error.Report(), "FORMULA PARSING Error", MessageBoxButton.OK, MessageBoxImage.Error); return false; } return true; } } }
35.47541
138
0.653882
[ "MIT" ]
zarrinmehr/OccupancySimulationModel
OSM/Data/Visualization/AddDataField.xaml.cs
4,328
C#
using System; using System.Collections.Generic; using System.Text; namespace ForeSpark.Home.Dto { public class RequestsHomeDto { public int Pending { get; set; } public int Approved { get; set; } public int Declined { get; set; } public int Processed { get; set; } } }
21
42
0.628571
[ "MIT" ]
ali-kiyani/ForeSpark
aspnet-core/src/ForeSpark.Application/Home/Dto/RequestsHomeDto.cs
317
C#
using Prism.Mvvm; namespace BookViewer.Models { public class Page : IPage { public int ChapterNo { get; } public int PageNo { get; } public string Text { get; } public Page(int chapterNo, int pageNo) { ChapterNo = chapterNo; PageNo = pageNo; Text = $"Chapter-{chapterNo} Page-{pageNo}"; } } }
21.722222
56
0.531969
[ "MIT" ]
nuitsjp/BookViewer
BookViewer/BookViewer/Models/Page.cs
393
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace Microsoft.ProjectOxford.Search.Core { /// <summary> /// Client for interacting with the search API's. This is an abstract class. /// </summary> public abstract class SearchClient { #region Fields private const string APPLICATION_JSON_CONTENT_TYPE = "application/json"; private const string GET_METHOD = "GET"; private const string OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private const string POST_METHOD = "POST"; #endregion Fields #region Constructors /// <summary> /// Initializes a new instance of the <see cref="SearchClient"/> class. /// </summary> /// <param name="apiKey">The API key.</param> public SearchClient(string apiKey) { this.ApiKey = apiKey; } #endregion Constructors #region Properties /// <summary> /// Gets or sets the API key. /// </summary> /// <value> /// The API key. /// </value> public string ApiKey { get; set; } /// <summary> /// Gets or sets the URL. /// </summary> /// <value> /// The URL. /// </value> public string Url { get; set; } #endregion Properties #region Methods /// <summary> /// Sends the post. /// </summary> /// <param name="data">The data.</param> /// <returns></returns> protected string SendPost(string data) { return SendPost(this.Url, data); } /// <summary> /// Sends the post. /// </summary> /// <param name="url">The URL.</param> /// <param name="data">The data.</param> /// <returns></returns> protected string SendPost(string url, string data) { return this.SendPostAsync(url, data).Result; } /// <summary> /// Sends the post asynchronously. /// </summary> /// <param name="data">The data.</param> /// <returns></returns> protected async Task<string> SendPostAsync(string data) { return await SendPostAsync(this.Url, data); } /// <summary> /// Sends the post asynchronously. /// </summary> /// <param name="url">The URL.</param> /// <param name="data">The data.</param> /// <returns></returns> /// <exception cref="System.ArgumentException"> /// url /// or /// ApiKey /// or /// data /// </exception> protected async Task<string> SendPostAsync(string url, string data) { if (String.IsNullOrWhiteSpace(url)) { throw new ArgumentException(nameof(url)); } if (String.IsNullOrWhiteSpace(this.ApiKey)) { throw new ArgumentException(nameof(ApiKey)); } if (String.IsNullOrWhiteSpace(data)) { throw new ArgumentException(nameof(data)); } byte[] reqData = Encoding.UTF8.GetBytes(data); var responseData = ""; using (var client = new HttpClient { BaseAddress = new Uri(url) }) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(APPLICATION_JSON_CONTENT_TYPE)); client.DefaultRequestHeaders.Add(OCP_APIM_SUBSCRIPTION_KEY, ApiKey); var content = new StringContent(data, Encoding.UTF8, "application/json"); using (var response = await client.PostAsync(url, content)) { responseData = await response.Content.ReadAsStringAsync(); } } return responseData; } /// <summary> /// Sends the get. /// </summary> /// <returns></returns> protected string SendGet() { return SendGet(this.Url); } /// <summary> /// Sends the get. /// </summary> /// <param name="url">The URL.</param> /// <returns></returns> protected string SendGet(string url) { return SendGetAsync(url).Result; } /// <summary> /// Sends the get asynchronous. /// </summary> /// <param name="url">The URL.</param> /// <returns></returns> /// <exception cref="System.ArgumentException"> /// url /// or /// ApiKey /// </exception> protected async Task<string> SendGetAsync(string url) { if (String.IsNullOrWhiteSpace(url)) { throw new ArgumentException(nameof(url)); } if (String.IsNullOrWhiteSpace(this.ApiKey)) { throw new ArgumentException(nameof(ApiKey)); } var responseData = ""; using (var client = new HttpClient { BaseAddress = new Uri(url) }) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(APPLICATION_JSON_CONTENT_TYPE)); client.DefaultRequestHeaders.Add(OCP_APIM_SUBSCRIPTION_KEY, ApiKey); using (var response = await client.GetAsync(url)) { responseData = await response.Content.ReadAsStringAsync(); } } return responseData; } #endregion Methods } }
27.791667
124
0.520906
[ "MIT" ]
Bhaskers-Blu-Org2/Cognitive-Search-DotNet
ClientLibrary/Microsoft.ProjectOxford.Search/Core/SearchClient.cs
6,005
C#
using System; using System.Reflection; namespace Giver.ValueGenerators { public class SingleGenerator : RandomGenerator<float> { public override float GetValue(MemberInfo memberInfo) { var mantissa = Random.NextDouble() * 2.0 - 1.0; var exponent = Math.Pow(2.0, Random.Next(-126, 128)); return (float) (mantissa * exponent); } } }
26.333333
65
0.627848
[ "MIT" ]
umutozel/Giver
Giver/ValueGenerators/SingleGenerator.cs
397
C#
// <copyright file="WpPmProMembershipLevel.cs" company="Andrii Kurdiumov"> // Copyright (c) Andrii Kurdiumov. All rights reserved. // </copyright> namespace AndriiKurdiumov.Wordpress.EntityFrameworkCore { using System.ComponentModel.DataAnnotations.Schema; /// <summary> /// Membership level. /// </summary> public class WpPmProMembershipLevel { /// <summary> /// Gets or sets id of the level. /// </summary> [Column("id")] public int Id { get; set; } /// <summary> /// Gets or sets name of the membership level. /// </summary> [Column("name")] public string Name { get; set; } } }
25.703704
75
0.592219
[ "MIT" ]
kant2002/wordpress-netcore
EntityFrameworkCore/WpPmProMembershipLevel.cs
696
C#
using System; using System.Collections.Generic; using System.Text; namespace System.Linq { /// <summary> /// 数据结果 /// </summary> /// <typeparam name="T">数据源类型</typeparam> [Serializable] public class DataResult<T> : IDataResult<T> { /// <summary> /// 数据结果 /// </summary> public IList<T> Result { get; set; } /// <summary> /// 数据总量 /// </summary> public int Count { get; set; } /// <summary> /// 空 DataResult /// </summary> /// <returns></returns> public static DataResult<T> Empty() { return new DataResult<T>() { Result = Enumerable.Empty<T>().ToList(), Count = 0, }; } } }
22.083333
56
0.461635
[ "Apache-2.0" ]
jm6041/Extensions
src/Linq/src/Jimlicat.Extensions.Linq/DataResult.cs
831
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> /// DvbTdtSettings Marshaller /// </summary> public class DvbTdtSettingsMarshaller : IRequestMarshaller<DvbTdtSettings, 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(DvbTdtSettings requestObject, JsonMarshallerContext context) { if(requestObject.IsSetRepInterval()) { context.Writer.WritePropertyName("repInterval"); context.Writer.Write(requestObject.RepInterval); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static DvbTdtSettingsMarshaller Instance = new DvbTdtSettingsMarshaller(); } }
32.935484
107
0.685602
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/MediaLive/Generated/Model/Internal/MarshallTransformations/DvbTdtSettingsMarshaller.cs
2,042
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace working_time_monitoring_management { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void add_new_employee(object sender, RoutedEventArgs e) { string name = name_box.Text; string surname = surname_box.Text; int card_number = int.Parse(card_number_box.Text); AddToDatabase.add(name, surname, card_number); MessageBox.Show("Dodano Pracownika"); } } }
26.135135
71
0.67425
[ "Unlicense" ]
mrychlicki/working_time_monitoring
working_time_monitoring_management/Add_employee.xaml.cs
969
C#
using System; using System.IO.Ports; using System.Text; using System.Threading; using Microsoft.SPOT; using Microsoft.SPOT.Hardware; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class TestPorts : IMFTestInterface { private MFTestResults result; private int portCount; private bool IsEmulator = false; private bool IsLoopback = false; private const string testString = @"\\//><:;',.Test string !@#$%^&**()123"; private byte[] sendbuff; private byte[] readbuff = new byte[256]; private SerialPort eventSerialPort = null; private int eventCount; [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); // Add your functionality here. portCount = HardwareProvider.HwProvider.GetSerialPortsCount(); if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) //The Emulator on Windows Host IsEmulator = true; Debug.Print("IsEmulator: " + IsEmulator); // Test for loopback sendbuff = Encoding.UTF8.GetBytes(testString); Log.Comment("Port count: " + portCount); if (portCount > 0) { using (TestSerialPort serialPort = new TestSerialPort(Serial.COM1)) { serialPort.ReadTimeout = 1000; try { serialPort.VerifyWrite(testString); this.IsLoopback = true; } catch { Log.Comment("No loopback detected. Functional tests will not run"); } } } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Constructor tests - should run on all platforms [TestMethod] public MFTestResults SerialPortConstructor_1() { result = MFTestResults.Pass; try { // Valid cases ConstructorSuccessTest(Serial.COM1); ConstructorSuccessTest(Serial.COM2); ConstructorSuccessTest(Serial.COM3); ConstructorSuccessTest("com4"); ConstructorSuccessTest("CoM5"); ConstructorSuccessTest("Com10"); ConstructorSuccessTest("Com100"); // Negative cases ArgumentExceptionTest(""); ArgumentExceptionTest(null); ArgumentExceptionTest("COM0"); ArgumentExceptionTest("COM" + int.MaxValue + "0"); ArgumentExceptionTest("COM"); ArgumentExceptionTest("SON1"); string longStr = "Com1 long"; for (int i = 0; i < 10; i++) { longStr += longStr; } ArgumentExceptionTest(longStr); } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } [TestMethod] public MFTestResults SerialPortConstructor_2() { result = MFTestResults.Pass; try { // Validate all BaudRate values - no casting/bounds tests ConstructorSuccessTest(BaudRate.Baudrate4800); ConstructorSuccessTest(BaudRate.Baudrate9600); ConstructorSuccessTest(BaudRate.Baudrate19200); ConstructorSuccessTest(BaudRate.Baudrate38400); ConstructorSuccessTest(BaudRate.Baudrate57600); ConstructorSuccessTest(BaudRate.Baudrate115200); ConstructorSuccessTest(BaudRate.Baudrate230400); } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } [TestMethod] public MFTestResults SerialPortConstructor_3() { result = MFTestResults.Pass; try { // Valid cases ConstructorSuccessTest(Parity.Even); ConstructorSuccessTest(Parity.Mark); ConstructorSuccessTest(Parity.None); ConstructorSuccessTest(Parity.Odd); ConstructorSuccessTest(Parity.Space); // No bounds checking so make sure all valid int values are fine. ConstructorSuccessTest(-1); ConstructorSuccessTest(int.MinValue); ConstructorSuccessTest(int.MaxValue); } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } [TestMethod] public MFTestResults SerialPortConstructor_4() { result = MFTestResults.Pass; try { // Valid cases ConstructorSuccessTest(5); ConstructorSuccessTest(6); ConstructorSuccessTest(7); ConstructorSuccessTest(8); ConstructorSuccessTest(9); // No bounds checking so make sure all valid int values are fine. ConstructorSuccessTest(-1); ConstructorSuccessTest(int.MinValue); ConstructorSuccessTest(int.MaxValue); } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } [TestMethod] public MFTestResults SerialPortConstructor_5() { result = MFTestResults.Pass; try { // Valid cases ConstructorSuccessTest(StopBits.None); ConstructorSuccessTest(StopBits.One); ConstructorSuccessTest(StopBits.OnePointFive); ConstructorSuccessTest(StopBits.Two); // No bounds checking so make sure all valid int values are fine. ConstructorSuccessTest(-1); ConstructorSuccessTest(int.MinValue); ConstructorSuccessTest(int.MaxValue); } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } #endregion - Constructor tests #region SerialPort Property tests [TestMethod] public MFTestResults GetSetBaudRate() { result = MFTestResults.Pass; try { using (TestSerialPort serialPort = new TestSerialPort(Serial.COM1)) { serialPort.Eval(serialPort.BaudRate, (int)BaudRate.Baudrate9600); serialPort.BaudRate = (int)BaudRate.Baudrate230400; serialPort.Eval(serialPort.BaudRate, (int)BaudRate.Baudrate230400); serialPort.BaudRate = (int)BaudRate.Baudrate19200; serialPort.EvalOpenClose(serialPort.BaudRate, (int)BaudRate.Baudrate19200); } } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } [TestMethod] public MFTestResults GetSetDataBits() { result = MFTestResults.Pass; try { using (TestSerialPort serialPort = new TestSerialPort(Serial.COM1)) { serialPort.Eval(serialPort.DataBits, 8); serialPort.DataBits = 7; serialPort.EvalOpenClose(serialPort.DataBits, 7); } } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } [TestMethod] public MFTestResults GetSetParity() { result = MFTestResults.Pass; try { using (TestSerialPort serialPort = new TestSerialPort(Serial.COM1)) { serialPort.Eval(serialPort.Parity, Parity.None); serialPort.Parity = Parity.Even; serialPort.Eval(serialPort.Parity, Parity.Even); serialPort.Parity = Parity.Odd; serialPort.EvalOpenClose(serialPort.Parity, Parity.Odd); } } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } [TestMethod] public MFTestResults GetSetStopBits() { result = MFTestResults.Pass; try { using (TestSerialPort serialPort = new TestSerialPort(Serial.COM1)) { serialPort.Eval(serialPort.StopBits, StopBits.One); serialPort.StopBits = StopBits.Two; serialPort.EvalOpenClose(serialPort.StopBits, StopBits.Two); } } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } [TestMethod] public MFTestResults GetSetHandShake() { result = MFTestResults.Pass; try { using (TestSerialPort serialPort = new TestSerialPort(Serial.COM1)) { serialPort.Eval(serialPort.Handshake, Handshake.None); serialPort.Handshake = Handshake.RequestToSend; serialPort.EvalOpenClose(serialPort.Handshake, Handshake.RequestToSend); serialPort.Handshake = Handshake.XOnXOff; serialPort.EvalOpenClose(serialPort.Handshake, Handshake.XOnXOff); } if (portCount > 0) { // Validate we can re-reserve all pins using (TestSerialPort serialPort = new TestSerialPort(Serial.COM1)) { serialPort.Handshake = Handshake.RequestToSend; serialPort.EvalOpenClose(serialPort.Handshake, Handshake.RequestToSend); serialPort.Open(); } } // TODO: Write Desktop tests to validate proper function of RTS/XonXoff } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } [TestMethod] public MFTestResults GetSetReadTimeout() { result = MFTestResults.Pass; try { using (TestSerialPort serialPort = new TestSerialPort(Serial.COM1)) { serialPort.Eval(serialPort.ReadTimeout, Timeout.Infinite); serialPort.ReadTimeout = 100; serialPort.Eval(serialPort.ReadTimeout, 100); serialPort.ReadTimeout = int.MinValue; serialPort.Eval(serialPort.ReadTimeout, int.MinValue); serialPort.ReadTimeout = int.MaxValue; serialPort.EvalOpenClose(serialPort.ReadTimeout, int.MaxValue); serialPort.ReadTimeout = 1000; serialPort.EvalOpenClose(serialPort.ReadTimeout, 1000); } } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } [TestMethod] public MFTestResults GetSetWriteTimeout() { result = MFTestResults.Pass; try { using (TestSerialPort serialPort = new TestSerialPort(Serial.COM1)) { serialPort.Eval(serialPort.WriteTimeout, Timeout.Infinite); serialPort.WriteTimeout = 100; serialPort.Eval(serialPort.WriteTimeout, 100); serialPort.WriteTimeout = int.MinValue; serialPort.Eval(serialPort.WriteTimeout, int.MinValue); serialPort.WriteTimeout = int.MaxValue; serialPort.EvalOpenClose(serialPort.WriteTimeout, int.MaxValue); } } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } [TestMethod] public MFTestResults GetPortName() { result = MFTestResults.Pass; try { using (TestSerialPort serialPort = new TestSerialPort(Serial.COM1)) { serialPort.Eval(serialPort.PortName, Serial.COM1); } if (portCount > 1) { using (TestSerialPort serialPort = new TestSerialPort(Serial.COM2)) { serialPort.Eval(serialPort.PortName, Serial.COM2); } } } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } [TestMethod] public MFTestResults GetBytesToRead() { result = MFTestResults.Pass; try { using (TestSerialPort serialPort = new TestSerialPort(Serial.COM1)) { serialPort.Eval(serialPort.BytesToRead, 0); } } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } [TestMethod] public MFTestResults GetBytesToWrite() { result = MFTestResults.Pass; try { using (TestSerialPort serialPort = new TestSerialPort(Serial.COM1)) { serialPort.Eval(serialPort.BytesToWrite, 0); } } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } #endregion SerialPort Property tests #region Functional Tests [TestMethod] public MFTestResults DataBufferTests() { if (!IsLoopback) return MFTestResults.Skip; result = MFTestResults.Pass; try { using (SerialPort serialPort = new SerialPort(Serial.COM1)) { // set flow control so we can fill both RX/TX buffers serialPort.Handshake = Handshake.RequestToSend; serialPort.WriteTimeout = 1000; serialPort.Open(); // buffer data in RX/TX serialPort.Write(sendbuff, 0, sendbuff.Length); Log.Comment("bytes to send: " + serialPort.BytesToWrite); Log.Comment("bytes to read: " + serialPort.BytesToRead); // clear RX buffer serialPort.DiscardInBuffer(); if (serialPort.BytesToRead != 0) { result = MFTestResults.Fail; Log.Exception(serialPort.BytesToRead + " bytes still in buffer after DiscardInBuffer!"); } // clear TX Buffer serialPort.DiscardOutBuffer(); if (serialPort.BytesToWrite != 0) { // BUGBUG: 21224 result = MFTestResults.Fail; Log.Exception(serialPort.BytesToWrite + " bytes still in buffer after DiscardOutBuffer!"); } serialPort.Close(); } } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } [TestMethod] public MFTestResults LargeSendBuffer() { if (!IsLoopback) return MFTestResults.Skip; result = MFTestResults.Pass; try { using (TestSerialPort serialPort = new TestSerialPort(Serial.COM1)) { serialPort.Handshake = Handshake.RequestToSend; serialPort.Open(); serialPort.AsyncRead = true; string start = MFUtilities.GetRandomSafeString(10000); byte[] buff = Encoding.UTF8.GetBytes(start); serialPort.Write(buff, 0, buff.Length); // wait for data to drain while (serialPort.AsyncResult.Length < start.Length && (serialPort.BytesToWrite > 0 || serialPort.BytesToRead > 0)) { Thread.Sleep(100); } if (serialPort.AsyncResult != start) { Log.Exception("Failed: " + serialPort.AsyncResult + " != " + start); result = MFTestResults.Fail; } // wait to make sure AsyncReader is closed; serialPort.AsyncRead = false; while (serialPort.IsAsyncReading) { Thread.Sleep(100); } } } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } [TestMethod] public MFTestResults VerifyValidChars() { if (!IsLoopback) return MFTestResults.Skip; result = MFTestResults.Pass; try { using (TestSerialPort serialPort = new TestSerialPort(Serial.COM1)) { serialPort.Open(); for (int i = 1; i < 255; i++) { string data = new string((char)i, 10); Log.FilteredComment("i = " + i + " chars: " + data); serialPort.VerifyWrite(data); } } } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } [TestMethod] public MFTestResults AdvancedGetSetTest() { if (!IsLoopback) return MFTestResults.Skip; result = MFTestResults.Pass; try { using (TestSerialPort serialPort = new TestSerialPort(Serial.COM1)) { // Exercise changing rate while open if port is available serialPort.VerifyWrite(); Log.Comment("Change baud and resend"); serialPort.BaudRate = (int)BaudRate.Baudrate19200; serialPort.VerifyWrite(); Log.Comment("Change Parity and resend"); serialPort.Parity = Parity.Even; serialPort.VerifyWrite(); Log.Comment("Change StopBit and resend"); serialPort.StopBits = StopBits.Two; serialPort.VerifyWrite(); Log.Comment("Change DataBits and resend"); serialPort.DataBits = 7; serialPort.VerifyWrite(); } } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } return result; } [TestMethod] public MFTestResults DataRcdEvent() { if (!IsLoopback) return MFTestResults.Skip; // BUGBUG: 21216 result = MFTestResults.Fail; try { eventCount = 0; eventSerialPort = new SerialPort(Serial.COM1); // register before open eventSerialPort.DataReceived += new SerialDataReceivedEventHandler(eventserialPort_DataReceived_BeforeOpen); eventSerialPort.Open(); eventSerialPort.DataReceived += new SerialDataReceivedEventHandler(eventSerialPort_DataReceived_AfterOpen); eventSerialPort.DataReceived += new SerialDataReceivedEventHandler(eventSerialPort_DataReceived_AfterOpen2); eventSerialPort.Write(sendbuff, 0, sendbuff.Length); eventSerialPort.Flush(); for (int i = 0; i < 100; i++) { Thread.Sleep(100); if (eventCount >= 3) { result = MFTestResults.Pass; break; } } Log.Comment(eventCount + " events fired"); eventSerialPort.Close(); } catch (Exception ex) { Log.Exception(ex.Message); } finally { eventSerialPort.Dispose(); } return result; } private SerialError expectedError; [TestMethod] public MFTestResults ErrorRcvdEvent() { if (!IsLoopback || IsEmulator) return MFTestResults.Skip; result = MFTestResults.Pass; try { eventCount = 0; // create a buffer several bytes bigger then internal buffers byte[] buffer = Encoding.UTF8.GetBytes(new string('a', 512+40)); eventSerialPort = new SerialPort(Serial.COM1); eventSerialPort.WriteTimeout = 1000; eventSerialPort.Handshake = Handshake.None; // register events eventSerialPort.ErrorReceived += new SerialErrorReceivedEventHandler(eventSerialPort_ErrorReceived_BeforeOpen); eventSerialPort.Open(); eventSerialPort.ErrorReceived += new SerialErrorReceivedEventHandler(eventSerialPort_ErrorReceived_AfterOpen); // Test RX overflow (no flow control) expectedError = SerialError.RXOver; eventSerialPort.Write(buffer, 0, buffer.Length / 2); Thread.Sleep(100); eventSerialPort.Write(buffer, 0, buffer.Length / 2); eventSerialPort.Close(); Thread.Sleep(500); if (eventCount == 0) { // BUGBUG: 21222 Log.Exception("Expected RXOver events fired, saw " + eventCount + " fired."); result = MFTestResults.Fail; } eventCount = 0; // Test TX overflow (flow control - HW) expectedError = SerialError.TXFull; eventSerialPort.Open(); for (int i = 0; i < 2; i++) { eventSerialPort.Write(buffer, 0, buffer.Length); } eventSerialPort.Close(); Thread.Sleep(500); if (eventCount == 0) { // BUGBUG: 21222 Log.Exception("Expected TXFull events fired, saw " + eventCount + " fired."); result = MFTestResults.Fail; } // TODO: Need to add PC based tests that allow testing Parity, Overrun, and Frame errors. This is done manually now. } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } finally { eventSerialPort.Dispose(); } return result; } #endregion #region Event handlers void eventSerialPort_DataReceived_AfterOpen2(object sender, SerialDataReceivedEventArgs e) { Log.Comment("AfterOpen2 event fired. " + eventSerialPort.BytesToRead + " bytes availabe to read. Event Type: " + e.EventType); if (eventSerialPort.BytesToRead > 0) eventCount++; } void eventSerialPort_DataReceived_AfterOpen(object sender, SerialDataReceivedEventArgs e) { Log.Comment("AfterOpen event fired. " + eventSerialPort.BytesToRead + " bytes availabe to read. Event Type: " + e.EventType); if (eventSerialPort.BytesToRead > 0) eventCount++; } void eventserialPort_DataReceived_BeforeOpen(object sender, SerialDataReceivedEventArgs e) { Log.Comment("BeforeOpen event fired. " + eventSerialPort.BytesToRead + " bytes availabe to read. Event Type: " + e.EventType); if (eventSerialPort.BytesToRead > 0) eventCount++; } void eventSerialPort_ErrorReceived_BeforeOpen(object sender, SerialErrorReceivedEventArgs e) { if (e.EventType == expectedError) { if (eventCount == 0) { Log.Comment("BeforeOpen event fired. " + eventSerialPort.BytesToRead + " bytes availabe to read. Event Type: " + e.EventType); } eventCount++; } // with loopback you can't get a TxFull without an RX FULL else if(!(e.EventType == SerialError.RXOver && expectedError == SerialError.TXFull)) { Log.Exception("Expected EventType " + expectedError + " but received EventType " + e.EventType); result = MFTestResults.Fail; } } void eventSerialPort_ErrorReceived_AfterOpen(object sender, SerialErrorReceivedEventArgs e) { if (e.EventType == expectedError) { if (eventCount == 0) { Log.Comment("AfterOpen event fired. Event Type: " + e.EventType); } eventCount++; } // with loopback you can't get a TxFull without an RX FULL else if (!(e.EventType == SerialError.RXOver && expectedError == SerialError.TXFull)) { Log.Exception("Expected EventType " + expectedError + " but received EventType " + e.EventType); result = MFTestResults.Fail; } } #endregion event handlers #region Private helper functions private void ConstructorSuccessTest(string port) { ConstructorSuccessTest(port, (int)BaudRate.Baudrate9600, Parity.None, 8, StopBits.One); } private void ConstructorSuccessTest(BaudRate baud) { ConstructorSuccessTest(Serial.COM1, (int)baud, Parity.None, 8, StopBits.One); } private void ConstructorSuccessTest(Parity parity) { ConstructorSuccessTest(Serial.COM1, (int)BaudRate.Baudrate9600, parity, 8, StopBits.One); } private void ConstructorSuccessTest(int databits) { ConstructorSuccessTest(Serial.COM1, (int)BaudRate.Baudrate9600, Parity.None, databits, StopBits.One); } private void ConstructorSuccessTest(StopBits stopbits) { ConstructorSuccessTest(Serial.COM1, (int)BaudRate.Baudrate9600, Parity.None, 8, stopbits); } private void ConstructorSuccessTest(string port, int baud, Parity parity, int databits, StopBits stopbits) { try { using (SerialPort serial = new SerialPort(port, baud, parity, databits, stopbits)) { } } catch (ArgumentException) { Log.Comment("Ignore argument exceptions in constructor"); } catch (Exception ex) { Log.Exception("Unexpected exception message for parity: " + parity + " - message: " + ex.Message); result = MFTestResults.Fail; } } private void ArgumentExceptionTest(string port) { if (port == null) ArgumentExceptionTest(port, 9600, Parity.None, 8, StopBits.One, "Exception was thrown: System.ArgumentNullException"); else ArgumentExceptionTest(port, 9600, Parity.None, 8, StopBits.One, "Invalid serial port name"); } private void ArgumentExceptionTest(int parity) { ArgumentExceptionTest(Serial.COM1, 9600, (Parity)parity, 8, StopBits.None, "parity"); } private void ArgumentExceptionTest(string port, int baud, Parity parity, int databits, StopBits stopbits, string message) { try { using (SerialPort serial = new SerialPort(port, baud, parity, databits, stopbits)) { } throw new Exception("SerialPort constructor using " + port + " unexpectedly succeeded. ArgumentException expected"); } catch (ArgumentException ex) { if (ex.Message != message) { Log.Exception("Unexpected exception message for port:" + port + " baud:" + baud + " parity:" + parity + " stopbits:" + stopbits + " - message: " + ex.Message); result = MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception for port:" + port + " baud:" + baud + " parity:" + parity + " stopbits:" + stopbits + " - message: " + ex.Message); result = MFTestResults.Fail; } } private void ValidateSendString(byte[] response) { string readString = new string(Encoding.UTF8.GetChars(response)); if (testString != readString) { result = MFTestResults.Fail; Log.Exception( "<![CDATA[" + testString + " != " + readString + "]]>"); } } #endregion } }
36.171264
179
0.501795
[ "Apache-2.0" ]
Sirokujira/MicroFrameworkPK_v4_3
Test/Platform/Tests/CLR/Microsoft.SPOT.Hardware/EmulateHardware/TestPorts.cs
31,469
C#
namespace Waves.UI.Dialogs.Interfaces { /// <summary> /// Interface for text tools. /// </summary> public interface IWavesDialogTextTool : IWavesDialogTool { /// <summary> /// Gets or sets text. /// </summary> string Text { get; } } }
20.857143
60
0.547945
[ "MIT" ]
ambertape/waves.ui
sources/Waves.UI/Dialogs/Interfaces/IWavesDialogTextTool.cs
294
C#
using UnityEngine; using System.Collections; public class CollectableTrigger : MonoBehaviour { public Collectable[] collectableList; private bool trigger = false; // Update is called once per frame void Update () { if (!trigger) { trigger = true; for (int i = 0; i < collectableList.Length; i++) { if(!collectableList[i]) continue; if(!collectableList[i].atPos || !collectableList[i].activated) { trigger = false; break; } } }else this.GetComponent<TriggerScript>().triggered = true; } }
17.3125
66
0.648014
[ "Apache-2.0" ]
jl4312/Project-Orion-Redo
BridgePrototype/Assets/scripts/Environment Scripts/CollectableTrigger.cs
556
C#
using System.Web.Mvc; namespace MVC5Template.Areas.WebApi { public class WebApiAreaRegistration : AreaRegistration { public override string AreaName { get { return "WebApi"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "WebApi_default", "WebApi/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } ); } } }
23.833333
75
0.506993
[ "MIT" ]
JapanComputerServicesInc/AspnetMVC5Template
MVC5Template/MVC5Template/Areas/WebApi/WebApiAreaRegistration.cs
574
C#
namespace TransitCity.UI { using System; using System.Windows; using System.Windows.Input; using Utility.Coordinates; /// <summary> /// Interaction logic for GameControl.xaml /// </summary> public partial class GameControl { public GameControl() { InitializeComponent(); Focusable = true; Loaded += (s, e) => Keyboard.Focus(this); } public event EventHandler CanvasLoaded; private void FrameworkElement_OnLoaded(object sender, RoutedEventArgs e) { var cityCanvas = sender as CityCanvas; if (cityCanvas != null) { ViewPosition.Size = Math.Min(cityCanvas.ActualHeight, cityCanvas.ActualWidth); CanvasLoaded?.Invoke(null, null); } } } }
25.029412
94
0.571093
[ "MIT" ]
gartenriese2/TransitCity
TransitCity/TransitCity/UI/GameControl.xaml.cs
853
C#
// (c) Copyright HutongGames. All rights reserved. namespace HutongGames.PlayMaker.Actions { [ActionCategory(ActionCategory.Math)] [Tooltip("Sets the value of a Bool Variable.")] public class SetBoolValue : FsmStateAction { [RequiredField] [UIHint(UIHint.Variable)] [Tooltip("Bool Variable to set.")] public FsmBool boolVariable; [RequiredField] [Tooltip("Value to set it to: Check to set to True, Uncheck to set to False.")] public FsmBool boolValue; [Tooltip("Repeat every frame.")] public bool everyFrame; public override void Reset() { boolVariable = null; boolValue = null; everyFrame = false; } public override void OnEnter() { boolVariable.Value = boolValue.Value; if (!everyFrame) Finish(); } public override void OnUpdate() { boolVariable.Value = boolValue.Value; } #if UNITY_EDITOR public override string AutoName() { return ActionHelpers.AutoNameSetVar("SetBool", boolVariable, boolValue); } #endif } }
21.416667
87
0.679961
[ "MIT" ]
aiden-ji/oneButtonBoB
Assets/PlayMaker/Actions/Math/SetBoolValue.cs
1,028
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2021 Ingo Herbote * https://www.yetanotherforum.net/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * https://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace YAF.Pages { #region Using using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.UI.WebControls; using YAF.Core.BaseModules; using YAF.Core.BasePages; using YAF.Core.Extensions; using YAF.Core.Helpers; using YAF.Core.Model; using YAF.Core.Services; using YAF.Types; using YAF.Types.Constants; using YAF.Types.Extensions; using YAF.Types.Flags; using YAF.Types.Interfaces; using YAF.Types.Interfaces.Identity; using YAF.Types.Models; using YAF.Web.Extensions; #endregion /// <summary> /// The Post Private Message Page /// </summary> public partial class PostPrivateMessage : ForumPage { #region Constants and Fields /// <summary> /// message body editor /// </summary> private ForumEditor editor; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref = "PostPrivateMessage" /> class. /// Default constructor. /// </summary> public PostPrivateMessage() : base("PMESSAGE") { } #endregion #region Methods /// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init"/> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param> protected override void OnInit([NotNull] EventArgs e) { if (this.PageContext.BoardSettings.AllowPrivateMessageAttachments) { this.PageContext.PageElements.AddScriptReference("FileUploadScript"); #if DEBUG this.PageContext.PageElements.RegisterCssIncludeContent("jquery.fileupload.comb.css"); #else this.PageContext.PageElements.RegisterCssIncludeContent("jquery.fileupload.comb.min.css"); #endif } base.OnInit(e); } /// <summary> /// Send pm to all users /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void AllUsers_Click([NotNull] object sender, [NotNull] EventArgs e) { // create one entry to show in dropdown var li = new ListItem(this.GetText("ALLUSERS"), "0"); // bind the list to dropdown this.ToList.Items.Add(li); this.ToList.Visible = true; this.To.Text = this.GetText("ALLUSERS"); // hide To text box this.To.Visible = false; // hide find users/all users buttons this.FindUsers.Visible = false; this.AllUsers.Visible = false; this.AllBuddies.Visible = false; // we need clear button now this.Clear.Visible = true; } /// <summary> /// Send PM to all Buddies /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void AllBuddies_Click([NotNull] object sender, [NotNull] EventArgs e) { // try to find users by user name var usersFound = this.Get<IFriends>().ListAll(); var friendsString = new StringBuilder(); if (!usersFound.Any()) { return; } // we found a user(s) usersFound.ForEach( row => friendsString.AppendFormat( "{0};", this.PageContext.BoardSettings.EnableDisplayName ? row.DisplayName : row.Name)); this.To.Text = friendsString.ToString(); // hide find users/all users buttons this.FindUsers.Visible = false; this.AllUsers.Visible = false; this.AllBuddies.Visible = false; // we need clear button now this.Clear.Visible = true; } /// <summary> /// Redirect user back to his PM inbox /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void Cancel_Click([NotNull] object sender, [NotNull] EventArgs e) { this.Get<LinkBuilder>().Redirect(ForumPages.MyMessages); } /// <summary> /// Clears the User List /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void Clear_Click([NotNull] object sender, [NotNull] EventArgs e) { // clear drop down this.ToList.Items.Clear(); // hide it and show empty To text box this.ToList.Visible = false; this.To.Text = string.Empty; this.To.Visible = true; // show find users and all users (if user is admin) this.FindUsers.Visible = true; this.AllUsers.Visible = this.PageContext.IsAdmin; this.AllBuddies.Visible = this.PageContext.UserHasBuddies; // clear button is not necessary now this.Clear.Visible = false; } /// <summary> /// Creates page links for this page. /// </summary> protected override void CreatePageLinks() { // forum index this.PageLinks.AddRoot(); // users control panel this.PageLinks.AddLink(this.PageContext.User.DisplayOrUserName(), this.Get<LinkBuilder>().GetLink(ForumPages.MyAccount)); // private messages this.PageLinks.AddLink( this.GetText(ForumPages.MyMessages.ToString(), "TITLE"), this.Get<LinkBuilder>().GetLink(ForumPages.MyMessages)); // post new message this.PageLinks.AddLink(this.GetText("TITLE")); } /// <summary> /// Find Users /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void FindUsers_Click([NotNull] object sender, [NotNull] EventArgs e) { if (this.To.Text.Length < 2) { // need at least 2 letters of user's name this.PageContext.AddLoadMessage(this.GetText("NEED_MORE_LETTERS"), MessageTypes.warning); return; } // try to find users by user name var usersFound = this.Get<IUserDisplayName>().FindUserContainsName(this.To.Text.Trim()).Where( u => !u.Block.BlockPMs && u.UserFlags.IsApproved && u.ID != this.PageContext.PageUserID).ToList(); if (usersFound.Any()) { // we found a user(s) this.ToList.DataSource = usersFound; this.ToList.DataValueField = "ID"; this.ToList.DataTextField = this.PageContext.BoardSettings.EnableDisplayName ? "DisplayName" : "Name"; this.ToList.DataBind(); // ToList.SelectedIndex = 0; // hide To text box and show To drop down this.ToList.Visible = true; this.To.Visible = false; // find is no more needed this.FindUsers.Visible = false; // we need clear button displayed now this.Clear.Visible = true; } else { // user not found this.PageContext.AddLoadMessage(this.GetText("USER_NOTFOUND"), MessageTypes.danger); return; } // re-bind data to the controls this.DataBind(); } /// <summary> /// Handles the Initialization event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void Page_Init([NotNull] object sender, [NotNull] EventArgs e) { this.editor = ForumEditorHelper.GetCurrentForumEditor(); this.editor.MaxCharacters = this.PageContext.BoardSettings.MaxPostSize; this.EditorLine.Controls.Add(this.editor); this.editor.UserCanUpload = this.PageContext.BoardSettings.AllowPrivateMessageAttachments; // add editor to the page this.EditorLine.Controls.Add(this.editor); } /// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { // if user isn't authenticated, redirect him to login page if (this.User == null || this.PageContext.IsGuest) { this.RedirectNoAccess(); } // this needs to be done just once, not during post-backs if (this.IsPostBack) { return; } // only administrators can send messages to all users this.AllUsers.Visible = this.PageContext.IsAdmin; this.AllBuddies.Visible = this.PageContext.UserHasBuddies; // Is Reply if (this.Get<HttpRequestBase>().QueryString.Exists("p")) { // PM is a reply or quoted reply (isQuoting) // to the given message id "p" var isQuoting = this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("q") == "1"; var isReport = this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("report") == "1"; // get quoted message var replyMessage = this.GetRepository<PMessage>().GetMessage( this.Get<LinkBuilder>().StringToIntOrRedirect(this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("p"))); // there is such a message if (replyMessage == null) { return; } // get message sender/recipient var toUserId = replyMessage.ToUserID; var fromUserId = replyMessage.FromUserID; // verify access to this PM if (toUserId != this.PageContext.PageUserID && fromUserId != this.PageContext.PageUserID) { this.Get<LinkBuilder>().AccessDenied(); } // handle subject var subject = replyMessage.Subject; if (!subject.StartsWith("Re: ")) { subject = $"Re: {subject}"; } this.PmSubjectTextBox.Text = subject; var displayName = this.Get<IUserDisplayName>().GetNameById(fromUserId); // set "To" user and disable changing... this.To.Text = displayName; this.To.Enabled = false; this.FindUsers.Visible = false; this.AllUsers.Visible = false; this.AllBuddies.Visible = false; if (!isQuoting) { return; } // PM is a quoted reply var body = replyMessage.Body; if (this.PageContext.BoardSettings.RemoveNestedQuotes) { body = this.Get<IFormatMessage>().RemoveNestedQuotes(body); } // Ensure quoted replies have bad words removed from them body = this.Get<IBadWordReplace>().Replace(body); // Quote the original message body = $"[QUOTE={displayName}]{body}[/QUOTE]"; // we don't want any whitespaces at the beginning of message this.editor.Text = body.TrimStart(); if (!isReport) { return; } var hostUser = this.GetRepository<User>().Get(u => u.BoardID == this.PageContext.PageBoardID && u.UserFlags.IsHostAdmin).FirstOrDefault(); if (hostUser != null) { this.To.Text = hostUser.DisplayOrUserName(); this.PmSubjectTextBox.Text = this.GetTextFormatted("REPORT_SUBJECT", displayName); var bodyReport = $"[QUOTE={displayName}]{replyMessage.Body}[/QUOTE]"; // Quote the original message bodyReport = this.GetTextFormatted("REPORT_BODY", bodyReport); // we don't want any whitespaces at the beginning of message this.editor.Text = bodyReport.TrimStart(); } else { this.Get<LinkBuilder>().AccessDenied(); } } else if (this.Get<HttpRequestBase>().QueryString.Exists("u") && this.Get<HttpRequestBase>().QueryString.Exists("r")) { // PM is being send as a quoted reply to a reported post // We check here if the user have access to the option if (!this.PageContext.IsModeratorInAnyForum && !this.PageContext.IsForumModerator) { return; } // get quoted message var reporter = this.GetRepository<User>().MessageReporter( this.Get<LinkBuilder>().StringToIntOrRedirect( this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("r")), this.Get<LinkBuilder>().StringToIntOrRedirect( this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("u"))) .FirstOrDefault(); // there is such a message // message info should be always returned as 1 row if (reporter == null) { return; } // handle subject this.PmSubjectTextBox.Text = this.GetText("REPORTED_SUBJECT"); var displayName = this.Get<IUserDisplayName>().GetNameById(reporter.Item1.ID); // set "To" user and disable changing... this.To.Text = displayName; this.To.Enabled = false; this.FindUsers.Visible = false; this.AllUsers.Visible = false; this.AllBuddies.Visible = false; // Parse content with delimiter '|' var quoteList = reporter.Item2.ReportText.Split('|'); // Quoted replies should have bad words in them // Reply to report PM is always a quoted reply // Quote the original message in a cycle for (var i = 0; i < quoteList.Length; i++) { // Add quote codes quoteList[i] = $"[QUOTE={displayName}]{quoteList[i]}[/QUOTE]\r\n"; // Replace DateTime delimiter '??' by ': ' // we don't want any whitespaces at the beginning of message this.editor.Text = quoteList[i].Replace("??", ": ") + this.editor.Text.TrimStart(); } } else if (this.Get<HttpRequestBase>().QueryString.Exists("u")) { // find user var foundUser = this.GetRepository<User>().GetById(this.Get<LinkBuilder>().StringToIntOrRedirect( this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("u"))); if (foundUser == null) { return; } if (foundUser.ID == this.PageContext.PageUserID) { return; } this.To.Text = foundUser.DisplayOrUserName(); this.To.Enabled = false; // hide find user/all users buttons this.FindUsers.Visible = false; this.AllUsers.Visible = false; this.AllBuddies.Visible = false; } else { // Blank PM // multi-receiver info is relevant only when sending blank PM if (this.PageContext.BoardSettings.PrivateMessageMaxRecipients < 1 || this.PageContext.IsAdmin) { return; } // format localized string this.MultiReceiverInfo.Text = $"{string.Format(this.GetText("MAX_RECIPIENT_INFO"), this.PageContext.BoardSettings.PrivateMessageMaxRecipients)} {this.GetText("MULTI_RECEIVER_INFO")}"; // display info this.MultiReceiverAlert.Visible = true; } } /// <summary> /// Previews the Message Output /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void Preview_Click([NotNull] object sender, [NotNull] EventArgs e) { // make preview row visible this.PreviewRow.Visible = true; this.PreviewMessagePost.MessageFlags.IsHtml = this.editor.UsesHTML; this.PreviewMessagePost.MessageFlags.IsBBCode = this.editor.UsesBBCode; this.PreviewMessagePost.Message = this.editor.Text; this.PreviewMessagePost.MessageID = 0; if (!this.PageContext.BoardSettings.AllowSignatures) { return; } var user = this.GetRepository<User>().GetById(this.PageContext.PageUserID); if (user.Signature.IsSet()) { this.PreviewMessagePost.Signature = user.Signature; } } /// <summary> /// Send Private Message /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void Save_Click([NotNull] object sender, [NotNull] EventArgs e) { var replyTo = this.Get<HttpRequestBase>().QueryString.Exists("p") ? this.Get<HttpRequestBase>().QueryString.GetFirstOrDefaultAsInt("p") : null; // Check if quoted message is Reply if (replyTo.HasValue) { var reply = this.GetRepository<PMessage>().GetSingle( m => m.ID == replyTo.Value); if (reply.ReplyTo is > 0) { replyTo = reply.ReplyTo.Value; } } // recipient was set in dropdown if (this.ToList.Visible) { this.To.Text = this.ToList.SelectedItem.Text; } if (this.To.Text.Length <= 0) { // recipient is required field this.PageContext.AddLoadMessage(this.GetText("need_to"), MessageTypes.warning); return; } // subject is required if (this.PmSubjectTextBox.Text.Trim().Length <= 0) { this.PageContext.AddLoadMessage(this.GetText("need_subject"), MessageTypes.warning); return; } // message is required if (this.editor.Text.Trim().Length <= 0) { this.PageContext.AddLoadMessage(this.GetText("need_message"), MessageTypes.warning); return; } if (this.ToList.SelectedItem is { Value: "0" }) { // administrator is sending PMs to all users var body = this.editor.Text; var messageFlags = new MessageFlags { IsHtml = this.editor.UsesHTML, IsBBCode = this.editor.UsesBBCode }; // test user's PM count if (!this.VerifyMessageAllowed(1, body)) { return; } this.GetRepository<PMessage>().SendMessage( this.PageContext.PageUserID, 0, this.PmSubjectTextBox.Text, body, messageFlags.BitValue, replyTo); // redirect to outbox (sent items), not control panel this.Get<LinkBuilder>().Redirect(ForumPages.MyMessages, "v={0}", "out"); } else { // remove all abundant whitespaces and separators var rx = new Regex(@";(\s|;)*;"); this.To.Text = rx.Replace(this.To.Text, ";"); if (this.To.Text.StartsWith(";")) { this.To.Text = this.To.Text.Substring(1); } if (this.To.Text.EndsWith(";")) { this.To.Text = this.To.Text.Substring(0, this.To.Text.Length - 1); } rx = new Regex(@"\s*;\s*"); this.To.Text = rx.Replace(this.To.Text, ";"); // list of recipients var recipients = new List<string>(this.To.Text.Trim().Split(';')); if (recipients.Count > this.PageContext.BoardSettings.PrivateMessageMaxRecipients && !this.PageContext.IsAdmin && this.PageContext.BoardSettings.PrivateMessageMaxRecipients != 0) { // to many recipients this.PageContext.AddLoadMessage( this.GetTextFormatted( "TOO_MANY_RECIPIENTS", this.PageContext.BoardSettings.PrivateMessageMaxRecipients), MessageTypes.warning); return; } if (!this.VerifyMessageAllowed(recipients.Count, this.editor.Text)) { return; } // list of recipient's ids var recipientIds = new List<int>(); // get recipients' IDs foreach (var recipient in recipients) { var user = this.Get<IUserDisplayName>().FindUserByName(recipient); if (user == null) { this.PageContext.AddLoadMessage( this.GetTextFormatted("NO_SUCH_USER", recipient), MessageTypes.warning); return; } if (user.UserFlags.IsGuest) { this.PageContext.AddLoadMessage(this.GetText("NOT_GUEST"), MessageTypes.danger); return; } // get recipient's ID from the database if (!recipientIds.Contains(user.ID)) { recipientIds.Add(user.ID); } var count = this.GetRepository<PMessage>().UserMessageCount(user.ID); // test receiving user's PM count if (count.NumberTotal + 1 < count.Allowed || this.PageContext.IsAdmin || this.Get<IAspNetUsersHelper>().GetBoardUser(user.ID, this.PageContext.PageBoardID).Item4.IsAdmin > 0) { continue; } // recipient has full PM box this.PageContext.AddLoadMessage( this.GetTextFormatted("RECIPIENTS_PMBOX_FULL", recipient), MessageTypes.danger); return; } // send PM to all recipients recipientIds.ForEach( userId => { var body = this.editor.Text; var messageFlags = new MessageFlags { IsHtml = this.editor.UsesHTML, IsBBCode = this.editor.UsesBBCode }; this.GetRepository<PMessage>().SendMessage( this.PageContext.PageUserID, userId, this.PmSubjectTextBox.Text, body, messageFlags.BitValue, replyTo); // reset lazy data as he should be informed at once this.Get<IDataCache>().Remove(string.Format(Constants.Cache.ActiveUserLazyData, userId)); if (this.PageContext.BoardSettings.AllowPMEmailNotification) { this.Get<ISendNotification>().ToPrivateMessageRecipient( userId, this.PmSubjectTextBox.Text.Trim()); } }); // redirect to outbox (sent items), not control panel this.Get<LinkBuilder>().Redirect(ForumPages.MyMessages, "v={0}", "out"); } } /// <summary> /// Verifies the message allowed. /// </summary> /// <param name="count">The recipients count.</param> /// <param name="message">The message.</param> /// <returns> /// Returns if the user is allowed to send a message or not /// </returns> private bool VerifyMessageAllowed(int count, string message) { // Check if SPAM Message first... if (!this.PageContext.IsAdmin && !this.PageContext.ForumModeratorAccess && !this.PageContext.BoardSettings.SpamServiceType.Equals(0)) { // Check content for spam if (!this.Get<ISpamCheck>().CheckPostForSpam( this.PageContext.IsGuest ? "Guest" : this.PageContext.User.DisplayOrUserName(), this.PageContext.Get<HttpRequestBase>().GetUserRealIPAddress(), message, this.PageContext.MembershipUser.Email, out var spamResult)) { return !this.Get<ISpamCheck>().ContainsSpamUrls(message); } var description = $@"Spam Check detected possible SPAM ({spamResult}) posted by User: {(this.PageContext.IsGuest ? "Guest" : this.PageContext.User.DisplayOrUserName())}"; switch (this.PageContext.BoardSettings.SpamMessageHandling) { case 0: this.Logger.SpamMessageDetected( this.PageContext.PageUserID, description); break; case 1: this.Logger.SpamMessageDetected( this.PageContext.PageUserID, $"{description}, it was flagged as unapproved post"); break; case 2: this.Logger.SpamMessageDetected( this.PageContext.PageUserID, $"{description}, post was rejected"); this.PageContext.AddLoadMessage(this.GetText("SPAM_MESSAGE"), MessageTypes.danger); break; case 3: this.Logger.SpamMessageDetected( this.PageContext.PageUserID, $"{description}, user was deleted and bannded"); this.Get<IAspNetUsersHelper>().DeleteAndBanUser( this.PageContext.PageUserID, this.PageContext.MembershipUser, this.PageContext.User.IP); break; } return false; } /////////////////////////////// // test sending user's PM count // get user's name var countInfo = this.GetRepository<PMessage>().UserMessageCount(this.PageContext.PageUserID); if (countInfo.NumberTotal + count <= countInfo.Allowed || this.PageContext.IsAdmin) { return true; } // user has full PM box this.PageContext.AddLoadMessage( this.GetTextFormatted("OWN_PMBOX_FULL", countInfo.Allowed), MessageTypes.danger); return false; } #endregion } }
38.819071
174
0.498299
[ "Apache-2.0" ]
thecarnie/YAFNET
yafsrc/YetAnotherForum.NET/Pages/PostPrivateMessage.ascx.cs
30,940
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/shellapi.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="SHNAMEMAPPINGW" /> struct.</summary> public static unsafe partial class SHNAMEMAPPINGWTests { /// <summary>Validates that the <see cref="SHNAMEMAPPINGW" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<SHNAMEMAPPINGW>(), Is.EqualTo(sizeof(SHNAMEMAPPINGW))); } /// <summary>Validates that the <see cref="SHNAMEMAPPINGW" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(SHNAMEMAPPINGW).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="SHNAMEMAPPINGW" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(SHNAMEMAPPINGW), Is.EqualTo(24)); } else { Assert.That(sizeof(SHNAMEMAPPINGW), Is.EqualTo(16)); } } } }
35.795455
145
0.632381
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
tests/Interop/Windows/um/shellapi/SHNAMEMAPPINGWTests.cs
1,577
C#
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System.Linq.Expressions; using System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.Scripting.Utils; using AstUtils = Microsoft.Scripting.Ast.Utils; using RuntimeHelpers = Microsoft.Scripting.Runtime.ScriptingRuntimeHelpers; namespace Microsoft.Scripting.Actions.Calls { /// <summary> /// An argument that the user wants to explicitly pass by-reference (with copy-in copy-out semantics). /// The user passes a StrongBox[T] object whose value will get updated when the call returns. /// </summary> internal sealed class ReferenceArgBuilder : SimpleArgBuilder { private readonly Type _elementType; private ParameterExpression _tmp; public ReferenceArgBuilder(ParameterInfo info, Type elementType, Type strongBox, int index) : base(info, strongBox, index, false, false) { _elementType = elementType; } protected override SimpleArgBuilder Copy(int newIndex) { return new ReferenceArgBuilder(ParameterInfo, _elementType, Type, newIndex); } public override ArgBuilder Clone(ParameterInfo newType) { Type elementType = newType.ParameterType.GetElementType(); return new ReferenceArgBuilder(newType, elementType, typeof(StrongBox<>).MakeGenericType(elementType), Index); } public override int Priority { get { return 5; } } internal protected override Expression ToExpression(OverloadResolver resolver, RestrictedArguments args, bool[] hasBeenUsed) { if (_tmp == null) { _tmp = resolver.GetTemporary(_elementType, "outParam"); } Debug.Assert(!hasBeenUsed[Index]); hasBeenUsed[Index] = true; Expression arg = args.GetObject(Index).Expression; return Expression.Condition( Expression.TypeIs(arg, Type), Expression.Assign( _tmp, Expression.Field( AstUtils.Convert(arg, Type), Type.GetDeclaredField("Value") ) ), Expression.Throw( Expression.Call( new Func<Type, object, Exception>(RuntimeHelpers.MakeIncorrectBoxTypeError).GetMethodInfo(), AstUtils.Constant(_elementType), AstUtils.Convert(arg, typeof(object)) ), _elementType ) ); } internal override Expression UpdateFromReturn(OverloadResolver resolver, RestrictedArguments args) { return Expression.Assign( Expression.Field( Expression.Convert(args.GetObject(Index).Expression, Type), Type.GetDeclaredField("Value") ), _tmp ); } internal override Expression ByRefArgument { get { return _tmp; } } } }
38.744898
134
0.591783
[ "MIT" ]
IMaeland/IronSmalltalk
DLR/Microsoft.Dynamic/Actions/Calls/ReferenceArgBuilder.cs
3,797
C#
using System; using System.Collections.Generic; namespace DeviceSim.DataObjects.Models { public partial class TripPoints { public string Id { get; set; } public string TripId { get; set; } public double Latitude { get; set; } public double Longitude { get; set; } public double Speed { get; set; } public DateTime RecordedTimeStamp { get; set; } public int Sequence { get; set; } public double Rpm { get; set; } public double ShortTermFuelBank { get; set; } public double LongTermFuelBank { get; set; } public double ThrottlePosition { get; set; } public double RelativeThrottlePosition { get; set; } public double Runtime { get; set; } public double DistanceWithMalfunctionLight { get; set; } public double EngineLoad { get; set; } public double MassFlowRate { get; set; } public double EngineFuelRate { get; set; } public string Vin { get; set; } public bool HasObddata { get; set; } public bool HasSimulatedObddata { get; set; } public byte[] Version { get; set; } public DateTimeOffset CreatedAt { get; set; } public DateTimeOffset? UpdatedAt { get; set; } public bool Deleted { get; set; } public Trips Trip { get; set; } } }
37.388889
64
0.615899
[ "MIT" ]
AndrewConniff/openhack-devops-proctor
simulator/DeviceSim/DataObjects/Models/TripPoints.cs
1,348
C#
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\d3d12.h(14211,9) using System; using System.Runtime.InteropServices; namespace DirectN { [StructLayout(LayoutKind.Sequential)] public partial struct D3D12_AUTO_BREADCRUMB_NODE1 { [MarshalAs(UnmanagedType.LPStr)] public byte pCommandListDebugNameA; [MarshalAs(UnmanagedType.LPWStr)] public string pCommandListDebugNameW; [MarshalAs(UnmanagedType.LPStr)] public byte pCommandQueueDebugNameA; [MarshalAs(UnmanagedType.LPWStr)] public string pCommandQueueDebugNameW; public IntPtr pCommandList; public IntPtr pCommandQueue; public uint BreadcrumbCount; public IntPtr pLastBreadcrumbValue; public IntPtr pCommandHistory; public IntPtr pNext; public uint BreadcrumbContextsCount; public IntPtr pBreadcrumbContexts; } }
34.142857
84
0.685146
[ "MIT" ]
Steph55/DirectN
DirectN/DirectN/Generated/D3D12_AUTO_BREADCRUMB_NODE1.cs
958
C#
using System.Collections.Generic; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Skoruba.IdentityServer4.Admin.Constants; namespace Skoruba.IdentityServer4.Admin.Controllers { [Authorize] public class AccountController : BaseController { public AccountController(ILogger<ConfigurationController> logger) : base(logger) { } public IActionResult AccessDenied() { return View(); } public IActionResult Logout() { return new SignOutResult(new List<string> { AuthorizationConsts.SignInScheme, AuthorizationConsts.OidcAuthenticationScheme }, new AuthenticationProperties { RedirectUri = "/" }); } } }
28
137
0.694048
[ "MIT" ]
Sindrenj/IdentityServer4.Admin
src/Skoruba.IdentityServer4.Admin/Controllers/AccountController.cs
842
C#
using DesktopWidgets.Helpers; using DesktopWidgets.WidgetBase; using DesktopWidgets.WidgetBase.ViewModel; namespace DesktopWidgets.Widgets.Calculator { public class ViewModel : WidgetViewModelBase { public ViewModel(WidgetId id) : base(id) { Settings = id.GetSettings() as Settings; if (Settings == null) { } } public Settings Settings { get; } } }
23.315789
52
0.616253
[ "Apache-2.0" ]
Yourrrrlove/DesktopWidgets
DesktopWidgets/Widgets/Calculator/ViewModel.cs
445
C#
using TES3Lib.Base; using Utility; namespace TES3Lib.Subrecords.REFR { public class INDX : Subrecord { public int Unknown { get; set; } public INDX() { } public INDX(byte[] rawData) : base(rawData) { var reader = new ByteReader(); Unknown = reader.ReadBytes<int>(base.Data, base.Size); } } }
18.47619
66
0.53866
[ "MIT" ]
NullCascade/TES3Tool
TES3Lib/Subrecords/REFR/INDX.cs
390
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: grafeas/v1/grafeas.proto // </auto-generated> // Original file comments: // Copyright 2019 The Grafeas Authors. 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. // #pragma warning disable 0414, 1591 #region Designer generated code using grpc = global::Grpc.Core; namespace Grafeas.V1 { /// <summary> /// [Grafeas](https://grafeas.io) API. /// /// Retrieves analysis results of Cloud components such as Docker container /// images. /// /// Analysis results are stored as a series of occurrences. An `Occurrence` /// contains information about a specific analysis instance on a resource. An /// occurrence refers to a `Note`. A note contains details describing the /// analysis and is generally stored in a separate project, called a `Provider`. /// Multiple occurrences can refer to the same note. /// /// For example, an SSL vulnerability could affect multiple images. In this case, /// there would be one note for the vulnerability and an occurrence for each /// image with the vulnerability referring to that note. /// </summary> public static partial class Grafeas { static readonly string __ServiceName = "grafeas.v1.Grafeas"; static void __Helper_SerializeMessage(global::Google.Protobuf.IMessage message, grpc::SerializationContext context) { #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION if (message is global::Google.Protobuf.IBufferMessage) { context.SetPayloadLength(message.CalculateSize()); global::Google.Protobuf.MessageExtensions.WriteTo(message, context.GetBufferWriter()); context.Complete(); return; } #endif context.Complete(global::Google.Protobuf.MessageExtensions.ToByteArray(message)); } static class __Helper_MessageCache<T> { public static readonly bool IsBufferMessage = global::System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(global::Google.Protobuf.IBufferMessage)).IsAssignableFrom(typeof(T)); } static T __Helper_DeserializeMessage<T>(grpc::DeserializationContext context, global::Google.Protobuf.MessageParser<T> parser) where T : global::Google.Protobuf.IMessage<T> { #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION if (__Helper_MessageCache<T>.IsBufferMessage) { return parser.ParseFrom(context.PayloadAsReadOnlySequence()); } #endif return parser.ParseFrom(context.PayloadAsNewBuffer()); } static readonly grpc::Marshaller<global::Grafeas.V1.GetOccurrenceRequest> __Marshaller_grafeas_v1_GetOccurrenceRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.GetOccurrenceRequest.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.Occurrence> __Marshaller_grafeas_v1_Occurrence = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.Occurrence.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.ListOccurrencesRequest> __Marshaller_grafeas_v1_ListOccurrencesRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.ListOccurrencesRequest.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.ListOccurrencesResponse> __Marshaller_grafeas_v1_ListOccurrencesResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.ListOccurrencesResponse.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.DeleteOccurrenceRequest> __Marshaller_grafeas_v1_DeleteOccurrenceRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.DeleteOccurrenceRequest.Parser)); static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_google_protobuf_Empty = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Protobuf.WellKnownTypes.Empty.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.CreateOccurrenceRequest> __Marshaller_grafeas_v1_CreateOccurrenceRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.CreateOccurrenceRequest.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.BatchCreateOccurrencesRequest> __Marshaller_grafeas_v1_BatchCreateOccurrencesRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.BatchCreateOccurrencesRequest.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.BatchCreateOccurrencesResponse> __Marshaller_grafeas_v1_BatchCreateOccurrencesResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.BatchCreateOccurrencesResponse.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.UpdateOccurrenceRequest> __Marshaller_grafeas_v1_UpdateOccurrenceRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.UpdateOccurrenceRequest.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.GetOccurrenceNoteRequest> __Marshaller_grafeas_v1_GetOccurrenceNoteRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.GetOccurrenceNoteRequest.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.Note> __Marshaller_grafeas_v1_Note = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.Note.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.GetNoteRequest> __Marshaller_grafeas_v1_GetNoteRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.GetNoteRequest.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.ListNotesRequest> __Marshaller_grafeas_v1_ListNotesRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.ListNotesRequest.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.ListNotesResponse> __Marshaller_grafeas_v1_ListNotesResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.ListNotesResponse.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.DeleteNoteRequest> __Marshaller_grafeas_v1_DeleteNoteRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.DeleteNoteRequest.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.CreateNoteRequest> __Marshaller_grafeas_v1_CreateNoteRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.CreateNoteRequest.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.BatchCreateNotesRequest> __Marshaller_grafeas_v1_BatchCreateNotesRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.BatchCreateNotesRequest.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.BatchCreateNotesResponse> __Marshaller_grafeas_v1_BatchCreateNotesResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.BatchCreateNotesResponse.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.UpdateNoteRequest> __Marshaller_grafeas_v1_UpdateNoteRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.UpdateNoteRequest.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.ListNoteOccurrencesRequest> __Marshaller_grafeas_v1_ListNoteOccurrencesRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.ListNoteOccurrencesRequest.Parser)); static readonly grpc::Marshaller<global::Grafeas.V1.ListNoteOccurrencesResponse> __Marshaller_grafeas_v1_ListNoteOccurrencesResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Grafeas.V1.ListNoteOccurrencesResponse.Parser)); static readonly grpc::Method<global::Grafeas.V1.GetOccurrenceRequest, global::Grafeas.V1.Occurrence> __Method_GetOccurrence = new grpc::Method<global::Grafeas.V1.GetOccurrenceRequest, global::Grafeas.V1.Occurrence>( grpc::MethodType.Unary, __ServiceName, "GetOccurrence", __Marshaller_grafeas_v1_GetOccurrenceRequest, __Marshaller_grafeas_v1_Occurrence); static readonly grpc::Method<global::Grafeas.V1.ListOccurrencesRequest, global::Grafeas.V1.ListOccurrencesResponse> __Method_ListOccurrences = new grpc::Method<global::Grafeas.V1.ListOccurrencesRequest, global::Grafeas.V1.ListOccurrencesResponse>( grpc::MethodType.Unary, __ServiceName, "ListOccurrences", __Marshaller_grafeas_v1_ListOccurrencesRequest, __Marshaller_grafeas_v1_ListOccurrencesResponse); static readonly grpc::Method<global::Grafeas.V1.DeleteOccurrenceRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteOccurrence = new grpc::Method<global::Grafeas.V1.DeleteOccurrenceRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "DeleteOccurrence", __Marshaller_grafeas_v1_DeleteOccurrenceRequest, __Marshaller_google_protobuf_Empty); static readonly grpc::Method<global::Grafeas.V1.CreateOccurrenceRequest, global::Grafeas.V1.Occurrence> __Method_CreateOccurrence = new grpc::Method<global::Grafeas.V1.CreateOccurrenceRequest, global::Grafeas.V1.Occurrence>( grpc::MethodType.Unary, __ServiceName, "CreateOccurrence", __Marshaller_grafeas_v1_CreateOccurrenceRequest, __Marshaller_grafeas_v1_Occurrence); static readonly grpc::Method<global::Grafeas.V1.BatchCreateOccurrencesRequest, global::Grafeas.V1.BatchCreateOccurrencesResponse> __Method_BatchCreateOccurrences = new grpc::Method<global::Grafeas.V1.BatchCreateOccurrencesRequest, global::Grafeas.V1.BatchCreateOccurrencesResponse>( grpc::MethodType.Unary, __ServiceName, "BatchCreateOccurrences", __Marshaller_grafeas_v1_BatchCreateOccurrencesRequest, __Marshaller_grafeas_v1_BatchCreateOccurrencesResponse); static readonly grpc::Method<global::Grafeas.V1.UpdateOccurrenceRequest, global::Grafeas.V1.Occurrence> __Method_UpdateOccurrence = new grpc::Method<global::Grafeas.V1.UpdateOccurrenceRequest, global::Grafeas.V1.Occurrence>( grpc::MethodType.Unary, __ServiceName, "UpdateOccurrence", __Marshaller_grafeas_v1_UpdateOccurrenceRequest, __Marshaller_grafeas_v1_Occurrence); static readonly grpc::Method<global::Grafeas.V1.GetOccurrenceNoteRequest, global::Grafeas.V1.Note> __Method_GetOccurrenceNote = new grpc::Method<global::Grafeas.V1.GetOccurrenceNoteRequest, global::Grafeas.V1.Note>( grpc::MethodType.Unary, __ServiceName, "GetOccurrenceNote", __Marshaller_grafeas_v1_GetOccurrenceNoteRequest, __Marshaller_grafeas_v1_Note); static readonly grpc::Method<global::Grafeas.V1.GetNoteRequest, global::Grafeas.V1.Note> __Method_GetNote = new grpc::Method<global::Grafeas.V1.GetNoteRequest, global::Grafeas.V1.Note>( grpc::MethodType.Unary, __ServiceName, "GetNote", __Marshaller_grafeas_v1_GetNoteRequest, __Marshaller_grafeas_v1_Note); static readonly grpc::Method<global::Grafeas.V1.ListNotesRequest, global::Grafeas.V1.ListNotesResponse> __Method_ListNotes = new grpc::Method<global::Grafeas.V1.ListNotesRequest, global::Grafeas.V1.ListNotesResponse>( grpc::MethodType.Unary, __ServiceName, "ListNotes", __Marshaller_grafeas_v1_ListNotesRequest, __Marshaller_grafeas_v1_ListNotesResponse); static readonly grpc::Method<global::Grafeas.V1.DeleteNoteRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteNote = new grpc::Method<global::Grafeas.V1.DeleteNoteRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "DeleteNote", __Marshaller_grafeas_v1_DeleteNoteRequest, __Marshaller_google_protobuf_Empty); static readonly grpc::Method<global::Grafeas.V1.CreateNoteRequest, global::Grafeas.V1.Note> __Method_CreateNote = new grpc::Method<global::Grafeas.V1.CreateNoteRequest, global::Grafeas.V1.Note>( grpc::MethodType.Unary, __ServiceName, "CreateNote", __Marshaller_grafeas_v1_CreateNoteRequest, __Marshaller_grafeas_v1_Note); static readonly grpc::Method<global::Grafeas.V1.BatchCreateNotesRequest, global::Grafeas.V1.BatchCreateNotesResponse> __Method_BatchCreateNotes = new grpc::Method<global::Grafeas.V1.BatchCreateNotesRequest, global::Grafeas.V1.BatchCreateNotesResponse>( grpc::MethodType.Unary, __ServiceName, "BatchCreateNotes", __Marshaller_grafeas_v1_BatchCreateNotesRequest, __Marshaller_grafeas_v1_BatchCreateNotesResponse); static readonly grpc::Method<global::Grafeas.V1.UpdateNoteRequest, global::Grafeas.V1.Note> __Method_UpdateNote = new grpc::Method<global::Grafeas.V1.UpdateNoteRequest, global::Grafeas.V1.Note>( grpc::MethodType.Unary, __ServiceName, "UpdateNote", __Marshaller_grafeas_v1_UpdateNoteRequest, __Marshaller_grafeas_v1_Note); static readonly grpc::Method<global::Grafeas.V1.ListNoteOccurrencesRequest, global::Grafeas.V1.ListNoteOccurrencesResponse> __Method_ListNoteOccurrences = new grpc::Method<global::Grafeas.V1.ListNoteOccurrencesRequest, global::Grafeas.V1.ListNoteOccurrencesResponse>( grpc::MethodType.Unary, __ServiceName, "ListNoteOccurrences", __Marshaller_grafeas_v1_ListNoteOccurrencesRequest, __Marshaller_grafeas_v1_ListNoteOccurrencesResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Grafeas.V1.GrafeasReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of Grafeas</summary> [grpc::BindServiceMethod(typeof(Grafeas), "BindService")] public abstract partial class GrafeasBase { /// <summary> /// Gets the specified occurrence. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grafeas.V1.Occurrence> GetOccurrence(global::Grafeas.V1.GetOccurrenceRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lists occurrences for the specified project. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grafeas.V1.ListOccurrencesResponse> ListOccurrences(global::Grafeas.V1.ListOccurrencesRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Deletes the specified occurrence. For example, use this method to delete an /// occurrence when the occurrence is no longer applicable for the given /// resource. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteOccurrence(global::Grafeas.V1.DeleteOccurrenceRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Creates a new occurrence. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grafeas.V1.Occurrence> CreateOccurrence(global::Grafeas.V1.CreateOccurrenceRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Creates new occurrences in batch. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grafeas.V1.BatchCreateOccurrencesResponse> BatchCreateOccurrences(global::Grafeas.V1.BatchCreateOccurrencesRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Updates the specified occurrence. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grafeas.V1.Occurrence> UpdateOccurrence(global::Grafeas.V1.UpdateOccurrenceRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Gets the note attached to the specified occurrence. Consumer projects can /// use this method to get a note that belongs to a provider project. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grafeas.V1.Note> GetOccurrenceNote(global::Grafeas.V1.GetOccurrenceNoteRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Gets the specified note. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grafeas.V1.Note> GetNote(global::Grafeas.V1.GetNoteRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lists notes for the specified project. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grafeas.V1.ListNotesResponse> ListNotes(global::Grafeas.V1.ListNotesRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Deletes the specified note. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteNote(global::Grafeas.V1.DeleteNoteRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Creates a new note. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grafeas.V1.Note> CreateNote(global::Grafeas.V1.CreateNoteRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Creates new notes in batch. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grafeas.V1.BatchCreateNotesResponse> BatchCreateNotes(global::Grafeas.V1.BatchCreateNotesRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Updates the specified note. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grafeas.V1.Note> UpdateNote(global::Grafeas.V1.UpdateNoteRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lists occurrences referencing the specified note. Provider projects can use /// this method to get all occurrences across consumer projects referencing the /// specified note. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Grafeas.V1.ListNoteOccurrencesResponse> ListNoteOccurrences(global::Grafeas.V1.ListNoteOccurrencesRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for Grafeas</summary> public partial class GrafeasClient : grpc::ClientBase<GrafeasClient> { /// <summary>Creates a new client for Grafeas</summary> /// <param name="channel">The channel to use to make remote calls.</param> public GrafeasClient(grpc::ChannelBase channel) : base(channel) { } /// <summary>Creates a new client for Grafeas that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public GrafeasClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected GrafeasClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected GrafeasClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Gets the specified occurrence. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.Occurrence GetOccurrence(global::Grafeas.V1.GetOccurrenceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetOccurrence(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the specified occurrence. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.Occurrence GetOccurrence(global::Grafeas.V1.GetOccurrenceRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetOccurrence, null, options, request); } /// <summary> /// Gets the specified occurrence. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.Occurrence> GetOccurrenceAsync(global::Grafeas.V1.GetOccurrenceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetOccurrenceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the specified occurrence. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.Occurrence> GetOccurrenceAsync(global::Grafeas.V1.GetOccurrenceRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetOccurrence, null, options, request); } /// <summary> /// Lists occurrences for the specified project. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.ListOccurrencesResponse ListOccurrences(global::Grafeas.V1.ListOccurrencesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListOccurrences(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists occurrences for the specified project. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.ListOccurrencesResponse ListOccurrences(global::Grafeas.V1.ListOccurrencesRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListOccurrences, null, options, request); } /// <summary> /// Lists occurrences for the specified project. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.ListOccurrencesResponse> ListOccurrencesAsync(global::Grafeas.V1.ListOccurrencesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListOccurrencesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists occurrences for the specified project. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.ListOccurrencesResponse> ListOccurrencesAsync(global::Grafeas.V1.ListOccurrencesRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListOccurrences, null, options, request); } /// <summary> /// Deletes the specified occurrence. For example, use this method to delete an /// occurrence when the occurrence is no longer applicable for the given /// resource. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteOccurrence(global::Grafeas.V1.DeleteOccurrenceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteOccurrence(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes the specified occurrence. For example, use this method to delete an /// occurrence when the occurrence is no longer applicable for the given /// resource. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteOccurrence(global::Grafeas.V1.DeleteOccurrenceRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteOccurrence, null, options, request); } /// <summary> /// Deletes the specified occurrence. For example, use this method to delete an /// occurrence when the occurrence is no longer applicable for the given /// resource. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteOccurrenceAsync(global::Grafeas.V1.DeleteOccurrenceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteOccurrenceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes the specified occurrence. For example, use this method to delete an /// occurrence when the occurrence is no longer applicable for the given /// resource. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteOccurrenceAsync(global::Grafeas.V1.DeleteOccurrenceRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteOccurrence, null, options, request); } /// <summary> /// Creates a new occurrence. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.Occurrence CreateOccurrence(global::Grafeas.V1.CreateOccurrenceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateOccurrence(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a new occurrence. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.Occurrence CreateOccurrence(global::Grafeas.V1.CreateOccurrenceRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateOccurrence, null, options, request); } /// <summary> /// Creates a new occurrence. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.Occurrence> CreateOccurrenceAsync(global::Grafeas.V1.CreateOccurrenceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateOccurrenceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a new occurrence. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.Occurrence> CreateOccurrenceAsync(global::Grafeas.V1.CreateOccurrenceRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateOccurrence, null, options, request); } /// <summary> /// Creates new occurrences in batch. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.BatchCreateOccurrencesResponse BatchCreateOccurrences(global::Grafeas.V1.BatchCreateOccurrencesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return BatchCreateOccurrences(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates new occurrences in batch. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.BatchCreateOccurrencesResponse BatchCreateOccurrences(global::Grafeas.V1.BatchCreateOccurrencesRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_BatchCreateOccurrences, null, options, request); } /// <summary> /// Creates new occurrences in batch. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.BatchCreateOccurrencesResponse> BatchCreateOccurrencesAsync(global::Grafeas.V1.BatchCreateOccurrencesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return BatchCreateOccurrencesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates new occurrences in batch. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.BatchCreateOccurrencesResponse> BatchCreateOccurrencesAsync(global::Grafeas.V1.BatchCreateOccurrencesRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_BatchCreateOccurrences, null, options, request); } /// <summary> /// Updates the specified occurrence. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.Occurrence UpdateOccurrence(global::Grafeas.V1.UpdateOccurrenceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateOccurrence(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates the specified occurrence. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.Occurrence UpdateOccurrence(global::Grafeas.V1.UpdateOccurrenceRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateOccurrence, null, options, request); } /// <summary> /// Updates the specified occurrence. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.Occurrence> UpdateOccurrenceAsync(global::Grafeas.V1.UpdateOccurrenceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateOccurrenceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates the specified occurrence. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.Occurrence> UpdateOccurrenceAsync(global::Grafeas.V1.UpdateOccurrenceRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateOccurrence, null, options, request); } /// <summary> /// Gets the note attached to the specified occurrence. Consumer projects can /// use this method to get a note that belongs to a provider project. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.Note GetOccurrenceNote(global::Grafeas.V1.GetOccurrenceNoteRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetOccurrenceNote(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the note attached to the specified occurrence. Consumer projects can /// use this method to get a note that belongs to a provider project. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.Note GetOccurrenceNote(global::Grafeas.V1.GetOccurrenceNoteRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetOccurrenceNote, null, options, request); } /// <summary> /// Gets the note attached to the specified occurrence. Consumer projects can /// use this method to get a note that belongs to a provider project. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.Note> GetOccurrenceNoteAsync(global::Grafeas.V1.GetOccurrenceNoteRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetOccurrenceNoteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the note attached to the specified occurrence. Consumer projects can /// use this method to get a note that belongs to a provider project. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.Note> GetOccurrenceNoteAsync(global::Grafeas.V1.GetOccurrenceNoteRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetOccurrenceNote, null, options, request); } /// <summary> /// Gets the specified note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.Note GetNote(global::Grafeas.V1.GetNoteRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetNote(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the specified note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.Note GetNote(global::Grafeas.V1.GetNoteRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetNote, null, options, request); } /// <summary> /// Gets the specified note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.Note> GetNoteAsync(global::Grafeas.V1.GetNoteRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetNoteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the specified note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.Note> GetNoteAsync(global::Grafeas.V1.GetNoteRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetNote, null, options, request); } /// <summary> /// Lists notes for the specified project. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.ListNotesResponse ListNotes(global::Grafeas.V1.ListNotesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListNotes(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists notes for the specified project. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.ListNotesResponse ListNotes(global::Grafeas.V1.ListNotesRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListNotes, null, options, request); } /// <summary> /// Lists notes for the specified project. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.ListNotesResponse> ListNotesAsync(global::Grafeas.V1.ListNotesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListNotesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists notes for the specified project. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.ListNotesResponse> ListNotesAsync(global::Grafeas.V1.ListNotesRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListNotes, null, options, request); } /// <summary> /// Deletes the specified note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteNote(global::Grafeas.V1.DeleteNoteRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteNote(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes the specified note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteNote(global::Grafeas.V1.DeleteNoteRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteNote, null, options, request); } /// <summary> /// Deletes the specified note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteNoteAsync(global::Grafeas.V1.DeleteNoteRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteNoteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes the specified note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteNoteAsync(global::Grafeas.V1.DeleteNoteRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteNote, null, options, request); } /// <summary> /// Creates a new note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.Note CreateNote(global::Grafeas.V1.CreateNoteRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateNote(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a new note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.Note CreateNote(global::Grafeas.V1.CreateNoteRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateNote, null, options, request); } /// <summary> /// Creates a new note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.Note> CreateNoteAsync(global::Grafeas.V1.CreateNoteRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateNoteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a new note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.Note> CreateNoteAsync(global::Grafeas.V1.CreateNoteRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateNote, null, options, request); } /// <summary> /// Creates new notes in batch. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.BatchCreateNotesResponse BatchCreateNotes(global::Grafeas.V1.BatchCreateNotesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return BatchCreateNotes(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates new notes in batch. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.BatchCreateNotesResponse BatchCreateNotes(global::Grafeas.V1.BatchCreateNotesRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_BatchCreateNotes, null, options, request); } /// <summary> /// Creates new notes in batch. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.BatchCreateNotesResponse> BatchCreateNotesAsync(global::Grafeas.V1.BatchCreateNotesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return BatchCreateNotesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates new notes in batch. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.BatchCreateNotesResponse> BatchCreateNotesAsync(global::Grafeas.V1.BatchCreateNotesRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_BatchCreateNotes, null, options, request); } /// <summary> /// Updates the specified note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.Note UpdateNote(global::Grafeas.V1.UpdateNoteRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateNote(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates the specified note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.Note UpdateNote(global::Grafeas.V1.UpdateNoteRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateNote, null, options, request); } /// <summary> /// Updates the specified note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.Note> UpdateNoteAsync(global::Grafeas.V1.UpdateNoteRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateNoteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates the specified note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.Note> UpdateNoteAsync(global::Grafeas.V1.UpdateNoteRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateNote, null, options, request); } /// <summary> /// Lists occurrences referencing the specified note. Provider projects can use /// this method to get all occurrences across consumer projects referencing the /// specified note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.ListNoteOccurrencesResponse ListNoteOccurrences(global::Grafeas.V1.ListNoteOccurrencesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListNoteOccurrences(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists occurrences referencing the specified note. Provider projects can use /// this method to get all occurrences across consumer projects referencing the /// specified note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Grafeas.V1.ListNoteOccurrencesResponse ListNoteOccurrences(global::Grafeas.V1.ListNoteOccurrencesRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListNoteOccurrences, null, options, request); } /// <summary> /// Lists occurrences referencing the specified note. Provider projects can use /// this method to get all occurrences across consumer projects referencing the /// specified note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.ListNoteOccurrencesResponse> ListNoteOccurrencesAsync(global::Grafeas.V1.ListNoteOccurrencesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListNoteOccurrencesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists occurrences referencing the specified note. Provider projects can use /// this method to get all occurrences across consumer projects referencing the /// specified note. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Grafeas.V1.ListNoteOccurrencesResponse> ListNoteOccurrencesAsync(global::Grafeas.V1.ListNoteOccurrencesRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListNoteOccurrences, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override GrafeasClient NewInstance(ClientBaseConfiguration configuration) { return new GrafeasClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(GrafeasBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_GetOccurrence, serviceImpl.GetOccurrence) .AddMethod(__Method_ListOccurrences, serviceImpl.ListOccurrences) .AddMethod(__Method_DeleteOccurrence, serviceImpl.DeleteOccurrence) .AddMethod(__Method_CreateOccurrence, serviceImpl.CreateOccurrence) .AddMethod(__Method_BatchCreateOccurrences, serviceImpl.BatchCreateOccurrences) .AddMethod(__Method_UpdateOccurrence, serviceImpl.UpdateOccurrence) .AddMethod(__Method_GetOccurrenceNote, serviceImpl.GetOccurrenceNote) .AddMethod(__Method_GetNote, serviceImpl.GetNote) .AddMethod(__Method_ListNotes, serviceImpl.ListNotes) .AddMethod(__Method_DeleteNote, serviceImpl.DeleteNote) .AddMethod(__Method_CreateNote, serviceImpl.CreateNote) .AddMethod(__Method_BatchCreateNotes, serviceImpl.BatchCreateNotes) .AddMethod(__Method_UpdateNote, serviceImpl.UpdateNote) .AddMethod(__Method_ListNoteOccurrences, serviceImpl.ListNoteOccurrences).Build(); } /// <summary>Register service method with a service binder with or without implementation. Useful when customizing the service binding logic. /// Note: this method is part of an experimental API that can change or be removed without any prior notice.</summary> /// <param name="serviceBinder">Service methods will be bound by calling <c>AddMethod</c> on this object.</param> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static void BindService(grpc::ServiceBinderBase serviceBinder, GrafeasBase serviceImpl) { serviceBinder.AddMethod(__Method_GetOccurrence, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Grafeas.V1.GetOccurrenceRequest, global::Grafeas.V1.Occurrence>(serviceImpl.GetOccurrence)); serviceBinder.AddMethod(__Method_ListOccurrences, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Grafeas.V1.ListOccurrencesRequest, global::Grafeas.V1.ListOccurrencesResponse>(serviceImpl.ListOccurrences)); serviceBinder.AddMethod(__Method_DeleteOccurrence, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Grafeas.V1.DeleteOccurrenceRequest, global::Google.Protobuf.WellKnownTypes.Empty>(serviceImpl.DeleteOccurrence)); serviceBinder.AddMethod(__Method_CreateOccurrence, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Grafeas.V1.CreateOccurrenceRequest, global::Grafeas.V1.Occurrence>(serviceImpl.CreateOccurrence)); serviceBinder.AddMethod(__Method_BatchCreateOccurrences, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Grafeas.V1.BatchCreateOccurrencesRequest, global::Grafeas.V1.BatchCreateOccurrencesResponse>(serviceImpl.BatchCreateOccurrences)); serviceBinder.AddMethod(__Method_UpdateOccurrence, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Grafeas.V1.UpdateOccurrenceRequest, global::Grafeas.V1.Occurrence>(serviceImpl.UpdateOccurrence)); serviceBinder.AddMethod(__Method_GetOccurrenceNote, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Grafeas.V1.GetOccurrenceNoteRequest, global::Grafeas.V1.Note>(serviceImpl.GetOccurrenceNote)); serviceBinder.AddMethod(__Method_GetNote, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Grafeas.V1.GetNoteRequest, global::Grafeas.V1.Note>(serviceImpl.GetNote)); serviceBinder.AddMethod(__Method_ListNotes, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Grafeas.V1.ListNotesRequest, global::Grafeas.V1.ListNotesResponse>(serviceImpl.ListNotes)); serviceBinder.AddMethod(__Method_DeleteNote, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Grafeas.V1.DeleteNoteRequest, global::Google.Protobuf.WellKnownTypes.Empty>(serviceImpl.DeleteNote)); serviceBinder.AddMethod(__Method_CreateNote, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Grafeas.V1.CreateNoteRequest, global::Grafeas.V1.Note>(serviceImpl.CreateNote)); serviceBinder.AddMethod(__Method_BatchCreateNotes, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Grafeas.V1.BatchCreateNotesRequest, global::Grafeas.V1.BatchCreateNotesResponse>(serviceImpl.BatchCreateNotes)); serviceBinder.AddMethod(__Method_UpdateNote, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Grafeas.V1.UpdateNoteRequest, global::Grafeas.V1.Note>(serviceImpl.UpdateNote)); serviceBinder.AddMethod(__Method_ListNoteOccurrences, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Grafeas.V1.ListNoteOccurrencesRequest, global::Grafeas.V1.ListNoteOccurrencesResponse>(serviceImpl.ListNoteOccurrences)); } } } #endregion
70.418519
367
0.7224
[ "Apache-2.0" ]
garrettwong/google-cloud-dotnet
apis/Grafeas.V1/Grafeas.V1/GrafeasGrpc.g.cs
76,052
C#
using EM.GIS.Data; using EM.GIS.Geometries; using System; using System.Drawing; using System.Threading; namespace EM.GIS.Symbology { /// <summary> /// 图层接口 /// </summary> public interface ILayer : ILegendItem,IDynamicVisibility, IDrawable { /// <summary> /// 数据集 /// </summary> IDataSet DataSet { get; set; } /// <summary> /// 范围 /// </summary> IExtent Extent { get; set; } /// <summary> /// 父图层组 /// </summary> new IGroup Parent { get; set; } /// <summary> /// 地图框架 /// </summary> IFrame Frame { get; set; } /// <summary> /// 在指定范围是否可见 /// </summary> /// <param name="extent"></param> /// <param name="rectangle"></param> /// <returns></returns> bool GetVisible(IExtent extent,Rectangle rectangle); } }
23.435897
71
0.497812
[ "MIT" ]
chiraylu/EMap
EM.GIS.Symbology/Layers/ILayer.cs
968
C#
using System; using System.IO; using System.Linq; using Bit.Core.Contracts; using Bit.Core.Models; namespace Bit.Core.Implementations { public class DefaultAppEnvironmentProvider : IAppEnvironmentProvider { private AppEnvironment _activeEnvironment; private static IAppEnvironmentProvider _current; public virtual IPathProvider PathProvider { get; set; } public virtual IContentFormatter ContentFormatter { get; set; } public static IAppEnvironmentProvider Current { get { if (_current == null) { _current = new DefaultAppEnvironmentProvider { ContentFormatter = DefaultJsonContentFormatter.Current, PathProvider = DefaultPathProvider.Current }; } return _current; } set => _current = value; } public virtual AppEnvironment GetActiveAppEnvironment() { if (_activeEnvironment != null) return _activeEnvironment; string environmentsAsJson = File.ReadAllText(PathProvider.MapPath("environments.json")); AppEnvironment[] allEnvironments = ContentFormatter.DeSerialize<AppEnvironment[]>(environmentsAsJson); AppEnvironment[] activeEnvironments = allEnvironments.Where(env => env.IsActive).ToArray(); if (!activeEnvironments.Any()) throw new InvalidOperationException("There is no active environment"); if (activeEnvironments.Length > 1) throw new InvalidOperationException("There are more than one active environment"); _activeEnvironment = activeEnvironments.Single(); return _activeEnvironment; } public override string ToString() { return _activeEnvironment?.ToString() ?? base.ToString(); } } }
32.754098
114
0.609109
[ "MIT" ]
lightdawncoders/bit-framework
src/Server/Bit.Core/Implementations/DefaultAppEnvironmentProvider.cs
2,000
C#
using System.Security.Claims; using AuctionMarket.Server.Application.Abstractions; using AuctionMarket.Server.Domain.Entities; using Microsoft.AspNetCore.Http; namespace AuctionMarket.Server.Infrastructure.Services; public class CurrentAccountService : ICurrentAccountService { private readonly IHttpContextAccessor _httpContextAccessor; public CurrentAccountService(IHttpContextAccessor httpContextAccessor) => _httpContextAccessor = httpContextAccessor; public Guid? GetId() => FindFirstGuid(ClaimTypes.NameIdentifier); public Guid? GetSecurityStamp() => FindFirstGuid(nameof(User.SecurityStamp)); private Guid? FindFirstGuid(string claimType) => Guid.TryParse(FindFirstValue(claimType), out var guid) ? guid : null; private string? FindFirstValue(string claimType) => _httpContextAccessor.HttpContext?.User.FindFirstValue(claimType); }
37.25
81
0.791946
[ "MIT" ]
MustafaNesin/AuctionMarket
src/Server.Infrastructure/Services/CurrentAccountService.cs
896
C#
// ———————————————————————– // <copyright file="ImmunizationSummary.cs" company="EDXLSharp"> // 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. // </copyright> using System; using System.Xml; namespace MEXLSitRep { /// <summary> /// Immunization Summary sub type of Casualty and Illness Summary By Period /// </summary> [Serializable] public partial class ImmunizationSummary { #region Public Delegates/Events #endregion #region Private Member Variables /// <summary> /// The number of non-responders/responders who have received mass immunizations relevant /// specifically to incident conditions and/or as part of incident operations. /// </summary> private int? haveReceivedMassImmunizations; /// <summary> /// Proposed % of people who have received mass immunization /// </summary> private double? percentReceived; /// <summary> /// The number of non-responders/responders who require mass /// immunizations relevant to incident conditions and/or as part of incident /// operations. /// </summary> private int? requireMassImmunizations; /// <summary> /// Proposed % of people who require mass immunization /// </summary> private double? percentRequire; #endregion #region Constructors /// <summary> /// Initializes a new instance of the ImmunizationSummary class /// Default Constructor - Does Nothing /// </summary> public ImmunizationSummary() { } #endregion #region Public Accessors /// <summary> /// Gets or sets /// </summary> public int? HaveReceivedMassImmunizations { get { return this.haveReceivedMassImmunizations; } set { this.haveReceivedMassImmunizations = value; } } /// <summary> /// Gets or sets /// </summary> public double? PercentReceived { get { return this.percentReceived; } set { this.percentReceived = value; } } /// <summary> /// Gets or sets /// </summary> public int? RequireMasImmunizations { get { return this.requireMassImmunizations; } set { this.requireMassImmunizations = value; } } /// <summary> /// Gets or sets /// </summary> public double? PercentRequire { get { return this.percentRequire; } set { this.percentRequire = value; } } #endregion #region Public Member Functions /// <summary> /// Writes this Object to an inline XML Document /// </summary> /// <param name="xwriter">Valid XMLWriter</param> internal void WriteXML(XmlWriter xwriter) { xwriter.WriteStartElement("ImmunizationSummary"); if (this.haveReceivedMassImmunizations != null) { xwriter.WriteElementString("HaveReceivedMassImmunizations", this.haveReceivedMassImmunizations.ToString()); } if (this.percentReceived != null) { xwriter.WriteElementString("PercentRecieved", this.percentReceived.ToString()); } if (this.requireMassImmunizations != null) { xwriter.WriteElementString("RequireMassImmunizations", this.requireMassImmunizations.ToString()); } if (this.percentRequire != null) { xwriter.WriteElementString("PercentRequire", this.percentRequire.ToString()); } xwriter.WriteEndElement(); } /// <summary> /// Reads this Object's values from an XML node list /// </summary> /// <param name="rootnode">root XML Node of the Object element</param> internal void ReadXML(XmlNode rootnode) { foreach (XmlNode childnode in rootnode.ChildNodes) { if (string.IsNullOrEmpty(childnode.InnerText)) { continue; } switch (childnode.LocalName) { case "HaveReceivedMassImmunizations": this.haveReceivedMassImmunizations = Convert.ToInt32(childnode.InnerText); break; case "PercentRecieved": this.PercentReceived = Convert.ToDouble(childnode.InnerText); break; case "RequireMassImmunizations": this.requireMassImmunizations = Convert.ToInt32(childnode.InnerText); break; case "PercentRequire": this.percentRequire = Convert.ToDouble(childnode.InnerText); break; case "#comment": break; default: throw new ArgumentException("Unexpected Child Node Name: " + childnode.Name + " in CasualtyAndIllnessSummary"); } } } #endregion #region Protected Member Functions /// <summary> /// Validates This Message element For Required Values and Conformance /// </summary> protected void Validate() { } #endregion #region Private Member Functions #endregion } }
28.263158
123
0.640782
[ "Apache-2.0" ]
1stResponder/em-serializers
EDXLSHARP/MEXLSitRepLib/ImmunizationSummary.cs
5,420
C#
namespace SRMLExtras.Templates { /// <summary> /// A template to create new activator UIs /// </summary> public class ActivatorUITemplate : ModPrefab<ActivatorUITemplate> { // The UI component protected Create<BaseUI> baseUI; /// <summary> /// Template to create new activator UIs /// </summary> /// <param name="name">The name of the object (prefixes are recommended, but not needed)</param> /// <param name="baseUI">The UI component to add</param> public ActivatorUITemplate(string name, Create<BaseUI> baseUI) : base(name) { this.baseUI = baseUI; } /// <summary> /// Creates the object of the template (To get the prefab version use .ToPrefab() after calling this) /// </summary> public override ActivatorUITemplate Create() { // Create main object mainObject.AddComponents( baseUI, new Create<UIInputLocker>((locker) => locker.lockEvenSpecialScenes = false) ); return this; } } }
26.361111
103
0.683878
[ "MIT" ]
RicardoTheCoder/SRMLExtras
NewThings/Templates/UIs/ActivatorUITemplate.cs
951
C#
#if USE_HOT using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using System.Linq; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class System_Reflection_FieldInfo_Binding { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(System.Reflection.FieldInfo); args = new Type[]{}; method = type.GetMethod("get_Attributes", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_Attributes_0); args = new Type[]{}; method = type.GetMethod("get_FieldHandle", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_FieldHandle_1); args = new Type[]{}; method = type.GetMethod("get_FieldType", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_FieldType_2); args = new Type[]{typeof(System.Object)}; method = type.GetMethod("GetValue", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetValue_3); args = new Type[]{}; method = type.GetMethod("get_MemberType", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_MemberType_4); args = new Type[]{}; method = type.GetMethod("get_IsLiteral", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_IsLiteral_5); args = new Type[]{}; method = type.GetMethod("get_IsStatic", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_IsStatic_6); args = new Type[]{}; method = type.GetMethod("get_IsInitOnly", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_IsInitOnly_7); args = new Type[]{}; method = type.GetMethod("get_IsPublic", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_IsPublic_8); args = new Type[]{}; method = type.GetMethod("get_IsPrivate", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_IsPrivate_9); args = new Type[]{}; method = type.GetMethod("get_IsFamily", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_IsFamily_10); args = new Type[]{}; method = type.GetMethod("get_IsAssembly", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_IsAssembly_11); args = new Type[]{}; method = type.GetMethod("get_IsFamilyAndAssembly", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_IsFamilyAndAssembly_12); args = new Type[]{}; method = type.GetMethod("get_IsFamilyOrAssembly", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_IsFamilyOrAssembly_13); args = new Type[]{}; method = type.GetMethod("get_IsPinvokeImpl", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_IsPinvokeImpl_14); args = new Type[]{}; method = type.GetMethod("get_IsSpecialName", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_IsSpecialName_15); args = new Type[]{}; method = type.GetMethod("get_IsNotSerialized", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_IsNotSerialized_16); args = new Type[]{typeof(System.Object), typeof(System.Object), typeof(System.Reflection.BindingFlags), typeof(System.Reflection.Binder), typeof(System.Globalization.CultureInfo)}; method = type.GetMethod("SetValue", flag, null, args, null); app.RegisterCLRMethodRedirection(method, SetValue_17); args = new Type[]{typeof(System.Object), typeof(System.Object)}; method = type.GetMethod("SetValue", flag, null, args, null); app.RegisterCLRMethodRedirection(method, SetValue_18); args = new Type[]{typeof(System.RuntimeFieldHandle)}; method = type.GetMethod("GetFieldFromHandle", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetFieldFromHandle_19); args = new Type[]{typeof(System.RuntimeFieldHandle), typeof(System.RuntimeTypeHandle)}; method = type.GetMethod("GetFieldFromHandle", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetFieldFromHandle_20); args = new Type[]{}; method = type.GetMethod("GetOptionalCustomModifiers", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetOptionalCustomModifiers_21); args = new Type[]{}; method = type.GetMethod("GetRequiredCustomModifiers", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetRequiredCustomModifiers_22); args = new Type[]{}; method = type.GetMethod("GetRawConstantValue", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetRawConstantValue_23); args = new Type[]{typeof(System.Object)}; method = type.GetMethod("Equals", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Equals_24); args = new Type[]{}; method = type.GetMethod("GetHashCode", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetHashCode_25); args = new Type[]{typeof(System.Reflection.FieldInfo), typeof(System.Reflection.FieldInfo)}; method = type.GetMethod("op_Equality", flag, null, args, null); app.RegisterCLRMethodRedirection(method, op_Equality_26); args = new Type[]{typeof(System.Reflection.FieldInfo), typeof(System.Reflection.FieldInfo)}; method = type.GetMethod("op_Inequality", flag, null, args, null); app.RegisterCLRMethodRedirection(method, op_Inequality_27); args = new Type[]{}; method = type.GetMethod("get_IsSecurityCritical", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_IsSecurityCritical_28); args = new Type[]{}; method = type.GetMethod("get_IsSecuritySafeCritical", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_IsSecuritySafeCritical_29); args = new Type[]{}; method = type.GetMethod("get_IsSecurityTransparent", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_IsSecurityTransparent_30); app.RegisterCLRCreateArrayInstance(type, s => new System.Reflection.FieldInfo[s]); } static StackObject* get_Attributes_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.Attributes; return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* get_FieldHandle_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.FieldHandle; return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* get_FieldType_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.FieldType; object obj_result_of_this_method = result_of_this_method; if(obj_result_of_this_method is CrossBindingAdaptorType) { return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance); } return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* GetValue_3(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Object @obj = (System.Object)typeof(System.Object).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetValue(@obj); object obj_result_of_this_method = result_of_this_method; if(obj_result_of_this_method is CrossBindingAdaptorType) { return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance, true); } return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method, true); } static StackObject* get_MemberType_4(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.MemberType; return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* get_IsLiteral_5(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.IsLiteral; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* get_IsStatic_6(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.IsStatic; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* get_IsInitOnly_7(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.IsInitOnly; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* get_IsPublic_8(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.IsPublic; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* get_IsPrivate_9(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.IsPrivate; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* get_IsFamily_10(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.IsFamily; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* get_IsAssembly_11(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.IsAssembly; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* get_IsFamilyAndAssembly_12(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.IsFamilyAndAssembly; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* get_IsFamilyOrAssembly_13(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.IsFamilyOrAssembly; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* get_IsPinvokeImpl_14(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.IsPinvokeImpl; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* get_IsSpecialName_15(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.IsSpecialName; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* get_IsNotSerialized_16(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.IsNotSerialized; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* SetValue_17(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 6); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Globalization.CultureInfo @culture = (System.Globalization.CultureInfo)typeof(System.Globalization.CultureInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Reflection.Binder @binder = (System.Reflection.Binder)typeof(System.Reflection.Binder).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); System.Reflection.BindingFlags @invokeAttr = (System.Reflection.BindingFlags)typeof(System.Reflection.BindingFlags).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 4); System.Object @value = (System.Object)typeof(System.Object).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 5); System.Object @obj = (System.Object)typeof(System.Object).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 6); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); instance_of_this_method.SetValue(@obj, @value, @invokeAttr, @binder, @culture); return __ret; } static StackObject* SetValue_18(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Object @value = (System.Object)typeof(System.Object).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Object @obj = (System.Object)typeof(System.Object).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); instance_of_this_method.SetValue(@obj, @value); return __ret; } static StackObject* GetFieldFromHandle_19(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.RuntimeFieldHandle @handle = (System.RuntimeFieldHandle)typeof(System.RuntimeFieldHandle).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = System.Reflection.FieldInfo.GetFieldFromHandle(@handle); object obj_result_of_this_method = result_of_this_method; if(obj_result_of_this_method is CrossBindingAdaptorType) { return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance); } return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* GetFieldFromHandle_20(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.RuntimeTypeHandle @declaringType = (System.RuntimeTypeHandle)typeof(System.RuntimeTypeHandle).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.RuntimeFieldHandle @handle = (System.RuntimeFieldHandle)typeof(System.RuntimeFieldHandle).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = System.Reflection.FieldInfo.GetFieldFromHandle(@handle, @declaringType); object obj_result_of_this_method = result_of_this_method; if(obj_result_of_this_method is CrossBindingAdaptorType) { return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance); } return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* GetOptionalCustomModifiers_21(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetOptionalCustomModifiers(); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* GetRequiredCustomModifiers_22(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetRequiredCustomModifiers(); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* GetRawConstantValue_23(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetRawConstantValue(); object obj_result_of_this_method = result_of_this_method; if(obj_result_of_this_method is CrossBindingAdaptorType) { return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance, true); } return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method, true); } static StackObject* Equals_24(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Object @obj = (System.Object)typeof(System.Object).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.Equals(@obj); __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* GetHashCode_25(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetHashCode(); __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method; return __ret + 1; } static StackObject* op_Equality_26(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo @right = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Reflection.FieldInfo @left = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = left == right; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* op_Inequality_27(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo @right = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Reflection.FieldInfo @left = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = left != right; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* get_IsSecurityCritical_28(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.IsSecurityCritical; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* get_IsSecuritySafeCritical_29(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.IsSecuritySafeCritical; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* get_IsSecurityTransparent_30(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.FieldInfo instance_of_this_method = (System.Reflection.FieldInfo)typeof(System.Reflection.FieldInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.IsSecurityTransparent; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } } } #endif
54.686275
207
0.692465
[ "MIT" ]
huangchaoqun/XIL
Assets/XIL/Auto/System_Reflection_FieldInfo_Binding.cs
39,046
C#
using PontoID.Web.Models; using PontoID.Web.Services.Contracts; using PontoID.Web.Services.IntegrationsConfig; using RestSharp; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace PontoID.Web.Services { public class TurmaService : IntegrationApi, ITurmaService { public TurmaService(IntegrationConfig integrationConfig) : base(integrationConfig) { } public async Task<ResponseApi<TurmaViewModel>> Adicionar(TurmaViewModel model) { var restRequest = new RestRequest("Turma", DataFormat.Json); restRequest.AddJsonBody(model); return await this._client.PostAsync<ResponseApi<TurmaViewModel>>(restRequest); } public async Task<ResponseApi<bool>> Delete(Guid id) { var restRequest = new RestRequest("Turma/{id}", DataFormat.Json); restRequest.AddUrlSegment("id", id); return await this._client.DeleteAsync<ResponseApi<bool>>(restRequest); } public async Task<TurmaViewModel> Detalhes(Guid id) { var restRequest = new RestRequest("Turma/{id}", DataFormat.Json); restRequest.AddUrlSegment("id", id); return await this._client.GetAsync<TurmaViewModel>(restRequest); } public async Task<ResponseApi<TurmaViewModel>> Editar(TurmaViewModel model) { var restRequest = new RestRequest("Turma", DataFormat.Json); restRequest.AddJsonBody(model); return await this._client.PutAsync<ResponseApi<TurmaViewModel>>(restRequest); } public async Task<List<TurmaViewModel>> Listar(TurmaRequest request) { var restRequest = new RestRequest("Turma/Listar", DataFormat.Json); restRequest.AddJsonBody(request); return await this._client.PostAsync<List<TurmaViewModel>>(restRequest); } } }
36.641509
90
0.664264
[ "MIT" ]
ronilsonsilva/pontoid
src/Presentation/PontoID.Web/Services/TurmaService.cs
1,944
C#
#region Copyright // Copyright © EPiServer AB. All rights reserved. // // This code is released by EPiServer AB under the Source Code File - Specific License Conditions, published August 20, 2007. // See http://www.episerver.com/Specific_License_Conditions for details. #endregion using System; using System.Collections; using System.Configuration; using System.Data; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; namespace EPiServer.Templates.Advanced.Workroom.Pages { public partial class NotificationEmail : TemplatePage { } }
28.166667
126
0.781065
[ "MIT" ]
Episerver-trainning/episerver6r2_sso
Templates/Advanced/Workroom/Pages/NotificationEmail.aspx.cs
679
C#
namespace Rhino.Licensing { using System; using System.Runtime.Serialization; /// <summary> /// Thrown when a valid license file can not be /// found on the client machine. /// </summary> [Serializable] public class LicenseFileNotFoundException : RhinoLicensingException { /// <summary> /// Creates a new instance of <seealso cref="LicenseFileNotFoundException"/> /// </summary> public LicenseFileNotFoundException() { } /// <summary> /// Creates a new instance of <seealso cref="LicenseFileNotFoundException"/> /// </summary> /// <param name="message">error message</param> public LicenseFileNotFoundException(string message) : base(message) { } /// <summary> /// Creates a new instance of <seealso cref="LicenseFileNotFoundException"/> /// </summary> /// <param name="message">error message</param> /// <param name="inner">inner exception</param> public LicenseFileNotFoundException(string message, Exception inner) : base(message, inner) { } /// <summary> /// Creates a new instance of <seealso cref="LicenseFileNotFoundException"/> /// </summary> /// <param name="info">serialization information</param> /// <param name="context">streaming context</param> protected LicenseFileNotFoundException( SerializationInfo info, StreamingContext context) : base(info, context) { } } }
33.08
85
0.574365
[ "Apache-2.0", "MIT" ]
ianbattersby/NServiceBus
src/NServiceBus.Core/Rhino.Licensing/LicenseFileNotFoundException.cs
1,605
C#
using ObjectMentor.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Console { class Program { static void Main(string[] args) { try { var arg = new Args("l,p#,d*", args); var logging = arg.GetBoolean('l'); int port = arg.GetInt32('p'); var directory = arg.GetString('d'); System.Console.WriteLine($"Logging: {logging}; Port: {port}; Directory: {directory}"); } catch (Exception e) { System.Console.WriteLine(e.Message); } } } }
24.1
102
0.51314
[ "Unlicense" ]
Pvlerick/CommandLineArgumentParser
Console/Program.cs
725
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Ecs.Model.V20140526; namespace Aliyun.Acs.Ecs.Transform.V20140526 { public class ModifyCommandResponseUnmarshaller { public static ModifyCommandResponse Unmarshall(UnmarshallerContext context) { ModifyCommandResponse modifyCommandResponse = new ModifyCommandResponse(); modifyCommandResponse.HttpResponse = context.HttpResponse; modifyCommandResponse.RequestId = context.StringValue("ModifyCommand.RequestId"); return modifyCommandResponse; } } }
35.475
84
0.755462
[ "Apache-2.0" ]
bbs168/aliyun-openapi-net-sdk
aliyun-net-sdk-ecs/Ecs/Transform/V20140526/ModifyCommandResponseUnmarshaller.cs
1,419
C#
namespace UnitTestRunnerApiAdaptor.Runners.NUnit { using System.IO; using System.Xml; using System.Xml.Serialization; using global::NUnit.Engine; using UnitTestRunnerApiAdaptor; using UnitTestRunnerApiAdaptor.Runners.NUnit.Serialization; /// <summary> /// Entry point to the main NUnit test runner. /// </summary> public class NUnitTestRunner : ITestRunner<NUnitTestRunner> { private TestRunnerSettings runnerSettings; /// <summary> Include runner settings for the test run. </summary> /// <param name="runnerSettings"> The runner settings. </param> /// <returns> The current instance of this TestRunner. </returns> public ITestRunner<NUnitTestRunner> WithRunnerSettings(TestRunnerSettings runnerSettings) { this.runnerSettings = runnerSettings; return this; } /// <summary> Runs the tests. </summary> /// <returns> The Results of the test run. </returns> public TestRunnerResults Run() { using ITestEngine nunitEngine = TestEngineActivator.CreateInstance(); nunitEngine.WorkDirectory = this.runnerSettings.TestAssemblyFullPath; var package = new TestPackage(this.runnerSettings.TestAssemblyFullName); package.AddSetting("WorkDirectory", $"{this.runnerSettings.TestAssemblyFullPath} PATH"); var filter = this.GetTestFiter(nunitEngine); using var runner = nunitEngine.GetRunner(package); // Run all the tests in the assembly var testListener = new DefaultTestEventListener(); var testResult = runner.Run(testListener, filter); var deserializedTestResults = Deserialize<TestRun>(testResult); System.Console.WriteLine(deserializedTestResults.TestSuites[0].Total); return new TestRunnerResults(true, TestRunnerType.NUnit); } private static T Deserialize<T>(XmlNode xmlNode) where T : class { using var memoryStream = new MemoryStream(); var serializer = new XmlSerializer(typeof(T)); using var xmlNodeReader = new XmlNodeReader(xmlNode); return serializer.Deserialize(xmlNodeReader) as T; } private TestFilter GetTestFiter(ITestEngine nunitEngine) { var filterService = nunitEngine.Services.GetService<ITestFilterService>(); var builder = filterService.GetTestFilterBuilder(); this.runnerSettings.TestsToRun.ForEach(t => builder.AddTest(t.FullyQualifiedTestName)); var filter = builder.GetFilter(); return filter; } } }
38.309859
100
0.653676
[ "MIT" ]
bradwilson/UnitTestRunnerApiAdaptor
UnitTestRunnerApiAdaptor/Runners/NUnit/NUnitTestRunner.cs
2,722
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestParser.Parser { public abstract class ATestParser : IParser { /// <summary> /// Parser to read function list. /// </summary> public AParser FunctionListParser { get; set; } /// <summary> /// Parser to read function. /// </summary> public AParser FunctionParser { get; set; } /// <summary> /// Parser to read test cases. /// </summary> public AParser TestCaseParser { get; set; } /// <summary> /// Abstract function to read function. /// </summary> /// <param name="path">Paht to file designing test.</param> /// <returns>Object about test.</returns> public abstract object Parse(string path); /// <summary> /// Abstract function to read function. /// </summary> /// <param name="path">Stream to read from data to parse.</param> /// <returns>Object about test.</returns> public abstract object Parse(Stream stream); } }
25.333333
68
0.642857
[ "MIT" ]
CountrySideEngineer/TestSupportTools
AutoTestPrep/dev/src/TestParser/Parser/ATestParser.cs
1,066
C#
using System.Collections; using System.Collections.Generic; using System; using UnityEngine; using UnityEngine.UI; namespace ET { public static class DlgTestSystem { public static void RegisterUIEvent(this DlgTest self) { self.View.EButton_Test.AddListener(() => { self.OnTestClickHandler(); }); } public static void ShowWindow(this DlgTest self, Entity contextData = null) { } public static void OnTestClickHandler(this DlgTest self) { Log.Debug("click Test"); } } }
17.517241
77
0.716535
[ "MIT" ]
RushBitch/ET-EUI
Unity/Codes/HotfixView/Demo/UI/DlgTest/DlgTestSystem.cs
510
C#
using System; using System.Collections.Generic; namespace Lox { public sealed class Token : SyntaxNode { public string Lexeme { get; } public object Literal { get; } public int Line { get; } public override SyntaxKind Kind { get; } public Token(SyntaxKind type, string lexeme, object literal, int line) { Kind = type; this.Lexeme = lexeme; this.Literal = literal; this.Line = line; } public override string ToString() { return Kind + " " + Lexeme + " " + Literal; } public override IEnumerable<SyntaxNode> GetChildren() { return Array.Empty<SyntaxNode>(); } } }
22.909091
78
0.539683
[ "MIT" ]
FaberSanZ/Lox.NET
Src/Lox/Syntax/Token.cs
758
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 dataexchange-2017-07-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.DataExchange.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DataExchange.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for GetDataSet operation /// </summary> public class GetDataSetResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { GetDataSetResponse response = new GetDataSetResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Arn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Arn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("AssetType", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.AssetType = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("CreatedAt", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; response.CreatedAt = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Description", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Description = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Id", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Id = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Name", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Name = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Origin", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Origin = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("OriginDetails", targetDepth)) { var unmarshaller = OriginDetailsUnmarshaller.Instance; response.OriginDetails = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("SourceId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.SourceId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Tags", targetDepth)) { var unmarshaller = new DictionaryUnmarshaller<string, string, StringUnmarshaller, StringUnmarshaller>(StringUnmarshaller.Instance, StringUnmarshaller.Instance); response.Tags = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("UpdatedAt", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; response.UpdatedAt = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerException")) { return InternalServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException")) { return ThrottlingExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException")) { return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonDataExchangeException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static GetDataSetResponseUnmarshaller _instance = new GetDataSetResponseUnmarshaller(); internal static GetDataSetResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetDataSetResponseUnmarshaller Instance { get { return _instance; } } } }
42.824176
196
0.575186
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/DataExchange/Generated/Model/Internal/MarshallTransformations/GetDataSetResponseUnmarshaller.cs
7,794
C#
using Minidump.Templates; using System; using System.Collections.Generic; using System.Runtime.InteropServices; using static Minidump.Helpers; namespace Minidump.Decryptor { public class KerberosSessions { public static List<KerberosLogonItem> FindSessions(Program.MiniDump minidump, kerberos.KerberosTemplate template) { var klogonlist = new List<KerberosLogonItem>(); long position = find_signature(minidump, "kerberos.dll", template.signature); if (position == 0) { Console.WriteLine("[x] Error: Could not find KerberosSessionList signature\n"); return klogonlist; } var ptr_entry_loc = get_ptr_with_offset(minidump.fileBinaryReader, (position + template.first_entry_offset), minidump.sysinfo); var ptr_entry = Minidump.Helpers.ReadUInt64(minidump.fileBinaryReader, (long)ptr_entry_loc); //long kerbUnloadLogonSessionTableAddr = Rva2offset(minidump, (long)ptr_entry); //minidump.fileBinaryReader.BaseStream.Seek(kerbUnloadLogonSessionTableAddr, 0); //Console.WriteLine("Parsing kerberos sessions"); WalkAVLTables(minidump, (long)ptr_entry, klogonlist, template); return klogonlist; } private static void WalkAVLTables(Program.MiniDump minidump, long kerbUnloadLogonSessionTableAddr, List<KerberosLogonItem> klogonlist, kerberos.KerberosTemplate template) { if (kerbUnloadLogonSessionTableAddr == 0) return; kerbUnloadLogonSessionTableAddr = Rva2offset(minidump, kerbUnloadLogonSessionTableAddr); minidump.fileBinaryReader.BaseStream.Seek(kerbUnloadLogonSessionTableAddr, 0); var entryBytes = minidump.fileBinaryReader.ReadBytes(Marshal.SizeOf(typeof(kerberos.RTL_AVL_TABLE))); var entry = ReadStruct<kerberos.RTL_AVL_TABLE>(entryBytes); //Minidump.Helpers.PrintProperties(entry); if (entry.OrderedPointer != 0) { var item = new KerberosLogonItem(); long address = Rva2offset(minidump, entry.OrderedPointer); minidump.fileBinaryReader.BaseStream.Seek(address, 0); item.LogonSessionAddress = address; item.LogonSessionBytes = minidump.fileBinaryReader.ReadBytes(template.LogonSessionTypeSize); klogonlist.Add(item); //Minidump.Helpers.PrintProperties(item); } if (entry.BalancedRoot.RightChild != 0) WalkAVLTables(minidump, entry.BalancedRoot.RightChild, klogonlist, template); if (entry.BalancedRoot.LeftChild != 0) WalkAVLTables(minidump, entry.BalancedRoot.LeftChild, klogonlist, template); } public class KerberosLogonItem { public long LogonSessionAddress { get; set; } public byte[] LogonSessionBytes { get; set; } } } }
43.710145
178
0.661472
[ "BSD-3-Clause" ]
Bl4d3666/SharpMapExec
SharpMapExec/Projects/MiniDump/Decryptor/KerberosSessions.cs
3,018
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using BenchmarkDotNet.Attributes; namespace BenchPlayground.Benchmarks.System.Text { public class StringBuilderAppendFormat { [ParamsSource(nameof(Values))] public byte[] Data { get; set; } public IEnumerable<byte[]> Values { get; } = new[] { Enumerable.Range(0, 16).Select(x => (byte)x).ToArray(), Enumerable.Range(0, 128).Select(x => (byte)x).ToArray(), Enumerable.Range(0, 256).Select(x => (byte)x).ToArray(), }; [Benchmark] public string AppendFormat() { var sb = new StringBuilder(); for (int i = 0; i < Data.Length; i++) sb.AppendFormat("{0:X2}", Data[i]); return sb.ToString(); } [Benchmark(Baseline = true)] public string Append() { var sb = new StringBuilder(); for (int i = 0; i < Data.Length; i++) sb.Append(Data[i].ToString("X2")); return sb.ToString(); } [Benchmark] public string AppendInterpolated() { var sb = new StringBuilder(); for (int i = 0; i < Data.Length; i++) sb.Append($"{Data[i]:X2}"); return sb.ToString(); } } }
28.020408
68
0.518572
[ "MIT" ]
Therzok/BenchPlayground
BenchPlayground/Benchmarks/System.Text/StringBuilderAppendFormat.cs
1,375
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if NET452 || NETCOREAPP1_0 using System; namespace Internal.Microsoft.Extensions.DependencyModel { internal class EnvironmentWrapper : IEnvironment { public static IEnvironment Default = new EnvironmentWrapper(); public string GetEnvironmentVariable(string name) { return Environment.GetEnvironmentVariable(name); } } } #endif
25.590909
101
0.721137
[ "Apache-2.0" ]
erikbra/xunit
src/common/Microsoft.Extensions.DependencyModel/EnvironmentWrapper.cs
563
C#
//----------------------------------------------------------------------- // <copyright file="Parsers.cs" company="None"> // Copyright (c) IIHOSHI Yoshinori. // Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information. // </copyright> //----------------------------------------------------------------------- namespace ThScoreFileConverter.Models.Th14 { /// <summary> /// Provides the parsers used for DDC. /// </summary> internal static class Parsers { /// <summary> /// Gets the parser of <see cref="GameMode"/>. /// </summary> public static EnumShortNameParser<GameMode> GameModeParser { get; } = new EnumShortNameParser<GameMode>(); /// <summary> /// Gets the parser of <see cref="Level"/>. /// </summary> public static EnumShortNameParser<Level> LevelParser { get; } = new EnumShortNameParser<Level>(); /// <summary> /// Gets the parser of <see cref="LevelWithTotal"/>. /// </summary> public static EnumShortNameParser<LevelWithTotal> LevelWithTotalParser { get; } = new EnumShortNameParser<LevelWithTotal>(); /// <summary> /// Gets the parser of <see cref="Chara"/>. /// </summary> public static EnumShortNameParser<Chara> CharaParser { get; } = new EnumShortNameParser<Chara>(); /// <summary> /// Gets the parser of <see cref="CharaWithTotal"/>. /// </summary> public static EnumShortNameParser<CharaWithTotal> CharaWithTotalParser { get; } = new EnumShortNameParser<CharaWithTotal>(); /// <summary> /// Gets the parser of <see cref="Stage"/>. /// </summary> public static EnumShortNameParser<Stage> StageParser { get; } = new EnumShortNameParser<Stage>(); /// <summary> /// Gets the parser of <see cref="StageWithTotal"/>. /// </summary> public static EnumShortNameParser<StageWithTotal> StageWithTotalParser { get; } = new EnumShortNameParser<StageWithTotal>(); } }
37.396552
114
0.558783
[ "BSD-2-Clause" ]
armadillo-winX/ThScoreFileConverter
ThScoreFileConverter/Models/Th14/Parsers.cs
2,171
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; using System.Net.Http; using System.Net.Http.Json; using Microsoft.AspNetCore.Components.Forms; using Microsoft.AspNetCore.Components.Routing; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.Web.Virtualization; using Microsoft.AspNetCore.Components.WebAssembly.Http; using Microsoft.JSInterop; using PlannerApp; using PlannerApp.Shared; using MudBlazor; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Authorization; using PlannerApp.Components; using PlannerApp.Components.Authentication; using Blazored.FluentValidation; using PlannerApp.Client.Services.Interfaces; using PlannerApp.Shared.Models; namespace PlannerApp.Components { public partial class PlansTable { [Inject] public IPlanService PlanService{ get; set; } [Parameter] public EventCallback<PlanSummary> OnViewClicked { get; set; } [Parameter] public EventCallback<PlanSummary> OnDeleteClicked { get; set; } [Parameter] public EventCallback<PlanSummary> OnEditClicked { get; set; } private MudTable<PlanSummary> _table; private string _query = default; private async Task<TableData<PlanSummary>> ServerReloadAsync(TableState state) { var result = await PlanService.GetPlansAsync(_query, state.Page, state.PageSize); return new TableData<PlanSummary> { Items = result.Value.Records, TotalItems = result.Value.ItemsCount }; } private void OnSearch(string query) { _query = query; _table.ReloadServerData(); } } }
27.772727
93
0.708674
[ "MIT" ]
DevCisse/PlannerApp
src/PlannerApp/Components/Plans/PlansTable.razor.cs
1,833
C#
using System; using Musical_WebStore_BlazorApp.Server.Data.Models; namespace Admin.Models { public class ChatUser { public int ChatId {get;set;} public virtual Chat Chat {get;set;} public string UserId {get;set;} public virtual User User {get;set;} } }
21.285714
52
0.657718
[ "MIT" ]
Burion/AdminMS
Musical_WebStore_BlazorApp/Server/Models/ChatUser.cs
298
C#
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Blog.API.Installers { public interface IInstaller { void InstallServices(IServiceCollection services, IConfiguration configuration); } }
23.545455
88
0.783784
[ "MIT" ]
AbhijithSugunan/NetBlog
Blog.API/Blog.API/Installers/IInstaller.cs
261
C#
using System.Runtime.Serialization; using FluentAssertions; using Xunit; namespace Code.Library.Tests.Models { public class SerializationTests { private static readonly string _errorMessage = "this failed"; [Fact] public void GetObjectData_sets_correct_statuses_on_success_result() { Result okResult = Result.Ok(); ISerializable serializableObject = okResult; var serializationInfo = new SerializationInfo(typeof(Result), new FormatterConverter()); serializableObject.GetObjectData(serializationInfo, new StreamingContext()); serializationInfo.GetBoolean(nameof(Result.IsSuccess)).Should().BeTrue(); serializationInfo.GetBoolean(nameof(Result.IsFailure)).Should().BeFalse(); } [Fact] public void GetObjectData_sets_correct_statuses_on_failure_result() { Result failResult = Result.Fail(_errorMessage); ISerializable serializableObject = failResult; var serializationInfo = new SerializationInfo(typeof(Result), new FormatterConverter()); serializableObject.GetObjectData(serializationInfo, new StreamingContext()); serializationInfo.GetBoolean(nameof(Result.IsSuccess)).Should().BeFalse(); serializationInfo.GetBoolean(nameof(Result.IsFailure)).Should().BeTrue(); } [Fact] public void GetObjectData_adds_message_in_context_on_failure_result() { Result failResult = Result.Fail(_errorMessage); ISerializable serializableObject = failResult; var serializationInfo = new SerializationInfo(typeof(Result), new FormatterConverter()); serializableObject.GetObjectData(serializationInfo, new StreamingContext()); serializationInfo.GetString(nameof(Result.Error)).Should().Be(_errorMessage); } [Fact] public void GetObjectData_of_generic_result_adds_object_in_context_when_success_result() { SerializationTestObject language = new SerializationTestObject { Number = 232, String = "C#" }; Result<SerializationTestObject> okResult = Result.Ok(language); ISerializable serializableObject = okResult; var serializationInfo = new SerializationInfo(typeof(Result), new FormatterConverter()); serializableObject.GetObjectData(serializationInfo, new StreamingContext()); serializationInfo.GetValue(nameof(Result<SerializationTestObject>.Value), typeof(SerializationTestObject)) .Should().Be(language); } [Fact] public void GetObjectData_adds_error_object_in_serialization_context_when_failure_result() { SerializationTestObject errorObject = new SerializationTestObject { Number = 500, String = "Error message" }; Result<object, SerializationTestObject> failResult = Result.Fail<object, SerializationTestObject>(errorObject); ISerializable serializableObject = failResult; var serializationInfo = new SerializationInfo(typeof(Result), new FormatterConverter()); serializableObject.GetObjectData(serializationInfo, new StreamingContext()); serializationInfo .GetValue(nameof(Result<object, SerializationTestObject>.Error), typeof(SerializationTestObject)) .Should().Be(errorObject); } } public class SerializationTestObject { public string String { get; set; } public int Number { get; set; } } }
42.376471
123
0.687396
[ "Apache-2.0" ]
Abhith/Code.Library
src/Code.Library.Tests/Models/ResultTests/SerializationTests.cs
3,604
C#
using Forum.App.Contracts; namespace Forum.App.ViewModels { public class ReplyViewModel : ContentViewModel, IReplyViewModel { public ReplyViewModel(string author, string text) : base(text) { this.Author = author; } public string Author { get; } } }
21.333333
67
0.6
[ "MIT" ]
GeorgiGarnenkov/CSharp-Fundamentals
C#OOPAdvanced/Workshop/Forum.App/ViewModels/ReplyViewModel.cs
322
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.Vpc.Model.V20160428 { public class DisableVpcClassicLinkResponse : AcsResponse { private string requestId; public string RequestId { get { return requestId; } set { requestId = value; } } } }
26.465116
63
0.718805
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-vpc/Vpc/Model/V20160428/DisableVpcClassicLinkResponse.cs
1,138
C#
using System; using Paynova.Api.Client.EnsureThat; namespace Paynova.Api.Client.Model { public class ProfilePaymentOptions { /// <summary> /// Your identifier for the customer profile. /// </summary> public string ProfileId { get; private set; } /// <summary> /// The profile card use in the payment. If the payment is to be /// performed on a stored profile card, this parameter is required. /// </summary> public ProfileCard ProfileCard { get; set; } /// <summary> /// If you would like the customer to choose whether or not to save /// their card in your customer profile on Paynova's page, then set this option to true. /// </summary> /// <remarks> /// If you provide a profile id in profilePaymentOptions and this value is false, the /// card will be saved and the customer will not be presented with an option on Paynova's /// payment page. /// /// If you provide a profile id in profilePaymentOptions and this value is not present /// (null), the card will be saved. /// /// If you provide a profile id in profilePaymentOptions and this value is true, the /// customer will be presented with the option to choose whether or not they want their /// card saved on Paynova's payment page. If the customer opts to save their card, you /// will receive a profile card identifier after the payment has been completed /// (assuming the customer pays with a card), otherwise the card will not be saved to /// the customer's profile and you will not receive an identifier. /// </remarks> public bool? DisplaySaveProfileCardOption { get; set; } /// <summary> /// Creates an instance of <see cref="ProfilePaymentOptions"/> with required data. /// </summary> /// <param name="profileId">Your identifier for the customer profile.</param> public ProfilePaymentOptions(string profileId) { Ensure.That(profileId, "profileId").IsNotNullOrEmpty(); ProfileId = profileId; } /// <summary> /// Creates an instance of <see cref="ProfilePaymentOptions"/> with required data. /// </summary> /// <param name="profileId">Your identifier for the customer profile.</param> /// <param name="cardId">Paynova's unique id for the card stored in the customer profile.</param> public ProfilePaymentOptions(string profileId, Guid cardId) : this(profileId) { ProfileCard = new ProfileCard(cardId); } /// <summary> /// Creates an instance of <see cref="ProfilePaymentOptions"/> with required data. /// </summary> /// <param name="profileId">Your identifier for the customer profile.</param> /// <param name="cardId">Paynova's unique id for the card stored in the customer profile.</param> /// <param name="cvc"> /// Depending on the payment channel and your acquiring agreement, the card CVC /// (three or four digit security code) may be required. Paynova will inform you if /// you are required to send this information. /// </param> public ProfilePaymentOptions(string profileId, Guid cardId, string cvc) : this(profileId) { ProfileCard = new ProfileCard(cardId, cvc); } } }
44.807692
105
0.622604
[ "MIT" ]
Paynova/paynova-api-net-client
src/projects/Paynova.Api.Client/Model/ProfilePaymentOptions.cs
3,497
C#
// Only one of the next 5 should be uncommented. #define CODEFIRST_PROVIDER //#define DATABASEFIRST_NEW //#define ORACLE_EDMX //#define NHIBERNATE using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.OData; using System.Web.Http; #if CODEFIRST_PROVIDER using Models.NorthwindIB.CF; using Foo; using System.ComponentModel.DataAnnotations; using System.Web.OData.Query; using System.Net.Http; using System.Net; using System.Threading.Tasks; using System.Data.Entity.Infrastructure; #elif DATABASEFIRST_OLD using Breeze.ContextProvider.EF6; using Models.NorthwindIB.EDMX; #elif DATABASEFIRST_NEW using Breeze.ContextProvider.EF6; using Models.NorthwindIB.EDMX_2012; #elif ORACLE_EDMX using Breeze.ContextProvider.EF6; using Models.NorthwindIB.Oracle; #elif NHIBERNATE using Breeze.ContextProvider.NH; using NHibernate; using NHibernate.Linq; using Models.NorthwindIB.NH; #endif namespace Test.WebApi2.OData4.Controllers { public abstract class BaseController2<TEntity, TKey1, TKey2> : BaseController<TEntity> where TEntity : class { // PATCH odata/TodoItems(5) [AcceptVerbs("PATCH", "MERGE")] public async Task<IHttpActionResult> Patch([FromODataUri] TKey1 key1, [FromODataUri] TKey2 key2, Delta<TEntity> patch) { if (!ModelState.IsValid) { return BadRequest(ModelState); } TEntity item = await Items.FindAsync(key1, key2); if (item == null) { return NotFound(); } patch.Patch(item); try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { //if (!TodoItemExists(key)) { // return NotFound(); //} throw; } return Updated(item); } // DELETE odata/TodoItems(5) public async Task<IHttpActionResult> Delete([FromODataUri] TKey1 key1, [FromODataUri] TKey2 key2) { TEntity item = await Items.FindAsync(key1, key2); if (item == null) { return NotFound(); } Items.Remove(item); await _context.SaveChangesAsync(); return StatusCode(HttpStatusCode.NoContent); } } public abstract class BaseController1<TEntity, TKey> : BaseController<TEntity> where TEntity : class { // PATCH odata/TodoItems(5) [AcceptVerbs("PATCH", "MERGE")] public async Task<IHttpActionResult> Patch([FromODataUri] TKey key, Delta<TEntity> patch) { if (!ModelState.IsValid) { return BadRequest(ModelState); } TEntity item = await Items.FindAsync(key); if (item == null) { return NotFound(); } patch.Patch(item); try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { //if (!TodoItemExists(key)) { // return NotFound(); //} throw; } return Updated(item); } // DELETE odata/TodoItems(5) public async Task<IHttpActionResult> Delete([FromODataUri] TKey key) { TEntity item = await Items.FindAsync(key); if (item == null) { return NotFound(); } Items.Remove(item); await _context.SaveChangesAsync(); return StatusCode(HttpStatusCode.NoContent); } } public abstract class BaseController<TEntity> : ODataController where TEntity : class { internal readonly NorthwindIBContext_CF _context = new NorthwindIBContext_CF(); internal DbSet<TEntity> _items; public DbSet<TEntity> Items { get { if (_items == null) { _items = _context.Set<TEntity>(); } return _items; } } [EnableQuery] public virtual IQueryable<TEntity> Get() { return _context.Set<TEntity>(); } // POST odata/TodoItems public async Task<IHttpActionResult> Post(TEntity item) { if (!ModelState.IsValid) { return BadRequest(ModelState); } Items.Add(item); await _context.SaveChangesAsync(); return Created(item); } //private bool ItemExists(int key) { // return Items.Count(e => e.Id == key) > 0; //} } public class ProductsController : BaseController1<Product, Int32> { } public class CustomersController : BaseController1<Customer, Guid> { } public class OrdersController : BaseController1<Order, Int32> { [EnableQuery(MaxExpansionDepth = 5)] public override IQueryable<Order> Get() { return base.Get(); } } public class EmployeesController : BaseController1<Employee, Int32> { } public class SuppliersController : BaseController1<Supplier, Int32> { } public class OrderDetailsController : BaseController2<OrderDetail, Int32, Int32> { } public class CategoriesController : BaseController1<Category, Int32> { } public class RegionsController : BaseController1<Region, Int32> { } public class TerritoriesController : BaseController1<Territory, Int32> { } public class UsersController : BaseController1<User, Int32> { } // OData WebApi 2.1 does not support enums - 2.2 is supposed to but wasn't released RTM as of 5/29/2014 public class RolesController : BaseController<Role> { } public class CommentsController : BaseController1<Comment, Int32> { } public class TimeLimitsController : BaseController1<TimeLimit, Int32> { } // //[HttpGet] // //public String Metadata() { // // var folder = Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data"); // // var fileName = Path.Combine(folder, "metadata.json"); // // var jsonMetadata = File.ReadAllText(fileName); // // return jsonMetadata; // //} // //[HttpGet] // //public HttpResponseMessage Metadata() { // // var result = new HttpResponseMessage { Content = new StringContent(ContextProvider.Metadata())}; // // result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); // // return result; // //} // #region Save methods //// [HttpPost] //// public SaveResult SaveChanges(JObject saveBundle) { //// return ContextProvider.SaveChanges(saveBundle); //// } //// [HttpPost] //// public SaveResult SaveWithTransactionScope(JObject saveBundle) { //// var txSettings = new TransactionSettings() { TransactionType = TransactionType.TransactionScope }; //// return ContextProvider.SaveChanges(saveBundle, txSettings); //// } //// [HttpPost] //// public SaveResult SaveWithDbTransaction(JObject saveBundle) { //// var txSettings = new TransactionSettings() { TransactionType = TransactionType.DbTransaction }; //// return ContextProvider.SaveChanges(saveBundle, txSettings); //// } //// [HttpPost] //// public SaveResult SaveWithNoTransaction(JObject saveBundle) { //// var txSettings = new TransactionSettings() { TransactionType = TransactionType.None }; //// return ContextProvider.SaveChanges(saveBundle, txSettings); //// } //// [HttpPost] //// public SaveResult SaveWithComment(JObject saveBundle) { //// ContextProvider.BeforeSaveEntitiesDelegate = AddComment; //// return ContextProvider.SaveChanges(saveBundle); //// } //// [HttpPost] //// public SaveResult SaveWithExit(JObject saveBundle) { //// return new SaveResult() { Entities = new List<Object>(), KeyMappings = new List<KeyMapping>() }; //// } //// [HttpPost] //// public SaveResult SaveAndThrow(JObject saveBundle) { //// ContextProvider.BeforeSaveEntitiesDelegate = ThrowError; //// return ContextProvider.SaveChanges(saveBundle); //// } //// [HttpPost] //// public SaveResult SaveWithEntityErrorsException(JObject saveBundle) { //// ContextProvider.BeforeSaveEntitiesDelegate = ThrowEntityErrorsException; //// return ContextProvider.SaveChanges(saveBundle); //// } //// [HttpPost] //// public SaveResult SaveWithFreight(JObject saveBundle) { //// ContextProvider.BeforeSaveEntityDelegate = CheckFreight; //// return ContextProvider.SaveChanges(saveBundle); //// } //// [HttpPost] //// public SaveResult SaveWithFreight2(JObject saveBundle) { //// ContextProvider.BeforeSaveEntitiesDelegate = CheckFreightOnOrders; //// return ContextProvider.SaveChanges(saveBundle); //// } //// [HttpPost] //// public SaveResult SaveCheckInitializer(JObject saveBundle) { //// ContextProvider.BeforeSaveEntitiesDelegate = AddOrder; //// return ContextProvider.SaveChanges(saveBundle); //// } //// [HttpPost] //// public SaveResult SaveCheckUnmappedProperty(JObject saveBundle) { //// ContextProvider.BeforeSaveEntityDelegate = CheckUnmappedProperty; //// return ContextProvider.SaveChanges(saveBundle); //// } //// [HttpPost] //// public SaveResult SaveCheckUnmappedPropertySerialized(JObject saveBundle) { //// ContextProvider.BeforeSaveEntityDelegate = CheckUnmappedPropertySerialized; //// return ContextProvider.SaveChanges(saveBundle); //// } //// [HttpPost] //// public SaveResult SaveCheckUnmappedPropertySuppressed(JObject saveBundle) { //// ContextProvider.BeforeSaveEntityDelegate = CheckUnmappedPropertySuppressed; //// return ContextProvider.SaveChanges(saveBundle); //// } //// private Dictionary<Type, List<EntityInfo>> ThrowError(Dictionary<Type, List<EntityInfo>> saveMap) { //// throw new Exception("Deliberately thrown exception"); //// } //// private Dictionary<Type, List<EntityInfo>> ThrowEntityErrorsException(Dictionary<Type, List<EntityInfo>> saveMap) { //// List<EntityInfo> orderInfos; //// if (saveMap.TryGetValue(typeof(Order), out orderInfos)) { //// var errors = orderInfos.Select(oi => { ////#if NHIBERNATE //// return new EntityError() { //// EntityTypeName = typeof(Order).FullName, //// ErrorMessage = "Cannot save orders with this save method", //// ErrorName = "WrongMethod", //// KeyValues = new object[] { ((Order) oi.Entity).OrderID }, //// PropertyName = "OrderID" //// }; ////#else //// return new EFEntityError(oi, "WrongMethod", "Cannot save orders with this save method", "OrderID"); ////#endif //// }); //// var ex = new EntityErrorsException("test of custom exception message", errors); //// // if you want to see a different error status code use this. //// // ex.StatusCode = HttpStatusCode.Conflict; // Conflict = 409 ; default is Forbidden (403). //// throw ex; //// } //// return saveMap; //// } //// private Dictionary<Type, List<EntityInfo>> AddOrder(Dictionary<Type, List<EntityInfo>> saveMap) { //// var order = new Order(); //// order.OrderDate = DateTime.Today; //// var ei = ContextProvider.CreateEntityInfo(order); //// List<EntityInfo> orderInfos; //// if (!saveMap.TryGetValue(typeof(Order), out orderInfos)) { //// orderInfos = new List<EntityInfo>(); //// saveMap.Add(typeof(Order), orderInfos); //// } //// orderInfos.Add(ei); //// return saveMap; //// } //// private Dictionary<Type, List<EntityInfo>> CheckFreightOnOrders(Dictionary<Type, List<EntityInfo>> saveMap) { //// List<EntityInfo> entityInfos; //// if (saveMap.TryGetValue(typeof(Order), out entityInfos)) { //// foreach (var entityInfo in entityInfos) { //// CheckFreight(entityInfo); //// } //// } //// return saveMap; //// } //// private bool CheckFreight(EntityInfo entityInfo) { //// if ((ContextProvider.SaveOptions.Tag as String) == "freight update") { //// var order = entityInfo.Entity as Order; //// order.Freight = order.Freight + 1; //// } else if ((ContextProvider.SaveOptions.Tag as String) == "freight update-ov") { //// var order = entityInfo.Entity as Order; //// order.Freight = order.Freight + 1; //// entityInfo.OriginalValuesMap["Freight"] = null; //// } else if ((ContextProvider.SaveOptions.Tag as String) == "freight update-force") { //// var order = entityInfo.Entity as Order; //// order.Freight = order.Freight + 1; //// entityInfo.ForceUpdate = true; //// } //// return true; //// } //// private Dictionary<Type, List<EntityInfo>> AddComment(Dictionary<Type, List<EntityInfo>> saveMap) { //// var comment = new Comment(); //// var tag = ContextProvider.SaveOptions.Tag; //// comment.Comment1 = (tag == null) ? "Generic comment" : tag.ToString(); //// comment.CreatedOn = DateTime.Now; //// comment.SeqNum = 1; //// var ei = ContextProvider.CreateEntityInfo(comment); //// List<EntityInfo> commentInfos; //// if (!saveMap.TryGetValue(typeof(Comment), out commentInfos)) { //// commentInfos = new List<EntityInfo>(); //// saveMap.Add(typeof(Comment), commentInfos); //// } //// commentInfos.Add(ei); //// return saveMap; //// } //// private bool CheckUnmappedProperty(EntityInfo entityInfo) { //// var unmappedValue = entityInfo.UnmappedValuesMap["myUnmappedProperty"]; //// if ((String)unmappedValue != "anything22") { //// throw new Exception("wrong value for unmapped property: " + unmappedValue); //// } //// Customer cust = entityInfo.Entity as Customer; //// return false; //// } //// private bool CheckUnmappedPropertySuppressed(EntityInfo entityInfo) { //// if (entityInfo.UnmappedValuesMap != null) { //// throw new Exception("unmapped properties should have been suppressed"); //// } //// return false; //// } //// private bool CheckUnmappedPropertySerialized(EntityInfo entityInfo) { //// var unmappedValue = entityInfo.UnmappedValuesMap["myUnmappedProperty"]; //// if ((String)unmappedValue != "ANYTHING22") { //// throw new Exception("wrong value for unmapped property: " + unmappedValue); //// } //// var anotherOne = entityInfo.UnmappedValuesMap["anotherOne"]; //// if (((dynamic) anotherOne).z[5].foo.Value != 4) { //// throw new Exception("wrong value for 'anotherOne.z[5].foo'"); //// } //// if (((dynamic)anotherOne).extra.Value != 666) { //// throw new Exception("wrong value for 'anotherOne.extra'"); //// } //// Customer cust = entityInfo.Entity as Customer; //// if (cust.CompanyName.ToUpper() != cust.CompanyName) { //// throw new Exception("Uppercasing of company name did not occur"); //// } //// return false; //// } // #endregion // #region standard queries // [HttpGet] // public List<Employee> QueryInvolvingMultipleEntities() { //#if NHIBERNATE // // need to figure out what to do here // //return new List<Employee>(); // var dc0 = new NorthwindNHContext(); // var dc = new NorthwindNHContext(); //#elif CODEFIRST_PROVIDER // var dc0 = new NorthwindIBContext_CF(); // var dc = new EFContextProvider<NorthwindIBContext_CF>(); //#elif DATABASEFIRST_OLD // var dc0 = new NorthwindIBContext_EDMX(); // var dc = new EFContextProvider<NorthwindIBContext_EDMX>(); //#elif DATABASEFIRST_NEW // var dc0 = new NorthwindIBContext_EDMX_2012(); // var dc = new EFContextProvider<NorthwindIBContext_EDMX_2012>(); //#elif ORACLE_EDMX // var dc0 = new NorthwindIBContext_EDMX_Oracle(); // var dc = new EFContextProvider<NorthwindIBContext_EDMX_Oracle>(); //#endif // //the query executes using pure EF // var query0 = (from t1 in dc0.Employees // where (from t2 in dc0.Orders select t2.EmployeeID).Distinct().Contains(t1.EmployeeID) // select t1); // var result0 = query0.ToList(); // //the same query fails if using EFContextProvider // dc0 = dc.Context; // var query = (from t1 in dc0.Employees // where (from t2 in dc0.Orders select t2.EmployeeID).Distinct().Contains(t1.EmployeeID) // select t1); // var result = query.ToList(); // return result; // } // [HttpGet] ////#if NHIBERNATE //// [BreezeNHQueryable(MaxAnyAllExpressionDepth = 3)] ////#else //// [EnableBreezeQuery(MaxAnyAllExpressionDepth = 3)] ////#endif // public IQueryable<Customer> Customers() { // var custs = _context.Customers; // return custs; // } // [HttpGet] // public IQueryable<Customer> CustomersStartingWith(string companyName) { // if (companyName == "null") { // throw new Exception("nulls should not be passed as 'null'"); // } // if (String.IsNullOrEmpty(companyName)) { // companyName = ""; // } // var custs = _context.Customers.Where(c => c.CompanyName.StartsWith(companyName)); // return custs; // } // [HttpGet] // public Object CustomerCountsByCountry() { // return _context.Customers.GroupBy(c => c.Country).Select(g => new { g.Key, Count = g.Count() }); // } // [HttpGet] // public Customer CustomerWithScalarResult() { // return _context.Customers.First(); // } // [HttpGet] // public IQueryable<Customer> CustomersWithHttpError() { // var responseMsg = new HttpResponseMessage(HttpStatusCode.NotFound); // responseMsg.Content = new StringContent("Custom error message"); // responseMsg.ReasonPhrase = "Custom Reason"; // throw new HttpResponseException(responseMsg); // } // [HttpGet] ////#if NHIBERNATE //// [BreezeNHQueryable(MaxExpansionDepth = 3)] ////#else //// [EnableBreezeQuery(MaxExpansionDepth = 3)] ////#endif // public IQueryable<Order> Orders() { // var orders = _context.Orders; // return orders; // } // [HttpGet] // public IQueryable<Employee> Employees() { // return _context.Employees; // } // [HttpGet] // //[EnableBreezeQuery] // public IEnumerable<Employee> EnumerableEmployees() { // return _context.Employees.ToList(); // } // [HttpGet] // public IQueryable<Employee> EmployeesFilteredByCountryAndBirthdate(DateTime birthDate, string country) { // return _context.Employees.Where(emp => emp.BirthDate >= birthDate && emp.Country == country); // } // [HttpGet] // public IQueryable<OrderDetail> OrderDetails() { // return _context.OrderDetails; // } // [HttpGet] // [Queryable] // public IQueryable<Product> Products() { // return _context.Products; // } // [HttpGet] // public IQueryable<Supplier> Suppliers() { // return _context.Suppliers; // } // [HttpGet] // public IQueryable<Region> Regions() { // return _context.Regions; // } // [HttpGet] // public IQueryable<Territory> Territories() { // return _context.Territories; // } // [HttpGet] // public IQueryable<Category> Categories() { // return _context.Categories; // } // [HttpGet] // public IQueryable<Role> Roles() { // return _context.Roles; // } // [HttpGet] // public IQueryable<User> Users() { // return _context.Users; // } // [HttpGet] // public IQueryable<TimeLimit> TimeLimits() { // return _context.TimeLimits; // } // [HttpGet] // public IQueryable<TimeGroup> TimeGroups() { // return _context.TimeGroups; // } // [HttpGet] // public IQueryable<Comment> Comments() { // return _context.Comments; // } // [HttpGet] // public IQueryable<UnusualDate> UnusualDates() { // return _context.UnusualDates; // } //#if ! DATABASEFIRST_OLD // [HttpGet] // public IQueryable<Geospatial> Geospatials() { // return _context.Geospatials; // } //#endif // #endregion // #region named queries // [HttpGet] // public Customer CustomerFirstOrDefault() { // var customer = _context.Customers.Where(c => c.CompanyName.StartsWith("blah")).FirstOrDefault(); // return customer; // } // [HttpGet] // // AltCustomers will not be in the resourceName/entityType map; // public IQueryable<Customer> AltCustomers() { // return _context.Customers; // } // [HttpGet] // public IQueryable<Employee> SearchEmployees([FromUri] int[] employeeIds) { // var query = _context.Employees.AsQueryable(); // if (employeeIds.Length > 0) { // query = query.Where(emp => employeeIds.Contains(emp.EmployeeID)); // var result = query.ToList(); // } // return query; // } // [HttpGet] // public IQueryable<Customer> SearchCustomers([FromUri] CustomerQBE qbe) { // // var query = _context.Customers.Where(c => // // c.CompanyName.StartsWith(qbe.CompanyName)); // var ok = qbe != null && qbe.CompanyName != null & qbe.ContactNames.Length > 0 && qbe.City.Length > 1; // if (!ok) { // throw new Exception("qbe error"); // } // // just testing that qbe actually made it in not attempted to write qbe logic here // // so just return first 3 customers. // return _context.Customers.Take(3); // } // [HttpGet] // public IQueryable<Customer> SearchCustomers2([FromUri] CustomerQBE[] qbeList) { // if (qbeList.Length < 2) { // throw new Exception("all least two items must be passed in"); // } // var ok = qbeList.All(qbe => { // return qbe.CompanyName != null & qbe.ContactNames.Length > 0 && qbe.City.Length > 1; // }); // if (!ok) { // throw new Exception("qbeList error"); // } // // just testing that qbe actually made it in not attempted to write qbe logic here // // so just return first 3 customers. // return _context.Customers.Take(3); // } // public class CustomerQBE { // public String CompanyName { get; set; } // public String[] ContactNames { get; set; } // public String City { get; set; } // } // [HttpGet] // public IQueryable<Customer> CustomersOrderedStartingWith(string companyName) { // var customers = _context.Customers.Where(c => c.CompanyName.StartsWith(companyName)).OrderBy(cust => cust.CompanyName); // var list = customers.ToList(); // return customers; // } // [HttpGet] // public IQueryable<Employee> EmployeesMultipleParams(int employeeID, string city) { // // HACK: // if (city == "null") { // city = null; // } // var emps = _context.Employees.Where(emp => emp.EmployeeID == employeeID || emp.City.Equals(city)); // return emps; // } // [HttpGet] // public IEnumerable<Object> Lookup1Array() { // var regions = _context.Regions; // var lookups = new List<Object>(); // lookups.Add(new {regions = regions}); // return lookups; // } // [HttpGet] // public object Lookups() { // var regions = _context.Regions; // var territories = _context.Territories; // var categories = _context.Categories; // var lookups = new { regions, territories, categories }; // return lookups; // } // [HttpGet] // public IEnumerable<Object> LookupsEnumerableAnon() { // var regions = _context.Regions; // var territories = _context.Territories; // var categories = _context.Categories; // var lookups = new List<Object>(); // lookups.Add(new {regions = regions, territories = territories, categories = categories}); // return lookups; // } // [HttpGet] // public IQueryable<Object> CompanyNames() { // var stuff = _context.Customers.Select(c => c.CompanyName); // return stuff; // } // [HttpGet] // public IQueryable<Object> CompanyNamesAndIds() { // var stuff = _context.Customers.Select(c => new { c.CompanyName, c.CustomerID }); // return stuff; // } // [HttpGet] // public IQueryable<CustomerDTO> CompanyNamesAndIdsAsDTO() { // var stuff = _context.Customers.Select(c => new CustomerDTO() { CompanyName = c.CompanyName, CustomerID = c.CustomerID }); // return stuff; // } // public class CustomerDTO { // public CustomerDTO() { // } // public CustomerDTO(String companyName, Guid customerID) { // CompanyName = companyName; // CustomerID = customerID; // } // public Guid CustomerID { get; set; } // public String CompanyName { get; set; } // public AnotherType AnotherItem { get; set; } // } // public class AnotherType { // } // [HttpGet] // public IQueryable<Object> CustomersWithBigOrders() { // var stuff = _context.Customers.Where(c => c.Orders.Any(o => o.Freight > 100)).Select(c => new { Customer = c, BigOrders = c.Orders.Where(o => o.Freight > 100) }); // return stuff; // } // [HttpGet] //#if NHIBERNATE // public IQueryable<Object> CompanyInfoAndOrders(System.Web.Http.OData.Query.ODataQueryOptions options) { // // Need to handle this specially for NH, to prevent $top being applied to Orders // var query = _context.Customers; // var queryHelper = new NHQueryHelper(); // // apply the $filter, $skip, $top to the query // var query2 = queryHelper.ApplyQuery(query, options); // // execute query, then expand the Orders // var r = query2.Cast<Customer>().ToList(); // NHInitializer.InitializeList(r, "Orders"); // // after all is loaded, create the projection // var stuff = r.AsQueryable().Select(c => new { c.CompanyName, c.CustomerID, c.Orders }); // queryHelper.ConfigureFormatter(Request, query); //#else // public IQueryable<Object> CompanyInfoAndOrders() { // var stuff = _context.Customers.Select(c => new { c.CompanyName, c.CustomerID, c.Orders }); //#endif // return stuff; // } // [HttpGet] // public Object CustomersAndProducts() { // var stuff = new { Customers = _context.Customers.ToList(), Products = _context.Products.ToList() }; // return stuff; // } // [HttpGet] // public IQueryable<Object> TypeEnvelopes() { // var stuff = this.GetType().Assembly.GetTypes() // .Select(t => new { t.Assembly.FullName, t.Name, t.Namespace }) // .AsQueryable(); // return stuff; // } // [HttpGet] // public IQueryable<Customer> CustomersAndOrders() { // var custs = _context.Customers.Include("Orders"); // return custs; // } // [HttpGet] // public IQueryable<Order> OrdersAndCustomers() { // var orders = _context.Orders.Include("Customer"); // return orders; // } // [HttpGet] // public IQueryable<Customer> CustomersStartingWithA() { // var custs = _context.Customers.Where(c => c.CompanyName.StartsWith("A")); // return custs; // } // [HttpGet] ////#if NHIBERNATE //// [BreezeNHQueryable] ////#else //// [EnableBreezeQuery] ////#endif // public HttpResponseMessage CustomersAsHRM() { // var customers = _context.Customers.Cast<Customer>(); // var response = Request.CreateResponse(HttpStatusCode.OK, customers); // return response; // } // #endregion // } }
31.426744
170
0.63111
[ "MIT" ]
ColinBlair/breeze.server.net
Tests/Test.WebApi2.Odata4.EF6/Controllers/NorthwindIBController.cs
27,029
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("Adaptive.ReactiveTrader.Client.WindowsStoreApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Adaptive.ReactiveTrader.Client.WindowsStoreApp")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)]
38.241379
84
0.752029
[ "Apache-2.0" ]
AdaptiveConsulting/ReactiveTrader
src/Adaptive.ReactiveTrader.Client.WindowsStoreApp/Properties/AssemblyInfo.cs
1,112
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; using ItemTappedEventArgs = Syncfusion.ListView.XForms.ItemTappedEventArgs; namespace SfListViewTapIssue { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); this.BindingContext = this; } public string[] Items => new[] { "Hello", "World" }; public ICommand TappedCommand => new Command(RemoveListView); private void RemoveListView() { Layout.Children.Clear(); } private async void ListView_OnItemTapped(object sender, ItemTappedEventArgs e) { //await Task.Delay(100); <-- this dirty hack works around the problem Layout.Children.Clear(); } } }
24.702703
86
0.640044
[ "MIT" ]
MartinZikmund/SfListViewTapProblem
SfListViewTapIssue/SfListViewTapIssue/MainPage.xaml.cs
916
C#
using Zenit.Ast; using Zenit.Semantics.Symbols; namespace Zenit.Semantics.Resolvers { class ClassPropertySymbolResolver : INodeVisitor<SymbolResolverVisitor, ClassPropertyNode, ISymbol> { public ISymbol Visit(SymbolResolverVisitor binder, ClassPropertyNode node) { /*var classScope = binder.SymbolTable.CurrentScope as ClassScope; if (classScope == null) throw new SymbolException($"Current scope is not a class scope ({binder.SymbolTable.CurrentScope.GetType().Name})"); // Get the property name var propertyName = node.Name.Value; // Check if the symbol is already defined if (classScope.HasSymbol(propertyName)) throw new SymbolException($"Symbol {propertyName} is already defined."); // Create the property type var propertyType = SymbolHelper.GetType(binder.SymbolTable, binder.Inferrer, node.SymbolInfo.Type); // Create the new symbol for the property var access = SymbolHelper.GetAccess(node.SymbolInfo.Access); var storage = SymbolHelper.GetStorage(node.SymbolInfo.Mutability); var symbol = classScope.CreateProperty(propertyName, propertyType, access, storage); // If it is a type assumption, register the symbol under that assumption if (binder.Inferrer.IsTypeAssumption(propertyType)) binder.Inferrer.AddTypeDependency(propertyType, symbol); // If the property has a definition, visit the right-hand side expression node.Definition?.Visit(binder);*/ return null; } } }
41.925
132
0.661896
[ "MIT" ]
lbrugnara/flsharp
FrontEnd/Semantics/Resolvers/ClassPropertySymbolResolver.cs
1,679
C#
using Avalonia; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Markup.Xaml; using MessageBlaster.ViewModels; using MessageBlaster.Views; namespace MessageBlaster { public class App : Application { public override void Initialize() { AvaloniaXamlLoader.Load(this); } public override void OnFrameworkInitializationCompleted() { if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { desktop.MainWindow = new MainWindow { DataContext = new MainWindowViewModel(desktop.MainWindow), }; } base.OnFrameworkInitializationCompleted(); } } }
27.071429
87
0.621372
[ "MIT" ]
Kakarot/MessageBlaster
MessageBlaster/App.xaml.cs
758
C#
using Routine.Core.Configuration; using System; namespace Routine.Engine.Virtual { public class VirtualParameter : IParameter { private readonly IParametric owner; public SingleConfiguration<VirtualParameter, string> Name { get; } public SingleConfiguration<VirtualParameter, IType> ParameterType { get; } public SingleConfiguration<VirtualParameter, int> Index { get; } public VirtualParameter(IParametric owner) { this.owner = owner; Name = new SingleConfiguration<VirtualParameter, string>(this, nameof(Name), true); ParameterType = new SingleConfiguration<VirtualParameter, IType>(this, nameof(ParameterType), true); Index = new SingleConfiguration<VirtualParameter, int>(this, nameof(Index)); } #region ITypeComponent implementation object[] ITypeComponent.GetCustomAttributes() => Array.Empty<object>(); string ITypeComponent.Name => Name.Get(); IType ITypeComponent.ParentType => owner.ParentType; #endregion #region IParameter implementation IParametric IParameter.Owner => owner; IType IParameter.ParameterType => ParameterType.Get(); int IParameter.Index => Index.Get(); bool IParameter.IsOptional => false; bool IParameter.HasDefaultValue => false; object IParameter.DefaultValue => null; #endregion } }
30.681818
103
0.722222
[ "MIT" ]
multinetinventiv/routine
src/Routine/Engine/Virtual/VirtualParameter.cs
1,352
C#
using System; using System.Collections.Generic; using System.Linq; using Ardalis.GuardClauses; using VPBot.DataObjects.Base; using VPBot.DataObjects.Contracts.Core; using VPBot.DataObjects.Contracts.Services; using VPBot.DataObjects.Models; namespace VPBot.Application.Queries { public class GetMessagesQuery : BaseQuery<Func<Message, bool>, List<Message>> { private readonly IChatbotService _chatbotService; private readonly IUnitOfWork _unitOfWork; public GetMessagesQuery(IChatbotService chatbotService, IUnitOfWork unitOfWork) { Guard.Against.Null(chatbotService, nameof(chatbotService)); Guard.Against.Null(unitOfWork, nameof(unitOfWork)); _chatbotService = chatbotService; _unitOfWork = unitOfWork; } public override List<Message> Execute(Func<Message, bool> query = null) { // TODO: add support for other types of messages //var textMessagePersistence = _unitOfWork.GetPersistence<Message>(typeof(Message)); //if (_chatbotService.HasUnreadMessages()) //{ // var unreadMessages = _chatbotService.GetMessages(); // foreach (var message in unreadMessages) // textMessagePersistence.Add(message); // _unitOfWork.CommitChanges(); //} //var messages = textMessagePersistence.Query(); var messages = _chatbotService.GetMessages(); if (query != null) messages = messages.Where(query).ToList(); return messages; } } }
30.407407
96
0.6419
[ "MIT" ]
Jerajo/PVBot
vpbot/vpbot.Application/Queries/GetMessagesQuery.cs
1,644
C#
using System; using System.Collections.Generic; using Microsoft.OpenApi.Models; namespace Swashbuckle.AspNetCore.SwaggerGen { public abstract class SchemaGeneratorBase : ISchemaGenerator { private readonly SchemaGeneratorOptions _generatorOptions; private readonly List<SchemaGeneratorHandler> _handlers; protected SchemaGeneratorBase(SchemaGeneratorOptions generatorOptions) { _generatorOptions = generatorOptions; _handlers = new List<SchemaGeneratorHandler>(); } protected void AddHandler(SchemaGeneratorHandler handler) { _handlers.Add(handler); } public OpenApiSchema GenerateSchema(Type type, SchemaRepository schemaRepository) { if (_generatorOptions.CustomTypeMappings.ContainsKey(type)) { return _generatorOptions.CustomTypeMappings[type](); } if (type.IsNullable(out Type innerType)) return GenerateSchema(innerType, schemaRepository); foreach (var handler in _handlers) { if (!handler.CanCreateSchemaFor(type, out bool shouldBeReferenced)) continue; return shouldBeReferenced ? CreateReferenceSchema(type, schemaRepository, () => ApplyFiltersTo(handler.CreateDefinitionSchema(type, schemaRepository), type, schemaRepository)) : ApplyFiltersTo(handler.CreateDefinitionSchema(type, schemaRepository), type, schemaRepository); } throw new NotSupportedException($"Cannot generate schema for type {type}"); } private OpenApiSchema CreateReferenceSchema(Type type, SchemaRepository schemaRepository, Func<OpenApiSchema> factoryMethod) { return schemaRepository.GetOrAdd( type: type, schemaId: _generatorOptions.SchemaIdSelector(type), factoryMethod: factoryMethod); } private OpenApiSchema ApplyFiltersTo(OpenApiSchema schema, Type type, SchemaRepository schemaRepository) { var filterContext = new SchemaFilterContext(type, schemaRepository, this); foreach (var filter in _generatorOptions.SchemaFilters) { filter.Apply(schema, filterContext); } return schema; } } public abstract class SchemaGeneratorHandler { public abstract bool CanCreateSchemaFor(Type type, out bool shouldBeReferenced); public abstract OpenApiSchema CreateDefinitionSchema(Type type, SchemaRepository schemaRepository); } }
37.013889
169
0.663039
[ "MIT" ]
mchandschuh/Swashbuckle.AspNetCore
src/Swashbuckle.AspNetCore.SwaggerGen/SchemaGenerator/SchemaGeneratorBase.cs
2,667
C#
// This file isn't generated, but this comment is necessary to exclude it from StyleCop analysis. // For more info see: https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2108 // <auto-generated/> using System.Diagnostics.Contracts; namespace Alba.CsConsoleFormat { internal interface IConsoleBufferSource { int Width { get; } int Height { get; } [Pure] ConsoleChar[] GetLine(int y); [Pure] ConsoleChar? GetChar(int x, int y); [Pure] char GetLineChar(int x, int y); } }
24.478261
98
0.642984
[ "MIT" ]
nseedio/nseed
src/NSeed/ThirdParty/CsConsoleFormat/Formatting/IConsoleBufferSource.cs
563
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("8.AlbumInfoFromCatalogue")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("8.AlbumInfoFromCatalogue")] [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("c759246a-f3eb-4a3e-90e9-1c537b194897")] // 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.405405
84
0.748065
[ "MIT" ]
aleksandra992/CSharp
Databases/XML Processing in .NET/8.AlbumInfoFromCatalogue/Properties/AssemblyInfo.cs
1,424
C#
using System.Collections.Generic; using System.Linq; using Cosmos.I18N.Core; using EnumsNET; namespace Cosmos.I18N.Countries.Europe { /// <summary> /// France Regions /// </summary> public static partial class France { private static IEnumerable<EnumMember<EnumValues>> InternalEnumMembersCache { get; } = RegionEnumHelper.Cache<EnumValues>(); private static Dictionary<long, EnumValues> InternalCrCodeMappingCache { get; } = RegionEnumHelper.Mapping(InternalEnumMembersCache); private static IEnumerable<EnumMember<EnumValues>> Filter(string flag) => RegionEnumHelper.Filter(InternalEnumMembersCache, flag); #region Region getter public static class Regions { /// <summary> /// Département et région d'outre-mer Mayotte /// </summary> public static EnumValues Mayotte => EnumValues.Mayotte; /// <summary> /// Département et région d'outre-mer Martinique /// </summary> public static EnumValues Martinique => EnumValues.Martinique; /// <summary> /// Département et région d'outre-mer Guadeloupe /// </summary> public static EnumValues Guadeloupe => EnumValues.Guadeloupe; /// <summary> /// Département et région d'outre-mer Guyane /// </summary> public static EnumValues Guiana => EnumValues.Guiana; /// <summary> /// Département et région d'outre-mer La Réunion /// </summary> public static EnumValues Réunion => EnumValues.Réunion; /// <summary> /// Saint Martin French Part /// </summary> public static EnumValues SaintMartin => EnumValues.SaintMartin; /// <summary> /// French Southern Territories /// </summary> public static EnumValues SouthernTerritories => EnumValues.SouthernTerritories; /// <summary> /// SaintBarts /// </summary> public static EnumValues SaintBarts => EnumValues.SaintBarts; /// <summary> /// Département Bas-Rhin /// </summary> public static EnumValues DépartementBasRhin => EnumValues.DépartementBasRhin; /// <summary> /// Département Haut-Rhin /// </summary> public static EnumValues DépartementHautRhin => EnumValues.DépartementHautRhin; /// <summary> /// Dordogne /// </summary> public static EnumValues Dordogne => EnumValues.Dordogne; /// <summary> /// Gironde /// </summary> public static EnumValues Gironde => EnumValues.Gironde; /// <summary> /// Landes /// </summary> public static EnumValues Landes => EnumValues.Landes; /// <summary> /// Lot-et-Garonne /// </summary> public static EnumValues LotEtGaronne => EnumValues.LotEtGaronne; /// <summary> /// Pyrénées-Atlantiques /// </summary> public static EnumValues PyrénéesAtlantiques => EnumValues.PyrénéesAtlantiques; /// <summary> /// Cantal /// </summary> public static EnumValues Cantal => EnumValues.Cantal; /// <summary> /// Haute-Loire /// </summary> public static EnumValues HauteLoire => EnumValues.HauteLoire; /// <summary> /// Puy-de-Dôme /// </summary> public static EnumValues PuyDeDôme => EnumValues.PuyDeDôme; /// <summary> /// Allier /// </summary> public static EnumValues Allier => EnumValues.Allier; /// <summary> /// Côte-d’Or /// </summary> public static EnumValues CôtedOr => EnumValues.CôtedOr; /// <summary> /// Nièvre /// </summary> public static EnumValues Nièvre => EnumValues.Nièvre; /// <summary> /// Saône-et-Loire /// </summary> public static EnumValues SaôneEtLoire => EnumValues.SaôneEtLoire; /// <summary> /// Yonne /// </summary> public static EnumValues Yonne => EnumValues.Yonne; /// <summary> /// Côtes-d’Armor /// </summary> public static EnumValues CôtesdArmor => EnumValues.CôtesdArmor; /// <summary> /// Finistère /// </summary> public static EnumValues Finistère => EnumValues.Finistère; /// <summary> /// Ille-et-Vilaine /// </summary> public static EnumValues IlleEtVilaine => EnumValues.IlleEtVilaine; /// <summary> /// Morbihan /// </summary> public static EnumValues Morbihan => EnumValues.Morbihan; /// <summary> /// Cher /// </summary> public static EnumValues Cher => EnumValues.Cher; /// <summary> /// Eure-et-Loir /// </summary> public static EnumValues EureEtLoir => EnumValues.EureEtLoir; /// <summary> /// Indre /// </summary> public static EnumValues Indre => EnumValues.Indre; /// <summary> /// Indre-et-Loire /// </summary> public static EnumValues IndreEtLoire => EnumValues.IndreEtLoire; /// <summary> /// Loir-et-Cher /// </summary> public static EnumValues LoirEtCher => EnumValues.LoirEtCher; /// <summary> /// Loiret /// </summary> public static EnumValues Loiret => EnumValues.Loiret; /// <summary> /// Aube /// </summary> public static EnumValues Aube => EnumValues.Aube; /// <summary> /// Marne /// </summary> public static EnumValues Marne => EnumValues.Marne; /// <summary> /// Haute-Marne /// </summary> public static EnumValues HauteMarne => EnumValues.HauteMarne; /// <summary> /// Ardennes /// </summary> public static EnumValues Ardennes => EnumValues.Ardennes; /// <summary> /// Corse-du-Sud /// </summary> public static EnumValues CorseDuSud => EnumValues.CorseDuSud; /// <summary> /// Haute-Corse /// </summary> public static EnumValues HauteCorse => EnumValues.HauteCorse; /// <summary> /// Doubs /// </summary> public static EnumValues Doubs => EnumValues.Doubs; /// <summary> /// Jura /// </summary> public static EnumValues Jura => EnumValues.Jura; /// <summary> /// Haute-Saône /// </summary> public static EnumValues HauteSaône => EnumValues.HauteSaône; /// <summary> /// Territoire de Belfort /// </summary> public static EnumValues TerritoireDeBelfort => EnumValues.TerritoireDeBelfort; /// <summary> /// Paris /// </summary> public static EnumValues Paris => EnumValues.Paris; /// <summary> /// Seine-et-Marne /// </summary> public static EnumValues SeineEtMarne => EnumValues.SeineEtMarne; /// <summary> /// Yvelines /// </summary> public static EnumValues Yvelines => EnumValues.Yvelines; /// <summary> /// Essonne /// </summary> public static EnumValues Essonne => EnumValues.Essonne; /// <summary> /// Hauts-de-Seine /// </summary> public static EnumValues HautsDeSeine => EnumValues.HautsDeSeine; /// <summary> /// Seine-Saint-Denis /// </summary> public static EnumValues SeineSaintDenis => EnumValues.SeineSaintDenis; /// <summary> /// Val-de-Marne /// </summary> public static EnumValues ValDeMarne => EnumValues.ValDeMarne; /// <summary> /// Val-d’Oise /// </summary> public static EnumValues ValdOise => EnumValues.ValdOise; /// <summary> /// Aude /// </summary> public static EnumValues Aude => EnumValues.Aude; /// <summary> /// Gard /// </summary> public static EnumValues Gard => EnumValues.Gard; /// <summary> /// Hérault /// </summary> public static EnumValues Hérault => EnumValues.Hérault; /// <summary> /// Lozère /// </summary> public static EnumValues Lozère => EnumValues.Lozère; /// <summary> /// Pyrénées-Orientales /// </summary> public static EnumValues PyrénéesOrientales => EnumValues.PyrénéesOrientales; /// <summary> /// Corrèze /// </summary> public static EnumValues Corrèze => EnumValues.Corrèze; /// <summary> /// Creuse /// </summary> public static EnumValues Creuse => EnumValues.Creuse; /// <summary> /// Haute-Vienne /// </summary> public static EnumValues HauteVienne => EnumValues.HauteVienne; /// <summary> /// Meurthe-et-Moselle /// </summary> public static EnumValues MeurtheEtMoselle => EnumValues.MeurtheEtMoselle; /// <summary> /// Meuse /// </summary> public static EnumValues Meuse => EnumValues.Meuse; /// <summary> /// Département Moselle /// </summary> public static EnumValues DépartementMoselle => EnumValues.DépartementMoselle; /// <summary> /// Vosges /// </summary> public static EnumValues Vosges => EnumValues.Vosges; /// <summary> /// Aveyron /// </summary> public static EnumValues Aveyron => EnumValues.Aveyron; /// <summary> /// Haute-Garonne /// </summary> public static EnumValues HauteGaronne => EnumValues.HauteGaronne; /// <summary> /// Gers /// </summary> public static EnumValues Gers => EnumValues.Gers; /// <summary> /// Lot /// </summary> public static EnumValues Lot => EnumValues.Lot; /// <summary> /// Hautes-Pyrénées /// </summary> public static EnumValues HautesPyrénées => EnumValues.HautesPyrénées; /// <summary> /// Tarn /// </summary> public static EnumValues Tarn => EnumValues.Tarn; /// <summary> /// Tarn-et-Garonne /// </summary> public static EnumValues TarnEtGaronne => EnumValues.TarnEtGaronne; /// <summary> /// Ariège /// </summary> public static EnumValues Ariège => EnumValues.Ariège; /// <summary> /// Nord /// </summary> public static EnumValues Nord => EnumValues.Nord; /// <summary> /// Pas-de-Calais /// </summary> public static EnumValues PasDeCalais => EnumValues.PasDeCalais; /// <summary> /// Calvados /// </summary> public static EnumValues Calvados => EnumValues.Calvados; /// <summary> /// Manche /// </summary> public static EnumValues Manche => EnumValues.Manche; /// <summary> /// Orne /// </summary> public static EnumValues Orne => EnumValues.Orne; /// <summary> /// Eure /// </summary> public static EnumValues Eure => EnumValues.Eure; /// <summary> /// Seine-Maritime /// </summary> public static EnumValues SeineMaritime => EnumValues.SeineMaritime; /// <summary> /// Loire-Atlantique /// </summary> public static EnumValues LoireAtlantique => EnumValues.LoireAtlantique; /// <summary> /// Maine-et-Loire /// </summary> public static EnumValues MaineEtLoire => EnumValues.MaineEtLoire; /// <summary> /// Mayenne /// </summary> public static EnumValues Mayenne => EnumValues.Mayenne; /// <summary> /// Sarthe /// </summary> public static EnumValues Sarthe => EnumValues.Sarthe; /// <summary> /// Vendée /// </summary> public static EnumValues Vendée => EnumValues.Vendée; /// <summary> /// Oise /// </summary> public static EnumValues Oise => EnumValues.Oise; /// <summary> /// Somme /// </summary> public static EnumValues Somme => EnumValues.Somme; /// <summary> /// Aisne /// </summary> public static EnumValues Aisne => EnumValues.Aisne; /// <summary> /// Charente /// </summary> public static EnumValues Charente => EnumValues.Charente; /// <summary> /// Charente-Maritime /// </summary> public static EnumValues CharenteMaritime => EnumValues.CharenteMaritime; /// <summary> /// Deux-Sèvres /// </summary> public static EnumValues DeuxSèvres => EnumValues.DeuxSèvres; /// <summary> /// Vienne /// </summary> public static EnumValues Vienne => EnumValues.Vienne; /// <summary> /// Bouches-du-Rhône /// </summary> public static EnumValues BouchesDuRhône => EnumValues.BouchesDuRhône; /// <summary> /// Var /// </summary> public static EnumValues Var => EnumValues.Var; /// <summary> /// Vaucluse /// </summary> public static EnumValues Vaucluse => EnumValues.Vaucluse; /// <summary> /// Alpes-de-Haute-Provence /// </summary> public static EnumValues AlpesDeHauteProvence => EnumValues.AlpesDeHauteProvence; /// <summary> /// Hautes-Alpes /// </summary> public static EnumValues HautesAlpes => EnumValues.HautesAlpes; /// <summary> /// Alpes-Maritimes /// </summary> public static EnumValues AlpesMaritimes => EnumValues.AlpesMaritimes; /// <summary> /// Drôme /// </summary> public static EnumValues Drôme => EnumValues.Drôme; /// <summary> /// Isère /// </summary> public static EnumValues Isère => EnumValues.Isère; /// <summary> /// Loire /// </summary> public static EnumValues Loire => EnumValues.Loire; /// <summary> /// Rhône /// </summary> public static EnumValues Rhône => EnumValues.Rhône; /// <summary> /// Savoie /// </summary> public static EnumValues Savoie => EnumValues.Savoie; /// <summary> /// Haute-Savoie /// </summary> public static EnumValues HauteSavoie => EnumValues.HauteSavoie; /// <summary> /// Ain /// </summary> public static EnumValues Ain => EnumValues.Ain; /// <summary> /// Ardèche /// </summary> public static EnumValues Ardèche => EnumValues.Ardèche; } #endregion #region Region definition /// <summary> /// Special regions /// </summary> public static class Special { /// <summary> /// Mayotte /// </summary> // ReSharper disable once MemberHidesStaticFromOuterClass public static Country Mayotte => Country.Mayotte; /// <summary> /// Mayotte /// </summary> public static CountryCode MayotteCode => CountryCode.YT; /// <summary> /// Martinique /// </summary> // ReSharper disable once MemberHidesStaticFromOuterClass public static Country Martinique => Country.Martinique; /// <summary> /// Martinique /// </summary> public static CountryCode MartiniqueCode => CountryCode.MQ; /// <summary> /// Guadeloupe /// </summary> // ReSharper disable once MemberHidesStaticFromOuterClass public static Country Guadeloupe => Country.Guadeloupe; /// <summary> /// Guadeloupe /// </summary> public static CountryCode GuadeloupeCode => CountryCode.GP; /// <summary> /// Guiana /// </summary> // ReSharper disable once MemberHidesStaticFromOuterClass public static Country Guiana => Country.Guiana; /// <summary> /// Guiana /// </summary> public static CountryCode GuianaCode => CountryCode.GF; /// <summary> /// Réunion /// </summary> // ReSharper disable once MemberHidesStaticFromOuterClass public static Country Réunion => Country.Réunion; /// <summary> /// Réunion /// </summary> public static CountryCode RéunionCode => CountryCode.RE; /// <summary> /// SaintMartinFrenchPart /// </summary> // ReSharper disable once MemberHidesStaticFromOuterClass public static Country SaintMartin => Country.SaintMartinFrenchPart; /// <summary> /// SaintMartinFrenchPart /// </summary> public static CountryCode SaintMartinCode => CountryCode.MF; } /// <summary> /// Enum values for France regions. /// </summary> public enum EnumValues { /// <summary> /// Département et région d'outre-mer Mayotte /// </summary> [AliasInShort("YT")] [RegionCode(2_00_001_1001)] [RegionFlag("overseas")] Mayotte, /// <summary> /// Département et région d'outre-mer Martinique /// </summary> [AliasInShort("MQ")] [RegionCode(2_00_001_1002)] [RegionFlag("overseas")] Martinique, /// <summary> /// Département et région d'outre-mer Guadeloupe /// </summary> [AliasInShort("GP")] [RegionCode(2_00_001_1003)] [RegionFlag("overseas")] Guadeloupe, /// <summary> /// Département et région d'outre-mer Guyane /// </summary> [AliasInShort("GF")] [RegionCode(2_00_001_1004)] [RegionFlag("overseas")] Guiana, /// <summary> /// Département et région d'outre-mer La Réunion /// </summary> [AliasInShort("RE")] [RegionCode(2_00_001_1005)] [RegionFlag("overseas")] Réunion, /// <summary> /// Saint Martin French Part /// </summary> [AliasInShort("MF")] [RegionCode(2_00_001_1006)] [RegionFlag("overseas")] SaintMartin, /// <summary> /// French Southern Territories /// </summary> [AliasInShort("TF")] [RegionCode(2_00_001_1007)] [RegionFlag("overseas")] SouthernTerritories, /// <summary> /// SaintBarts /// </summary> [AliasInShort("BL")] [RegionCode(2_00_001_1008)] [RegionFlag("overseas")] SaintBarts, /// <summary> /// Département Bas-Rhin /// </summary> [AliasInShort("67")] [RegionCode(2_00_001_0067)] [RegionFlag("main")] DépartementBasRhin, /// <summary> /// Département Haut-Rhin /// </summary> [AliasInShort("68")] [RegionCode(2_00_001_0068)] [RegionFlag("main")] DépartementHautRhin, /// <summary> /// Dordogne /// </summary> [AliasInShort("24")] [RegionCode(2_00_001_0024)] [RegionFlag("main")] Dordogne, /// <summary> /// Gironde /// </summary> [AliasInShort("33")] [RegionCode(2_00_001_0033)] [RegionFlag("main")] Gironde, /// <summary> /// Landes /// </summary> [AliasInShort("40")] [RegionCode(2_00_001_0040)] [RegionFlag("main")] Landes, /// <summary> /// Lot-et-Garonne /// </summary> [AliasInShort("47")] [RegionCode(2_00_001_0047)] [RegionFlag("main")] LotEtGaronne, /// <summary> /// Pyrénées-Atlantiques /// </summary> [AliasInShort("64")] [RegionCode(2_00_001_0064)] [RegionFlag("main")] PyrénéesAtlantiques, /// <summary> /// Cantal /// </summary> [AliasInShort("15")] [RegionCode(2_00_001_0015)] [RegionFlag("main")] Cantal, /// <summary> /// Haute-Loire /// </summary> [AliasInShort("43")] [RegionCode(2_00_001_0043)] [RegionFlag("main")] HauteLoire, /// <summary> /// Puy-de-Dôme /// </summary> [AliasInShort("63")] [RegionCode(2_00_001_0063)] [RegionFlag("main")] PuyDeDôme, /// <summary> /// Allier /// </summary> [AliasInShort("03")] [RegionCode(2_00_001_0003)] [RegionFlag("main")] Allier, /// <summary> /// Côte-d’Or /// </summary> [AliasInShort("21")] [RegionCode(2_00_001_0021)] [RegionFlag("main")] CôtedOr, /// <summary> /// Nièvre /// </summary> [AliasInShort("58")] [RegionCode(2_00_001_0058)] [RegionFlag("main")] Nièvre, /// <summary> /// Saône-et-Loire /// </summary> [AliasInShort("71")] [RegionCode(2_00_001_0071)] [RegionFlag("main")] SaôneEtLoire, /// <summary> /// Yonne /// </summary> [AliasInShort("89")] [RegionCode(2_00_001_0089)] [RegionFlag("main")] Yonne, /// <summary> /// Côtes-d’Armor /// </summary> [AliasInShort("22")] [RegionCode(2_00_001_0022)] [RegionFlag("main")] CôtesdArmor, /// <summary> /// Finistère /// </summary> [AliasInShort("29")] [RegionCode(2_00_001_0029)] [RegionFlag("main")] Finistère, /// <summary> /// Ille-et-Vilaine /// </summary> [AliasInShort("35")] [RegionCode(2_00_001_0035)] [RegionFlag("main")] IlleEtVilaine, /// <summary> /// Morbihan /// </summary> [AliasInShort("56")] [RegionCode(2_00_001_0056)] [RegionFlag("main")] Morbihan, /// <summary> /// Cher /// </summary> [AliasInShort("18")] [RegionCode(2_00_001_0018)] [RegionFlag("main")] Cher, /// <summary> /// Eure-et-Loir /// </summary> [AliasInShort("28")] [RegionCode(2_00_001_0028)] [RegionFlag("main")] EureEtLoir, /// <summary> /// Indre /// </summary> [AliasInShort("36")] [RegionCode(2_00_001_0036)] [RegionFlag("main")] Indre, /// <summary> /// Indre-et-Loire /// </summary> [AliasInShort("37")] [RegionCode(2_00_001_0037)] [RegionFlag("main")] IndreEtLoire, /// <summary> /// Loir-et-Cher /// </summary> [AliasInShort("41")] [RegionCode(2_00_001_0041)] [RegionFlag("main")] LoirEtCher, /// <summary> /// Loiret /// </summary> [AliasInShort("45")] [RegionCode(2_00_001_0045)] [RegionFlag("main")] Loiret, /// <summary> /// Aube /// </summary> [AliasInShort("10")] [RegionCode(2_00_001_0010)] [RegionFlag("main")] Aube, /// <summary> /// Marne /// </summary> [AliasInShort("51")] [RegionCode(2_00_001_0051)] [RegionFlag("main")] Marne, /// <summary> /// Haute-Marne /// </summary> [AliasInShort("52")] [RegionCode(2_00_001_0052)] [RegionFlag("main")] HauteMarne, /// <summary> /// Ardennes /// </summary> [AliasInShort("08")] [RegionCode(2_00_001_0008)] [RegionFlag("main")] Ardennes, /// <summary> /// Corse-du-Sud /// </summary> [AliasInShort("2A")] [RegionCode(2_00_001_1021)] [RegionFlag("main")] CorseDuSud, /// <summary> /// Haute-Corse /// </summary> [AliasInShort("2B")] [RegionCode(2_00_001_1022)] [RegionFlag("main")] HauteCorse, /// <summary> /// Doubs /// </summary> [AliasInShort("25")] [RegionCode(2_00_001_0025)] [RegionFlag("main")] Doubs, /// <summary> /// Jura /// </summary> [AliasInShort("39")] [RegionCode(2_00_001_0039)] [RegionFlag("main")] Jura, /// <summary> /// Haute-Saône /// </summary> [AliasInShort("70")] [RegionCode(2_00_001_0070)] [RegionFlag("main")] HauteSaône, /// <summary> /// Territoire de Belfort /// </summary> [AliasInShort("90")] [RegionCode(2_00_001_0090)] [RegionFlag("main")] TerritoireDeBelfort, /// <summary> /// Paris /// </summary> [AliasInShort("75")] [RegionCode(2_00_001_0075)] [RegionFlag("main")] Paris, /// <summary> /// Seine-et-Marne /// </summary> [AliasInShort("77")] [RegionCode(2_00_001_0077)] [RegionFlag("main")] SeineEtMarne, /// <summary> /// Yvelines /// </summary> [AliasInShort("78")] [RegionCode(2_00_001_0078)] [RegionFlag("main")] Yvelines, /// <summary> /// Essonne /// </summary> [AliasInShort("91")] [RegionCode(2_00_001_0091)] [RegionFlag("main")] Essonne, /// <summary> /// Hauts-de-Seine /// </summary> [AliasInShort("92")] [RegionCode(2_00_001_0092)] [RegionFlag("main")] HautsDeSeine, /// <summary> /// Seine-Saint-Denis /// </summary> [AliasInShort("93")] [RegionCode(2_00_001_0093)] [RegionFlag("main")] SeineSaintDenis, /// <summary> /// Val-de-Marne /// </summary> [AliasInShort("94")] [RegionCode(2_00_001_0094)] [RegionFlag("main")] ValDeMarne, /// <summary> /// Val-d’Oise /// </summary> [AliasInShort("95")] [RegionCode(2_00_001_0095)] [RegionFlag("main")] ValdOise, /// <summary> /// Aude /// </summary> [AliasInShort("11")] [RegionCode(2_00_001_0001)] [RegionFlag("main")] Aude, /// <summary> /// Gard /// </summary> [AliasInShort("30")] [RegionCode(2_00_001_0030)] [RegionFlag("main")] Gard, /// <summary> /// Hérault /// </summary> [AliasInShort("34")] [RegionCode(2_00_001_0034)] [RegionFlag("main")] Hérault, /// <summary> /// Lozère /// </summary> [AliasInShort("48")] [RegionCode(2_00_001_0048)] [RegionFlag("main")] Lozère, /// <summary> /// Pyrénées-Orientales /// </summary> [AliasInShort("66")] [RegionCode(2_00_001_0066)] [RegionFlag("main")] PyrénéesOrientales, /// <summary> /// Corrèze /// </summary> [AliasInShort("19")] [RegionCode(2_00_001_0019)] [RegionFlag("main")] Corrèze, /// <summary> /// Creuse /// </summary> [AliasInShort("23")] [RegionCode(2_00_001_0023)] [RegionFlag("main")] Creuse, /// <summary> /// Haute-Vienne /// </summary> [AliasInShort("87")] [RegionCode(2_00_001_0087)] [RegionFlag("main")] HauteVienne, /// <summary> /// Meurthe-et-Moselle /// </summary> [AliasInShort("54")] [RegionCode(2_00_001_0054)] [RegionFlag("main")] MeurtheEtMoselle, /// <summary> /// Meuse /// </summary> [AliasInShort("55")] [RegionCode(2_00_001_0055)] [RegionFlag("main")] Meuse, /// <summary> /// Département Moselle /// </summary> [AliasInShort("57")] [RegionCode(2_00_001_0057)] [RegionFlag("main")] DépartementMoselle, /// <summary> /// Vosges /// </summary> [AliasInShort("88")] [RegionCode(2_00_001_0088)] [RegionFlag("main")] Vosges, /// <summary> /// Aveyron /// </summary> [AliasInShort("12")] [RegionCode(2_00_001_0012)] [RegionFlag("main")] Aveyron, /// <summary> /// Haute-Garonne /// </summary> [AliasInShort("31")] [RegionCode(2_00_001_0031)] [RegionFlag("main")] HauteGaronne, /// <summary> /// Gers /// </summary> [AliasInShort("32")] [RegionCode(2_00_001_0032)] [RegionFlag("main")] Gers, /// <summary> /// Lot /// </summary> [AliasInShort("46")] [RegionCode(2_00_001_0046)] [RegionFlag("main")] Lot, /// <summary> /// Hautes-Pyrénées /// </summary> [AliasInShort("65")] [RegionCode(2_00_001_0065)] [RegionFlag("main")] HautesPyrénées, /// <summary> /// Tarn /// </summary> [AliasInShort("81")] [RegionCode(2_00_001_0081)] [RegionFlag("main")] Tarn, /// <summary> /// Tarn-et-Garonne /// </summary> [AliasInShort("82")] [RegionCode(2_00_001_0082)] [RegionFlag("main")] TarnEtGaronne, /// <summary> /// Ariège /// </summary> [AliasInShort("09")] [RegionCode(2_00_001_0009)] [RegionFlag("main")] Ariège, /// <summary> /// Nord /// </summary> [AliasInShort("59")] [RegionCode(2_00_001_0059)] [RegionFlag("main")] Nord, /// <summary> /// Pas-de-Calais /// </summary> [AliasInShort("62")] [RegionCode(2_00_001_0062)] [RegionFlag("main")] PasDeCalais, /// <summary> /// Calvados /// </summary> [AliasInShort("14")] [RegionCode(2_00_001_0014)] [RegionFlag("main")] Calvados, /// <summary> /// Manche /// </summary> [AliasInShort("50")] [RegionCode(2_00_001_0050)] [RegionFlag("main")] Manche, /// <summary> /// Orne /// </summary> [AliasInShort("61")] [RegionCode(2_00_001_0061)] [RegionFlag("main")] Orne, /// <summary> /// Eure /// </summary> [AliasInShort("27")] [RegionCode(2_00_001_0027)] [RegionFlag("main")] Eure, /// <summary> /// Seine-Maritime /// </summary> [AliasInShort("76")] [RegionCode(2_00_001_0076)] [RegionFlag("main")] SeineMaritime, /// <summary> /// Loire-Atlantique /// </summary> [AliasInShort("44")] [RegionCode(2_00_001_0044)] [RegionFlag("main")] LoireAtlantique, /// <summary> /// Maine-et-Loire /// </summary> [AliasInShort("49")] [RegionCode(2_00_001_0049)] [RegionFlag("main")] MaineEtLoire, /// <summary> /// Mayenne /// </summary> [AliasInShort("53")] [RegionCode(2_00_001_0053)] [RegionFlag("main")] Mayenne, /// <summary> /// Sarthe /// </summary> [AliasInShort("72")] [RegionCode(2_00_001_0072)] [RegionFlag("main")] Sarthe, /// <summary> /// Vendée /// </summary> [AliasInShort("85")] [RegionCode(2_00_001_0085)] [RegionFlag("main")] Vendée, /// <summary> /// Oise /// </summary> [AliasInShort("60")] [RegionCode(2_00_001_0060)] [RegionFlag("main")] Oise, /// <summary> /// Somme /// </summary> [AliasInShort("80")] [RegionCode(2_00_001_0080)] [RegionFlag("main")] Somme, /// <summary> /// Aisne /// </summary> [AliasInShort("02")] [RegionCode(2_00_001_0002)] [RegionFlag("main")] Aisne, /// <summary> /// Charente /// </summary> [AliasInShort("16")] [RegionCode(2_00_001_0016)] [RegionFlag("main")] Charente, /// <summary> /// Charente-Maritime /// </summary> [AliasInShort("17")] [RegionCode(2_00_001_0017)] [RegionFlag("main")] CharenteMaritime, /// <summary> /// Deux-Sèvres /// </summary> [AliasInShort("79")] [RegionCode(2_00_001_0079)] [RegionFlag("main")] DeuxSèvres, /// <summary> /// Vienne /// </summary> [AliasInShort("86")] [RegionCode(2_00_001_0086)] [RegionFlag("main")] Vienne, /// <summary> /// Bouches-du-Rhône /// </summary> [AliasInShort("13")] [RegionCode(2_00_001_0013)] [RegionFlag("main")] BouchesDuRhône, /// <summary> /// Var /// </summary> [AliasInShort("83")] [RegionCode(2_00_001_0083)] [RegionFlag("main")] Var, /// <summary> /// Vaucluse /// </summary> [AliasInShort("84")] [RegionCode(2_00_001_0084)] [RegionFlag("main")] Vaucluse, /// <summary> /// Alpes-de-Haute-Provence /// </summary> [AliasInShort("04")] [RegionCode(2_00_001_0004)] [RegionFlag("main")] AlpesDeHauteProvence, /// <summary> /// Hautes-Alpes /// </summary> [AliasInShort("05")] [RegionCode(2_00_001_0005)] [RegionFlag("main")] HautesAlpes, /// <summary> /// Alpes-Maritimes /// </summary> [AliasInShort("06")] [RegionCode(2_00_001_0006)] [RegionFlag("main")] AlpesMaritimes, /// <summary> /// Drôme /// </summary> [AliasInShort("26")] [RegionCode(2_00_001_0026)] [RegionFlag("main")] Drôme, /// <summary> /// Isère /// </summary> [AliasInShort("38")] [RegionCode(2_00_001_0038)] [RegionFlag("main")] Isère, /// <summary> /// Loire /// </summary> [AliasInShort("42")] [RegionCode(2_00_001_0042)] [RegionFlag("main")] Loire, /// <summary> /// Rhône /// </summary> [AliasInShort("69")] [RegionCode(2_00_001_0069)] [RegionFlag("main")] Rhône, /// <summary> /// Savoie /// </summary> [AliasInShort("73")] [RegionCode(2_00_001_0073)] [RegionFlag("main")] Savoie, /// <summary> /// Haute-Savoie /// </summary> [AliasInShort("74")] [RegionCode(2_00_001_0074)] [RegionFlag("main")] HauteSavoie, /// <summary> /// Ain /// </summary> [AliasInShort("01")] [RegionCode(2_00_001_0001)] [RegionFlag("main")] Ain, /// <summary> /// Ardèche /// </summary> [AliasInShort("07")] [RegionCode(2_00_001_0007)] [RegionFlag("main")] Ardèche, /// <summary> /// Unknown /// </summary> [IgnoreRegion] [AliasInShort("??")] [RegionCode(0)] Unknown, } #endregion #region Static methods /// <summary> /// Convert from special regions of France /// </summary> /// <param name="country"></param> /// <returns></returns> public static EnumValues FromSpecialRegions(Country country) { switch (country) { case Country.Mayotte: return EnumValues.Mayotte; case Country.Martinique: return EnumValues.Martinique; case Country.Guadeloupe: return EnumValues.Guadeloupe; case Country.Guiana: return EnumValues.Guiana; case Country.Réunion: return EnumValues.Réunion; case Country.SaintMartinFrenchPart: return EnumValues.SaintMartin; case Country.FrenchSouthernTerritories: return EnumValues.SouthernTerritories; case Country.SaintBarts: return EnumValues.SaintBarts; default: return EnumValues.Unknown; } } /// <summary> /// Convert from special regions of France /// </summary> /// <param name="code"></param> /// <returns></returns> public static EnumValues FromSpecialRegions(CountryCode code) { switch (code) { case CountryCode.YT: return EnumValues.Mayotte; case CountryCode.MQ: return EnumValues.Martinique; case CountryCode.GP: return EnumValues.Guadeloupe; case CountryCode.GF: return EnumValues.Guiana; case CountryCode.RE: return EnumValues.Réunion; case CountryCode.MF: return EnumValues.SaintMartin; case CountryCode.TF: return EnumValues.SouthernTerritories; case CountryCode.BL: return EnumValues.SaintBarts; default: return EnumValues.Unknown; } } #endregion #region All regions getter /// <summary> /// Get all region code /// </summary> /// <returns></returns> public static IEnumerable<string> GetAllRegionCodes() => InternalEnumMembersCache.Select(member => member.Value.ToFullRegionCode()); /// <summary> /// 获得本土地区的地区代号 /// </summary> /// <returns></returns> public static IEnumerable<string> GetMainRegionCodes() => Filter("mainland").Select(member => member.Value.ToFullRegionCode()); /// <summary> /// 获得海外地区的地区代号 /// </summary> /// <returns></returns> public static IEnumerable<string> GetOverseasRegionCodes() => Filter("overseas").Select(member => member.Value.ToFullRegionCode()); /// <summary> /// Get all numeric region code(CEP-1 / Cosmos Region Code). /// </summary> /// <returns></returns> public static IEnumerable<long> GetAllNumericRegionCodes() => InternalEnumMembersCache.Select(member => member.Value.ToNumericRegionCode()); #endregion } }
28.699681
141
0.448781
[ "Apache-2.0" ]
alexinea/I18N
src/Cosmos.I18N.Countries/Cosmos/I18N/Countries/Europe/France.Regions.cs
45,139
C#
using IdentityServer4.Stores; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using System.Threading.Tasks; namespace Jp.UI.SSO.Util { public static class Extensions { /// <summary> /// Determines whether the client is configured to use PKCE. /// </summary> /// <param name="store">The store.</param> /// <param name="client_id">The client identifier.</param> /// <returns></returns> public static async Task<bool> IsPkceClientAsync(this IClientStore store, string client_id) { if (!string.IsNullOrWhiteSpace(client_id)) { var client = await store.FindEnabledClientByIdAsync(client_id); return client?.RequirePkce == true; } return false; } public static bool IsBehindReverseProxy(this IWebHostEnvironment host, IConfiguration configuration) { var config = configuration["ASPNETCORE_REVERSEPROXY"]; return !string.IsNullOrEmpty(config) && config.Equals("true"); } } }
32.764706
108
0.625673
[ "MIT" ]
aeleftheriadis/JPProject.IdentityServer4.SSO
src/Frontend/Jp.UI.SSO/Util/Extensions.cs
1,116
C#
using System; using UnityEditor.ShaderGraph; using UnityEngine.Rendering; namespace UnityEditor.Rendering.Universal.ShaderGraph { static class CreateSpriteLitShaderGraph { [MenuItem("Assets/Create/Shader Graph/URP/Sprite Lit Shader Graph", priority = CoreUtils.Sections.section1 + CoreUtils.Priorities.assetsCreateShaderMenuPriority + 1)] public static void CreateSpriteLitGraph() { var target = (UniversalTarget)Activator.CreateInstance(typeof(UniversalTarget)); target.TrySetActiveSubTarget(typeof(UniversalSpriteLitSubTarget)); var blockDescriptors = new[] { BlockFields.VertexDescription.Position, BlockFields.VertexDescription.Normal, BlockFields.VertexDescription.Tangent, BlockFields.SurfaceDescription.BaseColor, UniversalBlockFields.SurfaceDescription.SpriteMask, BlockFields.SurfaceDescription.NormalTS, BlockFields.SurfaceDescription.Alpha, }; GraphUtil.CreateNewGraphWithOutputs(new[] { target }, blockDescriptors); } } }
38.833333
174
0.680687
[ "MIT" ]
Liaoer/ToonShader
Packages/com.unity.render-pipelines.universal@12.1.3/Editor/2D/ShaderGraph/AssetCallbacks/CreateSpriteLitShaderGraph.cs
1,165
C#
using System; using Newtonsoft.Json; using SharpYaml.Serialization; using WorkflowCore.Models.DefinitionStorage.v1; namespace WorkflowCore.Services.DefinitionStorage { public static class Deserializers { private static Serializer yamlSerializer = new Serializer(); public static Func<string, DefinitionSourceV1> Json = (source) => JsonConvert.DeserializeObject<DefinitionSourceV1>(source); public static Func<string, DefinitionSourceV1> Yaml = (source) => yamlSerializer.DeserializeInto(source, new DefinitionSourceV1()); } }
33.294118
139
0.765018
[ "MIT" ]
201512130144/demo
src/WorkflowCore.DSL/Services/Deserializers.cs
568
C#
using System; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; using SIS.WebServer.Routing; namespace SIS.WebServer { public class Server { private const string LocalhostIpAddress = "127.0.0.1"; private readonly int port; private readonly TcpListener listener; private readonly ServerRoutingTable serverRoutingTable; private bool isRunning; public Server(int port, ServerRoutingTable serverRoutingTable) { this.port = port; this.listener = new TcpListener(IPAddress.Parse(LocalhostIpAddress), port); this.serverRoutingTable = serverRoutingTable; } public void Run() { this.listener.Start(); this.isRunning = true; Console.WriteLine($"Server started at http://{LocalhostIpAddress}:{this.port}"); while (isRunning) { var client = listener.AcceptSocketAsync().GetAwaiter().GetResult(); Task.Run(() => Listen(client)); } } public async void Listen(Socket client) { var connectionHandler = new ConnectionHandler(client, this.serverRoutingTable); await connectionHandler.ProcessRequestAsync(); } } }
27.416667
92
0.613222
[ "MIT" ]
stoyanovmiroslav/CSharp-Web
CSharp Web Development Basics/CSharp-Web-Development-Basics-Exams/SIS.WebServer/Server.cs
1,316
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace toy_web { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); } } }
31.020408
143
0.661184
[ "MIT" ]
victoliveiramos/toy
src/toy-web/Startup.cs
1,522
C#
// <copyright file="EnvironmentModule.cs"> // Copyright 2019 Marcus Walther // </copyright> // <author>Marcus Walther</author> // ReSharper disable UnusedMember.Global namespace EnvironmentModuleCore { using System.Collections.Generic; using System.Linq; /// <summary> /// This class represents a loaded environment module in the environment. It holds references to all information given by the user or the description file. /// </summary> public class EnvironmentModule : EnvironmentModuleInfo { #region Private Fields /// <summary> /// All path info objects that can be accesses using the Properties "AppendPaths", "Paths" and "PrependPaths". /// </summary> private readonly Dictionary<string, PathInfo> pathInfos; #endregion #region Constructors /// <summary> /// Initializes a new instance of the EnvironmentModule class with the given parameters. /// </summary> /// <param name="baseModule">The info object of the module.</param> /// <param name="isLoadedDirectly">True if the module was loaded directly by the user. False if the module was loaded as dependency of another module.</param> /// <param name="sourceModule">The module that has triggered the loading. Should be set if isLoadedDirectly is false.</param> public EnvironmentModule( EnvironmentModuleInfo baseModule, bool isLoadedDirectly = true, EnvironmentModuleInfo sourceModule = null) : base(baseModule) { IsLoadedDirectly = isLoadedDirectly; SourceModule = sourceModule; pathInfos = new Dictionary<string, PathInfo>(); Aliases = new Dictionary<string, AliasInfo>(); Functions = new Dictionary<string, FunctionInfo>(); } #endregion #region Properties /// <summary> /// Gets or sets the collection of aliases (dictionary-keys) that are set if the module is loaded. The aliases /// are deleted if unload is called. The value represents the command and an optional description. /// </summary> public Dictionary<string, AliasInfo> Aliases { get; protected set; } /// <summary> /// Gets a collection of paths that are appended to the environment variables when the module is loaded. The values /// are removed from the environment when unload is called. /// </summary> public HashSet<PathInfo> AppendPaths { get { return new HashSet<PathInfo>(pathInfos.Values.Where(x => x.PathType == PathType.APPEND)); } } /// <summary> /// Gets or sets a collection of aliases (dictionary-keys) that are set if the module is loaded. The aliases /// are deleted if unload is called. The value represents the command. /// </summary> public Dictionary<string, FunctionInfo> Functions { get; protected set; } /// <summary> /// Gets or sets a value indicating whether the module was loaded by the user or as dependency of another module. /// </summary> public bool IsLoadedDirectly { get; set; } /// <summary> /// Gets a collection of paths that are added to the environment variables when the module is loaded. The values /// are removed from the environment-variable when unload is called. /// </summary> public HashSet<PathInfo> Paths => new HashSet<PathInfo>(pathInfos.Values); /// <summary> /// Gets a collection of paths that are prepended to the environment variables when the module is loaded. The values /// are removed from the environment-variable when unload is called. /// </summary> public HashSet<PathInfo> PrependPaths { get { return new HashSet<PathInfo>(pathInfos.Values.Where(x => x.PathType == PathType.PREPEND)); } } /// <summary> /// Gets or sets the reference counter that is decreased when the module is removed and increased when loaded or referenced as dependency. /// </summary> public int ReferenceCounter { get; set; } /// <summary> /// Gets a collection of paths that are set to the environment variables when the module is loaded. The values /// are removed from the environment-variable when unload is called. /// </summary> public HashSet<PathInfo> SetPaths { get { return new HashSet<PathInfo>(pathInfos.Values.Where(x => x.PathType == PathType.SET)); } } /// <summary> /// Gets or sets the module that has triggered the loading of the module. The value is null if the module was loaded directly by the user. /// </summary> public EnvironmentModuleInfo SourceModule { get; protected set; } #endregion #region Public Functions /// <summary> /// Add a prepend environment variable manipulation to the definition. /// </summary> /// <param name="envVar">The environment variable to modify.</param> /// <param name="path">The value to prepend.</param> public void AddPrependPath(string envVar, string path) { AddPath(PathType.PREPEND, envVar, path); } /// <summary> /// Add a append environment variable manipulation to the definition. /// </summary> /// <param name="envVar">The environment variable to modify.</param> /// <param name="path">The value to append.</param> public void AddAppendPath(string envVar, string path) { AddPath(PathType.APPEND, envVar, path); } /// <summary> /// Add a environment variable manipulation to the definition that overwrites or defines an environment variable. /// </summary> /// <param name="envVar">The environment variable to modify.</param> /// <param name="path">The value to set.</param> public void AddSetPath(string envVar, string path) { AddPath(PathType.SET, envVar, path); } /// <summary> /// Add a new alias definition to the environment module. /// </summary> /// <param name="aliasName">The name of the alias to define.</param> /// <param name="command">The command that should be executed on invocation.</param> /// <param name="description">An additional description that can be displayed for the user.</param> public void AddAlias(string aliasName, string command, string description = "") { Aliases[aliasName] = new AliasInfo(aliasName, FullName, command, description); } /// <summary> /// Add a new function definition to the environment module. /// </summary> /// <param name="functionName">The name of the function to define.</param> /// <param name="content">The function content. Usually this is a ScriptBlock. The object must provide an Invoke function.</param> public void AddFunction(string functionName, object content) { Functions[functionName] = new FunctionInfo(functionName, FullName, content); } #endregion #region Protected Functions /// <summary> /// Add a new environment variable manipulation to the definition of the environment module. /// </summary> /// <param name="pathType">The type of the path manipulation.</param> /// <param name="variable">The environment variable to modify.</param> /// <param name="value">The new value to use for the manipulation.</param> protected void AddPath(PathType pathType, string variable, string value) { string key = $"{pathType.ToString()}_{variable}"; if (!pathInfos.TryGetValue(key, out var info)) { info = new PathInfo(FullName, pathType, variable, new List<string>() { value }); } else { if (pathType == PathType.SET) info.Values[0] = value; else info.Values.Add(value); } pathInfos[key] = info; } #endregion } }
44.715054
166
0.620055
[ "MIT" ]
MarcusWalther/EnvironmentModuleCoreSrc
EnvironmentModuleCore/EnvironmentModule.cs
8,319
C#
using myoddweb.directorywatcher.interfaces; namespace myoddweb.directorywatcher.utils.Helper { internal class Statistics : IStatistics { /// <inheritdoc /> public long Id { get; } /// <inheritdoc /> public double ElapsedTime { get; } /// <inheritdoc /> public long NumberOfEvents { get; } public Statistics( long id, double elapsedTime, long numberOfEvents) { Id = id; ElapsedTime = elapsedTime; NumberOfEvents = numberOfEvents; } } }
20.833333
72
0.652
[ "MIT" ]
FFMG/myoddweb.directorywatcher
src/myoddweb.directorywatcher/utils/Helper/Statistics.cs
502
C#
namespace EA.Iws.Requests.Movement { using System; using Core.Authorization; using Core.Authorization.Permissions; using Core.Documents; using Prsd.Core.Mediator; [RequestAuthorization(ExportMovementPermissions.CanReadExportMovements)] public class GenerateMovementDocuments : IRequest<FileData> { public Guid[] MovementIds { get; private set; } public GenerateMovementDocuments(Guid[] movementIds) { MovementIds = movementIds; } } }
25.85
76
0.688588
[ "Unlicense" ]
DEFRA/prsd-iws
src/EA.Iws.Requests/Movement/GenerateMovementDocuments.cs
519
C#
using System; using System.IO.Ports; using System.Text; using System.Windows; using System.Diagnostics; using Newtonsoft.Json; using System.Windows.Threading; using System.Windows.Controls.Primitives; using System.Threading; using System.Dynamic; using System.Collections.ObjectModel; using System.Windows.Controls; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows.Media; using System.Linq; using System.Reflection; using OxyPlot; using OxyPlot.Series; using OxyPlot.Axes; using NDesk.Options; using Spiked3; namespace pilot_test { public partial class MainWindow { public void CurrentTestX(object sender, RoutedEventArgs e) { //Pilot = Pilot.Factory("192.168.42.1"); //Pilot = Pilot.Factory("127.0.0.1"); Pilot = Pilot.Factory("com3"); Pilot.OnPilotReceive += Pilot_OnReceive; Pilot.Send(new { Cmd = "SRVO", Value = 10 }); System.Threading.Thread.Sleep(500); Pilot.Send(new { Cmd = "SRVO", Value = 90 }); System.Threading.Thread.Sleep(500); Pilot.Send(new { Cmd = "SRVO", Value = 170 }); System.Threading.Thread.Sleep(500); Pilot.Send(new { Cmd = "SRVO", Value = 90 }); } [UiButton("NavPlanTest")] public void CurrentTest(object sender, RoutedEventArgs e) { try { Pilot = Pilot.Factory("192.168.42.1"); //Pilot = Pilot.Factory("127.0.0.1"); //Pilot = Pilot.Factory("com15"); Pilot.OnPilotReceive += Pilot_OnReceive; Pilot.Send(new { Cmd = "CONFIG", TPM = 353, MMX = 450, StrRv = -1 }); Pilot.Send(new { Cmd = "CONFIG", M1 = new int[] { 1, -1 }, M2 = new int[] { -1, 1 } }); Pilot.Send(new { Cmd = "CONFIG", HPID = new float[] { 75f, .8f, .04f } }); Pilot.Send(new { Cmd = "RESET" }); Pilot.Send(new { Cmd = "ESC", Value = 1 }); Pilot.Send(new { Cmd = "MOV", Dist = 1, Pwr = 40 }); Pilot.waitForEvent(); Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate { })); // doEvents //var hdgTo0 = 180; float hdgTo0 = (float)(Math.Atan2(X, -Y) * 180 / Math.PI); Pilot.Send(new { Cmd = "ROT", Hdg = hdgTo0 }); Pilot.waitForEvent(); Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate { })); // doEvents float distTo0 = (float)(Math.Sqrt(X * X + Y * Y)); Pilot.Send(new { Cmd = "MOV", Dist = distTo0, Hdg = hdgTo0, Pwr = 40.0F }); Pilot.waitForEvent(); Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate { })); // doEvents Pilot.Send(new { Cmd = "ROT", Hdg = 0.0 }); Pilot.waitForEvent(); Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate { })); // doEvents Pilot.Send(new { Cmd = "ESC", Value = 0 }); } catch (TimeoutException) { Trace.WriteLine("Timeout waiting for event"); Pilot.Send(new { Cmd = "ESC", Value = 0 }); Pilot.Send(new { Cmd = "MOV", M1 = 0, M2 = 0 }); } } } }
38.767442
125
0.558788
[ "MIT" ]
spiked3/pilot_test
pilot_test/CurrentTest.cs
3,334
C#
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoadRO.Business.ERCLevel { /// <summary> /// D03Level11ReChild (read only object).<br/> /// This is a generated base class of <see cref="D03Level11ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="D02Level1"/> collection. /// </remarks> [Serializable] public partial class D03Level11ReChild : ReadOnlyBase<D03Level11ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_Child_Name, "Level_1_1 Child Name"); /// <summary> /// Gets the Level_1_1 Child Name. /// </summary> /// <value>The Level_1_1 Child Name.</value> public string Level_1_1_Child_Name { get { return GetProperty(Level_1_1_Child_NameProperty); } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="D03Level11ReChild"/> object, based on given parameters. /// </summary> /// <param name="cParentID2">The CParentID2 parameter of the D03Level11ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="D03Level11ReChild"/> object.</returns> internal static D03Level11ReChild GetD03Level11ReChild(int cParentID2) { return DataPortal.FetchChild<D03Level11ReChild>(cParentID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="D03Level11ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private D03Level11ReChild() { // Prevent direct creation } #endregion #region Data Access /// <summary> /// Loads a <see cref="D03Level11ReChild"/> object from the database, based on given criteria. /// </summary> /// <param name="cParentID2">The CParent ID2.</param> protected void Child_Fetch(int cParentID2) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetD03Level11ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@CParentID2", cParentID2).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, cParentID2); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } BusinessRules.CheckRules(); } } /// <summary> /// Loads a <see cref="D03Level11ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_Child_NameProperty, dr.GetString("Level_1_1_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } #endregion #region Pseudo Events /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); #endregion } }
34.044776
162
0.564226
[ "MIT" ]
CslaGenFork/CslaGenFork
tags/DeepLoad sample v.1.0.0/SelfLoadRO.Business/ERCLevel/D03Level11ReChild.Designer.cs
4,562
C#
using DepthChartManager.Helpers; using System; namespace DepthChartManager.Domain { public class Player { public Player(League league, Team team, string name) { Contract.Requires<Exception>(league != null, Resource.LeagueNameIsInvalid); Contract.Requires<Exception>(team != null, Resource.TeamNameIsInvalid); Contract.Requires<Exception>(!string.IsNullOrWhiteSpace(name), Resource.PlayerNameIsInvalid); Id = Guid.NewGuid(); League = league; Team = team; Name = name; } public Guid Id { get; } public League League { get; } public Team Team { get; } public string Name { get; } } }
26.392857
105
0.600812
[ "MIT" ]
stackpond/depth-chart-manager
DepthChartManager.Domain/Player.cs
741
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Solid.Lsp; namespace Solid.Lsp { public class ClienteOuro: Cliente { public override double Disconto() { return ValorTotal - 100; } } }
17.111111
41
0.652597
[ "MIT" ]
CasaDoCodigoORG/Solid
2-Lsp/ClienteOuro.cs
310
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Threading.Tasks; using DynamicData.Annotations; using DynamicData.Binding; using DynamicData.Cache.Internal; using DynamicData.Kernel; using DynamicData.List.Internal; using DynamicData.List.Linq; // ReSharper disable once CheckNamespace namespace DynamicData { /// <summary> /// Extensions for ObservableList /// </summary> public static class ObservableListEx { #region Populate change set from standard rx observable /// <summary> /// Converts the observable to an observable changeset. /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="scheduler">The scheduler (only used for time expiry).</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source /// or /// keySelector</exception> public static IObservable<IChangeSet<T>> ToObservableChangeSet<T>(this IObservable<T> source, IScheduler scheduler = null) { if (source == null) throw new ArgumentNullException(nameof(source)); return ToObservableChangeSet(source, null, -1, scheduler); } /// <summary> /// Converts the observable to an observable changeset, allowing time expiry to be specified /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="expireAfter">Specify on a per object level the maximum time before an object expires from a cache</param> /// <param name="scheduler">The scheduler (only used for time expiry).</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source /// or /// keySelector</exception> public static IObservable<IChangeSet<T>> ToObservableChangeSet<T>(this IObservable<T> source, Func<T, TimeSpan?> expireAfter, IScheduler scheduler = null) { if (source == null) throw new ArgumentNullException(nameof(source)); if (expireAfter == null) throw new ArgumentNullException(nameof(expireAfter)); return ToObservableChangeSet(source, expireAfter, -1, scheduler); } /// <summary> /// Converts the observable to an observable changeset, with a specified limit of how large the list can be. /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="limitSizeTo">Remove the oldest items when the size has reached this limit</param> /// <param name="scheduler">The scheduler (only used for time expiry).</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source /// or /// keySelector</exception> public static IObservable<IChangeSet<T>> ToObservableChangeSet<T>(this IObservable<T> source, int limitSizeTo, IScheduler scheduler = null) { if (source == null) throw new ArgumentNullException(nameof(source)); return ToObservableChangeSet(source, null, limitSizeTo, scheduler); } /// <summary> /// Converts the observable to an observable changeset, allowing size and time limit to be specified /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="expireAfter">Specify on a per object level the maximum time before an object expires from a cache</param> /// <param name="limitSizeTo">Remove the oldest items when the size has reached this limit</param> /// <param name="scheduler">The scheduler (only used for time expiry).</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source /// or /// keySelector</exception> public static IObservable<IChangeSet<T>> ToObservableChangeSet<T>(this IObservable<T> source, Func<T, TimeSpan?> expireAfter, int limitSizeTo, IScheduler scheduler = null) { if (source == null) throw new ArgumentNullException(nameof(source)); return new ToObservableChangeSet<T>(source, expireAfter, limitSizeTo, scheduler).Run(); } /// <summary> /// Converts the observable to an observable changeset. /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="scheduler">The scheduler (only used for time expiry).</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source /// or /// keySelector</exception> public static IObservable<IChangeSet<T>> ToObservableChangeSet<T>(this IObservable<IEnumerable<T>> source, IScheduler scheduler = null) { return ToObservableChangeSet<T>(source, null, -1, scheduler); } /// <summary> /// Converts the observable to an observable changeset, allowing size and time limit to be specified /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="limitSizeTo">Remove the oldest items when the size has reached this limit</param> /// <param name="scheduler">The scheduler (only used for time expiry).</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source /// or /// keySelector</exception> public static IObservable<IChangeSet<T>> ToObservableChangeSet<T>(this IObservable<IEnumerable<T>> source, int limitSizeTo, IScheduler scheduler = null) { return ToObservableChangeSet<T>(source, null, limitSizeTo, scheduler); } /// <summary> /// Converts the observable to an observable changeset, allowing size to be specified /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="expireAfter">Specify on a per object level the maximum time before an object expires from a cache</param> /// <param name="scheduler">The scheduler (only used for time expiry).</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source /// or /// keySelector</exception> public static IObservable<IChangeSet<T>> ToObservableChangeSet<T>(this IObservable<IEnumerable<T>> source, Func<T, TimeSpan?> expireAfter, IScheduler scheduler = null) { return ToObservableChangeSet(source, expireAfter, 0, scheduler); } /// <summary> /// Converts the observable to an observable changeset, allowing size and time limit to be specified /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="expireAfter">Specify on a per object level the maximum time before an object expires from a cache</param> /// <param name="limitSizeTo">Remove the oldest items when the size has reached this limit</param> /// <param name="scheduler">The scheduler (only used for time expiry).</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source /// or /// keySelector</exception> public static IObservable<IChangeSet<T>> ToObservableChangeSet<T>(this IObservable<IEnumerable<T>> source, Func<T, TimeSpan?> expireAfter, int limitSizeTo, IScheduler scheduler = null) { if (source == null) throw new ArgumentNullException(nameof(source)); return new ToObservableChangeSet<T>(source, expireAfter, limitSizeTo, scheduler).Run(); } #endregion #region Auto Refresh /// <summary> /// Automatically refresh downstream operators when any property changes. /// </summary> /// <param name="source">The source observable</param> /// <param name="changeSetBuffer">Batch up changes by specifying the buffer. This greatly increases performance when many elements have sucessive property changes</param> /// <param name="propertyChangeThrottle">When observing on multiple property changes, apply a throttle to prevent excessive refesh invocations</param> /// <param name="scheduler">The scheduler</param> /// <returns>An observable change set with additional refresh changes</returns> public static IObservable<IChangeSet<TObject>> AutoRefresh<TObject>(this IObservable<IChangeSet<TObject>> source, TimeSpan? changeSetBuffer = null, TimeSpan? propertyChangeThrottle = null, IScheduler scheduler = null) where TObject : INotifyPropertyChanged { if (source == null) throw new ArgumentNullException(nameof(source)); return source.AutoRefreshOnObservable(t => { if (propertyChangeThrottle == null) return t.WhenAnyPropertyChanged(); return t.WhenAnyPropertyChanged() .Throttle(propertyChangeThrottle.Value, scheduler ?? Scheduler.Default); }, changeSetBuffer, scheduler); } /// <summary> /// Automatically refresh downstream operators when properties change. /// </summary> /// <param name="source">The source observable</param> /// <param name="propertyAccessor">Specify a property to observe changes. When it changes a Refresh is invoked</param> /// <param name="changeSetBuffer">Batch up changes by specifying the buffer. This greatly increases performance when many elements have sucessive property changes</param> /// <param name="propertyChangeThrottle">When observing on multiple property changes, apply a throttle to prevent excessive refesh invocations</param> /// <param name="scheduler">The scheduler</param> /// <returns>An observable change set with additional refresh changes</returns> public static IObservable<IChangeSet<TObject>> AutoRefresh<TObject, TProperty>(this IObservable<IChangeSet<TObject>> source, Expression<Func<TObject, TProperty>> propertyAccessor, TimeSpan? changeSetBuffer = null, TimeSpan? propertyChangeThrottle = null, IScheduler scheduler = null) where TObject : INotifyPropertyChanged { if (source == null) throw new ArgumentNullException(nameof(source)); if (propertyAccessor == null) throw new ArgumentNullException(nameof(propertyAccessor)); return source.AutoRefreshOnObservable(t => { if (propertyChangeThrottle == null) return t.WhenPropertyChanged(propertyAccessor, false); return t.WhenPropertyChanged(propertyAccessor,false) .Throttle(propertyChangeThrottle.Value, scheduler ?? Scheduler.Default); }, changeSetBuffer, scheduler); } /// <summary> /// Automatically refresh downstream operator. The refresh is triggered when the observable receives a notification /// </summary> /// <param name="source">The source observable change set</param> /// <param name="reevaluator">An observable which acts on items within the collection and produces a value when the item should be refreshed</param> /// <param name="changeSetBuffer">Batch up changes by specifying the buffer. This greatly increases performance when many elements require a refresh</param> /// <param name="scheduler">The scheduler</param> /// <returns>An observable change set with additional refresh changes</returns> public static IObservable<IChangeSet<TObject>> AutoRefreshOnObservable<TObject, TAny>(this IObservable<IChangeSet<TObject>> source, Func<TObject, IObservable<TAny>> reevaluator, TimeSpan? changeSetBuffer = null, IScheduler scheduler = null) { if (source == null) throw new ArgumentNullException(nameof(source)); if (reevaluator == null) throw new ArgumentNullException(nameof(reevaluator)); return new AutoRefresh<TObject, TAny>(source, reevaluator, changeSetBuffer, scheduler).Run(); } /// <summary> /// Supress refresh notifications /// </summary> /// <param name="source">The source observable change set</param> /// <returns></returns> public static IObservable<IChangeSet<T>> SupressRefresh<T>(this IObservable<IChangeSet<T>> source) { return source.WhereReasonsAreNot(ListChangeReason.Refresh); } #endregion #region Conversion /// <summary> /// Removes the index from all changes. /// /// NB: This operator has been introduced as a temporary fix for creating an Or operator using merge many. /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> public static IObservable<IChangeSet<T>> RemoveIndex<T>([NotNull] this IObservable<IChangeSet<T>> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Select(changes => new ChangeSet<T>(changes.YieldWithoutIndex())); } /// <summary> /// Adds a key to the change set result which enables all observable cache features of dynamic data /// </summary> /// <remarks> /// All indexed changes are dropped i.e. sorting is not supported by this function /// </remarks> /// <typeparam name="TObject">The type of object.</typeparam> /// <typeparam name="TKey">The type of key.</typeparam> /// <param name="source">The source.</param> /// <param name="keySelector">The key selector.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// </exception> public static IObservable<IChangeSet<TObject, TKey>> AddKey<TObject, TKey>( [NotNull] this IObservable<IChangeSet<TObject>> source, [NotNull] Func<TObject, TKey> keySelector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); return source.Select(changes => new ChangeSet<TObject, TKey>(new AddKeyEnumerator<TObject, TKey>(changes, keySelector))); } /// <summary> /// Convert the object using the sepcified conversion function. /// /// This is a lighter equivalent of Transform and is designed to be used with non-disposable objects /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <typeparam name="TDestination">The type of the destination.</typeparam> /// <param name="source">The source.</param> /// <param name="conversionFactory">The conversion factory.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// </exception> [Obsolete("Prefer Cast as it is does the same thing but is semantically correct")] public static IObservable<IChangeSet<TDestination>> Convert<TObject, TDestination>( [NotNull] this IObservable<IChangeSet<TObject>> source, [NotNull] Func<TObject, TDestination> conversionFactory) { if (source == null) throw new ArgumentNullException(nameof(source)); if (conversionFactory == null) throw new ArgumentNullException(nameof(conversionFactory)); return source.Select(changes => changes.Transform(conversionFactory)); } /// <summary> /// Cast the underlying type of an object. Use before a Cast function /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <returns></returns> public static IObservable<IChangeSet<object>> CastToObject<T>(this IObservable<IChangeSet<T>> source) { return source.Select(changes => { var items = changes.Transform(t => (object)t); return new ChangeSet<object>(items); }); } /// <summary> /// Cast the changes to another form /// </summary> /// <typeparam name="TDestination">The type of the destination.</typeparam> /// <param name="source">The source.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// </exception> public static IObservable<IChangeSet<TDestination>> Cast<TDestination>([NotNull] this IObservable<IChangeSet<object>> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Select(changes => changes.Transform(t=>(TDestination)t)); } /// <summary> /// Cast the changes to another form /// /// Alas, I had to add the converter due to type inference issues. The converter can be avoided by CastToObject() first /// </summary> /// <typeparam name="TSource">The type of the object.</typeparam> /// <typeparam name="TDestination">The type of the destination.</typeparam> /// <param name="source">The source.</param> /// <param name="conversionFactory">The conversion factory.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// </exception> public static IObservable<IChangeSet<TDestination>> Cast<TSource, TDestination>([NotNull] this IObservable<IChangeSet<TSource>> source, [NotNull] Func<TSource, TDestination> conversionFactory) { if (source == null) throw new ArgumentNullException(nameof(source)); if (conversionFactory == null) throw new ArgumentNullException(nameof(conversionFactory)); return source.Select(changes => changes.Transform(conversionFactory)); } #endregion #region Binding /// <summary> /// Binds a clone of the observable changeset to the target observable collection /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="targetCollection">The target collection.</param> /// <param name="resetThreshold">The reset threshold.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// source /// or /// targetCollection /// </exception> public static IObservable<IChangeSet<T>> Bind<T>([NotNull] this IObservable<IChangeSet<T>> source, [NotNull] IObservableCollection<T> targetCollection, int resetThreshold = 25) { if (source == null) throw new ArgumentNullException(nameof(source)); if (targetCollection == null) throw new ArgumentNullException(nameof(targetCollection)); var adaptor = new ObservableCollectionAdaptor<T>(targetCollection, resetThreshold); return source.Adapt(adaptor); } /// <summary> /// Creates a binding to a readonly observable collection which is specified as an 'out' parameter /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="readOnlyObservableCollection">The resulting read only observable collection.</param> /// <param name="resetThreshold">The reset threshold.</param> /// <returns>A continuation of the source stream</returns> /// <exception cref="System.ArgumentNullException"> /// </exception> public static IObservable<IChangeSet<T>> Bind<T>([NotNull] this IObservable<IChangeSet<T>> source, out ReadOnlyObservableCollection<T> readOnlyObservableCollection, int resetThreshold = 25) { if (source == null) throw new ArgumentNullException(nameof(source)); var target = new ObservableCollectionExtended<T>(); var result = new ReadOnlyObservableCollection<T>(target); var adaptor = new ObservableCollectionAdaptor<T>(target, resetThreshold); readOnlyObservableCollection = result; return source.Adapt(adaptor); } #if SUPPORTS_BINDINGLIST /// <summary> /// Binds a clone of the observable changeset to the target observable collection /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="bindingList">The target binding list</param> /// <param name="resetThreshold">The reset threshold.</param> /// <exception cref="System.ArgumentNullException"> /// source /// or /// targetCollection /// </exception> public static IObservable<IChangeSet<T>> Bind<T>([NotNull] this IObservable<IChangeSet<T>> source, [NotNull] BindingList<T> bindingList, int resetThreshold = 25) { if (source == null) throw new ArgumentNullException(nameof(source)); if (bindingList == null) throw new ArgumentNullException(nameof(bindingList)); return source.Adapt(new BindingListAdaptor<T>(bindingList, resetThreshold)); } #endif /// <summary> /// Injects a side effect into a changeset observable /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="adaptor">The adaptor.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// source /// or /// adaptor /// </exception> public static IObservable<IChangeSet<T>> Adapt<T>([NotNull] this IObservable<IChangeSet<T>> source, [NotNull] IChangeSetAdaptor<T> adaptor) { if (source == null) throw new ArgumentNullException(nameof(source)); if (adaptor == null) throw new ArgumentNullException(nameof(adaptor)); return Observable.Create<IChangeSet<T>>(observer => { var locker = new object(); return source .Synchronize(locker) .Select(changes => { adaptor.Adapt(changes); return changes; }).SubscribeSafe(observer); }); } #endregion #region Populate into an observable list /// <summary> /// list. /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="destination">The destination.</param> /// <returns></returns> /// <exception cref="ArgumentNullException"> /// source /// or /// destination /// </exception> /// <exception cref="System.ArgumentNullException">source /// or /// destination</exception> public static IDisposable PopulateInto<T>([NotNull] this IObservable<IChangeSet<T>> source, [NotNull] ISourceList<T> destination) { if (source == null) throw new ArgumentNullException(nameof(source)); if (destination == null) throw new ArgumentNullException(nameof(destination)); return source.Subscribe(changes => destination.Edit(updater => updater.Clone(changes))); } /// <summary> /// Converts the source list to an read only observable list /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source</exception> public static IObservableList<T> AsObservableList<T>([NotNull] this ISourceList<T> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return new AnonymousObservableList<T>(source); } /// <summary> /// Converts the source observable to an read only observable list /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source</exception> public static IObservableList<T> AsObservableList<T>([NotNull] this IObservable<IChangeSet<T>> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return new AnonymousObservableList<T>(source); } /// <summary> /// List equivalent to Publish().RefCount(). The source is cached so long as there is at least 1 subscriber. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> public static IObservable<IChangeSet<T>> RefCount<T>([NotNull] this IObservable<IChangeSet<T>> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return new RefCount<T>(source).Run(); } #endregion #region Core List Operators /// <summary> /// Filters the source using the specified valueSelector /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="predicate">The valueSelector.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source</exception> public static IObservable<IChangeSet<T>> Filter<T>(this IObservable<IChangeSet<T>> source, Func<T, bool> predicate) { if (source == null) throw new ArgumentNullException(nameof(source)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); return new Filter<T>(source, predicate).Run(); } /// <summary> /// Filters source using the specified filter observable predicate. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="predicate"></param> /// <param name="filterPolicy">Should the filter clear and replace, or calculate a diff-set</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source /// or /// filterController</exception> public static IObservable<IChangeSet<T>> Filter<T>([NotNull] this IObservable<IChangeSet<T>> source, [NotNull] IObservable<Func<T, bool>> predicate, ListFilterPolicy filterPolicy = ListFilterPolicy.CalculateDiff) { if (source == null) throw new ArgumentNullException(nameof(source)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); return new Filter<T>(source, predicate, filterPolicy).Run(); } /// <summary> /// Filters source on the specified property using the specified predicate. /// /// The filter will automatically reapply when a property changes /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <typeparam name="TProperty">The type of the property.</typeparam> /// <param name="source">The source.</param> /// <param name="propertySelector">The property selector. When the property changes the filter specified will be re-evaluated</param> /// <param name="predicate">A predicate based on the object which contains the changed property</param> /// <param name="propertyChangedThrottle">The property changed throttle.</param> /// <param name="scheduler">The scheduler used when throttling</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// </exception> [Obsolete("Use AutoRefresh(), followed by Filter() instead")] public static IObservable<IChangeSet<TObject>> FilterOnProperty<TObject, TProperty>(this IObservable<IChangeSet<TObject>> source, Expression<Func<TObject, TProperty>> propertySelector, Func<TObject, bool> predicate, TimeSpan? propertyChangedThrottle = null, IScheduler scheduler = null) where TObject : INotifyPropertyChanged { if (source == null) throw new ArgumentNullException(nameof(source)); if (propertySelector == null) throw new ArgumentNullException(nameof(propertySelector)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); return new FilterOnProperty<TObject, TProperty>(source, propertySelector, predicate, propertyChangedThrottle, scheduler).Run(); } /// <summary> /// Filters source on the specified observable property using the specified predicate. /// /// The filter will automatically reapply when a property changes /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="objectFilterObservable">The filter property selector. When the observable changes the filter will be re-evaluated</param> /// <param name="propertyChangedThrottle">The property changed throttle.</param> /// <param name="scheduler">The scheduler used when throttling</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// </exception> public static IObservable<IChangeSet<TObject>> FilterOnObservable<TObject>(this IObservable<IChangeSet<TObject>> source, Func<TObject, IObservable<bool>> objectFilterObservable, TimeSpan? propertyChangedThrottle = null, IScheduler scheduler = null) { if (source == null) throw new ArgumentNullException(nameof(source)); return new FilterOnObservable<TObject>(source, objectFilterObservable, propertyChangedThrottle, scheduler).Run(); } /// <summary> /// Reverse sort of the changset /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// source /// or /// comparer /// </exception> public static IObservable<IChangeSet<T>> Reverse<T>(this IObservable<IChangeSet<T>> source) { var reverser = new Reverser<T>(); if (source == null) throw new ArgumentNullException(nameof(source)); return source.Select(changes => new ChangeSet<T>(reverser.Reverse(changes))); } /// <summary> /// Projects each update item to a new form using the specified transform function /// </summary> /// <typeparam name="TSource">The type of the source.</typeparam> /// <typeparam name="TDestination">The type of the destination.</typeparam> /// <param name="source">The source.</param> /// <param name="transformFactory">The transform factory.</param> /// <param name="transformOnRefresh">Should a new transform be applied when a refresh event is received</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// source /// or /// valueSelector /// </exception> public static IObservable<IChangeSet<TDestination>> Transform<TSource, TDestination>(this IObservable<IChangeSet<TSource>> source, Func<TSource, TDestination> transformFactory, bool transformOnRefresh = false) { if (source == null) throw new ArgumentNullException(nameof(source)); if (transformFactory == null) throw new ArgumentNullException(nameof(transformFactory)); return source.Transform<TSource, TDestination>((t, previous, idx) => transformFactory(t), transformOnRefresh); } /// <summary> /// Projects each update item to a new form using the specified transform function /// </summary> /// <typeparam name="TSource">The type of the source.</typeparam> /// <typeparam name="TDestination">The type of the destination.</typeparam> /// <param name="source">The source.</param> /// <param name="transformFactory">The transform function</param> /// <param name="transformOnRefresh">Should a new transform be applied when a refresh event is received</param> /// <returns>A an observable changeset of the transformed object</returns> /// <exception cref="System.ArgumentNullException"> /// source /// or /// valueSelector /// </exception> public static IObservable<IChangeSet<TDestination>> Transform<TSource, TDestination>(this IObservable<IChangeSet<TSource>> source, Func<TSource, int, TDestination> transformFactory, bool transformOnRefresh = false) { if (source == null) throw new ArgumentNullException(nameof(source)); if (transformFactory == null) throw new ArgumentNullException(nameof(transformFactory)); return source.Transform<TSource, TDestination>((t, previous, idx) => transformFactory(t,idx),transformOnRefresh); } /// <summary> /// Projects each update item to a new form using the specified transform function. /// /// *** Annoyingly when using this overload you will have to explicitly specify the generic type arguments as type inference fails /// </summary> /// <typeparam name="TSource">The type of the source.</typeparam> /// <typeparam name="TDestination">The type of the destination.</typeparam> /// <param name="source">The source.</param> /// <param name="transformFactory">The transform function</param> /// <param name="transformOnRefresh">Should a new transform be applied when a refresh event is received</param> /// <returns>A an observable changeset of the transformed object</returns> /// <exception cref="System.ArgumentNullException"> /// source /// or /// valueSelector /// </exception> public static IObservable<IChangeSet<TDestination>> Transform<TSource, TDestination>(this IObservable<IChangeSet<TSource>> source, Func<TSource, Optional<TDestination>, TDestination> transformFactory, bool transformOnRefresh = false) { if (source == null) throw new ArgumentNullException(nameof(source)); if (transformFactory == null) throw new ArgumentNullException(nameof(transformFactory)); return source.Transform<TSource, TDestination>((t, previous, idx) => transformFactory(t, previous), transformOnRefresh); } /// <summary> /// Projects each update item to a new form using the specified transform function /// /// *** Annoyingly when using this overload you will have to explicy specify the generic type arguments as type inference fails /// </summary> /// <typeparam name="TSource">The type of the source.</typeparam> /// <typeparam name="TDestination">The type of the destination.</typeparam> /// <param name="source">The source.</param> /// <param name="transformFactory">The transform factory.</param> /// <param name="transformOnRefresh">Should a new transform be applied when a refresh event is received</param> /// <returns>A an observable changeset of the transformed object</returns> /// <exception cref="System.ArgumentNullException"> /// source /// or /// valueSelector /// </exception> public static IObservable<IChangeSet<TDestination>> Transform<TSource, TDestination>(this IObservable<IChangeSet<TSource>> source, Func<TSource, Optional<TDestination>, int, TDestination> transformFactory, bool transformOnRefresh = false) { if (source == null) throw new ArgumentNullException(nameof(source)); if (transformFactory == null) throw new ArgumentNullException(nameof(transformFactory)); return new Transformer<TSource, TDestination>(source, transformFactory, transformOnRefresh).Run(); } /// <summary> /// Projects each update item to a new form using the specified transform function /// </summary> /// <typeparam name="TSource">The type of the source.</typeparam> /// <typeparam name="TDestination">The type of the destination.</typeparam> /// <param name="source">The source.</param> /// <param name="transformFactory">The transform factory.</param> /// <returns>A an observable changeset of the transformed object</returns> /// <exception cref="System.ArgumentNullException"> /// source /// or /// valueSelector /// </exception> public static IObservable<IChangeSet<TDestination>> TransformAsync<TSource, TDestination>( this IObservable<IChangeSet<TSource>> source, Func<TSource, Task<TDestination>> transformFactory) { if (source == null) throw new ArgumentNullException(nameof(source)); if (transformFactory == null) throw new ArgumentNullException(nameof(transformFactory)); return new TransformAsync<TSource, TDestination>(source, transformFactory).Run(); } /// <summary> /// Equivalent to a select many transform. To work, the key must individually identify each child. /// </summary> /// <typeparam name="TDestination">The type of the destination.</typeparam> /// <typeparam name="TSource">The type of the source.</typeparam> /// <param name="source">The source.</param> /// <param name="manyselector">The manyselector.</param> /// <param name="equalityComparer">Used when an item has been replaced to determine whether child items are the same as previous children</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// source /// or /// manyselector /// </exception> public static IObservable<IChangeSet<TDestination>> TransformMany<TDestination, TSource>( [NotNull] this IObservable<IChangeSet<TSource>> source, [NotNull] Func<TSource, IEnumerable<TDestination>> manyselector, IEqualityComparer<TDestination> equalityComparer = null) { if (source == null) throw new ArgumentNullException(nameof(source)); if (manyselector == null) throw new ArgumentNullException(nameof(manyselector)); return new TransformMany<TSource, TDestination>(source, manyselector, equalityComparer).Run(); } /// <summary> /// Flatten the nested observable collection, and observe subsequentl observable collection changes /// </summary> /// <typeparam name="TDestination">The type of the destination.</typeparam> /// <typeparam name="TSource">The type of the source.</typeparam> /// <param name="source">The source.</param> /// <param name="manyselector">The manyselector.</param> /// <param name="equalityComparer">Used when an item has been replaced to determine whether child items are the same as previous children</param> public static IObservable<IChangeSet<TDestination>> TransformMany<TDestination, TSource>( this IObservable<IChangeSet<TSource>> source, Func<TSource, ObservableCollection<TDestination>> manyselector, IEqualityComparer<TDestination> equalityComparer = null) { return new TransformMany<TSource, TDestination>(source,manyselector, equalityComparer).Run(); } /// <summary> /// Flatten the nested observable collection, and observe subsequentl observable collection changes /// </summary> /// <typeparam name="TDestination">The type of the destination.</typeparam> /// <typeparam name="TSource">The type of the source.</typeparam> /// <param name="source">The source.</param> /// <param name="manyselector">The manyselector.</param> /// <param name="equalityComparer">Used when an item has been replaced to determine whether child items are the same as previous children</param> public static IObservable<IChangeSet<TDestination>> TransformMany<TDestination, TSource>(this IObservable<IChangeSet<TSource>> source, Func<TSource, ReadOnlyObservableCollection<TDestination>> manyselector, IEqualityComparer<TDestination> equalityComparer = null) { return new TransformMany<TSource, TDestination>(source, manyselector, equalityComparer).Run(); } /// <summary> /// Flatten the nested observable list, and observe subsequent observable collection changes /// </summary> /// <typeparam name="TDestination">The type of the destination.</typeparam> /// <typeparam name="TSource">The type of the source.</typeparam> /// <param name="source">The source.</param> /// <param name="manyselector">The manyselector.</param> /// <param name="equalityComparer">Used when an item has been replaced to determine whether child items are the same as previous children</param> public static IObservable<IChangeSet<TDestination>> TransformMany<TDestination, TSource>(this IObservable<IChangeSet<TSource>> source, Func<TSource, IObservableList<TDestination>> manyselector, IEqualityComparer<TDestination> equalityComparer = null) { return new TransformMany<TSource, TDestination>(source, manyselector, equalityComparer).Run(); } /// <summary> /// Selects distinct values from the source, using the specified value selector /// </summary> /// <typeparam name="TObject">The type of the source.</typeparam> /// <typeparam name="TValue">The type of the destination.</typeparam> /// <param name="source">The source.</param> /// <param name="valueSelector">The transform factory.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// source /// or /// valueSelector /// </exception> public static IObservable<IChangeSet<TValue>> DistinctValues<TObject, TValue>( this IObservable<IChangeSet<TObject>> source, Func<TObject, TValue> valueSelector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (valueSelector == null) throw new ArgumentNullException(nameof(valueSelector)); return new Distinct<TObject, TValue>(source, valueSelector).Run(); } /// <summary> /// Groups the source on the value returned by group selector factory. The groupings contains an inner observable list. /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <typeparam name="TGroup">The type of the group.</typeparam> /// <param name="source">The source.</param> /// <param name="groupSelector">The group selector.</param> /// <param name="regrouper">Force the grouping function to recalculate the group value. /// For example if you have a time based grouping with values like `Last Minute', 'Last Hour', 'Today' etc regrouper is used to refresh these groupings</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// source /// or /// groupSelector /// </exception> public static IObservable<IChangeSet<IGroup<TObject, TGroup>>> GroupOn<TObject, TGroup>( this IObservable<IChangeSet<TObject>> source, Func<TObject, TGroup> groupSelector, IObservable<Unit> regrouper = null) { if (source == null) throw new ArgumentNullException(nameof(source)); if (groupSelector == null) throw new ArgumentNullException(nameof(groupSelector)); return new GroupOn<TObject, TGroup>(source, groupSelector, regrouper).Run(); } /// <summary> /// Groups the source on the value returned by group selector factory. Each update produces immuatable grouping. /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <typeparam name="TGroupKey">The type of the group key.</typeparam> /// <param name="source">The source.</param> /// <param name="groupSelectorKey">The group selector key.</param> /// <param name="regrouper">Force the grouping function to recalculate the group value. /// For example if you have a time based grouping with values like `Last Minute', 'Last Hour', 'Today' etc regrouper is used to refresh these groupings</param> /// <returns></returns> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// source /// or /// groupSelectorKey /// </exception> public static IObservable<IChangeSet<List.IGrouping<TObject, TGroupKey>>> GroupWithImmutableState <TObject, TGroupKey>(this IObservable<IChangeSet<TObject>> source, Func<TObject, TGroupKey> groupSelectorKey, IObservable<Unit> regrouper = null) { if (source == null) throw new ArgumentNullException(nameof(source)); if (groupSelectorKey == null) throw new ArgumentNullException(nameof(groupSelectorKey)); return new GroupOnImmutable<TObject, TGroupKey>(source, groupSelectorKey, regrouper).Run(); } /// <summary> /// Groups the source using the property specified by the property selector. The resulting groupings contains an inner observable list. /// Groups are re-applied when the property value changed. /// When there are likely to be a large number of group property changes specify a throttle to improve performance /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <typeparam name="TGroup">The type of the group.</typeparam> /// <param name="source">The source.</param> /// <param name="propertySelector">The property selector used to group the items</param> /// <param name="propertyChangedThrottle">The property changed throttle.</param> /// <param name="scheduler">The scheduler.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// </exception> public static IObservable<IChangeSet<IGroup<TObject, TGroup>>> GroupOnProperty<TObject, TGroup>( this IObservable<IChangeSet<TObject>> source, Expression<Func<TObject, TGroup>> propertySelector, TimeSpan? propertyChangedThrottle = null, IScheduler scheduler = null) where TObject : INotifyPropertyChanged { if (source == null) throw new ArgumentNullException(nameof(source)); if (propertySelector == null) throw new ArgumentNullException(nameof(propertySelector)); return new GroupOnProperty<TObject, TGroup>(source, propertySelector, propertyChangedThrottle, scheduler).Run(); } /// <summary> /// Groups the source using the property specified by the property selector. The resulting groupings are immutable. /// Groups are re-applied when the property value changed. /// When there are likely to be a large number of group property changes specify a throttle to improve performance /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <typeparam name="TGroup">The type of the group.</typeparam> /// <param name="source">The source.</param> /// <param name="propertySelector">The property selector used to group the items</param> /// <param name="propertyChangedThrottle">The property changed throttle.</param> /// <param name="scheduler">The scheduler.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// </exception> public static IObservable<IChangeSet<List.IGrouping<TObject, TGroup>>> GroupOnPropertyWithImmutableState<TObject, TGroup>(this IObservable<IChangeSet<TObject>> source, Expression<Func<TObject, TGroup>> propertySelector, TimeSpan? propertyChangedThrottle = null, IScheduler scheduler = null) where TObject : INotifyPropertyChanged { if (source == null) throw new ArgumentNullException(nameof(source)); if (propertySelector == null) throw new ArgumentNullException(nameof(propertySelector)); return new GroupOnPropertyWithImmutableState<TObject, TGroup>(source, propertySelector, propertyChangedThrottle, scheduler).Run(); } /// <summary> /// Prevents an empty notification /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source</exception> public static IObservable<IChangeSet<T>> NotEmpty<T>(this IObservable<IChangeSet<T>> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Where(s => s.Count != 0); } /// <summary> /// Clones the target list as a side effect of the stream /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="target"></param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source</exception> public static IObservable<IChangeSet<T>> Clone<T>(this IObservable<IChangeSet<T>> source, IList<T> target) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Do(target.Clone); } #endregion #region Sort /// <summary> /// Sorts the sequence using the specified comparer. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="comparer">The comparer used for sorting</param> /// <param name="options">For improved performance, specify SortOptions.UseBinarySearch. This can only be used when the values which are sorted on are immutable</param> /// <param name="resetThreshold">Since sorting can be slow for large record sets, the reset threshold is used to force the list re-ordered </param> /// <param name="resort">OnNext of this observable causes data to resort. This is required when the value which is sorted on mutable</param> /// <param name="comparerChanged">An observable comparer used to change the comparer on which the sorted list i</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source /// or /// comparer</exception> public static IObservable<IChangeSet<T>> Sort<T>(this IObservable<IChangeSet<T>> source, IComparer<T> comparer, SortOptions options = SortOptions.None, IObservable<Unit> resort = null, IObservable<IComparer<T>> comparerChanged = null, int resetThreshold = 50) { if (source == null) throw new ArgumentNullException(nameof(source)); if (comparer == null) throw new ArgumentNullException(nameof(comparer)); return new Sort<T>(source, comparer, options, resort, comparerChanged, resetThreshold).Run(); } /// <summary> /// Sorts the sequence using the specified observable comparer. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="options">For improved performance, specify SortOptions.UseBinarySearch. This can only be used when the values which are sorted on are immutable</param> /// <param name="resetThreshold">Since sorting can be slow for large record sets, the reset threshold is used to force the list re-ordered </param> /// <param name="resort">OnNext of this observable causes data to resort. This is required when the value which is sorted on mutable</param> /// <param name="comparerChanged">An observable comparer used to change the comparer on which the sorted list i</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source /// or /// comparer</exception> public static IObservable<IChangeSet<T>> Sort<T>(this IObservable<IChangeSet<T>> source, IObservable<IComparer<T>> comparerChanged, SortOptions options = SortOptions.None, IObservable<Unit> resort = null, int resetThreshold = 50) { if (source == null) throw new ArgumentNullException(nameof(source)); if (comparerChanged == null) throw new ArgumentNullException(nameof(comparerChanged)); return new Sort<T>(source, null, options, resort, comparerChanged, resetThreshold).Run(); } #endregion #region Item operators /// <summary> /// Provides a call back for each item change. /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="action">The action.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// </exception> public static IObservable<IChangeSet<TObject>> ForEachChange<TObject>( [NotNull] this IObservable<IChangeSet<TObject>> source, [NotNull] Action<Change<TObject>> action) { if (source == null) throw new ArgumentNullException(nameof(source)); if (action == null) throw new ArgumentNullException(nameof(action)); return source.Do(changes => changes.ForEach(action)); } /// <summary> /// Provides a call back for each item change. /// /// Range changes are flattened, so there is only need to check for Add, Replace, Remove and Clear /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="action">The action.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// </exception> public static IObservable<IChangeSet<TObject>> ForEachItemChange<TObject>( [NotNull] this IObservable<IChangeSet<TObject>> source, [NotNull] Action<ItemChange<TObject>> action) { if (source == null) throw new ArgumentNullException(nameof(source)); if (action == null) throw new ArgumentNullException(nameof(action)); return source.Do(changes => changes.Flatten().ForEach(action)); } /// <summary> /// Dynamically merges the observable which is selected from each item in the stream, and unmerges the item /// when it is no longer part of the stream. /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <typeparam name="TDestination">The type of the destination.</typeparam> /// <param name="source">The source.</param> /// <param name="observableSelector">The observable selector.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source /// or /// observableSelector</exception> public static IObservable<TDestination> MergeMany<T, TDestination>( [NotNull] this IObservable<IChangeSet<T>> source, [NotNull] Func<T, IObservable<TDestination>> observableSelector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (observableSelector == null) throw new ArgumentNullException(nameof(observableSelector)); return new MergeMany<T, TDestination>(source, observableSelector).Run(); } /// <summary> /// Watches each item in the collection and notifies when any of them has changed /// </summary> /// <typeparam name="TObject"></typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="source">The source.</param> /// <param name="propertyAccessor">The property accessor.</param> /// <param name="notifyOnInitialValue">if set to <c>true</c> [notify on initial value].</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// </exception> public static IObservable<TValue> WhenValueChanged<TObject, TValue>( [NotNull] this IObservable<IChangeSet<TObject>> source, [NotNull] Expression<Func<TObject, TValue>> propertyAccessor, bool notifyOnInitialValue = true) where TObject : INotifyPropertyChanged { if (source == null) throw new ArgumentNullException(nameof(source)); if (propertyAccessor == null) throw new ArgumentNullException(nameof(propertyAccessor)); var factory = propertyAccessor.GetFactory(); return source.MergeMany(t => factory(t, notifyOnInitialValue).Select(pv=>pv.Value)); } /// <summary> /// Watches each item in the collection and notifies when any of them has changed /// </summary> /// <typeparam name="TObject"></typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="source">The source.</param> /// <param name="propertyAccessor">The property accessor.</param> /// <param name="notifyOnInitialValue">if set to <c>true</c> [notify on initial value].</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// </exception> public static IObservable<PropertyValue<TObject, TValue>> WhenPropertyChanged<TObject, TValue>( [NotNull] this IObservable<IChangeSet<TObject>> source, [NotNull] Expression<Func<TObject, TValue>> propertyAccessor, bool notifyOnInitialValue = true) where TObject : INotifyPropertyChanged { if (source == null) throw new ArgumentNullException(nameof(source)); if (propertyAccessor == null) throw new ArgumentNullException(nameof(propertyAccessor)); var factory = propertyAccessor.GetFactory(); return source.MergeMany(t => factory(t, notifyOnInitialValue)); } /// <summary> /// Watches each item in the collection and notifies when any of them has changed /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="propertiesToMonitor">specify properties to Monitor, or omit to monitor all property changes</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// </exception> public static IObservable<TObject> WhenAnyPropertyChanged<TObject>([NotNull] this IObservable<IChangeSet<TObject>> source, params string[] propertiesToMonitor) where TObject : INotifyPropertyChanged { if (source == null) throw new ArgumentNullException(nameof(source)); return source.MergeMany(t => t.WhenAnyPropertyChanged(propertiesToMonitor)); } /// <summary> /// Subscribes to each item when it is added to the stream and unsubcribes when it is removed. All items will be unsubscribed when the stream is disposed /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="subscriptionFactory">The subsription function</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source /// or /// subscriptionFactory</exception> /// <remarks> /// Subscribes to each item when it is added or updates and unsubcribes when it is removed /// </remarks> public static IObservable<IChangeSet<T>> SubscribeMany<T>(this IObservable<IChangeSet<T>> source, Func<T, IDisposable> subscriptionFactory) { if (source == null) throw new ArgumentNullException(nameof(source)); if (subscriptionFactory == null) throw new ArgumentNullException(nameof(subscriptionFactory)); return new SubscribeMany<T>(source, subscriptionFactory).Run(); } /// <summary> /// Disposes each item when no longer required. /// /// Individual items are disposed when removed or replaced. All items /// are disposed when the stream is disposed /// </summary> /// <remarks> /// </remarks> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <returns>A continuation of the original stream</returns> /// <exception cref="System.ArgumentNullException">source</exception> public static IObservable<IChangeSet<T>> DisposeMany<T>(this IObservable<IChangeSet<T>> source) { return source.OnItemRemoved(t => { var d = t as IDisposable; d?.Dispose(); }); } /// <summary> /// Callback for each item as and when it is being removed from the stream /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="removeAction">The remove action.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// source /// or /// removeAction /// </exception> public static IObservable<IChangeSet<T>> OnItemRemoved<T>(this IObservable<IChangeSet<T>> source, Action<T> removeAction) { if (source == null) throw new ArgumentNullException(nameof(source)); if (removeAction == null) throw new ArgumentNullException(nameof(removeAction)); return new OnBeingRemoved<T>(source, removeAction).Run(); } /// <summary> /// Callback for each item as and when it is being added to the stream /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="addAction">The add action.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> OnItemAdded<T>(this IObservable<IChangeSet<T>> source, Action<T> addAction) { if (source == null) throw new ArgumentNullException(nameof(source)); if (addAction == null) throw new ArgumentNullException(nameof(addAction)); return new OnBeingAdded<T>(source, addAction).Run(); } #endregion #region Reason filtering /// <summary> /// Includes changes for the specified reasons only /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="reasons">The reasons.</param> /// <returns></returns> /// <exception cref="System.ArgumentException">Must enter at least 1 reason</exception> public static IObservable<IChangeSet<T>> WhereReasonsAre<T>(this IObservable<IChangeSet<T>> source, params ListChangeReason[] reasons) { if (reasons.Length == 0) throw new ArgumentException("Must enter at least 1 reason", nameof(reasons)); var matches = new HashSet<ListChangeReason>(reasons); return source.Select(changes => { var filtered = changes.Where(change => matches.Contains(change.Reason)).YieldWithoutIndex(); return new ChangeSet<T>(filtered); }).NotEmpty(); } /// <summary> /// Excludes updates for the specified reasons /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="reasons">The reasons.</param> /// <returns></returns> /// <exception cref="System.ArgumentException">Must enter at least 1 reason</exception> public static IObservable<IChangeSet<T>> WhereReasonsAreNot<T>(this IObservable<IChangeSet<T>> source, params ListChangeReason[] reasons) { if (reasons.Length == 0) throw new ArgumentException("Must enter at least 1 reason", nameof(reasons)); var matches = new HashSet<ListChangeReason>(reasons); return source.Select(updates => { var filtered = updates.Where(u => !matches.Contains(u.Reason)).YieldWithoutIndex(); return new ChangeSet<T>(filtered); }).NotEmpty(); } #endregion #region Buffering /// <summary> /// Buffers changes for an intial period only. After the period has elapsed, not further buffering occurs. /// </summary> /// <param name="source">The source changeset</param> /// <param name="initalBuffer">The period to buffer, measure from the time that the first item arrives</param> /// <param name="scheduler">The scheduler to buffer on</param> public static IObservable<IChangeSet<TObject>> BufferInitial<TObject>(this IObservable<IChangeSet<TObject>> source, TimeSpan initalBuffer, IScheduler scheduler = null) { return source.DeferUntilLoaded().Publish(shared => { var initial = shared.Buffer(initalBuffer, scheduler ?? Scheduler.Default) .FlattenBufferResult() .Take(1); return initial.Concat(shared); }); } /// <summary> /// Convert the result of a buffer operation to a change set /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> FlattenBufferResult<T>(this IObservable<IList<IChangeSet<T>>> source) { return source .Where(x => x.Count != 0) .Select(updates => new ChangeSet<T>(updates.SelectMany(u => u))); } /// <summary> /// Batches the underlying updates if a pause signal (i.e when the buffer selector return true) has been received. /// When a resume signal has been received the batched updates will be fired. /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="pauseIfTrueSelector">When true, observable begins to buffer and when false, window closes and buffered result if notified</param> /// <param name="scheduler">The scheduler.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source</exception> public static IObservable<IChangeSet<T>> BufferIf<T>([NotNull] this IObservable<IChangeSet<T>> source, [NotNull] IObservable<bool> pauseIfTrueSelector, IScheduler scheduler = null) { return BufferIf(source, pauseIfTrueSelector, false, scheduler); } /// <summary> /// Batches the underlying updates if a pause signal (i.e when the buffer selector return true) has been received. /// When a resume signal has been received the batched updates will be fired. /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="pauseIfTrueSelector">When true, observable begins to buffer and when false, window closes and buffered result if notified</param> /// <param name="intialPauseState">if set to <c>true</c> [intial pause state].</param> /// <param name="scheduler">The scheduler.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source</exception> public static IObservable<IChangeSet<T>> BufferIf<T>([NotNull] this IObservable<IChangeSet<T>> source, [NotNull] IObservable<bool> pauseIfTrueSelector, bool intialPauseState = false, IScheduler scheduler = null) { if (source == null) throw new ArgumentNullException(nameof(source)); if (pauseIfTrueSelector == null) throw new ArgumentNullException(nameof(pauseIfTrueSelector)); return BufferIf(source, pauseIfTrueSelector, intialPauseState, null, scheduler); } /// <summary> /// Batches the underlying updates if a pause signal (i.e when the buffer selector return true) has been received. /// When a resume signal has been received the batched updates will be fired. /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="pauseIfTrueSelector">When true, observable begins to buffer and when false, window closes and buffered result if notified</param> /// <param name="timeOut">Specify a time to ensure the buffer window does not stay open for too long</param> /// <param name="scheduler">The scheduler.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source</exception> public static IObservable<IChangeSet<T>> BufferIf<T>(this IObservable<IChangeSet<T>> source, IObservable<bool> pauseIfTrueSelector, TimeSpan? timeOut = null, IScheduler scheduler = null) { return BufferIf(source, pauseIfTrueSelector, false, timeOut, scheduler); } /// <summary> /// Batches the underlying updates if a pause signal (i.e when the buffer selector return true) has been received. /// When a resume signal has been received the batched updates will be fired. /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="pauseIfTrueSelector">When true, observable begins to buffer and when false, window closes and buffered result if notified</param> /// <param name="intialPauseState">if set to <c>true</c> [intial pause state].</param> /// <param name="timeOut">Specify a time to ensure the buffer window does not stay open for too long</param> /// <param name="scheduler">The scheduler.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source</exception> public static IObservable<IChangeSet<T>> BufferIf<T>(this IObservable<IChangeSet<T>> source, IObservable<bool> pauseIfTrueSelector, bool intialPauseState = false, TimeSpan? timeOut = null, IScheduler scheduler = null) { if (source == null) throw new ArgumentNullException(nameof(source)); if (pauseIfTrueSelector == null) throw new ArgumentNullException(nameof(pauseIfTrueSelector)); return new BufferIf<T>(source, pauseIfTrueSelector, intialPauseState, timeOut, scheduler).Run(); } /// <summary> /// The latest copy of the cache is exposed for querying after each modification to the underlying data /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <typeparam name="TDestination">The type of the destination.</typeparam> /// <param name="source">The source.</param> /// <param name="resultSelector">The result selector.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// source /// or /// resultSelector /// </exception> public static IObservable<TDestination> QueryWhenChanged<TObject, TDestination>( this IObservable<IChangeSet<TObject>> source, Func<IReadOnlyCollection<TObject>, TDestination> resultSelector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); return source.QueryWhenChanged().Select(resultSelector); } /// <summary> /// The latest copy of the cache is exposed for querying i) after each modification to the underlying data ii) upon subscription /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source</exception> public static IObservable<IReadOnlyCollection<T>> QueryWhenChanged<T>([NotNull] this IObservable<IChangeSet<T>> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return new QueryWhenChanged<T>(source).Run(); } /// <summary> /// Converts the changeset into a fully formed collection. Each change in the source results in a new collection /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <returns></returns> public static IObservable<IReadOnlyCollection<TObject>> ToCollection<TObject>(this IObservable<IChangeSet<TObject>> source) { return source.QueryWhenChanged(items => items); } /// <summary> /// Converts the changeset into a fully formed sorted collection. Each change in the source results in a new sorted collection /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <typeparam name="TSortKey">The sort key</typeparam> /// <param name="source">The source.</param> /// <param name="sort">The sort function</param> /// <param name="sortOrder">The sort order. Defaults to ascending</param> /// <returns></returns> public static IObservable<IReadOnlyCollection<TObject>> ToSortedCollection<TObject, TSortKey>(this IObservable<IChangeSet<TObject>> source, Func<TObject, TSortKey> sort, SortDirection sortOrder = SortDirection.Ascending) { return source.QueryWhenChanged(query => sortOrder == SortDirection.Ascending ? new ReadOnlyCollectionLight<TObject>(query.OrderBy(sort)) : new ReadOnlyCollectionLight<TObject>(query.OrderByDescending(sort))); } /// <summary> /// Converts the changeset into a fully formed sorted collection. Each change in the source results in a new sorted collection /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <param name="comparer">The sort comparer</param> /// <returns></returns> public static IObservable<IReadOnlyCollection<TObject>> ToSortedCollection<TObject>(this IObservable<IChangeSet<TObject>> source, IComparer<TObject> comparer) { return source.QueryWhenChanged(query => { var items = query.AsList(); items.Sort(comparer); return new ReadOnlyCollectionLight<TObject>(items); }); } /// <summary> /// Defer the subscribtion until loaded and skip initial changeset /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">source</exception> public static IObservable<IChangeSet<T>> SkipInitial<T>(this IObservable<IChangeSet<T>> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.DeferUntilLoaded().Skip(1); } /// <summary> /// Defer the subscription until the stream has been inflated with data /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> DeferUntilLoaded<T>([NotNull] this IObservable<IChangeSet<T>> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return new DeferUntilLoaded<T>(source).Run(); } /// <summary> /// Defer the subscription until the cache has been inflated with data /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="source">The source.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> DeferUntilLoaded<T>(this IObservableList<T> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Connect().DeferUntilLoaded(); } #endregion #region Virtualisation / Paging /// <summary> /// Virtualises the source using parameters provided via the requests observable /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="requests">The requests.</param> /// <returns></returns> public static IObservable<IVirtualChangeSet<T>> Virtualise<T>([NotNull] this IObservable<IChangeSet<T>> source, [NotNull] IObservable<IVirtualRequest> requests) { if (source == null) throw new ArgumentNullException(nameof(source)); if (requests == null) throw new ArgumentNullException(nameof(requests)); return new Virtualiser<T>(source, requests).Run(); } /// <summary> /// Limits the size of the result set to the specified number of items /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="numberOfItems">The number of items.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> Top<T>([NotNull] this IObservable<IChangeSet<T>> source, int numberOfItems) { if (source == null) throw new ArgumentNullException(nameof(source)); if (numberOfItems <= 0) throw new ArgumentOutOfRangeException(nameof(numberOfItems), "Number of items should be greater than zero"); return source.Virtualise(Observable.Return(new VirtualRequest(0, numberOfItems))); } /// <summary> /// Applies paging to the the data source /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="requests">Observable to control page requests</param> /// <returns></returns> public static IObservable<IChangeSet<T>> Page<T>([NotNull] this IObservable<IChangeSet<T>> source, [NotNull] IObservable<IPageRequest> requests) { if (source == null) throw new ArgumentNullException(nameof(source)); if (requests == null) throw new ArgumentNullException(nameof(requests)); return new Pager<T>(source, requests).Run(); } #endregion #region Expiry / size limiter /// <summary> /// Limits the size of the source cache to the specified limit. /// Notifies which items have been removed from the source list. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="sizeLimit">The size limit.</param> /// <param name="scheduler">The scheduler.</param> /// <returns></returns> /// <exception cref="System.ArgumentException">sizeLimit cannot be zero</exception> /// <exception cref="ArgumentNullException">source</exception> /// <exception cref="ArgumentException">sizeLimit cannot be zero</exception> public static IObservable<IEnumerable<T>> LimitSizeTo<T>([NotNull] this ISourceList<T> source, int sizeLimit, IScheduler scheduler = null) { if (source == null) throw new ArgumentNullException(nameof(source)); if (sizeLimit <= 0) throw new ArgumentException("sizeLimit cannot be zero", nameof(sizeLimit)); var locker = new object(); var limiter = new LimitSizeTo<T>(source, sizeLimit, scheduler ?? Scheduler.Default, locker); return limiter.Run().Synchronize(locker).Do(source.RemoveMany); } /// <summary> /// Removes items from the cache according to the value specified by the time selector function /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="timeSelector">Selector returning when to expire the item. Return null for non-expiring item</param> /// <param name="scheduler">The scheduler</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// </exception> public static IObservable<IEnumerable<T>> ExpireAfter<T>([NotNull] this ISourceList<T> source, [NotNull] Func<T, TimeSpan?> timeSelector, IScheduler scheduler = null) { return source.ExpireAfter(timeSelector, null, scheduler); } /// <summary> /// Removes items from the cache according to the value specified by the time selector function /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="timeSelector">Selector returning when to expire the item. Return null for non-expiring item</param> /// <param name="pollingInterval">Enter the polling interval to optimise expiry timers, if ommited 1 timer is created for each unique expiry time</param> /// <param name="scheduler">The scheduler</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// </exception> public static IObservable<IEnumerable<T>> ExpireAfter<T>([NotNull] this ISourceList<T> source, [NotNull] Func<T, TimeSpan?> timeSelector, TimeSpan? pollingInterval = null, IScheduler scheduler = null) { if (source == null) throw new ArgumentNullException(nameof(source)); if (timeSelector == null) throw new ArgumentNullException(nameof(timeSelector)); var locker = new object(); var limiter = new ExpireAfter<T>(source, timeSelector, pollingInterval, scheduler ?? Scheduler.Default, locker); return limiter.Run().Synchronize(locker).Do(source.RemoveMany); } #endregion #region Logical collection operators /// <summary> /// Apply a logical Or operator between the collections. /// Items which are in any of the sources are included in the result /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sources">The source.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> Or<T>([NotNull] this ICollection<IObservable<IChangeSet<T>>> sources) { return sources.Combine(CombineOperator.Or); } /// <summary> /// Apply a logical Or operator between the collections. /// Items which are in any of the sources are included in the result /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="others">The others.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> Or<T>([NotNull] this IObservable<IChangeSet<T>> source, params IObservable<IChangeSet<T>>[] others) { return source.Combine(CombineOperator.Or, others); } /// <summary> /// Dynamically apply a logical Or operator between the items in the outer observable list. /// Items which are in any of the sources are included in the result /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sources">The source.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> Or<T>( [NotNull] this IObservableList<IObservable<IChangeSet<T>>> sources) { return sources.Combine(CombineOperator.Or); } /// <summary> /// Dynamically apply a logical Or operator between the items in the outer observable list. /// Items which are in any of the sources are included in the result /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sources">The source.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> Or<T>([NotNull] this IObservableList<IObservableList<T>> sources) { return sources.Combine(CombineOperator.Or); } /// <summary> /// Dynamically apply a logical Or operator between the items in the outer observable list. /// Items which are in any of the sources are included in the result /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sources">The source.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> Or<T>([NotNull] this IObservableList<ISourceList<T>> sources) { return sources.Combine(CombineOperator.Or); } /// <summary> /// Apply a logical Xor operator between the collections. /// Items which are only in one of the sources are included in the result /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="others">The others.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> Xor<T>([NotNull] this IObservable<IChangeSet<T>> source, params IObservable<IChangeSet<T>>[] others) { return source.Combine(CombineOperator.Xor, others); } /// <summary> /// Apply a logical Xor operator between the collections. /// Items which are only in one of the sources are included in the result /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sources">The sources.</param> /// <returns></returns>> public static IObservable<IChangeSet<T>> Xor<T>([NotNull] this ICollection<IObservable<IChangeSet<T>>> sources) { return sources.Combine(CombineOperator.Xor); } /// <summary> /// Dynamically apply a logical Xor operator between the items in the outer observable list. /// Items which are in any of the sources are included in the result /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sources">The source.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> Xor<T>( [NotNull] this IObservableList<IObservable<IChangeSet<T>>> sources) { return sources.Combine(CombineOperator.Xor); } /// <summary> /// Dynamically apply a logical Xor operator between the items in the outer observable list. /// Items which are in any of the sources are included in the result /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sources">The source.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> Xor<T>([NotNull] this IObservableList<IObservableList<T>> sources) { return sources.Combine(CombineOperator.Xor); } /// <summary> /// Dynamically apply a logical Xor operator between the items in the outer observable list. /// Items which are in any of the sources are included in the result /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sources">The source.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> Xor<T>([NotNull] this IObservableList<ISourceList<T>> sources) { return sources.Combine(CombineOperator.Xor); } /// <summary> /// Apply a logical And operator between the collections. /// Items which are in all of the sources are included in the result /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="others">The others.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> And<T>([NotNull] this IObservable<IChangeSet<T>> source, params IObservable<IChangeSet<T>>[] others) { return source.Combine(CombineOperator.And, others); } /// <summary> /// Apply a logical And operator between the collections. /// Items which are in all of the sources are included in the result /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sources">The sources.</param> /// <returns></returns>> public static IObservable<IChangeSet<T>> And<T>([NotNull] this ICollection<IObservable<IChangeSet<T>>> sources) { return sources.Combine(CombineOperator.And); } /// <summary> /// Dynamically apply a logical And operator between the items in the outer observable list. /// Items which are in any of the sources are included in the result /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sources">The source.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> And<T>( [NotNull] this IObservableList<IObservable<IChangeSet<T>>> sources) { return sources.Combine(CombineOperator.And); } /// <summary> /// Dynamically apply a logical And operator between the items in the outer observable list. /// Items which are in any of the sources are included in the result /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sources">The source.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> And<T>([NotNull] this IObservableList<IObservableList<T>> sources) { return sources.Combine(CombineOperator.And); } /// <summary> /// Dynamically apply a logical And operator between the items in the outer observable list. /// Items which are in any of the sources are included in the result /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sources">The source.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> And<T>([NotNull] this IObservableList<ISourceList<T>> sources) { return sources.Combine(CombineOperator.And); } /// <summary> /// Apply a logical Except operator between the collections. /// Items which are in the source and not in the others are included in the result /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="others">The others.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> Except<T>([NotNull] this IObservable<IChangeSet<T>> source, params IObservable<IChangeSet<T>>[] others) { return source.Combine(CombineOperator.Except, others); } /// <summary> /// Apply a logical Except operator between the collections. /// Items which are in the source and not in the others are included in the result /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sources">The sources.</param> /// <returns></returns>> public static IObservable<IChangeSet<T>> Except<T>( [NotNull] this ICollection<IObservable<IChangeSet<T>>> sources) { return sources.Combine(CombineOperator.Except); } /// <summary> /// Dynamically apply a logical Except operator. Items from the first observable list are included when an equivalent item does not exist in the other sources. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sources">The source.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> Except<T>( [NotNull] this IObservableList<IObservable<IChangeSet<T>>> sources) { return sources.Combine(CombineOperator.Except); } /// <summary> /// Dynamically apply a logical Except operator. Items from the first observable list are included when an equivalent item does not exist in the other sources. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sources">The source.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> Except<T>([NotNull] this IObservableList<IObservableList<T>> sources) { return sources.Combine(CombineOperator.Except); } /// <summary> /// Dynamically apply a logical Except operator. Items from the first observable list are included when an equivalent item does not exist in the other sources. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sources">The source.</param> /// <returns></returns> public static IObservable<IChangeSet<T>> Except<T>([NotNull] this IObservableList<ISourceList<T>> sources) { return sources.Combine(CombineOperator.Except); } private static IObservable<IChangeSet<T>> Combine<T>( [NotNull] this ICollection<IObservable<IChangeSet<T>>> sources, CombineOperator type) { if (sources == null) throw new ArgumentNullException(nameof(sources)); return new Combiner<T>(sources, type).Run(); } private static IObservable<IChangeSet<T>> Combine<T>([NotNull] this IObservable<IChangeSet<T>> source, CombineOperator type, params IObservable<IChangeSet<T>>[] others) { if (source == null) throw new ArgumentNullException(nameof(source)); if (others.Length == 0) throw new ArgumentException("Must be at least one item to combine with", nameof(others)); var items = source.EnumerateOne().Union(others).ToList(); return new Combiner<T>(items, type).Run(); } private static IObservable<IChangeSet<T>> Combine<T>([NotNull] this IObservableList<ISourceList<T>> sources, CombineOperator type) { if (sources == null) throw new ArgumentNullException(nameof(sources)); return Observable.Create<IChangeSet<T>>(observer => { var changesSetList = sources.Connect().Transform(s => s.Connect()).AsObservableList(); var subscriber = changesSetList.Combine(type).SubscribeSafe(observer); return new CompositeDisposable(changesSetList, subscriber); }); } private static IObservable<IChangeSet<T>> Combine<T>([NotNull] this IObservableList<IObservableList<T>> sources, CombineOperator type) { if (sources == null) throw new ArgumentNullException(nameof(sources)); return Observable.Create<IChangeSet<T>>(observer => { var changesSetList = sources.Connect().Transform(s => s.Connect()).AsObservableList(); var subscriber = changesSetList.Combine(type).SubscribeSafe(observer); return new CompositeDisposable(changesSetList, subscriber); }); } private static IObservable<IChangeSet<T>> Combine<T>( [NotNull] this IObservableList<IObservable<IChangeSet<T>>> sources, CombineOperator type) { if (sources == null) throw new ArgumentNullException(nameof(sources)); return new DynamicCombiner<T>(sources, type).Run(); } #endregion #region Switch /// <summary> /// Transforms an observable sequence of observable lists into a single sequence /// producing values only from the most recent observable sequence. /// Each time a new inner observable sequence is received, unsubscribe from the /// previous inner observable sequence and clear the existing result set /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="sources">The source.</param> /// <returns> /// The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. /// </returns> /// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="T:System.ArgumentNullException"><paramref name="sources" /> is null.</exception> public static IObservable<IChangeSet<T>> Switch<T>(this IObservable<IObservableList<T>> sources) { if (sources == null) throw new ArgumentNullException(nameof(sources)); return sources.Select(cache => cache.Connect()).Switch(); } /// <summary> /// Transforms an observable sequence of observable changes sets into an observable sequence /// producing values only from the most recent observable sequence. /// Each time a new inner observable sequence is received, unsubscribe from the /// previous inner observable sequence and clear the existing resukt set /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="sources">The source.</param> /// <returns> /// The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. /// </returns> /// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="T:System.ArgumentNullException"><paramref name="sources" /> is null.</exception> public static IObservable<IChangeSet<T>> Switch<T>(this IObservable<IObservable<IChangeSet<T>>> sources) { if (sources == null) throw new ArgumentNullException(nameof(sources)); return new Switch<T>(sources).Run(); } #endregion #region Start with /// <summary> /// Prepends an empty changeset to the source /// </summary> public static IObservable<IChangeSet<T>> StartWithEmpty<T>(this IObservable<IChangeSet<T>> source) { return source.StartWith(ChangeSet<T>.Empty); } #endregion } }
50.992168
221
0.61264
[ "MIT" ]
Didovgopoly/DynamicData
DynamicData/List/ObservableListEx.cs
104,179
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("Canasta")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Canasta")] [assembly: AssemblyCopyright("Copyright © Microsoft 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("09a26b7f-ca7d-4072-9525-2d968e0dcc7a")] // 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.945946
85
0.727967
[ "MIT" ]
vivibau/CanastaCSharpOld
Client/Canasta/Properties/AssemblyInfo.cs
1,444
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.As.V20180419.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class CreateScalingPolicyRequest : AbstractModel { /// <summary> /// Auto scaling group ID. /// </summary> [JsonProperty("AutoScalingGroupId")] public string AutoScalingGroupId{ get; set; } /// <summary> /// Alarm trigger policy name. /// </summary> [JsonProperty("ScalingPolicyName")] public string ScalingPolicyName{ get; set; } /// <summary> /// The method to adjust the desired number of instances after the alarm is triggered. Value range: <br><li>CHANGE_IN_CAPACITY: Increase or decrease the desired number of instances </li><li>EXACT_CAPACITY: Adjust to the specified desired number of instances </li> <li>PERCENT_CHANGE_IN_CAPACITY: Adjust the desired number of instances by percentage </li> /// </summary> [JsonProperty("AdjustmentType")] public string AdjustmentType{ get; set; } /// <summary> /// The adjusted value of desired number of instances after the alarm is triggered. Value range: <br><li>When AdjustmentType is CHANGE_IN_CAPACITY, if AdjustmentValue is a positive value, some new instances will be added after the alarm is triggered, and if it is a negative value, some existing instances will be removed after the alarm is triggered </li> <li> When AdjustmentType is EXACT_CAPACITY, the value of AdjustmentValue is the desired number of instances after the alarm is triggered, which should be equal to or greater than 0 </li> <li> When AdjustmentType is PERCENT_CHANGE_IN_CAPACITY, if AdjusmentValue (in %) is a positive value, new instances will be added by percentage after the alarm is triggered; if it is a negative value, existing instances will be removed by percentage after the alarm is triggered. /// </summary> [JsonProperty("AdjustmentValue")] public long? AdjustmentValue{ get; set; } /// <summary> /// Alarm monitoring metric. /// </summary> [JsonProperty("MetricAlarm")] public MetricAlarm MetricAlarm{ get; set; } /// <summary> /// Cooldown period in seconds. Default value: 300 seconds. /// </summary> [JsonProperty("Cooldown")] public ulong? Cooldown{ get; set; } /// <summary> /// Notification group ID, which is the set of user group IDs. You can query the user group IDs through the [ListGroups](https://intl.cloud.tencent.com/document/product/598/34589?from_cn_redirect=1) API. /// </summary> [JsonProperty("NotificationUserGroupIds")] public string[] NotificationUserGroupIds{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "AutoScalingGroupId", this.AutoScalingGroupId); this.SetParamSimple(map, prefix + "ScalingPolicyName", this.ScalingPolicyName); this.SetParamSimple(map, prefix + "AdjustmentType", this.AdjustmentType); this.SetParamSimple(map, prefix + "AdjustmentValue", this.AdjustmentValue); this.SetParamObj(map, prefix + "MetricAlarm.", this.MetricAlarm); this.SetParamSimple(map, prefix + "Cooldown", this.Cooldown); this.SetParamArraySimple(map, prefix + "NotificationUserGroupIds.", this.NotificationUserGroupIds); } } }
49.627907
831
0.680881
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet-intl-en
TencentCloud/As/V20180419/Models/CreateScalingPolicyRequest.cs
4,268
C#
namespace Workout.Services.Privilege { /// <summary> /// Class describing a privilege status. /// </summary> public class PrivilegeItem { #region properties /// <summary> /// The privilege key. /// </summary> public string Privilege { get; } /// <summary> /// Flag indicating whether the permission is granted or not. /// </summary> public bool Granted { get; private set; } /// <summary> /// Flag indicating whether the permission has been checked or not. /// </summary> public bool Checked { get; private set; } #endregion #region methods /// <summary> /// Initializes class instance. /// </summary> /// <param name="privilege">Privilege key.</param> public PrivilegeItem(string privilege) { Privilege = privilege; } /// <summary> /// Sets the flag indicating whether permission has been granted or not. /// </summary> /// <param name="value">True if permission has been granted, false otherwise.</param> public void GrantPermission(bool value) { Granted = value; Checked = true; } #endregion } }
25.647059
93
0.54052
[ "Apache-2.0" ]
AchoWang/Tizen-CSharp-Samples
Wearable/Workout/src/Workout/Services/Privilege/PrivilegeItem.cs
1,310
C#
/* * Copyright 2004 The Apache Software Foundation * * 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; namespace Monodoc.Lucene.Net.Store { /// <summary> A memory-resident {@link Directory} implementation. /// /// </summary> /// <version> $Id: RAMDirectory.java,v 1.15 2004/05/09 12:41:47 ehatcher Exp $ /// </version> public sealed class RAMDirectory : Directory { private class AnonymousClassLock:Lock { public AnonymousClassLock(System.String name, RAMDirectory enclosingInstance) { InitBlock(name, enclosingInstance); } private void InitBlock(System.String name, RAMDirectory enclosingInstance) { this.name = name; this.enclosingInstance = enclosingInstance; } private System.String name; private RAMDirectory enclosingInstance; public RAMDirectory Enclosing_Instance { get { return enclosingInstance; } } public override bool Obtain() { lock (Enclosing_Instance.files.SyncRoot) { if (!Enclosing_Instance.FileExists(name)) { Enclosing_Instance.CreateFile(name).Close(); return true; } return false; } } public override void Release() { Enclosing_Instance.DeleteFile(name); } public override bool IsLocked() { return Enclosing_Instance.FileExists(name); } } internal System.Collections.Hashtable files = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); /// <summary>Constructs an empty {@link Directory}. </summary> public RAMDirectory() { } /// <summary> Creates a new <code>RAMDirectory</code> instance from a different /// <code>Directory</code> implementation. This can be used to load /// a disk-based index into memory. /// <P> /// This should be used only with indices that can fit into memory. /// /// </summary> /// <param name="dir">a <code>Directory</code> value /// </param> /// <exception cref=""> IOException if an error occurs /// </exception> public RAMDirectory(Directory dir) : this(dir, false) { } private RAMDirectory(Directory dir, bool closeDir) { System.String[] files = dir.List(); for (int i = 0; i < files.Length; i++) { // make place on ram disk OutputStream os = CreateFile(System.IO.Path.GetFileName(files[i])); // read current file InputStream is_Renamed = dir.OpenFile(files[i]); // and copy to ram disk int len = (int) is_Renamed.Length(); byte[] buf = new byte[len]; is_Renamed.ReadBytes(buf, 0, len); os.WriteBytes(buf, len); // graceful cleanup is_Renamed.Close(); os.Close(); } if (closeDir) dir.Close(); } /// <summary> Creates a new <code>RAMDirectory</code> instance from the {@link FSDirectory}. /// /// </summary> /// <param name="dir">a <code>File</code> specifying the index directory /// </param> public RAMDirectory(System.IO.FileInfo dir) : this(FSDirectory.GetDirectory(dir, false), true) { } /// <summary> Creates a new <code>RAMDirectory</code> instance from the {@link FSDirectory}. /// /// </summary> /// <param name="dir">a <code>String</code> specifying the full index directory path /// </param> public RAMDirectory(System.String dir) : this(FSDirectory.GetDirectory(dir, false), true) { } /// <summary>Returns an array of strings, one for each file in the directory. </summary> public override System.String[] List() { System.String[] result = new System.String[files.Count]; int i = 0; System.Collections.IEnumerator names = files.Keys.GetEnumerator(); while (names.MoveNext()) { result[i++] = ((System.String) names.Current); } return result; } /// <summary>Returns true iff the named file exists in this directory. </summary> public override bool FileExists(System.String name) { RAMFile file = (RAMFile) files[name]; return file != null; } /// <summary>Returns the time the named file was last modified. </summary> public override long FileModified(System.String name) { RAMFile file = (RAMFile) files[name]; return file.lastModified; } /// <summary>Set the modified time of an existing file to now. </summary> public override void TouchFile(System.String name) { // final boolean MONITOR = false; RAMFile file = (RAMFile) files[name]; long ts2, ts1 = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; do { try { System.Threading.Thread.Sleep(new System.TimeSpan((System.Int64) 10000 * 0 + 100 * 1)); } catch (System.Threading.ThreadInterruptedException) { } ts2 = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; // if (MONITOR) { // count++; // } } while (ts1 == ts2); file.lastModified = ts2; // if (MONITOR) // System.out.println("SLEEP COUNT: " + count); } /// <summary>Returns the length in bytes of a file in the directory. </summary> public override long FileLength(System.String name) { RAMFile file = (RAMFile) files[name]; return file.length; } /// <summary>Removes an existing file in the directory. </summary> public override void DeleteFile(System.String name) { files.Remove(name); } /// <summary>Removes an existing file in the directory. </summary> public override void RenameFile(System.String from, System.String to) { RAMFile file = (RAMFile) files[from]; files.Remove(from); files[to] = file; } /// <summary>Creates a new, empty file in the directory with the given name. /// Returns a stream writing this file. /// </summary> public override OutputStream CreateFile(System.String name) { RAMFile file = new RAMFile(); files[name] = file; return new RAMOutputStream(file); } /// <summary>Returns a stream reading an existing file. </summary> public override InputStream OpenFile(System.String name) { RAMFile file = (RAMFile) files[name]; return new RAMInputStream(file); } /// <summary>Construct a {@link Lock}.</summary> /// <param name="name">the name of the lock file /// </param> public override Lock MakeLock(System.String name) { return new AnonymousClassLock(name, this); } /// <summary>Closes the store to future operations. </summary> public override void Close() { } } }
29.962185
127
0.640583
[ "Apache-2.0" ]
OpenPSS/psm-mono
mcs/tools/monodoc/Lucene.Net/Lucene.Net/Store/RAMDirectory.cs
7,131
C#
namespace SqlOptimizerBenchmark.Controls.BenchmarkObjectControls { partial class TestRunDetail { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle(); this.testResultsBrowser = new SqlOptimizerBenchmark.Controls.TestResultBrowser.TestResultsBrowser(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.gpxSummary = new System.Windows.Forms.GroupBox(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.txtExecutionSettings = new System.Windows.Forms.TextBox(); this.txtDbProviderSettings = new System.Windows.Forms.MaskedTextBox(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.lblTestsProcessed = new System.Windows.Forms.Label(); this.lblTestsPassed = new System.Windows.Forms.Label(); this.lblTestsFailed = new System.Windows.Forms.Label(); this.lblSuccess = new System.Windows.Forms.Label(); this.progressBar = new System.Windows.Forms.ProgressBar(); this.label5 = new System.Windows.Forms.Label(); this.lblErrors = new System.Windows.Forms.Label(); this.btnCopySelectedQueries = new System.Windows.Forms.Button(); this.btnSaveToDatabase = new System.Windows.Forms.Button(); this.btnExportToCsv = new System.Windows.Forms.Button(); this.gpxLog = new System.Windows.Forms.GroupBox(); this.logBrowser = new SqlOptimizerBenchmark.Controls.LogBrowser(); this.dataGridViewTextBoxColumn13 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn14 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn15 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn10 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn11 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn12 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn7 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn8 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn9 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn5 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn6 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.btnClearLog = new System.Windows.Forms.ToolStripButton(); ((System.ComponentModel.ISupportInitialize)(this.testResultsBrowser)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.gpxSummary.SuspendLayout(); this.tableLayoutPanel2.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this.gpxLog.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.logBrowser)).BeginInit(); this.toolStrip1.SuspendLayout(); this.SuspendLayout(); // // testResultsBrowser // this.testResultsBrowser.AllowUserToAddRows = false; this.testResultsBrowser.AllowUserToDeleteRows = false; this.testResultsBrowser.AllowUserToResizeRows = false; this.testResultsBrowser.BorderStyle = System.Windows.Forms.BorderStyle.None; this.testResultsBrowser.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.testResultsBrowser.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.testResultsBrowser.Dock = System.Windows.Forms.DockStyle.Fill; this.testResultsBrowser.Location = new System.Drawing.Point(0, 0); this.testResultsBrowser.Name = "testResultsBrowser"; this.testResultsBrowser.ReadOnly = true; this.testResultsBrowser.Size = new System.Drawing.Size(840, 218); this.testResultsBrowser.TabIndex = 0; this.testResultsBrowser.NavigateBenchmarkObject += new SqlOptimizerBenchmark.Controls.BenchmarkObjectEventHandler(this.testResultsBrowser_NavigateBenchmarkObject); this.testResultsBrowser.SelectionChanged += new System.EventHandler(this.testResultsBrowser_SelectionChanged); // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel2; this.splitContainer1.Location = new System.Drawing.Point(0, 0); this.splitContainer1.Name = "splitContainer1"; this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.testResultsBrowser); this.splitContainer1.Panel1.Controls.Add(this.gpxSummary); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.gpxLog); this.splitContainer1.Size = new System.Drawing.Size(840, 614); this.splitContainer1.SplitterDistance = 377; this.splitContainer1.TabIndex = 1; // // gpxSummary // this.gpxSummary.Controls.Add(this.tableLayoutPanel2); this.gpxSummary.Controls.Add(this.tableLayoutPanel1); this.gpxSummary.Controls.Add(this.btnCopySelectedQueries); this.gpxSummary.Controls.Add(this.btnSaveToDatabase); this.gpxSummary.Controls.Add(this.btnExportToCsv); this.gpxSummary.Dock = System.Windows.Forms.DockStyle.Bottom; this.gpxSummary.Location = new System.Drawing.Point(0, 218); this.gpxSummary.Name = "gpxSummary"; this.gpxSummary.Size = new System.Drawing.Size(840, 159); this.gpxSummary.TabIndex = 1; this.gpxSummary.TabStop = false; this.gpxSummary.Text = "Summary"; // // tableLayoutPanel2 // this.tableLayoutPanel2.ColumnCount = 2; this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 131F)); this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel2.Controls.Add(this.label6, 0, 0); this.tableLayoutPanel2.Controls.Add(this.label7, 0, 1); this.tableLayoutPanel2.Controls.Add(this.txtExecutionSettings, 1, 0); this.tableLayoutPanel2.Controls.Add(this.txtDbProviderSettings, 1, 1); this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Bottom; this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 102); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; this.tableLayoutPanel2.RowCount = 3; this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel2.Size = new System.Drawing.Size(834, 54); this.tableLayoutPanel2.TabIndex = 10; // // label6 // this.label6.Anchor = System.Windows.Forms.AnchorStyles.Right; this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(29, 6); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(99, 13); this.label6.TabIndex = 0; this.label6.Text = "Execution settings:"; // // label7 // this.label7.Anchor = System.Windows.Forms.AnchorStyles.Right; this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(20, 31); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(108, 13); this.label7.TabIndex = 0; this.label7.Text = "DB Provider settings:"; // // txtExecutionSettings // this.txtExecutionSettings.Dock = System.Windows.Forms.DockStyle.Fill; this.txtExecutionSettings.Location = new System.Drawing.Point(134, 3); this.txtExecutionSettings.Name = "txtExecutionSettings"; this.txtExecutionSettings.ReadOnly = true; this.txtExecutionSettings.Size = new System.Drawing.Size(697, 21); this.txtExecutionSettings.TabIndex = 0; // // txtDbProviderSettings // this.txtDbProviderSettings.Dock = System.Windows.Forms.DockStyle.Fill; this.txtDbProviderSettings.Location = new System.Drawing.Point(134, 28); this.txtDbProviderSettings.Name = "txtDbProviderSettings"; this.txtDbProviderSettings.ReadOnly = true; this.txtDbProviderSettings.Size = new System.Drawing.Size(697, 21); this.txtDbProviderSettings.TabIndex = 1; // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 11; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 105F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 50F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 61F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 50F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 52F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 50F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 64F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 70F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 60F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 50F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0); this.tableLayoutPanel1.Controls.Add(this.label2, 2, 0); this.tableLayoutPanel1.Controls.Add(this.label3, 4, 0); this.tableLayoutPanel1.Controls.Add(this.label4, 6, 0); this.tableLayoutPanel1.Controls.Add(this.lblTestsProcessed, 1, 0); this.tableLayoutPanel1.Controls.Add(this.lblTestsPassed, 3, 0); this.tableLayoutPanel1.Controls.Add(this.lblTestsFailed, 5, 0); this.tableLayoutPanel1.Controls.Add(this.lblSuccess, 7, 0); this.tableLayoutPanel1.Controls.Add(this.progressBar, 0, 1); this.tableLayoutPanel1.Controls.Add(this.label5, 8, 0); this.tableLayoutPanel1.Controls.Add(this.lblErrors, 9, 0); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top; this.tableLayoutPanel1.Location = new System.Drawing.Point(3, 17); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 4; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(834, 47); this.tableLayoutPanel1.TabIndex = 1; // // label1 // this.label1.Anchor = System.Windows.Forms.AnchorStyles.Right; this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(13, 6); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(89, 13); this.label1.TabIndex = 0; this.label1.Text = "Tests processed:"; // // label2 // this.label2.Anchor = System.Windows.Forms.AnchorStyles.Right; this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(168, 6); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(45, 13); this.label2.TabIndex = 1; this.label2.Text = "Passed:"; // // label3 // this.label3.Anchor = System.Windows.Forms.AnchorStyles.Right; this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(276, 6); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(39, 13); this.label3.TabIndex = 1; this.label3.Text = "Failed:"; // // label4 // this.label4.Anchor = System.Windows.Forms.AnchorStyles.Right; this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(380, 6); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(49, 13); this.label4.TabIndex = 1; this.label4.Text = "Success:"; // // lblTestsProcessed // this.lblTestsProcessed.Anchor = System.Windows.Forms.AnchorStyles.Left; this.lblTestsProcessed.AutoSize = true; this.lblTestsProcessed.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.lblTestsProcessed.Location = new System.Drawing.Point(108, 6); this.lblTestsProcessed.Name = "lblTestsProcessed"; this.lblTestsProcessed.Size = new System.Drawing.Size(14, 13); this.lblTestsProcessed.TabIndex = 2; this.lblTestsProcessed.Text = "0"; // // lblTestsPassed // this.lblTestsPassed.Anchor = System.Windows.Forms.AnchorStyles.Left; this.lblTestsPassed.AutoSize = true; this.lblTestsPassed.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.lblTestsPassed.Location = new System.Drawing.Point(219, 6); this.lblTestsPassed.Name = "lblTestsPassed"; this.lblTestsPassed.Size = new System.Drawing.Size(14, 13); this.lblTestsPassed.TabIndex = 2; this.lblTestsPassed.Text = "0"; // // lblTestsFailed // this.lblTestsFailed.Anchor = System.Windows.Forms.AnchorStyles.Left; this.lblTestsFailed.AutoSize = true; this.lblTestsFailed.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.lblTestsFailed.Location = new System.Drawing.Point(321, 6); this.lblTestsFailed.Name = "lblTestsFailed"; this.lblTestsFailed.Size = new System.Drawing.Size(14, 13); this.lblTestsFailed.TabIndex = 2; this.lblTestsFailed.Text = "0"; // // lblSuccess // this.lblSuccess.Anchor = System.Windows.Forms.AnchorStyles.Left; this.lblSuccess.AutoSize = true; this.lblSuccess.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.lblSuccess.Location = new System.Drawing.Point(435, 6); this.lblSuccess.Name = "lblSuccess"; this.lblSuccess.Size = new System.Drawing.Size(14, 13); this.lblSuccess.TabIndex = 2; this.lblSuccess.Text = "0"; // // progressBar // this.tableLayoutPanel1.SetColumnSpan(this.progressBar, 11); this.progressBar.Dock = System.Windows.Forms.DockStyle.Fill; this.progressBar.Location = new System.Drawing.Point(3, 28); this.progressBar.Name = "progressBar"; this.progressBar.Size = new System.Drawing.Size(828, 14); this.progressBar.TabIndex = 3; // // label5 // this.label5.Anchor = System.Windows.Forms.AnchorStyles.Right; this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(519, 6); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(40, 13); this.label5.TabIndex = 1; this.label5.Text = "Errors:"; // // lblErrors // this.lblErrors.Anchor = System.Windows.Forms.AnchorStyles.Left; this.lblErrors.AutoSize = true; this.lblErrors.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.lblErrors.Location = new System.Drawing.Point(565, 6); this.lblErrors.Name = "lblErrors"; this.lblErrors.Size = new System.Drawing.Size(14, 13); this.lblErrors.TabIndex = 2; this.lblErrors.Text = "0"; // // btnCopySelectedQueries // this.btnCopySelectedQueries.Image = global::SqlOptimizerBenchmark.Properties.Resources.CopySql_16; this.btnCopySelectedQueries.Location = new System.Drawing.Point(306, 70); this.btnCopySelectedQueries.Margin = new System.Windows.Forms.Padding(0); this.btnCopySelectedQueries.Name = "btnCopySelectedQueries"; this.btnCopySelectedQueries.Size = new System.Drawing.Size(150, 25); this.btnCopySelectedQueries.TabIndex = 5; this.btnCopySelectedQueries.Text = "Copy selected queries"; this.btnCopySelectedQueries.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.btnCopySelectedQueries.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.btnCopySelectedQueries.UseVisualStyleBackColor = true; this.btnCopySelectedQueries.Click += new System.EventHandler(this.btnCopySelectedQueries_Click); // // btnSaveToDatabase // this.btnSaveToDatabase.Image = global::SqlOptimizerBenchmark.Properties.Resources.SaveToDb_16; this.btnSaveToDatabase.Location = new System.Drawing.Point(156, 70); this.btnSaveToDatabase.Margin = new System.Windows.Forms.Padding(0); this.btnSaveToDatabase.Name = "btnSaveToDatabase"; this.btnSaveToDatabase.Size = new System.Drawing.Size(150, 25); this.btnSaveToDatabase.TabIndex = 4; this.btnSaveToDatabase.Text = "Save to database"; this.btnSaveToDatabase.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.btnSaveToDatabase.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.btnSaveToDatabase.UseVisualStyleBackColor = true; this.btnSaveToDatabase.Click += new System.EventHandler(this.btnSaveToDatabase_Click); // // btnExportToCsv // this.btnExportToCsv.Image = global::SqlOptimizerBenchmark.Properties.Resources.ExcelFile_16; this.btnExportToCsv.Location = new System.Drawing.Point(6, 70); this.btnExportToCsv.Margin = new System.Windows.Forms.Padding(0); this.btnExportToCsv.Name = "btnExportToCsv"; this.btnExportToCsv.Size = new System.Drawing.Size(150, 25); this.btnExportToCsv.TabIndex = 4; this.btnExportToCsv.Text = "Export to CSV"; this.btnExportToCsv.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.btnExportToCsv.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.btnExportToCsv.UseVisualStyleBackColor = true; this.btnExportToCsv.Click += new System.EventHandler(this.btnExportToCsv_Click); // // gpxLog // this.gpxLog.Controls.Add(this.logBrowser); this.gpxLog.Controls.Add(this.toolStrip1); this.gpxLog.Dock = System.Windows.Forms.DockStyle.Fill; this.gpxLog.Location = new System.Drawing.Point(0, 0); this.gpxLog.Name = "gpxLog"; this.gpxLog.Size = new System.Drawing.Size(840, 233); this.gpxLog.TabIndex = 2; this.gpxLog.TabStop = false; this.gpxLog.Text = "Log"; // // logBrowser // this.logBrowser.AllowUserToAddRows = false; this.logBrowser.AllowUserToDeleteRows = false; this.logBrowser.BorderStyle = System.Windows.Forms.BorderStyle.None; this.logBrowser.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.logBrowser.ColumnHeadersVisible = false; this.logBrowser.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.dataGridViewTextBoxColumn13, this.dataGridViewTextBoxColumn14, this.dataGridViewTextBoxColumn15, this.dataGridViewTextBoxColumn10, this.dataGridViewTextBoxColumn11, this.dataGridViewTextBoxColumn12, this.dataGridViewTextBoxColumn7, this.dataGridViewTextBoxColumn8, this.dataGridViewTextBoxColumn9, this.dataGridViewTextBoxColumn4, this.dataGridViewTextBoxColumn5, this.dataGridViewTextBoxColumn6, this.dataGridViewTextBoxColumn1, this.dataGridViewTextBoxColumn2, this.dataGridViewTextBoxColumn3}); this.logBrowser.Dock = System.Windows.Forms.DockStyle.Fill; this.logBrowser.Location = new System.Drawing.Point(3, 40); this.logBrowser.Name = "logBrowser"; this.logBrowser.ReadOnly = true; this.logBrowser.Size = new System.Drawing.Size(834, 190); this.logBrowser.TabIndex = 2; // // dataGridViewTextBoxColumn13 // dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter; this.dataGridViewTextBoxColumn13.DefaultCellStyle = dataGridViewCellStyle1; this.dataGridViewTextBoxColumn13.HeaderText = "Time"; this.dataGridViewTextBoxColumn13.Name = "dataGridViewTextBoxColumn13"; this.dataGridViewTextBoxColumn13.ReadOnly = true; this.dataGridViewTextBoxColumn13.Width = 120; // // dataGridViewTextBoxColumn14 // this.dataGridViewTextBoxColumn14.FillWeight = 50F; this.dataGridViewTextBoxColumn14.HeaderText = "Message"; this.dataGridViewTextBoxColumn14.Name = "dataGridViewTextBoxColumn14"; this.dataGridViewTextBoxColumn14.ReadOnly = true; this.dataGridViewTextBoxColumn14.Width = 200; // // dataGridViewTextBoxColumn15 // this.dataGridViewTextBoxColumn15.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.dataGridViewTextBoxColumn15.FillWeight = 50F; this.dataGridViewTextBoxColumn15.HeaderText = "Statement"; this.dataGridViewTextBoxColumn15.MinimumWidth = 200; this.dataGridViewTextBoxColumn15.Name = "dataGridViewTextBoxColumn15"; this.dataGridViewTextBoxColumn15.ReadOnly = true; // // dataGridViewTextBoxColumn10 // dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter; this.dataGridViewTextBoxColumn10.DefaultCellStyle = dataGridViewCellStyle2; this.dataGridViewTextBoxColumn10.HeaderText = "Time"; this.dataGridViewTextBoxColumn10.Name = "dataGridViewTextBoxColumn10"; this.dataGridViewTextBoxColumn10.ReadOnly = true; this.dataGridViewTextBoxColumn10.Width = 120; // // dataGridViewTextBoxColumn11 // this.dataGridViewTextBoxColumn11.FillWeight = 50F; this.dataGridViewTextBoxColumn11.HeaderText = "Message"; this.dataGridViewTextBoxColumn11.Name = "dataGridViewTextBoxColumn11"; this.dataGridViewTextBoxColumn11.ReadOnly = true; this.dataGridViewTextBoxColumn11.Width = 200; // // dataGridViewTextBoxColumn12 // this.dataGridViewTextBoxColumn12.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.dataGridViewTextBoxColumn12.FillWeight = 50F; this.dataGridViewTextBoxColumn12.HeaderText = "Statement"; this.dataGridViewTextBoxColumn12.MinimumWidth = 200; this.dataGridViewTextBoxColumn12.Name = "dataGridViewTextBoxColumn12"; this.dataGridViewTextBoxColumn12.ReadOnly = true; // // dataGridViewTextBoxColumn7 // dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter; this.dataGridViewTextBoxColumn7.DefaultCellStyle = dataGridViewCellStyle3; this.dataGridViewTextBoxColumn7.HeaderText = "Time"; this.dataGridViewTextBoxColumn7.Name = "dataGridViewTextBoxColumn7"; this.dataGridViewTextBoxColumn7.ReadOnly = true; this.dataGridViewTextBoxColumn7.Width = 120; // // dataGridViewTextBoxColumn8 // this.dataGridViewTextBoxColumn8.FillWeight = 50F; this.dataGridViewTextBoxColumn8.HeaderText = "Message"; this.dataGridViewTextBoxColumn8.Name = "dataGridViewTextBoxColumn8"; this.dataGridViewTextBoxColumn8.ReadOnly = true; this.dataGridViewTextBoxColumn8.Width = 200; // // dataGridViewTextBoxColumn9 // this.dataGridViewTextBoxColumn9.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.dataGridViewTextBoxColumn9.FillWeight = 50F; this.dataGridViewTextBoxColumn9.HeaderText = "Statement"; this.dataGridViewTextBoxColumn9.MinimumWidth = 200; this.dataGridViewTextBoxColumn9.Name = "dataGridViewTextBoxColumn9"; this.dataGridViewTextBoxColumn9.ReadOnly = true; // // dataGridViewTextBoxColumn4 // dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter; this.dataGridViewTextBoxColumn4.DefaultCellStyle = dataGridViewCellStyle4; this.dataGridViewTextBoxColumn4.HeaderText = "Time"; this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4"; this.dataGridViewTextBoxColumn4.ReadOnly = true; this.dataGridViewTextBoxColumn4.Width = 120; // // dataGridViewTextBoxColumn5 // this.dataGridViewTextBoxColumn5.FillWeight = 50F; this.dataGridViewTextBoxColumn5.HeaderText = "Message"; this.dataGridViewTextBoxColumn5.Name = "dataGridViewTextBoxColumn5"; this.dataGridViewTextBoxColumn5.ReadOnly = true; this.dataGridViewTextBoxColumn5.Width = 200; // // dataGridViewTextBoxColumn6 // this.dataGridViewTextBoxColumn6.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.dataGridViewTextBoxColumn6.FillWeight = 50F; this.dataGridViewTextBoxColumn6.HeaderText = "Statement"; this.dataGridViewTextBoxColumn6.MinimumWidth = 200; this.dataGridViewTextBoxColumn6.Name = "dataGridViewTextBoxColumn6"; this.dataGridViewTextBoxColumn6.ReadOnly = true; // // dataGridViewTextBoxColumn1 // dataGridViewCellStyle5.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter; this.dataGridViewTextBoxColumn1.DefaultCellStyle = dataGridViewCellStyle5; this.dataGridViewTextBoxColumn1.HeaderText = "Time"; this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1"; this.dataGridViewTextBoxColumn1.ReadOnly = true; this.dataGridViewTextBoxColumn1.Width = 120; // // dataGridViewTextBoxColumn2 // this.dataGridViewTextBoxColumn2.FillWeight = 50F; this.dataGridViewTextBoxColumn2.HeaderText = "Message"; this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2"; this.dataGridViewTextBoxColumn2.ReadOnly = true; this.dataGridViewTextBoxColumn2.Width = 200; // // dataGridViewTextBoxColumn3 // this.dataGridViewTextBoxColumn3.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.dataGridViewTextBoxColumn3.FillWeight = 50F; this.dataGridViewTextBoxColumn3.HeaderText = "Statement"; this.dataGridViewTextBoxColumn3.MinimumWidth = 200; this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3"; this.dataGridViewTextBoxColumn3.ReadOnly = true; // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.btnClearLog}); this.toolStrip1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.Flow; this.toolStrip1.Location = new System.Drawing.Point(3, 17); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(834, 23); this.toolStrip1.TabIndex = 1; this.toolStrip1.Text = "toolStrip1"; // // btnClearLog // this.btnClearLog.Image = global::SqlOptimizerBenchmark.Properties.Resources.Clear_16; this.btnClearLog.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnClearLog.Name = "btnClearLog"; this.btnClearLog.Size = new System.Drawing.Size(74, 20); this.btnClearLog.Text = "Clear log"; this.btnClearLog.Click += new System.EventHandler(this.btnClearLog_Click); // // TestRunDetail // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.splitContainer1); this.Name = "TestRunDetail"; this.Size = new System.Drawing.Size(840, 614); ((System.ComponentModel.ISupportInitialize)(this.testResultsBrowser)).EndInit(); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); this.gpxSummary.ResumeLayout(false); this.tableLayoutPanel2.ResumeLayout(false); this.tableLayoutPanel2.PerformLayout(); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.gpxLog.ResumeLayout(false); this.gpxLog.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.logBrowser)).EndInit(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.ResumeLayout(false); } #endregion private TestResultBrowser.TestResultsBrowser testResultsBrowser; private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton btnClearLog; private System.Windows.Forms.GroupBox gpxSummary; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label lblTestsProcessed; private System.Windows.Forms.Label lblTestsPassed; private System.Windows.Forms.Label lblTestsFailed; private System.Windows.Forms.Label lblSuccess; private System.Windows.Forms.ProgressBar progressBar; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label lblErrors; private System.Windows.Forms.GroupBox gpxLog; private System.Windows.Forms.Button btnExportToCsv; private LogBrowser logBrowser; private System.Windows.Forms.Button btnSaveToDatabase; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox txtExecutionSettings; private System.Windows.Forms.MaskedTextBox txtDbProviderSettings; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn5; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn6; private System.Windows.Forms.Button btnCopySelectedQueries; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn7; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn8; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn9; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn10; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn11; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn12; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn13; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn14; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn15; } }
59.359756
175
0.663225
[ "Apache-2.0" ]
RadimBaca/QueryOptimizerBenchmark
benchmark_runner/src/SqlOptimizerBechmark/SqlOptimizerBenchmark/Controls/BenchmarkObjectControls/TestRunDetail.Designer.cs
38,942
C#
using System.Security.Claims; namespace BookFast.Security { public interface ISecurityContextAcceptor { ClaimsPrincipal Principal { set; } } }
18.111111
45
0.711656
[ "MIT" ]
PeterJD/book-fast-service-fabric
Common/BookFast.Security/ISecurityContextAcceptor.cs
163
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Tests; using System.Diagnostics; namespace System.Collections.Specialized.Tests { public class ListDictionaryValuesTests : ICollection_NonGeneric_Tests { protected override Type ICollection_NonGeneric_CopyTo_ArrayOfEnumType_ThrowType => typeof(InvalidCastException); protected override Type ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType_ThrowType => typeof(InvalidCastException); protected override Type ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType_ThrowType => typeof(InvalidCastException); protected override bool Enumerator_Current_UndefinedOperation_Throws => true; protected override bool IsReadOnly => true; protected override ICollection NonGenericICollectionFactory() => new ListDictionary().Values; protected override ICollection NonGenericICollectionFactory(int count) { ListDictionary list = new ListDictionary(); int seed = 13453; for (int i = 0; i < count; i++) list.Add(CreateT(seed++), CreateT(seed++)); return list.Keys; } private string CreateT(int seed) { int stringLength = seed % 10 + 5; Random rand = new Random(seed); byte[] bytes = new byte[stringLength]; rand.NextBytes(bytes); return Convert.ToBase64String(bytes); } protected override void AddToCollection(ICollection collection, int numberOfItemsToAdd) => Debug.Assert(false); protected override IEnumerable<ModifyEnumerable> ModifyEnumerables => new List<ModifyEnumerable>(); } }
41.347826
134
0.709779
[ "MIT" ]
OceanYan/corefx
src/System.Collections.Specialized/tests/ListDictionary/ListDictionary.Values.Tests.cs
1,902
C#
using Cryptography.Domain.Abstractions; using Cryptography.Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cryptography.BusinessLogic.Services { public class A5Service : IA5Service { public int[] Encrypt(A5Data a5Data) { int[] key = GetKey(a5Data); for (int i = 0; i < a5Data.InputValues.Length; i++) { a5Data.InputValues[i] ^= key[i]; } return a5Data.InputValues; } public int[] Decrypt(A5Data a5Data) { return Encrypt(a5Data); } public int[] GetKey(A5Data a5Data) { List<int> registerA = a5Data.RegisterA; List<int> registerB = a5Data.RegisterB; List<int> registerC = a5Data.RegisterC; int outValue, tailA, tailB, tailC; int[] output = new int[16]; for (int i = 0; i < 16; i++) { outValue = registerA[0] ^ registerB[0] ^ registerC[0]; tailA = 0; tailB = 0; tailC = 0; tailA = Feedback(registerA, a5Data.IndicesA); tailB = Feedback(registerB, a5Data.IndicesB); tailC = Feedback(registerC, a5Data.IndicesC); registerA = updateRegister(registerA, tailA); registerB = updateRegister(registerB, tailB); registerC = updateRegister(registerC, tailC); output[i] = outValue; } return output; } private int Feedback(List<int> register, List<int> indices) { int value = 0; foreach (int index in indices) value ^= register[index]; return value; } private List<int> updateRegister(List<int> register, int value) { // shift for (int i = 0; i < register.Count - 1; i++) { register[i] = register[i + 1]; } register[register.Count - 1] = value; return register; } } }
27.222222
71
0.511565
[ "MIT" ]
val-ugs/UDevMe.Cryptography
Cryptography.BusinessLogic/Services/A5Service.cs
2,207
C#
using System; using System.Collections; using System.Collections.Generic; using AggregateSource.Properties; namespace AggregateSource { /// <summary> /// Represents an optional value. /// </summary> /// <typeparam name="T">The type of the optional value.</typeparam> public struct Optional<T> : IEnumerable<T>, IEquatable<Optional<T>> { /// <summary> /// The empty instance. /// </summary> public static readonly Optional<T> Empty = new Optional<T>(); readonly bool _hasValue; readonly T _value; /// <summary> /// Initializes a new <see cref="Optional{T}"/> instance. /// </summary> /// <param name="value">The value to initialize with.</param> public Optional(T value) { _hasValue = true; _value = value; } /// <summary> /// Gets an indication if this instance has a value. /// </summary> public bool HasValue { get { return _hasValue; } } /// <summary> /// Gets the value associated with this instance. /// </summary> /// <exception cref="InvalidOperationException">Thrown when this instance has no value.</exception> public T Value { get { if (!HasValue) throw new InvalidOperationException(Resources.Optional_NoValue); return _value; } } /// <summary> /// Gets the enumerator. /// </summary> /// <returns></returns> public IEnumerator<T> GetEnumerator() { if (HasValue) { yield return _value; } } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if (ReferenceEquals(obj, null)) return false; if (GetType() != obj.GetType()) return false; return Equals((Optional<T>) obj); } /// <summary> /// Determines whether the specified <see cref="Optional{T}" /> is equal to this instance. /// </summary> /// <param name="other">The <see cref="Optional{T}" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="Optional{T}" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(Optional<T> other) { return _hasValue.Equals(other._hasValue) && EqualityComparer<T>.Default.Equals(_value, other._value); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { return _hasValue.GetHashCode() ^ EqualityComparer<T>.Default.GetHashCode(_value) ^ typeof (T).GetHashCode(); } } }
33.686957
123
0.54285
[ "BSD-3-Clause" ]
danbarua/AggregateSource
src/Core/AggregateSource/Optional.cs
3,876
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.DataMigration.Outputs { [OutputType] public sealed class GetTdeCertificatesSqlTaskPropertiesResponse { /// <summary> /// Array of command properties. /// </summary> public readonly ImmutableArray<Union<Outputs.MigrateMISyncCompleteCommandPropertiesResponse, Outputs.MigrateSyncCompleteCommandPropertiesResponse>> Commands; /// <summary> /// Array of errors. This is ignored if submitted. /// </summary> public readonly ImmutableArray<Outputs.ODataErrorResponse> Errors; /// <summary> /// Task input /// </summary> public readonly Outputs.GetTdeCertificatesSqlTaskInputResponse? Input; /// <summary> /// Task output. This is ignored if submitted. /// </summary> public readonly ImmutableArray<Outputs.GetTdeCertificatesSqlTaskOutputResponse> Output; /// <summary> /// The state of the task. This is ignored if submitted. /// </summary> public readonly string State; /// <summary> /// Task type. /// Expected value is 'GetTDECertificates.Sql'. /// </summary> public readonly string TaskType; [OutputConstructor] private GetTdeCertificatesSqlTaskPropertiesResponse( ImmutableArray<Union<Outputs.MigrateMISyncCompleteCommandPropertiesResponse, Outputs.MigrateSyncCompleteCommandPropertiesResponse>> commands, ImmutableArray<Outputs.ODataErrorResponse> errors, Outputs.GetTdeCertificatesSqlTaskInputResponse? input, ImmutableArray<Outputs.GetTdeCertificatesSqlTaskOutputResponse> output, string state, string taskType) { Commands = commands; Errors = errors; Input = input; Output = output; State = state; TaskType = taskType; } } }
34.707692
165
0.654255
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/DataMigration/Outputs/GetTdeCertificatesSqlTaskPropertiesResponse.cs
2,256
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Models.ViewModels { public class InventoryViewModel { [Display(Name = "Store Name")] [RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")] public string LocationName { get; set; } //this stuff is from the product [Display(Name = "Product Name")] [RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")] public string ProductName { get; set; } [Display(Name = "Price")] [Range(0, double.MaxValue)] public double Price { get; set; } [Range(0, int.MaxValue)] public int Quantity { get; set; } [Display(Name = "Description")] public string Description { get; set; } [Display(Name = "ID")] public Guid InventoryId { get; set; } //FK [Display(Name = "Store")] public Guid LocationId { get; set; } [Display(Name = "Customer")] public Guid ProductId { get; set; } } }
25.413043
85
0.597947
[ "MIT" ]
12142020-dotnet-uta/TrevorGrahamRepo1
P1_TrevorGraham/MvcStoreApplication/Models/ViewModels/InventoryViewModel.cs
1,171
C#
using System; using System.ComponentModel.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { [Export(typeof(FileChangeWatcherProvider))] internal sealed class FileChangeWatcherProvider { private readonly TaskCompletionSource<IVsFileChangeEx> _fileChangeService = new TaskCompletionSource<IVsFileChangeEx>(TaskCreationOptions.RunContinuationsAsynchronously); [ImportingConstructor] public FileChangeWatcherProvider(IThreadingContext threadingContext, [Import(typeof(SVsServiceProvider))] Shell.IAsyncServiceProvider serviceProvider) { // We do not want background work to implicitly block on the availability of the SVsFileChangeEx to avoid any deadlock risk, // since the first fetch for a file watcher might end up happening on the background. Watcher = new FileChangeWatcher(_fileChangeService.Task); System.Threading.Tasks.Task.Run(async () => { await threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); var fileChangeService = (IVsFileChangeEx)await serviceProvider.GetServiceAsync(typeof(SVsFileChangeEx)).ConfigureAwait(true); _fileChangeService.SetResult(fileChangeService); }); } public FileChangeWatcher Watcher { get; } } }
45.970588
178
0.735765
[ "Apache-2.0" ]
Therzok/roslyn
src/VisualStudio/Core/Def/Implementation/ProjectSystem/FileChangeWatcherProvider.cs
1,565
C#
namespace WebApi.Services.Models { using AutoMapper; using WebApi.Common.Mapping; using WebApi.Data.Models.Products; public class ProductServiceModel: IMapFrom<Product>, IMapExplicitly { public int Id { get; set; } public string Name { get; set; } public void RegisterMappings(IProfileExpression profile) { profile .CreateMap<Product, ProductServiceModel>() .ForMember(a => a.Name, cfg => cfg.MapFrom(a => a.Name)); } } }
25.428571
73
0.602996
[ "MIT" ]
zrusev/product-store
WebApi/WebApi.Services/Models/ProductServiceModel.cs
536
C#
using UnityEngine; public class DoorDetails : MonoBehaviour { public int ID; void OnCollisionEnter2D() { Managers.RoomNavigationManager.ChangeRoom(ID); } }
17.9
54
0.698324
[ "MIT" ]
virtuoushub/game-off-2016
Assets/Scripts/DoorDetails.cs
181
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using ProjetoFinal2.Models; namespace ProjetoFinal2.Controllers { public class CadastroVoluntariosController : Controller { private readonly Context _context; public CadastroVoluntariosController(Context context) { _context = context; } // GET: CadastroVoluntarios public async Task<IActionResult> Index() { return View(await _context.CadastroVoluntario.ToListAsync()); } // GET: CadastroVoluntarios/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var cadastroVoluntario = await _context.CadastroVoluntario .FirstOrDefaultAsync(m => m.Id_Voluntario == id); if (cadastroVoluntario == null) { return NotFound(); } return View(cadastroVoluntario); } // GET: CadastroVoluntarios/Create public IActionResult Create() { return View(); } // POST: CadastroVoluntarios/Create // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id_Voluntario,Nome,Sobrenome,Endereco,Cidade,Estado,CEP,Psicologia,Juridico,Geral")] CadastroVoluntario cadastroVoluntario) { if (ModelState.IsValid) { _context.Add(cadastroVoluntario); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(cadastroVoluntario); } // GET: CadastroVoluntarios/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var cadastroVoluntario = await _context.CadastroVoluntario.FindAsync(id); if (cadastroVoluntario == null) { return NotFound(); } return View(cadastroVoluntario); } // POST: CadastroVoluntarios/Edit/5 // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("Id_Voluntario,Nome,Sobrenome,Endereco,Cidade,Estado,CEP,Psicologia,Juridico,Geral")] CadastroVoluntario cadastroVoluntario) { if (id != cadastroVoluntario.Id_Voluntario) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(cadastroVoluntario); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CadastroVoluntarioExists(cadastroVoluntario.Id_Voluntario)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(cadastroVoluntario); } // GET: CadastroVoluntarios/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var cadastroVoluntario = await _context.CadastroVoluntario .FirstOrDefaultAsync(m => m.Id_Voluntario == id); if (cadastroVoluntario == null) { return NotFound(); } return View(cadastroVoluntario); } // POST: CadastroVoluntarios/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var cadastroVoluntario = await _context.CadastroVoluntario.FindAsync(id); _context.CadastroVoluntario.Remove(cadastroVoluntario); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool CadastroVoluntarioExists(int id) { return _context.CadastroVoluntario.Any(e => e.Id_Voluntario == id); } } }
32.27451
184
0.558323
[ "MIT" ]
N-Potato/APRESENTACAO
ProjetoFinal terceira squad 7/ProjetoFinal2/Controllers/CadastroVoluntariosController.cs
4,940
C#
 using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle(resource.package.PreviewTOML.CONSTANT.NAME)] [assembly: AssemblyDescription(resource.package.PreviewTOML.CONSTANT.DESCRIPTION)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct(resource.package.PreviewTOML.CONSTANT.NAME)] [assembly: AssemblyCopyright(resource.package.PreviewTOML.CONSTANT.COPYRIGHT)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion(resource.package.PreviewTOML.CONSTANT.VERSION)] [assembly: AssemblyFileVersion(resource.package.PreviewTOML.CONSTANT.VERSION)]
43.125
82
0.824638
[ "Apache-2.0" ]
viacheslav-lozinskyi/Preview-TOML
application/preview-toml.vs/properties/AssemblyInfo.cs
692
C#