content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using UnityEngine; namespace Assets { public static class ScoreManager { /// <summary> /// 高度 /// </summary> public static decimal Altitude { get; set; } /// <summary> /// 高度(表示用) /// </summary> public static decimal ViewAltitude { get { return Altitude * 10; } } } }
19.277778
76
0.512968
[ "MIT" ]
yamakk0033/PencilRocket
Assets/Develop/Scripts/ScoreManager.cs
363
C#
#pragma checksum "D:\PROFESSIONAL\SHIRAJULMAMUN\Training\ASP.NET Core Batch 08\SMECommerce\SMECommerce.App\Views\Shared\_ValidationScriptsPartial.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "4b5e5ef4ebf7354cc35c7dacddd6bc3068f19a47" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared__ValidationScriptsPartial), @"mvc.1.0.view", @"/Views/Shared/_ValidationScriptsPartial.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "D:\PROFESSIONAL\SHIRAJULMAMUN\Training\ASP.NET Core Batch 08\SMECommerce\SMECommerce.App\Views\_ViewImports.cshtml" using SMECommerce.App; #line default #line hidden #nullable disable #nullable restore #line 2 "D:\PROFESSIONAL\SHIRAJULMAMUN\Training\ASP.NET Core Batch 08\SMECommerce\SMECommerce.App\Views\_ViewImports.cshtml" using SMECommerce.App.Models; #line default #line hidden #nullable disable #nullable restore #line 3 "D:\PROFESSIONAL\SHIRAJULMAMUN\Training\ASP.NET Core Batch 08\SMECommerce\SMECommerce.App\Views\_ViewImports.cshtml" using SMECommerce.App.Models.Auth; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"4b5e5ef4ebf7354cc35c7dacddd6bc3068f19a47", @"/Views/Shared/_ValidationScriptsPartial.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"6293b4c947e479223c9748822203e601c82f330c", @"/Views/_ViewImports.cshtml")] public class Views_Shared__ValidationScriptsPartial : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/jquery-validation/dist/jquery.validate.min.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4b5e5ef4ebf7354cc35c7dacddd6bc3068f19a474305", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4b5e5ef4ebf7354cc35c7dacddd6bc3068f19a475344", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
66.220183
406
0.764339
[ "MIT" ]
MoksedurRahman/Dot_Net_Core_Token_Base_Summary_
SMECommerce.App/obj/Debug/net5.0/Razor/Views/Shared/_ValidationScriptsPartial.cshtml.g.cs
7,218
C#
using System.Collections.Generic; using UnityEngine; using TMPro; public class SortOrder : MonoBehaviour { List<SpriteRenderer> spriteRenderers; SpriteRenderer mySP; // Use this for initialization void Awake () { mySP = GetComponent<SpriteRenderer>(); spriteRenderers = new List<SpriteRenderer>(GetComponentsInParent<SpriteRenderer>()); spriteRenderers.Remove(mySP); } // Update is called once per frame void Update () { Sort(); } void Sort() { int pos = Mathf.RoundToInt(transform.position.y * 100); pos /= 3; if (spriteRenderers.Count == 1) SingleSP(pos); else ManySP(pos); } void SingleSP(int pos) { mySP.sortingOrder = (pos + 1) * -1; spriteRenderers[0].sortingOrder = pos * -1; } void ManySP(int pos) { mySP.sortingOrder = (pos + 1) * -1; foreach (SpriteRenderer sp in spriteRenderers) { sp.sortingOrder = pos * -1; } } }
20.86
92
0.580058
[ "Apache-2.0" ]
yam-fine/Phone-Fighters
Phone_Fighters/Assets/Scripts/Misc/SortOrder.cs
1,045
C#
#region Imports using System.Threading.Tasks; #endregion namespace AzureFunctionsLabs.HTTPTrigger.Services { public interface IWebhookService { Task<bool> ClearCloudflareCache(); Task<bool> HandleStripeWebhook(string jsonData, string stripeSignature); } }
20.5
80
0.74216
[ "MIT" ]
a-patel/Azure-Functions-Samples
src/AzureFunctionsLabs.HTTPTrigger/Services/IWebhookService.cs
289
C#
using System; using DDD.Domain.Validations; namespace DDD.Domain.Commands { public class RemoveCustomerCommand : CustomerCommand { public RemoveCustomerCommand(Guid id) { Id = id; AggregateId = id; } public override bool IsValid() { ValidationResult = new RemoveCustomerCommandValidation().Validate(this); return ValidationResult.IsValid; } } }
21.666667
84
0.604396
[ "MIT" ]
Akbarsafari00/Textino.Backend
Src/DDD.Domain/Commands/RemoveCustomerCommand.cs
455
C#
// Copyright (c) 2020, Phoenix Contact GmbH & Co. KG // Licensed under the Apache License, Version 2.0 using System.Windows.Controls; namespace Moryx.Products.UI.Interaction { /// <summary> /// Interaction logic for ProductsWorkspaceView.xaml /// </summary> public partial class ProductsWorkspaceView : UserControl { /// <summary> /// Constructor for this UserControl /// </summary> public ProductsWorkspaceView() { InitializeComponent(); } } }
24.136364
60
0.625235
[ "Apache-2.0" ]
1nf0rmagician/MORYX-AbstractionLayer
src/Moryx.Products.UI.Interaction/Products/ProductsWorkspaceView.xaml.cs
531
C#
using Grumpy.SmartPower.Core.Model; namespace Grumpy.Weather.Client.VisualCrossing.Interface; public interface IVisualCrossingWeatherClient { public IEnumerable<WeatherItem> Get(DateOnly date); }
25.25
57
0.826733
[ "MIT" ]
GrumpyBusted/Grumpy.SmartPower
Grumpy.Weather.Client.VisualCrossing/Interface/IVisualCrossingWeatherClient.cs
204
C#
//----------------------------------------------------------------------- // <copyright file="Reachability.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using Akka.Util.Internal; namespace Akka.Cluster { /// <summary> /// Immutable data structure that holds the reachability status of subject nodes as seen /// from observer nodes. Failure detector for the subject nodes exist on the /// observer nodes. Changes (reachable, unreachable, terminated) are only performed /// by observer nodes to its own records. Each change bumps the version number of the /// record, and thereby it is always possible to determine which record is newest /// merging two instances. /// /// Aggregated status of a subject node is defined as (in this order): /// - Terminated if any observer node considers it as Terminated /// - Unreachable if any observer node considers it as Unreachable /// - Reachable otherwise, i.e. no observer node considers it as Unreachable /// </summary> internal class Reachability //TODO: ISerializable? { /// <summary> /// TBD /// </summary> public static readonly Reachability Empty = new Reachability(ImmutableList.Create<Record>(), ImmutableDictionary.Create<UniqueAddress, long>()); /// <summary> /// TBD /// </summary> /// <param name="records">TBD</param> /// <param name="versions">TBD</param> public Reachability(ImmutableList<Record> records, ImmutableDictionary<UniqueAddress, long> versions) { _cache = new Lazy<Cache>(() => new Cache(records)); _versions = versions; _records = records; } /// <summary> /// TBD /// </summary> public sealed class Record { readonly UniqueAddress _observer; /// <summary> /// TBD /// </summary> public UniqueAddress Observer { get { return _observer; } } readonly UniqueAddress _subject; /// <summary> /// TBD /// </summary> public UniqueAddress Subject { get { return _subject; } } readonly ReachabilityStatus _status; /// <summary> /// TBD /// </summary> public ReachabilityStatus Status { get { return _status; } } readonly long _version; /// <summary> /// TBD /// </summary> public long Version { get { return _version; } } /// <summary> /// TBD /// </summary> /// <param name="observer">TBD</param> /// <param name="subject">TBD</param> /// <param name="status">TBD</param> /// <param name="version">TBD</param> public Record(UniqueAddress observer, UniqueAddress subject, ReachabilityStatus status, long version) { _observer = observer; _subject = subject; _status = status; _version = version; } /// <inheritdoc/> public override bool Equals(object obj) { var other = obj as Record; if (other == null) return false; return _version.Equals(other._version) && _status == other.Status && _observer.Equals(other._observer) && _subject.Equals(other._subject); } /// <inheritdoc/> public override int GetHashCode() { unchecked { var hashCode = (Observer != null ? Observer.GetHashCode() : 0); hashCode = (hashCode * 397) ^ Version.GetHashCode(); hashCode = (hashCode * 397) ^ Status.GetHashCode(); hashCode = (hashCode * 397) ^ (Subject != null ? Subject.GetHashCode() : 0); return hashCode; } } } /// <summary> /// TBD /// </summary> public enum ReachabilityStatus { /// <summary> /// TBD /// </summary> Reachable, /// <summary> /// TBD /// </summary> Unreachable, /// <summary> /// TBD /// </summary> Terminated } /// <summary> /// TBD /// </summary> public ImmutableList<Record> Records { get { return _records; } } readonly ImmutableList<Record> _records; /// <summary> /// TBD /// </summary> public ImmutableDictionary<UniqueAddress, long> Versions { get { return _versions; } } readonly ImmutableDictionary<UniqueAddress, long> _versions; /// <summary> /// TBD /// </summary> class Cache { /// <summary> /// TBD /// </summary> public ImmutableDictionary<UniqueAddress, ImmutableDictionary<UniqueAddress, Record>> ObserverRowMap { get { return _observerRowsMap; } } readonly ImmutableDictionary<UniqueAddress, ImmutableDictionary<UniqueAddress, Record>> _observerRowsMap; /// <summary> /// TBD /// </summary> public ImmutableHashSet<UniqueAddress> AllTerminated { get { return _allTerminated; } } readonly ImmutableHashSet<UniqueAddress> _allTerminated; /// <summary> /// TBD /// </summary> public ImmutableHashSet<UniqueAddress> AllUnreachable { get { return _allUnreachable; } } readonly ImmutableHashSet<UniqueAddress> _allUnreachable; /// <summary> /// TBD /// </summary> public ImmutableHashSet<UniqueAddress> AllUnreachableOrTerminated { get { return _allUnreachableOrTerminated; } } readonly ImmutableHashSet<UniqueAddress> _allUnreachableOrTerminated; /// <summary> /// TBD /// </summary> /// <param name="records">TBD</param> public Cache(ImmutableList<Record> records) { if (records.IsEmpty) { _observerRowsMap = ImmutableDictionary.Create<UniqueAddress, ImmutableDictionary<UniqueAddress, Record>>(); _allTerminated = ImmutableHashSet.Create<UniqueAddress>(); _allUnreachable = ImmutableHashSet.Create<UniqueAddress>(); } else { var mapBuilder = new Dictionary<UniqueAddress, ImmutableDictionary<UniqueAddress, Record>>(); var terminatedBuilder = ImmutableHashSet.CreateBuilder<UniqueAddress>(); var unreachableBuilder = ImmutableHashSet.CreateBuilder<UniqueAddress>(); foreach (var r in records) { ImmutableDictionary<UniqueAddress, Record> m = mapBuilder.TryGetValue(r.Observer, out m) ? m.SetItem(r.Subject, r) //TODO: Other collections take items for Create. Create unnecessary array here : ImmutableDictionary.CreateRange(new[] { new KeyValuePair<UniqueAddress, Record>(r.Subject, r) }); mapBuilder.AddOrSet(r.Observer, m); if (r.Status == ReachabilityStatus.Unreachable) unreachableBuilder.Add(r.Subject); else if (r.Status == ReachabilityStatus.Terminated) terminatedBuilder.Add(r.Subject); } _observerRowsMap = ImmutableDictionary.CreateRange(mapBuilder); _allTerminated = terminatedBuilder.ToImmutable(); _allUnreachable = unreachableBuilder.ToImmutable().Except(AllTerminated); } _allUnreachableOrTerminated = _allTerminated.IsEmpty ? AllUnreachable : AllUnreachable.Union(AllTerminated); } } //TODO: Serialization should ignore readonly Lazy<Cache> _cache; ImmutableDictionary<UniqueAddress, Record> ObserverRows(UniqueAddress observer) { _cache.Value.ObserverRowMap.TryGetValue(observer, out var observerRows); return observerRows; } /// <summary> /// TBD /// </summary> /// <param name="observer">TBD</param> /// <param name="subject">TBD</param> /// <returns>TBD</returns> public Reachability Unreachable(UniqueAddress observer, UniqueAddress subject) { return Change(observer, subject, ReachabilityStatus.Unreachable); } /// <summary> /// TBD /// </summary> /// <param name="observer">TBD</param> /// <param name="subject">TBD</param> /// <returns>TBD</returns> public Reachability Reachable(UniqueAddress observer, UniqueAddress subject) { return Change(observer, subject, ReachabilityStatus.Reachable); } /// <summary> /// TBD /// </summary> /// <param name="observer">TBD</param> /// <param name="subject">TBD</param> /// <returns>TBD</returns> public Reachability Terminated(UniqueAddress observer, UniqueAddress subject) { return Change(observer, subject, ReachabilityStatus.Terminated); } long CurrentVersion(UniqueAddress observer) { return _versions.TryGetValue(observer, out long version) ? version : 0; } long NextVersion(UniqueAddress observer) { return CurrentVersion(observer) + 1; } private Reachability Change(UniqueAddress observer, UniqueAddress subject, ReachabilityStatus status) { var v = NextVersion(observer); var newVersions = _versions.SetItem(observer, v); var newRecord = new Record(observer, subject, status, v); var oldObserverRows = ObserverRows(observer); if (oldObserverRows == null && status == ReachabilityStatus.Reachable) return this; if (oldObserverRows == null) return new Reachability(_records.Add(newRecord), newVersions); if(!oldObserverRows.TryGetValue(subject, out var oldRecord)) { if (status == ReachabilityStatus.Reachable && oldObserverRows.Values.All(r => r.Status == ReachabilityStatus.Reachable)) return new Reachability(_records.FindAll(r => !r.Observer.Equals(observer)), newVersions); return new Reachability(_records.Add(newRecord), newVersions); } if (oldRecord.Status == ReachabilityStatus.Terminated || oldRecord.Status == status) return this; if (status == ReachabilityStatus.Reachable && oldObserverRows.Values.All(r => r.Status == ReachabilityStatus.Reachable || r.Subject.Equals(subject))) return new Reachability(_records.FindAll(r => !r.Observer.Equals(observer)), newVersions); var newRecords = _records.SetItem(_records.IndexOf(oldRecord), newRecord); return new Reachability(newRecords, newVersions); } /// <summary> /// TBD /// </summary> /// <param name="allowed">TBD</param> /// <param name="other">TBD</param> /// <returns>TBD</returns> public Reachability Merge(IEnumerable<UniqueAddress> allowed, Reachability other) { var recordBuilder = ImmutableList.CreateBuilder<Record>(); //TODO: Size hint somehow? var newVersions = _versions; foreach (var observer in allowed) { var observerVersion1 = CurrentVersion(observer); var observerVersion2 = other.CurrentVersion(observer); var rows1 = ObserverRows(observer); var rows2 = other.ObserverRows(observer); if (rows1 != null && rows2 != null) { var rows = observerVersion1 > observerVersion2 ? rows1 : rows2; foreach(var record in rows.Values.Where(r => allowed.Contains(r.Subject))) recordBuilder.Add(record); } if (rows1 != null && rows2 == null) { if(observerVersion1 > observerVersion2) foreach (var record in rows1.Values.Where(r => allowed.Contains(r.Subject))) recordBuilder.Add(record); } if (rows1 == null && rows2 != null) { if (observerVersion2 > observerVersion1) foreach (var record in rows2.Values.Where(r => allowed.Contains(r.Subject))) recordBuilder.Add(record); } if (observerVersion2 > observerVersion1) newVersions = newVersions.SetItem(observer, observerVersion2); } newVersions = ImmutableDictionary.CreateRange(newVersions.Where(p => allowed.Contains(p.Key))); return new Reachability(recordBuilder.ToImmutable(), newVersions); } /// <summary> /// TBD /// </summary> /// <param name="nodes">TBD</param> /// <returns>TBD</returns> public Reachability Remove(IEnumerable<UniqueAddress> nodes) { var nodesSet = nodes.ToImmutableHashSet(); var newRecords = _records.FindAll(r => !nodesSet.Contains(r.Observer) && !nodesSet.Contains(r.Subject)); var newVersions = _versions.RemoveRange(nodes); return new Reachability(newRecords, newVersions); } /// <summary> /// TBD /// </summary> /// <param name="nodes">TBD</param> /// <returns>TBD</returns> public Reachability RemoveObservers(ImmutableHashSet<UniqueAddress> nodes) { if (nodes.Count == 0) { return this; } else { var newRecords = _records.FindAll(r => !nodes.Contains(r.Observer)); var newVersions = _versions.RemoveRange(nodes); return new Reachability(newRecords, newVersions); } } public Reachability FilterRecords(Predicate<Record> f) { return new Reachability(Records.FindAll(f), Versions); } /// <summary> /// TBD /// </summary> /// <param name="observer">TBD</param> /// <param name="subject">TBD</param> /// <returns>TBD</returns> public ReachabilityStatus Status(UniqueAddress observer, UniqueAddress subject) { var observerRows = ObserverRows(observer); if (observerRows == null) return ReachabilityStatus.Reachable; if(!observerRows.TryGetValue(subject, out var record)) return ReachabilityStatus.Reachable; return record.Status; } /// <summary> /// TBD /// </summary> /// <param name="node">TBD</param> /// <returns>TBD</returns> public ReachabilityStatus Status(UniqueAddress node) { if (_cache.Value.AllTerminated.Contains(node)) return ReachabilityStatus.Terminated; if (_cache.Value.AllUnreachable.Contains(node)) return ReachabilityStatus.Unreachable; return ReachabilityStatus.Reachable; } /// <summary> /// TBD /// </summary> /// <param name="node">TBD</param> /// <returns>TBD</returns> public bool IsReachable(UniqueAddress node) { return IsAllReachable || !AllUnreachableOrTerminated.Contains(node); } /// <summary> /// TBD /// </summary> /// <param name="observer">TBD</param> /// <param name="subject">TBD</param> /// <returns>TBD</returns> public bool IsReachable(UniqueAddress observer, UniqueAddress subject) { return Status(observer, subject) == ReachabilityStatus.Reachable; } /* * def isReachable(observer: UniqueAddress, subject: UniqueAddress): Boolean = status(observer, subject) == Reachable */ /// <summary> /// TBD /// </summary> public bool IsAllReachable { get { return _records.IsEmpty; } } /// <summary> /// Doesn't include terminated /// </summary> public ImmutableHashSet<UniqueAddress> AllUnreachable { get { return _cache.Value.AllUnreachable; } } /// <summary> /// TBD /// </summary> public ImmutableHashSet<UniqueAddress> AllUnreachableOrTerminated { get { return _cache.Value.AllUnreachableOrTerminated; } } /// <summary> /// TBD /// </summary> /// <param name="observer">TBD</param> /// <returns>TBD</returns> public ImmutableHashSet<UniqueAddress> AllUnreachableFrom(UniqueAddress observer) { var observerRows = ObserverRows(observer); if (observerRows == null) return ImmutableHashSet.Create<UniqueAddress>(); return ImmutableHashSet.CreateRange( observerRows.Where(p => p.Value.Status == ReachabilityStatus.Unreachable).Select(p => p.Key)); } /// <summary> /// TBD /// </summary> public ImmutableDictionary<UniqueAddress, ImmutableHashSet<UniqueAddress>> ObserversGroupedByUnreachable { get { var builder = new Dictionary<UniqueAddress, ImmutableHashSet<UniqueAddress>>(); var grouped = _records.GroupBy(p => p.Subject); foreach (var records in grouped) { if (records.Any(r => r.Status == ReachabilityStatus.Unreachable)) { builder.Add(records.Key, records.Where(r => r.Status == ReachabilityStatus.Unreachable) .Select(r => r.Observer).ToImmutableHashSet()); } } return builder.ToImmutableDictionary(); } } /// <summary> /// TBD /// </summary> public ImmutableHashSet<UniqueAddress> AllObservers { get { return _records.Select(i => i.Observer).ToImmutableHashSet(); } } /// <summary> /// TBD /// </summary> /// <param name="observer">TBD</param> /// <returns>TBD</returns> public ImmutableList<Record> RecordsFrom(UniqueAddress observer) { var rows = ObserverRows(observer); if (rows == null) return ImmutableList.Create<Record>(); return rows.Values.ToImmutableList(); } /// <inheritdoc/> public override int GetHashCode() { return _versions.GetHashCode(); } /// <inheritdoc/> public override bool Equals(object obj) { var other = obj as Reachability; if (other == null) return false; return _records.Count == other._records.Count && _versions.Equals(other._versions) && _cache.Value.ObserverRowMap.Equals(other._cache.Value.ObserverRowMap); } /// <inheritdoc/> public override string ToString() { var builder = new StringBuilder("Reachability("); foreach (var observer in _versions.Keys) { var rows = ObserverRows(observer); if (rows == null) continue; builder.AppendJoin(", ", rows, (b, row, index) => b.AppendFormat("[{0} -> {1}: {2} [{3}] ({4})]", observer.Address, row.Key, row.Value.Status, Status(row.Key), row.Value.Version)); } return builder.Append(')').ToString(); } } }
37.667266
149
0.54061
[ "Apache-2.0" ]
DeepakArora76/akka.net
src/core/Akka.Cluster/Reachability.cs
20,945
C#
/****************************** Module Header ******************************\ * Module Name: SessionExtensions.cs * Project: CSASPNETMVCSession * Copyright (c) Microsoft Corporation. * * This sample demonstrates how to use Session in ASPNET MVC. * This class is the Extension for HttpSessionStateBase class. * * This source is subject to the Microsoft Public License. * See http://www.microsoft.com/en-us/openness/licenses.aspx#MPL * All other rights reserved. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. \***************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CSASPNETMVCSession { public static class SessionExtensions { /// <summary> /// Get value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="session"></param> /// <param name="key"></param> /// <returns></returns> public static T GetDataFromSession<T>(this HttpSessionStateBase session, string key) { return (T)session[key]; } /// <summary> /// Set value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="session"></param> /// <param name="key"></param> /// <param name="value"></param> public static void SetDataToSession<T>(this HttpSessionStateBase session, string key, object value) { session[key] = value; } } }
34.078431
107
0.579402
[ "MIT" ]
Ranin26/msdn-code-gallery-microsoft
OneCodeTeam/How to create and access session variables in ASP.NET MVC/[C#]-How to create and access session variables in ASP.NET MVC/C#/CSASPNETMVCSession/Models/SessionExtensions.cs
1,740
C#
using Author.OTP; using Author.UI.Messages; using Author.Utility; using System; using System.ComponentModel; using System.Runtime.CompilerServices; using Xamarin.Forms; namespace Author.UI.ViewModels { public class EntryPageViewModel : INotifyPropertyChanged { private bool _addingEntry = false; private MainPageEntryViewModel _entry = null; public MainPageEntryViewModel Entry { get => _entry; private set { if (value != _entry) { if (_entry != null) { _entry.Secret.PropertyChanged -= OnTypeChanged; } if (value != null) { value.Secret.PropertyChanged += OnTypeChanged; } _entry = value; OnPropertyChanged(); } } } private string _title = "Add OTP entry"; public string Title { get => _title; set { if (value != _title) { _title = value; OnPropertyChanged(); } } } private bool _lengthPickerEnabled = true; public bool LengthPickerEnabled { get => _lengthPickerEnabled; set { if (value != _lengthPickerEnabled) { _lengthPickerEnabled = value; OnPropertyChanged(); } } } private bool _periodSliderEnabled = true; public bool PeriodSliderEnabled { get => _periodSliderEnabled; set { if (value != _periodSliderEnabled) { _periodSliderEnabled = value; OnPropertyChanged(); } } } public Command DisappearingCommand { get; private set; } public Command AcceptCommand { get; private set; } public event PropertyChangedEventHandler PropertyChanged; public EntryPageViewModel() { DisappearingCommand = new Command(OnDisappearing); AcceptCommand = new Command(OnAcceptTapped); } private void OnDisappearing() { _entry = null; } private void OnAcceptTapped() { if (string.IsNullOrEmpty(Entry.Secret.Name) || string.IsNullOrEmpty(Entry.Secret.Data)) { try { Notification.Create("Detected invalid properties for the entry") .SetDuration(TimeSpan.FromSeconds(3)) .SetPosition(Notification.Position.Bottom) .Show(); } catch { } return; } if (_addingEntry) { MessagingCenter.Send(new AddEntry { Entry = Entry }, "AddEntry"); try { Notification.Create("Added new entry") .SetDuration(TimeSpan.FromSeconds(3)) .SetPosition(Notification.Position.Bottom) .Show(); } catch { } } else { MainPageEntryViewModel entry = Entry; entry.UpdateCode(Time.GetCurrent(), true); MessagingCenter.Send(new EditEntry { Entry = entry }, "EditEntry"); try { Notification.Create("Saved edited entry") .SetDuration(TimeSpan.FromSeconds(3)) .SetPosition(Notification.Position.Bottom) .Show(); } catch { } } } public void AddEntry(MainPageEntryViewModel entry = null) { Title = "Add OTP entry"; Entry = entry ?? new MainPageEntryViewModel(); _addingEntry = true; } public void EditEntry(MainPageEntryViewModel entry) { Title = "Edit OTP entry"; Entry = entry; _addingEntry = false; } private void OnTypeChanged(object sender, PropertyChangedEventArgs args) { if (args.PropertyName == "Type") { Factory.SetupEntryPage(((Secret)sender).Type, this); } } private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
27.5
86
0.460202
[ "Apache-2.0", "BSD-3-Clause" ]
danielga/Author
Author.UI.Xamarin/UI/ViewModels/EntryPageViewModel.cs
4,952
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( "SwaggerODataWebApiSample" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "" )] [assembly: AssemblyProduct( "SwaggerODataWebApiSample" )] [assembly: AssemblyCopyright( "Copyright © 2017" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "f3986f7b-af76-43d1-a44f-303023a08cd3" )] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )]
39.027778
84
0.740214
[ "MIT" ]
AzureMentor/aspnet-api-versioning
samples/webapi/SwaggerODataWebApiSample/Properties/AssemblyInfo.cs
1,408
C#
namespace NotBook.Api.Models.User.Request { public class UserForgotPasswordRequest { public string Email { get; set; } } }
20.285714
42
0.669014
[ "MIT" ]
dorukBen/notbook-server
NotBook.Api/Models/User/Request/UserForgotPasswordRequest.cs
142
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void FusedAddHalving_Vector128_Int16() { var test = new SimpleBinaryOpTest__FusedAddHalving_Vector128_Int16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__FusedAddHalving_Vector128_Int16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int16> _fld1; public Vector128<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__FusedAddHalving_Vector128_Int16 testClass) { var result = AdvSimd.FusedAddHalving(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__FusedAddHalving_Vector128_Int16 testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = AdvSimd.FusedAddHalving( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__FusedAddHalving_Vector128_Int16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public SimpleBinaryOpTest__FusedAddHalving_Vector128_Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.FusedAddHalving( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.FusedAddHalving( AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.FusedAddHalving), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.FusedAddHalving), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.FusedAddHalving( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int16>* pClsVar1 = &_clsVar1) fixed (Vector128<Int16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.FusedAddHalving( AdvSimd.LoadVector128((Int16*)(pClsVar1)), AdvSimd.LoadVector128((Int16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); var result = AdvSimd.FusedAddHalving(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)); var result = AdvSimd.FusedAddHalving(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__FusedAddHalving_Vector128_Int16(); var result = AdvSimd.FusedAddHalving(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__FusedAddHalving_Vector128_Int16(); fixed (Vector128<Int16>* pFld1 = &test._fld1) fixed (Vector128<Int16>* pFld2 = &test._fld2) { var result = AdvSimd.FusedAddHalving( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.FusedAddHalving(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = AdvSimd.FusedAddHalving( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.FusedAddHalving(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.FusedAddHalving( AdvSimd.LoadVector128((Int16*)(&test._fld1)), AdvSimd.LoadVector128((Int16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.FusedAddHalving(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.FusedAddHalving)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
42.279245
187
0.586755
[ "MIT" ]
2m0nd/runtime
src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/FusedAddHalving.Vector128.Int16.cs
22,408
C#
// 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 Microsoft.Azure.Commands.Network.Models; using Microsoft.Azure.Management.Network; using System; using System.Management.Automation; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Internal.Resources.Utilities.Models; using Microsoft.Azure.Management.Network.Models; namespace Microsoft.Azure.Commands.Network { [Cmdlet("Stop", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VirtualNetworkGatewayConnectionPacketCapture", DefaultParameterSetName = "ByName", SupportsShouldProcess = true), OutputType(typeof(PSVirtualNetworkGatewayPacketCaptureResult))] public class StopAzVirtualNetworkGatewayConnectionPacketCaptureCommand : VirtualNetworkGatewayConnectionBaseCmdlet { [Parameter( ParameterSetName = "ByName", Mandatory = true, HelpMessage = "The resource group name.")] [ResourceGroupCompleter] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Alias("ResourceName", "ConnectionName")] [Parameter( ParameterSetName = "ByName", Mandatory = true, HelpMessage = "The virtual network gateway connection name where packet capture is to be started.")] [ResourceNameCompleter("Microsoft.Network/connections", "ResourceGroupName")] [ValidateNotNullOrEmpty] public string Name { get; set; } [Alias("VirtualNetworkGatewayConnection")] [Parameter( ParameterSetName = "ByInputObject", Mandatory = true, ValueFromPipeline = true, HelpMessage = "The virtual network gateway connection object where packet capture to be started.")] [ValidateNotNullOrEmpty] public PSVirtualNetworkGatewayConnection InputObject { get; set; } [Parameter( ParameterSetName = "ByResourceId", Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The Azure resource ID of the VirtualNetworkGatewayConnection where packet capture to be started.")] [ValidateNotNullOrEmpty] public string ResourceId { get; set; } [Parameter( Mandatory = true, HelpMessage = "SAS Url for stop packet capture on virtual network gateway.")] public string SasUrl { get; set; } [Parameter( Mandatory = false, HelpMessage = "Run cmdlet in the background")] public SwitchParameter AsJob { get; set; } public override void Execute() { PSVirtualNetworkGatewayConnection existingConnection = null; if (ParameterSetName.Equals("ByInputObject")) { existingConnection = InputObject; this.ResourceGroupName = this.InputObject.ResourceGroupName; this.Name = this.InputObject.Name; } else { if (ParameterSetName.Equals("ByResourceId")) { var parsedResourceId = new ResourceIdentifier(ResourceId); Name = parsedResourceId.ResourceName; ResourceGroupName = parsedResourceId.ResourceGroupName; } existingConnection = this.GetVirtualNetworkGatewayConnection(this.ResourceGroupName, this.Name); } if (existingConnection == null) { throw new PSArgumentException(Properties.Resources.ResourceNotFound, "Virtual Network Gateway connection"); } VpnPacketCaptureStopParameters parameters = new VpnPacketCaptureStopParameters(); if (this.SasUrl != null) { parameters.SasUrl = SasUrl; } base.Execute(); if (ShouldProcess(this.Name, String.Format(Properties.Resources.CreatingLongRunningOperationMessage, this.ResourceGroupName, this.Name))) { WriteVerbose(String.Format(Properties.Resources.CreatingLongRunningOperationMessage, this.ResourceGroupName, this.Name)); PSVirtualNetworkGatewayConnectionPacketCaptureResult output = new PSVirtualNetworkGatewayConnectionPacketCaptureResult() { Name = existingConnection.Name, ResourceGroupName = existingConnection.ResourceGroupName, Tag = existingConnection.Tag, ResourceGuid = existingConnection.ResourceGuid, Location = existingConnection.Location, }; output.StartTime = DateTime.UtcNow; var result = this.VirtualNetworkGatewayConnectionClient.StopPacketCapture(this.ResourceGroupName, this.Name, parameters); output.EndTime = DateTime.UtcNow; WriteObject(output); } } } }
46.284553
150
0.63095
[ "MIT" ]
3quanfeng/azure-powershell
src/Network/Network/VirtualNetworkGatewayConnection/StopAzVirtualNetworkGatewayConnectionPacketCaptureCommand.cs
5,573
C#
//----------------------------------------------------------------------------- // Verve // Copyright (C) - Violent Tulip //----------------------------------------------------------------------------- function VerveEditor::DeleteControls() { while ( VerveEditorGroupStack.getCount() > 0 ) { VerveEditorGroupStack.getObject( 0 ).delete(); } while ( VerveEditorTrackStack.getCount() > 0 ) { VerveEditorTrackStack.getObject( 0 ).delete(); } } function VerveEditorStack::FindControl( %this, %object ) { %trackCount = %this.getCount(); for ( %i = 0; %i < %trackCount; %i++ ) { %track = %this.getObject( %i ); if ( %track.Proxy.getId() == %object.getId() ) { return %track; } } return -1; } function VerveEditorStack::FindControlIndex( %this, %object ) { %trackCount = %this.getCount(); for ( %i = 0; %i < %trackCount; %i++ ) { %track = %this.getObject( %i ); if ( %track.Proxy.getId() == %object.getId() ) { return %i; } } return -1; } //------------------------------------------------------------------------- function VerveEditorTimeLine::onLoseFirstResponder( %this ) { // Clear Selection. %this.setSelection( false ); // Force OnSelectionUpdate. %this.onSelectionUpdate(); } function VerveEditorTimeLine::StopUpdate( %this ) { // Cancel Event. cancel( $VerveEditor::Controller::TickEvent ); } function VerveEditorTimeLine::ControllerUpdate( %this ) { // Cancel Event. cancel( $VerveEditor::Controller::TickEvent ); %scrollParent = %this.getParentOfType( "VEditorScrollControl" ); if ( !isObject( %scrollParent ) ) { // Woops! return; } // Fetch Point. %point = %this.toPoint( $VerveEditor::Controller.Time ); // Fetch Scroll Point. %scrollPoint = %scrollParent.getScrollPositionX(); %scrollWidth = getWord( %scrollParent.getExtent(), 0 ) - 19; if ( ( %point < %scrollPoint ) || ( %point > ( %scrollPoint + %scrollWidth ) ) ) { // Scroll To View Time. %scrollParent.setScrollPosition( %point - %scrollWidth * 0.50, 0 ); } // Schedule Next Event. $VerveEditor::Controller::TickEvent = %this.schedule( 100, "ControllerUpdate" ); } function VerveEditorTimeLine::onSelectionUpdate( %this ) { // Fetch Selection. %selectionString = %this.getSelection(); %selectionActive = getWord( %selectionString, 0 ); if ( !%selectionActive ) { // Clear Selection. VerveEditorTrackTimeLine.setSelection( false ); } else { if ( !getWord( VerveEditorTrackTimeLine.getSelection(), 0 ) ) { // Clear Editor Selection. VerveEditor::ClearSelection(); } // Set Selection. VerveEditorTrackTimeLine.setSelection( true, getWord( %selectionString, 1 ), getWord( %selectionString, 2 ) ); } } function VerveEditorTimeLine::onSelectionRightClick( %this, %point, %modifiers, %clickCount ) { %this.DisplayContextMenu( getWord( %point, 0 ), getWord( %point, 1 ) ); } function VerveEditorTimeLine::DisplayContextMenu( %this, %x, %y ) { %contextMenu = $VerveEditor::VTimeLine::ContextMenu; if ( !isObject( %contextMenu ) ) { %contextMenu = new PopupMenu() { SuperClass = "VerveWindowMenu"; IsPopup = true; Label = "VTimeLineMenu"; Position = 0; Item[0] = "Insert Time Before" TAB "" TAB "VerveEditorTimeLine.InsertTimeBefore();"; Item[1] = "Insert Time After" TAB "" TAB "VerveEditorTimeLine.InsertTimeAfter();"; Item[2] = "" TAB ""; Item[3] = "Delete Time" TAB "" TAB "VerveEditorTimeLine.DeleteTime();"; }; %contextMenu.Init(); // Cache. $VerveEditor::VTimeLine::ContextMenu = %contextMenu; } // Display. if($Verve::UseSeparateWindow) %contextMenu.showPopup( VerveEditorWindow, %x, %y ); else %contextMenu.showPopup( Canvas, %x, %y ); } function VerveEditorTimeLine::InsertTimeBefore( %this ) { // Fetch Selection. %selectionString = %this.getSelection(); %selectionActive = getWord( %selectionString, 0 ); if ( !%selectionActive ) { // Woops! return; } // Determine Position. %selectionPosition = getWord( %selectionString, 1 ); // Insert Time. VerveEditor::InsertTime( %selectionPosition, getWord( %selectionString, 2 ) ); } function VerveEditorTimeLine::InsertTimeAfter( %this ) { // Fetch Selection. %selectionString = %this.getSelection(); %selectionActive = getWord( %selectionString, 0 ); if ( !%selectionActive ) { // Woops! return; } // Determine Position. %selectionPosition = getWord( %selectionString, 1 ) + getWord( %selectionString, 2 ); // Insert Time. VerveEditor::InsertTime( %selectionPosition, getWord( %selectionString, 2 ) ); } function VerveEditorTimeLine::DeleteTime( %this ) { // Fetch Selection. %selectionString = %this.getSelection(); %selectionActive = getWord( %selectionString, 0 ); if ( !%selectionActive ) { // Woops! return; } // Determine Position. %selectionPosition = getWord( %selectionString, 1 ); // Delete Time. VerveEditor::DeleteTime( %selectionPosition, getWord( %selectionString, 2 ) ); // Clear Selection. %this.setSelection( false ); // Force OnSelectionUpdate. %this.onSelectionUpdate(); } //------------------------------------------------------------------------- function VerveEditorTimeLineBackground::onMouseUp( %this, %point, %modifiers, %clickCount ) { // Clear Selection. VerveEditor::ClearSelection(); } function VerveEditorTimeLineBackground::onRightMouseUp( %this, %point, %modifiers, %clickCount ) { // Clear Selection. VerveEditor::ClearSelection(); if ( !%this.Context ) { // Return. return; } // Display Context Menu. $VerveEditor::Controller.schedule( 32, "DisplayContextMenu", getWord( %point, 0 ), getWord( %point, 1 ) ); }
26.626556
118
0.561166
[ "MIT" ]
Areloch/GG-Torque3D
Templates/BaseGame/game/tools/VerveEditor/Scripts/EditorControls.cs
6,417
C#
using System; using System.Collections.Generic; using System.Text; using OpenTK; namespace Examples.Shapes { public sealed class SlicedSphere : DrawableShape { public enum eSubdivisions { Zero = 0, One = 1, Two = 2, Three = 3, Four = 4, Five = 5, Six = 6, Seven = 7, Eight = 8, } public enum eDir { All, FrontTopRight, FrontBottomRight, FrontBottomLeft, FrontTopLeft, BackTopRight, BackBottomRight, BackBottomLeft, BackTopLeft, } public SlicedSphere(double radius, Vector3d offset, eSubdivisions subdivs, eDir[] sides, bool useDL) : base(useDL) { double Diameter = radius; PrimitiveMode = OpenTK.Graphics.OpenGL.BeginMode.Triangles; if (sides[0] == eDir.All) { sides = new eDir[] { eDir.FrontTopRight, eDir.FrontBottomRight, eDir.FrontBottomLeft, eDir.FrontTopLeft, eDir.BackTopRight, eDir.BackBottomRight, eDir.BackBottomLeft, eDir.BackTopLeft,}; } VertexArray = new VertexT2dN3dV3d[sides.Length * 3]; IndexArray = new uint[sides.Length * 3]; uint counter = 0; foreach (eDir s in sides) { GetDefaultVertices(s, Diameter, out VertexArray[counter + 0], out VertexArray[counter + 1], out VertexArray[counter + 2]); IndexArray[counter + 0] = counter + 0; IndexArray[counter + 1] = counter + 1; IndexArray[counter + 2] = counter + 2; counter += 3; } if (subdivs != eSubdivisions.Zero) { for (int s = 0; s < (int)subdivs; s++) { #region Assemble Chunks and convert to Arrays List<Chunk> AllChunks = new List<Chunk>(); for (uint i = 0; i < IndexArray.Length; i += 3) { Chunk chu; Subdivide(Diameter, ref VertexArray[IndexArray[i + 0]], ref VertexArray[IndexArray[i + 1]], ref VertexArray[IndexArray[i + 2]], out chu); AllChunks.Add(chu); } Chunk.GetArray(ref AllChunks, out VertexArray, out IndexArray); AllChunks.Clear(); #endregion Assemble Chunks and convert to Arrays } } for (int i = 0; i < VertexArray.Length; i++) { Vector3d.Add(ref VertexArray[i].Position, ref offset, out VertexArray[i].Position); } } private void GetDefaultVertices(eDir s, double scale, out VertexT2dN3dV3d first, out VertexT2dN3dV3d second, out VertexT2dN3dV3d third) { VertexT2dN3dV3d t1 = new VertexT2dN3dV3d(), t2 = new VertexT2dN3dV3d(), t3 = new VertexT2dN3dV3d(); switch (s) { case eDir.FrontTopRight: t1 = new VertexT2dN3dV3d(new Vector2d(0.5, 1.0), Vector3d.UnitY, Vector3d.UnitY * scale); t2 = new VertexT2dN3dV3d(new Vector2d(0.0, 0.0), Vector3d.UnitZ, Vector3d.UnitZ * scale); t3 = new VertexT2dN3dV3d(new Vector2d(0.5, 0.0), Vector3d.UnitX, Vector3d.UnitX * scale); break; case eDir.FrontBottomRight: t1 = new VertexT2dN3dV3d(new Vector2d(0.5, 0.0), Vector3d.UnitX, Vector3d.UnitX * scale); t2 = new VertexT2dN3dV3d(new Vector2d(0.0, 0.0), Vector3d.UnitZ, Vector3d.UnitZ * scale); t3 = new VertexT2dN3dV3d(new Vector2d(0.5, 1.0), -Vector3d.UnitY, -Vector3d.UnitY * scale); break; case eDir.FrontBottomLeft: t1 = new VertexT2dN3dV3d(new Vector2d(0.5, 0.0), Vector3d.UnitX, Vector3d.UnitX * scale); t2 = new VertexT2dN3dV3d(new Vector2d(0.5, 1.0), -Vector3d.UnitY, -Vector3d.UnitY * scale); t3 = new VertexT2dN3dV3d(new Vector2d(1.0, 0.0), -Vector3d.UnitZ, -Vector3d.UnitZ * scale); break; case eDir.FrontTopLeft: t1 = new VertexT2dN3dV3d(new Vector2d(1.0, 0.0), -Vector3d.UnitZ, -Vector3d.UnitZ * scale); t2 = new VertexT2dN3dV3d(new Vector2d(0.5, 1.0), Vector3d.UnitY, Vector3d.UnitY * scale); t3 = new VertexT2dN3dV3d(new Vector2d(0.5, 0.0), Vector3d.UnitX, Vector3d.UnitX * scale); break; case eDir.BackTopRight: t1 = new VertexT2dN3dV3d(new Vector2d(0.5, 1.0), Vector3d.UnitY, Vector3d.UnitY * scale); t2 = new VertexT2dN3dV3d(new Vector2d(0.0, 1.0), -Vector3d.UnitX, -Vector3d.UnitX * scale); t3 = new VertexT2dN3dV3d(new Vector2d(0.0, 0.0), Vector3d.UnitZ, Vector3d.UnitZ * scale); break; case eDir.BackBottomRight: t1 = new VertexT2dN3dV3d(new Vector2d(0.5, 1.0), -Vector3d.UnitY, -Vector3d.UnitY * scale); t2 = new VertexT2dN3dV3d(new Vector2d(0.0, 0.0), Vector3d.UnitZ, Vector3d.UnitZ * scale); t3 = new VertexT2dN3dV3d(new Vector2d(0.0, 1.0), -Vector3d.UnitX, -Vector3d.UnitX * scale); break; case eDir.BackBottomLeft: t1 = new VertexT2dN3dV3d(new Vector2d(0.5, 1.0), -Vector3d.UnitY, -Vector3d.UnitY * scale); t2 = new VertexT2dN3dV3d(new Vector2d(1.0, 1.0), -Vector3d.UnitX, -Vector3d.UnitX * scale); t3 = new VertexT2dN3dV3d(new Vector2d(1.0, 0.0), -Vector3d.UnitZ, -Vector3d.UnitZ * scale); break; case eDir.BackTopLeft: t1 = new VertexT2dN3dV3d(new Vector2d(0.5, 1.0), Vector3d.UnitY, Vector3d.UnitY * scale); t2 = new VertexT2dN3dV3d(new Vector2d(1.0, 0.0), -Vector3d.UnitZ, -Vector3d.UnitZ * scale); t3 = new VertexT2dN3dV3d(new Vector2d(1.0, 1.0), -Vector3d.UnitX, -Vector3d.UnitX * scale); break; } first = t1; second = t2; third = t3; } private void Subdivide(double Scale, ref VertexT2dN3dV3d first, ref VertexT2dN3dV3d second, ref VertexT2dN3dV3d third, out Chunk c) { c = new Chunk(6, 12); c.Vertices[0] = first; Vector3d.Lerp(ref first.Position, ref second.Position, 0.5, out c.Vertices[1].Normal); c.Vertices[1].Normal.Normalize(); c.Vertices[1].Position = c.Vertices[1].Normal * Scale; Vector2d.Lerp(ref first.TexCoord, ref second.TexCoord, 0.5, out c.Vertices[1].TexCoord); Vector3d.Lerp(ref third.Position, ref first.Position, 0.5, out c.Vertices[2].Normal); c.Vertices[2].Normal.Normalize(); c.Vertices[2].Position = c.Vertices[2].Normal * Scale; Vector2d.Lerp(ref third.TexCoord, ref first.TexCoord, 0.5, out c.Vertices[2].TexCoord); c.Vertices[3] = second; Vector3d.Lerp(ref second.Position, ref third.Position, 0.5, out c.Vertices[4].Normal); c.Vertices[4].Normal.Normalize(); c.Vertices[4].Position = c.Vertices[4].Normal * Scale; Vector2d.Lerp(ref second.TexCoord, ref third.TexCoord, 0.5, out c.Vertices[4].TexCoord); c.Vertices[5] = third; #region Indices c.Indices[0] = 0; c.Indices[1] = 1; c.Indices[2] = 2; c.Indices[3] = 2; c.Indices[4] = 1; c.Indices[5] = 4; c.Indices[6] = 1; c.Indices[7] = 3; c.Indices[8] = 4; c.Indices[9] = 2; c.Indices[10] = 4; c.Indices[11] = 5; #endregion Indices } } }
46.027473
143
0.516295
[ "MIT" ]
prepare/MiniAggLegacy
a_mini/projects/PixelFarm/MiniAgg.HardwareGraphics/OpenTkEssTest/Shapes/SlicedSphere.cs
8,377
C#
//using Raider.Extensions; //using System; //using System.Collections.Generic; //using System.Reflection; //using System.Threading.Tasks; //namespace Raider.Reflection //{ // public sealed class ObjectWrapper // { // public TypeWrapper TypeWrapper { get; } // public object TargetInstance { get; private set; } // public ObjectWrapper BaseObjectWrapper { get; private set; } // public bool AllowMemberTypeCasting // { // get // { // return TypeWrapper.AllowMemberTypeCasting; // } // set // { // TypeWrapper.AllowMemberTypeCasting = value; // } // } // public Type Type => TypeWrapper.Type; // private ObjectWrapper(TypeWrapper typeWrapper, object innerObject, bool allowMemberTypeCasting) // { // this.TypeWrapper = typeWrapper; // this.TargetInstance = innerObject; // this.AllowMemberTypeCasting = allowMemberTypeCasting; // } // public ObjectWrapper SetTargetInstance(object instance) // { // if (instance == null) // TargetInstance = null; // else if (instance.GetType() == TypeWrapper.Type) // TargetInstance = instance; // else // throw new ArgumentException($"{instance} type {instance.GetType().FullName} must be type of {TypeWrapper.Type.FullName}"); // return this; // } // //internal ObjectWrapper(TypeWrapper typeWrapper, ref object innerObject, bool allowMemberTypeCasting) // //{ // // this.typeWrapper = typeWrapper; // // this.innerObject = innerObject; // // this.AllowMemberTypeCasting = allowMemberTypeCasting; // //} // public static ObjectWrapper Create(Type objType, bool includeAllBaseTypes = false, List<System.Type> allowedBaseTypes = null, bool suppressExceptions = false, bool allowMemberTypeCasting = false) // { // return Create(objType, null, includeAllBaseTypes, allowedBaseTypes, suppressExceptions, allowMemberTypeCasting); // } // public static ObjectWrapper Create(Type objType, TypeWrapper tw, bool includeAllBaseTypes = false, List<System.Type> allowedBaseTypes = null, bool suppressExceptions = false, bool allowMemberTypeCasting = false) // { // if (!objType.IsClass && !objType.IsStruct()) // { // throw new InvalidOperationException(objType.ToFriendlyFullName()); // } // if (tw == null) // { // tw = TypeWrapper.Create(objType, suppressExceptions, allowMemberTypeCasting); // } // else // { // if (tw.Type != objType) // { // throw new Exception($"Type of ObjectWrapper {objType.ToFriendlyFullName()} is not equal to TypeWrapper type {tw.Type.ToFriendlyFullName()}"); // } // } // ObjectWrapper result = new ObjectWrapper(tw, null, allowMemberTypeCasting); // System.Type baseObjType = objType.BaseType; // if (includeAllBaseTypes || (allowedBaseTypes != null && allowedBaseTypes.Contains(baseObjType))) // { // try // { // if (baseObjType != null && baseObjType != typeof(object)) // { // result.BaseObjectWrapper = ObjectWrapper.CreateBaseObject(objType, baseObjType, allowedBaseTypes, suppressExceptions, allowMemberTypeCasting); // } // } // catch { } // } // return result; // } // private static ObjectWrapper CreateBaseObject(Type objType, System.Type baseType, List<System.Type> allowedBaseTypes, bool suppressExceptions, bool allowMemberTypeCasting) // { // if (!baseType.IsClass && !baseType.IsStruct()) // { // throw new InvalidOperationException(objType.ToFriendlyFullName()); // } // TypeWrapper tw = TypeWrapper.Create(baseType, suppressExceptions, allowMemberTypeCasting); // ObjectWrapper result = new ObjectWrapper(tw, null, allowMemberTypeCasting); // System.Type baseObjType = baseType.BaseType; // if (allowedBaseTypes == null || allowedBaseTypes.Contains(baseObjType)) // { // try // { // if (baseObjType != null && baseObjType != typeof(object)) // { // result.BaseObjectWrapper = ObjectWrapper.CreateBaseObject(objType, baseObjType, allowedBaseTypes, suppressExceptions, allowMemberTypeCasting); // } // } // catch { } // } // return result; // } // public static ObjectWrapper Create(object obj, bool includeAllBaseTypes = false, List<System.Type>? allowedBaseTypes = null, bool suppressExceptions = false, bool allowMemberTypeCasting = false) // { // return Create(obj, null, includeAllBaseTypes, allowedBaseTypes, suppressExceptions, allowMemberTypeCasting); // } // public static ObjectWrapper Create(object obj, TypeWrapper tw, bool includeAllBaseTypes = false, List<System.Type> allowedBaseTypes = null, bool suppressExceptions = false, bool allowMemberTypeCasting = false) // { // if (obj == null) throw new ArgumentNullException(nameof(obj)); // System.Type objType = obj.GetType(); // if (!objType.IsClass && !objType.IsStruct()) // { // throw new InvalidOperationException(objType.ToFriendlyFullName()); // } // if (tw == null) // { // tw = TypeWrapper.Create(objType, suppressExceptions, allowMemberTypeCasting); // } // else // { // if (tw.Type != objType) // { // throw new Exception($"Type of ObjectWrapper {objType.ToFriendlyFullName()} is not equal to TypeWrapper type {tw.Type.ToFriendlyFullName()}"); // } // } // ObjectWrapper result = new ObjectWrapper(tw, obj, allowMemberTypeCasting); // System.Type baseObjType = objType.BaseType; // if (includeAllBaseTypes || (allowedBaseTypes != null && allowedBaseTypes.Contains(baseObjType))) // { // try // { // if (baseObjType != null && baseObjType != typeof(object)) // { // result.BaseObjectWrapper = ObjectWrapper.CreateBaseObject(obj, baseObjType, allowedBaseTypes, suppressExceptions, allowMemberTypeCasting); // } // } // catch { } // } // return result; // } // private static ObjectWrapper CreateBaseObject(object obj, System.Type baseType, List<System.Type> allowedBaseTypes, bool suppressExceptions, bool allowMemberTypeCasting) // { // if (obj == null) throw new ArgumentNullException(nameof(obj)); // if (!baseType.IsClass && !baseType.IsStruct()) // { // throw new InvalidOperationException(baseType.ToFriendlyFullName()); // } // TypeWrapper tw = TypeWrapper.Create(baseType, suppressExceptions, allowMemberTypeCasting); // ObjectWrapper result = new ObjectWrapper(tw, obj, allowMemberTypeCasting); // System.Type baseObjType = baseType.BaseType; // if (allowedBaseTypes == null || allowedBaseTypes.Contains(baseObjType)) // { // try // { // if (baseObjType != null && baseObjType != typeof(object)) // { // result.BaseObjectWrapper = ObjectWrapper.CreateBaseObject(obj, baseObjType, allowedBaseTypes, suppressExceptions, allowMemberTypeCasting); // } // } // catch { } // } // return result; // } // public static ObjectWrapper Create<T>(bool includeAllBaseTypes = false, List<System.Type> allowedBaseTypes = null, bool suppressExceptions = false, bool allowMemberTypeCasting = false) // { // return Create<T>(null, includeAllBaseTypes, allowedBaseTypes, suppressExceptions, allowMemberTypeCasting); // } // public static ObjectWrapper Create<T>(TypeWrapper tw, bool includeAllBaseTypes = false, List<System.Type> allowedBaseTypes = null, bool suppressExceptions = false, bool allowMemberTypeCasting = false) // { // Type objType = typeof(T); // if (!objType.IsClass && !objType.IsStruct()) // { // throw new InvalidOperationException(objType.ToFriendlyFullName()); // } // if (tw == null) // { // tw = TypeWrapper.Create(objType, suppressExceptions, allowMemberTypeCasting); // } // else // { // if (tw.Type != objType) // { // throw new Exception($"Type of ObjectWrapper {objType.ToFriendlyFullName()} is not equal to TypeWrapper type {tw.Type.ToFriendlyFullName()}"); // } // } // ObjectWrapper result = new ObjectWrapper(tw, null, allowMemberTypeCasting); // System.Type baseObjType = objType.BaseType; // if (includeAllBaseTypes || (allowedBaseTypes != null && allowedBaseTypes.Contains(baseObjType))) // { // try // { // if (baseObjType != null && baseObjType != typeof(object)) // { // result.BaseObjectWrapper = ObjectWrapper.CreateBaseObject<T>(baseObjType, allowedBaseTypes, suppressExceptions, allowMemberTypeCasting); // } // } // catch { } // } // return result; // } // private static ObjectWrapper CreateBaseObject<T>(System.Type baseType, List<System.Type> allowedBaseTypes, bool suppressExceptions, bool allowMemberTypeCasting) // { // if (!baseType.IsClass && !baseType.IsStruct()) // { // throw new InvalidOperationException(baseType.ToFriendlyFullName()); // } // TypeWrapper tw = TypeWrapper.Create(baseType, suppressExceptions, allowMemberTypeCasting); // ObjectWrapper result = new ObjectWrapper(tw, null, allowMemberTypeCasting); // System.Type baseObjType = baseType.BaseType; // if (allowedBaseTypes == null || allowedBaseTypes.Contains(baseObjType)) // { // try // { // if (baseObjType != null && baseObjType != typeof(object)) // { // result.BaseObjectWrapper = ObjectWrapper.CreateBaseObject<T>(baseObjType, allowedBaseTypes, suppressExceptions, allowMemberTypeCasting); // } // } // catch { } // } // return result; // } // //internal static ObjectWrapper CreateFromStruct(ref object obj) // //{ // // TypeWrapper tw = TypeWrapper.Create(obj.GetType()); // // return new ObjectWrapper(tw, ref obj); // //} // public object this[string name] // { // get // { // return TypeWrapper[TargetInstance, name]; // } // set // { // TypeWrapper[TargetInstance, name] = value; // } // } // #region InvokeMethods // public void InvokeMethod(string methodName) // => TypeWrapper.InvokeMethod(TargetInstance, methodName, (Type[])null, (object[])null); // public void InvokeMethod(string methodName, Type methodParameterType, object methodParameter) // => TypeWrapper.InvokeMethod(TargetInstance, methodName, new Type[] { methodParameterType }, new object[] { methodParameter }); // public object InvokeMethod(string methodName, Type[] methodParameterTypes, object[] methodParameters) // => TypeWrapper.InvokeMethod(TargetInstance, methodName, methodParameterTypes, methodParameters); // public void InvokeGenericMethod(string methodName, Type[] methodGenericTypes) // => TypeWrapper.InvokeGenericMethod(TargetInstance, methodName, methodGenericTypes, (Type[])null, (object[])null); // public void InvokeGenericMethod(string methodName, Type[] methodGenericTypes, Type methodParameterType, object methodParameter) // => TypeWrapper.InvokeGenericMethod(TargetInstance, methodName, methodGenericTypes, new Type[] { methodParameterType }, new object[] { methodParameter }); // public object InvokeGenericMethod(string methodName, Type[] methodGenericTypes, Type[] methodParameterTypes, object[] methodParameters) // => TypeWrapper.InvokeGenericMethod(TargetInstance, methodName, methodGenericTypes, methodParameterTypes, methodParameters); // public async Task InvokeMethodAsync(string methodName) // => await TypeWrapper.InvokeMethodAsync(TargetInstance, methodName, (Type[])null, (object[])null); // public async Task InvokeMethodAsync(string methodName, Type methodParameterType, object methodParameter) // => await TypeWrapper.InvokeMethodAsync(TargetInstance, methodName, new Type[] { methodParameterType }, new object[] { methodParameter }); // public async Task<object> InvokeMethodAsync(string methodName, Type[] methodParameterTypes, object[] methodParameters) // => await TypeWrapper.InvokeMethodAsync(TargetInstance, methodName, methodParameterTypes, methodParameters); // public async Task InvokeGenericMethodAsync(string methodName, Type[] methodGenericTypes) // => await TypeWrapper.InvokeGenericMethodAsync(TargetInstance, methodName, methodGenericTypes, (Type[])null, (object[])null); // public async Task InvokeGenericMethodAsync(string methodName, Type[] methodGenericTypes, Type methodParameterType, object methodParameter) // => await TypeWrapper.InvokeGenericMethodAsync(TargetInstance, methodName, methodGenericTypes, new Type[] { methodParameterType }, new object[] { methodParameter }); // public async Task<object> InvokeGenericMethodAsync(string methodName, Type[] methodGenericTypes, Type[] methodParameterTypes, object[] methodParameters) // => await TypeWrapper.InvokeGenericMethodAsync(TargetInstance, methodName, methodGenericTypes, methodParameterTypes, methodParameters); // #endregion InvokeMethods // public Dictionary<string, Type> GetAllMemberTypes() // => TypeWrapper.GetAllMemberTypes(); // public List<string> GetAllMemberNames() // => TypeWrapper.GetAllMemberNames(); // public MemberInfo GetMember(string memberName) // => TypeWrapper.GetMember(memberName); // public Type GetMemberType(string memberName) // => TypeWrapper.GetMemberType(memberName); // public Dictionary<string, Type> GetAllPropertyTypes() // => TypeWrapper.GetAllPropertyTypes(); // public List<string> GetAllPropertyNames() // => TypeWrapper.GetAllPropertyNames(); // public List<PropertyInfo> GetAllPropertyInfos() // => TypeWrapper.GetAllPropertyInfos(); // public PropertyInfo GetPropertyInfo(string propertyName) // => TypeWrapper.GetPropertyInfo(propertyName); // public Type GetPropertyType(string propertyName) // => TypeWrapper.GetPropertyType(propertyName); // public Dictionary<string, Type> GetPublicProperties() // => TypeWrapper.GetPublicPropertyTypes(); // public Dictionary<string, Type> GetPublicPropertiesWithSetters() // => TypeWrapper.GetPublicPropertyTypesWithSetters(); // public Dictionary<string, Type> GetAllFieldTypes() // => TypeWrapper.GetAllFieldTypes(); // public List<string> GetAllFieldNames() // => TypeWrapper.GetAllFieldNames(); // public List<FieldInfo> GetAllFieldInfos() // => TypeWrapper.GetAllFieldInfos(); // public FieldInfo GetFieldInfo(string fieldName) // => TypeWrapper.GetFieldInfo(fieldName); // public Type GetFieldType(string fieldName) // => TypeWrapper.GetFieldType(fieldName); // public Dictionary<string, Type> GetPublicFieldTypes() // => TypeWrapper.GetPublicFieldTypes(); // public ConstructorInfo GetConstructorInfo(params Type[] paramTypes) // => TypeWrapper.GetConstructorInfo(paramTypes); // public List<MethodInfo> GetAllMethodInfos() // => TypeWrapper.GetAllMethodInfos(); // public MethodInfo GetMethodInfo(string methodName, params Type[] paramTypes) // => TypeWrapper.GetMethodInfo(methodName, paramTypes); // public MethodInfo GetGenericMethodInfo(string methodName, Type[] genericTypes, params Type[] paramTypes) // => TypeWrapper.GetGenericMethodInfo(methodName, genericTypes, paramTypes); // public PropertyWrapper GetPropertyWrapper(string propertyName) // => TypeWrapper.GetPropertyWrapper(propertyName); // public FieldWrapper GetFieldWrapper(string fieldName) // => TypeWrapper.GetFieldWrapper(fieldName); // public ConstructorWrapper GetConstructorWrapper(params Type[] paramTypes) // => TypeWrapper.GetConstructorWrapper(paramTypes); // public MethodWrapper GetMethodWrapper(string methodName, params Type[] paramTypes) // => TypeWrapper.GetMethodWrapper(methodName, paramTypes); // public MethodWrapper GetGenericMethodWrapper(string methodName, Type[] genericTypes, Type[] paramTypes, out MethodInfo genericMethodInfo) // => TypeWrapper.GetGenericMethodWrapper(methodName, genericTypes, paramTypes, out genericMethodInfo); // } //}
44.859375
221
0.648787
[ "Apache-2.0" ]
raider-net/Raider
src/Raider.Core/Reflection/Wrappers/ObjectWrapperOLD.cs
17,228
C#
using System; using System.Net; namespace Peek { public static class StatusCodeExtensions { public static string ToStatusCodeText(this int statusCode) { string statusCodeText; // Negative status code means incorret content, but it's only relevant if the site is otherwise running if (statusCode < 0 && Math.Abs(statusCode) < 300) { var sc = (HttpStatusCode)Math.Abs(statusCode); statusCodeText = $"{sc} - Incorrect content"; } else { var sc = (HttpStatusCode)Math.Abs(statusCode); statusCodeText = $"{sc}"; } return statusCodeText; } } public static class DateTimeExtensions { public static string FormattedDate(this DateTime date) { return date.ToString("yyyy-MM-dd HH:mm:ss"); } public static DateTime Update(this DateTime nextNotification) { return DateTime.Now > nextNotification ? nextNotification.AddSeconds(Program.slackReportInterval) : nextNotification; } } public static class StringExtensions { public static string Sanitize(this string s) { return s.TrimStart(new char[] { ',' }).TrimEnd(new char[] { '/' }).Trim(); } } }
29.510638
129
0.566691
[ "MIT" ]
drm-nz/peek
Extensions.cs
1,389
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace EddiDataDefinitions.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class CQCRatings { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal CQCRatings() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("EddiDataDefinitions.Properties.CQCRatings", typeof(CQCRatings).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Amateur. /// </summary> public static string Amateur { get { return ResourceManager.GetString("Amateur", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Champion. /// </summary> public static string Champion { get { return ResourceManager.GetString("Champion", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Elite. /// </summary> public static string Elite { get { return ResourceManager.GetString("Elite", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Helpless. /// </summary> public static string Helpless { get { return ResourceManager.GetString("Helpless", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Hero. /// </summary> public static string Hero { get { return ResourceManager.GetString("Hero", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Legend. /// </summary> public static string Legend { get { return ResourceManager.GetString("Legend", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Mostly Helpless. /// </summary> public static string MostlyHelpless { get { return ResourceManager.GetString("MostlyHelpless", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Professional. /// </summary> public static string Professional { get { return ResourceManager.GetString("Professional", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Semi-professional. /// </summary> public static string SemiProfessional { get { return ResourceManager.GetString("SemiProfessional", resourceCulture); } } } }
36.744828
187
0.55762
[ "Apache-2.0" ]
BullZye54/EDDI
DataDefinitions/Properties/CQCRatings.Designer.cs
5,330
C#
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ using NMF.Collections.Generic; using NMF.Collections.ObjectModel; using NMF.Expressions; using NMF.Expressions.Linq; using NMF.Models; using NMF.Models.Collections; using NMF.Models.Expressions; using NMF.Models.Meta; using NMF.Models.Repository; using NMF.Serialization; using NMF.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Linq; using TTC2017.SmartGrids.CIM.IEC61970.ControlArea; using TTC2017.SmartGrids.CIM.IEC61970.Core; using TTC2017.SmartGrids.CIM.IEC61970.Generation.GenerationDynamics; using TTC2017.SmartGrids.CIM.IEC61970.Informative.EnergyScheduling; using TTC2017.SmartGrids.CIM.IEC61970.Informative.Financial; using TTC2017.SmartGrids.CIM.IEC61970.Informative.MarketOperations; using TTC2017.SmartGrids.CIM.IEC61970.Wires; namespace TTC2017.SmartGrids.CIM.IEC61970.Generation.Production { public class ReservoirSpillsIntoReservoirsCollection : ObservableOppositeOrderedSet<IReservoir, IReservoir> { public ReservoirSpillsIntoReservoirsCollection(IReservoir parent) : base(parent) { } private void OnItemDeleted(object sender, System.EventArgs e) { this.Remove(((IReservoir)(sender))); } protected override void SetOpposite(IReservoir item, IReservoir parent) { if ((parent != null)) { item.Deleted += this.OnItemDeleted; item.SpillsFromReservoir = parent; } else { item.Deleted -= this.OnItemDeleted; if ((item.SpillsFromReservoir == this.Parent)) { item.SpillsFromReservoir = parent; } } } } }
31.917808
111
0.633047
[ "MIT" ]
georghinkel/ttc2017smartGrids
generator/Schema/IEC61970/Generation/Production/ReservoirSpillsIntoReservoirsCollection.cs
2,332
C#
// The MIT License (MIT) // // Copyright (c) 2014-2017, Institute for Software & Systems Engineering // // 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. namespace Tests.Serialization.RuntimeModels { using System.Collections.Generic; using SafetySharp.Modeling; using SafetySharp.Runtime; using Shouldly; using Utilities; internal class CyclicHierarchy : TestModel { private static bool _hasConstructorRun; protected override void Check() { var c = new C { F = 33 }; var d = new D { C = c }; var e = new E { C = new [] { c} }; var f = new F { E = e }; c.D = d; c.E = new List<E> {e}; e.F = f; var m = InitializeModel(d); _hasConstructorRun = false; Create(m); ExecutableStateFormulas.ShouldBeEmpty(); RootComponents.Length.ShouldBe(1); var root = RootComponents[0]; root.ShouldBeOfType<D>(); ((D)root).C.ShouldBeOfType<C>(); ((D)root).C.D.ShouldBeOfType<D>(); ((D)root).C.D.ShouldBe((D)root); ((D)root).C.F.ShouldBe(33); root.GetSubcomponents().ShouldBe(new[] { ((D)root).C }); ((D)root).C.GetSubcomponents().ShouldBe(new[] { root }); _hasConstructorRun.ShouldBe(false); } private class C : Component { public D D; public int F; public List<E> E; public C() { _hasConstructorRun = true; } } private class D : Component { public C C; public D() { _hasConstructorRun = true; } } private class E { public C[] C; public F F; public E() { _hasConstructorRun = true; } } private class F { public E E; public F() { _hasConstructorRun = true; } } } }
24.422018
80
0.672051
[ "MIT" ]
isse-augsburg/ssharp
SafetySharpTests/Serialization/RuntimeModels/cyclic hierarchy.cs
2,664
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup { internal sealed partial class EventHookupSessionManager { /// <summary> /// A session begins when an '=' is typed after a '+' and requires determining whether the /// += is being used to add an event handler to an event. If it is, then we also determine /// a candidate name for the event handler. /// </summary> internal class EventHookupSession : ForegroundThreadAffinitizedObject { public readonly Task<string> GetEventNameTask; private readonly CancellationTokenSource _cancellationTokenSource; private readonly ITrackingPoint _trackingPoint; private readonly ITrackingSpan _trackingSpan; private readonly ITextView _textView; private readonly ITextBuffer _subjectBuffer; public event Action Dismissed = () => { }; // For testing purposes only! Should always be null except in tests. internal Mutex TESTSessionHookupMutex = null; public ITrackingPoint TrackingPoint { get { AssertIsForeground(); return _trackingPoint; } } public ITrackingSpan TrackingSpan { get { AssertIsForeground(); return _trackingSpan; } } public ITextView TextView { get { AssertIsForeground(); return _textView; } } public ITextBuffer SubjectBuffer { get { AssertIsForeground(); return _subjectBuffer; } } public void Cancel() { AssertIsForeground(); _cancellationTokenSource.Cancel(); } public EventHookupSession( EventHookupSessionManager eventHookupSessionManager, EventHookupCommandHandler commandHandler, ITextView textView, ITextBuffer subjectBuffer, IAsynchronousOperationListener asyncListener, Mutex testSessionHookupMutex) : base(eventHookupSessionManager.ThreadingContext) { AssertIsForeground(); _cancellationTokenSource = new CancellationTokenSource(); _textView = textView; _subjectBuffer = subjectBuffer; this.TESTSessionHookupMutex = testSessionHookupMutex; var document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null && document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.ChangeDocument)) { var position = textView.GetCaretPoint(subjectBuffer).Value.Position; _trackingPoint = textView.TextSnapshot.CreateTrackingPoint(position, PointTrackingMode.Negative); _trackingSpan = textView.TextSnapshot.CreateTrackingSpan(new Span(position, 1), SpanTrackingMode.EdgeInclusive); var asyncToken = asyncListener.BeginAsyncOperation(GetType().Name + ".Start"); this.GetEventNameTask = Task.Factory.SafeStartNewFromAsync( () => DetermineIfEventHookupAndGetHandlerNameAsync(document, position, _cancellationTokenSource.Token), _cancellationTokenSource.Token, TaskScheduler.Default); var continuedTask = this.GetEventNameTask.SafeContinueWithFromAsync( async t => { await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, _cancellationTokenSource.Token); _cancellationTokenSource.Token.ThrowIfCancellationRequested(); if (t.Result != null) { commandHandler.EventHookupSessionManager.EventHookupFoundInSession(this); } }, _cancellationTokenSource.Token, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); continuedTask.CompletesAsyncOperation(asyncToken); } else { _trackingPoint = textView.TextSnapshot.CreateTrackingPoint(0, PointTrackingMode.Negative); _trackingSpan = textView.TextSnapshot.CreateTrackingSpan(new Span(), SpanTrackingMode.EdgeInclusive); this.GetEventNameTask = SpecializedTasks.Default<string>(); eventHookupSessionManager.CancelAndDismissExistingSessions(); } } private async Task<string> DetermineIfEventHookupAndGetHandlerNameAsync(Document document, int position, CancellationToken cancellationToken) { AssertIsBackground(); // For test purposes only! if (TESTSessionHookupMutex != null) { TESTSessionHookupMutex.WaitOne(); TESTSessionHookupMutex.ReleaseMutex(); } using (Logger.LogBlock(FunctionId.EventHookup_Determine_If_Event_Hookup, cancellationToken)) { var plusEqualsToken = await GetPlusEqualsTokenInsideAddAssignExpressionAsync(document, position, cancellationToken).ConfigureAwait(false); if (plusEqualsToken == null) { return null; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var eventSymbol = GetEventSymbol(semanticModel, plusEqualsToken.Value, cancellationToken); if (eventSymbol == null) { return null; } return GetEventHandlerName(eventSymbol, plusEqualsToken.Value, semanticModel, document.GetLanguageService<ISyntaxFactsService>()); } } private async Task<SyntaxToken?> GetPlusEqualsTokenInsideAddAssignExpressionAsync(Document document, int position, CancellationToken cancellationToken) { AssertIsBackground(); var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); if (token.Kind() != SyntaxKind.PlusEqualsToken) { return null; } if (!token.Parent.IsKind(SyntaxKind.AddAssignmentExpression)) { return null; } return token; } private IEventSymbol GetEventSymbol(SemanticModel semanticModel, SyntaxToken plusEqualsToken, CancellationToken cancellationToken) { AssertIsBackground(); var parentToken = plusEqualsToken.Parent as AssignmentExpressionSyntax; if (parentToken == null) { return null; } var symbol = semanticModel.GetSymbolInfo(parentToken.Left, cancellationToken).Symbol; if (symbol == null) { return null; } return symbol as IEventSymbol; } private string GetEventHandlerName(IEventSymbol eventSymbol, SyntaxToken plusEqualsToken, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService) { AssertIsBackground(); var basename = string.Format("{0}_{1}", GetNameObjectPart(eventSymbol, plusEqualsToken, semanticModel, syntaxFactsService), eventSymbol.Name); basename = basename.ToPascalCase(trimLeadingTypePrefix: false); var reservedNames = semanticModel.LookupSymbols(plusEqualsToken.SpanStart).Select(m => m.Name); return NameGenerator.EnsureUniqueness(basename, reservedNames); } /// <summary> /// Take another look at the LHS of the += node -- we need to figure out a default name /// for the event handler, and that's usually based on the object (which is usually a /// field of 'this', but not always) to which the event belongs. So, if the event is /// something like 'button1.Click' or 'this.listBox1.Select', we want the names /// 'button1' and 'listBox1' respectively. If the field belongs to 'this', then we use /// the name of this class, as we do if we can't make any sense out of the parse tree. /// </summary> private string GetNameObjectPart(IEventSymbol eventSymbol, SyntaxToken plusEqualsToken, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService) { AssertIsBackground(); var parentToken = plusEqualsToken.Parent as AssignmentExpressionSyntax; if (parentToken.Left is MemberAccessExpressionSyntax memberAccessExpression) { // This is expected -- it means the last thing is(probably) the event name. We // already have that in eventSymbol. What we need is the LHS of that dot. var lhs = memberAccessExpression.Expression; if (lhs is MemberAccessExpressionSyntax lhsMemberAccessExpression) { // Okay, cool. The name we're after is in the RHS of this dot. return lhsMemberAccessExpression.Name.ToString(); } if (lhs is NameSyntax lhsNameSyntax) { // Even easier -- the LHS of the dot is the name itself return lhsNameSyntax.ToString(); } } // If we didn't find an object name above, then the object name is the name of this class. // Note: For generic, it's ok(it's even a good idea) to exclude type variables, // because the name is only used as a prefix for the method name. var typeDeclaration = syntaxFactsService.GetContainingTypeDeclaration( semanticModel.SyntaxTree.GetRoot(), plusEqualsToken.SpanStart) as BaseTypeDeclarationSyntax; return typeDeclaration != null ? typeDeclaration.Identifier.Text : eventSymbol.ContainingType.Name; } } } }
44.977612
170
0.587938
[ "Apache-2.0" ]
DustinCampbell/roslyn
src/VisualStudio/CSharp/Impl/EventHookup/EventHookupSessionManager_EventHookupSession.cs
12,056
C#
using System; using static System.Console; using System.IO; using System.Diagnostics; using System.Linq; using System.Collections.Generic; using System.Numerics; namespace AoC { using Screen = Dictionary<Complex, Tile>; class Memory { public Memory(long[] memory) => _memory = memory.Select((value, index) => (value, index)) .ToDictionary(pair => (long)pair.index, pair => (long)pair.value); public long this[long key] { get { if (!_memory.ContainsKey(key)) _memory[key] = 0; return _memory[key]; } set => _memory[key] = value; } private IDictionary<long, long> _memory; } class IntCodeComputer { public bool Running { get; private set; } = true; public bool Polling { get; private set; } public bool Outputing { get; private set; } public IntCodeComputer(long[] memory, IEnumerable<long> input = default(List<long>)) { _memory = new Memory(memory); _input = new Queue<long>(input ?? new long[0]); _output = new Stack<long>(); } public long Run() { while (Running) Tick(); return _output.Pop(); } public void AddInput(int value) => _input.Enqueue(value); public IEnumerable<long> GetOutputs() => _output.ToArray(); public long GetOutput() { Outputing = false; return _output.Pop(); } public void Tick() { if (!Running) return; var instruction = _memory[_pointer]; var (opCode, p1Mode, p2Mode, p3mode) = ((int)instruction % 100, (int)(instruction / 100) % 10, (int)(instruction / 1000) % 10, (int)(instruction / 10000) % 10); switch (opCode) { case 1: // ADD _memory[GetAddress(3, p3mode)] = GetParameter(1, p1Mode) + GetParameter(2, p2Mode); _pointer += 4; break; case 2: // MUL _memory[GetAddress(3, p3mode)] = GetParameter(1, p1Mode) * GetParameter(2, p2Mode); _pointer += 4; break; case 3: // INPUT if (_input.Any()) { Polling = false; _memory[GetAddress(1, p1Mode)] = _input.Dequeue(); _pointer += 2; } else Polling = true; break; case 4: // OUTPUT Outputing = true; _output.Push(GetParameter(1, p1Mode)); _pointer += 2; break; case 5: // JMP_TRUE if (GetParameter(1, p1Mode) != 0) _pointer = GetParameter(2, p2Mode); else _pointer += 3; break; case 6: // JMP_FALSE if (GetParameter(1, p1Mode) == 0) _pointer = GetParameter(2, p2Mode); else _pointer += 3; break; case 7: // LESS_THAN _memory[GetAddress(3, p3mode)] = GetParameter(1, p1Mode) < GetParameter(2, p2Mode) ? 1 : 0; _pointer += 4; break; case 8: // LESS_THAN _memory[GetAddress(3, p3mode)] = GetParameter(1, p1Mode) == GetParameter(2, p2Mode) ? 1 : 0; _pointer += 4; break; case 9: _base += GetParameter(1, p1Mode); _pointer += 2; break; case 99: // HATL Running = false; break; default: throw new Exception($"Unknown instruction {_pointer} {opCode}"); } } private Memory _memory; private Queue<long> _input; private Stack<long> _output; private long _pointer; private long _base; private long GetAddress(int offset, int mode) { var value = _memory[_pointer + offset]; switch (mode) { case 0: // POSITION return value; case 2: // RELATIVE return _base + value; default: throw new Exception($"Unrecognized address mode '{mode}'"); } } private long GetParameter(int offset, int mode) { var value = _memory[_pointer + offset]; switch (mode) { case 0: // POSITION return _memory[value]; case 1: // IMMEDIATE return value; case 2: // RELATIVE return _memory[_base + value]; default: throw new Exception($"Unrecognized parameter mode '{mode}'"); } } } enum Tile { Empty, Wall, Block, Paddle, Ball } static class Program { static Dictionary<Tile, char> TILE_CHARS = new Dictionary<Tile, char> { { Tile.Empty, '.' }, { Tile.Wall, 'W' }, { Tile.Block, 'B' }, { Tile.Paddle, 'P' }, { Tile.Ball, 'X' } }; static void PrintScreen(Screen screen) { var maxX = (int)(screen.Keys.Max(p => p.Real)); var minX = (int)(screen.Keys.Min(p => p.Real)); var maxY = (int)(screen.Keys.Max(p => p.Imaginary)); var minY = (int)(screen.Keys.Min(p => p.Imaginary)); for (var y = minY; y < maxY + 1; y++) { for (var x = minX; x < maxX + 1; x++) { var c = ' '; var position = new Complex(x, y); if (screen.ContainsKey(position)) c = TILE_CHARS[screen[position]]; Write(c); } WriteLine(); } WriteLine(); ReadLine(); } static (int blocks, long score) RunGame(long[] memory) { var cabinet = new IntCodeComputer(memory); var screen = new Screen(); var currentOuput = new Stack<long>(); var ball = 0L; var paddle = 0L; var score = 0L; while (cabinet.Running) { cabinet.Tick(); if (cabinet.Polling) { var joystick = 0; if (ball > paddle) joystick = 1; else if (ball < paddle) joystick = -1; cabinet.AddInput(joystick); } if (cabinet.Outputing) { currentOuput.Push(cabinet.GetOutput()); if (currentOuput.Count == 3) { var value = currentOuput.Pop(); var y = currentOuput.Pop(); var x = currentOuput.Pop(); if (x == -1) score = value; else { var tile = (Tile)value; if (tile == Tile.Ball) ball = x; else if (tile == Tile.Paddle) paddle = x; screen[new Complex(x, y)] = tile; } } } } return (screen.Values.Count(tile => tile == Tile.Block), score); } static (long, long) Solve(long[] memory) { var part1Result = RunGame(memory).blocks; memory[0] = 2; return (part1Result, RunGame(memory).score); } static long[] GetInput(string filePath) => !File.Exists(filePath) ? throw new FileNotFoundException(filePath) : File.ReadAllText(filePath).Trim().Split(",").Select(long.Parse).ToArray(); static void Main(string[] args) { if (args.Length != 1) throw new Exception("Please, add input file path as parameter"); var watch = Stopwatch.StartNew(); var (part1Result, part2Result) = Solve(GetInput(args[0])); watch.Stop(); WriteLine($"P1: {part1Result}"); WriteLine($"P2: {part2Result}"); WriteLine(); WriteLine($"Time: {(double)watch.ElapsedTicks / 100 / TimeSpan.TicksPerSecond:f7}"); } } }
34.702602
173
0.41564
[ "CC0-1.0" ]
Bigsby/aoc
2019/13/cs/Program.cs
9,337
C#
// Copyright 2021 Google LLC // // 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 // // 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. // Generated code. DO NOT EDIT! namespace Google.Cloud.Tasks.V2Beta2.Snippets { using System.Threading.Tasks; using gctv = Google.Cloud.Tasks.V2Beta2; public sealed partial class GeneratedCloudTasksClientStandaloneSnippets { /// <summary>Snippet for GetTaskAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task GetTaskResourceNamesAsync() { // Create client CloudTasksClient cloudTasksClient = await CloudTasksClient.CreateAsync(); // Initialize request argument(s) TaskName name = TaskName.FromProjectLocationQueueTask("[PROJECT]", "[LOCATION]", "[QUEUE]", "[TASK]"); // Make the request gctv::Task response = await cloudTasksClient.GetTaskAsync(name); } } }
39
114
0.686538
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/tasks/v2beta2/google-cloud-tasks-v2beta2-csharp/Google.Cloud.Tasks.V2Beta2.StandaloneSnippets/CloudTasksClient.GetTaskResourceNamesAsyncSnippet.g.cs
1,560
C#
/* * Location API * * Geolocation, Geocoding and Maps * * OpenAPI spec version: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ using NUnit.Framework; using System; using System.Linq; using System.IO; using System.Collections.Generic; using unwired.Api; using unwired.Model; using unwired.Client; using System.Reflection; using Newtonsoft.Json; namespace unwired.Test { /// <summary> /// Class for testing AddressDetailsSchema /// </summary> /// <remarks> /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// </remarks> [TestFixture] public class AddressDetailsSchemaTests { // TODO uncomment below to declare an instance variable for AddressDetailsSchema //private AddressDetailsSchema instance; /// <summary> /// Setup before each test /// </summary> [SetUp] public void Init() { // TODO uncomment below to create an instance of AddressDetailsSchema //instance = new AddressDetailsSchema(); } /// <summary> /// Clean up after each test /// </summary> [TearDown] public void Cleanup() { } /// <summary> /// Test an instance of AddressDetailsSchema /// </summary> [Test] public void AddressDetailsSchemaInstanceTest() { // TODO uncomment below to test "IsInstanceOfType" AddressDetailsSchema //Assert.IsInstanceOfType<AddressDetailsSchema> (instance, "variable 'instance' is a AddressDetailsSchema"); } /// <summary> /// Test the property 'Area' /// </summary> [Test] public void AreaTest() { // TODO unit test for the property 'Area' } /// <summary> /// Test the property 'Locality' /// </summary> [Test] public void LocalityTest() { // TODO unit test for the property 'Locality' } /// <summary> /// Test the property 'District' /// </summary> [Test] public void DistrictTest() { // TODO unit test for the property 'District' } /// <summary> /// Test the property 'County' /// </summary> [Test] public void CountyTest() { // TODO unit test for the property 'County' } /// <summary> /// Test the property 'City' /// </summary> [Test] public void CityTest() { // TODO unit test for the property 'City' } /// <summary> /// Test the property 'State' /// </summary> [Test] public void StateTest() { // TODO unit test for the property 'State' } /// <summary> /// Test the property 'Country' /// </summary> [Test] public void CountryTest() { // TODO unit test for the property 'Country' } /// <summary> /// Test the property 'CountryCode' /// </summary> [Test] public void CountryCodeTest() { // TODO unit test for the property 'CountryCode' } /// <summary> /// Test the property 'PostalCode' /// </summary> [Test] public void PostalCodeTest() { // TODO unit test for the property 'PostalCode' } } }
25.117241
120
0.530752
[ "MIT" ]
3v1lW1th1n/locationapi-client-libraries
clients/csharp/src/unwired.Test/Model/AddressDetailsSchemaTests.cs
3,642
C#
// Project: Daggerfall Tools For Unity // Copyright: Copyright (C) 2009-2019 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: // // Notes: // using UnityEngine; using System; using System.Collections; using System.Text.RegularExpressions; namespace DaggerfallWorkshop.Game.Questing { /// <summary> /// Manages a text symbol used by quest system. /// Symbols are used by resources, tasks, and text replacement. /// </summary> public class Symbol { [SerializeField] string original; [SerializeField] string name; /// <summary> /// Gets original symbol at time it was set from source. /// This is used for serialization/deserialization only. /// </summary> public string Original { get { return original; } set { SetValue(value); } } /// <summary> /// Gets name of symbol stripped to inner symbol name only. /// This is what should be used by quest system. /// </summary> public string Name { get { return name; } } /// <summary> /// Default constructor. /// </summary> public Symbol() { } /// <summary> /// Set symbol constructor. /// </summary> /// <param name="original">Symbol text from source.</param> public Symbol(string original) { SetValue(original); } /// <summary> /// Gets original value. /// </summary> /// <returns>Symbol text from source.</returns> public string GetValue() { return original; } /// <summary> /// Set symbol original value. Name value is derived from inner text. /// </summary> /// <param name="original">Symbol text from source.</param> public void SetValue(string original) { this.original = original; name = Parser.GetInnerSymbolName(original); } /// <summary> /// Clone this symbol. /// </summary> /// <returns>New Symbol with same details as this one.</returns> public Symbol Clone() { Symbol clone = new Symbol(); clone.original = original; clone.name = name; return clone; } /// <summary> /// Compare value equality with another symbol. /// </summary> /// <param name="other">Other symbol.</param> /// <returns>True is values match.</returns> public override bool Equals(object other) { if (other == null) return false; if ((other as Symbol).name == name && (other as Symbol).original == original) { return true; } return false; } /// <summary> /// Override of GetHashCode. /// Name is most important value. /// Original is only serialized for reference. /// </summary> /// <returns>Name.GetHashCode()</returns> public override int GetHashCode() { return name.GetHashCode(); } } }
28
84
0.530045
[ "MIT" ]
Arcane21/daggerfall-unity
Assets/Scripts/Game/Questing/Symbol.cs
3,530
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Response to the SystemSubscriberGetCallProcessingParametersRequest18sp1. /// <see cref="SystemSubscriberGetCallProcessingParametersRequest18sp1"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""7f663d5135470c33ca64b0eed3c3aa0c:17014""}]")] public class SystemSubscriberGetCallProcessingParametersResponse18sp1 : BroadWorksConnector.Ocip.Models.C.OCIDataResponse { private bool _isExtendedCallingLineIdActive; [XmlElement(ElementName = "isExtendedCallingLineIdActive", IsNullable = false, Namespace = "")] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:17014")] public bool IsExtendedCallingLineIdActive { get => _isExtendedCallingLineIdActive; set { IsExtendedCallingLineIdActiveSpecified = true; _isExtendedCallingLineIdActive = value; } } [XmlIgnore] protected bool IsExtendedCallingLineIdActiveSpecified { get; set; } private bool _isRingTimeOutActive; [XmlElement(ElementName = "isRingTimeOutActive", IsNullable = false, Namespace = "")] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:17014")] public bool IsRingTimeOutActive { get => _isRingTimeOutActive; set { IsRingTimeOutActiveSpecified = true; _isRingTimeOutActive = value; } } [XmlIgnore] protected bool IsRingTimeOutActiveSpecified { get; set; } private int _ringTimeoutSeconds; [XmlElement(ElementName = "ringTimeoutSeconds", IsNullable = false, Namespace = "")] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:17014")] [MinInclusive(1)] [MaxInclusive(180)] public int RingTimeoutSeconds { get => _ringTimeoutSeconds; set { RingTimeoutSecondsSpecified = true; _ringTimeoutSeconds = value; } } [XmlIgnore] protected bool RingTimeoutSecondsSpecified { get; set; } private bool _allowEmergencyRemoteOfficeOriginations; [XmlElement(ElementName = "allowEmergencyRemoteOfficeOriginations", IsNullable = false, Namespace = "")] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:17014")] public bool AllowEmergencyRemoteOfficeOriginations { get => _allowEmergencyRemoteOfficeOriginations; set { AllowEmergencyRemoteOfficeOriginationsSpecified = true; _allowEmergencyRemoteOfficeOriginations = value; } } [XmlIgnore] protected bool AllowEmergencyRemoteOfficeOriginationsSpecified { get; set; } private int _maxNoAnswerNumberOfRings; [XmlElement(ElementName = "maxNoAnswerNumberOfRings", IsNullable = false, Namespace = "")] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:17014")] [MinInclusive(6)] [MaxInclusive(20)] public int MaxNoAnswerNumberOfRings { get => _maxNoAnswerNumberOfRings; set { MaxNoAnswerNumberOfRingsSpecified = true; _maxNoAnswerNumberOfRings = value; } } [XmlIgnore] protected bool MaxNoAnswerNumberOfRingsSpecified { get; set; } private BroadWorksConnector.Ocip.Models.IncomingCallToUserAliasMode _incomingCallToUserAliasMode; [XmlElement(ElementName = "incomingCallToUserAliasMode", IsNullable = false, Namespace = "")] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:17014")] public BroadWorksConnector.Ocip.Models.IncomingCallToUserAliasMode IncomingCallToUserAliasMode { get => _incomingCallToUserAliasMode; set { IncomingCallToUserAliasModeSpecified = true; _incomingCallToUserAliasMode = value; } } [XmlIgnore] protected bool IncomingCallToUserAliasModeSpecified { get; set; } private bool _bypassTerminationLoopDetection; [XmlElement(ElementName = "bypassTerminationLoopDetection", IsNullable = false, Namespace = "")] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:17014")] public bool BypassTerminationLoopDetection { get => _bypassTerminationLoopDetection; set { BypassTerminationLoopDetectionSpecified = true; _bypassTerminationLoopDetection = value; } } [XmlIgnore] protected bool BypassTerminationLoopDetectionSpecified { get; set; } private bool _honorCLIDBlockingForEmergencyCalls; [XmlElement(ElementName = "honorCLIDBlockingForEmergencyCalls", IsNullable = false, Namespace = "")] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:17014")] public bool HonorCLIDBlockingForEmergencyCalls { get => _honorCLIDBlockingForEmergencyCalls; set { HonorCLIDBlockingForEmergencyCallsSpecified = true; _honorCLIDBlockingForEmergencyCalls = value; } } [XmlIgnore] protected bool HonorCLIDBlockingForEmergencyCallsSpecified { get; set; } private bool _useUnicodeIdentityName; [XmlElement(ElementName = "useUnicodeIdentityName", IsNullable = false, Namespace = "")] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:17014")] public bool UseUnicodeIdentityName { get => _useUnicodeIdentityName; set { UseUnicodeIdentityNameSpecified = true; _useUnicodeIdentityName = value; } } [XmlIgnore] protected bool UseUnicodeIdentityNameSpecified { get; set; } } }
34.614525
131
0.637347
[ "MIT" ]
JTOne123/broadworks-connector-net
BroadworksConnector/Ocip/Models/SystemSubscriberGetCallProcessingParametersResponse18sp1.cs
6,196
C#
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace Win.AutoloteL3 { static class Program { /// <summary> /// Punto de entrada principal para la aplicación. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormMenu()); } public static byte[] imagenToByteArray(Image ImagenIn) { var ms = new MemoryStream(); ImagenIn.Save(ms, ImagenIn.RawFormat); return ms.ToArray(); } } }
23.545455
65
0.598456
[ "MIT" ]
AlmaOrtega20/ventas
AutoloteL3/AutoloteL3/Win.AutoloteL3/Program.cs
780
C#
using System; using System.Collections.Generic; using GoNorth.Services.ImplementationStatusCompare; namespace GoNorth.Data.Karta.Marker { /// <summary> /// Karta Map Marker Chapter Pixel Coordinats Modification Data /// </summary> public class MapMarkerChapterPixelCoords : IImplementationListComparable { /// <summary> /// Chapter Number /// </summary> public int ChapterNumber { get; set; } /// <summary> /// X-Position on the map /// </summary> [ValueCompareAttribute] public float X { get; set; } /// <summary> /// Y-Position on the map /// </summary> [ValueCompareAttribute] public float Y { get; set; } /// <summary> /// Id which is used in a list compare to detect deleted or new objects /// </summary> public string ListComparableId { get { return ChapterNumber.ToString(); } } /// <summary> /// Value which is used in a list compare for display /// </summary> public CompareDifferenceValue ListComparableValue { get { return new CompareDifferenceValue(ChapterNumber.ToString(), CompareDifferenceValue.ValueResolveType.None); } } } }
32.35
185
0.595054
[ "MIT" ]
NoisySpaceBalls/GoNorth
Data/Karta/Marker/MapMarkerChapterPixelCoords.cs
1,294
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("04-SummerOutfit")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("04-SummerOutfit")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fbc80792-173a-4385-99ea-9c7923234522")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.783784
84
0.747496
[ "MIT" ]
marinakolova/CSharp-Courses
Programming-Basics-with-CSharp-November-2018/07-NestedConditionalStatementsExercise/04-SummerOutfit/Properties/AssemblyInfo.cs
1,401
C#
using GraphQL; using GraphQL.Types; namespace UrbanCarton.Webapi.GraphQL { public class UrbanCartonSchema : Schema { public UrbanCartonSchema(IDependencyResolver dependencyResolver) : base(dependencyResolver) { Query = dependencyResolver.Resolve<UrbanCartonQuery>(); Mutation = dependencyResolver.Resolve<UrbanCartonMutation>(); Subscription = dependencyResolver.Resolve<UrbanCartonSubscription>(); } } }
29.9375
99
0.701461
[ "MIT" ]
pandeyabhishek28/UrbanCarton.Webapi
GraphQL/UrbanCartonSchema.cs
481
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by SpecFlow (http://www.specflow.org/). // SpecFlow Version:1.9.0.77 // SpecFlow Generator Version:1.9.0.0 // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #region Designer generated code #pragma warning disable namespace Orchard.Specs { using TechTalk.SpecFlow; [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.9.0.77")] [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [NUnit.Framework.TestFixtureAttribute()] [NUnit.Framework.DescriptionAttribute("Boolean Field")] public partial class BooleanFieldFeature { private static TechTalk.SpecFlow.ITestRunner testRunner; #line 1 "Boolean.feature" #line hidden [NUnit.Framework.TestFixtureSetUpAttribute()] public virtual void FeatureSetup() { testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(); TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Boolean Field", " In order to add boolean content to my types\r\n As an administrator\r\n I want to" + " create, edit and publish boolean fields", ProgrammingLanguage.CSharp, ((string[])(null))); testRunner.OnFeatureStart(featureInfo); } [NUnit.Framework.TestFixtureTearDownAttribute()] public virtual void FeatureTearDown() { testRunner.OnFeatureEnd(); testRunner = null; } [NUnit.Framework.SetUpAttribute()] public virtual void TestInitialize() { } [NUnit.Framework.TearDownAttribute()] public virtual void ScenarioTearDown() { testRunner.OnScenarioEnd(); } public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo) { testRunner.OnScenarioStart(scenarioInfo); } public virtual void ScenarioCleanup() { testRunner.CollectScenarioErrors(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Creating and using Boolean fields")] public virtual void CreatingAndUsingBooleanFields() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Creating and using Boolean fields", ((string[])(null))); #line 6 this.ScenarioSetup(scenarioInfo); #line 9 testRunner.Given("I have installed Orchard", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 10 testRunner.And("I have installed \"Orchard.Fields\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 11 testRunner.When("I go to \"Admin/ContentTypes\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 12 testRunner.Then("I should see \"<a[^>]*>.*?Create new type</a>\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 13 testRunner.When("I go to \"Admin/ContentTypes/Create\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line hidden TechTalk.SpecFlow.Table table1 = new TechTalk.SpecFlow.Table(new string[] { "name", "value"}); table1.AddRow(new string[] { "DisplayName", "Event"}); table1.AddRow(new string[] { "Name", "Event"}); #line 14 testRunner.And("I fill in", ((string)(null)), table1, "And "); #line 18 testRunner.And("I hit \"Create\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 19 testRunner.And("I am redirected", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 20 testRunner.Then("I should see \"The \\\"Event\\\" content type has been created.\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 21 testRunner.When("I go to \"Admin/ContentTypes/\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 22 testRunner.Then("I should see \"Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 25 testRunner.When("I go to \"Admin/ContentTypes/Edit/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 26 testRunner.And("I follow \"Add Field\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden TechTalk.SpecFlow.Table table2 = new TechTalk.SpecFlow.Table(new string[] { "name", "value"}); table2.AddRow(new string[] { "DisplayName", "Active"}); table2.AddRow(new string[] { "Name", "Active"}); table2.AddRow(new string[] { "FieldTypeName", "BooleanField"}); #line 27 testRunner.And("I fill in", ((string)(null)), table2, "And "); #line 32 testRunner.And("I hit \"Save\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 33 testRunner.And("I am redirected", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 34 testRunner.Then("I should see \"The \\\"Active\\\" field has been added.\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 37 testRunner.When("I go to \"Admin/Contents/Create/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 38 testRunner.Then("I should see \"Active\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden TechTalk.SpecFlow.Table table3 = new TechTalk.SpecFlow.Table(new string[] { "name", "value"}); table3.AddRow(new string[] { "Event.Active.Value", "true"}); #line 39 testRunner.When("I fill in", ((string)(null)), table3, "When "); #line 42 testRunner.And("I hit \"Save Draft\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 43 testRunner.And("I am redirected", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 44 testRunner.Then("I should see \"The Event has been created as a draft.\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 45 testRunner.When("I go to \"Admin/Contents/List\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 46 testRunner.Then("I should see \"Active:\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 47 testRunner.And("I should see \"Yes\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 50 testRunner.When("I go to \"Admin/ContentTypes/Edit/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line hidden TechTalk.SpecFlow.Table table4 = new TechTalk.SpecFlow.Table(new string[] { "name", "value"}); table4.AddRow(new string[] { "Fields[Active].BooleanFieldSettings.Hint", "Check if the event is active"}); #line 51 testRunner.And("I fill in", ((string)(null)), table4, "And "); #line 54 testRunner.And("I hit \"Save\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 55 testRunner.And("I am redirected", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 56 testRunner.And("I go to \"Admin/Contents/Create/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 57 testRunner.Then("I should see \"Check if the event is active\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 60 testRunner.When("I go to \"Admin/ContentTypes/Edit/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line hidden TechTalk.SpecFlow.Table table5 = new TechTalk.SpecFlow.Table(new string[] { "name", "value"}); table5.AddRow(new string[] { "Fields[Active].BooleanFieldSettings.DefaultValue", "True"}); #line 61 testRunner.And("I fill in", ((string)(null)), table5, "And "); #line 64 testRunner.And("I hit \"Save\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 65 testRunner.And("I am redirected", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 66 testRunner.Then("I should see \"\\\"Event\\\" settings have been saved.\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 67 testRunner.When("I go to \"Admin/Contents/Create/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 68 testRunner.Then("I should see \"checked=\\\"checked\\\"\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 71 testRunner.When("I go to \"Admin/ContentTypes/Edit/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line hidden TechTalk.SpecFlow.Table table6 = new TechTalk.SpecFlow.Table(new string[] { "name", "value"}); table6.AddRow(new string[] { "Fields[Active].BooleanFieldSettings.Optional", "false"}); table6.AddRow(new string[] { "Fields[Active].BooleanFieldSettings.SelectionMode", "Dropdown list"}); #line 72 testRunner.And("I fill in", ((string)(null)), table6, "And "); #line 76 testRunner.And("I hit \"Save\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 77 testRunner.And("I go to \"Admin/Contents/Create/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden TechTalk.SpecFlow.Table table7 = new TechTalk.SpecFlow.Table(new string[] { "name", "value"}); table7.AddRow(new string[] { "Event.Active.Value", ""}); #line 78 testRunner.And("I fill in", ((string)(null)), table7, "And "); #line 81 testRunner.And("I hit \"Save Draft\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden this.ScenarioCleanup(); } } } #pragma warning restore #endregion
47.175966
243
0.569414
[ "BSD-3-Clause" ]
AndreaPiovanelliLaser/Orchard
src/Orchard.Specs/Boolean.feature.cs
10,994
C#
using System; using System.Collections.Generic; using InventoryPoc.Data.Enums; namespace InventoryPoc.Data.Models.Profile { public class ContractDeliverable : IEntity { public int Id { get; set; } public DateTime? DueDate { get; set; } public ContractDeliverableStatus ContractDeliverableStatus { get; set; } public DeliveryMethodType DeliveryMethod { get; set; } public bool DeliverableCommitted { get; set; } public bool DeliverableRevised { get; set; } public int PrePayDays { get; set; } public DateTime DeliverableReceivedDate { get; set; } public int GroupId { get; set; } public virtual Group Group { get; set; } public int DeliverableId { get; set; } public virtual Deliverable Deliverable { get; set; } public virtual ICollection<DeliverableRecipient> Recipients { get; set; } } }
37.869565
78
0.699196
[ "MIT" ]
Bougiefever/SqlWithCosmosDb
InventoryPoc/Data/Models/Profile/ContractDeliverable.cs
873
C#
// // System.Web.UI.WebControls.Repeater.cs // // Authors: // Ben Maurer (bmaurer@novell.com) // // (C) 2005 Novell, Inc (http://www.novell.com) // // 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. // // Helpful resources while implementing this class: // // _Developing Microsoft ASP.NET Server Controls and Components_ (Kothari, Datye) // Chapters 16 and 20 (especially listing 20-3 on page 559) // // "Building DataBound Templated Custom ASP.NET Server Controls" (Mitchell) on MSDN // Right now, http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/databoundtemplatedcontrols.asp // works, but with msdn we all know that urls have a very short lifetime :-) // using System.Collections; using System.ComponentModel; using System.Security.Permissions; using System.Web.Util; namespace System.Web.UI.WebControls { // CAS [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)] // attributes [DefaultEvent ("ItemCommand")] [DefaultProperty ("DataSource")] [Designer ("System.Web.UI.Design.WebControls.RepeaterDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")] [ParseChildren (true)] [PersistChildren (false)] public class Repeater : Control, INamingContainer { object dataSource; #if NET_2_0 IDataSource boundDataSource; bool initialized; bool preRendered = false; bool requiresDataBinding; DataSourceSelectArguments selectArguments; IEnumerable data; #endif // See Kothari, listing 20-3 #if NET_2_0 protected internal #else protected #endif override void CreateChildControls () { // We are recreating the children from viewstate Controls.Clear(); // Build the children from the viewstate if (ViewState ["Items"] != null) CreateControlHierarchy (false); } // See Kothari, listing 20-3 protected override void OnDataBinding (EventArgs e) { base.OnDataBinding (EventArgs.Empty); Controls.Clear (); ClearChildViewState (); TrackViewState (); CreateControlHierarchy (true); ChildControlsCreated = true; } void DoItem (int i, ListItemType t, object d, bool databind) { RepeaterItem itm = CreateItem (i, t); if (t == ListItemType.Item || t == ListItemType.AlternatingItem) items.Add (itm); itm.DataItem = d; RepeaterItemEventArgs e = new RepeaterItemEventArgs (itm); InitializeItem (itm); // // It is very important that this be called *before* data // binding. Otherwise, we won't save our state in the viewstate. // Controls.Add (itm); OnItemCreated (e); if (databind) { itm.DataBind (); OnItemDataBound (e); } } protected virtual void CreateControlHierarchy (bool useDataSource) { IEnumerable ds; items = new ArrayList (); itemscol = null; if (useDataSource) { ds = GetData (); } else { // Optimize (shouldn't need all this memory ;-) ds = new object [(int) ViewState ["Items"]]; } // If there is no datasource, then we don't show anything. the "Items" // viewstate won't get set, so on postback, we won't get here if (ds == null) return; if (HeaderTemplate != null) DoItem (-1, ListItemType.Header, null, useDataSource); int idx = 0; foreach (object o in ds) { if (idx != 0 && SeparatorTemplate != null) DoItem (idx - 1, ListItemType.Separator, null, useDataSource); DoItem (idx, idx % 2 == 0 ? ListItemType.Item : ListItemType.AlternatingItem, o, useDataSource); idx ++; } if (FooterTemplate != null) DoItem (-1, ListItemType.Footer, null, useDataSource); ViewState ["Items"] = idx; } // Why does this get overriden? public override void DataBind () { // In all the examples I've seen online, this does base.OnDataBinding and // then does all the create child controls stuff. But from stack traces on // windows, this doesn't seem to be the case here. OnDataBinding (EventArgs.Empty); #if NET_2_0 RequiresDataBinding = false; #endif } protected virtual RepeaterItem CreateItem (int itemIndex, ListItemType itemType) { return new RepeaterItem (itemIndex, itemType); } protected virtual void InitializeItem (RepeaterItem item) { ITemplate t = null; switch (item.ItemType) { case ListItemType.Header: t = HeaderTemplate; break; case ListItemType.Footer: t = FooterTemplate; break; case ListItemType.Item: t = ItemTemplate; break; case ListItemType.AlternatingItem: t = AlternatingItemTemplate; if (t == null) t = ItemTemplate; break; case ListItemType.Separator: t = SeparatorTemplate; break; } if (t != null) t.InstantiateIn (item); } protected override bool OnBubbleEvent (object sender, EventArgs e) { RepeaterCommandEventArgs rcea = e as RepeaterCommandEventArgs; if (rcea != null) { OnItemCommand (rcea); return true; } return false; } public override ControlCollection Controls { get { EnsureChildControls (); return base.Controls; } } RepeaterItemCollection itemscol; ArrayList items; [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [WebSysDescription ("")] public virtual RepeaterItemCollection Items { get { if (itemscol == null) { if (items == null) items = new ArrayList (); itemscol = new RepeaterItemCollection (items); } return itemscol; } } [DefaultValue("")] [WebSysDescription ("")] [WebCategory ("Data")] public virtual string DataMember { get { return ViewState.GetString ("DataMember", ""); } set { if (value == null) ViewState.Remove ("DataMember"); else ViewState ["DataMember"] = value; #if NET_2_0 if (!Initialized) OnDataPropertyChanged (); #endif } } [Bindable(true)] [DefaultValue(null)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [WebSysDescription ("")] [WebCategory ("Data")] public virtual object DataSource { get { return dataSource; } set { if (value == null || value is IListSource || value is IEnumerable) { #if NET_2_0 // FIXME - can't duplicate in a test case ? LAMESPEC ? // can't duplicate in a test case // if ((dataSourceId != null) && (dataSourceId.Length != 0)) // throw new HttpException (Locale.GetText ("DataSourceID is already set.")); dataSource = value; if (!Initialized) OnDataPropertyChanged (); #else dataSource = value; #endif } else throw new ArgumentException (String.Format ( "An invalid data source is being used for {0}. A valid data source must implement either IListSource or IEnumerable", ID)); } } #if NET_2_0 [DefaultValue ("")] [IDReferenceProperty (typeof (DataSourceControl))] public virtual string DataSourceID { get { return ViewState.GetString ("DataSourceID", ""); } set { if (dataSource != null) throw new HttpException ("Only one of DataSource and DataSourceID can be specified."); ViewState ["DataSourceID"] = value; if (!Initialized) OnDataPropertyChanged (); } } [Browsable (true)] [DefaultValue(false)] public override bool EnableTheming { get { return base.EnableTheming; } set { base.EnableTheming = value; } } #endif ITemplate alt_itm_tmpl; [Browsable(false)] [DefaultValue(null)] [PersistenceMode(PersistenceMode.InnerProperty)] [TemplateContainer (typeof (RepeaterItem))] [WebSysDescription ("")] public virtual ITemplate AlternatingItemTemplate { get { return alt_itm_tmpl; } set { alt_itm_tmpl = value; } } ITemplate footer_tmpl; [Browsable(false)] [DefaultValue(null)] [PersistenceMode(PersistenceMode.InnerProperty)] [TemplateContainer (typeof (RepeaterItem))] [WebSysDescription ("")] public virtual ITemplate FooterTemplate { get { return footer_tmpl; } set { footer_tmpl = value; } } ITemplate header_tmpl; [Browsable(false)] [DefaultValue(null)] [PersistenceMode(PersistenceMode.InnerProperty)] [TemplateContainer (typeof (RepeaterItem))] [WebSysDescription ("")] public virtual ITemplate HeaderTemplate { get { return header_tmpl; } set { header_tmpl = value; } } ITemplate item_tmpl; [Browsable(false)] [DefaultValue(null)] [PersistenceMode(PersistenceMode.InnerProperty)] [TemplateContainer (typeof (RepeaterItem))] [WebSysDescription ("")] public virtual ITemplate ItemTemplate { get { return item_tmpl; } set { item_tmpl = value; } } ITemplate separator_tmpl; [Browsable(false)] [DefaultValue(null)] [PersistenceMode(PersistenceMode.InnerProperty)] [TemplateContainer (typeof (RepeaterItem))] [WebSysDescription ("")] public virtual ITemplate SeparatorTemplate { get { return separator_tmpl; } set { separator_tmpl = value; } } protected virtual void OnItemCommand (RepeaterCommandEventArgs e) { RepeaterCommandEventHandler h = (RepeaterCommandEventHandler) Events [ItemCommandEvent]; if (h != null) h (this, e); } static readonly object ItemCommandEvent = new object (); [WebSysDescription ("")] [WebCategory ("Action")] public event RepeaterCommandEventHandler ItemCommand { add { Events.AddHandler (ItemCommandEvent, value); } remove { Events.RemoveHandler (ItemCommandEvent, value); } } protected virtual void OnItemCreated (RepeaterItemEventArgs e) { RepeaterItemEventHandler h = (RepeaterItemEventHandler) Events [ItemCreatedEvent]; if (h != null) h (this, e); } static readonly object ItemCreatedEvent = new object (); [WebSysDescription ("")] [WebCategory ("Behavior")] public event RepeaterItemEventHandler ItemCreated { add { Events.AddHandler (ItemCreatedEvent, value); } remove { Events.RemoveHandler (ItemCreatedEvent, value); } } protected virtual void OnItemDataBound (RepeaterItemEventArgs e) { RepeaterItemEventHandler h = (RepeaterItemEventHandler) Events [ItemDataBoundEvent]; if (h != null) h (this, e); } static readonly object ItemDataBoundEvent = new object (); [WebSysDescription ("")] [WebCategory ("Behavior")] public event RepeaterItemEventHandler ItemDataBound { add { Events.AddHandler (ItemDataBoundEvent, value); } remove { Events.RemoveHandler (ItemDataBoundEvent, value); } } #if NET_2_0 protected bool Initialized { get { return initialized; } } protected bool IsBoundUsingDataSourceID { get { return (DataSourceID.Length != 0); } } protected bool RequiresDataBinding { get { return requiresDataBinding; } set { requiresDataBinding = value; if (value && preRendered && IsBoundUsingDataSourceID && Page != null && !Page.IsCallback) EnsureDataBound (); } } protected DataSourceSelectArguments SelectArguments { get { // MSDN: The first call to the SelectArguments property calls the // CreateDataSourceSelectArguments method to return the Empty value. if (selectArguments == null) selectArguments = CreateDataSourceSelectArguments(); return selectArguments; } } protected virtual DataSourceSelectArguments CreateDataSourceSelectArguments () { // MSDN: Returns the Empty value. return DataSourceSelectArguments.Empty; } protected void EnsureDataBound () { if (IsBoundUsingDataSourceID && RequiresDataBinding) DataBind (); } void SelectCallback (IEnumerable data) { this.data = data; } #endif #if NET_2_0 protected virtual #endif IEnumerable GetData () { IEnumerable result; #if NET_2_0 if (IsBoundUsingDataSourceID) { if (DataSourceID.Length == 0) return null; if (boundDataSource == null) return null; DataSourceView dsv = boundDataSource.GetView (String.Empty); dsv.Select (SelectArguments, new DataSourceViewSelectCallback (SelectCallback)); result = data; data = null; } else #endif result = DataSourceResolver.ResolveDataSource (DataSource, DataMember); return result; } #if NET_2_0 protected virtual void OnDataPropertyChanged () { if (Initialized) RequiresDataBinding = true; } protected virtual void OnDataSourceViewChanged (object sender, EventArgs e) { RequiresDataBinding = true; } protected internal override void OnInit (EventArgs e) { base.OnInit (e); Page page = Page; if (page != null) { page.PreLoad += new EventHandler (OnPagePreLoad); if (!IsViewStateEnabled && page.IsPostBack) RequiresDataBinding = true; } } protected virtual void OnPagePreLoad (object sender, EventArgs e) { Initialize (); } protected internal override void OnLoad (EventArgs e) { if (!Initialized) Initialize (); base.OnLoad (e); } void Initialize () { Page page = Page; if (page != null) { if (!page.IsPostBack || (IsViewStateEnabled && (ViewState ["Items"] == null))) RequiresDataBinding = true; } if (IsBoundUsingDataSourceID) ConnectToDataSource (); initialized = true; } protected internal override void OnPreRender (EventArgs e) { preRendered = true; EnsureDataBound (); base.OnPreRender (e); } void ConnectToDataSource () { /* verify that the data source exists and is an IDataSource */ object ctrl = null; if (Parent != null) ctrl = Parent.FindControl (DataSourceID); if (ctrl == null || !(ctrl is IDataSource)) { string format; if (ctrl == null) format = "DataSourceID of '{0}' must be the ID of a control of type IDataSource. A control with ID '{1}' could not be found."; else format = "DataSourceID of '{0}' must be the ID of a control of type IDataSource. '{1}' is not an IDataSource."; throw new HttpException (String.Format (format, ID, DataSourceID)); } boundDataSource = (IDataSource)ctrl; boundDataSource.GetView (String.Empty).DataSourceViewChanged += new EventHandler(OnDataSourceViewChanged); } #endif } }
25.386401
140
0.689051
[ "MIT" ]
zlxy/Genesis-3D
Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/System.Web/System.Web.UI.WebControls/Repeater.cs
15,308
C#
using System.Linq; using Esfa.Recruit.Vacancies.Client.Domain.Entities; namespace Esfa.Recruit.Employer.Web.ViewModels.VacancyManage { public class ManageVacancyViewModel { public string Title { get; internal set; } public VacancyStatus Status { get; internal set; } public string VacancyReference { get; internal set; } public string ClosingDate { get; internal set; } public string PossibleStartDate { get; internal set; } public bool IsDisabilityConfident { get; internal set; } public bool IsApplyThroughFaaVacancy { get; internal set; } public VacancyApplicationsViewModel Applications { get; internal set; } public bool HasApplications => Applications.Applications.Any(); public bool HasNoApplications => Applications.Applications == null || Applications.Applications?.Any() == false; public bool CanShowEditVacancyLink { get; internal set; } public bool CanShowCloseVacancyLink { get; internal set; } public string VacancyClosedInfoMessage { get; internal set; } public bool HasVacancyClosedInfoMessage => !string.IsNullOrEmpty(VacancyClosedInfoMessage); } }
49.625
120
0.717045
[ "MIT" ]
bjstone82/das-recruit
src/Employer/Employer.Web/ViewModels/VacancyManage/ManageVacancyViewModel.cs
1,191
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Collections.Generic; using Squidex.Domain.Apps.Core; using Squidex.Domain.Apps.Core.Schemas; using Squidex.Domain.Apps.Core.TestHelpers; using Squidex.Domain.Apps.Entities.Schemas.Commands; using Squidex.Domain.Apps.Entities.TestHelpers; using Squidex.Infrastructure; using Squidex.Infrastructure.Validation; using Xunit; #pragma warning disable SA1310 // Field names must not contain underscore namespace Squidex.Domain.Apps.Entities.Schemas.Guards { public class GuardSchemaTests : IClassFixture<TranslationsFixture> { private readonly Schema schema_0; private readonly NamedId<DomainId> appId = NamedId.Of(DomainId.NewGuid(), "my-app"); public GuardSchemaTests() { schema_0 = new Schema("my-schema") .AddString(1, "field1", Partitioning.Invariant) .AddString(2, "field2", Partitioning.Invariant) .AddUI(4, "field4", Partitioning.Invariant); } [Fact] public void CanCreate_should_throw_exception_if_name_not_valid() { var command = new CreateSchema { AppId = appId, Name = "INVALID NAME" }; ValidationAssert.Throws(() => GuardSchema.CanCreate(command), new ValidationError("Name is not a valid slug.", "Name")); } [Fact] public void CanCreate_should_throw_exception_if_field_name_invalid() { var command = new CreateSchema { AppId = appId, Fields = new List<UpsertSchemaField> { new UpsertSchemaField { Name = "invalid name", Properties = new StringFieldProperties(), Partitioning = Partitioning.Invariant.Key } }, Name = "new-schema" }; ValidationAssert.Throws(() => GuardSchema.CanCreate(command), new ValidationError("Name is not a Javascript property name.", "Fields[0].Name")); } [Fact] public void CanCreate_should_throw_exception_if_field_properties_null() { var command = new CreateSchema { AppId = appId, Fields = new List<UpsertSchemaField> { new UpsertSchemaField { Name = "field1", Properties = null!, Partitioning = Partitioning.Invariant.Key } }, Name = "new-schema" }; ValidationAssert.Throws(() => GuardSchema.CanCreate(command), new ValidationError("Properties is required.", "Fields[0].Properties")); } [Fact] public void CanCreate_should_throw_exception_if_field_properties_not_valid() { var command = new CreateSchema { AppId = appId, Fields = new List<UpsertSchemaField> { new UpsertSchemaField { Name = "field1", Properties = new StringFieldProperties { MinLength = 10, MaxLength = 5 }, Partitioning = Partitioning.Invariant.Key } }, Name = "new-schema" }; ValidationAssert.Throws(() => GuardSchema.CanCreate(command), new ValidationError("Max length must be greater or equal to min length.", "Fields[0].Properties.MinLength", "Fields[0].Properties.MaxLength")); } [Fact] public void CanCreate_should_throw_exception_if_field_partitioning_not_valid() { var command = new CreateSchema { AppId = appId, Fields = new List<UpsertSchemaField> { new UpsertSchemaField { Name = "field1", Properties = new StringFieldProperties(), Partitioning = "INVALID" } }, Name = "new-schema" }; ValidationAssert.Throws(() => GuardSchema.CanCreate(command), new ValidationError("Partitioning is not a valid value.", "Fields[0].Partitioning")); } [Fact] public void CanCreate_should_throw_exception_if_fields_contains_duplicate_name() { var command = new CreateSchema { AppId = appId, Fields = new List<UpsertSchemaField> { new UpsertSchemaField { Name = "field1", Properties = new StringFieldProperties(), Partitioning = Partitioning.Invariant.Key }, new UpsertSchemaField { Name = "field1", Properties = new StringFieldProperties(), Partitioning = Partitioning.Invariant.Key } }, Name = "new-schema" }; ValidationAssert.Throws(() => GuardSchema.CanCreate(command), new ValidationError("Field 'field1' has been added twice.", "Fields")); } [Fact] public void CanCreate_should_throw_exception_if_nested_field_name_invalid() { var command = new CreateSchema { AppId = appId, Fields = new List<UpsertSchemaField> { new UpsertSchemaField { Name = "array", Properties = new ArrayFieldProperties(), Partitioning = Partitioning.Invariant.Key, Nested = new List<UpsertSchemaNestedField> { new UpsertSchemaNestedField { Name = "invalid name", Properties = new StringFieldProperties() } } } }, Name = "new-schema" }; ValidationAssert.Throws(() => GuardSchema.CanCreate(command), new ValidationError("Name is not a Javascript property name.", "Fields[0].Nested[0].Name")); } [Fact] public void CanCreate_should_throw_exception_if_nested_field_properties_null() { var command = new CreateSchema { AppId = appId, Fields = new List<UpsertSchemaField> { new UpsertSchemaField { Name = "array", Properties = new ArrayFieldProperties(), Partitioning = Partitioning.Invariant.Key, Nested = new List<UpsertSchemaNestedField> { new UpsertSchemaNestedField { Name = "nested1", Properties = null! } } } }, Name = "new-schema" }; ValidationAssert.Throws(() => GuardSchema.CanCreate(command), new ValidationError("Properties is required.", "Fields[0].Nested[0].Properties")); } [Fact] public void CanCreate_should_throw_exception_if_nested_field_is_array() { var command = new CreateSchema { AppId = appId, Fields = new List<UpsertSchemaField> { new UpsertSchemaField { Name = "array", Properties = new ArrayFieldProperties(), Partitioning = Partitioning.Invariant.Key, Nested = new List<UpsertSchemaNestedField> { new UpsertSchemaNestedField { Name = "nested1", Properties = new ArrayFieldProperties() } } } }, Name = "new-schema" }; ValidationAssert.Throws(() => GuardSchema.CanCreate(command), new ValidationError("Nested field cannot be array fields.", "Fields[0].Nested[0].Properties")); } [Fact] public void CanCreate_should_throw_exception_if_nested_field_properties_not_valid() { var command = new CreateSchema { AppId = appId, Fields = new List<UpsertSchemaField> { new UpsertSchemaField { Name = "array", Properties = new ArrayFieldProperties(), Partitioning = Partitioning.Invariant.Key, Nested = new List<UpsertSchemaNestedField> { new UpsertSchemaNestedField { Name = "nested1", Properties = new StringFieldProperties { MinLength = 10, MaxLength = 5 } } } } }, Name = "new-schema" }; ValidationAssert.Throws(() => GuardSchema.CanCreate(command), new ValidationError("Max length must be greater or equal to min length.", "Fields[0].Nested[0].Properties.MinLength", "Fields[0].Nested[0].Properties.MaxLength")); } [Fact] public void CanCreate_should_throw_exception_if_nested_field_have_duplicate_names() { var command = new CreateSchema { AppId = appId, Fields = new List<UpsertSchemaField> { new UpsertSchemaField { Name = "array", Properties = new ArrayFieldProperties(), Partitioning = Partitioning.Invariant.Key, Nested = new List<UpsertSchemaNestedField> { new UpsertSchemaNestedField { Name = "nested1", Properties = new StringFieldProperties() }, new UpsertSchemaNestedField { Name = "nested1", Properties = new StringFieldProperties() } } } }, Name = "new-schema" }; ValidationAssert.Throws(() => GuardSchema.CanCreate(command), new ValidationError("Field 'nested1' has been added twice.", "Fields[0].Nested")); } [Fact] public void CanCreate_should_throw_exception_if_ui_field_is_invalid() { var command = new CreateSchema { AppId = appId, Fields = new List<UpsertSchemaField> { new UpsertSchemaField { Name = "field1", Properties = new UIFieldProperties(), IsHidden = true, IsDisabled = true, Partitioning = Partitioning.Invariant.Key } }, FieldsInLists = new FieldNames("field1"), FieldsInReferences = new FieldNames("field1"), Name = "new-schema" }; ValidationAssert.Throws(() => GuardSchema.CanCreate(command), new ValidationError("UI field cannot be hidden.", "Fields[0].IsHidden"), new ValidationError("UI field cannot be disabled.", "Fields[0].IsDisabled"), new ValidationError("Field cannot be an UI field.", "FieldsInLists[0]"), new ValidationError("Field cannot be an UI field.", "FieldsInReferences[0]")); } [Fact] public void CanCreate_should_throw_exception_if_invalid_lists_field_are_used() { var command = new CreateSchema { Fields = new List<UpsertSchemaField> { new UpsertSchemaField { Name = "field1", Properties = new StringFieldProperties(), Partitioning = Partitioning.Invariant.Key }, new UpsertSchemaField { Name = "field4", Properties = new UIFieldProperties(), Partitioning = Partitioning.Invariant.Key } }, FieldsInLists = new FieldNames(null!, null!, "field3", "field1", "field1", "field4"), FieldsInReferences = null, Name = "new-schema" }; ValidationAssert.Throws(() => GuardSchema.CanCreate(command), new ValidationError("Field is required.", "FieldsInLists[0]"), new ValidationError("Field is required.", "FieldsInLists[1]"), new ValidationError("Field is not part of the schema.", "FieldsInLists[2]"), new ValidationError("Field cannot be an UI field.", "FieldsInLists[5]"), new ValidationError("Field 'field1' has been added twice.", "FieldsInLists")); } [Fact] public void CanCreate_should_throw_exception_if_invalid_references_field_are_used() { var command = new CreateSchema { Fields = new List<UpsertSchemaField> { new UpsertSchemaField { Name = "field1", Properties = new StringFieldProperties(), Partitioning = Partitioning.Invariant.Key }, new UpsertSchemaField { Name = "field4", Properties = new UIFieldProperties(), Partitioning = Partitioning.Invariant.Key } }, FieldsInLists = null, FieldsInReferences = new FieldNames(null!, null!, "field3", "field1", "field1", "field4"), Name = "new-schema" }; ValidationAssert.Throws(() => GuardSchema.CanCreate(command), new ValidationError("Field is required.", "FieldsInReferences[0]"), new ValidationError("Field is required.", "FieldsInReferences[1]"), new ValidationError("Field is not part of the schema.", "FieldsInReferences[2]"), new ValidationError("Field cannot be an UI field.", "FieldsInReferences[5]"), new ValidationError("Field 'field1' has been added twice.", "FieldsInReferences")); } [Fact] public void CanCreate_should_throw_exception_if_references_contains_meta_field() { var command = new CreateSchema { FieldsInLists = null, FieldsInReferences = new FieldNames("meta.id"), Name = "new-schema" }; ValidationAssert.Throws(() => GuardSchema.CanCreate(command), new ValidationError("Field is not part of the schema.", "FieldsInReferences[0]")); } [Fact] public void CanCreate_should_not_throw_exception_if_command_is_valid() { var command = new CreateSchema { AppId = appId, Fields = new List<UpsertSchemaField> { new UpsertSchemaField { Name = "field1", Properties = new StringFieldProperties(), IsHidden = true, IsDisabled = true, Partitioning = Partitioning.Invariant.Key }, new UpsertSchemaField { Name = "field2", Properties = ValidProperties(), Partitioning = Partitioning.Invariant.Key }, new UpsertSchemaField { Name = "field3", Properties = new ArrayFieldProperties(), Partitioning = Partitioning.Invariant.Key, Nested = new List<UpsertSchemaNestedField> { new UpsertSchemaNestedField { Name = "nested1", Properties = ValidProperties() }, new UpsertSchemaNestedField { Name = "nested2", Properties = ValidProperties() } } } }, FieldsInLists = new FieldNames("field1", "meta.id"), FieldsInReferences = new FieldNames("field1"), Name = "new-schema" }; GuardSchema.CanCreate(command); } [Fact] public void CanConfigureUIFields_should_throw_exception_if_invalid_lists_field_are_used() { var command = new ConfigureUIFields { FieldsInLists = new FieldNames(null!, null!, "field3", "field1", "field1", "field4"), FieldsInReferences = null }; ValidationAssert.Throws(() => GuardSchema.CanConfigureUIFields(command, schema_0), new ValidationError("Field is required.", "FieldsInLists[0]"), new ValidationError("Field is required.", "FieldsInLists[1]"), new ValidationError("Field is not part of the schema.", "FieldsInLists[2]"), new ValidationError("Field cannot be an UI field.", "FieldsInLists[5]"), new ValidationError("Field 'field1' has been added twice.", "FieldsInLists")); } [Fact] public void CanConfigureUIFields_should_throw_exception_if_invalid_references_field_are_used() { var command = new ConfigureUIFields { FieldsInLists = null, FieldsInReferences = new FieldNames(null!, null!, "field3", "field1", "field1", "field4") }; ValidationAssert.Throws(() => GuardSchema.CanConfigureUIFields(command, schema_0), new ValidationError("Field is required.", "FieldsInReferences[0]"), new ValidationError("Field is required.", "FieldsInReferences[1]"), new ValidationError("Field is not part of the schema.", "FieldsInReferences[2]"), new ValidationError("Field cannot be an UI field.", "FieldsInReferences[5]"), new ValidationError("Field 'field1' has been added twice.", "FieldsInReferences")); } [Fact] public void CanConfigureUIFields_should_throw_exception_if_references_contains_meta_field() { var command = new ConfigureUIFields { FieldsInLists = null, FieldsInReferences = new FieldNames("meta.id") }; ValidationAssert.Throws(() => GuardSchema.CanConfigureUIFields(command, schema_0), new ValidationError("Field is not part of the schema.", "FieldsInReferences[0]")); } [Fact] public void CanConfigureUIFields_should_not_throw_exception_if_command_is_valid() { var command = new ConfigureUIFields { FieldsInLists = new FieldNames("field1", "meta.id"), FieldsInReferences = new FieldNames("field2") }; GuardSchema.CanConfigureUIFields(command, schema_0); } [Fact] public void CanConfigureFieldRules_should_throw_exception_if_field_rules_are_invalid() { var command = new ConfigureFieldRules { FieldRules = new List<FieldRuleCommand> { new FieldRuleCommand { Field = "field", Action = (FieldRuleAction)5 }, new FieldRuleCommand(), } }; ValidationAssert.Throws(() => GuardSchema.CanConfigureFieldRules(command), new ValidationError("Action is not a valid value.", "FieldRules[0].Action"), new ValidationError("Field is required.", "FieldRules[1].Field")); } [Fact] public void CanConfigureFieldRules_should_not_throw_exception_if_field_rules_are_valid() { var command = new ConfigureFieldRules { FieldRules = new List<FieldRuleCommand> { new FieldRuleCommand { Field = "field1", Action = FieldRuleAction.Disable, Condition = "a == b" }, new FieldRuleCommand { Field = "field2" } } }; GuardSchema.CanConfigureFieldRules(command); } [Fact] public void CanConfigureFieldRules_should_not_throw_exception_if_field_rules_are_null() { var command = new ConfigureFieldRules { FieldRules = null }; GuardSchema.CanConfigureFieldRules(command); } [Fact] public void CanPublish_should_not_throw_exception() { var command = new PublishSchema(); GuardSchema.CanPublish(command); } [Fact] public void CanUnpublish_should_not_throw_exception() { var command = new UnpublishSchema(); GuardSchema.CanUnpublish(command); } [Fact] public void CanReorder_should_throw_exception_if_field_ids_contains_invalid_id() { var command = new ReorderFields { FieldIds = new List<long> { 1, 3 } }; ValidationAssert.Throws(() => GuardSchema.CanReorder(command, schema_0), new ValidationError("Field ids do not cover all fields.", "FieldIds")); } [Fact] public void CanReorder_should_throw_exception_if_field_ids_do_not_covers_all_fields() { var command = new ReorderFields { FieldIds = new List<long> { 1 } }; ValidationAssert.Throws(() => GuardSchema.CanReorder(command, schema_0), new ValidationError("Field ids do not cover all fields.", "FieldIds")); } [Fact] public void CanReorder_should_throw_exception_if_field_ids_null() { var command = new ReorderFields { FieldIds = null! }; ValidationAssert.Throws(() => GuardSchema.CanReorder(command, schema_0), new ValidationError("Field IDs is required.", "FieldIds")); } [Fact] public void CanReorder_should_throw_exception_if_parent_field_not_found() { var command = new ReorderFields { FieldIds = new List<long> { 1, 2 }, ParentFieldId = 99 }; Assert.Throws<DomainObjectNotFoundException>(() => GuardSchema.CanReorder(command, schema_0)); } [Fact] public void CanReorder_should_not_throw_exception_if_field_ids_are_valid() { var command = new ReorderFields { FieldIds = new List<long> { 1, 2, 4 } }; GuardSchema.CanReorder(command, schema_0); } [Fact] public void CanConfigurePreviewUrls_should_throw_exception_if_preview_urls_null() { var command = new ConfigurePreviewUrls { PreviewUrls = null! }; ValidationAssert.Throws(() => GuardSchema.CanConfigurePreviewUrls(command), new ValidationError("Preview URLs is required.", "PreviewUrls")); } [Fact] public void CanConfigurePreviewUrls_should_not_throw_exception_if_valid() { var command = new ConfigurePreviewUrls { PreviewUrls = new Dictionary<string, string>() }; GuardSchema.CanConfigurePreviewUrls(command); } [Fact] public void CanChangeCategory_should_not_throw_exception() { var command = new ChangeCategory(); GuardSchema.CanChangeCategory(command); } [Fact] public void CanDelete_should_not_throw_exception() { var command = new DeleteSchema(); GuardSchema.CanDelete(command); } private static StringFieldProperties ValidProperties() { return new StringFieldProperties { MinLength = 10, MaxLength = 20 }; } } }
37.847552
118
0.483057
[ "MIT" ]
gfollesa/squidex
backend/tests/Squidex.Domain.Apps.Entities.Tests/Schemas/Guards/GuardSchemaTests.cs
27,064
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #nullable enable #pragma warning disable CS1591 #pragma warning disable CS0108 #pragma warning disable 618 using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Linq; using System.Runtime.Serialization; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using JetBrains.Space.Common; using JetBrains.Space.Common.Json.Serialization; using JetBrains.Space.Common.Json.Serialization.Polymorphism; using JetBrains.Space.Common.Types; namespace JetBrains.Space.Client; public class TeamDirectoryInvitationsForIdPatchRequest : IPropagatePropertyAccessPath { public TeamDirectoryInvitationsForIdPatchRequest() { } public TeamDirectoryInvitationsForIdPatchRequest(string? inviteeEmail = null, string? inviteeFirstName = null, string? inviteeLastName = null, string? team = null, string? role = null) { InviteeEmail = inviteeEmail; InviteeFirstName = inviteeFirstName; InviteeLastName = inviteeLastName; Team = team; Role = role; } private PropertyValue<string?> _inviteeEmail = new PropertyValue<string?>(nameof(TeamDirectoryInvitationsForIdPatchRequest), nameof(InviteeEmail), "inviteeEmail"); #if NET6_0_OR_GREATER [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] #endif [JsonPropertyName("inviteeEmail")] public string? InviteeEmail { get => _inviteeEmail.GetValue(InlineErrors); set => _inviteeEmail.SetValue(value); } private PropertyValue<string?> _inviteeFirstName = new PropertyValue<string?>(nameof(TeamDirectoryInvitationsForIdPatchRequest), nameof(InviteeFirstName), "inviteeFirstName"); #if NET6_0_OR_GREATER [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] #endif [JsonPropertyName("inviteeFirstName")] public string? InviteeFirstName { get => _inviteeFirstName.GetValue(InlineErrors); set => _inviteeFirstName.SetValue(value); } private PropertyValue<string?> _inviteeLastName = new PropertyValue<string?>(nameof(TeamDirectoryInvitationsForIdPatchRequest), nameof(InviteeLastName), "inviteeLastName"); #if NET6_0_OR_GREATER [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] #endif [JsonPropertyName("inviteeLastName")] public string? InviteeLastName { get => _inviteeLastName.GetValue(InlineErrors); set => _inviteeLastName.SetValue(value); } private PropertyValue<string?> _team = new PropertyValue<string?>(nameof(TeamDirectoryInvitationsForIdPatchRequest), nameof(Team), "team"); #if NET6_0_OR_GREATER [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] #endif [JsonPropertyName("team")] public string? Team { get => _team.GetValue(InlineErrors); set => _team.SetValue(value); } private PropertyValue<string?> _role = new PropertyValue<string?>(nameof(TeamDirectoryInvitationsForIdPatchRequest), nameof(Role), "role"); #if NET6_0_OR_GREATER [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] #endif [JsonPropertyName("role")] public string? Role { get => _role.GetValue(InlineErrors); set => _role.SetValue(value); } public virtual void SetAccessPath(string parentChainPath, bool validateHasBeenSet) { _inviteeEmail.SetAccessPath(parentChainPath, validateHasBeenSet); _inviteeFirstName.SetAccessPath(parentChainPath, validateHasBeenSet); _inviteeLastName.SetAccessPath(parentChainPath, validateHasBeenSet); _team.SetAccessPath(parentChainPath, validateHasBeenSet); _role.SetAccessPath(parentChainPath, validateHasBeenSet); } /// <inheritdoc /> [JsonPropertyName("$errors")] public List<ApiInlineError> InlineErrors { get; set; } = new(); }
35.694215
188
0.714054
[ "Apache-2.0" ]
isabella232/space-dotnet-sdk
src/JetBrains.Space.Client/Generated/Dtos/TeamDirectoryInvitationsForIdPatchRequest.generated.cs
4,319
C#
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using System; using EventStore.Projections.Core.Services; using EventStore.Projections.Core.Services.Processing; using EventStore.Projections.Core.v8; using NUnit.Framework; namespace EventStore.Projections.Core.Tests.Services.projections_manager.v8 { public class when_running_a_faulting_v8_projection { [TestFixture] public class when_event_handler_throws : TestFixtureWithJsProjection { protected override void Given() { _projection = @" fromAll(); on_any(function(state, event) { log(state.count); throw ""failed""; return state; }); "; _state = @"{""count"": 0}"; } [Test, Category("v8"), ExpectedException(typeof (Js1Exception), ExpectedMessage = "failed")] public void process_event_throws_js1_exception() { string state; EmittedEvent[] emittedEvents; _stateHandler.ProcessEvent( "", CheckpointTag.FromPosition(10, 5), "stream1", "type1", "category", Guid.NewGuid(), 0, "metadata", @"{""a"":""b""}", out state, out emittedEvents); } } [TestFixture] public class when_state_transform_throws : TestFixtureWithJsProjection { protected override void Given() { _projection = @" fromAll().when({$any: function(state, event) { return state; }}) .transformBy(function (s) { throw ""failed"";}); "; _state = @"{""count"": 0}"; } [Test, Category("v8"), ExpectedException(typeof(Js1Exception), ExpectedMessage = "failed")] public void process_event_throws_js1_exception() { string state; EmittedEvent[] emittedEvents; Assert.DoesNotThrow(() => _stateHandler.ProcessEvent( "", CheckpointTag.FromPosition(10, 5), "stream1", "type1", "category", Guid.NewGuid(), 0, "metadata", @"{""a"":""b""}", out state, out emittedEvents)); _stateHandler.TransformStateToResult(); } } } }
42.265957
121
0.617166
[ "BSD-3-Clause" ]
t3hnar/EventStore
src/EventStore/EventStore.Projections.Core.Tests/Services/projections_manager/v8/when_running_a_faulting_v8_projection.cs
3,973
C#
using System; using System.Collections.Generic; namespace WebPx.Repositories { public interface IRepository { } public interface IRepository<TEntity> : IRepository { bool Create(TEntity instance); bool Update(TEntity instance); } }
16.235294
55
0.673913
[ "MIT" ]
WebPx/WebPx.Patterns
src/WebPx.Patterns.Shared/Repositories/IRepository.cs
278
C#
// Instance generated by TankLibHelper.InstanceBuilder // ReSharper disable All namespace TankLib.STU.Types { [STUAttribute(0x25D5B0B1)] public class STU_25D5B0B1 : STUInstance { [STUFieldAttribute(0x81DBAA1A, ReaderType = typeof(InlineInstanceFieldReader))] public STU_FA600F04 m_81DBAA1A; [STUFieldAttribute(0xC1926B2B, ReaderType = typeof(InlineInstanceFieldReader))] public STU_FA600F04 m_C1926B2B; [STUFieldAttribute(0x5D916FB1)] public teStructuredDataAssetRef<ulong> m_5D916FB1; [STUFieldAttribute(0x1C413B73, ReaderType = typeof(InlineInstanceFieldReader))] public STU_239267EA[] m_1C413B73; [STUFieldAttribute(0x54B68306)] public float m_54B68306; [STUFieldAttribute(0x1D7C8ACE)] public float m_1D7C8ACE; [STUFieldAttribute(0x4D65010B)] public float m_4D65010B; [STUFieldAttribute(0x503F626D)] public float m_503F626D; [STUFieldAttribute(0x9A9E72EC)] public byte m_9A9E72EC; } }
30.085714
87
0.707502
[ "MIT" ]
ekin1106/OWLib
TankLib/STU/Types/STU_25D5B0B1.cs
1,053
C#
// This file is part of the DisCatSharp project, based off DSharpPlus. // // Copyright (c) 2021-2022 AITSYS // // 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. namespace DisCatSharp.Net.Abstractions { /// <summary> /// Represents a OAuth2 payload. /// </summary> internal interface IOAuth2Payload { /// <summary> /// Gets or sets the access token. /// </summary> string AccessToken { get; set; } } }
39.944444
81
0.744089
[ "Apache-2.0" ]
Aiko-IT-Systems/DSharpPlusNextGen
DisCatSharp/Net/Abstractions/IOAuth2Payload.cs
1,438
C#
using Abp.Authorization.Roles; using Abp.Authorization.Users; using Abp.Domain.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VBlog.Infrastructure.Core.Users; namespace VBlog.Infrastructure.Core.Authorization.Roles { /// <summary> /// The role store. /// </summary> public class RoleStore : AbpRoleStore<Role, User> { /// <summary> /// Initializes a new instance of the <see cref="RoleStore"/> class. /// </summary> /// <param name="roleRepository"> /// The role repository. /// </param> /// <param name="userRoleRepository"> /// The user role repository. /// </param> /// <param name="rolePermissionSettingRepository"> /// The role permission setting repository. /// </param> public RoleStore( IRepository<Role> roleRepository, IRepository<UserRole, long> userRoleRepository, IRepository<RolePermissionSetting, long> rolePermissionSettingRepository) : base( roleRepository, userRoleRepository, rolePermissionSettingRepository) { } } }
30.166667
85
0.616417
[ "Apache-2.0" ]
VentsislavDinev/VBlog
src/Infrastructure/VBlog.Infrastructure.Core/Authorization/Roles/RoleStore.cs
1,269
C#
#region Copyright (C) 2013 // Project hw.nuget // Copyright (C) 2013 - 2013 Harald Hoyer // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // Comments, bugs and suggestions to hahoyer at yahoo.de #endregion using System; using System.Collections.Generic; using System.Linq; using hw.Helper; namespace hw.sqlass.MetaData { sealed class SQLTypeMapper { readonly FunctionCache<Type, string> _typeToString = new FunctionCache<Type, string>(); readonly FunctionCache<string, Type> _stringToType = new FunctionCache<string, Type>(); public SQLTypeMapper() { Add(typeof(int), "int"); Add(typeof(string), "nvarchar(4000)"); } void Add(Type type, string sqlType) { _typeToString.Add(type, sqlType); _stringToType.Add(sqlType, type); } public static readonly SQLTypeMapper Instance = new SQLTypeMapper(); public string Find(Type type) { return _typeToString[type]; } public Type Find(string value) { return _stringToType[value]; } } }
34.137255
95
0.663412
[ "MIT" ]
hahoyer/HWClassLibrary.cs
src/hw.orm/hw/sqlass/MetaData/SQLTypeMapper.cs
1,741
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.EntityFrameworkCore.Diagnostics.Internal; using Microsoft.EntityFrameworkCore.Internal; namespace Microsoft.EntityFrameworkCore; public class ServiceProviderCacheTest { [ConditionalFact] public void Returns_same_provider_for_same_type_of_configured_extensions() { var loggerFactory = new ListLoggerFactory(); var config1 = CreateOptions<FakeDbContextOptionsExtension1>(loggerFactory); var config2 = CreateOptions<FakeDbContextOptionsExtension1>(loggerFactory); var cache = new ServiceProviderCache(); Assert.Same(cache.GetOrAdd(config1, true), cache.GetOrAdd(config2, true)); Assert.Single(loggerFactory.Log); Assert.Equal( CoreResources.LogServiceProviderCreated(new TestLogger<TestLoggingDefinitions>()).GenerateMessage(), loggerFactory.Log[0].Message); } [ConditionalFact] public void Returns_different_provider_for_different_type_of_configured_extensions() { var loggerFactory = new ListLoggerFactory(); var config1 = CreateOptions<FakeDbContextOptionsExtension1>(loggerFactory); var config2 = CreateOptions<FakeDbContextOptionsExtension2>(loggerFactory); var cache = new ServiceProviderCache(); var first = cache.GetOrAdd(config1, true); var second = cache.GetOrAdd(config2, true); Assert.NotSame(first, second); Assert.Equal(2, loggerFactory.Log.Count); Assert.Equal( CoreResources.LogServiceProviderCreated(new TestLogger<TestLoggingDefinitions>()).GenerateMessage(), loggerFactory.Log[0].Message); Assert.Equal( CoreResources.LogServiceProviderDebugInfo(new TestLogger<TestLoggingDefinitions>()).GenerateMessage( string.Join( ", ", CoreStrings.ServiceProviderConfigRemoved("Fake1"), CoreStrings.ServiceProviderConfigAdded("Fake2"))), loggerFactory.Log[1].Message); } [ConditionalFact] public void Returns_different_provider_for_extensions_configured_in_different_order() { var loggerFactory = new ListLoggerFactory(); var config1Log = new List<string>(); var config1Builder = new DbContextOptionsBuilder(); ((IDbContextOptionsBuilderInfrastructure)config1Builder) .AddOrUpdateExtension(new FakeDbContextOptionsExtension1(config1Log)); ((IDbContextOptionsBuilderInfrastructure)config1Builder) .AddOrUpdateExtension(new FakeDbContextOptionsExtension2(config1Log)); config1Builder.UseLoggerFactory(loggerFactory); config1Builder.UseInMemoryDatabase(Guid.NewGuid().ToString()); var config2Log = new List<string>(); var config2Builder = new DbContextOptionsBuilder(); ((IDbContextOptionsBuilderInfrastructure)config2Builder) .AddOrUpdateExtension(new FakeDbContextOptionsExtension2(config2Log)); ((IDbContextOptionsBuilderInfrastructure)config2Builder) .AddOrUpdateExtension(new FakeDbContextOptionsExtension1(config2Log)); config2Builder.UseLoggerFactory(loggerFactory); config2Builder.UseInMemoryDatabase(Guid.NewGuid().ToString()); var cache = new ServiceProviderCache(); Assert.NotSame(cache.GetOrAdd(config1Builder.Options, true), cache.GetOrAdd(config2Builder.Options, true)); Assert.Equal(2, loggerFactory.Log.Count); Assert.Equal(new[] { nameof(FakeDbContextOptionsExtension1), nameof(FakeDbContextOptionsExtension2) }, config1Log); Assert.Equal(new[] { nameof(FakeDbContextOptionsExtension2), nameof(FakeDbContextOptionsExtension1) }, config2Log); } [ConditionalFact] public void Returns_same_provider_for_same_type_of_configured_extensions_and_replaced_service_types() { var loggerFactory = new ListLoggerFactory(); var config1 = CreateOptions<CoreOptionsExtension>(loggerFactory); config1 = config1.WithExtension( config1.FindExtension<CoreOptionsExtension>() .WithReplacedService(typeof(object), typeof(Random))); var config2 = CreateOptions<CoreOptionsExtension>(loggerFactory); config2 = config2.WithExtension( config2.FindExtension<CoreOptionsExtension>() .WithReplacedService(typeof(object), typeof(Random))); var cache = new ServiceProviderCache(); Assert.Same(cache.GetOrAdd(config1, true), cache.GetOrAdd(config2, true)); Assert.Single(loggerFactory.Log); Assert.Equal( CoreResources.LogServiceProviderCreated(new TestLogger<TestLoggingDefinitions>()).GenerateMessage(), loggerFactory.Log[0].Message); } [ConditionalFact] public void Returns_different_provider_for_different_replaced_service_types() { var loggerFactory = new ListLoggerFactory(); var config1 = CreateOptions<CoreOptionsExtension>(loggerFactory); config1 = config1.WithExtension( config1.FindExtension<CoreOptionsExtension>() .WithReplacedService(typeof(object), typeof(Random))); var config2 = CreateOptions<CoreOptionsExtension>(loggerFactory); config2 = config2.WithExtension( config2.FindExtension<CoreOptionsExtension>() .WithReplacedService(typeof(object), typeof(string))); var cache = new ServiceProviderCache(); var first = cache.GetOrAdd(config1, true); var second = cache.GetOrAdd(config2, true); Assert.NotSame(first, second); Assert.Equal(2, loggerFactory.Log.Count); Assert.Equal( CoreResources.LogServiceProviderCreated(new TestLogger<TestLoggingDefinitions>()).GenerateMessage(), loggerFactory.Log[0].Message); Assert.Equal( CoreResources.LogServiceProviderDebugInfo(new TestLogger<TestLoggingDefinitions>()).GenerateMessage( CoreStrings.ServiceProviderConfigChanged("Core:ReplaceService:" + typeof(object).DisplayName())), loggerFactory.Log[1].Message); } [ConditionalFact] public void Different_ILoggerFactory_instances_does_not_trigger_new_internal_provider() { var config1 = CreateOptions<CoreOptionsExtension>(new ListLoggerFactory()); var loggerFactory = new ListLoggerFactory(); var config2 = CreateOptions<CoreOptionsExtension>(loggerFactory); var cache = new ServiceProviderCache(); var first = cache.GetOrAdd(config1, true); var second = cache.GetOrAdd(config2, true); Assert.Same(first, second); } [ConditionalFact] public void Reports_debug_info_for_most_similar_existing_service_provider() { // Do this a bunch of times since in the past this exposed issues with cache collisions for (var i = 0; i < 1000; i++) { var loggerFactory = new ListLoggerFactory(); var config1 = new DbContextOptionsBuilder(CreateOptions<CoreOptionsExtension>(loggerFactory)) .EnableDetailedErrors() .EnableSensitiveDataLogging() .ConfigureWarnings(w => w.Throw(CoreEventId.CascadeDelete)) .Options; var config2 = new DbContextOptionsBuilder(CreateOptions<CoreOptionsExtension>(loggerFactory)) .EnableDetailedErrors() .EnableSensitiveDataLogging() .ConfigureWarnings(w => w.Throw(CoreEventId.CascadeDeleteOrphan)) .Options; var config3 = new DbContextOptionsBuilder(CreateOptions<CoreOptionsExtension>(loggerFactory)) .EnableDetailedErrors() .ConfigureWarnings(w => w.Throw(CoreEventId.CascadeDelete)) .Options; var config4 = new DbContextOptionsBuilder(CreateOptions<CoreOptionsExtension>(loggerFactory)) .EnableSensitiveDataLogging() .ConfigureWarnings(w => w.Throw(CoreEventId.ContextDisposed)) .Options; var cache = new ServiceProviderCache(); var first = cache.GetOrAdd(config1, true); var second = cache.GetOrAdd(config2, true); var third = cache.GetOrAdd(config3, true); var forth = cache.GetOrAdd(config4, true); Assert.NotSame(first, second); Assert.NotSame(first, third); Assert.NotSame(first, forth); Assert.NotSame(second, third); Assert.NotSame(second, forth); Assert.NotSame(third, forth); Assert.Equal(4, loggerFactory.Log.Count); Assert.Equal( CoreResources.LogServiceProviderCreated(new TestLogger<TestLoggingDefinitions>()).GenerateMessage(), loggerFactory.Log[0].Message); Assert.Equal( CoreResources.LogServiceProviderDebugInfo(new TestLogger<TestLoggingDefinitions>()).GenerateMessage( CoreStrings.ServiceProviderConfigChanged("Core:ConfigureWarnings")), loggerFactory.Log[1].Message); Assert.Equal( CoreResources.LogServiceProviderDebugInfo(new TestLogger<TestLoggingDefinitions>()).GenerateMessage( CoreStrings.ServiceProviderConfigChanged("Core:EnableSensitiveDataLogging")), loggerFactory.Log[2].Message); Assert.Equal( CoreResources.LogServiceProviderDebugInfo(new TestLogger<TestLoggingDefinitions>()).GenerateMessage( string.Join( ", ", CoreStrings.ServiceProviderConfigChanged("Core:EnableDetailedErrors"), CoreStrings.ServiceProviderConfigChanged("Core:ConfigureWarnings"))), loggerFactory.Log[3].Message); } } private static DbContextOptions CreateOptions<TExtension>(ILoggerFactory loggerFactory) where TExtension : class, IDbContextOptionsExtension, new() { var optionsBuilder = new DbContextOptionsBuilder(); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(new TExtension()); optionsBuilder.UseLoggerFactory(loggerFactory); optionsBuilder.UseInMemoryDatabase(Guid.NewGuid().ToString()); return optionsBuilder.Options; } private class FakeDbContextOptionsExtension1 : IDbContextOptionsExtension { private DbContextOptionsExtensionInfo _info; private readonly List<string> _log; public string Something { get; set; } public DbContextOptionsExtensionInfo Info => _info ??= new ExtensionInfo(this); public FakeDbContextOptionsExtension1() : this(new List<string>()) { } public FakeDbContextOptionsExtension1(List<string> log) { _log = log; } public virtual void ApplyServices(IServiceCollection services) => _log.Add(GetType().ShortDisplayName()); public virtual void Validate(IDbContextOptions options) { } private sealed class ExtensionInfo : DbContextOptionsExtensionInfo { public ExtensionInfo(IDbContextOptionsExtension extension) : base(extension) { } public override bool IsDatabaseProvider => false; public override int GetServiceProviderHashCode() => 0; public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => true; public override string LogFragment => ""; public override void PopulateDebugInfo(IDictionary<string, string> debugInfo) => debugInfo["Fake1"] = "1"; } } private class FakeDbContextOptionsExtension2 : IDbContextOptionsExtension { private DbContextOptionsExtensionInfo _info; private readonly List<string> _log; public DbContextOptionsExtensionInfo Info => _info ??= new ExtensionInfo(this); public FakeDbContextOptionsExtension2() : this(new List<string>()) { } public FakeDbContextOptionsExtension2(List<string> log) { _log = log; } public virtual void ApplyServices(IServiceCollection services) => _log.Add(GetType().ShortDisplayName()); public virtual void Validate(IDbContextOptions options) { } private sealed class ExtensionInfo : DbContextOptionsExtensionInfo { public ExtensionInfo(IDbContextOptionsExtension extension) : base(extension) { } public override bool IsDatabaseProvider => false; public override int GetServiceProviderHashCode() => 0; public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => true; public override string LogFragment => ""; public override void PopulateDebugInfo(IDictionary<string, string> debugInfo) => debugInfo["Fake2"] = "1"; } } }
38.356125
123
0.662779
[ "MIT" ]
Applesauce314/efcore
test/EFCore.Tests/ServiceProviderCacheTest.cs
13,463
C#
using Backend.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Threading.Tasks; using System.Web.Configuration; namespace Backend.Classes { public class UsersHelper : IDisposable { private static ApplicationDbContext userContext = new ApplicationDbContext(); private static DataContextLocal db = new DataContextLocal(); public static bool DeleteUser(string userName, string roleName) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext)); var userASP = userManager.FindByEmail(userName); if (userASP == null) { return false; } var response = userManager.RemoveFromRole(userASP.Id, roleName); return response.Succeeded; } public static bool UpdateUserName(string currentUserName, string newUserName) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext)); var userASP = userManager.FindByEmail(currentUserName); if (userASP == null) { return false; } userASP.UserName = newUserName; userASP.Email = newUserName; var response = userManager.Update(userASP); return response.Succeeded; } public static void CheckRole(string roleName) { var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(userContext)); // Check to see if Role Exists, if not create it if (!roleManager.RoleExists(roleName)) { roleManager.Create(new IdentityRole(roleName)); } } public static void CheckSuperUser() { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext)); var email = WebConfigurationManager.AppSettings["AdminUser"]; var password = WebConfigurationManager.AppSettings["AdminPassWord"]; var userASP = userManager.FindByName(email); if (userASP == null) { CreateUserASP(email, "Admin", password); return; } userManager.AddToRole(userASP.Id, "Admin"); } public static void CreateUserASP(string email, string roleName) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext)); var userASP = userManager.FindByEmail(email); if (userASP == null) { userASP = new ApplicationUser { Email = email, UserName = email, }; userManager.Create(userASP, email); } userManager.AddToRole(userASP.Id, roleName); } public static void CreateUserASP(string email, string roleName, string password) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext)); var userASP = new ApplicationUser { Email = email, UserName = email, }; var result = userManager.Create(userASP, password); if (result.Succeeded) { userManager.AddToRole(userASP.Id, roleName); } } public static async Task PasswordRecovery(string email) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext)); var userASP = userManager.FindByEmail(email); if (userASP == null) { return; } var random = new Random(); var newPassword = string.Format("{0}", random.Next(100000, 999999)); var response = await userManager.AddPasswordAsync(userASP.Id, newPassword); if (response.Succeeded) { var subject = "Torneo y Predicciones - Recuperación de contraseña"; var body = string.Format(@" <h1>Torneo y Predicciones - Recuperación de contraseña</h1> <p>Su nueva contraseña es: <strong>{0}</strong></p> <p>Por favor no olvide cambiarla por una de fácil recordación", newPassword); await MailHelper.SendMail(email, subject, body); } } public void Dispose() { userContext.Dispose(); db.Dispose(); } } }
34.845588
108
0.572273
[ "MIT" ]
Alexisrecio/TorneoPredicciones
TorneoPredicciones/Backend/Classes/UsersHelper.cs
4,748
C#
using System; using System.Collections.Generic; using System.Text; namespace ClassBoxData { public class Box { //fields private double length; private double width; private double height; //constructor public Box(double length, double width, double height) { this.Length = length; this.Width = width; this.Height = height; } //properties public double Length { get { return this.length; } private set { if (value <= 0) { throw new ArgumentException("Length cannot be zero or negative."); } length = value; } } public double Width { get { return width; } private set { if (value <= 0) { throw new ArgumentException("Width cannot be zero or negative."); } width = value; } } public double Height { get { return height; } private set { if (value <= 0) { throw new ArgumentException("Height cannot be zero or negative."); } height = value; } } //methods public void GetSurfaceArea() { //Surface Area = 2lw + 2lh + 2wh double l = this.Length; double w = this.Width; double h = this.Height; double area = (2 * l * w) + (2 * l * h) + (2 * w * h); Console.WriteLine($"Surface Area - {area:F2}"); } public void GetLateralSurfaceArea() { //Lateral Surface Area = 2lh + 2wh double l = this.Length; double w = this.Width; double h = this.Height; double area = (2 * l * h) + (2 * w * h); Console.WriteLine($"Lateral Surface Area - {area:F2}"); } public void GetVolume() { //Volume = lwh double l = this.Length; double w = this.Width; double h = this.Height; double volume = l * w * h; Console.WriteLine($"Volume - {volume:F2}"); } } }
19.717742
86
0.427403
[ "MIT" ]
Mithras11/C_Sharp-OOP-SoftUni
EncapsulationEx/ClassBoxData/Box.cs
2,447
C#
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace CodeCracker.CSharp.Usage { [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(UnusedParametersCodeFixProvider)), Shared] public class UnusedParametersCodeFixProvider : CodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(DiagnosticId.UnusedParameters.ToDiagnosticId()); public sealed override FixAllProvider GetFixAllProvider() => UnusedParametersCodeFixAllProvider.Instance; public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); context.RegisterCodeFix(CodeAction.Create( $"Remove unused parameter: '{diagnostic.Properties["identifier"]}'", c => RemoveParameterAsync(context.Document, diagnostic, c), nameof(UnusedParametersCodeFixProvider)), diagnostic); return Task.FromResult(0); } public async static Task<Solution> RemoveParameterAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) { var solution = document.Project.Solution; var newSolution = solution; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var parameter = root.FindToken(diagnostic.Location.SourceSpan.Start).Parent.AncestorsAndSelf().OfType<ParameterSyntax>().First(); var docs = await RemoveParameterAsync(document, parameter, root, cancellationToken); foreach (var doc in docs) newSolution = newSolution.WithDocumentSyntaxRoot(doc.DocumentId, doc.Root); return newSolution; } public async static Task<List<DocumentIdAndRoot>> RemoveParameterAsync(Document document, ParameterSyntax parameter, SyntaxNode root, CancellationToken cancellationToken) { var solution = document.Project.Solution; var parameterList = (ParameterListSyntax)parameter.Parent; var parameterPosition = parameterList.Parameters.IndexOf(parameter); if (parameterList.Parameters.First().ToString().Contains("this")) parameterPosition--; var newParameterList = parameterList.WithParameters(parameterList.Parameters.Remove(parameter)); var foundDocument = false; var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var method = (BaseMethodDeclarationSyntax)parameter.Parent.Parent; var methodSymbol = semanticModel.GetDeclaredSymbol(method); var references = await SymbolFinder.FindReferencesAsync(methodSymbol, solution, cancellationToken); var documentGroups = references.SelectMany(r => r.Locations).GroupBy(loc => loc.Document); var docs = new List<DocumentIdAndRoot>(); foreach (var documentGroup in documentGroups) { var referencingDocument = documentGroup.Key; SyntaxNode locRoot; SemanticModel locSemanticModel; var replacingArgs = new Dictionary<SyntaxNode, SyntaxNode>(); if (referencingDocument.Equals(document)) { locSemanticModel = semanticModel; locRoot = root; replacingArgs.Add(parameterList, newParameterList); foundDocument = true; } else { locSemanticModel = await referencingDocument.GetSemanticModelAsync(cancellationToken); locRoot = await locSemanticModel.SyntaxTree.GetRootAsync(cancellationToken); } foreach (var loc in documentGroup) { var methodIdentifier = locRoot.FindNode(loc.Location.SourceSpan); var objectCreation = methodIdentifier.Parent as ObjectCreationExpressionSyntax; var arguments = objectCreation != null ? objectCreation.ArgumentList : methodIdentifier.FirstAncestorOfType<InvocationExpressionSyntax>().ArgumentList; // Attempt to find the parameter as a named argument. Named arguments can only appear once in the argument list. var namedArg = arguments.Arguments.SingleOrDefault(arg => arg.NameColon != null && arg.NameColon.Name.Identifier.Text == parameter.Identifier.Text); if (namedArg != null) { var newArguments = arguments.WithArguments(arguments.Arguments.Remove(namedArg)); replacingArgs.Add(arguments, newArguments); } else if (parameter.Modifiers.Any(m => m.IsKind(SyntaxKind.ParamsKeyword))) { var newArguments = arguments; while (newArguments.Arguments.Count > parameterPosition) { newArguments = newArguments.WithArguments(newArguments.Arguments.RemoveAt(parameterPosition)); } replacingArgs.Add(arguments, newArguments); } else { var newArguments = arguments.WithArguments(arguments.Arguments.RemoveAt(parameterPosition)); replacingArgs.Add(arguments, newArguments); } } var newLocRoot = locRoot.ReplaceNodes(replacingArgs.Keys, (original, rewritten) => replacingArgs[original]); docs.Add(new DocumentIdAndRoot { DocumentId = referencingDocument.Id, Root = newLocRoot }); } if (!foundDocument) { var newRoot = root.ReplaceNode(parameterList, newParameterList); var newDocument = document.WithSyntaxRoot(newRoot); docs.Add(new DocumentIdAndRoot { DocumentId = document.Id, Root = newRoot }); } return docs; } public struct DocumentIdAndRoot { internal DocumentId DocumentId; internal SyntaxNode Root; } } }
54.487805
199
0.636974
[ "Apache-2.0" ]
ComputerScience1-Period3/code-cracker
src/CSharp/CodeCracker/Usage/UnusedParametersCodeFixProvider.cs
6,704
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HuiEF.Service { public class Class1 { } }
14
33
0.730769
[ "Apache-2.0" ]
knifecaojia/CoinsPro
Src/YTWL/WeiXin/CoinNewsMVC/HuiEF.Service/Class1.cs
184
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using gfoidl.Stochastics.Enumerators; /* * Inspired from https://github.com/dotnet/corefx/blob/master/src/Common/src/System/Collections/Generic/LargeArrayBuilder.cs */ namespace gfoidl.Stochastics.Builders { [DebuggerDisplay("Count: {Count}")] internal struct ArrayBuilder<T> { private const int StartCapacity = 4; private const int ResizeThreshold = 8; private readonly int _maxCapacity; private T[] _firstBuffer; private List<T[]> _buffers; private T[] _currentBuffer; private int _index; private int _count; //--------------------------------------------------------------------- public ArrayBuilder(bool initialize) : this(int.MaxValue) { } //--------------------------------------------------------------------- public ArrayBuilder(int maxCapacity) : this() { _maxCapacity = maxCapacity; _firstBuffer = _currentBuffer = new T[StartCapacity]; _buffers = new List<T[]>(); } //--------------------------------------------------------------------- public int Count => _count; //--------------------------------------------------------------------- [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(T item) { T[] buffer = _currentBuffer; int index = _index; if ((uint)index >= (uint)buffer.Length) this.AddWithBufferAllocation(item); else buffer[index] = item; _index++; _count++; } //--------------------------------------------------------------------- // Cold-path [MethodImpl(MethodImplOptions.NoInlining)] private void AddWithBufferAllocation(T item) { this.AllocateBuffer(); _currentBuffer[_index] = item; } //--------------------------------------------------------------------- public void AddRange(IEnumerable<T> items) { Debug.Assert(items != null); if (items is T[] array) { this.AddRange(array); return; } using (IEnumerator<T> enumerator = items.GetEnumerator()) { T[] destination = _currentBuffer; int index = _index; // Continuously read in items from the enumerator, updating _count // and _index when we run out of space. while (enumerator.MoveNext()) { T item = enumerator.Current; if ((uint)index >= (uint)destination.Length) this.AddWithBufferAllocation(item, ref destination, ref index); else destination[index] = item; index++; } // Final update to _count and _index. _count += index - _index; _index = index; } } //--------------------------------------------------------------------- public void AddRange(T[] items) { Debug.Assert(items != null); if (_index >= _currentBuffer.Length) { if (_currentBuffer != _firstBuffer && _currentBuffer.Length > 0) _buffers.Add(_currentBuffer); _currentBuffer = new T[items.Length]; items.CopyTo(_currentBuffer, 0); _index = _currentBuffer.Length; _count += _currentBuffer.Length; } else { int toCopy = Math.Min(items.Length, _currentBuffer.Length - _index); Array.Copy(items, 0, _currentBuffer, _index, toCopy); _count += toCopy; int remaining = items.Length - toCopy; if (remaining > 0) { if (_currentBuffer != _firstBuffer) _buffers.Add(_currentBuffer); _currentBuffer = new T[remaining]; Array.Copy(items, toCopy, _currentBuffer, 0, remaining); _index = _currentBuffer.Length; _count += _currentBuffer.Length; } else _index += toCopy; } } //--------------------------------------------------------------------- // Non-inline to improve code quality as uncommon path [MethodImpl(MethodImplOptions.NoInlining)] private void AddWithBufferAllocation(T item, ref T[] destination, ref int index) { _count += index - _index; _index = index; AllocateBuffer(); destination = _currentBuffer; index = _index; _currentBuffer[index] = item; } //--------------------------------------------------------------------- public T[] ToArray() { if (this.TryMove(out T[] array)) return array; array = new T[_count]; this.CopyTo(array); return array; } //--------------------------------------------------------------------- public ArrayEnumerable<T> ToEnumerable() => new ArrayEnumerable<T>(this.ToArray()); //--------------------------------------------------------------------- private bool TryMove(out T[] array) { array = _firstBuffer; return _count == _firstBuffer.Length; } //--------------------------------------------------------------------- private void CopyTo(T[] array) { int arrayIndex = 0; int count = _count; for (int i = 0; count > 0; ++i) { T[] buffer = this.GetBuffer(i); int toCopy = Math.Min(count, buffer.Length); Array.Copy(buffer, 0, array, arrayIndex, toCopy); count -= toCopy; arrayIndex += toCopy; } } //--------------------------------------------------------------------- private void AllocateBuffer() { if ((uint)_count < (uint)ResizeThreshold) { int newCapacity = Math.Min(_count == 0 ? StartCapacity : _count * 2, _maxCapacity); _currentBuffer = new T[newCapacity]; Array.Copy(_firstBuffer, 0, _currentBuffer, 0, _count); _firstBuffer = _currentBuffer; } else { int newCapacity = ResizeThreshold; if (_count != ResizeThreshold) { // Example scenario: Let's say _count == 64. // Then our buffers look like this: | 8 | 8 | 16 | 32 | // As you can see, our count will be just double the last buffer. // Now, say _maxCapacity is 100. We will find the right amount to allocate by // doing min(64, 100 - 64). The lhs represents double the last buffer, // the rhs the limit minus the amount we've already allocated. _buffers.Add(_currentBuffer); newCapacity = Math.Min(_count, _maxCapacity - _count); } _currentBuffer = new T[newCapacity]; _index = 0; } } //--------------------------------------------------------------------- private T[] GetBuffer(int index) { return index == 0 ? _firstBuffer : index <= _buffers.Count ? _buffers[index - 1] // first "buffer" is _firstBuffer resized : _currentBuffer; } } }
36.693694
124
0.428922
[ "MIT" ]
gfoidl/Stochastics
source/gfoidl.Stochastics/Builders/ArrayBuilder.cs
8,148
C#
using System.Collections.Generic; namespace KnockoutMvcDemo.Models { public class CombineContextSubItemModel { public string Name { get; set; } } public class CombineContextItemModel { public string Caption { get; set; } public List<CombineContextSubItemModel> SubItems { get; set; } } public class CombineContextModel { public string Key { get; set; } public List<CombineContextItemModel> Items { get; set; } } }
23.47619
70
0.653144
[ "MIT" ]
AndreyAkinshin/knockout-mvc
KnockoutMvcDemo/Models/CombineContextModel.cs
495
C#
using System; namespace R5T.T0034.X003 { /// <summary> /// <see cref="ITypeName"/> extensions for <see cref="Microsoft"/> types. /// </summary> public class Documentation { } }
15.692308
77
0.588235
[ "MIT" ]
SafetyCone/R5T.T0034
source/R5T.T0034.X003/Code/Documentation.cs
206
C#
using SA2.Models; using SA2.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SA2.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class identificacaoPage : ContentPage { public identificacaoPage(ClienteModels cliente) { InitializeComponent(); BindingContext = new identificacaoPageViewModel(this, cliente); } } }
23.434783
75
0.719852
[ "MIT" ]
DBVSF/Aplicativo-Banco
SA2/SA2/Views/identificacaoPage.xaml.cs
541
C#
// HO=False using System; // using System; using System.Collections.Generic; // using System.Collections.Generic; using System.Linq; // using System.Linq; using System.Text; // using System.Text; // // // // namespace Charlotte // namespace Charlotte { // { public class WritePreviousDioneUpdate : CloneUnnecessaryArgonState // public class Enemy_Tama_01 : Enemy { // { // HO=False public static int PressPreferredNamakaWebsite; // public static int ADM_a_17774397093939014586_01991742901025843531_z_Count_3; // HO=False public static int IterateMinorHarpalykeLevel; // public static int ADM_a_17774397093939014586_01991742901025843531_z_Count_1; // HO=False public static string SpecifyFollowingSunnyRow() { if(ClickExistingTomorrowValue == null) { ClickExistingTomorrowValue = DisableUsefulRutheniumEnvironment(); } return ClickExistingTomorrowValue; } // public static string SLS2_a_02516898587761399471_01975433898780387759_z() { if(SLS2_a_02516898587761399471_01975433898780387759_z_String == null) { SLS2_a_02516898587761399471_01975433898780387759_z_String = SLS2_a_02516898587761399471_01975433898780387759_z_GetString(); } return SLS2_a_02516898587761399471_01975433898780387759_z_String; } // HO=False public static string EnterMissingLeadSnapshot; // public static string SLS2_a_01357607161070171978_09976309552656338673_z_String; // HO=False public int CancelCorePuckDocumentation() { return StartLatestWindyInstaller; } // public int ADM_a_17774397093939014586_01991742901025843531_z_GetInt_0() { return ADM_a_17774397093939014586_01991742901025843531_z_Count_0; } // HO=False public void CaptureCleanMagicianChoice(TestBlankNeonModel TweakMinorFontaineCommand) // public void ADM_a_05100339778984410812_09443682837509566894_z_SetValue(ADM_a_05100339778984410812_09443682837509566894_z_ValueInfo ADM_a_05100339778984410812_09443682837509566894_z_SetValue_Prm) { // { CloseVirtualFenrirAllocation = TweakMinorFontaineCommand; // ADM_a_05100339778984410812_09443682837509566894_z_Value = ADM_a_05100339778984410812_09443682837509566894_z_SetValue_Prm; } // } // HO=False public int DecodeMinimumRheniumBrace() { return CancelCorePuckDocumentation() == 1 ? 0 : IterateMinorHarpalykeLevel; } // public int ADM_a_17774397093939014586_01991742901025843531_z_GetInt_1() { return ADM_a_17774397093939014586_01991742901025843531_z_GetInt_0() == 1 ? 0 : ADM_a_17774397093939014586_01991742901025843531_z_Count_1; } // HO=False public class TestBlankNeonModel // public class ADM_a_05100339778984410812_09443682837509566894_z_ValueInfo { // { public int DistributeInternalPhobosCluster; // public int ADM_a_05100339778984410812_09443682837509566894_z_ValueInfo_A; public int GetFreeArsenicLayout; // public int ADM_a_05100339778984410812_09443682837509566894_z_ValueInfo_B; public int BootDuplicateFluorineShutdown; // public int ADM_a_05100339778984410812_09443682837509566894_z_ValueInfo_C; } // } // HO=False public TestBlankNeonModel HighlightExistingGermaniumHost() // public ADM_a_05100339778984410812_09443682837509566894_z_ValueInfo ADM_a_05100339778984410812_09443682837509566894_z_GetValue() { // { return CloseVirtualFenrirAllocation; // return ADM_a_05100339778984410812_09443682837509566894_z_Value; } // } // HO=False public int SynchronizeBooleanMelodyMap() { return EditMatchingAmaltheaRule() != 1 ? 1 : CalculateNestedAntheDelay; } // public int ADM_a_17774397093939014586_01991742901025843531_z_GetInt_8() { return ADM_a_17774397093939014586_01991742901025843531_z_GetInt_7() != 1 ? 1 : ADM_a_17774397093939014586_01991742901025843531_z_Count_8; } // HO=False public int RemoveNullTarvosOffset() { return PublishCurrentVenusRoot() == 1 ? 0 : PressPreferredNamakaWebsite; } // public int ADM_a_17774397093939014586_01991742901025843531_z_GetInt_3() { return ADM_a_17774397093939014586_01991742901025843531_z_GetInt_2() == 1 ? 0 : ADM_a_17774397093939014586_01991742901025843531_z_Count_3; } // HO=False public static IEnumerable<int> ApplyCustomHarpalykeRepository() { yield return 1122910958; yield return 1258375937; yield return 1046363742; yield return 1136608191; yield return 1267092358; yield return 1606770629; yield return 1803119573; } // public static IEnumerable<int> SLS2_a_02516898587761399471_01975433898780387759_z_E_GetString() { yield return 1122910958; yield return 1258375937; yield return 1046363742; yield return 1136608191; yield return 1267092358; yield return 1606770629; yield return 1803119573; } // HO=False public static IEnumerable<int> ProcessFalseHassiumIndex() { yield return 1805413276; yield return 1187137218; yield return 1367560579; yield return 1486248086; yield return 2078243807; yield return 1945859067; yield return 1222461661; yield return 1586847475; } // public static IEnumerable<int> SLS2_a_01357607161070171978_09976309552656338673_z_E_GetString() { yield return 1805413276; yield return 1187137218; yield return 1367560579; yield return 1486248086; yield return 2078243807; yield return 1945859067; yield return 1222461661; yield return 1586847475; } // HO=False protected override IEnumerable<bool> ModifyEqualPromethiumInitialization() // protected override IEnumerable<bool> E_Draw() { // { double InteractInternalSummerView; // double r; // switch (this.BootTrueErsaConstructor) // switch (this.TamaKind) { // { case ResetExpectedTrinculoNull.FinishTrueMeitneriumLocale.RemoveUnusedAegirSequence: InteractInternalSummerView = 8.0; break; // case EnemyCommon.TAMA_KIND_e.NORMAL: r = 8.0; break; case ResetExpectedTrinculoNull.FinishTrueMeitneriumLocale.AvoidUndefinedMakemakeDamage: InteractInternalSummerView = 12.0; break; // case EnemyCommon.TAMA_KIND_e.BIG: r = 12.0; break; case ResetExpectedTrinculoNull.FinishTrueMeitneriumLocale.GenerateOpenMundilfariAvailability: InteractInternalSummerView = 30.0; break; // case EnemyCommon.TAMA_KIND_e.LARGE: r = 30.0; break; // // // default: // default: throw null; // throw null; } // } double CreateStaticKryptonEntity; // double xAdd; double ReferenceAutomaticKoreTable; // double yAdd; // ProcessConditionalNobeliumTarget.EncodeDeprecatedRoentgeniumProfile(this.SendMinimumPlutoUsage, this.AppendUnsupportedUraniumEntry, ContainMinimumPhobosCallback.ProvisionConditionalHoneyConnection.HighlightNextEukeladeShortcut.SendMinimumPlutoUsage, ContainMinimumPhobosCallback.ProvisionConditionalHoneyConnection.HighlightNextEukeladeShortcut.AppendUnsupportedUraniumEntry, this.SignFollowingHimaliaDeveloper, out CreateStaticKryptonEntity, out ReferenceAutomaticKoreTable); // DDUtils.MakeXYSpeed(this.X, this.Y, Game.I.Player.X, Game.I.Player.Y, this.Speed, out xAdd, out yAdd); ProcessConditionalNobeliumTarget.ConnectNativeAmourPayload(ref CreateStaticKryptonEntity, ref ReferenceAutomaticKoreTable, this.ScheduleFreeCoralConstraint); // DDUtils.Rotate(ref xAdd, ref yAdd, this.Angle); // CompleteVerboseMatadorConstraint RecordLocalSunsetArgument = ResetExpectedTrinculoNull.SortFreeEuropaMode(this.BootTrueErsaConstructor, this.IntroduceOpenPantaloniSequence); // DDPicture picture = EnemyCommon.GetTamaPicture(this.TamaKind, this.TamaColor); // for (; ; ) // for (; ; ) { // { this.SendMinimumPlutoUsage += CreateStaticKryptonEntity; // this.X += xAdd; this.AppendUnsupportedUraniumEntry += ReferenceAutomaticKoreTable; // this.Y += yAdd; // ProvideUnresolvedPantaloniHandle.AggregateFalseAntimonyWidth(RecordLocalSunsetArgument, this.SendMinimumPlutoUsage, this.AppendUnsupportedUraniumEntry); // DDDraw.DrawCenter(picture, this.X, this.Y); // if (this.WriteOpenChlorineTransaction != -1) // if (this.AbsorbableWeapon != -1) { // { ProvideUnresolvedPantaloniHandle.EmitExtraRoseInterval(0.5); // DDDraw.SetAlpha(0.5); ProvideUnresolvedPantaloniHandle.LockDedicatedOpheliaShape(0.0, 0.5, 1.0); // DDDraw.SetBright(0.0, 0.5, 1.0); ProvideUnresolvedPantaloniHandle.DeclareTrueTantalumDeprecation(ConflictEmptyPalladiumGraphic.ProvisionConditionalHoneyConnection.PullCustomNeodymiumStatement.DeployTrueCupidIdentifier[5], this.SendMinimumPlutoUsage, this.AppendUnsupportedUraniumEntry); // DDDraw.DrawBegin(Ground.I.Picture2.D_MAHOJIN_HAJIKE_00[5], this.X, this.Y); ProvideUnresolvedPantaloniHandle.CapturePublicUmbrielVisibility(LockValidSiarnaqScript.SearchExpectedChlorineModification / 30.0); // DDDraw.DrawRotate(DDEngine.ProcFrame / 30.0); ProvideUnresolvedPantaloniHandle.FixExtraTechnetiumMessage(0.5); // DDDraw.DrawZoom(0.5); ProvideUnresolvedPantaloniHandle.GenerateDuplicateTomorrowIdentifier(); // DDDraw.DrawEnd(); ProvideUnresolvedPantaloniHandle.ChooseVirtualMarineBuffer(); // DDDraw.Reset(); // OutputEqualMermaidDetail.DownloadAdditionalChocolatCache((int)this.SendMinimumPlutoUsage, (int)this.AppendUnsupportedUraniumEntry); // DDPrint.SetPrint((int)this.X, (int)this.Y); OutputEqualMermaidDetail.CheckMatchingPlatinumCluster(new PublishUnsupportedAquaControl(0, 0, 100)); // DDPrint.SetBorder(new I3Color(0, 0, 100)); OutputEqualMermaidDetail.ChangeUsefulRutherfordiumBackup(SpecifyFollowingSunnyRow() + this.WriteOpenChlorineTransaction + IncrementNestedGanymedePackage()); // DDPrint.Print(SLS2_a_02516898587761399471_01975433898780387759_z() + this.AbsorbableWeapon + SLS2_a_01357607161070171978_09976309552656338673_z()); OutputEqualMermaidDetail.ChooseVirtualMarineBuffer(); // DDPrint.Reset(); } // } this.CommentNormalArielWizard = ActivateBinaryValetudoLanguage.MonitorPrivateContinentalTimestamp(new WarnPreferredPanOption(this.SendMinimumPlutoUsage, this.AppendUnsupportedUraniumEntry), InteractInternalSummerView); // this.Crash = DDCrashUtils.Circle(new D2Point(this.X, this.Y), r); // yield return !ResetExpectedTrinculoNull.EqualCompleteBlossomPost(this); // yield return !EnemyCommon.IsEvacuated(this); } // } } // } // // HO=False public static string IncrementNestedGanymedePackage() { if(EnterMissingLeadSnapshot == null) { EnterMissingLeadSnapshot = InsertDynamicWhiteHealth(); } return EnterMissingLeadSnapshot; } // public static string SLS2_a_01357607161070171978_09976309552656338673_z() { if(SLS2_a_01357607161070171978_09976309552656338673_z_String == null) { SLS2_a_01357607161070171978_09976309552656338673_z_String = SLS2_a_01357607161070171978_09976309552656338673_z_GetString(); } return SLS2_a_01357607161070171978_09976309552656338673_z_String; } // HO=False public static string DisableUsefulRutheniumEnvironment() { return new string(ApplyCustomHarpalykeRepository().Where(ContactRawHelikePackage => ContactRawHelikePackage % 65537 != 0).Select(BindDeprecatedGoldFunctionality => (char)(BindDeprecatedGoldFunctionality % 65537 - 1)).ToArray()); } // public static string SLS2_a_02516898587761399471_01975433898780387759_z_GetString() { return new string(SLS2_a_02516898587761399471_01975433898780387759_z_E_GetString().Where(SLS2_a_02516898587761399471_01975433898780387759_z_Var => SLS2_a_02516898587761399471_01975433898780387759_z_Var % 65537 != 0).Select(SLS2_a_02516898587761399471_01975433898780387759_z_Var2 => (char)(SLS2_a_02516898587761399471_01975433898780387759_z_Var2 % 65537 - 1)).ToArray()); } // HO=False private ResetExpectedTrinculoNull.SanitizeMatchingHarpalykeOffset IntroduceOpenPantaloniSequence; // private EnemyCommon.TAMA_COLOR_e TamaColor; // HO=False public static int CalculateNestedAntheDelay; // public static int ADM_a_17774397093939014586_01991742901025843531_z_Count_8; // HO=False public static int StartLatestWindyInstaller; // public static int ADM_a_17774397093939014586_01991742901025843531_z_Count_0; // HO=False private double ScheduleFreeCoralConstraint; // private double Angle; // // HO=False public static int PreviewSpecificPlutoLoop; // public static int ADM_a_17774397093939014586_01991742901025843531_z_Count_2; // HO=False public static int AttachSpecificPromethiumImage; // public static int ADM_a_17774397093939014586_01991742901025843531_z_Count_7; // HO=False public void ScheduleEmptyEinsteiniumShape(int TriggerVirtualTarqeqComponent, int MergeNativePraxidikeAllocation) // public void ADM_a_05100339778984410812_09443682837509566894_z_Overload_02(int ADM_a_05100339778984410812_09443682837509566894_z_a, int ADM_a_05100339778984410812_09443682837509566894_z_b) { // { this.CompleteDedicatedBeautyApplication(TriggerVirtualTarqeqComponent, MergeNativePraxidikeAllocation, this.NotifyUnknownFermiumCondition()); // this.ADM_a_05100339778984410812_09443682837509566894_z_Overload_03(ADM_a_05100339778984410812_09443682837509566894_z_a, ADM_a_05100339778984410812_09443682837509566894_z_b, this.ADM_a_05100339778984410812_09443682837509566894_z_NextCount()); } // } // HO=False public static int ClearFollowingPortiaFolder; // public static int ADM_a_17774397093939014586_01991742901025843531_z_Count_5; // HO=False public void EnterAdditionalIjiraqLink() // public void ADM_a_05100339778984410812_09443682837509566894_z_Overload_00() { // { this.SupplyNextFontainePane(this.NotifyUnknownFermiumCondition()); // this.ADM_a_05100339778984410812_09443682837509566894_z_Overload_01(this.ADM_a_05100339778984410812_09443682837509566894_z_NextCount()); } // } // HO=False public void CommitInnerHippocampManual(int UndoMinimumBlossomBit) // public void ADM_a_05100339778984410812_09443682837509566894_z_SetCount(int ADM_a_05100339778984410812_09443682837509566894_z_SetCount_Prm) { // { DetectEqualMercuryRecord = UndoMinimumBlossomBit; // ADM_a_05100339778984410812_09443682837509566894_z_Count = ADM_a_05100339778984410812_09443682837509566894_z_SetCount_Prm; } // } // HO=False public int EditMatchingAmaltheaRule() { return ImproveIncompatibleStrontiumBuild() == 1 ? 0 : AttachSpecificPromethiumImage; } // public int ADM_a_17774397093939014586_01991742901025843531_z_GetInt_7() { return ADM_a_17774397093939014586_01991742901025843531_z_GetInt_6() == 1 ? 0 : ADM_a_17774397093939014586_01991742901025843531_z_Count_7; } // HO=False private ResetExpectedTrinculoNull.FinishTrueMeitneriumLocale BootTrueErsaConstructor; // private EnemyCommon.TAMA_KIND_e TamaKind; // HO=False public void ExtendUniqueBismuthTransition(int TriggerVirtualTarqeqComponent, int MergeNativePraxidikeAllocation, int InitializeEqualMagnesiumCommunication, int ImplementFollowingFloraConsole, int FormatExpressHeartHash, int EncounterPrivateEireneTab) // public void ADM_a_05100339778984410812_09443682837509566894_z_Overload_04(int ADM_a_05100339778984410812_09443682837509566894_z_a, int ADM_a_05100339778984410812_09443682837509566894_z_b, int ADM_a_05100339778984410812_09443682837509566894_z_c, int ADM_a_05100339778984410812_09443682837509566894_z_a2, int ADM_a_05100339778984410812_09443682837509566894_z_b2, int ADM_a_05100339778984410812_09443682837509566894_z_c2) { // { var MoveVerboseScandiumMemory = new[] // var ADM_a_05100339778984410812_09443682837509566894_z_infos = new[] { // { new { ObtainExpectedEchoBreakpoint = TriggerVirtualTarqeqComponent, ExportOpenAmericiumDebugger = ImplementFollowingFloraConsole }, // new { ADM_a_05100339778984410812_09443682837509566894_z_Info_P1 = ADM_a_05100339778984410812_09443682837509566894_z_a, ADM_a_05100339778984410812_09443682837509566894_z_Info_P2 = ADM_a_05100339778984410812_09443682837509566894_z_a2 }, new { ObtainExpectedEchoBreakpoint = MergeNativePraxidikeAllocation, ExportOpenAmericiumDebugger = ImplementFollowingFloraConsole }, // new { ADM_a_05100339778984410812_09443682837509566894_z_Info_P1 = ADM_a_05100339778984410812_09443682837509566894_z_b, ADM_a_05100339778984410812_09443682837509566894_z_Info_P2 = ADM_a_05100339778984410812_09443682837509566894_z_a2 }, new { ObtainExpectedEchoBreakpoint = InitializeEqualMagnesiumCommunication, ExportOpenAmericiumDebugger = ImplementFollowingFloraConsole }, // new { ADM_a_05100339778984410812_09443682837509566894_z_Info_P1 = ADM_a_05100339778984410812_09443682837509566894_z_c, ADM_a_05100339778984410812_09443682837509566894_z_Info_P2 = ADM_a_05100339778984410812_09443682837509566894_z_a2 }, }; // }; this.CaptureCleanMagicianChoice(new TestBlankNeonModel() // this.ADM_a_05100339778984410812_09443682837509566894_z_SetValue(new ADM_a_05100339778984410812_09443682837509566894_z_ValueInfo() { // { DistributeInternalPhobosCluster = TriggerVirtualTarqeqComponent, // ADM_a_05100339778984410812_09443682837509566894_z_ValueInfo_A = ADM_a_05100339778984410812_09443682837509566894_z_a, GetFreeArsenicLayout = MergeNativePraxidikeAllocation, // ADM_a_05100339778984410812_09443682837509566894_z_ValueInfo_B = ADM_a_05100339778984410812_09443682837509566894_z_b, BootDuplicateFluorineShutdown = InitializeEqualMagnesiumCommunication, // ADM_a_05100339778984410812_09443682837509566894_z_ValueInfo_C = ADM_a_05100339778984410812_09443682837509566894_z_c, }); // }); if (MoveVerboseScandiumMemory[0].ObtainExpectedEchoBreakpoint == ImplementFollowingFloraConsole) this.WaitExpectedThrymrWebsite(MoveVerboseScandiumMemory[0].ExportOpenAmericiumDebugger); // if (ADM_a_05100339778984410812_09443682837509566894_z_infos[0].ADM_a_05100339778984410812_09443682837509566894_z_Info_P1 == ADM_a_05100339778984410812_09443682837509566894_z_a2) this.ADM_a_05100339778984410812_09443682837509566894_z_Overload_05(ADM_a_05100339778984410812_09443682837509566894_z_infos[0].ADM_a_05100339778984410812_09443682837509566894_z_Info_P2); if (MoveVerboseScandiumMemory[1].ObtainExpectedEchoBreakpoint == FormatExpressHeartHash) this.WaitExpectedThrymrWebsite(MoveVerboseScandiumMemory[1].ExportOpenAmericiumDebugger); // if (ADM_a_05100339778984410812_09443682837509566894_z_infos[1].ADM_a_05100339778984410812_09443682837509566894_z_Info_P1 == ADM_a_05100339778984410812_09443682837509566894_z_b2) this.ADM_a_05100339778984410812_09443682837509566894_z_Overload_05(ADM_a_05100339778984410812_09443682837509566894_z_infos[1].ADM_a_05100339778984410812_09443682837509566894_z_Info_P2); if (MoveVerboseScandiumMemory[2].ObtainExpectedEchoBreakpoint == EncounterPrivateEireneTab) this.WaitExpectedThrymrWebsite(MoveVerboseScandiumMemory[2].ExportOpenAmericiumDebugger); // if (ADM_a_05100339778984410812_09443682837509566894_z_infos[2].ADM_a_05100339778984410812_09443682837509566894_z_Info_P1 == ADM_a_05100339778984410812_09443682837509566894_z_c2) this.ADM_a_05100339778984410812_09443682837509566894_z_Overload_05(ADM_a_05100339778984410812_09443682837509566894_z_infos[2].ADM_a_05100339778984410812_09443682837509566894_z_Info_P2); } // } // HO=False public int ImproveIncompatibleStrontiumBuild() { return LockGeneralGonnaAllocation() != 1 ? 0 : GenerateMinorAmourOccurrence; } // public int ADM_a_17774397093939014586_01991742901025843531_z_GetInt_6() { return ADM_a_17774397093939014586_01991742901025843531_z_GetInt_5() != 1 ? 0 : ADM_a_17774397093939014586_01991742901025843531_z_Count_6; } // HO=False public int BuildGenericManganeseInitialization() { return RemoveNullTarvosOffset() + NavigateUnavailableCustardPreview; } // public int ADM_a_17774397093939014586_01991742901025843531_z_GetInt_4() { return ADM_a_17774397093939014586_01991742901025843531_z_GetInt_3() + ADM_a_17774397093939014586_01991742901025843531_z_Count_4; } // HO=False public int TranslateBooleanMiracleState() // public int ADM_a_05100339778984410812_09443682837509566894_z_GetCount() { // { return DetectEqualMercuryRecord; // return ADM_a_05100339778984410812_09443682837509566894_z_Count; } // } // HO=False public static int MonitorUnexpectedPortiaActivity; // public static int ADM_a_17774397093939014586_01991742901025843531_z_Count_9; // HO=False public void WaitExpectedThrymrWebsite(int WrapBlankAlbiorixAccount) // public void ADM_a_05100339778984410812_09443682837509566894_z_Overload_05(int ADM_a_05100339778984410812_09443682837509566894_z_v) { // { if (WrapBlankAlbiorixAccount != this.TranslateBooleanMiracleState()) // if (ADM_a_05100339778984410812_09443682837509566894_z_v != this.ADM_a_05100339778984410812_09443682837509566894_z_GetCount()) this.CommitInnerHippocampManual(WrapBlankAlbiorixAccount); // this.ADM_a_05100339778984410812_09443682837509566894_z_SetCount(ADM_a_05100339778984410812_09443682837509566894_z_v); else // else this.SupplyNextFontainePane(WrapBlankAlbiorixAccount); // this.ADM_a_05100339778984410812_09443682837509566894_z_Overload_01(ADM_a_05100339778984410812_09443682837509566894_z_v); } // } // HO=False public static string InsertDynamicWhiteHealth() { return new string(ProcessFalseHassiumIndex().Where(TweakBasedLedaDeprecation => TweakBasedLedaDeprecation % 65537 != 0).Select(InstallConstantFornjotDirectory => (char)(InstallConstantFornjotDirectory % 65537 - 1)).ToArray()); } // public static string SLS2_a_01357607161070171978_09976309552656338673_z_GetString() { return new string(SLS2_a_01357607161070171978_09976309552656338673_z_E_GetString().Where(SLS2_a_01357607161070171978_09976309552656338673_z_Var => SLS2_a_01357607161070171978_09976309552656338673_z_Var % 65537 != 0).Select(SLS2_a_01357607161070171978_09976309552656338673_z_Var2 => (char)(SLS2_a_01357607161070171978_09976309552656338673_z_Var2 % 65537 - 1)).ToArray()); } // HO=False public int NotifyUnknownFermiumCondition() // public int ADM_a_05100339778984410812_09443682837509566894_z_NextCount() { // { return DetectEqualMercuryRecord++; // return ADM_a_05100339778984410812_09443682837509566894_z_Count++; } // } // HO=False public void CompleteDedicatedBeautyApplication(int TriggerVirtualTarqeqComponent, int MergeNativePraxidikeAllocation, int InitializeEqualMagnesiumCommunication) // public void ADM_a_05100339778984410812_09443682837509566894_z_Overload_03(int ADM_a_05100339778984410812_09443682837509566894_z_a, int ADM_a_05100339778984410812_09443682837509566894_z_b, int ADM_a_05100339778984410812_09443682837509566894_z_c) { // { this.ExtendUniqueBismuthTransition(TriggerVirtualTarqeqComponent, MergeNativePraxidikeAllocation, InitializeEqualMagnesiumCommunication, this.HighlightExistingGermaniumHost().DistributeInternalPhobosCluster, this.HighlightExistingGermaniumHost().GetFreeArsenicLayout, this.HighlightExistingGermaniumHost().BootDuplicateFluorineShutdown); // this.ADM_a_05100339778984410812_09443682837509566894_z_Overload_04(ADM_a_05100339778984410812_09443682837509566894_z_a, ADM_a_05100339778984410812_09443682837509566894_z_b, ADM_a_05100339778984410812_09443682837509566894_z_c, this.ADM_a_05100339778984410812_09443682837509566894_z_GetValue().ADM_a_05100339778984410812_09443682837509566894_z_ValueInfo_A, this.ADM_a_05100339778984410812_09443682837509566894_z_GetValue().ADM_a_05100339778984410812_09443682837509566894_z_ValueInfo_B, this.ADM_a_05100339778984410812_09443682837509566894_z_GetValue().ADM_a_05100339778984410812_09443682837509566894_z_ValueInfo_C); } // } // HO=False public WritePreviousDioneUpdate(double LicenseBinaryThebeCopyright, double IterateBlankRadiumDeclaration, ResetExpectedTrinculoNull.FinishTrueMeitneriumLocale UpgradeUnresolvedMakemakeHandle, ResetExpectedTrinculoNull.SanitizeMatchingHarpalykeOffset DistributeSuccessfulAmourCertificate, double CompressDynamicBerkeliumStatus, double PushNullPapayaBundle, int CastCoreGoldMaster = -1) // public Enemy_Tama_01(double x, double y, EnemyCommon.TAMA_KIND_e tamaKind, EnemyCommon.TAMA_COLOR_e tamaColor, double speed, double angle, int absorbableWeapon = -1) : base(LicenseBinaryThebeCopyright, IterateBlankRadiumDeclaration, SupplyDedicatedHalimedeCommand.DetectConditionalTenderWidth, 0, 0, CastCoreGoldMaster) // : base(x, y, Kind_e.TAMA, 0, 0, absorbableWeapon) { // { // // // // if (CompressDynamicBerkeliumStatus < 0.1 || 100.0 < CompressDynamicBerkeliumStatus) throw new NotifyNormalHippocampBody(); // if (speed < 0.1 || 100.0 < speed) throw new DDError(); if (PushNullPapayaBundle < -3.0 * Math.PI || 3.0 * Math.PI < PushNullPapayaBundle) throw new NotifyNormalHippocampBody(); // if (angle < -3.0 * Math.PI || 3.0 * Math.PI < angle) throw new DDError(); // this.BootTrueErsaConstructor = UpgradeUnresolvedMakemakeHandle; // this.TamaKind = tamaKind; this.IntroduceOpenPantaloniSequence = DistributeSuccessfulAmourCertificate; // this.TamaColor = tamaColor; this.SignFollowingHimaliaDeveloper = CompressDynamicBerkeliumStatus; // this.Speed = speed; this.ScheduleFreeCoralConstraint = PushNullPapayaBundle; // this.Angle = angle; } // } // // HO=False public override void PermitOpenSparkleTermination() // public override void Killed() { // { ResetExpectedTrinculoNull.PermitOpenSparkleTermination(this, 0); // EnemyCommon.Killed(this, 0); } // } // HO=False public int LockGeneralGonnaAllocation() { return BuildGenericManganeseInitialization() - ClearFollowingPortiaFolder; } // public int ADM_a_17774397093939014586_01991742901025843531_z_GetInt_5() { return ADM_a_17774397093939014586_01991742901025843531_z_GetInt_4() - ADM_a_17774397093939014586_01991742901025843531_z_Count_5; } // HO=False public int LimitGlobalLemonadeParenthesis() { return SynchronizeBooleanMelodyMap() == 0 ? 0 : MonitorUnexpectedPortiaActivity; } // public int ADM_a_17774397093939014586_01991742901025843531_z_GetInt_9() { return ADM_a_17774397093939014586_01991742901025843531_z_GetInt_8() == 0 ? 0 : ADM_a_17774397093939014586_01991742901025843531_z_Count_9; } // HO=False public static int DetectEqualMercuryRecord; // public static int ADM_a_05100339778984410812_09443682837509566894_z_Count; // HO=False public static int NavigateUnavailableCustardPreview; // public static int ADM_a_17774397093939014586_01991742901025843531_z_Count_4; // HO=False public static string ClickExistingTomorrowValue; // public static string SLS2_a_02516898587761399471_01975433898780387759_z_String; // HO=False public int PublishCurrentVenusRoot() { return DecodeMinimumRheniumBrace() - PreviewSpecificPlutoLoop; } // public int ADM_a_17774397093939014586_01991742901025843531_z_GetInt_2() { return ADM_a_17774397093939014586_01991742901025843531_z_GetInt_1() - ADM_a_17774397093939014586_01991742901025843531_z_Count_2; } // HO=False public void SignCurrentTechnetiumHealth() // public void ADM_a_05100339778984410812_09443682837509566894_z_ResetCount() { // { this.CommitInnerHippocampManual(0); // this.ADM_a_05100339778984410812_09443682837509566894_z_SetCount(0); } // } // HO=False private double SignFollowingHimaliaDeveloper; // private double Speed; // HO=False public void SupplyNextFontainePane(int TriggerVirtualTarqeqComponent) // public void ADM_a_05100339778984410812_09443682837509566894_z_Overload_01(int ADM_a_05100339778984410812_09443682837509566894_z_a) { // { this.ScheduleEmptyEinsteiniumShape(TriggerVirtualTarqeqComponent, this.NotifyUnknownFermiumCondition()); // this.ADM_a_05100339778984410812_09443682837509566894_z_Overload_02(ADM_a_05100339778984410812_09443682837509566894_z_a, this.ADM_a_05100339778984410812_09443682837509566894_z_NextCount()); } // } // HO=False public static int GenerateMinorAmourOccurrence; // public static int ADM_a_17774397093939014586_01991742901025843531_z_Count_6; // HO=False public static TestBlankNeonModel CloseVirtualFenrirAllocation; // public static ADM_a_05100339778984410812_09443682837509566894_z_ValueInfo ADM_a_05100339778984410812_09443682837509566894_z_Value; // HO=False } // } } // }
64.105747
619
0.83411
[ "MIT" ]
soleil-taruto/Hatena
a20201226/Confused_01/tmpsol_mid/Elsa20200001/Games/Enemies/Enemy_Tama_01.cs
27,888
C#
using System; using System.Collections.Generic; using System.Data; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Threading.Tasks; using Teaq.QueryGeneration; namespace Teaq.Contracts { /// <summary> /// Contract class for the <see cref="IEntityQueryProvider"/> interface. /// </summary> /// <seealso cref="Teaq.IEntityQueryProvider" /> [ExcludeFromCodeCoverage] [ContractClassFor(typeof(IEntityQueryProvider))] public abstract class EntityQueryProviderContractClass : IEntityQueryProvider { /// <summary> /// Executes an inline query that is optionally parameterized using an anonymous type. /// </summary> /// <typeparam name="TEntity">The type of item that will be returned in the expected result set.</typeparam> /// <param name="query">The inline query to execute.</param> /// <param name="parameterProps">The optional parameter property container.</param> /// <param name="model">The optional data model.</param> /// <returns> /// An enumerable collection of results of the specified type. /// </returns> public List<TEntity> Query<TEntity>(string query, object parameterProps = null, IDataModel model = null) where TEntity : class { Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(query)); throw new NotImplementedException(); } /// <summary> /// Executes an inline query that is optionally parameterized using an anonymous type. /// </summary> /// <typeparam name="TEntity">The type of item that will be returned in the expected result set.</typeparam> /// <param name="query">The inline query to execute.</param> /// <param name="handler">The data reader handler.</param> /// <param name="parameterProps">The optional parameter property container.</param> /// <returns> /// An enumerable collection of results of the specified type. /// </returns> public List<TEntity> Query<TEntity>(string query, IDataHandler<TEntity> handler, object parameterProps = null) where TEntity : class { Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(query)); Contract.Requires<ArgumentNullException>(handler != null); throw new NotImplementedException(); } /// <summary> /// Queries the repository for a collection of entities. /// </summary> /// <typeparam name="TEntity">The entity type to be returned.</typeparam> /// <param name="command">The command to execute.</param> /// <param name="handler">The handler to read individual entities from the data reader.</param> /// <returns> /// The collection of entities. /// </returns> /// <exception cref="NotImplementedException">This is a contract only implementation.</exception> public List<TEntity> QueryAs<TEntity>(QueryCommand command, Func<IDataReader, TEntity> handler) where TEntity : class { Contract.Requires<ArgumentNullException>(command != null); Contract.Requires<ArgumentNullException>(handler != null); throw new NotImplementedException(); } /// <summary> /// Queries the repository for a collection of entities that may differ from the type used to build the query. /// </summary> /// <typeparam name="TEntity">The entity type to be returned.</typeparam> /// <param name="command">The command to execute.</param> /// <param name="model">The optional data model.</param> /// <returns> /// The collection of entities. /// </returns> public List<TEntity> QueryAs<TEntity>(QueryCommand command, IDataModel model = null) where TEntity : class { Contract.Requires<ArgumentNullException>(command != null); throw new NotImplementedException(); } /// <summary> /// Executes a query built using a fluent expression. /// </summary> /// <typeparam name="TEntity">The type of item that will be returned in the expected result set.</typeparam> /// <param name="command">The command built from the data model.</param> /// <param name="handler">The data reader handler.</param> /// <returns> /// An enumerable collection of results of the specified type. /// </returns> /// <exception cref="NotImplementedException">This is a contract only implementation.</exception> public List<TEntity> Query<TEntity>(QueryCommand<TEntity> command, IDataHandler<TEntity> handler) where TEntity : class { Contract.Requires<ArgumentNullException>(command != null); Contract.Requires<ArgumentNullException>(handler != null); throw new NotImplementedException(); } /// <summary> /// Executes a query built using a fluent expression. /// </summary> /// <typeparam name="TEntity">The type of item that will be returned in the expected result set.</typeparam> /// <param name="command">The query built using a fluent expression.</param> /// <param name="model">The optional data model.</param> /// <returns> /// An enumerable collection of results of the specified type. /// </returns> /// <exception cref="NotImplementedException">This is a contract only implementation.</exception> public List<TEntity> Query<TEntity>(QueryCommand<TEntity> command, IDataModel model = null) where TEntity : class { Contract.Requires<ArgumentNullException>(command != null); throw new NotImplementedException(); } /// <summary> /// Executes an inline query that is optionally parameterized using an anonymous type. /// </summary> /// <typeparam name="TEntity">The type of item that will be returned in the expected result set.</typeparam> /// <param name="query">The inline query to execute.</param> /// <param name="parameterProps">The optional parameter property container.</param> /// <param name="model">The optional data model.</param> /// <returns> /// An enumerable collection of results of the specified type. /// </returns> public Task<IEnumerable<TEntity>> QueryAsync<TEntity>(string query, object parameterProps = null, IDataModel model = null) where TEntity : class { Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(query)); throw new NotImplementedException(); } /// <summary> /// Executes an inline query that is optionally parameterized using an anonymous type. /// </summary> /// <typeparam name="TEntity">The type of item that will be returned in the expected result set.</typeparam> /// <param name="query">The inline query to execute.</param> /// <param name="handler">The data reader handler.</param> /// <param name="parameterProps">The optional parameter property container.</param> /// <returns> /// An enumerable collection of results of the specified type. /// </returns> public Task<IEnumerable<TEntity>> QueryAsync<TEntity>(string query, IDataHandler<TEntity> handler, object parameterProps = null) where TEntity : class { Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(query)); Contract.Requires<ArgumentNullException>(handler != null); throw new NotImplementedException(); } /// <summary> /// Queries the repository asynchronously for a collection of entities. /// </summary> /// <typeparam name="TEntity">The entity type to be returned.</typeparam> /// <param name="command">The command to execute.</param> /// <param name="handler">The handler to read individual entities from the data reader.</param> /// <returns> /// The awaitable collection of entities. /// </returns> /// <exception cref="NotImplementedException">This is a contract only implementation.</exception> public Task<IEnumerable<TEntity>> QueryAsync<TEntity>(QueryCommand command, Func<IDataReader, TEntity> handler) where TEntity : class { Contract.Requires<ArgumentNullException>(command != null); Contract.Requires<ArgumentNullException>(handler != null); throw new NotImplementedException(); } /// <summary> /// Executes a query built using a fluent expression to be materialized by a custom handler. /// </summary> /// <typeparam name="TEntity">The type of item that will be returned in the expected result set.</typeparam> /// <param name="command">The query built using a fluent expression.</param> /// <param name="handler">The data reader handler to use.</param> /// <returns> /// An awaitable, enumerable collection of results of the specified type. /// </returns> /// <exception cref="NotImplementedException">This is a contract only implementation.</exception> public Task<IEnumerable<TEntity>> QueryAsync<TEntity>(QueryCommand<TEntity> command, IDataHandler<TEntity> handler) where TEntity : class { Contract.Requires<ArgumentNullException>(command != null); Contract.Requires<ArgumentNullException>(handler != null); throw new NotImplementedException(); } /// <summary> /// Executes a query built using a fluent expression. /// </summary> /// <typeparam name="TEntity">The type of item that will be returned in the expected result set.</typeparam> /// <param name="command">The query built using a fluent expression.</param> /// <param name="model">The optional data model.</param> /// <returns> /// An awaitable, enumerable collection of results of the specified type. /// </returns> /// <exception cref="NotImplementedException">This is a contract only implementation.</exception> public Task<IEnumerable<TEntity>> QueryAsync<TEntity>(QueryCommand<TEntity> command, IDataModel model = null) where TEntity : class { Contract.Requires<ArgumentNullException>(command != null); throw new NotImplementedException(); } /// <summary> /// Queries the repository for a collection of entities that may differ from the type used to build the query. /// </summary> /// <typeparam name="TEntity">The entity type to be returned.</typeparam> /// <param name="command">The command to execute.</param> /// <param name="model">The optional data model.</param> /// <returns> /// The collection of entities. /// </returns> public Task<IEnumerable<TEntity>> QueryAsAsync<TEntity>(QueryCommand command, IDataModel model = null) where TEntity : class { Contract.Requires<ArgumentNullException>(command != null); throw new NotImplementedException(); } /// <summary> /// Queries the repository for a collection of entities that may differ from the type used to build the query. /// </summary> /// <typeparam name="TEntity">The entity type to be returned.</typeparam> /// <param name="command">The command to execute.</param> /// <param name="handler">The handler to read individual entities from the data reader.</param> /// <returns> /// The collection of entities. /// </returns> public Task<IEnumerable<TEntity>> QueryAsAsync<TEntity>(QueryCommand command, Func<IDataReader, TEntity> handler) where TEntity : class { Contract.Requires<ArgumentNullException>(command != null); Contract.Requires<ArgumentNullException>(handler != null); throw new NotImplementedException(); } /// <summary> /// Executes an inline query that is optionally parameterized using an anonymous type. /// </summary> /// <typeparam name="TEntity">The entity type to be returned.</typeparam> /// <param name="query">The inline query to execute.</param> /// <param name="handler">The handler to read individual entities from the data reader.</param> /// <param name="parameterProps">The optional parameter property container.</param> /// <returns> /// The collection of entities. /// </returns> /// <exception cref="NotImplementedException"></exception> public List<TEntity> Query<TEntity>(string query, Func<IDataReader, TEntity> handler, object parameterProps = null) where TEntity : class { Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(query)); Contract.Requires<ArgumentNullException>(handler != null); throw new NotImplementedException(); } /// <summary> /// Executes a query built using a fluent expression. /// </summary> /// <typeparam name="TEntity">The entity type to be returned.</typeparam> /// <param name="command">The command to execute.</param> /// <param name="handler">The handler to read individual entities from the data reader.</param> /// <returns> /// The collection of entities. /// </returns> /// <exception cref="NotImplementedException"></exception> public List<TEntity> Query<TEntity>(QueryCommand<TEntity> command, Func<IDataReader, TEntity> handler) where TEntity : class { Contract.Requires<ArgumentNullException>(command != null); Contract.Requires<ArgumentNullException>(handler != null); throw new NotImplementedException(); } /// <summary> /// Executes a query built using a fluent expression to be materialized by a custom handler. /// </summary> /// <typeparam name="TEntity">The type of item that will be returned in the expected result set.</typeparam> /// <param name="command">The query built using a fluent expression.</param> /// <param name="handler">The data reader handler to use.</param> /// <returns> /// An awaitable, enumerable collection of results of the specified type. /// </returns> /// <exception cref="NotImplementedException"></exception> public List<TEntity> QueryAs<TEntity>(QueryCommand command, IDataHandler<TEntity> handler) where TEntity : class { Contract.Requires<ArgumentNullException>(command != null); Contract.Requires<ArgumentNullException>(handler != null); throw new NotImplementedException(); } /// <summary> /// Executes an inline query that is optionally parameterized using an anonymous type. /// </summary> /// <typeparam name="TEntity">The type of item that will be returned in the expected result set.</typeparam> /// <param name="query">The inline query to execute.</param> /// <param name="handler">The data reader handler.</param> /// <param name="parameterProps">The optional parameter property container.</param> /// <returns> /// An enumerable collection of results of the specified type. /// </returns> /// <exception cref="NotImplementedException"></exception> public Task<IEnumerable<TEntity>> QueryAsync<TEntity>(string query, Func<IDataReader, TEntity> handler, object parameterProps = null) where TEntity : class { Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(query)); Contract.Requires<ArgumentNullException>(handler != null); throw new NotImplementedException(); } /// <summary> /// Queries the repository asynchronously for a collection of entities. /// </summary> /// <typeparam name="TEntity">The entity type to be returned.</typeparam> /// <param name="command">The command to execute.</param> /// <param name="handler">The handler to read individual entities from the data reader.</param> /// <returns> /// The awaitable collection of entities. /// </returns> /// <exception cref="NotImplementedException"></exception> public Task<IEnumerable<TEntity>> QueryAsync<TEntity>(QueryCommand<TEntity> command, Func<IDataReader, TEntity> handler) where TEntity : class { Contract.Requires<ArgumentNullException>(command != null); Contract.Requires<ArgumentNullException>(handler != null); throw new NotImplementedException(); } /// <summary> /// Queries the repository for a collection of entities that may differ from the type used to build the query. /// </summary> /// <typeparam name="TEntity">The type of item that will be returned in the expected result set.</typeparam> /// <param name="command">The query built using a fluent expression.</param> /// <param name="handler">The data reader handler to use.</param> /// <returns> /// An awaitable, enumerable collection of results of the specified type. /// </returns> /// <exception cref="NotImplementedException"></exception> public Task<IEnumerable<TEntity>> QueryAsAsync<TEntity>(QueryCommand command, IDataHandler<TEntity> handler) where TEntity : class { Contract.Requires<ArgumentNullException>(command != null); Contract.Requires<ArgumentNullException>(handler != null); throw new NotImplementedException(); } } }
50.635593
163
0.641172
[ "MIT" ]
bkjuice/teaq
src/Teaq/Contracts/EntityQueryProviderContractClass.cs
17,927
C#
namespace DashboardCode.Routines.Storage { public interface IAdoBatch { void RemoveAll<TEntity>() where TEntity : class; } }
20.714286
56
0.675862
[ "Apache-2.0" ]
DashboardCode/Routines
Routines/Storage/IAdoBatch.cs
147
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Threading.Tasks; using Squidex.Infrastructure.Commands; using Squidex.Infrastructure.States; namespace Squidex.Infrastructure.TestHelpers { public class MyGrain : DomainObjectGrain<MyDomainState> { public MyGrain(IStore<Guid> store) : base(store) { } protected override Task<object> ExecuteAsync(IAggregateCommand command) { return Task.FromResult<object>(null); } } }
30.392857
79
0.493537
[ "MIT" ]
jiveabillion/squidex
tests/Squidex.Infrastructure.Tests/TestHelpers/MyGrain.cs
853
C#
namespace System.Configuration.Abstractions { public interface IConvertType { Type TargetType { get; } object Convert(string configurationValue); } }
22.25
50
0.679775
[ "MIT" ]
davidwhitney/System.Configuration.Abstractions
System.Configuration.Abstractions/IConvertType.cs
180
C#
/* C# "AbstractSearcher.cs" by Jeremy Love <mailto:jez@jezlove.uk> copyright 2020 */ using System; using System.Collections.Generic; using System.Linq; using System.IO; namespace ReSearcher { public abstract class AbstractSearcher : ISearcher { protected readonly String filter; protected AbstractSearcher(String filter = Filters.any) { this.filter = filter; } #region searching-file-system protected Func<Boolean> cancellationRequestedChecker; protected TextWriter log; public SelectionSearchResults search(IEnumerable<FileSystemInfo> fileSystemInfos, Func<Boolean> cancellationRequestedChecker, TextWriter log) { this.cancellationRequestedChecker = cancellationRequestedChecker; this.log = log; return(new SelectionSearchResults(searchItems(fileSystemInfos))); } protected IEnumerable<ISearchResultBranch> searchItems(IEnumerable<FileSystemInfo> fileSystemInfos) { foreach(FileSystemInfo fileSystemInfo in fileSystemInfos) { ISearchResultBranch iSearchResultBranch = searchItem(fileSystemInfo); if(null != iSearchResultBranch) { yield return(iSearchResultBranch); } } } protected ISearchResultBranch searchItem(FileSystemInfo fileSystemInfo) { if(cancellationRequestedChecker()) return(null); FileInfo fileInfo = fileSystemInfo as FileInfo; if(null != fileInfo) { return(searchFile(fileInfo)); } else { return(searchDirectory((DirectoryInfo)(fileSystemInfo))); } } protected DirectorySearchResults searchDirectory(DirectoryInfo directoryInfo) { return(new DirectorySearchResults(directoryInfo, searchItems(directoryInfo.EnumerateFileSystemInfos(filter)))); } protected abstract FileSearchResults searchFile(FileInfo fileInfo); #endregion } }
27.411765
147
0.733369
[ "MIT" ]
jezlove/ReSearcher
AbstractSearcher.cs
1,864
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ public partial class CMSAdminControls_UI_SmartTip { /// <summary> /// pnlTooltip control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel pnlTooltip; }
30.434783
81
0.501429
[ "MIT" ]
BryanSoltis/KenticoMVCWidgetShowcase
CMS/CMSAdminControls/UI/SmartTip.ascx.designer.cs
702
C#
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; using Approve.RuleBase; using Approve.RuleCenter; using Approve.EntityBase; public partial class Admin_MainOther_LogInfo : System.Web.UI.Page { Share rb = new Share(); protected void Page_Load(object sender, EventArgs e) { //RBase rb=new RCenter(); if (!IsPostBack) { if(!String.IsNullOrEmpty(Request.QueryString["FID"])) { string fid=Request.QueryString["FID"]; string sql = "SELECT * FROM CF_Sys_Log WHERE FID='"+fid+"'"; DataTable dtLogs = rb.GetTable(sql); if (dtLogs.Rows.Count > 0) { txt_Explorer.Text = EConvert.ToString(dtLogs.Rows[0]["FBrowserType"]); txt_Info.Text = EConvert.ToString(dtLogs.Rows[0]["FDescription"]); txt_Ip.Text = EConvert.ToString(dtLogs.Rows[0]["FIPAddress"]); txt_LogSort.Text = getOperation(EConvert.ToInt(dtLogs.Rows[0]["FOperation"])); txt_LogTime.Text = EConvert.ToString(dtLogs.Rows[0]["FLogTime"]); txt_LogTitle.Text = EConvert.ToString(dtLogs.Rows[0]["FTitle"]); txt_LogType.Text = getLogType(EConvert.ToInt(dtLogs.Rows[0]["FLogType"])); txt_Operator.Text = EConvert.ToString(dtLogs.Rows[0]["FOperator"]); txt_ServerName.Text = EConvert.ToString(dtLogs.Rows[0]["FServerName"]); txt_Link.Text = EConvert.ToString(dtLogs.Rows[0]["FDirectory"]); txt_SystemType.Text = EConvert.ToString(dtLogs.Rows[0]["FSystemType"]); //txt_Info.Enabled = false; //所属系统 getSysCode(EConvert.ToString(dtLogs.Rows[0]["FSysCode"])); } } } } private string getLogType(int? tid) { switch (tid) { case 1: return "信息日志"; case 2: return "错误日志"; case 3: return "警告日志"; } return ""; } private string getOperation(int? tid) { switch (tid) { case 1: return "系统"; case 2: return "安全"; case 3: return "应用"; case 4: return "操作"; } return ""; } private string getSysCode(string code) { if (!string.IsNullOrEmpty(code)) { string sysName = rb.GetSignValue("select fname from cf_sys_systemname where fnumber="+code); if (!string.IsNullOrEmpty(sysName)) { this.txt_SysName.Text = sysName; } else { sysName = rb.GetSignValue("select fname from cf_sys_platform where fnumber="+code); if (!string.IsNullOrEmpty(sysName)) this.txt_SysName.Text = sysName; } } return ""; } }
30.110092
103
0.52925
[ "MIT" ]
coojee2012/pm3
SurveyDesign/Share/Sys/LogInfo.aspx.cs
3,332
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. global using System; global using System.Collections; global using System.Collections.Generic; global using System.Diagnostics.CodeAnalysis; global using System.Linq; global using System.Text; global using System.Text.Encodings.Web; global using System.Text.Json; global using System.Text.Json.Serialization; global using System.Threading.Tasks; global using static System.Text.Json.JsonSerializer;
36.8
72
0.79529
[ "MIT" ]
dotnet/versionsweeper
src/DotNet.Extensions/GlobalUsings.cs
554
C#
using Microsoft.Maui.Controls.Internals; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Media; namespace Microsoft.Maui.Controls.Compatibility.Platform.UWP { public static class FontExtensions { public static void ApplyFont(this Control self, Font font) => self.UpdateFont(font, CompatServiceProvider.FontManager); public static void ApplyFont(this TextBlock self, Font font) => self.UpdateFont(font, CompatServiceProvider.FontManager); public static FontFamily ToFontFamily(this Font font) => CompatServiceProvider.FontManager.GetFontFamily(font); public static FontFamily ToFontFamily(this string fontFamily) => CompatServiceProvider.FontManager.GetFontFamily(Font.OfSize(fontFamily, 0.0)); internal static void ApplyFont(this Control self, IFontElement element) => self.UpdateFont(element.AsFont(), CompatServiceProvider.FontManager); internal static void ApplyFont(this TextBlock self, IFontElement element) => self.UpdateFont(element.AsFont(), CompatServiceProvider.FontManager); internal static void ApplyFont(this UI.Xaml.Documents.TextElement self, IFontElement element) => self.UpdateFont(element.AsFont(), CompatServiceProvider.FontManager); internal static double GetFontSize(this NamedSize size) => CompatServiceProvider.FontManager.GetFontSize(Font.OfSize(null, size)); internal static bool IsDefault(this IFontElement self) => self.FontFamily == null && self.FontSize == Device.GetNamedSize(NamedSize.Default, typeof(Label), true) && self.FontAttributes == FontAttributes.None; static Font AsFont(this IFontElement element) => Font.OfSize(element.FontFamily, element.FontSize).WithAttributes(element.FontAttributes); } }
43.794872
153
0.793326
[ "MIT" ]
Amir-Hossin-pr/maui
src/Compatibility/Core/src/WinUI/FontExtensions.cs
1,708
C#
using System.Text; using System.Text.RegularExpressions; namespace CloudAwesome.Pbi.SourceControl { public static class ExtensionMethods { public static string ToValidFileName(this string inputString) { var validNameChars = new Regex("[A-Z0-9_-]", RegexOptions.Compiled | RegexOptions.IgnoreCase); var result = new StringBuilder(); foreach (var match in validNameChars.Matches(inputString)) { result.Append(match); } return result.ToString().Trim(); } } }
26.545455
106
0.614726
[ "MIT" ]
Cloud-Awesome/powerbi-source-control
src/CloudAwesome.Pbi.SourceControl/CloudAwesome.Pbi.SourceControl/ExtensionMethods.cs
586
C#
using System; using System.Runtime.Serialization; namespace CryptoKitties.Net.Api.Models { /// <summary> /// Base class shared by all kitties /// </summary> [DataContract] [KnownType(typeof(KittySummary))] [KnownType(typeof(Kitty))] [KnownType(typeof(RelatedKitty))] public class KittyBase { /// <summary> /// Kitty Id /// </summary> [DataMember(Name="id")] public Int64 Id { get; set; } /// <summary> /// Nickname /// </summary> [DataMember(Name="name")] public string Name { get; set; } /// <summary> /// URL to kitty image /// </summary> [DataMember(Name="image_url")] public string ImageUrl { get; set; } /// <summary> /// URL to cdn-based kitty image /// </summary> [DataMember(Name="image_url_cdn")] public string ImageUrlCdn { get; set; } /// <summary> /// The Generation of this kitty /// </summary> [DataMember(Name="generation")] public int Generation { get; set; } /// <summary> /// When the kitty was created /// </summary> [DataMember(Name="created_at")] public DateTime CreatedAt { get; set; } /// <summary> /// The color of the kitty /// </summary> [DataMember(Name="color")] public string Color{ get; set; } /// <summary> /// If <c>true</c> then the kitty is fancy. /// </summary> [DataMember(Name="is_fancy")] public bool IsFancy { get; set; } /// <summary> /// The name of this kitty&apos;s &quot;Fancy&quot; type. /// </summary> [DataMember(Name="fancy_type")] public string FancyType { get; set; } /// <summary> /// If set to <c>true</c> then this is an exclusive kitty. /// </summary> [DataMember(Name="is_exclusive")] public bool IsExclusive { get; set; } /// <summary> /// A <see cref="Profile"/> describing the owner. /// </summary> [DataMember(Name="owner")] public Profile Owner { get; set; } /// <summary> /// A <see cref="KittyStatus"/> containing kitty status. /// </summary> [DataMember(Name="status")] public KittyStatus Status { get; set; } /// <summary> /// Whether or not this kitty was hatched? /// </summary> [DataMember(Name="hatched")] public bool Hatched { get; set; } } }
27.784946
66
0.518963
[ "MIT" ]
seanmobrien/CryptoKitties.Net.Api
src/CryptoKitties.Net.Api/Api/Models/KittyBase.cs
2,584
C#
/* * Copyright(c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using Tizen.NUI; using Tizen.NUI.Components; namespace NUITizenGallery { internal class GridTest3 : IExample { private Window window; public void Activate() { window = NUIApplication.GetDefaultWindow(); window.GetDefaultNavigator().Push(new GridTest3Page()); } public void Deactivate() { window.GetDefaultNavigator().Pop(); } } }
27.333333
75
0.675422
[ "Apache-2.0", "MIT" ]
JSUYA/TizenFX
test/NUITizenGallery/Examples/GridTest/GridTest3.cs
1,066
C#
using System; using UnityEngine; [AddComponentMenu("NGUI/Interaction/Button Rotation")] public class UIButtonRotation : MonoBehaviour { public float duration = 0.2f; public Vector3 hover = Vector3.zero; private bool mHighlighted; private Quaternion mRot; private bool mStarted; public Vector3 pressed = Vector3.zero; public Transform tweenTarget; private void OnDisable() { if (this.mStarted && (this.tweenTarget != null)) { TweenRotation component = this.tweenTarget.GetComponent<TweenRotation>(); if (component != null) { component.rotation = this.mRot; component.enabled = false; } } } private void OnEnable() { if (this.mStarted && this.mHighlighted) { this.OnHover(UICamera.IsHighlighted(base.gameObject)); } } private void OnHover(bool isOver) { if (base.enabled) { if (!this.mStarted) { this.Start(); } TweenRotation.Begin(this.tweenTarget.gameObject, this.duration, !isOver ? this.mRot : (this.mRot * Quaternion.Euler(this.hover))).method = UITweener.Method.EaseInOut; this.mHighlighted = isOver; } } private void OnPress(bool isPressed) { if (base.enabled) { if (!this.mStarted) { this.Start(); } TweenRotation.Begin(this.tweenTarget.gameObject, this.duration, !isPressed ? (!UICamera.IsHighlighted(base.gameObject) ? this.mRot : (this.mRot * Quaternion.Euler(this.hover))) : (this.mRot * Quaternion.Euler(this.pressed))).method = UITweener.Method.EaseInOut; } } private void Start() { if (!this.mStarted) { this.mStarted = true; if (this.tweenTarget == null) { this.tweenTarget = base.transform; } this.mRot = this.tweenTarget.localRotation; } } }
28.746667
274
0.543599
[ "MIT" ]
Jagerente/RCFixed
Source/UIButtonRotation.cs
2,158
C#
namespace eaw.hardpointduplicator { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.MainFormMainBoxSplitContainer = new System.Windows.Forms.SplitContainer(); this.Panel1TableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.IsTurretCheckBox = new System.Windows.Forms.CheckBox(); this.Generate70CheckBox = new System.Windows.Forms.CheckBox(); this.GenerateR90CheckBox = new System.Windows.Forms.CheckBox(); this.GenerateR270CheckBox = new System.Windows.Forms.CheckBox(); this.GenerateButton = new System.Windows.Forms.Button(); this.GenerateR360CheckBox = new System.Windows.Forms.CheckBox(); this.HardpointCountNumericUpDown = new System.Windows.Forms.NumericUpDown(); this.HardPointBaseNameTextBox = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.Panel2TableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.HardpointCodeRichTextBox = new System.Windows.Forms.RichTextBox(); this.ReplacementTextBox = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.MainFormMainBoxSplitContainer)).BeginInit(); this.MainFormMainBoxSplitContainer.Panel1.SuspendLayout(); this.MainFormMainBoxSplitContainer.Panel2.SuspendLayout(); this.MainFormMainBoxSplitContainer.SuspendLayout(); this.Panel1TableLayoutPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.HardpointCountNumericUpDown)).BeginInit(); this.Panel2TableLayoutPanel.SuspendLayout(); this.SuspendLayout(); // // MainFormMainBoxSplitContainer // resources.ApplyResources(this.MainFormMainBoxSplitContainer, "MainFormMainBoxSplitContainer"); this.MainFormMainBoxSplitContainer.Name = "MainFormMainBoxSplitContainer"; // // MainFormMainBoxSplitContainer.Panel1 // this.MainFormMainBoxSplitContainer.Panel1.Controls.Add(this.Panel1TableLayoutPanel); // // MainFormMainBoxSplitContainer.Panel2 // this.MainFormMainBoxSplitContainer.Panel2.Controls.Add(this.Panel2TableLayoutPanel); // // Panel1TableLayoutPanel // resources.ApplyResources(this.Panel1TableLayoutPanel, "Panel1TableLayoutPanel"); this.Panel1TableLayoutPanel.Controls.Add(this.IsTurretCheckBox, 0, 0); this.Panel1TableLayoutPanel.Controls.Add(this.Generate70CheckBox, 0, 1); this.Panel1TableLayoutPanel.Controls.Add(this.GenerateR90CheckBox, 0, 2); this.Panel1TableLayoutPanel.Controls.Add(this.GenerateR270CheckBox, 0, 3); this.Panel1TableLayoutPanel.Controls.Add(this.GenerateButton, 0, 7); this.Panel1TableLayoutPanel.Controls.Add(this.GenerateR360CheckBox, 0, 4); this.Panel1TableLayoutPanel.Controls.Add(this.HardpointCountNumericUpDown, 1, 6); this.Panel1TableLayoutPanel.Controls.Add(this.HardPointBaseNameTextBox, 1, 5); this.Panel1TableLayoutPanel.Controls.Add(this.label1, 0, 5); this.Panel1TableLayoutPanel.Controls.Add(this.label2, 0, 6); this.Panel1TableLayoutPanel.Name = "Panel1TableLayoutPanel"; // // IsTurretCheckBox // resources.ApplyResources(this.IsTurretCheckBox, "IsTurretCheckBox"); this.Panel1TableLayoutPanel.SetColumnSpan(this.IsTurretCheckBox, 2); this.IsTurretCheckBox.Name = "IsTurretCheckBox"; this.IsTurretCheckBox.UseVisualStyleBackColor = true; this.IsTurretCheckBox.CheckedChanged += new System.EventHandler(this.IsTurretCheckBox_CheckedChanged); // // Generate70CheckBox // resources.ApplyResources(this.Generate70CheckBox, "Generate70CheckBox"); this.Panel1TableLayoutPanel.SetColumnSpan(this.Generate70CheckBox, 2); this.Generate70CheckBox.Name = "Generate70CheckBox"; this.Generate70CheckBox.UseVisualStyleBackColor = true; // // GenerateR90CheckBox // resources.ApplyResources(this.GenerateR90CheckBox, "GenerateR90CheckBox"); this.Panel1TableLayoutPanel.SetColumnSpan(this.GenerateR90CheckBox, 2); this.GenerateR90CheckBox.Name = "GenerateR90CheckBox"; this.GenerateR90CheckBox.UseVisualStyleBackColor = true; // // GenerateR270CheckBox // resources.ApplyResources(this.GenerateR270CheckBox, "GenerateR270CheckBox"); this.Panel1TableLayoutPanel.SetColumnSpan(this.GenerateR270CheckBox, 2); this.GenerateR270CheckBox.Name = "GenerateR270CheckBox"; this.GenerateR270CheckBox.UseVisualStyleBackColor = true; // // GenerateButton // this.Panel1TableLayoutPanel.SetColumnSpan(this.GenerateButton, 2); resources.ApplyResources(this.GenerateButton, "GenerateButton"); this.GenerateButton.Name = "GenerateButton"; this.GenerateButton.UseVisualStyleBackColor = true; this.GenerateButton.Click += new System.EventHandler(this.GenerateButton_Click); // // GenerateR360CheckBox // resources.ApplyResources(this.GenerateR360CheckBox, "GenerateR360CheckBox"); this.Panel1TableLayoutPanel.SetColumnSpan(this.GenerateR360CheckBox, 2); this.GenerateR360CheckBox.Name = "GenerateR360CheckBox"; this.GenerateR360CheckBox.UseVisualStyleBackColor = true; // // HardpointCountNumericUpDown // resources.ApplyResources(this.HardpointCountNumericUpDown, "HardpointCountNumericUpDown"); this.HardpointCountNumericUpDown.Maximum = new decimal(new int[] { 1000, 0, 0, 0}); this.HardpointCountNumericUpDown.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.HardpointCountNumericUpDown.Name = "HardpointCountNumericUpDown"; this.HardpointCountNumericUpDown.Value = new decimal(new int[] { 1, 0, 0, 0}); // // HardPointBaseNameTextBox // resources.ApplyResources(this.HardPointBaseNameTextBox, "HardPointBaseNameTextBox"); this.HardPointBaseNameTextBox.Name = "HardPointBaseNameTextBox"; // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // Panel2TableLayoutPanel // resources.ApplyResources(this.Panel2TableLayoutPanel, "Panel2TableLayoutPanel"); this.Panel2TableLayoutPanel.Controls.Add(this.HardpointCodeRichTextBox, 0, 0); this.Panel2TableLayoutPanel.Controls.Add(this.ReplacementTextBox, 1, 1); this.Panel2TableLayoutPanel.Controls.Add(this.label3, 0, 1); this.Panel2TableLayoutPanel.Name = "Panel2TableLayoutPanel"; // // HardpointCodeRichTextBox // this.Panel2TableLayoutPanel.SetColumnSpan(this.HardpointCodeRichTextBox, 2); resources.ApplyResources(this.HardpointCodeRichTextBox, "HardpointCodeRichTextBox"); this.HardpointCodeRichTextBox.Name = "HardpointCodeRichTextBox"; // // ReplacementTextBox // resources.ApplyResources(this.ReplacementTextBox, "ReplacementTextBox"); this.ReplacementTextBox.Name = "ReplacementTextBox"; // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // MainForm // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.MainFormMainBoxSplitContainer); this.Name = "MainForm"; this.MainFormMainBoxSplitContainer.Panel1.ResumeLayout(false); this.MainFormMainBoxSplitContainer.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.MainFormMainBoxSplitContainer)).EndInit(); this.MainFormMainBoxSplitContainer.ResumeLayout(false); this.Panel1TableLayoutPanel.ResumeLayout(false); this.Panel1TableLayoutPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.HardpointCountNumericUpDown)).EndInit(); this.Panel2TableLayoutPanel.ResumeLayout(false); this.Panel2TableLayoutPanel.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SplitContainer MainFormMainBoxSplitContainer; private System.Windows.Forms.TableLayoutPanel Panel2TableLayoutPanel; private System.Windows.Forms.TableLayoutPanel Panel1TableLayoutPanel; private System.Windows.Forms.CheckBox IsTurretCheckBox; private System.Windows.Forms.CheckBox Generate70CheckBox; private System.Windows.Forms.CheckBox GenerateR90CheckBox; private System.Windows.Forms.CheckBox GenerateR270CheckBox; private System.Windows.Forms.Button GenerateButton; private System.Windows.Forms.RichTextBox HardpointCodeRichTextBox; private System.Windows.Forms.TextBox ReplacementTextBox; private System.Windows.Forms.CheckBox GenerateR360CheckBox; private System.Windows.Forms.NumericUpDown HardpointCountNumericUpDown; private System.Windows.Forms.TextBox HardPointBaseNameTextBox; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; } }
50.90708
140
0.64824
[ "MIT" ]
KadVenku/hardpoint-duplicator
eaw.hardpointcreator/MainForm.Designer.cs
11,507
C#
namespace Rest.Data.VO { public class FileDetailVO { public string DocumentName { get; set; } public string DocumentType { get; set; } public string DocumentUrl { get; set; } } }
22.4
48
0.584821
[ "Apache-2.0" ]
Guifgr/Rest
Rest/Data/VO/FileDetailVO.cs
226
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Portal.Models.Api201901Preview { using static Microsoft.Azure.PowerShell.Cmdlets.Portal.Runtime.Extensions; /// <summary>The dashboard lenses.</summary> public partial class DashboardPropertiesLenses : Microsoft.Azure.PowerShell.Cmdlets.Portal.Models.Api201901Preview.IDashboardPropertiesLenses, Microsoft.Azure.PowerShell.Cmdlets.Portal.Models.Api201901Preview.IDashboardPropertiesLensesInternal { /// <summary>Creates an new <see cref="DashboardPropertiesLenses" /> instance.</summary> public DashboardPropertiesLenses() { } } /// The dashboard lenses. public partial interface IDashboardPropertiesLenses : Microsoft.Azure.PowerShell.Cmdlets.Portal.Runtime.IJsonSerializable, Microsoft.Azure.PowerShell.Cmdlets.Portal.Runtime.IAssociativeArray<Microsoft.Azure.PowerShell.Cmdlets.Portal.Models.Api201901Preview.IDashboardLens> { } /// The dashboard lenses. internal partial interface IDashboardPropertiesLensesInternal { } }
37.366667
158
0.73149
[ "MIT" ]
3quanfeng/azure-powershell
src/Portal/generated/api/Models/Api201901Preview/DashboardPropertiesLenses.cs
1,092
C#
/* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. * See LICENSE in the source repository root for complete license information. */ using MvvmCross.Platform.Plugins; namespace XamarinNativePropertyManager.iOS.Bootstrap { public class VisibilityPluginBootstrap : MvxLoaderPluginBootstrapAction<MvvmCross.Plugins.Visibility.PluginLoader, MvvmCross.Plugins.Visibility.iOS.Plugin> { } }
31.5
124
0.777778
[ "MIT" ]
OfficeGlobal/xamarin-csharp-propertymanager-sample
XamarinNativePropertyManager.iOS/Bootstrap/VisibilityPluginBootstrap.cs
441
C#
// ----------------------------------------------------------------------------------------- // <copyright file="TableSasUnitTests.cs" company="Microsoft"> // Copyright 2013 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // ----------------------------------------------------------------------------------------- using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Shared.Protocol; using Microsoft.WindowsAzure.Storage.Table.Entities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; namespace Microsoft.WindowsAzure.Storage.Table { [TestClass] public class TableSasUnitTests : TableTestBase { #region Locals + Ctors public TableSasUnitTests() { } private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #endregion #region Additional test attributes // // You can use the following additional attributes as you write your tests: // // Use ClassInitialize to run code before running the first test in the class // [ClassInitialize()] // public static void MyClassInitialize(TestContext testContext) { } // // Use ClassCleanup to run code after all tests in a class have run // [ClassCleanup()] // public static void MyClassCleanup() { } // // Use TestInitialize to run code before running each test // // // Use TestInitialize to run code before running each test [TestInitialize()] public void MyTestInitialize() { if (TestBase.TableBufferManager != null) { TestBase.TableBufferManager.OutstandingBufferCount = 0; } } // // Use TestCleanup to run code after each test has run [TestCleanup()] public void MyTestCleanup() { if (TestBase.TableBufferManager != null) { Assert.AreEqual(0, TestBase.TableBufferManager.OutstandingBufferCount); } } #endregion #region Constructor Tests [TestMethod] [Description("Test TableSas via various constructors")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSASConstructors() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); var entity = new BaseEntity("PK", "RK"); entity.Populate(); table.Execute(TableOperation.Insert(entity)); // Prepare SAS authentication with full permissions string sasToken = table.GetSharedAccessSignature( new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Add | SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Query, SharedAccessExpiryTime = DateTimeOffset.Now.AddMinutes(30) }, null /* accessPolicyIdentifier */, null /* startPk */, null /* startRk */, null /* endPk */, null /* endRk */); CloudStorageAccount sasAccount; StorageCredentials sasCreds; CloudTableClient sasClient; CloudTable sasTable; Uri baseUri = new Uri(TestBase.TargetTenantConfig.TableServiceEndpoint); // SAS via connection string parse sasAccount = CloudStorageAccount.Parse(string.Format("TableEndpoint={0};SharedAccessSignature={1}", baseUri.AbsoluteUri, sasToken)); sasClient = sasAccount.CreateCloudTableClient(); sasTable = sasClient.GetTableReference(table.Name); Assert.AreEqual(1, sasTable.ExecuteQuery(new TableQuery<BaseEntity>()).Count()); // SAS via account constructor sasCreds = new StorageCredentials(sasToken); sasAccount = new CloudStorageAccount(sasCreds, null, null, baseUri, null); sasClient = sasAccount.CreateCloudTableClient(); sasTable = sasClient.GetTableReference(table.Name); Assert.AreEqual(1, sasTable.ExecuteQuery(new TableQuery<BaseEntity>()).Count()); // SAS via client constructor URI + Creds sasCreds = new StorageCredentials(sasToken); sasClient = new CloudTableClient(baseUri, sasCreds); sasTable = sasClient.GetTableReference(table.Name); Assert.AreEqual(1, sasTable.ExecuteQuery(new TableQuery<BaseEntity>()).Count()); // SAS via CloudTable constructor Uri + Client sasCreds = new StorageCredentials(sasToken); sasTable = new CloudTable(table.Uri, tableClient.Credentials); sasClient = sasTable.ServiceClient; Assert.AreEqual(1, sasTable.ExecuteQuery(new TableQuery<BaseEntity>()).Count()); } finally { table.DeleteIfExists(); } } #endregion #region Permissions [TestMethod] [Description("Tests setting and getting table permissions")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSetGetPermissions() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); var entity = new BaseEntity("PK", "RK"); entity.Populate(); table.Execute(TableOperation.Insert(entity)); TablePermissions expectedPermissions = new TablePermissions(); TablePermissions testPermissions = table.GetPermissions(); AssertPermissionsEqual(expectedPermissions, testPermissions); // Add a policy, check setting and getting. expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Query, SharedAccessStartTime = DateTimeOffset.Now - TimeSpan.FromHours(1), SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromHours(1) }); table.SetPermissions(expectedPermissions); TestHelper.SpinUpTo30SecondsIgnoringFailures(() => { testPermissions = table.GetPermissions(); AssertPermissionsEqual(expectedPermissions, testPermissions); }); } finally { table.DeleteIfExists(); } } [TestMethod] [Description("Tests Null Access Policy")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSASNullAccessPolicy() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); var entity = new BaseEntity("PK", "RK"); entity.Populate(); table.Execute(TableOperation.Insert(entity)); TablePermissions expectedPermissions = new TablePermissions(); // Add a policy expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Query | SharedAccessTablePermissions.Add, SharedAccessStartTime = DateTimeOffset.Now - TimeSpan.FromHours(1), SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromHours(1) }); table.SetPermissions(expectedPermissions); // Generate the sasToken the user should use string sasToken = table.GetSharedAccessSignature(null, expectedPermissions.SharedAccessPolicies.First().Key, "AAAA", null, "AAAA", null); CloudTable sasTable = new CloudTable(table.Uri, new StorageCredentials(sasToken)); TestHelper.SpinUpTo30SecondsIgnoringFailures(() => sasTable.Execute(TableOperation.Insert(new DynamicTableEntity("AAAA", "foo")))); TableResult result = null; TestHelper.SpinUpTo30SecondsIgnoringFailures(() => result = sasTable.Execute(TableOperation.Retrieve("AAAA", "foo"))); Assert.IsNotNull(result.Result); // revoke table permissions table.SetPermissions(new TablePermissions()); TestHelper.SpinUpTo30SecondsIgnoringFailures(() => { OperationContext opContext = new OperationContext(); try { sasTable.Execute(TableOperation.Insert(new DynamicTableEntity("AAAA", "foo2")), null, opContext); Assert.Fail(); } catch (Exception) { Assert.AreEqual(opContext.LastResult.HttpStatusCode, (int)HttpStatusCode.Forbidden); } }); TestHelper.SpinUpTo30SecondsIgnoringFailures(() => { OperationContext opContext = new OperationContext(); try { result = sasTable.Execute(TableOperation.Retrieve("AAAA", "foo"), null, opContext); Assert.Fail(); } catch (Exception) { Assert.AreEqual(opContext.LastResult.HttpStatusCode, (int)HttpStatusCode.Forbidden); } }); } finally { table.DeleteIfExists(); } } #endregion #region SAS Operations /// <summary> /// Normally it's better to separate out a test like this into multiple smaller tests, but here we parallelize because /// each of these tests takes a very long time. /// </summary> [TestMethod] [Description("Tests table SAS with query permissions.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSasPermsTestSync() { List<Task> tasks = new List<Task>(); tasks.Add(Task.Run(() => TestTableSas(SharedAccessTablePermissions.Query))); tasks.Add(Task.Run(() => TestTableSas(SharedAccessTablePermissions.Delete))); tasks.Add(Task.Run(() => TestTableSas(SharedAccessTablePermissions.Update))); tasks.Add(Task.Run(() => TestTableSas(SharedAccessTablePermissions.Add))); tasks.Add(Task.Run(() => TestTableSas(SharedAccessTablePermissions.Query | SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Update | SharedAccessTablePermissions.Add))); Task.WaitAll(tasks.ToArray()); } /// <summary> /// Tests table access permissions with SAS, using a stored policy and using permissions on the URI. /// Various table range constraints are tested. /// </summary> /// <param name="accessPermissions">The permissions to test.</param> internal void TestTableSas(SharedAccessTablePermissions accessPermissions) { string startPk = "M"; string startRk = "F"; string endPk = "S"; string endRk = "T"; List<Task> tasks = new List<Task>(); // No ranges specified tasks.Add(Task.Run(() => TestTableSasWithRange(accessPermissions, null, null, null, null))); // All ranges specified tasks.Add(Task.Run(() => TestTableSasWithRange(accessPermissions, startPk, startRk, endPk, endRk))); // StartPk & StartRK specified tasks.Add(Task.Run(() => TestTableSasWithRange(accessPermissions, startPk, startRk, null, null))); // StartPk specified tasks.Add(Task.Run(() => TestTableSasWithRange(accessPermissions, startPk, null, null, null))); // EndPk & EndRK specified tasks.Add(Task.Run(() => TestTableSasWithRange(accessPermissions, null, null, endPk, endRk))); // EndPk specified tasks.Add(Task.Run(() => TestTableSasWithRange(accessPermissions, null, null, endPk, null))); // StartPk and EndPk specified tasks.Add(Task.Run(() => TestTableSasWithRange(accessPermissions, startPk, null, endPk, null))); // StartRk and StartRK and EndPk specified tasks.Add(Task.Run(() => TestTableSasWithRange(accessPermissions, startPk, startRk, endPk, null))); // StartRk and EndPK and EndPk specified tasks.Add(Task.Run(() => TestTableSasWithRange(accessPermissions, startPk, null, endPk, endRk))); Task.WaitAll(tasks.ToArray()); } /// <summary> /// Tests table access permissions with SAS, using a stored policy and using permissions on the URI. /// </summary> /// <param name="accessPermissions">The permissions to test.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> internal void TestTableSasWithRange( SharedAccessTablePermissions accessPermissions, string startPk, string startRk, string endPk, string endRk) { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); // Set up a policy string identifier = Guid.NewGuid().ToString(); TablePermissions permissions = new TablePermissions(); permissions.SharedAccessPolicies.Add(identifier, new SharedAccessTablePolicy { Permissions = accessPermissions, SharedAccessExpiryTime = DateTimeOffset.Now.AddDays(1) }); table.SetPermissions(permissions); Thread.Sleep(30 * 1000); // Prepare SAS authentication using access identifier string sasString = table.GetSharedAccessSignature(new SharedAccessTablePolicy(), identifier, startPk, startRk, endPk, endRk); CloudTableClient identifierSasClient = new CloudTableClient(tableClient.BaseUri, new StorageCredentials(sasString)); // Prepare SAS authentication using explicit policy sasString = table.GetSharedAccessSignature( new SharedAccessTablePolicy { Permissions = accessPermissions, SharedAccessExpiryTime = DateTimeOffset.Now.AddMinutes(30) }, null, startPk, startRk, endPk, endRk); CloudTableClient explicitSasClient = new CloudTableClient(tableClient.BaseUri, new StorageCredentials(sasString)); // Point query TestPointQuery(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestPointQuery(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Add row TestAdd(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestAdd(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Update row (merge) TestUpdateMerge(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestUpdateMerge(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Update row (replace) TestUpdateReplace(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestUpdateReplace(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Delete row TestDelete(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestDelete(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Upsert row (merge) TestUpsertMerge(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestUpsertMerge(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Upsert row (replace) TestUpsertReplace(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestUpsertReplace(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); } finally { table.DeleteIfExists(); } } /// <summary> /// Test point queries entities inside and outside the given range. /// </summary> /// <param name="testClient">The table client to test.</param> /// <param name="tableName">The name of the table to test.</param> /// <param name="accessPermissions">The access permissions of the table client.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> private void TestPointQuery( CloudTableClient testClient, string tableName, SharedAccessTablePermissions accessPermissions, string startPk, string startRk, string endPk, string endRk) { bool expectSuccess = ((accessPermissions & SharedAccessTablePermissions.Query) != 0); Action<BaseEntity, OperationContext> queryDelegate = (tableEntity, ctx) => { TableResult retrieveResult = testClient.GetTableReference(tableName).Execute(TableOperation.Retrieve<BaseEntity>(tableEntity.PartitionKey, tableEntity.RowKey), null, ctx); if (expectSuccess) { Assert.IsNotNull(retrieveResult.Result); } else { Assert.AreEqual(ctx.LastResult.HttpStatusCode, (int)HttpStatusCode.OK); } }; // Perform test TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, queryDelegate, "point query", expectSuccess, expectSuccess ? HttpStatusCode.OK : HttpStatusCode.NotFound, false, expectSuccess); } /// <summary> /// Test update (merge) on entities inside and outside the given range. /// </summary> /// <param name="testClient">The table client to test.</param> /// <param name="tableName">The name of the table to test.</param> /// <param name="accessPermissions">The access permissions of the table client.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> private void TestUpdateMerge( CloudTableClient testClient, string tableName, SharedAccessTablePermissions accessPermissions, string startPk, string startRk, string endPk, string endRk) { Action<BaseEntity, OperationContext> updateDelegate = (tableEntity, ctx) => { // Merge entity tableEntity.A = "10"; tableEntity.ETag = "*"; testClient.GetTableReference(tableName).Execute(TableOperation.Merge(tableEntity), null, ctx); }; bool expectSuccess = (accessPermissions & SharedAccessTablePermissions.Update) != 0; // Perform test TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, updateDelegate, "update merge", expectSuccess, expectSuccess ? HttpStatusCode.NoContent : HttpStatusCode.Forbidden); } /// <summary> /// Test update (replace) on entities inside and outside the given range. /// </summary> /// <param name="testClient">The table client to test.</param> /// <param name="tableName">The name of the table to test.</param> /// <param name="accessPermissions">The access permissions of the table client.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> private void TestUpdateReplace( CloudTableClient testClient, string tableName, SharedAccessTablePermissions accessPermissions, string startPk, string startRk, string endPk, string endRk) { Action<BaseEntity, OperationContext> updateDelegate = (tableEntity, ctx) => { // replace entity tableEntity.A = "20"; tableEntity.ETag = "*"; testClient.GetTableReference(tableName).Execute(TableOperation.Replace(tableEntity), null, ctx); }; bool expectSuccess = (accessPermissions & SharedAccessTablePermissions.Update) != 0; // Perform test TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, updateDelegate, "update replace", expectSuccess, expectSuccess ? HttpStatusCode.NoContent : HttpStatusCode.Forbidden); } /// <summary> /// Test adding entities inside and outside the given range. /// </summary> /// <param name="testClient">The table client to test.</param> /// <param name="tableName">The name of the table to test.</param> /// <param name="accessPermissions">The access permissions of the table client.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> private void TestAdd( CloudTableClient testClient, string tableName, SharedAccessTablePermissions accessPermissions, string startPk, string startRk, string endPk, string endRk) { Action<BaseEntity, OperationContext> addDelegate = (tableEntity, ctx) => { // insert entity tableEntity.A = "10"; testClient.GetTableReference(tableName).Execute(TableOperation.Insert(tableEntity), null, ctx); }; bool expectSuccess = (accessPermissions & SharedAccessTablePermissions.Add) != 0; // Perform test TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, addDelegate, "add", expectSuccess, expectSuccess ? HttpStatusCode.Created : HttpStatusCode.Forbidden); } /// <summary> /// Test deleting entities inside and outside the given range. /// </summary> /// <param name="testClient">The table client to test.</param> /// <param name="tableName">The name of the table to test.</param> /// <param name="accessPermissions">The access permissions of the table client.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> private void TestDelete( CloudTableClient testClient, string tableName, SharedAccessTablePermissions accessPermissions, string startPk, string startRk, string endPk, string endRk) { Action<BaseEntity, OperationContext> deleteDelegate = (tableEntity, ctx) => { // delete entity tableEntity.A = "10"; tableEntity.ETag = "*"; testClient.GetTableReference(tableName).Execute(TableOperation.Delete(tableEntity), null, ctx); }; bool expectSuccess = (accessPermissions & SharedAccessTablePermissions.Delete) != 0; // Perform test TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, deleteDelegate, "delete", expectSuccess, expectSuccess ? HttpStatusCode.NoContent : HttpStatusCode.Forbidden); } /// <summary> /// Test upsert (insert or merge) on entities inside and outside the given range. /// </summary> /// <param name="testClient">The table client to test.</param> /// <param name="tableName">The name of the table to test.</param> /// <param name="accessPermissions">The access permissions of the table client.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> private void TestUpsertMerge( CloudTableClient testClient, string tableName, SharedAccessTablePermissions accessPermissions, string startPk, string startRk, string endPk, string endRk) { Action<BaseEntity, OperationContext> upsertDelegate = (tableEntity, ctx) => { // insert or merge entity tableEntity.A = "10"; testClient.GetTableReference(tableName).Execute(TableOperation.InsertOrMerge(tableEntity), null, ctx); }; SharedAccessTablePermissions upsertPermissions = (SharedAccessTablePermissions.Update | SharedAccessTablePermissions.Add); bool expectSuccess = (accessPermissions & upsertPermissions) == upsertPermissions; // Perform test TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, upsertDelegate, "upsert merge", expectSuccess, expectSuccess ? HttpStatusCode.NoContent : HttpStatusCode.Forbidden); } /// <summary> /// Test upsert (insert or replace) on entities inside and outside the given range. /// </summary> /// <param name="testClient">The table client to test.</param> /// <param name="tableName">The name of the table to test.</param> /// <param name="accessPermissions">The access permissions of the table client.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> private void TestUpsertReplace( CloudTableClient testClient, string tableName, SharedAccessTablePermissions accessPermissions, string startPk, string startRk, string endPk, string endRk) { Action<BaseEntity, OperationContext> upsertDelegate = (tableEntity, ctx) => { // insert or replace entity tableEntity.A = "10"; testClient.GetTableReference(tableName).Execute(TableOperation.InsertOrReplace(tableEntity), null, ctx); }; SharedAccessTablePermissions upsertPermissions = (SharedAccessTablePermissions.Update | SharedAccessTablePermissions.Add); bool expectSuccess = (accessPermissions & upsertPermissions) == upsertPermissions; // Perform test TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, upsertDelegate, "upsert replace", expectSuccess, expectSuccess ? HttpStatusCode.NoContent : HttpStatusCode.Forbidden); } /// <summary> /// Test a table operation on entities inside and outside the given range. /// </summary> /// <param name="tableName">The name of the table to test.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> /// <param name="runOperationDelegate">A delegate with the table operation to test.</param> /// <param name="opName">The name of the operation being tested.</param> /// <param name="expectSuccess">Whether the operation should succeed on entities within the range.</param> private void TestOperationWithRange( string tableName, string startPk, string startRk, string endPk, string endRk, Action<BaseEntity, OperationContext> runOperationDelegate, string opName, bool expectSuccess, HttpStatusCode expectedStatusCode) { TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, runOperationDelegate, opName, expectSuccess, expectedStatusCode, false /* isRangeQuery */); } /// <summary> /// Test a table operation on entities inside and outside the given range. /// </summary> /// <param name="tableName">The name of the table to test.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> /// <param name="runOperationDelegate">A delegate with the table operation to test.</param> /// <param name="opName">The name of the operation being tested.</param> /// <param name="expectSuccess">Whether the operation should succeed on entities within the range.</param> /// <param name="expectedStatusCode">The status code expected for the response.</param> /// <param name="isRangeQuery">Specifies if the operation is a range query.</param> private void TestOperationWithRange( string tableName, string startPk, string startRk, string endPk, string endRk, Action<BaseEntity, OperationContext> runOperationDelegate, string opName, bool expectSuccess, HttpStatusCode expectedStatusCode, bool isRangeQuery) { TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, runOperationDelegate, opName, expectSuccess, expectedStatusCode, isRangeQuery, false /* isPointQuery */); } /// <summary> /// Test a table operation on entities inside and outside the given range. /// </summary> /// <param name="tableName">The name of the table to test.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> /// <param name="runOperationDelegate">A delegate with the table operation to test.</param> /// <param name="opName">The name of the operation being tested.</param> /// <param name="expectSuccess">Whether the operation should succeed on entities within the range.</param> /// <param name="expectedStatusCode">The status code expected for the response.</param> /// <param name="isRangeQuery">Specifies if the operation is a range query.</param> /// <param name="isPointQuery">Specifies if the operation is a point query.</param> private void TestOperationWithRange( string tableName, string startPk, string startRk, string endPk, string endRk, Action<BaseEntity, OperationContext> runOperationDelegate, string opName, bool expectSuccess, HttpStatusCode expectedStatusCode, bool isRangeQuery, bool isPointQuery) { CloudTableClient referenceClient = GenerateCloudTableClient(); string partitionKey = startPk ?? endPk ?? "M"; string rowKey = startRk ?? endRk ?? "S"; // if we expect a success for creation - avoid inserting duplicate entities BaseEntity tableEntity = new BaseEntity(partitionKey, rowKey); tableEntity.Populate(); if (expectedStatusCode == HttpStatusCode.Created) { try { tableEntity.ETag = "*"; referenceClient.GetTableReference(tableName).Execute(TableOperation.Delete(tableEntity)); } catch (Exception) { } } else { // only for add we should not be adding the entity referenceClient.GetTableReference(tableName).Execute(TableOperation.InsertOrReplace(tableEntity)); } if (expectSuccess) { runOperationDelegate(tableEntity, null); } else { TestHelper.ExpectedException( (ctx) => runOperationDelegate(tableEntity, ctx), string.Format("{0} without appropriate permission.", opName), (int)HttpStatusCode.Forbidden); } if (startPk != null) { tableEntity.PartitionKey = "A"; if (startPk.CompareTo(tableEntity.PartitionKey) <= 0) { Assert.Inconclusive("Test error: partition key for this test must not be less than or equal to \"A\""); } TestHelper.ExpectedException( (ctx) => runOperationDelegate(tableEntity, ctx), string.Format("{0} before allowed partition key range", opName), (int)(isPointQuery ? HttpStatusCode.NotFound : HttpStatusCode.Forbidden)); tableEntity.PartitionKey = partitionKey; } if (endPk != null) { tableEntity.PartitionKey = "Z"; if (endPk.CompareTo(tableEntity.PartitionKey) >= 0) { Assert.Inconclusive("Test error: partition key for this test must not be greater than or equal to \"Z\""); } TestHelper.ExpectedException( (ctx) => runOperationDelegate(tableEntity, ctx), string.Format("{0} after allowed partition key range", opName), (int)(isPointQuery ? HttpStatusCode.NotFound : HttpStatusCode.Forbidden)); tableEntity.PartitionKey = partitionKey; } if (startRk != null) { if (isRangeQuery || startPk != null) { tableEntity.PartitionKey = startPk; tableEntity.RowKey = "A"; if (startRk.CompareTo(tableEntity.RowKey) <= 0) { Assert.Inconclusive("Test error: row key for this test must not be less than or equal to \"A\""); } TestHelper.ExpectedException( (ctx) => runOperationDelegate(tableEntity, ctx), string.Format("{0} before allowed row key range", opName), (int)(isPointQuery ? HttpStatusCode.NotFound : HttpStatusCode.Forbidden)); tableEntity.RowKey = rowKey; } } if (endRk != null) { if (isRangeQuery || endPk != null) { tableEntity.PartitionKey = endPk; tableEntity.RowKey = "Z"; if (endRk.CompareTo(tableEntity.RowKey) >= 0) { Assert.Inconclusive("Test error: row key for this test must not be greater than or equal to \"Z\""); } TestHelper.ExpectedException( (ctx) => runOperationDelegate(tableEntity, ctx), string.Format("{0} after allowed row key range", opName), (int)(isPointQuery ? HttpStatusCode.NotFound : HttpStatusCode.Forbidden)); tableEntity.RowKey = rowKey; } } } #endregion #region SAS Error Conditions //[TestMethod] // Disabled until service bug is fixed [Description("Attempt to use SAS to authenticate table operations that must not work with SAS.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSasInvalidOperations() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); // Prepare SAS authentication with full permissions string sasString = table.GetSharedAccessSignature( new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Delete, SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30) }, null, null, null, null, null); CloudTableClient sasClient = new CloudTableClient(tableClient.BaseUri, new StorageCredentials(sasString)); // Construct a valid set of service properties to upload. ServiceProperties properties = new ServiceProperties(new LoggingProperties(), new MetricsProperties(), new MetricsProperties()); properties.Logging.Version = Constants.AnalyticsConstants.LoggingVersionV1; properties.HourMetrics.Version = Constants.AnalyticsConstants.MetricsVersionV1; properties.Logging.RetentionDays = 9; sasClient.GetServiceProperties(); sasClient.SetServiceProperties(properties); // Test invalid client operations // BUGBUG: ListTables hides the exception. We should fix this // TestHelpers.ExpectedException(() => sasClient.ListTablesSegmented(), "List tables with SAS", HttpStatusCode.Forbidden); TestHelper.ExpectedException((ctx) => sasClient.GetServiceProperties(), "Get service properties with SAS", (int)HttpStatusCode.Forbidden); TestHelper.ExpectedException((ctx) => sasClient.SetServiceProperties(properties), "Set service properties with SAS", (int)HttpStatusCode.Forbidden); CloudTable sasTable = sasClient.GetTableReference(table.Name); // Verify that creation fails with SAS TestHelper.ExpectedException((ctx) => sasTable.Create(null, ctx), "Create a table with SAS", (int)HttpStatusCode.Forbidden); // Create the table. table.Create(); // Test invalid table operations TestHelper.ExpectedException((ctx) => sasTable.Delete(null, ctx), "Delete a table with SAS", (int)HttpStatusCode.Forbidden); TestHelper.ExpectedException((ctx) => sasTable.GetPermissions(null, ctx), "Get ACL with SAS", (int)HttpStatusCode.Forbidden); TestHelper.ExpectedException((ctx) => sasTable.SetPermissions(new TablePermissions(), null, ctx), "Set ACL with SAS", (int)HttpStatusCode.Forbidden); } finally { table.DeleteIfExists(); } } #endregion #region Update SAS token [TestMethod] [Description("Update table SAS.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableUpdateSasTestSync() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); BaseEntity entity = new BaseEntity("PK", "RK"); entity.Populate(); table.Execute(TableOperation.Insert(entity)); SharedAccessTablePolicy policy = new SharedAccessTablePolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = SharedAccessTablePermissions.Delete, }; string sasToken = table.GetSharedAccessSignature(policy); StorageCredentials creds = new StorageCredentials(sasToken); CloudTable sasTable = new CloudTable(table.Uri, creds); BaseEntity entity2 = new BaseEntity("PK", "RK2"); entity2.Populate(); TestHelper.ExpectedException( () => sasTable.Execute(TableOperation.Insert(entity2)), "Try to insert an entity when SAS doesn't allow inserts", HttpStatusCode.Forbidden); sasTable.Execute(TableOperation.Delete(entity)); SharedAccessTablePolicy policy2 = new SharedAccessTablePolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Add, }; string sasToken2 = table.GetSharedAccessSignature(policy2); creds.UpdateSASToken(sasToken2); sasTable = new CloudTable(table.Uri, creds); BaseEntity entity3 = new BaseEntity("PK", "RK2"); entity3.Populate(); sasTable.Execute(TableOperation.Insert(entity3)); } finally { table.DeleteIfExists(); } } #endregion #region SasUri [TestMethod] [Description("Use table SasUri.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSasUriTestSync() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); BaseEntity entity = new BaseEntity("PK", "RK"); entity.Populate(); BaseEntity entity1 = new BaseEntity("PK", "RK1"); entity1.Populate(); table.Execute(TableOperation.Insert(entity)); table.Execute(TableOperation.Insert(entity1)); SharedAccessTablePolicy policy = new SharedAccessTablePolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = SharedAccessTablePermissions.Delete, }; string sasToken = table.GetSharedAccessSignature(policy); StorageCredentials creds = new StorageCredentials(sasToken); CloudStorageAccount sasAcc = new CloudStorageAccount(creds, null /* blobEndpoint */, null /* queueEndpoint */, new Uri(TestBase.TargetTenantConfig.TableServiceEndpoint), null /* fileEndpoint */); CloudTableClient client = sasAcc.CreateCloudTableClient(); CloudTable sasTable = new CloudTable(client.Credentials.TransformUri(table.Uri)); sasTable.Execute(TableOperation.Delete(entity)); CloudTable sasTable2 = new CloudTable(new Uri(table.Uri.ToString() + sasToken)); sasTable2.Execute(TableOperation.Delete(entity1)); } finally { table.DeleteIfExists(); } } [TestMethod] [Description("Use table SasUri.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSasUriPkRkTestSync() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); SharedAccessTablePolicy policy = new SharedAccessTablePolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = SharedAccessTablePermissions.Add, }; string sasTokenPkRk = table.GetSharedAccessSignature(policy, null, "tables_batch_0", "00", "tables_batch_1", "04"); StorageCredentials credsPkRk = new StorageCredentials(sasTokenPkRk); // transform uri from credentials CloudTable sasTableTransformed = new CloudTable(credsPkRk.TransformUri(table.Uri)); // create uri by appending sas CloudTable sasTableDirect = new CloudTable(new Uri(table.Uri.ToString() + sasTokenPkRk)); BaseEntity pkrkEnt = new BaseEntity("tables_batch_0", "00"); pkrkEnt.Populate(); sasTableTransformed.Execute(TableOperation.Insert(pkrkEnt)); pkrkEnt = new BaseEntity("tables_batch_0", "01"); pkrkEnt.Populate(); sasTableDirect.Execute(TableOperation.Insert(pkrkEnt)); Action<BaseEntity, CloudTable, OperationContext> insertDelegate = (tableEntity, sasTable1, ctx) => { tableEntity.Populate(); sasTable1.Execute(TableOperation.Insert(tableEntity), null, ctx); }; pkrkEnt = new BaseEntity("tables_batch_2", "00"); pkrkEnt.Populate(); TestHelper.ExpectedException( (ctx) => insertDelegate(pkrkEnt, sasTableTransformed, ctx), string.Format("Inserted entity without appropriate SAS permissions."), (int)HttpStatusCode.Forbidden); TestHelper.ExpectedException( (ctx) => insertDelegate(pkrkEnt, sasTableDirect, ctx), string.Format("Inserted entity without appropriate SAS permissions."), (int)HttpStatusCode.Forbidden); pkrkEnt = new BaseEntity("tables_batch_1", "05"); TestHelper.ExpectedException( (ctx) => insertDelegate(pkrkEnt, sasTableTransformed, ctx), string.Format("Inserted entity without appropriate SAS permissions."), (int)HttpStatusCode.Forbidden); TestHelper.ExpectedException( (ctx) => insertDelegate(pkrkEnt, sasTableDirect, ctx), string.Format("Inserted entity without appropriate SAS permissions."), (int)HttpStatusCode.Forbidden); } finally { table.DeleteIfExists(); } } #endregion #region SASIPAddressTests /// <summary> /// Helper function for testing the IPAddressOrRange funcitonality for tables /// </summary> /// <param name="generateInitialIPAddressOrRange">Function that generates an initial IPAddressOrRange object to use. This is expected to fail on the service.</param> /// <param name="generateFinalIPAddressOrRange">Function that takes in the correct IP address (according to the service) and returns the IPAddressOrRange object /// that should be accepted by the service</param> public void CloudTableSASIPAddressHelper(Func<IPAddressOrRange> generateInitialIPAddressOrRange, Func<IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange) { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); SharedAccessTablePolicy policy = new SharedAccessTablePolicy() { Permissions = SharedAccessTablePermissions.Query, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; DynamicTableEntity entity = new DynamicTableEntity("PK", "RK", null, new Dictionary<string, EntityProperty>() { { "prop", new EntityProperty(4) } }); table.Execute(new TableOperation(entity, TableOperationType.Insert)); // The plan then is to use an incorrect IP address to make a call to the service // ensure that we get an error message // parse the error message to get my actual IP (as far as the service sees) // then finally test the success case to ensure we can actually make requests IPAddressOrRange ipAddressOrRange = generateInitialIPAddressOrRange(); string tableToken = table.GetSharedAccessSignature(policy, null, null, null, null, null, null, ipAddressOrRange); StorageCredentials tableSAS = new StorageCredentials(tableToken); Uri tableSASUri = tableSAS.TransformUri(table.Uri); StorageUri tableSASStorageUri = tableSAS.TransformUri(table.StorageUri); CloudTable tableWithSAS = new CloudTable(tableSASUri); OperationContext opContext = new OperationContext(); IPAddress actualIP = null; bool exceptionThrown = false; TableResult result = null; DynamicTableEntity resultEntity = new DynamicTableEntity(); TableOperation retrieveOp = new TableOperation(resultEntity, TableOperationType.Retrieve); retrieveOp.RetrievePartitionKey = entity.PartitionKey; retrieveOp.RetrieveRowKey = entity.RowKey; try { result = tableWithSAS.Execute(retrieveOp, null, opContext); } catch (StorageException e) { string[] parts = e.RequestInformation.HttpStatusMessage.Split(' '); exceptionThrown = true; Assert.IsNull(actualIP); } Assert.IsTrue(exceptionThrown); ipAddressOrRange = null; tableToken = table.GetSharedAccessSignature(policy, null, null, null, null, null, null, ipAddressOrRange); tableSAS = new StorageCredentials(tableToken); tableSASUri = tableSAS.TransformUri(table.Uri); tableSASStorageUri = tableSAS.TransformUri(table.StorageUri); tableWithSAS = new CloudTable(tableSASUri); resultEntity = new DynamicTableEntity(); retrieveOp = new TableOperation(resultEntity, TableOperationType.Retrieve); retrieveOp.RetrievePartitionKey = entity.PartitionKey; retrieveOp.RetrieveRowKey = entity.RowKey; resultEntity = (DynamicTableEntity)tableWithSAS.Execute(retrieveOp).Result; Assert.AreEqual(entity.Properties["prop"].PropertyType, resultEntity.Properties["prop"].PropertyType); Assert.AreEqual(entity.Properties["prop"].Int32Value.Value, resultEntity.Properties["prop"].Int32Value.Value); Assert.IsTrue(table.StorageUri.PrimaryUri.Equals(tableWithSAS.Uri)); Assert.IsNull(tableWithSAS.StorageUri.SecondaryUri); tableWithSAS = new CloudTable(tableSASStorageUri, null); resultEntity = new DynamicTableEntity(); retrieveOp = new TableOperation(resultEntity, TableOperationType.Retrieve); retrieveOp.RetrievePartitionKey = entity.PartitionKey; retrieveOp.RetrieveRowKey = entity.RowKey; resultEntity = (DynamicTableEntity)tableWithSAS.Execute(retrieveOp).Result; Assert.AreEqual(entity.Properties["prop"].PropertyType, resultEntity.Properties["prop"].PropertyType); Assert.AreEqual(entity.Properties["prop"].Int32Value.Value, resultEntity.Properties["prop"].Int32Value.Value); Assert.IsTrue(table.StorageUri.Equals(tableWithSAS.StorageUri)); } finally { table.DeleteIfExists(); } } [TestMethod] [Description("Perform a SAS request specifying an IP address or range and ensure that everything works properly.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudTableSASIPAddressQueryParam() { CloudTableSASIPAddressHelper(() => { // We need an IP address that will never be a valid source IPAddress invalidIP = IPAddress.Parse("255.255.255.255"); return new IPAddressOrRange(invalidIP.ToString()); }, (IPAddress actualIP) => { return new IPAddressOrRange(actualIP.ToString()); }); } [TestMethod] [Description("Perform a SAS request specifying an IP address or range and ensure that everything works properly.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudTableSASIPRangeQueryParam() { CloudTableSASIPAddressHelper(() => { // We need an IP address that will never be a valid source IPAddress invalidIPBegin = IPAddress.Parse("255.255.255.0"); IPAddress invalidIPEnd = IPAddress.Parse("255.255.255.255"); return new IPAddressOrRange(invalidIPBegin.ToString(), invalidIPEnd.ToString()); }, (IPAddress actualIP) => { byte[] actualAddressBytes = actualIP.GetAddressBytes(); byte[] initialAddressBytes = actualAddressBytes.ToArray(); initialAddressBytes[0]--; byte[] finalAddressBytes = actualAddressBytes.ToArray(); finalAddressBytes[0]++; return new IPAddressOrRange(new IPAddress(initialAddressBytes).ToString(), new IPAddress(finalAddressBytes).ToString()); }); } #endregion #region SASHttpsTests [TestMethod] [Description("Perform a SAS request specifying a shared protocol and ensure that everything works properly.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudTableSASSharedProtocolsQueryParam() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); SharedAccessTablePolicy policy = new SharedAccessTablePolicy() { Permissions = SharedAccessTablePermissions.Query, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; DynamicTableEntity entity = new DynamicTableEntity("PK", "RK", null, new Dictionary<string, EntityProperty>() { { "prop", new EntityProperty(4) } }); table.Execute(new TableOperation(entity, TableOperationType.Insert)); foreach (SharedAccessProtocol? protocol in new SharedAccessProtocol?[] { null, SharedAccessProtocol.HttpsOrHttp, SharedAccessProtocol.HttpsOnly }) { string tableToken = table.GetSharedAccessSignature(policy, null, null, null, null, null, protocol, null); StorageCredentials tableSAS = new StorageCredentials(tableToken); Uri tableSASUri = new Uri(table.Uri + tableSAS.SASToken); StorageUri tableSASStorageUri = new StorageUri(new Uri(table.StorageUri.PrimaryUri + tableSAS.SASToken), new Uri(table.StorageUri.SecondaryUri + tableSAS.SASToken)); int httpPort = tableSASUri.Port; int securePort = 443; if (!string.IsNullOrEmpty(TestBase.TargetTenantConfig.TableSecurePortOverride)) { securePort = Int32.Parse(TestBase.TargetTenantConfig.TableSecurePortOverride); } var schemesAndPorts = new[] { new { scheme = Uri.UriSchemeHttp, port = httpPort}, new { scheme = Uri.UriSchemeHttps, port = securePort} }; CloudTable tableWithSAS = null; TableOperation retrieveOp = TableOperation.Retrieve(entity.PartitionKey, entity.RowKey); foreach (var item in schemesAndPorts) { tableSASUri = TransformSchemeAndPort(tableSASUri, item.scheme, item.port); tableSASStorageUri = new StorageUri(TransformSchemeAndPort(tableSASStorageUri.PrimaryUri, item.scheme, item.port), TransformSchemeAndPort(tableSASStorageUri.SecondaryUri, item.scheme, item.port)); if (protocol.HasValue && protocol.Value == SharedAccessProtocol.HttpsOnly && string.CompareOrdinal(item.scheme, Uri.UriSchemeHttp) == 0) { tableWithSAS = new CloudTable(tableSASUri); TestHelper.ExpectedException(() => tableWithSAS.Execute(retrieveOp), "Access a table using SAS with a shared protocols that does not match", HttpStatusCode.Unused); tableWithSAS = new CloudTable(tableSASStorageUri, null); TestHelper.ExpectedException(() => tableWithSAS.Execute(retrieveOp), "Access a table using SAS with a shared protocols that does not match", HttpStatusCode.Unused); } else { tableWithSAS = new CloudTable(tableSASUri); TableResult result = tableWithSAS.Execute(retrieveOp); Assert.AreEqual(entity.Properties["prop"], ((DynamicTableEntity)result.Result).Properties["prop"]); tableWithSAS = new CloudTable(tableSASStorageUri, null); result = tableWithSAS.Execute(retrieveOp); Assert.AreEqual(entity.Properties["prop"], ((DynamicTableEntity)result.Result).Properties["prop"]); } } } } finally { table.DeleteIfExists(); } } private static Uri TransformSchemeAndPort(Uri input, string scheme, int port) { UriBuilder builder = new UriBuilder(input); builder.Scheme = scheme; builder.Port = port; return builder.Uri; } #endregion #region Test Helpers internal static void AssertPermissionsEqual(TablePermissions permissions1, TablePermissions permissions2) { Assert.AreEqual(permissions1.SharedAccessPolicies.Count, permissions2.SharedAccessPolicies.Count); foreach (KeyValuePair<string, SharedAccessTablePolicy> pair in permissions1.SharedAccessPolicies) { SharedAccessTablePolicy policy1 = pair.Value; SharedAccessTablePolicy policy2 = permissions2.SharedAccessPolicies[pair.Key]; Assert.IsNotNull(policy1); Assert.IsNotNull(policy2); Assert.AreEqual(policy1.Permissions, policy2.Permissions); if (policy1.SharedAccessStartTime != null) { Assert.IsTrue(Math.Floor((policy1.SharedAccessStartTime.Value - policy2.SharedAccessStartTime.Value).TotalSeconds) == 0); } if (policy1.SharedAccessExpiryTime != null) { Assert.IsTrue(Math.Floor((policy1.SharedAccessExpiryTime.Value - policy2.SharedAccessExpiryTime.Value).TotalSeconds) == 0); } } } #endregion } }
45.85473
220
0.58083
[ "Apache-2.0" ]
Tarak-Chandra-Sarkar/azure-storage-net
Test/ClassLibraryCommon/Table/SAS/TableSasUnitTests.cs
67,867
C#
#region Copyright // Copyright Hitachi Consulting // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System.Collections.Generic; namespace Xigadee { /// <summary> /// This class contains the specific policy options for the type of logging. /// </summary> public class AzureStorageDataCollectorPolicy:DataCollectorPolicy { /// <summary> /// This is the Log options. /// </summary> public AzureStorageDataCollectorOptions Log { get; set; } = new AzureStorageDataCollectorOptions(DataCollectionSupport.Logger , AzureStorageBehaviour.BlobAndTable , serializerTable: AzureStorageHelper.ToTableLogEvent , binaryMakeId: BinaryContainerHelper.LoggerMakeId , binaryMakeFolder: BinaryContainerHelper.LoggerMakeFolder , isSupported: AzureStorageHelper.DefaultLogLevelSupport ); /// <summary> /// This is the EventSource options. /// </summary> public AzureStorageDataCollectorOptions EventSource { get; set; } = new AzureStorageDataCollectorOptions(DataCollectionSupport.EventSource , AzureStorageBehaviour.Blob , binaryMakeId: BinaryContainerHelper.EventSourceMakeId , binaryMakeFolder: BinaryContainerHelper.EventSourceMakeFolder ); /// <summary> /// This is the Statistics options. By default encryption is not set for statistics. /// </summary> public AzureStorageDataCollectorOptions Statistics { get; set; } = new AzureStorageDataCollectorOptions(DataCollectionSupport.Statistics , AzureStorageBehaviour.Blob , makeId: BinaryContainerHelper.StatisticsMakeId , binaryMakeId: BinaryContainerHelper.StatisticsMakeId , binaryMakeFolder: BinaryContainerHelper.StatisticsMakeFolder ) { EncryptionPolicy = AzureStorageEncryption.None}; /// <summary> /// This is the Dispatcher options. /// </summary> public AzureStorageDataCollectorOptions Dispatcher { get; set; } = new AzureStorageDataCollectorOptions(DataCollectionSupport.Dispatcher , AzureStorageBehaviour.Table , AzureStorageHelper.ToTableDispatcherEvent ); /// <summary> /// This is the Boundary Table storage options. /// </summary> public AzureStorageDataCollectorOptions Boundary { get; set; } = new AzureStorageDataCollectorOptions(DataCollectionSupport.Boundary , AzureStorageBehaviour.Table , AzureStorageHelper.ToTableBoundaryEvent ); /// <summary> /// This is the Telemetry Table storage options. /// </summary> public AzureStorageDataCollectorOptions Telemetry { get; set; } = new AzureStorageDataCollectorOptions(DataCollectionSupport.Telemetry , AzureStorageBehaviour.Table , AzureStorageHelper.ToTableTelemetryEvent ); /// <summary> /// This is the Resource Table storage options. /// </summary> public AzureStorageDataCollectorOptions Resource { get; set; } = new AzureStorageDataCollectorOptions(DataCollectionSupport.Resource , AzureStorageBehaviour.Table , AzureStorageHelper.ToTableGeneric ); /// <summary> /// This is the Resource Table storage options. /// </summary> public AzureStorageDataCollectorOptions Security { get; set; } = new AzureStorageDataCollectorOptions(DataCollectionSupport.Security , AzureStorageBehaviour.Table , AzureStorageHelper.ToTableGeneric ); /// <summary> /// This is the Custom options. /// </summary> public AzureStorageDataCollectorOptions Custom { get; set; } = new AzureStorageDataCollectorOptions(DataCollectionSupport.Custom); /// <summary> /// This is the Boundary Table storage options. /// </summary> public AzureStorageDataCollectorOptions ApiBoundary { get; set; } = new AzureStorageDataCollectorOptions(DataCollectionSupport.ApiBoundary , AzureStorageBehaviour.BlobAndTable , AzureStorageHelper.ToTableBoundaryEvent , binaryMakeId: BinaryContainerHelper.BoundaryMakeId , binaryMakeFolder: BinaryContainerHelper.BoundaryMakeFolder ); /// <summary> /// This is an enumeration of all the options. /// </summary> public virtual IEnumerable<AzureStorageDataCollectorOptions> Options { get { yield return Log; yield return EventSource; yield return Statistics; yield return Dispatcher; yield return Boundary; yield return Telemetry; yield return Resource; yield return Custom; yield return Security; yield return ApiBoundary; } } } }
42.413043
92
0.626858
[ "Apache-2.0" ]
xigadee/Microservice
Src/Xigadee.Azure.Storage/DataCollection/AzureStorageDataCollectorPolicy.cs
5,855
C#
// ----------------------------------------------------------------------------------------- // <copyright file="BaseEntity.cs" company="Microsoft"> // Copyright 2012 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // ----------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.WindowsAzure.Storage.Table.DataServices; namespace Microsoft.WindowsAzure.Storage.Table.DataServices.Entities { public class BaseEntity : TableServiceEntity { public BaseEntity() : base() { } public BaseEntity(string pk, string rk) : base(pk, rk) { } public string A { get; set; } public string B { get; set; } public string C { get; set; } public void Randomize() { A = Guid.NewGuid().ToString(); B = Guid.NewGuid().ToString(); C = Guid.NewGuid().ToString(); } } }
33.64
94
0.54459
[ "Apache-2.0" ]
takekazuomi/azure-sdk-for-net
microsoft-azure-api/Services/Storage/Test/Unit/DotNetCommon/Table/DataServices/Entities/BaseEntity.cs
1,635
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 datapipeline-2012-10-29.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DataPipeline.Model { /// <summary> /// Container for the parameters to the SetTaskStatus operation. /// Task runners call <code>SetTaskStatus</code> to notify AWS Data Pipeline that a task /// is completed and provide information about the final status. A task runner makes this /// call regardless of whether the task was sucessful. A task runner does not need to /// call <code>SetTaskStatus</code> for tasks that are canceled by the web service during /// a call to <a>ReportTaskProgress</a>. /// </summary> public partial class SetTaskStatusRequest : AmazonDataPipelineRequest { private string _errorId; private string _errorMessage; private string _errorStackTrace; private string _taskId; private TaskStatus _taskStatus; /// <summary> /// Gets and sets the property ErrorId. /// <para> /// If an error occurred during the task, this value specifies the error code. This value /// is set on the physical attempt object. It is used to display error information to /// the user. It should not start with string "Service_" which is reserved by the system. /// </para> /// </summary> [AWSProperty(Min=0, Max=1024)] public string ErrorId { get { return this._errorId; } set { this._errorId = value; } } // Check to see if ErrorId property is set internal bool IsSetErrorId() { return this._errorId != null; } /// <summary> /// Gets and sets the property ErrorMessage. /// <para> /// If an error occurred during the task, this value specifies a text description of the /// error. This value is set on the physical attempt object. It is used to display error /// information to the user. The web service does not parse this value. /// </para> /// </summary> public string ErrorMessage { get { return this._errorMessage; } set { this._errorMessage = value; } } // Check to see if ErrorMessage property is set internal bool IsSetErrorMessage() { return this._errorMessage != null; } /// <summary> /// Gets and sets the property ErrorStackTrace. /// <para> /// If an error occurred during the task, this value specifies the stack trace associated /// with the error. This value is set on the physical attempt object. It is used to display /// error information to the user. The web service does not parse this value. /// </para> /// </summary> [AWSProperty(Min=0, Max=1024)] public string ErrorStackTrace { get { return this._errorStackTrace; } set { this._errorStackTrace = value; } } // Check to see if ErrorStackTrace property is set internal bool IsSetErrorStackTrace() { return this._errorStackTrace != null; } /// <summary> /// Gets and sets the property TaskId. /// <para> /// The ID of the task assigned to the task runner. This value is provided in the response /// for <a>PollForTask</a>. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=2048)] public string TaskId { get { return this._taskId; } set { this._taskId = value; } } // Check to see if TaskId property is set internal bool IsSetTaskId() { return this._taskId != null; } /// <summary> /// Gets and sets the property TaskStatus. /// <para> /// If <code>FINISHED</code>, the task successfully completed. If <code>FAILED</code>, /// the task ended unsuccessfully. Preconditions use false. /// </para> /// </summary> [AWSProperty(Required=true)] public TaskStatus TaskStatus { get { return this._taskStatus; } set { this._taskStatus = value; } } // Check to see if TaskStatus property is set internal bool IsSetTaskStatus() { return this._taskStatus != null; } } }
34.946667
110
0.607974
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/DataPipeline/Generated/Model/SetTaskStatusRequest.cs
5,242
C#
using NATS.Client; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading; using Utils; namespace Replier { class Program { static void Main(string[] args) { try { new Replier().Run(args); } catch (Exception ex) { Console.Error.WriteLine("Exception: " + ex.Message); Console.Error.WriteLine(ex); } } } class Replier { Dictionary<string, string> parsedArgs = new Dictionary<string, string>(); int count = 20000; string url = Defaults.Url; //string url = "nats://nats:4222"; string subject = "foo"; bool sync = false; int received = 0; bool verbose = false; Msg replyMsg = new Msg(); string creds = null; private string queueGroup=null; public void Run(string[] args) { parseArgs(args); banner(); Options opts = ConnectionFactory.GetDefaultOptions(); opts.Url = url; if (creds != null) { opts.SetUserCredentials(creds); } replyMsg.Data = Encoding.UTF8.GetBytes("reply"); using (IConnection c = new ConnectionFactory().CreateConnection(opts)) { TimeSpan elapsed; if (sync) { elapsed = receiveSyncSubscriber(c); } else { elapsed = receiveAsyncSubscriber(c); } Console.Write("Replied to {0} msgs in {1} seconds ", received, elapsed.TotalSeconds); Console.WriteLine("({0} replies/second).", (int)(received / elapsed.TotalSeconds)); printStats(c); } } private void printStats(IConnection c) { IStatistics s = c.Stats; Console.WriteLine("Statistics: "); Console.WriteLine(" Incoming Payload Bytes: {0}", s.InBytes); Console.WriteLine(" Incoming Messages: {0}", s.InMsgs); Console.WriteLine(" Outgoing Payload Bytes: {0}", s.OutBytes); Console.WriteLine(" Outgoing Messages: {0}", s.OutMsgs); } private TimeSpan receiveAsyncSubscriber(IConnection c) { Stopwatch sw = null; AutoResetEvent subDone = new AutoResetEvent(false); EventHandler<MsgHandlerEventArgs> msgHandler = (sender, args) => { if (received == 0) { sw = new Stopwatch(); sw.Start(); } received++; if (verbose) Console.WriteLine("Received: " + args.Message); replyMsg.Subject = args.Message.Reply; c.Publish(replyMsg); c.Flush(); if (received == count) { sw.Stop(); subDone.Set(); } }; using (IAsyncSubscription s = (queueGroup == null?c.SubscribeAsync(subject, msgHandler): c.SubscribeAsync(subject, queueGroup,msgHandler))) { // just wait to complete subDone.WaitOne(); } return sw.Elapsed; } private TimeSpan receiveSyncSubscriber(IConnection c) { using (ISyncSubscription s = queueGroup==null?c.SubscribeSync(subject): c.SubscribeSync(subject, queueGroup)) { Stopwatch sw = new Stopwatch(); while (received < count) { if (received == 0) sw.Start(); Msg m = s.NextMessage(); received++; if (verbose) Console.WriteLine("Received: " + m); replyMsg.Subject = m.Reply; c.Publish(replyMsg); } sw.Stop(); return sw.Elapsed; } } private void usage() { Console.Error.WriteLine( "Usage: Replier [-url url] [-subject subject] " + "-count [count] -creds [file] [-sync] [-verbose]"); Environment.Exit(-1); } private void parseArgs(string[] args) { if (args == null) return; bool exists = false; (exists,verbose) = "VERBOSE".GetEnvironmentVariable(false); (exists, subject) = "SUBJECT".GetEnvironmentVariable(subject); (exists, url) = "URL".GetEnvironmentVariable(url); (exists, queueGroup) = "QUEUE_GROUP".GetEnvironmentVariable(queueGroup); for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-sync") || args[i].Equals("-verbose")) { parsedArgs.Add(args[i], "true"); } else { if (i + 1 == args.Length) usage(); parsedArgs.Add(args[i], args[i + 1]); i++; } } if (parsedArgs.ContainsKey("-count")) count = Convert.ToInt32(parsedArgs["-count"]); if (parsedArgs.ContainsKey("-url")) url = parsedArgs["-url"]; if (parsedArgs.ContainsKey("-subject")) subject = parsedArgs["-subject"]; if (parsedArgs.ContainsKey("-sync")) sync = true; if (parsedArgs.ContainsKey("-verbose")) verbose = true; if (parsedArgs.ContainsKey("-creds")) creds = parsedArgs["-creds"]; Console.WriteLine($"VERBOSE={verbose}"); Console.WriteLine($"SUBJECT={subject}"); Console.WriteLine($"URL={url}"); Console.WriteLine($"QUEUE_GROUP={queueGroup}"); } private void banner() { Console.WriteLine("Receiving {0} messages on subject {1}", count, subject); Console.WriteLine(" Url: {0}", url); Console.WriteLine(" Receiving: {0}", sync ? "Synchronously" : "Asynchronously"); } } }
29.235556
151
0.463819
[ "MIT" ]
P7CoreOrg/dotnetcore-nats-play
src/Replier/Program.cs
6,580
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 organizations-2016-11-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Organizations.Model { /// <summary> /// An OU with the same name already exists. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class DuplicateOrganizationalUnitException : AmazonOrganizationsException { /// <summary> /// Constructs a new DuplicateOrganizationalUnitException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public DuplicateOrganizationalUnitException(string message) : base(message) {} /// <summary> /// Construct instance of DuplicateOrganizationalUnitException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public DuplicateOrganizationalUnitException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of DuplicateOrganizationalUnitException /// </summary> /// <param name="innerException"></param> public DuplicateOrganizationalUnitException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of DuplicateOrganizationalUnitException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public DuplicateOrganizationalUnitException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of DuplicateOrganizationalUnitException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public DuplicateOrganizationalUnitException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the DuplicateOrganizationalUnitException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected DuplicateOrganizationalUnitException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
48.370968
178
0.688563
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Organizations/Generated/Model/DuplicateOrganizationalUnitException.cs
5,998
C#
using System; using Core.Entities; using Core.Entities.Financial; namespace Core.ApplicationModels.Dtos.Financial { public class BillingDto : BaseEntityDto { public int BeneficiaryId { get; set; } public string BeneficiaryName { get; set; } public PersonDocumentType PersonType { get; set; } public DateTime? EndDate { get; set; } public decimal Price { get; set; } public decimal? Discount { get; set; } public bool IsPaid { get; set; } public static BillingDto FromModel(Billing model) { return new BillingDto() { BeneficiaryName = model.BeneficiaryName, PersonType = model.PersonType, EndDate = model.EndDate, Price = model.Price, Discount = model.Discount, IsPaid = model.IsPaid, }; } public Billing ToModel() { return new Billing() { BeneficiaryName = BeneficiaryName, PersonType = PersonType, EndDate = EndDate, Price = Price, Discount = Discount, IsPaid = IsPaid, }; } } }
27.354167
58
0.505712
[ "MIT" ]
adnanioricce/DHsys
src/Libraries/Core/ApplicationModels/Dtos/Financial/BillingDto.cs
1,313
C#
// This file is part of the DisCatSharp project. // // Copyright (c) 2021 AITSYS // // 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.Globalization; using DisCatSharp.Enums.Discord; using DisCatSharp.Net; using DisCatSharp.Net.Abstractions; namespace DisCatSharp.Entities { /// <summary> /// Represents a team consisting of users. A team can own an application. /// </summary> public sealed class DiscordTeam : SnowflakeObject, IEquatable<DiscordTeam> { /// <summary> /// Gets the team's name. /// </summary> public string Name { get; internal set; } /// <summary> /// Gets the team's icon hash. /// </summary> public string IconHash { get; internal set; } /// <summary> /// Gets the team's icon. /// </summary> public string Icon => !string.IsNullOrWhiteSpace(this.IconHash) ? $"{DiscordDomain.GetDomain(CoreDomain.DiscordCdn).Url}{Endpoints.TEAM_ICONS}/{this.Id.ToString(CultureInfo.InvariantCulture)}/{this.IconHash}.png?size=1024" : null; /// <summary> /// Gets the owner of the team. /// </summary> public DiscordUser Owner { get; internal set; } /// <summary> /// Gets the members of this team. /// </summary> public IReadOnlyList<DiscordTeamMember> Members { get; internal set; } /// <summary> /// Initializes a new instance of the <see cref="DiscordTeam"/> class. /// </summary> /// <param name="tt">The tt.</param> internal DiscordTeam(TransportTeam tt) { this.Id = tt.Id; this.Name = tt.Name; this.IconHash = tt.IconHash; } /// <summary> /// Compares this team to another object and returns whether they are equal. /// </summary> /// <param name="obj">Object to compare this team to.</param> /// <returns>Whether this team is equal to the given object.</returns> public override bool Equals(object obj) => obj is DiscordTeam other && this == other; /// <summary> /// Compares this team to another team and returns whether they are equal. /// </summary> /// <param name="other">Team to compare to.</param> /// <returns>Whether the teams are equal.</returns> public bool Equals(DiscordTeam other) => this == other; /// <summary> /// Gets the hash code of this team. /// </summary> /// <returns>Hash code of this team.</returns> public override int GetHashCode() => this.Id.GetHashCode(); /// <summary> /// Converts this team to its string representation. /// </summary> /// <returns>The string representation of this team.</returns> public override string ToString() => $"Team: {this.Name} ({this.Id})"; public static bool operator ==(DiscordTeam left, DiscordTeam right) => left?.Id == right?.Id; public static bool operator !=(DiscordTeam left, DiscordTeam right) => left?.Id != right?.Id; } /// <summary> /// Represents a member of <see cref="DiscordTeam"/>. /// </summary> public sealed class DiscordTeamMember : IEquatable<DiscordTeamMember> { /// <summary> /// Gets the member's membership status. /// </summary> public DiscordTeamMembershipStatus MembershipStatus { get; internal set; } /// <summary> /// Gets the member's permissions within the team. /// </summary> public IReadOnlyCollection<string> Permissions { get; internal set; } /// <summary> /// Gets the team this member belongs to. /// </summary> public DiscordTeam Team { get; internal set; } /// <summary> /// Gets the user who is the team member. /// </summary> public DiscordUser User { get; internal set; } /// <summary> /// Initializes a new instance of the <see cref="DiscordTeamMember"/> class. /// </summary> /// <param name="ttm">The ttm.</param> internal DiscordTeamMember(TransportTeamMember ttm) { this.MembershipStatus = (DiscordTeamMembershipStatus)ttm.MembershipState; this.Permissions = new ReadOnlySet<string>(new HashSet<string>(ttm.Permissions)); } /// <summary> /// Compares this team member to another object and returns whether they are equal. /// </summary> /// <param name="obj">Object to compare to.</param> /// <returns>Whether this team is equal to given object.</returns> public override bool Equals(object obj) => obj is DiscordTeamMember other && this == other; /// <summary> /// Compares this team member to another team member and returns whether they are equal. /// </summary> /// <param name="other">Team member to compare to.</param> /// <returns>Whether this team member is equal to the given one.</returns> public bool Equals(DiscordTeamMember other) => this == other; /// <summary> /// Gets a hash code of this team member. /// </summary> /// <returns>Hash code of this team member.</returns> public override int GetHashCode() { var hash = 13; hash = (hash * 7) + this.User.GetHashCode(); hash = (hash * 7) + this.Team.GetHashCode(); return hash; } /// <summary> /// Converts this team member to their string representation. /// </summary> /// <returns>String representation of this team member.</returns> public override string ToString() => $"Team member: {this.User.Username}#{this.User.Discriminator} ({this.User.Id}), part of team {this.Team.Name} ({this.Team.Id})"; public static bool operator ==(DiscordTeamMember left, DiscordTeamMember right) => left?.Team?.Id == right?.Team?.Id && left?.User?.Id == right?.User?.Id; public static bool operator !=(DiscordTeamMember left, DiscordTeamMember right) => left?.Team?.Id != right?.Team?.Id || left?.User?.Id != right?.User?.Id; } /// <summary> /// Signifies the status of user's team membership. /// </summary> public enum DiscordTeamMembershipStatus : int { /// <summary> /// Indicates that this user is invited to the team, and is pending membership. /// </summary> Invited = 1, /// <summary> /// Indicates that this user is a member of the team. /// </summary> Accepted = 2 } }
38.465686
223
0.606474
[ "Apache-2.0", "MIT" ]
Auros/DisCatSharp
DisCatSharp/Entities/User/DiscordTeam.cs
7,847
C#
using System; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Rca.HueSandbox { class Program { static void Main(string[] args) { Console.WriteLine("Welcome to the Hue-Sandbox :)"); var hue = new HueWrapper(); Console.WriteLine("Scanning for bridges..."); hue.ScanBridges(); Thread.Sleep(500); Console.WriteLine("IPs of found bridges:"); foreach (var bridge in hue.LocatedBridges) Console.WriteLine(bridge.IpAddress); Console.WriteLine("Press any key to initialize the first bridge, for first connection you must press the bridge-button"); Console.ReadKey(); hue.Initialize(); Console.WriteLine("Bridge initialized"); Console.WriteLine("Press any key to switch out all lights"); Console.ReadKey(); hue.TestLight(); Console.ReadKey(); } } }
29.735294
133
0.585559
[ "MIT" ]
rmmlr/HueSandbox
HueSandbox/Program.cs
1,013
C#
namespace System.Collections.Generic { public interface IEnumerable<out T> : IEnumerable { IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); new IEnumerator<T> GetEnumerator(); } }
27.375
67
0.684932
[ "MIT" ]
john-h-k/NetRt
System.Private.CoreLib/Collections/Generic/IEnumerable`1.cs
221
C#
using System; using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.EventSystems; public class LevelEndScreen : ScreenBase, IPointerClickHandler { [SerializeField] public Animator animator; [SerializeField] private GameObject levelCompleteBanner; [SerializeField] private GameObject scoreHorizontalLayout; [SerializeField] private TextMeshProUGUI levelCompletedText; [SerializeField] private TextMeshProUGUI highScoreText; [SerializeField] private TextMeshProUGUI scoreText; [SerializeField] private TextMeshProUGUI bestScoreText; [SerializeField] private TextMeshProUGUI gainedGoldText; [SerializeField] private GameObject tapToContinue; [SerializeField] private ParticleSystem coinBurstVFX; [SerializeField] private ParticleSystem coinScoreVFX; [SerializeField] private List<ParticleSystem> colorfulVFXs; public event Action OnTapToContinue; public static LevelEndScreen Instance { get; private set; } protected override void Awake() { if(Instance == null) { Instance = this; } else if(Instance != this) { Destroy(gameObject); } base.Awake(); } protected override void Start() { base.Start(); FinishLine.OnFinishLine += UpdateEndLevelScreen; GameManager.Instance.OnGameOver += Instance_OnGameOver; GameManager.Instance.OnIsNewHighScore += GameManager_IsNewHighScore; CoinVFXStateMachineBehaviour.OnPlayCoinVFX += LevelEndScreen_OnScorePanelSlidedFinished; ScoreBlendInStateMachineBehaviour.OnScoreBlendInStart += ScoreBlendInStateMachineBehaviour_OnScoreBlendInStart; ShowLevelCompleteAndTapToContinue.OnReadyToShow += ShowLevelCompleteAndTapToContinue_OnReadyToShow; } private void ShowLevelCompleteAndTapToContinue_OnReadyToShow(bool isLevelSuccess) { levelCompleteBanner.gameObject.SetActive(true); tapToContinue.SetActive(true); InGameScreen.Instance.currentLevelPanel.SetActive(false); levelsPanel.SetActive(true); if (isLevelSuccess) { StartCoroutine(UpdateLevelsProgressBarRoutine()); foreach (ParticleSystem colorfulVFX in colorfulVFXs) { colorfulVFX.Play(); } } } private void ScoreBlendInStateMachineBehaviour_OnScoreBlendInStart() { scoreHorizontalLayout.SetActive(true); } private void LevelEndScreen_OnScorePanelSlidedFinished(CoinVFXType vfxType) { (vfxType == CoinVFXType.Burst ? coinBurstVFX : coinScoreVFX).Play(); } private void OnDestroy() { FinishLine.OnFinishLine -= UpdateEndLevelScreen; GameManager.Instance.OnGameOver -= Instance_OnGameOver; GameManager.Instance.OnIsNewHighScore -= GameManager_IsNewHighScore; CoinVFXStateMachineBehaviour.OnPlayCoinVFX -= LevelEndScreen_OnScorePanelSlidedFinished; ScoreBlendInStateMachineBehaviour.OnScoreBlendInStart -= ScoreBlendInStateMachineBehaviour_OnScoreBlendInStart; ShowLevelCompleteAndTapToContinue.OnReadyToShow -= ShowLevelCompleteAndTapToContinue_OnReadyToShow; } private void Instance_OnGameOver(int newScore, int scoreMultiplier) { levelCompletedText.text = "GAME OVER!"; scoreText.text = (newScore / scoreMultiplier) + " x " + scoreMultiplier + " = " + newScore; highScoreText.text = "SCORE"; bestScoreText.text = "Best Score - " + GameManager.Instance.highScore; bestScoreText.gameObject.SetActive(GameManager.Instance.highScore > 0); gameObject.SetActive(true); UpdateLevelsBar(GameManager.Instance.CurrentLevel); animator.SetTrigger("LevelEndTrigger"); } private void GameManager_IsNewHighScore(bool isNewHighScore, int newScore, int scoreMultiplier, int highScore) { highScoreText.text = isNewHighScore ? "NEW HIGH SCORE!" : "SCORE"; scoreText.text = (newScore / scoreMultiplier) + " x " + scoreMultiplier + " = " + newScore; gainedGoldText.text = "+" + newScore.ToString(); bestScoreText.text = "Best Score - " + highScore; bestScoreText.gameObject.SetActive(!isNewHighScore); } private void UpdateEndLevelScreen() { levelCompletedText.text = "Level " + GameManager.Instance.CurrentLevel + " Completed!"; gameObject.SetActive(true); UpdateLevelsBar(GameManager.Instance.CurrentLevel); animator.SetTrigger("LevelEndTrigger"); } private IEnumerator UpdateLevelsProgressBarRoutine() { yield return new WaitForSeconds(0.25f); UpdateLevelsBar(GameManager.Instance.CurrentLevel + 1, 0.5f); } public void OnPointerClick(PointerEventData eventData) { if (!tapToContinue.activeInHierarchy) return; StopAllCoroutines(); scoreHorizontalLayout.SetActive(false); foreach (ParticleSystem colorfulVFX in colorfulVFXs) { colorfulVFX.Stop(); } levelCompleteBanner.gameObject.SetActive(false); tapToContinue.SetActive(false); InGameScreen.Instance.currentLevelPanel.SetActive(true); if (!GameManager.Instance.isGameOver) { UpdateLevelsBar(GameManager.Instance.CurrentLevel + 1); } OnTapToContinue?.Invoke(); } } public enum CoinVFXType { Burst, MoveToScore }
37.691781
119
0.706705
[ "MIT" ]
mhmtckr27/Cube-Games-Case
Assets/Scripts/UI/LevelEndScreen.cs
5,503
C#
#if UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_EDITOR /** * Autogenerated by Thrift Compiler () * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.IO; using Thrift; using Thrift.Collections; using System.Runtime.Serialization; using Thrift.Protocol; using Thrift.Transport; namespace GetSocialSdk.Core { /// <summary> /// #sdk7 /// </summary> #if !SILVERLIGHT [Serializable] #endif public partial class DeleteVoteResponse : TBase { public DeleteVoteResponse() { } public void Read (TProtocol iprot) { iprot.IncrementRecursionDepth(); try { TField field; iprot.ReadStructBegin(); while (true) { field = iprot.ReadFieldBegin(); if (field.Type == TType.Stop) { break; } switch (field.ID) { default: TProtocolUtil.Skip(iprot, field.Type); break; } iprot.ReadFieldEnd(); } iprot.ReadStructEnd(); } finally { iprot.DecrementRecursionDepth(); } } public void Write(TProtocol oprot) { oprot.IncrementRecursionDepth(); try { TStruct struc = new TStruct("DeleteVoteResponse"); oprot.WriteStructBegin(struc); oprot.WriteFieldStop(); oprot.WriteStructEnd(); } finally { oprot.DecrementRecursionDepth(); } } public override string ToString() { StringBuilder __sb = new StringBuilder("DeleteVoteResponse("); __sb.Append(")"); return __sb.ToString(); } } } #endif
20.352273
68
0.59129
[ "Apache-2.0" ]
Sohail8338/getsocial-unity-sdk
example/GetSocialSdkDemo/Assets/GetSocial/GetSocialNative/Scripts/Core/Internal/Generated/DeleteVoteResponse.cs
1,791
C#
using System.Text.RegularExpressions; namespace Microsoft.Recognizers.Text.Choice { public interface IBooleanExtractorConfiguration : IChoiceExtractorConfiguration { Regex TrueRegex { get; } Regex FalseRegex { get; } } }
21
83
0.718254
[ "MIT" ]
7i77an/Recognizers-Text
.NET/Microsoft.Recognizers.Text.Choice/Extractors/IBooleanExtractorConfiguration.cs
254
C#
namespace Splatter.AI.BehaviourTree { /// <summary> /// Node return types of the execute function. /// </summary> public enum NodeResult { /// <summary> /// The node did not meet the criteria to carry on. /// </summary> Running, /// <summary> /// The node failed. /// </summary> Failure, /// <summary> /// The node succeeded. /// </summary> Success } }
23.45
59
0.490405
[ "MIT" ]
ormesam/splatter
Assets/Splatter/Scripts/Runtime/AI/BehaviourTree/NodeResult.cs
469
C#
using System; class Program { static void Main() // 100/100 { string name = Console.ReadLine(); PrintName(name); } static void PrintName(string name) { Console.WriteLine("Hello, {0}!", name); } }
18.769231
47
0.557377
[ "MIT" ]
GabrielRezendi/Programming-Fundamentals-2017
02.Extented Fundamentals/12.ARRAYS AND METHODS - EXERCISES/01. Hello, Name!/Program.cs
246
C#
namespace GrabCaster.Framework.AzureQueueTrigger { using System; using GrabCaster.Framework.Contracts.Attributes; using GrabCaster.Framework.Contracts.Globals; using GrabCaster.Framework.Contracts.Triggers; using Microsoft.ServiceBus; using Microsoft.ServiceBus.Messaging; /// <summary> /// The azure queue trigger. /// </summary> [TriggerContract("{79F1CAB1-6E78-4BF9-8D2E-F15E87F605CA}", "Azure Queue Trigger", "Azure Queue Trigger", false, true, false)] public class AzureQueueTrigger : ITriggerType { /// <summary> /// Gets or sets the connection string. /// </summary> [TriggerPropertyContract("ConnectionString", "Azure ConnectionString")] public string ConnectionString { get; set; } /// <summary> /// Gets or sets the queue path. /// </summary> [TriggerPropertyContract("QueuePath", "QueuePath")] public string QueuePath { get; set; } /// <summary> /// Gets or sets the context. /// </summary> public EventActionContext Context { get; set; } /// <summary> /// Gets or sets the set event action trigger. /// </summary> public SetEventActionTrigger SetEventActionTrigger { get; set; } /// <summary> /// Gets or sets the data context. /// </summary> [TriggerPropertyContract("DataContext", "Trigger Default Main Data")] public byte[] DataContext { get; set; } /// <summary> /// The execute. /// </summary> /// <param name="setEventActionTrigger"> /// The set event action trigger. /// </param> /// <param name="context"> /// The context. /// </param> [TriggerActionContract("{647FE4E4-2FD0-4AF4-8FC2-B3019F0BA571}", "Main action", "Main action description")] public void Execute(SetEventActionTrigger setEventActionTrigger, EventActionContext context) { try { var namespaceManager = NamespaceManager.CreateFromConnectionString(this.ConnectionString); if (!namespaceManager.QueueExists(this.QueuePath)) { namespaceManager.CreateQueue(this.QueuePath); } var client = QueueClient.CreateFromConnectionString(this.ConnectionString, this.QueuePath); // Configure the callback options var options = new OnMessageOptions { AutoComplete = false, AutoRenewTimeout = TimeSpan.FromMinutes(1) }; // Callback to handle received messages client.OnMessage( message => { try { // Remove message from queue this.DataContext = message.GetBody<byte[]>(); message.Complete(); setEventActionTrigger(this, context); } catch (Exception) { // Indicates a problem, unlock message in queue message.Abandon(); } }, options); } catch (Exception) { // ignored } } } }
35.744898
121
0.522124
[ "MIT" ]
debiaggi/GrabCaster
SDK/Triggers/AzureQueueTrigger/AzureQueueTrigger.cs
3,505
C#
using System.Windows; using Xunit; namespace VideoScriptEditor.Geometry.Tests { public class RectExtensionsTests { [Fact] public void TopCenterTest() { Rect testRect = new Rect(10, 10, 20, 20); Point expectedTopCenter = new Point(20, 10); Assert.Equal(expectedTopCenter, testRect.TopCenter()); } } }
23.176471
66
0.583756
[ "MIT" ]
danjoconnell/VideoScriptEditor
VideoScriptEditor/VideoScriptEditor.Tests/Geometry/RectExtensionsTests.cs
396
C#
/* * ARXivar Workflow API * * ARXivar Workflow API * * OpenAPI spec version: v1 * Contact: info@abletech.it * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using IO.Swagger.Workflow.Client; using IO.Swagger.Workflow.Model; namespace IO.Swagger.Workflow.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IFormulesApi : IApiAccessor { #region Synchronous Operations /// <summary> /// This call evaluates a formula /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">Formula to evaluate</param> /// <returns>FormuleTestResultRm</returns> FormuleTestResultRm ApiV1FormulesEvaluatePost (FormuleTestRequestRm body); /// <summary> /// This call evaluates a formula /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">Formula to evaluate</param> /// <returns>ApiResponse of FormuleTestResultRm</returns> ApiResponse<FormuleTestResultRm> ApiV1FormulesEvaluatePostWithHttpInfo (FormuleTestRequestRm body); /// <summary> /// This call return the list of the profile fields of a specific class that can be used in the formula engine /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="documentTypeSystemId"></param> /// <returns>ProfileFormulaFieldRm</returns> ProfileFormulaFieldRm ApiV1FormulesFieldsProfileClassDocumentTypeSystemIdGet (int? documentTypeSystemId); /// <summary> /// This call return the list of the profile fields of a specific class that can be used in the formula engine /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="documentTypeSystemId"></param> /// <returns>ApiResponse of ProfileFormulaFieldRm</returns> ApiResponse<ProfileFormulaFieldRm> ApiV1FormulesFieldsProfileClassDocumentTypeSystemIdGetWithHttpInfo (int? documentTypeSystemId); /// <summary> /// This call return the list of the profile fields that can be used in the formula engine /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ProfileFormulaFieldRm</returns> ProfileFormulaFieldRm ApiV1FormulesFieldsProfileGet (); /// <summary> /// This call return the list of the profile fields that can be used in the formula engine /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of ProfileFormulaFieldRm</returns> ApiResponse<ProfileFormulaFieldRm> ApiV1FormulesFieldsProfileGetWithHttpInfo (); /// <summary> /// This call return the list of the profile fields that can be used in the formula engine /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ProfileFormulaFieldRm</returns> ProfileFormulaFieldRm ApiV1FormulesFieldsSystemGet (); /// <summary> /// This call return the list of the profile fields that can be used in the formula engine /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of ProfileFormulaFieldRm</returns> ApiResponse<ProfileFormulaFieldRm> ApiV1FormulesFieldsSystemGetWithHttpInfo (); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// This call evaluates a formula /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">Formula to evaluate</param> /// <returns>Task of FormuleTestResultRm</returns> System.Threading.Tasks.Task<FormuleTestResultRm> ApiV1FormulesEvaluatePostAsync (FormuleTestRequestRm body); /// <summary> /// This call evaluates a formula /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">Formula to evaluate</param> /// <returns>Task of ApiResponse (FormuleTestResultRm)</returns> System.Threading.Tasks.Task<ApiResponse<FormuleTestResultRm>> ApiV1FormulesEvaluatePostAsyncWithHttpInfo (FormuleTestRequestRm body); /// <summary> /// This call return the list of the profile fields of a specific class that can be used in the formula engine /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="documentTypeSystemId"></param> /// <returns>Task of ProfileFormulaFieldRm</returns> System.Threading.Tasks.Task<ProfileFormulaFieldRm> ApiV1FormulesFieldsProfileClassDocumentTypeSystemIdGetAsync (int? documentTypeSystemId); /// <summary> /// This call return the list of the profile fields of a specific class that can be used in the formula engine /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="documentTypeSystemId"></param> /// <returns>Task of ApiResponse (ProfileFormulaFieldRm)</returns> System.Threading.Tasks.Task<ApiResponse<ProfileFormulaFieldRm>> ApiV1FormulesFieldsProfileClassDocumentTypeSystemIdGetAsyncWithHttpInfo (int? documentTypeSystemId); /// <summary> /// This call return the list of the profile fields that can be used in the formula engine /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ProfileFormulaFieldRm</returns> System.Threading.Tasks.Task<ProfileFormulaFieldRm> ApiV1FormulesFieldsProfileGetAsync (); /// <summary> /// This call return the list of the profile fields that can be used in the formula engine /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse (ProfileFormulaFieldRm)</returns> System.Threading.Tasks.Task<ApiResponse<ProfileFormulaFieldRm>> ApiV1FormulesFieldsProfileGetAsyncWithHttpInfo (); /// <summary> /// This call return the list of the profile fields that can be used in the formula engine /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ProfileFormulaFieldRm</returns> System.Threading.Tasks.Task<ProfileFormulaFieldRm> ApiV1FormulesFieldsSystemGetAsync (); /// <summary> /// This call return the list of the profile fields that can be used in the formula engine /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse (ProfileFormulaFieldRm)</returns> System.Threading.Tasks.Task<ApiResponse<ProfileFormulaFieldRm>> ApiV1FormulesFieldsSystemGetAsyncWithHttpInfo (); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class FormulesApi : IFormulesApi { private IO.Swagger.Workflow.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="FormulesApi"/> class. /// </summary> /// <returns></returns> public FormulesApi(String basePath) { this.Configuration = new IO.Swagger.Workflow.Client.Configuration { BasePath = basePath }; ExceptionFactory = IO.Swagger.Workflow.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Initializes a new instance of the <see cref="FormulesApi"/> class /// </summary> /// <returns></returns> public FormulesApi() { this.Configuration = IO.Swagger.Workflow.Client.Configuration.Default; ExceptionFactory = IO.Swagger.Workflow.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Initializes a new instance of the <see cref="FormulesApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public FormulesApi(IO.Swagger.Workflow.Client.Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = IO.Swagger.Workflow.Client.Configuration.Default; else this.Configuration = configuration; ExceptionFactory = IO.Swagger.Workflow.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public IO.Swagger.Workflow.Client.Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public IO.Swagger.Workflow.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public IDictionary<String, String> DefaultHeader() { return new ReadOnlyDictionary<string, string>(this.Configuration.DefaultHeader); } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// This call evaluates a formula /// </summary> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">Formula to evaluate</param> /// <returns>FormuleTestResultRm</returns> public FormuleTestResultRm ApiV1FormulesEvaluatePost (FormuleTestRequestRm body) { ApiResponse<FormuleTestResultRm> localVarResponse = ApiV1FormulesEvaluatePostWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// This call evaluates a formula /// </summary> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">Formula to evaluate</param> /// <returns>ApiResponse of FormuleTestResultRm</returns> public ApiResponse< FormuleTestResultRm > ApiV1FormulesEvaluatePostWithHttpInfo (FormuleTestRequestRm body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling FormulesApi->ApiV1FormulesEvaluatePost"); var localVarPath = "/api/v1/formules/evaluate"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json-patch+json", "application/json", "text/json", "application/_*+json" }; String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "text/plain", "application/json", "text/json" }; String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = this.Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (Bearer) required if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = this.Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) this.Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ApiV1FormulesEvaluatePost", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<FormuleTestResultRm>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), (FormuleTestResultRm) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(FormuleTestResultRm))); } /// <summary> /// This call evaluates a formula /// </summary> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">Formula to evaluate</param> /// <returns>Task of FormuleTestResultRm</returns> public async System.Threading.Tasks.Task<FormuleTestResultRm> ApiV1FormulesEvaluatePostAsync (FormuleTestRequestRm body) { ApiResponse<FormuleTestResultRm> localVarResponse = await ApiV1FormulesEvaluatePostAsyncWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// This call evaluates a formula /// </summary> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">Formula to evaluate</param> /// <returns>Task of ApiResponse (FormuleTestResultRm)</returns> public async System.Threading.Tasks.Task<ApiResponse<FormuleTestResultRm>> ApiV1FormulesEvaluatePostAsyncWithHttpInfo (FormuleTestRequestRm body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling FormulesApi->ApiV1FormulesEvaluatePost"); var localVarPath = "/api/v1/formules/evaluate"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json-patch+json", "application/json", "text/json", "application/_*+json" }; String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "text/plain", "application/json", "text/json" }; String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = this.Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (Bearer) required if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = this.Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await this.Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ApiV1FormulesEvaluatePost", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<FormuleTestResultRm>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), (FormuleTestResultRm) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(FormuleTestResultRm))); } /// <summary> /// This call return the list of the profile fields of a specific class that can be used in the formula engine /// </summary> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="documentTypeSystemId"></param> /// <returns>ProfileFormulaFieldRm</returns> public ProfileFormulaFieldRm ApiV1FormulesFieldsProfileClassDocumentTypeSystemIdGet (int? documentTypeSystemId) { ApiResponse<ProfileFormulaFieldRm> localVarResponse = ApiV1FormulesFieldsProfileClassDocumentTypeSystemIdGetWithHttpInfo(documentTypeSystemId); return localVarResponse.Data; } /// <summary> /// This call return the list of the profile fields of a specific class that can be used in the formula engine /// </summary> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="documentTypeSystemId"></param> /// <returns>ApiResponse of ProfileFormulaFieldRm</returns> public ApiResponse< ProfileFormulaFieldRm > ApiV1FormulesFieldsProfileClassDocumentTypeSystemIdGetWithHttpInfo (int? documentTypeSystemId) { // verify the required parameter 'documentTypeSystemId' is set if (documentTypeSystemId == null) throw new ApiException(400, "Missing required parameter 'documentTypeSystemId' when calling FormulesApi->ApiV1FormulesFieldsProfileClassDocumentTypeSystemIdGet"); var localVarPath = "/api/v1/formules/fields/profile/class/{documentTypeSystemId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "text/plain", "application/json", "text/json" }; String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); if (documentTypeSystemId != null) localVarPathParams.Add("documentTypeSystemId", this.Configuration.ApiClient.ParameterToString(documentTypeSystemId)); // path parameter // authentication (Bearer) required if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = this.Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) this.Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ApiV1FormulesFieldsProfileClassDocumentTypeSystemIdGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProfileFormulaFieldRm>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), (ProfileFormulaFieldRm) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProfileFormulaFieldRm))); } /// <summary> /// This call return the list of the profile fields of a specific class that can be used in the formula engine /// </summary> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="documentTypeSystemId"></param> /// <returns>Task of ProfileFormulaFieldRm</returns> public async System.Threading.Tasks.Task<ProfileFormulaFieldRm> ApiV1FormulesFieldsProfileClassDocumentTypeSystemIdGetAsync (int? documentTypeSystemId) { ApiResponse<ProfileFormulaFieldRm> localVarResponse = await ApiV1FormulesFieldsProfileClassDocumentTypeSystemIdGetAsyncWithHttpInfo(documentTypeSystemId); return localVarResponse.Data; } /// <summary> /// This call return the list of the profile fields of a specific class that can be used in the formula engine /// </summary> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="documentTypeSystemId"></param> /// <returns>Task of ApiResponse (ProfileFormulaFieldRm)</returns> public async System.Threading.Tasks.Task<ApiResponse<ProfileFormulaFieldRm>> ApiV1FormulesFieldsProfileClassDocumentTypeSystemIdGetAsyncWithHttpInfo (int? documentTypeSystemId) { // verify the required parameter 'documentTypeSystemId' is set if (documentTypeSystemId == null) throw new ApiException(400, "Missing required parameter 'documentTypeSystemId' when calling FormulesApi->ApiV1FormulesFieldsProfileClassDocumentTypeSystemIdGet"); var localVarPath = "/api/v1/formules/fields/profile/class/{documentTypeSystemId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "text/plain", "application/json", "text/json" }; String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); if (documentTypeSystemId != null) localVarPathParams.Add("documentTypeSystemId", this.Configuration.ApiClient.ParameterToString(documentTypeSystemId)); // path parameter // authentication (Bearer) required if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = this.Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await this.Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ApiV1FormulesFieldsProfileClassDocumentTypeSystemIdGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProfileFormulaFieldRm>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), (ProfileFormulaFieldRm) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProfileFormulaFieldRm))); } /// <summary> /// This call return the list of the profile fields that can be used in the formula engine /// </summary> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ProfileFormulaFieldRm</returns> public ProfileFormulaFieldRm ApiV1FormulesFieldsProfileGet () { ApiResponse<ProfileFormulaFieldRm> localVarResponse = ApiV1FormulesFieldsProfileGetWithHttpInfo(); return localVarResponse.Data; } /// <summary> /// This call return the list of the profile fields that can be used in the formula engine /// </summary> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of ProfileFormulaFieldRm</returns> public ApiResponse< ProfileFormulaFieldRm > ApiV1FormulesFieldsProfileGetWithHttpInfo () { var localVarPath = "/api/v1/formules/fields/profile"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "text/plain", "application/json", "text/json" }; String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = this.Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) this.Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ApiV1FormulesFieldsProfileGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProfileFormulaFieldRm>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), (ProfileFormulaFieldRm) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProfileFormulaFieldRm))); } /// <summary> /// This call return the list of the profile fields that can be used in the formula engine /// </summary> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ProfileFormulaFieldRm</returns> public async System.Threading.Tasks.Task<ProfileFormulaFieldRm> ApiV1FormulesFieldsProfileGetAsync () { ApiResponse<ProfileFormulaFieldRm> localVarResponse = await ApiV1FormulesFieldsProfileGetAsyncWithHttpInfo(); return localVarResponse.Data; } /// <summary> /// This call return the list of the profile fields that can be used in the formula engine /// </summary> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse (ProfileFormulaFieldRm)</returns> public async System.Threading.Tasks.Task<ApiResponse<ProfileFormulaFieldRm>> ApiV1FormulesFieldsProfileGetAsyncWithHttpInfo () { var localVarPath = "/api/v1/formules/fields/profile"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "text/plain", "application/json", "text/json" }; String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = this.Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await this.Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ApiV1FormulesFieldsProfileGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProfileFormulaFieldRm>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), (ProfileFormulaFieldRm) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProfileFormulaFieldRm))); } /// <summary> /// This call return the list of the profile fields that can be used in the formula engine /// </summary> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ProfileFormulaFieldRm</returns> public ProfileFormulaFieldRm ApiV1FormulesFieldsSystemGet () { ApiResponse<ProfileFormulaFieldRm> localVarResponse = ApiV1FormulesFieldsSystemGetWithHttpInfo(); return localVarResponse.Data; } /// <summary> /// This call return the list of the profile fields that can be used in the formula engine /// </summary> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of ProfileFormulaFieldRm</returns> public ApiResponse< ProfileFormulaFieldRm > ApiV1FormulesFieldsSystemGetWithHttpInfo () { var localVarPath = "/api/v1/formules/fields/system"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "text/plain", "application/json", "text/json" }; String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = this.Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) this.Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ApiV1FormulesFieldsSystemGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProfileFormulaFieldRm>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), (ProfileFormulaFieldRm) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProfileFormulaFieldRm))); } /// <summary> /// This call return the list of the profile fields that can be used in the formula engine /// </summary> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ProfileFormulaFieldRm</returns> public async System.Threading.Tasks.Task<ProfileFormulaFieldRm> ApiV1FormulesFieldsSystemGetAsync () { ApiResponse<ProfileFormulaFieldRm> localVarResponse = await ApiV1FormulesFieldsSystemGetAsyncWithHttpInfo(); return localVarResponse.Data; } /// <summary> /// This call return the list of the profile fields that can be used in the formula engine /// </summary> /// <exception cref="IO.Swagger.Workflow.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse (ProfileFormulaFieldRm)</returns> public async System.Threading.Tasks.Task<ApiResponse<ProfileFormulaFieldRm>> ApiV1FormulesFieldsSystemGetAsyncWithHttpInfo () { var localVarPath = "/api/v1/formules/fields/system"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "text/plain", "application/json", "text/json" }; String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = this.Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await this.Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ApiV1FormulesFieldsSystemGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProfileFormulaFieldRm>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), (ProfileFormulaFieldRm) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProfileFormulaFieldRm))); } } }
50.789534
184
0.649023
[ "Apache-2.0" ]
zanardini/ARXivarNext-WebApi
ARXivarNext-ConsumingWebApi/IO.Swagger.Workflow/Api/FormulesApi.cs
44,644
C#
// *********************************************************************** // Assembly : Microsoft.Legal.MatterCenter.Utility // Author : v-lapedd // Created : 04-07-2016 // // *********************************************************************** // <copyright file="IDocumentRepository.cs" company="Microsoft"> // Copyright (c) . All rights reserved. // </copyright> // This interface contains all the document related functionalities // *********************************************************************** using Microsoft.SharePoint.Client; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; #region Matter Related Namespaces using Microsoft.Legal.MatterCenter.Models; using Microsoft.AspNetCore.Http; #endregion namespace Microsoft.Legal.MatterCenter.Repository { /// <summary> /// Interface matter repository contains all document related methods such as finding document, pin, unpin, document etc /// </summary> public interface IDocumentRepository:ICommonRepository { Task<SearchResponseVM> GetDocumentsAsync(SearchRequestVM searchRequestVM); Task<dynamic> GetDocumentAndClientGUIDAsync(Client client); void SetUploadItemProperties(ClientContext clientContext, string documentLibraryName, string fileName, string folderPath, Dictionary<string, string> mailProperties); void CreateFileInsideFolder(ClientContext clientContext, string folderPath, FileCreationInformation newFile); bool FolderExists(string folderPath, ClientContext clientContext, string documentLibraryName); bool PerformContentCheck(ClientContext context, MemoryStream localMemoryStream, string serverFileURL); DuplicateDocument DocumentExists(ClientContext clientContext, ContentCheckDetails contentCheck, string documentLibraryName, string folderPath, bool isMail); GenericResponseVM UploadDocument(string folderName, IFormFile uploadedFile, string fileName, Dictionary<string, string> mailProperties, string clientUrl, string folder, string documentLibraryName); Stream DownloadAttachments(string attachmentUrl); } }
49.590909
205
0.691109
[ "MIT" ]
atjohns2/BCBSNCMatterCenter
tree/master/cloud/src/solution/Microsoft.Legal.MatterCenter.Service/Microsoft.Legal.MatterCenter.Repository/Document/IDocumentRepository.cs
2,184
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using rzeczuchyTasks.ViewModel; namespace rzeczuchyTasks.Model { public class ToDo : INotifyPropertyChanged { public const int MaxNameLength = 50; private string label; private bool isChecked; private readonly MainViewModel parent; public ToDo(int id, string label, bool isChecked, MainViewModel parent) { this.parent = parent; Id = id; this.label = label.Length > MaxNameLength ? label.Substring(0, MaxNameLength) : label; this.isChecked = isChecked; } public int Id { get; } public string Label { get { return label; } set { label = value; OnPropertyChanged("Label"); parent.SaveToDos(); } } public bool IsChecked { get { return isChecked; } set { isChecked = value; OnPropertyChanged("IsChecked"); parent.SaveToDos(); } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
25.534483
98
0.562458
[ "MIT" ]
rzeczuchy/rzeczuchyTasks
rzeczuchyTasks/Model/ToDo.cs
1,483
C#
/* Copyright 2010-2014 MongoDB Inc. * * 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 MongoDB.Bson; using NUnit.Framework; namespace MongoDB.Bson.Tests.Jira.CSharp260 { [TestFixture] public class CSharp260Tests { [Test] public void TestConstantPattern() { var json = "{ rx : /abc/ }"; var document = BsonDocument.Parse(json); Assert.AreEqual(BsonType.RegularExpression, document["rx"].BsonType); var rx = document["rx"].AsBsonRegularExpression; Assert.AreEqual("abc", rx.Pattern); Assert.AreEqual("", rx.Options); } [Test] public void TestConstantPatternWithOptions() { var json = "{ rx : /abc/imxs }"; var document = BsonDocument.Parse(json); Assert.AreEqual(BsonType.RegularExpression, document["rx"].BsonType); var rx = document["rx"].AsBsonRegularExpression; Assert.AreEqual("abc", rx.Pattern); Assert.AreEqual("imxs", rx.Options); } [Test] public void TestNewRegExpPattern() { var json = "{ rx : new RegExp('abc') }"; var document = BsonDocument.Parse(json); Assert.AreEqual(BsonType.RegularExpression, document["rx"].BsonType); var rx = document["rx"].AsBsonRegularExpression; Assert.AreEqual("abc", rx.Pattern); Assert.AreEqual("", rx.Options); } [Test] public void TestNewRegExpPatternWithOptions() { var json = "{ rx : new RegExp('abc', 'imxs') }"; var document = BsonDocument.Parse(json); Assert.AreEqual(BsonType.RegularExpression, document["rx"].BsonType); var rx = document["rx"].AsBsonRegularExpression; Assert.AreEqual("abc", rx.Pattern); Assert.AreEqual("imxs", rx.Options); } [Test] public void TestRegExpPattern() { var json = "{ rx : RegExp('abc') }"; var document = BsonDocument.Parse(json); Assert.AreEqual(BsonType.RegularExpression, document["rx"].BsonType); var rx = document["rx"].AsBsonRegularExpression; Assert.AreEqual("abc", rx.Pattern); Assert.AreEqual("", rx.Options); } [Test] public void TestRegExpPatternWithOptions() { var json = "{ rx : RegExp('abc', 'imxs') }"; var document = BsonDocument.Parse(json); Assert.AreEqual(BsonType.RegularExpression, document["rx"].BsonType); var rx = document["rx"].AsBsonRegularExpression; Assert.AreEqual("abc", rx.Pattern); Assert.AreEqual("imxs", rx.Options); } [Test] public void TestStrictPattern() { var json = "{ rx : { $regex : 'abc' } }"; var document = BsonDocument.Parse(json); Assert.AreEqual(BsonType.RegularExpression, document["rx"].BsonType); var rx = document["rx"].AsBsonRegularExpression; Assert.AreEqual("abc", rx.Pattern); Assert.AreEqual("", rx.Options); } [Test] public void TestStrictPatternWithOptions() { var json = "{ rx : { $regex : 'abc', $options : 'imxs' } }"; var document = BsonDocument.Parse(json); Assert.AreEqual(BsonType.RegularExpression, document["rx"].BsonType); var rx = document["rx"].AsBsonRegularExpression; Assert.AreEqual("abc", rx.Pattern); Assert.AreEqual("imxs", rx.Options); } } }
36.80531
81
0.585958
[ "Apache-2.0" ]
InternationNova/MEANJS
src/MongoDB.Bson.Tests/Jira/CSharp260Tests.cs
4,161
C#
namespace CraluTweaks.Config { class CraluTweaksConfig { public bool AdjustWithRightClickEnabled = false; public bool CarryableBunchOCandlesEnabled = true; public bool CarryableChandelierEnabled = true; public bool CarryableFlowerpotEnabled = true; public bool CarryableForgeEnabled = true; public bool CarryableLogWithResinEnabled = false; public bool CarryableMoldrackEnabled = true; public bool CarryableMoldsEnabled = true; public bool CarryableOvenEnabled = true; public bool CarryableShelfEnabled = true; public bool CarryableToolrackEnabled = true; public bool CarryableTorchholderEnabled = true; public bool Compost2xEnabled = true; public bool DropWallpapersEnabled = true; public bool InfiniteTraderMoneyEnabled = true; public bool LazyKnappingClayformingEnabled = false; public bool PickUpBonesEnabled = true; public bool PlacePieOnShelfEnabled = true; public bool PlacePotOnShelfEnabled = true; public bool RackableFirestarterEnabled = true; public bool ScrapRecipesEnabled = true; public bool UsePlanksInPitKilnEnabled = true; public bool VisuallyGlowingArrowsAndSpearsEnabled = false; public CraluTweaksConfig() { } public CraluTweaksConfig(CraluTweaksConfig previousConfig) { AdjustWithRightClickEnabled = previousConfig.AdjustWithRightClickEnabled; CarryableBunchOCandlesEnabled = previousConfig.CarryableBunchOCandlesEnabled; CarryableChandelierEnabled = previousConfig.CarryableChandelierEnabled; CarryableFlowerpotEnabled = previousConfig.CarryableFlowerpotEnabled; CarryableForgeEnabled = previousConfig.CarryableForgeEnabled; CarryableLogWithResinEnabled = previousConfig.CarryableLogWithResinEnabled; CarryableMoldrackEnabled = previousConfig.CarryableMoldrackEnabled; CarryableMoldsEnabled = previousConfig.CarryableMoldsEnabled; CarryableOvenEnabled = previousConfig.CarryableOvenEnabled; CarryableShelfEnabled = previousConfig.CarryableShelfEnabled; CarryableToolrackEnabled = previousConfig.CarryableToolrackEnabled; CarryableTorchholderEnabled = previousConfig.CarryableTorchholderEnabled; Compost2xEnabled = previousConfig.Compost2xEnabled; DropWallpapersEnabled = previousConfig.DropWallpapersEnabled; InfiniteTraderMoneyEnabled = previousConfig.InfiniteTraderMoneyEnabled; LazyKnappingClayformingEnabled = previousConfig.LazyKnappingClayformingEnabled; PickUpBonesEnabled = previousConfig.PickUpBonesEnabled; PlacePieOnShelfEnabled = previousConfig.PlacePieOnShelfEnabled; PlacePotOnShelfEnabled = previousConfig.PlacePotOnShelfEnabled; RackableFirestarterEnabled = previousConfig.RackableFirestarterEnabled; ScrapRecipesEnabled = previousConfig.ScrapRecipesEnabled; UsePlanksInPitKilnEnabled = previousConfig.UsePlanksInPitKilnEnabled; VisuallyGlowingArrowsAndSpearsEnabled = previousConfig.VisuallyGlowingArrowsAndSpearsEnabled; } } }
50.466667
99
0.805152
[ "MIT" ]
Craluminum2413/CraluTweaks
src/CraluTweaksConfig.cs
3,028
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Net; using System.Net.Http; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Owin; using Xunit; using Xunit.Extensions; namespace Microsoft.Owin.Host.IntegrationTests { public class ClientCertificateTests : TestBase { private const HttpStatusCode CertFound = HttpStatusCode.Accepted; private const HttpStatusCode CertNotFound = HttpStatusCode.NotFound; private const HttpStatusCode CertFoundWithErrors = HttpStatusCode.ExpectationFailed; public void DontAccessCertificate(IAppBuilder app) { app.Run(context => { context.Response.StatusCode = (int)CertNotFound; return Task.FromResult(0); }); } public void CheckClientCertificate(IAppBuilder app) { app.Run(async context => { var certLoader = context.Get<Func<Task>>("ssl.LoadClientCertAsync"); if (certLoader != null) { await certLoader(); var asyncCert = context.Get<X509Certificate>("ssl.ClientCertificate"); var asyncCertError = context.Get<Exception>("ssl.ClientCertificateErrors"); context.Response.StatusCode = asyncCert == null ? (int)CertNotFound : asyncCertError == null ? (int)CertFound : (int)CertFoundWithErrors; } else { var syncCert = context.Get<X509Certificate>("ssl.ClientCertificate"); var syncCertError = context.Get<Exception>("ssl.ClientCertificateErrors"); context.Response.StatusCode = syncCert == null ? (int)CertNotFound : syncCertError == null ? (int)CertFound : (int)CertFoundWithErrors; } }); } [Theory, Trait("scheme", "https")] [InlineData("Microsoft.Owin.Host.SystemWeb")] [InlineData("Microsoft.Owin.Host.HttpListener")] public async Task NoCertProvided_DontAccessCertificate_Success(string serverName) { ServicePointManager.ServerCertificateValidationCallback = AcceptAllCerts; int port = RunWebServer( serverName, DontAccessCertificate, https: true); var client = new HttpClient(); client.Timeout = TimeSpan.FromSeconds(5); try { var response = await client.GetAsync("https://localhost:" + port); Assert.Equal(CertNotFound, response.StatusCode); } finally { ServicePointManager.ServerCertificateValidationCallback = null; } } [Theory, Trait("scheme", "https")] [InlineData("Microsoft.Owin.Host.SystemWeb")] [InlineData("Microsoft.Owin.Host.HttpListener")] public async Task NoCertProvided_CheckClientCertificate_Success(string serverName) { ServicePointManager.ServerCertificateValidationCallback = AcceptAllCerts; int port = RunWebServer( serverName, CheckClientCertificate, https: true); var client = new HttpClient(); client.Timeout = TimeSpan.FromSeconds(5); try { var response = await client.GetAsync("https://localhost:" + port); Assert.Equal(CertNotFound, response.StatusCode); } finally { ServicePointManager.ServerCertificateValidationCallback = null; } } [Theory, Trait("scheme", "https")] [InlineData("Microsoft.Owin.Host.SystemWeb")] [InlineData("Microsoft.Owin.Host.HttpListener")] public async Task ValidCertProvided_DontAccessCertificate_Success(string serverName) { ServicePointManager.ServerCertificateValidationCallback = AcceptAllCerts; int port = RunWebServer( serverName, DontAccessCertificate, https: true); X509Certificate2 clientCert = FindClientCert(); Assert.NotNull(clientCert); var handler = new WebRequestHandler(); handler.ClientCertificates.Add(clientCert); var client = new HttpClient(handler); client.Timeout = TimeSpan.FromSeconds(5); try { var response = await client.GetAsync("https://localhost:" + port); Assert.Equal(CertNotFound, response.StatusCode); } finally { ServicePointManager.ServerCertificateValidationCallback = null; } } // IIS needs this section in applicationhost.config: // <system.webServer><security><access sslFlags="SslNegotiateCert" />... // http://www.iis.net/configreference/system.webserver/security/access [Theory, Trait("scheme", "https")] [InlineData("Microsoft.Owin.Host.SystemWeb")] [InlineData("Microsoft.Owin.Host.HttpListener")] public async Task ValidCertProvided_CheckClientCertificate_Success(string serverName) { ServicePointManager.ServerCertificateValidationCallback = AcceptAllCerts; int port = RunWebServer( serverName, CheckClientCertificate, https: true); X509Certificate2 clientCert = FindClientCert(); Assert.NotNull(clientCert); var handler = new WebRequestHandler(); handler.ClientCertificates.Add(clientCert); var client = new HttpClient(handler); client.Timeout = TimeSpan.FromSeconds(5); try { var response = await client.GetAsync("https://localhost:" + port); Assert.Equal(CertFound, response.StatusCode); } finally { ServicePointManager.ServerCertificateValidationCallback = null; } } [Theory, Trait("scheme", "https")] [InlineData("Microsoft.Owin.Host.SystemWeb", HttpStatusCode.Forbidden)] [InlineData("Microsoft.Owin.Host.HttpListener", CertNotFound)] public async Task SelfSignedCertProvided_DontAccessCertificate_Success(string serverName, HttpStatusCode expectedResult) { ServicePointManager.ServerCertificateValidationCallback = AcceptAllCerts; int port = RunWebServer( serverName, DontAccessCertificate, https: true); var handler = new WebRequestHandler(); handler.ClientCertificates.Add(new X509Certificate2(@"SelfSignedClientCert.pfx", "katana")); var client = new HttpClient(handler); client.Timeout = TimeSpan.FromSeconds(5); try { var response = await client.GetAsync("https://localhost:" + port); Assert.Equal(expectedResult, response.StatusCode); } finally { ServicePointManager.ServerCertificateValidationCallback = null; } } [Theory, Trait("scheme", "https")] [InlineData("Microsoft.Owin.Host.SystemWeb", HttpStatusCode.Forbidden)] [InlineData("Microsoft.Owin.Host.HttpListener", CertFoundWithErrors)] public async Task SelfSignedCertProvided_CheckClientCertificate_Success(string serverName, HttpStatusCode expectedResult) { ServicePointManager.ServerCertificateValidationCallback = AcceptAllCerts; int port = RunWebServer( serverName, CheckClientCertificate, https: true); var handler = new WebRequestHandler(); handler.ClientCertificates.Add(new X509Certificate2(@"SelfSignedClientCert.pfx", "katana")); var client = new HttpClient(handler); client.Timeout = TimeSpan.FromSeconds(5); try { var response = await client.GetAsync("https://localhost:" + port); Assert.Equal(expectedResult, response.StatusCode); } finally { ServicePointManager.ServerCertificateValidationCallback = null; } } private bool AcceptAllCerts(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; } private X509Certificate2 FindClientCert() { var store = new X509Store(); store.Open(OpenFlags.ReadOnly); foreach (var cert in store.Certificates) { bool isClientAuth = false; bool isSmartCard = false; foreach (var extension in cert.Extensions) { var eku = extension as X509EnhancedKeyUsageExtension; if (eku != null) { foreach (var oid in eku.EnhancedKeyUsages) { if (oid.FriendlyName == "Client Authentication") { isClientAuth = true; } else if (oid.FriendlyName == "Smart Card Logon") { isSmartCard = true; break; } } } } if (isClientAuth && !isSmartCard && cert.Verify()) { return cert; } } return null; } } }
38.763359
129
0.565085
[ "Apache-2.0" ]
Bouke/AspNetKatana
tests/Microsoft.Owin.Host.IntegrationTests/ClientCertificateTests.cs
10,158
C#
namespace Scorpio.Compile.CodeDom { //成员类型 a.b["c"].d[1] public abstract class CodeMember : CodeObject { public CodeObject Parent; //父级 public int index; //索引 public string key; //字符串 public CodeObject codeKey; //变量 public bool nullTo = false; ///?. 获取变量 public CodeMember(int line) : base(line) { } } //根据索引获取变量 public class CodeMemberIndex : CodeMember { public CodeMemberIndex(int index, int line) : base(line) { this.index = index; } public CodeMemberIndex(int index, CodeObject parent, int line) : base(line) { this.index = index; this.Parent = parent; } } //根据索引获取变量 public class CodeMemberInternal : CodeMember { public CodeMemberInternal(int index, int line) : base(line) { this.index = index; } } //根据字符串获取变量 public class CodeMemberString : CodeMember { public CodeMemberString(string key, int line) : base(line) { this.key = key; } public CodeMemberString(string key, CodeObject parent, int line) : base(line) { this.key = key; this.Parent = parent; } } public class CodeMemberObject : CodeMember { public CodeMemberObject(CodeObject obj, CodeObject parent, int line) : base(line) { this.codeKey = obj; this.Parent = parent; } } }
33.909091
91
0.563003
[ "MIT" ]
qq576067421/Scorpio-CSharpForCSHotfix
Scorpio-CSharp-2.0/Scorpio/src/Compile/CodeDom/CodeMember.cs
1,576
C#
namespace egami { partial class ImageForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.pictureBox = new System.Windows.Forms.PictureBox(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); this.SuspendLayout(); // // pictureBox // this.pictureBox.Cursor = System.Windows.Forms.Cursors.Cross; this.pictureBox.Location = new System.Drawing.Point(0, 2); this.pictureBox.Name = "pictureBox"; this.pictureBox.Size = new System.Drawing.Size(135, 134); this.pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBox.TabIndex = 0; this.pictureBox.TabStop = false; this.pictureBox.Click += new System.EventHandler(this.pictureBox_Click); // // ImageForm // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScroll = true; this.ClientSize = new System.Drawing.Size(584, 361); this.Controls.Add(this.pictureBox); this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Name = "ImageForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "image-path"; this.Load += new System.EventHandler(this.ImageForm_Load); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion internal System.Windows.Forms.PictureBox pictureBox; } }
38.3
146
0.588959
[ "Unlicense" ]
umstek/egami
egami/ImageForm.Designer.cs
2,683
C#
namespace Componentes { partial class F_ComboBox { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.cb_transportes = new System.Windows.Forms.ComboBox(); this.btn_mostrarSelecionado = new System.Windows.Forms.Button(); this.btn_limparElemento = new System.Windows.Forms.Button(); this.btn_resetarElemento = new System.Windows.Forms.Button(); this.tb_transporte = new System.Windows.Forms.TextBox(); this.btn_addNovoTransporte = new System.Windows.Forms.Button(); this.SuspendLayout(); // // cb_transportes // this.cb_transportes.FormattingEnabled = true; this.cb_transportes.Items.AddRange(new object[] { "Carro", "Avião", "Navio", "Ônibus", "Trem"}); this.cb_transportes.Location = new System.Drawing.Point(12, 12); this.cb_transportes.Name = "cb_transportes"; this.cb_transportes.Size = new System.Drawing.Size(144, 21); this.cb_transportes.TabIndex = 0; this.cb_transportes.SelectedIndexChanged += new System.EventHandler(this.cb_transportes_SelectedIndexChanged); // // btn_mostrarSelecionado // this.btn_mostrarSelecionado.Location = new System.Drawing.Point(162, 12); this.btn_mostrarSelecionado.Name = "btn_mostrarSelecionado"; this.btn_mostrarSelecionado.Size = new System.Drawing.Size(210, 23); this.btn_mostrarSelecionado.TabIndex = 1; this.btn_mostrarSelecionado.Text = "Mostrar Selecionado"; this.btn_mostrarSelecionado.UseVisualStyleBackColor = true; this.btn_mostrarSelecionado.Click += new System.EventHandler(this.btn_mostrarSelecionado_Click); // // btn_limparElemento // this.btn_limparElemento.Location = new System.Drawing.Point(162, 42); this.btn_limparElemento.Name = "btn_limparElemento"; this.btn_limparElemento.Size = new System.Drawing.Size(210, 23); this.btn_limparElemento.TabIndex = 2; this.btn_limparElemento.Text = "Limpar Elementos"; this.btn_limparElemento.UseVisualStyleBackColor = true; this.btn_limparElemento.Click += new System.EventHandler(this.btn_limparElemento_Click); // // btn_resetarElemento // this.btn_resetarElemento.Location = new System.Drawing.Point(162, 72); this.btn_resetarElemento.Name = "btn_resetarElemento"; this.btn_resetarElemento.Size = new System.Drawing.Size(210, 23); this.btn_resetarElemento.TabIndex = 3; this.btn_resetarElemento.Text = "Resetar Elementos"; this.btn_resetarElemento.UseVisualStyleBackColor = true; this.btn_resetarElemento.Click += new System.EventHandler(this.btn_resetarElemento_Click); // // tb_transporte // this.tb_transporte.Location = new System.Drawing.Point(162, 113); this.tb_transporte.Name = "tb_transporte"; this.tb_transporte.Size = new System.Drawing.Size(208, 20); this.tb_transporte.TabIndex = 4; // // btn_addNovoTransporte // this.btn_addNovoTransporte.Location = new System.Drawing.Point(162, 140); this.btn_addNovoTransporte.Name = "btn_addNovoTransporte"; this.btn_addNovoTransporte.Size = new System.Drawing.Size(208, 23); this.btn_addNovoTransporte.TabIndex = 5; this.btn_addNovoTransporte.Text = "Adicionar Novo Transporte"; this.btn_addNovoTransporte.UseVisualStyleBackColor = true; this.btn_addNovoTransporte.Click += new System.EventHandler(this.btn_addNovoTransporte_Click); // // F_ComboBox // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(382, 367); this.Controls.Add(this.btn_addNovoTransporte); this.Controls.Add(this.tb_transporte); this.Controls.Add(this.btn_resetarElemento); this.Controls.Add(this.btn_limparElemento); this.Controls.Add(this.btn_mostrarSelecionado); this.Controls.Add(this.cb_transportes); this.Name = "F_ComboBox"; this.Text = "F_ComboBox"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ComboBox cb_transportes; private System.Windows.Forms.Button btn_mostrarSelecionado; private System.Windows.Forms.Button btn_limparElemento; private System.Windows.Forms.Button btn_resetarElemento; private System.Windows.Forms.TextBox tb_transporte; private System.Windows.Forms.Button btn_addNovoTransporte; } }
46.367188
122
0.620893
[ "MIT" ]
danhpaiva/cfb-csharp-2020
parte02/componentes/Componentes/forms/F_ComboBox.Designer.cs
5,939
C#
using Microsoft.Bot.Builder.FormFlow; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BneDev.TimesheetNinja.Bot.Builder.Forms { [Serializable] public class AddTime { [Template(TemplateUsage.Feedback, new[] { "OK GOT IT" })] [Template(TemplateUsage.NotUnderstood, new[] { "Sorry. I don't recognise that project.", "I need a valid project to assign your time to. If you didn't mean to assign time, type _back_ at anytime" })] public String Project { get; set; } public DateTime? From { get; set; } public DateTime? To { get; set; } public double? Hours { get; set; } // Default 8 } }
30.347826
207
0.664756
[ "MIT" ]
kierenh/TimesheetNinjaBot
TimesheetNinjaBot/BneDev.TimesheetNinja.Bot.Builder/Forms/AddTime.cs
700
C#
using System; namespace Dibware.Template.Core.Domain.Exceptions { /// <summary> /// Encapsualtes validation exception information /// </summary> public class ValidationException : ApplicationException { #region Construct /// <summary> /// Initializes a new instance of the <see cref="ValidationException"/> class. /// </summary> public ValidationException() : base() { } /// <summary> /// Initializes a new instance of the <see cref="ValidationException"/> class. /// </summary> /// <param name="message">A message that describes the error.</param> public ValidationException(String message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="ValidationException"/> class. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception. If the <paramref name="innerException" /> parameter is not a null reference, the current exception is raised in a catch block that handles the inner exception.</param> public ValidationException(String message, Exception innerException) : base(message, innerException) { } #endregion } }
42.5
266
0.655882
[ "MIT" ]
dibley1973/Dibware.Template.Presentation.Web
Dibware.Template.Core.Domain/Exceptions/ValidationException.cs
1,362
C#
using System; using System.Collections.Generic; using System.Net.Http.Headers; using KeyPayV2.Nz.Models.Common; using Newtonsoft.Json.Converters; using Newtonsoft.Json; using KeyPayV2.Nz.Enums; namespace KeyPayV2.Nz.Models.Ess { public class EssWorkTypeModel { public bool IsUnitBasedWorkType { get; set; } public string UnitType { get; set; } public int Id { get; set; } public string Name { get; set; } public int? PayCategoryId { get; set; } public int? LeaveCategoryId { get; set; } public string ExternalId { get; set; } public string Source { get; set; } public bool AccruesLeave { get; set; } public IList<EmploymentTypeEnum> EmploymentTypes { get; set; } [JsonConverter(typeof(StringEnumConverter))] public WorkTypeMappingType? MappingType { get; set; } public string ShortCode { get; set; } public int? AwardPackageId { get; set; } public string AwardPackageName { get; set; } } }
35.066667
71
0.639734
[ "MIT" ]
KeyPay/keypay-dotnet-v2
src/keypay-dotnet/Nz/Models/Ess/EssWorkTypeModel.cs
1,052
C#
//------------------------------------------------------------------------------ // <auto-generated> // Ten kod został wygenerowany przez narzędzie. // Wersja wykonawcza:4.0.30319.42000 // // Zmiany w tym pliku mogą spowodować nieprawidłowe zachowanie i zostaną utracone, jeśli // kod zostanie ponownie wygenerowany. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("aplikacja4")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("aplikacja4")] [assembly: System.Reflection.AssemblyTitleAttribute("aplikacja4")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Wygenerowane przez klasę WriteCodeFragment programu MSBuild.
43.875
93
0.650522
[ "MIT" ]
LOpuchlik/pjatk
APBD/cw7/aplikacja7/obj/Debug/netcoreapp3.1/aplikacja4.AssemblyInfo.cs
1,061
C#