content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Drawing; namespace DamageMeter.D3D9Render.Overlays { public class TextLabel : Overlay { public override bool Visible { get => base.Visible; set { if (base.Visible==value) return; DxOverlay.TextSetShown(Id, value); base.Visible = value; } } private string _text; public string Text { get => _text; set { if (_text==value)return; DxOverlay.TextSetStringUnicode(Id, value); _text = value; } } private bool _shadow; public bool Shadow { get => _shadow; set { DxOverlay.TextSetShadow(Id, value); _shadow = value; } } private Color _color; public Color Color { get => _color; set { DxOverlay.TextSetColor(Id, (uint)value.ToArgb()); _color = value; } } private Point _position; public Point Position { get => _position; set { DxOverlay.TextSetPos(Id, value.X, value.Y); _position = value; } } public TextLabel(string font, int size, TypeFace type, Point position, Color color, string text, bool shadow, bool show) { Id = DxOverlay.TextCreateUnicode(font, size, type.HasFlag(TypeFace.Bold), type.HasFlag(TypeFace.Italic), position.X, position.Y, (uint)color.ToArgb(), text, shadow, show); //_font = font; //_size = size; //_type = type; _text = text; _shadow = shadow; base.Visible = show; _color = color; _position = position; } public override void Destroy() { DxOverlay.TextDestroy(Id); base.Destroy(); } public void TextUpdate(string font, int size, bool bold, bool italic) { DxOverlay.TextUpdateUnicode(Id, font, size, bold, italic); } } }
25.806818
183
0.468516
[ "MIT" ]
tmopcode/ShinraMeter_beta_kr
DamageMeter.D3D9Render/Overlays/TextLabel.cs
2,273
C#
namespace LikeComparison.DatabaseTests { using Dapper; using LikeComparison.TransactSql; using Microsoft.Data.SqlClient; public partial class LikeTransactSqlTests { [DataTestMethod] [DataRow(null, "/")] [DataRow("a%", null)] [ExpectedException(typeof(ArgumentNullException))] public void LikeTransactSqlRegexWithEscapeThrowArgumentNullException(string pattern, string escape) { var regex = LikeTransactSql.LikeRegex(pattern, escape); Assert.IsNotNull(regex); } [DataTestMethod] [DataRow("abcdef", null, "/")] [DataRow("abcdef", "a%", null)] [ExpectedException(typeof(ArgumentNullException))] public void LikeTransactSqlWithEscapeThrowArgumentNullException(string matchExpression, string pattern, string escape) { var actual = matchExpression.Like(pattern, escape); Assert.IsNotNull(actual); } [DataTestMethod] [DataRow("abcdef", "a%", "\\", true)] [DataRow("abcdef", "a%", "a", false)] [DataRow("abcdef", "EaEbEc%", "E", true)] [DataRow("abcdef", "%\\e_", "\\", true)] public async Task LikeTransactSqlWithEscapeSpecials(string matchExpression, string pattern, string escape, bool expected) { bool actual = await LikeTransactSqlWithEscapeAssert(matchExpression, pattern, escape).ConfigureAwait(false); Assert.AreEqual(expected, actual); } [DataTestMethod] [DataRow("aAB", "_%", 79860, "\\")] public void LikeTransactSqlWithEscapeComparision(string expressionLetters, string patternLetters, int combinations, string escape) { var cases = LikeTestCase.Generate(expressionLetters, patternLetters); Assert.AreEqual(combinations, cases.Count()); Parallel.ForEachAsync(cases, new ParallelOptions() { MaxDegreeOfParallelism = 50 }, async (c, t) => { string matchExpression = c[0].ToString(); string pattern = c[1].ToString(); bool actual = await LikeTransactSqlWithEscapeAssert(matchExpression, pattern, escape).ConfigureAwait(false); Assert.IsNotNull(actual); }).Wait(); } private static async Task<bool> LikeTransactSqlWithEscapeAssert(string matchExpression, string pattern, string escape) { var expected = await LikeTransactSqlOperatorWithEscapeAsync(matchExpression, pattern, escape).ConfigureAwait(false); var regex = LikeTransactSql.LikeRegex(pattern, escape) ?? "<Null>"; var message = $"Query:'{matchExpression}' LIKE '{pattern}' ESCAPE '{escape}'. Regex:{regex}"; try { var actual = matchExpression.Like(pattern, escape); Assert.AreEqual(expected, actual, message); return actual; } catch (Exception ex) { Assert.IsTrue(false, $"{message}. Exception:{ex.Message}."); throw; } } private static async Task<bool> LikeTransactSqlOperatorWithEscapeAsync(string matchExpression, string pattern, string escape) { string query = $"SELECT CASE WHEN '{matchExpression}' LIKE '{pattern}' ESCAPE '{escape}' THEN 1 ELSE 0 END"; string connectionString = $"{testcontainer?.ConnectionString}TrustServerCertificate=True;"; using var connection = new SqlConnection(connectionString); return await connection.ExecuteScalarAsync<bool>(query).ConfigureAwait(false); } } }
41.897727
138
0.623813
[ "MIT" ]
cagrin/LikeComparison
LikeComparison.Tests/DatabaseTests/LikeTransactSqlTests.WithEscape.cs
3,687
C#
namespace Imagin.Common.Input { /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public delegate void PropertyEnabledEventHandler(object sender, PropertyEnabledEventArgs e); }
24.9
96
0.630522
[ "BSD-2-Clause" ]
OkumaScott/Imagin.NET
Imagin.Common.WPF/Input/PropertyEnabledEventHandler.cs
251
C#
/* MIT License Copyright (c) Léo Corporation 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 Gavilya.Classes; using Gavilya.Windows; using Microsoft.Win32; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Gavilya.Pages.FirstRunPages { /// <summary> /// Logique d'interaction pour ImportGamesPage.xaml /// </summary> public partial class ImportGamesPage : Page { FirstRun FirstRun; public ImportGamesPage(FirstRun firstRun) { InitializeComponent(); FirstRun = firstRun; // Define } private void NextPage() { FirstRun.ChangePage(Enums.FirstRunPages.Finish); // Change page } private void ImportBtn_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new(); // Create an OpenFileDialog openFileDialog.Filter = $"{Properties.Resources.GavFiles}|*.gav"; // Extension openFileDialog.Title = Properties.Resources.ImportGames; // Title if (openFileDialog.ShowDialog() ?? true) // If the user opend a file { new GameSaver().Import(openFileDialog.FileName, true); // Import } FirstRun.ChangePage(Enums.FirstRunPages.SelectImportedGames); // Change page } private void SkipBtn_Click(object sender, RoutedEventArgs e) { NextPage(); // Change page } } }
31.716049
81
0.770339
[ "MIT" ]
Leo-Corporation/Gavilya
Gavilya/Pages/FirstRunPages/ImportGamesPage.xaml.cs
2,572
C#
using Sandbox; using Sandbox.UI; using Sandbox.UI.Construct; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VRP.VGui.UI { public class VGuiContextList : Panel { public static VGuiContextList Instance; private const int BUTTON_HEIGHT = 30; private const int BUTTON_MARGIN = 3; private int _numOptions; public VGuiContextList() { StyleSheet.Load( "/VGui/UI/VGuiContextList.scss" ); this.Style.PaddingBottom = BUTTON_MARGIN; Instance?.Delete( true ); Instance = this; } public Panel ContextParent { get; set; } public Action<string, string> Callback { get; set; } public override void Tick() { base.Tick(); if (this.ContextParent == null || this.ContextParent.IsDeleting || !this.ContextParent.IsVisible) { this.Delete( true ); } } public static VGuiContextList Create(Panel parent, Action<string, string> callback) { var context = Local.Hud.AddChild<VGuiContextList>(); context.Callback = callback; context.ContextParent = parent; var self = parent.Box.Rect; var rect = context.Box.Rect; context.Style.Top = self.top + self.height; context.Style.Left = self.left; return context; } public override string GetClipboardValue( bool cut ) { this.Delete( true ); return base.GetClipboardValue( cut ); } public void AddOption(string name, string value) { // TODO: Make button (when copy to clipboard is added) //var button = Add.Button( name ); var button = Add.TextEntry( value ?? name ); button.Style.Height = BUTTON_HEIGHT; button.Style.MinHeight = BUTTON_HEIGHT; button.Style.Margin = BUTTON_MARGIN; button.Style.MarginBottom = 0; button.AddEventListener( "onclick", ( e ) => { /*this.Callback?.Invoke( name, value ); this.Delete( true );*/ e.StopPropagation(); } ); _numOptions++; this.Style.Height = _numOptions * (BUTTON_HEIGHT + BUTTON_MARGIN); } } }
22.3
100
0.686597
[ "MIT" ]
civilgamers/vrp
code/VGui/UI/VGuiContextList.cs
2,009
C#
using GameEstate.Core; using System.IO; namespace GameEstate.Formats.Binary.Tes.Records { public class SNDRRecord : Record { public override string ToString() => $"SNDR: {EDID.Value}"; public STRVField EDID { get; set; } // Editor ID public CREFField CNAME; // RGB color public override bool CreateField(BinaryReader r, TesFormat format, string type, int dataSize) { switch (type) { case "EDID": EDID = r.ReadSTRV(dataSize); return true; case "CNAME": CNAME = r.ReadT<CREFField>(dataSize); return true; default: return false; } } } }
31.863636
102
0.563481
[ "MIT" ]
smorey2/GameEstate
src/GameExtensions/Tes/src/GameEstate.Extensions.Tes/Formats/Binary/Tes/Records/005-SNDR.Sound Reference.cs
703
C#
// ------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a tool. // Mono Runtime Version: 4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> // ------------------------------------------------------------------------------ namespace PubNub_Messaging { public partial class Resource { public partial class Attribute { private Attribute() { } } public partial class Drawable { // aapt resource value: 0x7f020000 public const int Icon = 2130837504; private Drawable() { } } public partial class Id { // aapt resource value: 0x7f050005 public const int btnCancel = 2131034117; // aapt resource value: 0x7f050009 public const int btnDetailedHis = 2131034121; // aapt resource value: 0x7f05000a public const int btnHereNow = 2131034122; // aapt resource value: 0x7f050003 public const int btnLaunch = 2131034115; // aapt resource value: 0x7f050008 public const int btnPresence = 2131034120; // aapt resource value: 0x7f050007 public const int btnPublish = 2131034119; // aapt resource value: 0x7f050006 public const int btnSubscribe = 2131034118; // aapt resource value: 0x7f050004 public const int btnSubscribeConnCallback = 2131034116; // aapt resource value: 0x7f05000b public const int btnTime = 2131034123; // aapt resource value: 0x7f05000c public const int btnUnsub = 2131034124; // aapt resource value: 0x7f05000d public const int btnUnsubPres = 2131034125; // aapt resource value: 0x7f05000e public const int scroll = 2131034126; // aapt resource value: 0x7f050001 public const int tbSsl = 2131034113; // aapt resource value: 0x7f050000 public const int txtChannel = 2131034112; // aapt resource value: 0x7f050002 public const int txtCipher = 2131034114; // aapt resource value: 0x7f05000f public const int txtViewLog = 2131034127; private Id() { } } public partial class Layout { // aapt resource value: 0x7f030000 public const int Launch = 2130903040; // aapt resource value: 0x7f030001 public const int Main = 2130903041; private Layout() { } } public partial class String { // aapt resource value: 0x7f040010 public const int app_name = 2130968592; // aapt resource value: 0x7f040000 public const int cancel = 2130968576; // aapt resource value: 0x7f04000a public const int channel = 2130968586; // aapt resource value: 0x7f04000e public const int cipher = 2130968590; // aapt resource value: 0x7f040006 public const int detailedHistory = 2130968582; // aapt resource value: 0x7f04000b public const int enablessl = 2130968587; // aapt resource value: 0x7f040005 public const int herenow = 2130968581; // aapt resource value: 0x7f04000f public const int launch = 2130968591; // aapt resource value: 0x7f040004 public const int presence = 2130968580; // aapt resource value: 0x7f040003 public const int publish = 2130968579; // aapt resource value: 0x7f04000d public const int sslOff = 2130968589; // aapt resource value: 0x7f04000c public const int sslOn = 2130968588; // aapt resource value: 0x7f040001 public const int subscribe = 2130968577; // aapt resource value: 0x7f040002 public const int subscribeConnCallback = 2130968578; // aapt resource value: 0x7f040007 public const int time = 2130968583; // aapt resource value: 0x7f040008 public const int unsubscribe = 2130968584; // aapt resource value: 0x7f040009 public const int unsubscribePres = 2130968585; private String() { } } } }
23.700599
81
0.646791
[ "MIT" ]
goodybag/pubnub-api
mono-for-android/3.3.0.1/Pubnub-Messaging/PubNub_Messaging/Resources/Resource.designer.cs
3,958
C#
// Copyright (c) Richasy. All rights reserved. using System.Threading.Tasks; using Richasy.Bili.App.Controls; using Richasy.Bili.ViewModels.Uwp; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace Richasy.Bili.App.Pages { /// <summary> /// 可用于自身或导航至 Frame 内部的空白页. /// </summary> public sealed partial class DynamicFeedPage : Page, IRefreshPage { /// <summary> /// <see cref="ViewModel"/>的依赖属性. /// </summary> public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(nameof(ViewModel), typeof(DynamicModuleViewModel), typeof(DynamicFeedPage), new PropertyMetadata(DynamicModuleViewModel.Instance)); /// <summary> /// Initializes a new instance of the <see cref="DynamicFeedPage"/> class. /// </summary> public DynamicFeedPage() { this.InitializeComponent(); this.Loaded += OnLoadedAsync; } /// <summary> /// 视图模型. /// </summary> public DynamicModuleViewModel ViewModel { get { return (DynamicModuleViewModel)GetValue(ViewModelProperty); } set { SetValue(ViewModelProperty, value); } } /// <inheritdoc/> public Task RefreshAsync() => ViewModel.InitializeRequestAsync(); private async void OnLoadedAsync(object sender, RoutedEventArgs e) { if (!ViewModel.IsRequested) { await ViewModel.InitializeRequestAsync(); } } private async void OnViewRequestLoadMoreAsync(object sender, System.EventArgs e) { await ViewModel.RequestDataAsync(); } private async void OnDynamicRefreshButtonClickAsync(object sender, RoutedEventArgs e) { await RefreshAsync(); } private async void OnLoginButtonClickAsync(object sender, RoutedEventArgs e) { LoginButton.IsEnabled = false; await AccountViewModel.Instance.TrySignInAsync(); if (LoginButton != null) { LoginButton.IsEnabled = true; } } } }
30.342466
171
0.601354
[ "MIT" ]
Caseming/Bili.Uwp
src/App/Pages/DynamicFeedPage.xaml.cs
2,265
C#
using System.Threading.Tasks; using Strive.Core.Services; using Strive.Core.Services.Equipment.Gateways; using Strive.Infrastructure.KeyValue.Abstractions; namespace Strive.Infrastructure.KeyValue.Repos { public class EquipmentTokenRepository : IEquipmentTokenRepository, IKeyValueRepo { private const string PROPERTY_KEY = "equipmentToken"; private readonly IKeyValueDatabase _database; public EquipmentTokenRepository(IKeyValueDatabase database) { _database = database; } public async ValueTask RemoveAllDataOfConference(string conferenceId) { var key = GetKey(conferenceId); await _database.KeyDeleteAsync(key); } public ValueTask Set(Participant participant, string token) { var key = GetKey(participant.ConferenceId); return _database.HashSetAsync(key, participant.Id, token); } public ValueTask<string?> Get(Participant participant) { var key = GetKey(participant.ConferenceId); return _database.HashGetAsync(key, participant.Id); } private static string GetKey(string conferenceId) { return DatabaseKeyBuilder.ForProperty(PROPERTY_KEY).ForConference(conferenceId).ToString(); } } }
31.162791
103
0.674627
[ "Apache-2.0" ]
Anapher/PaderConference
src/Services/ConferenceManagement/Strive.Infrastructure/KeyValue/Repos/EquipmentTokenRepository.cs
1,340
C#
//// ---------------------------------------------------------------------------------- //// //// Copyright Microsoft Corporation //// Licensed under the Apache License, Version 2.0 (the "License"); //// you may not use this file except in compliance with the License. //// You may obtain a copy of the License at //// http://www.apache.org/licenses/LICENSE-2.0 //// Unless required by applicable law or agreed to in writing, software //// distributed under the License is distributed on an "AS IS" BASIS, //// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //// See the License for the specific language governing permissions and //// limitations under the License. //// ---------------------------------------------------------------------------------- using System.Diagnostics.CodeAnalysis; namespace Microsoft.Azure.Commands.SiteRecovery { /// <summary> /// General Constant definition /// </summary> public static class Constants { /// <summary> /// ASR vault type /// </summary> public const string ASRVaultType = "HyperVRecoveryManagerVault"; /// <summary> /// Vault Credential version. /// </summary> public const string VaultCredentialVersion = "1.0"; /// <summary> /// The version of Extended resource info. /// </summary> public const string VaultSecurityInfoVersion = "1.0"; /// <summary> /// extended information version. /// </summary> public const string VaultExtendedInfoContractVersion = "V2014_09"; /// <summary> /// A valid value for the string field Microsoft.WindowsAzure.CloudServiceManagement.resource.OperationStatus.Type /// </summary> public const string RdfeOperationStatusTypeCreate = "Create"; /// <summary> /// A valid value for the string field Microsoft.WindowsAzure.CloudServiceManagement.resource.OperationStatus.Type /// </summary> public const string RdfeOperationStatusTypeDelete = "Delete"; /// <summary> /// A valid value for the string field Microsoft.WindowsAzure.CloudServiceManagement.resource.OperationStatus.Result /// </summary> public const string RdfeOperationStatusResultSucceeded = "Succeeded"; /// <summary> /// A valid value for the string field Microsoft.WindowsAzure.CloudServiceManagement.resource.OperationStatus.Failed /// </summary> public const string RdfeOperationStatusResultFailed = "Failed"; /// <summary> /// A valid value for the string field Microsoft.WindowsAzure.CloudServiceManagement.resource.OperationStatus.InProgress /// </summary> public const string RdfeOperationStatusResultInProgress = "InProgress"; /// <summary> /// Cloud service name prefix /// </summary> public const string CloudServiceNameExtensionPrefix = "CS-"; /// <summary> /// Cloud service name suffix /// </summary> public const string CloudServiceNameExtensionSuffix = "-RecoveryServices"; /// <summary> /// Schema Version of RP /// </summary> public const string RpSchemaVersion = "1.1"; /// <summary> /// Resource Provider Namespace. /// </summary> public const string ResourceNamespace = "WAHyperVRecoveryManager"; /// <summary> /// Represents None string value. /// </summary> public const string None = "None"; /// <summary> /// Represents Existing string value. /// </summary> public const string Existing = "Existing"; /// <summary> /// Represents New string value. /// </summary> public const string New = "New"; /// <summary> /// Represents direction primary to secondary. /// </summary> public const string PrimaryToRecovery = "PrimaryToRecovery"; /// <summary> /// Represents direction secondary to primary. /// </summary> public const string RecoveryToPrimary = "RecoveryToPrimary"; /// <summary> /// Represents Optimize value ForDowntime. /// </summary> public const string ForDowntime = "ForDowntime"; /// <summary> /// Represents Optimize value for Synchronization. /// </summary> public const string ForSynchronization = "ForSynchronization"; /// <summary> /// Represents primary location. /// </summary> public const string PrimaryLocation = "Primary"; /// <summary> /// Represents Recovery location. /// </summary> public const string RecoveryLocation = "Recovery"; /// <summary> /// Represents HyperVReplica string constant. /// </summary> public const string HyperVReplica2012 = "HyperVReplica2012"; /// <summary> /// Represents HyperVReplicaBlue string constant. /// </summary> public const string HyperVReplica2012R2 = "HyperVReplica2012R2"; /// <summary> /// Represents HyperVReplica string constant. /// </summary> public const string HyperVReplicaAzure = "HyperVReplicaAzure"; /// <summary> /// Represents HyperVReplicaAzureReplicationDetails string constant. /// </summary> public const string HyperVReplicaAzureReplicationDetails = "HyperVReplicaAzureReplicationDetails"; /// <summary> /// Represents HyperVReplica2012ReplicationDetails string constant. /// </summary> public const string HyperVReplica2012ReplicationDetails = "HyperVReplica2012ReplicationDetails"; /// <summary> /// Represents InMageAzureV2ProviderSpecificSettings string constant. /// </summary> public const string InMageAzureV2ProviderSpecificSettings = "InMageAzureV2ProviderSpecificSettings"; /// <summary> /// Represents InMageProviderSpecificSettings string constant. /// </summary> public const string InMageProviderSpecificSettings = "InMageProviderSpecificSettings"; /// <summary> /// Represents San string constant. /// </summary> public const string San = "San"; /// <summary> /// Represents HyperVReplica string constant. /// </summary> public const string AzureContainer = "Microsoft Azure"; /// <summary> /// Represents OnlineReplicationMethod string constant. /// </summary> public const string OnlineReplicationMethod = "Online"; /// <summary> /// Represents OfflineReplicationMethod string constant. /// </summary> public const string OfflineReplicationMethod = "Offline"; /// <summary> /// Represents OS Windows. /// </summary> public const string OSWindows = "Windows"; /// <summary> /// Represents OS Linux. /// </summary> public const string OSLinux = "Linux"; /// <summary> /// Represents Enable protection. /// </summary> public const string EnableProtection = "Enable"; /// <summary> /// Represents Disable protection. /// </summary> public const string DisableProtection = "Disable"; /// <summary> /// Represents Direction string value. /// </summary> public const string Direction = "Direction"; /// <summary> /// Represents RPId string value. /// </summary> public const string RPId = "RPId"; /// <summary> /// Represents ID string value. /// </summary> public const string ID = "ID"; /// <summary> /// Represents NetworkType string value. /// </summary> public const string NetworkType = "NetworkType"; /// <summary> /// Represents ProtectionEntityId string value. /// </summary> public const string ProtectionEntityId = "ProtectionEntityId"; /// <summary> /// Azure fabric Id. In E2A context Recovery Server Id is always this. /// </summary> public const string AzureFabricId = "21a9403c-6ec1-44f2-b744-b4e50b792387"; /// <summary> /// Authentication Type as Certificate based authentication. /// </summary> public const string AuthenticationTypeCertificate = "Certificate"; /// <summary> /// Authentication Type as Kerberos. /// </summary> public const string AuthenticationTypeKerberos = "Kerberos"; /// <summary> /// Acceptable values of Replication Frequency in seconds (as per portal). /// </summary> public const string Thirty = "30"; /// <summary> /// Acceptable values of Replication Frequency in seconds (as per portal). /// </summary> public const string ThreeHundred = "300"; /// <summary> /// Acceptable values of Replication Frequency in seconds (as per portal). /// </summary> public const string NineHundred = "900"; /// <summary> /// Replication type - async. /// </summary> public const string Sync = "Sync"; /// <summary> /// Replication type - async. /// </summary> public const string Async = "Async"; /// <summary> /// SourceSiteOperations - Required. /// </summary> public const string Required = "Required"; /// <summary> /// SourceSiteOperations - NotRequired. /// </summary> public const string NotRequired = "NotRequired"; /// <summary> /// FabricType - VMM. /// </summary> public const string VMM = "VMM"; /// <summary> /// FabricType - HyperVSite. /// </summary> public const string HyperVSite = "HyperVSite"; /// <summary> /// FabricType - VMware. /// </summary> public const string VMware = "VMware"; /// <summary> /// Nic Selection Type - NotSelected /// </summary> public const string NotSelected = "NotSelected"; /// <summary> /// Nic Selection Type - SelectedByDefault /// </summary> public const string SelectedByDefault = "SelectedByDefault"; /// <summary> /// Nic Selection Type - SelectedByUser /// </summary> public const string SelectedByUser = "SelectedByUser"; /// <summary> /// Failover deployment model: NotApplicable /// </summary> public const string NotApplicable = "NotApplicable"; /// <summary> /// Failover deployment model: Classic /// </summary> public const string Classic = "Classic"; /// <summary> /// Failover deployment model: ResourceMananger /// </summary> public const string ResourceManager = "ResourceManager"; /// <summary> /// Group Type: Shutdown /// </summary> public const string Shutdown = "Shutdown"; /// <summary> /// Group Type: Boot /// </summary> public const string Boot = "Boot"; /// <summary> /// Group Type: Failover /// </summary> public const string Failover = "Failover"; /// <summary> /// JSON field: InstanceType /// </summary> public const string InstanceType = "InstanceType"; } /// <summary> /// ARM Resource Type Constants /// </summary> public static class ARMResourceTypeConstants { /// <summary> /// Subscriptions /// </summary> public const string Subscriptions = "subscriptions"; /// <summary> /// Resource Groups /// </summary> public const string ResourceGroups = "resourceGroups"; /// <summary> /// Providers /// </summary> public const string Providers = "providers"; /// <summary> /// Site Recovery Vault /// </summary> public const string SiteRecoveryVault = "SiteRecoveryVault"; /// <summary> /// Recovery Services Vault /// </summary> public const string RecoveryServicesVault = "Vaults"; /// <summary> /// Replication Policies /// </summary> public const string ReplicationPolicies = "replicationPolicies"; /// <summary> /// Replication Fabrics /// </summary> public const string ReplicationFabrics = "replicationFabrics"; /// <summary> /// Replication Protection Containers /// </summary> public const string ReplicationProtectionContainers = "replicationProtectionContainers"; /// <summary> /// Replication Protected Items /// </summary> public const string ReplicationProtectedItems = "replicationProtectedItems"; /// <summary> /// Replication Networks /// </summary> public const string ReplicationNetworks = "replicationNetworks"; /// <summary> /// Virtual Networks /// </summary> public const string VirtualNetworks = "virtualNetworks"; /// <summary> /// Recovery provider resource name. /// </summary> public const string RecoveryServicesProviders = "replicationRecoveryServicesProviders"; /// <summary> /// Protection container mappings resource name. /// </summary> public const string ProtectionContainerMappings = "replicationProtectionContainerMappings"; /// <summary> /// Protectable Items resource name. /// </summary> public const string ProtectableItems = "replicationProtectableItems"; /// <summary> /// Recovery Points resource name. /// </summary> public const string RecoveryPoints = "recoveryPoints"; /// <summary> /// Jobs resource name. /// </summary> public const string Jobs = "replicationJobs"; /// <summary> /// Policies resource name. /// </summary> public const string Policies = "replicationPolicies"; /// <summary> /// RecoveryPlans resource name. /// </summary> public const string RecoveryPlans = "replicationRecoveryPlans"; /// <summary> /// Logical Networks resource name. /// </summary> public const string LogicalNetworks = "replicationLogicalNetworks"; /// <summary> /// Network Mappings resource name. /// </summary> public const string NetworkMappings = "replicationNetworkMappings"; /// <summary> /// VCenters resource name. /// </summary> public const string VCenters = "replicationvCenters"; /// <summary> /// Replication Vault Usages. /// </summary> public const string ReplicationVaultUsages = "replicationUsages"; /// <summary> /// Vault Usages. /// </summary> public const string VaultUsages = "usages"; /// <summary> /// Events resource name. /// </summary> public const string Events = "replicationEvents"; /// <summary> /// Storage classification resource name. /// </summary> public const string StorageClassification = "replicationStorageClassifications"; /// <summary> /// Storage classification mapping resource name. /// </summary> public const string StorageClassificationMapping = "replicationStorageClassificationMappings"; /// <summary> /// Alerts resource name. /// </summary> public const string Alerts = "replicationAlertSettings"; /// <summary> /// List Recovery Azure Vm size operation name. /// </summary> public const string TargetComputeSizes = "targetComputeSizes"; } /// <summary> /// Constants for current version. /// </summary> public class ARMResourceIdPaths { /// <summary> /// ARM resource path for fabric. /// </summary> public const string FabricResourceIdPath = ARMRoutePathConstants.FabricsRoutePath + "/{0}"; /// <summary> /// ARM resource path for recovery services providers. /// </summary> public const string RecoveryServicesProviderResourceIdPath = FabricResourceIdPath + "/" + ARMResourceTypeConstants.RecoveryServicesProviders + "/{1}"; /// <summary> /// ARM resource path for recovery services providers. /// </summary> public const string ProtectionContainerResourceIdPath = FabricResourceIdPath + "/" + ARMResourceTypeConstants.ReplicationProtectionContainers + "/{1}"; /// <summary> /// ARM resource path for protection container mappings. /// </summary> public const string ProtectionContainerMappingResourceIdPath = ProtectionContainerResourceIdPath + "/" + ARMResourceTypeConstants.ProtectionContainerMappings + "/{2}"; /// <summary> /// ARM resource path for ProtectableItems. /// </summary> public const string ProtectableItemResourceIdPath = ProtectionContainerResourceIdPath + "/" + ARMResourceTypeConstants.ProtectableItems + "/{2}"; /// <summary> /// ARM resource path for ReplicatedProtectedItems. /// </summary> public const string ReplicatedProtectedItemResourceIdPath = ProtectionContainerResourceIdPath + "/" + ARMResourceTypeConstants.ReplicationProtectedItems + "/{2}"; /// <summary> /// ARM resource path for RecoveryPoints. /// </summary> public const string RecoveryPointResourceIdPath = ReplicatedProtectedItemResourceIdPath + "/" + ARMResourceTypeConstants.RecoveryPoints + "/{3}"; /// <summary> /// ARM resource path for Jobs. /// </summary> public const string JobResourceIdPath = ARMRoutePathConstants.JobsRoutePath + "/{0}"; /// <summary> /// ARM resource path for Policies. /// </summary> public const string PolicyResourceIdPath = ARMRoutePathConstants.PoliciesRoutePath + "/{0}"; /// <summary> /// ARM resource path for RecoveryPlans. /// </summary> public const string RecoveryPlanResourceIdPath = ARMRoutePathConstants.RecoveryPlansRoutePath + "/{0}"; /// <summary> /// ARM resource path for Networks. /// </summary> public const string NetworkResourceIdPath = FabricResourceIdPath + "/" + ARMResourceTypeConstants.ReplicationNetworks + "/{1}"; /// <summary> /// ARM resource path for LogicalNetworks. /// </summary> public const string LogicalNetworkResourceIdPath = FabricResourceIdPath + "/" + ARMResourceTypeConstants.LogicalNetworks + "/{1}"; /// <summary> /// ARM resource path for Network Mappings. /// </summary> public const string NetworkMappingResourceIdPath = NetworkResourceIdPath + "/" + ARMResourceTypeConstants.NetworkMappings + "/{2}"; /// <summary> /// ARM Resource path for Vcenters. /// </summary> public const string VCenterResourceIdPath = FabricResourceIdPath + "/" + ARMResourceTypeConstants.VCenters + "/{1}"; /// <summary> /// ARM resource path for event. /// </summary> public const string EventResourceIdPath = ARMRoutePathConstants.EventsRoutePath + "/{0}"; /// <summary> /// ARM resource path for storage classification. /// </summary> public const string StorageClassificationResourceIdPath = FabricResourceIdPath + "/" + ARMResourceTypeConstants.StorageClassification + "/{1}"; /// <summary> /// ARM resource path for storage classification mapping. /// </summary> public const string StorageClassificationMappingResourceIdPath = StorageClassificationResourceIdPath + "/" + ARMResourceTypeConstants.StorageClassificationMapping + "/{2}"; /// <summary> /// ARM resource path for event. /// </summary> public const string AlertsResourceIdPath = ARMRoutePathConstants.AlertsRoutePath + "/{0}"; /// <summary> /// SRS ARM Url Pattern. /// </summary> public const string SRSArmUrlPattern = "/Subscriptions/{0}/resourceGroups/{1}/providers/{2}/{3}/{4}"; #region External ARM Resource Id /// <summary> /// Storage account ARM Id. /// </summary> public const string StorageAccountArmId = "/subscriptions/{0}/resourceGroups/{1}/providers/{2}/storageAccounts/{3}"; /// <summary> /// ARM resource path for Azure Networks. /// </summary> public const string AzureNetworksPath = "/subscriptions/{0}/resourceGroups/{1}/providers/{2}/virtualNetworks/{3}"; /// <summary> /// Automation runbook ARM Id. /// </summary> public const string AutomationRunbookArmId = "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Automation/automationAccounts/{2}/runbooks/{3}"; #endregion } /// <summary> /// Constants for Route paths. /// </summary> [SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Keeping all related classes together.")] public class ARMRoutePathConstants { /// <summary> /// Vault level ReplicatedProtectedItems route path. /// </summary> public const string VaultLevelReplicationProtectedItemsRoutePath = ARMResourceTypeConstants.ReplicationProtectedItems; /// <summary> /// Vault level ProtectionContainerMappings route path. /// </summary> public const string VaultLevelProtectionContainerMappingsRoutePath = ARMResourceTypeConstants.ProtectionContainerMappings; /// <summary> /// Vault level ProtectionContainers route path. /// </summary> public const string VaultLevelProtectionContainersRoutePath = ARMResourceTypeConstants.ReplicationProtectionContainers; /// <summary> /// Vault level storage classification route path. /// </summary> public const string VaultLevelStorageClassificationRoutePath = ARMResourceTypeConstants.StorageClassification; /// <summary> /// Vault level storage classification mapping route path. /// </summary> public const string VaultLevelStorageClassificationMappingRoutePath = ARMResourceTypeConstants.StorageClassificationMapping; /// <summary> /// Fabric route path. /// </summary> public const string FabricsRoutePath = ARMResourceTypeConstants.ReplicationFabrics; /// <summary> /// RecoveryServicesProvider route path. /// </summary> public const string RecoveryServicesProvidersRoutePath = FabricsRoutePath + "/{fabricName}/" + ARMResourceTypeConstants.RecoveryServicesProviders; /// <summary> /// RecoveryServicesProvider view API route path. /// </summary> public const string RecoveryServicesProvidersViewRoutePath = ARMResourceTypeConstants.RecoveryServicesProviders; /// <summary> /// ProtectionContainer route path. /// </summary> public const string ProtectionContainersRoutePath = FabricsRoutePath + "/{fabricName}/" + ARMResourceTypeConstants.ReplicationProtectionContainers; /// <summary> /// Protection container mappings path. /// </summary> public const string ProtectionContainerMappingsRoutePath = ProtectionContainersRoutePath + "/{protectionContainerName}/" + ARMResourceTypeConstants.ProtectionContainerMappings; /// <summary> /// ProtectableItems route path. /// </summary> public const string ProtectableItemsRoutePath = ProtectionContainersRoutePath + "/{protectionContainerName}/" + ARMResourceTypeConstants.ProtectableItems; /// <summary> /// ReplicatedProtectedItems route path. /// </summary> public const string ReplicationProtectedItemsRoutePath = ProtectionContainersRoutePath + "/{protectionContainerName}/" + ARMResourceTypeConstants.ReplicationProtectedItems; /// <summary> /// RecoveryPoints route path. /// </summary> public const string RecoveryPointsRoutePath = ReplicationProtectedItemsRoutePath + "/{replicatedProtectedItemName}/" + ARMResourceTypeConstants.RecoveryPoints; /// <summary> /// Jobs route path. /// </summary> public const string JobsRoutePath = ARMResourceTypeConstants.Jobs; /// <summary> /// Jobs route path. /// </summary> public const string PoliciesRoutePath = ARMResourceTypeConstants.Policies; /// <summary> /// Jobs route path. /// </summary> public const string RecoveryPlansRoutePath = ARMResourceTypeConstants.RecoveryPlans; /// <summary> /// Replication Networks Route Path /// </summary> public const string NetworksRoutePath = FabricsRoutePath + "/{fabricName}/" + ARMResourceTypeConstants.ReplicationNetworks; /// <summary> /// Replication Logical Networks Route Path /// </summary> public const string LogicalNetworksRoutePath = FabricsRoutePath + "/{fabricName}/" + ARMResourceTypeConstants.LogicalNetworks; /// <summary> /// Network Mappings Route Path /// </summary> public const string NetworkMappingsRoutePath = NetworksRoutePath + "/{networkName}/" + ARMResourceTypeConstants.NetworkMappings; /// <summary> /// VCenters route path. /// </summary> public const string VCentersRoutePath = FabricsRoutePath + "/{fabricName}/" + ARMResourceTypeConstants.VCenters; /// <summary> /// Events route path. /// </summary> public const string EventsRoutePath = ARMResourceTypeConstants.Events; /// <summary> /// Storage route path. /// </summary> public const string StorageClassificationRoutePath = FabricsRoutePath + "/{fabricName}/" + ARMResourceTypeConstants.StorageClassification; /// <summary> /// Storage mapping route path. /// </summary> public const string StorageClassificationMappingRoutePath = StorageClassificationRoutePath + "/{storageClassificationName}/" + ARMResourceTypeConstants.StorageClassificationMapping; /// <summary> /// Alerts route path. /// </summary> public const string AlertsRoutePath = ARMResourceTypeConstants.Alerts; /// <summary> /// Operations route path. /// </summary> public const string OperationsRoutePath = "operations"; /// <summary> /// Operations route path. /// </summary> public const string TargetComputesSizesPath = ReplicationProtectedItemsRoutePath + "/{replicatedProtectedItemName}/" + ARMResourceTypeConstants.TargetComputeSizes; } }
37.026178
185
0.59421
[ "MIT" ]
hchungmsft/azure-powershell
src/ResourceManager/SiteRecovery/Commands.SiteRecovery/Models/PSConstants.cs
27,527
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 datasync-2018-11-09.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.DataSync.Model { /// <summary> /// Container for the parameters to the CancelTaskExecution operation. /// Cancels execution of a task. /// /// /// <para> /// When you cancel a task execution, the transfer of some files is abruptly interrupted. /// The contents of files that are transferred to the destination might be incomplete /// or inconsistent with the source files. However, if you start a new task execution /// on the same task and you allow the task execution to complete, file content on the /// destination is complete and consistent. This applies to other unexpected failures /// that interrupt a task execution. In all of these cases, DataSync successfully complete /// the transfer when you start the next task execution. /// </para> /// </summary> public partial class CancelTaskExecutionRequest : AmazonDataSyncRequest { private string _taskExecutionArn; /// <summary> /// Gets and sets the property TaskExecutionArn. /// <para> /// The Amazon Resource Name (ARN) of the task execution to cancel. /// </para> /// </summary> [AWSProperty(Required=true, Max=128)] public string TaskExecutionArn { get { return this._taskExecutionArn; } set { this._taskExecutionArn = value; } } // Check to see if TaskExecutionArn property is set internal bool IsSetTaskExecutionArn() { return this._taskExecutionArn != null; } } }
35.2
106
0.67776
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/DataSync/Generated/Model/CancelTaskExecutionRequest.cs
2,464
C#
using Microsoft.Azure.Management.Compute.Models; using System.Threading; using System.Threading.Tasks; namespace DenevCloud.AspNetCore.Services.Azure.VirtualMachines { public interface IVMManager { VirtualMachine GetVirtualMachine(string VMName); Task<VirtualMachine> GetVirtualMachineAsync(string VMName); Task<VirtualMachine> GetVirtualMachineAsync(string VMName, CancellationToken token); void StartVirtualMachine(string VMName); Task StartVirtualMachineAsync(string VMName); Task StartVirtualMachineAsync(string VMName, CancellationToken token); void RestartVirtualMachine(string VMName, bool skipShutdown = false); Task RestartVirtualMachineAsync(string VMName); Task RestartVirtualMachineAsync(string VMName, CancellationToken token); void DeallocateVirtualMachine(string VMName); //Task DeallocateVirtualMachineAsync(string VMName, CancellationToken token); Task DeallocateVirtualMachineAsync(string VMName); void PowerOffVirtualMachine(string VMName, bool skipShutdown = false); Task PowerOffVirtualMachineAsync(string VMName, bool skipShutdown = false); Task PowerOffVirtualMachineAsync(string VMName, CancellationToken token, bool skipShutdown = false); //void GetListVirtualMachines(); //Task GetListVirtualMachinesAsync(); //Task GetListVirtualMachinesAsync(CancellationToken token); } }
52.035714
108
0.761839
[ "Apache-2.0" ]
DenevCloud/DenevCloud.AspNetCore.Services.Azure
DenevCloud.AspNetCore.Services.Azure/VirtualMachines/IVMManager.cs
1,459
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using BuildXL.Cache.ContentStore.Distributed.NuCache; using BuildXL.Cache.ContentStore.FileSystem; using BuildXL.Cache.ContentStore.Interfaces.FileSystem; using BuildXL.Cache.ContentStore.Interfaces.Tracing; using BuildXL.Cache.ContentStore.InterfacesTest.Results; using BuildXL.Cache.ContentStore.InterfacesTest.Time; using ContentStoreTest.Test; using BuildXL.Cache.MemoizationStore.Stores; using BuildXL.Cache.MemoizationStore.Interfaces.Results; using BuildXL.Cache.MemoizationStore.Interfaces.Sessions; using BuildXL.Cache.MemoizationStore.Interfaces.Stores; using BuildXL.Cache.MemoizationStore.InterfacesTest.Sessions; using BuildXL.Cache.MemoizationStore.InterfacesTest.Results; using Xunit; using System; using System.Diagnostics.ContractsLight; using BuildXL.Cache.ContentStore.Tracing.Internal; using FluentAssertions; namespace BuildXL.Cache.MemoizationStore.Test.Sessions { public class RocksDbMemoizationSessionTests : MemoizationSessionTests { private readonly MemoryClock _clock = new MemoryClock(); public RocksDbMemoizationSessionTests() : base(() => new PassThroughFileSystem(TestGlobal.Logger), TestGlobal.Logger) { } protected override IMemoizationStore CreateStore(DisposableDirectory testDirectory) { return CreateStore(testDirectory, configMutator: null); } protected IMemoizationStore CreateStore(DisposableDirectory testDirectory, Action<RocksDbContentLocationDatabaseConfiguration> configMutator = null) { var memoConfig = new RocksDbMemoizationStoreConfiguration() { Database = new RocksDbContentLocationDatabaseConfiguration(testDirectory.Path) }; configMutator?.Invoke(memoConfig.Database); return new RocksDbMemoizationStore(Logger, _clock, memoConfig); } [Fact] public Task GetSelectorsGivesSelectorsInReverseLruOrderAfterAdd() { var context = new Context(Logger); var weakFingerprint = Fingerprint.Random(); var selector1 = Selector.Random(); var selector2 = Selector.Random(); var strongFingerprint1 = new StrongFingerprint(weakFingerprint, selector1); var strongFingerprint2 = new StrongFingerprint(weakFingerprint, selector2); var contentHashListWithDeterminism1 = new ContentHashListWithDeterminism(ContentHashList.Random(), CacheDeterminism.None); var contentHashListWithDeterminism2 = new ContentHashListWithDeterminism(ContentHashList.Random(), CacheDeterminism.None); return RunTestAsync(context, async session => { await session.AddOrGetContentHashListAsync(context, strongFingerprint1, contentHashListWithDeterminism1, Token).ShouldBeSuccess(); _clock.Increment(); await session.AddOrGetContentHashListAsync(context, strongFingerprint2, contentHashListWithDeterminism2, Token).ShouldBeSuccess(); _clock.Increment(); List<GetSelectorResult> getSelectorResults = await session.GetSelectors(context, weakFingerprint, Token).ToList(CancellationToken.None); Assert.Equal(2, getSelectorResults.Count); GetSelectorResult r1 = getSelectorResults[0]; Assert.True(r1.Succeeded); Assert.True(r1.Selector == selector2); GetSelectorResult r2 = getSelectorResults[1]; Assert.True(r2.Succeeded); Assert.True(r2.Selector == selector1); }); } [Fact] public Task GetSelectorsGivesSelectorsInReverseLruOrderAfterGet() { var context = new Context(Logger); var weakFingerprint = Fingerprint.Random(); var selector1 = Selector.Random(); var selector2 = Selector.Random(); var strongFingerprint1 = new StrongFingerprint(weakFingerprint, selector1); var strongFingerprint2 = new StrongFingerprint(weakFingerprint, selector2); var contentHashListWithDeterminism1 = new ContentHashListWithDeterminism(ContentHashList.Random(), CacheDeterminism.None); var contentHashListWithDeterminism2 = new ContentHashListWithDeterminism(ContentHashList.Random(), CacheDeterminism.None); return RunTestAsync(context, async (store, session) => { await session.AddOrGetContentHashListAsync(context, strongFingerprint1, contentHashListWithDeterminism1, Token).ShouldBeSuccess(); _clock.Increment(); await session.AddOrGetContentHashListAsync(context, strongFingerprint2, contentHashListWithDeterminism2, Token).ShouldBeSuccess(); _clock.Increment(); await session.GetContentHashListAsync(context, strongFingerprint1, Token).ShouldBeSuccess(); _clock.Increment(); List<GetSelectorResult> getSelectorResults = await session.GetSelectors(context, weakFingerprint, Token).ToList(); Assert.Equal(2, getSelectorResults.Count); GetSelectorResult r1 = getSelectorResults[0]; Assert.True(r1.Succeeded); Assert.True(r1.Selector == selector1); GetSelectorResult r2 = getSelectorResults[1]; Assert.True(r2.Succeeded); Assert.True(r2.Selector == selector2); }); } [Fact] public Task GarbageCollectionKeepsLastAdded() { var context = new Context(Logger); var weakFingerprint = Fingerprint.Random(); var selector1 = Selector.Random(); var selector2 = Selector.Random(); var strongFingerprint1 = new StrongFingerprint(weakFingerprint, selector1); var strongFingerprint2 = new StrongFingerprint(weakFingerprint, selector2); var contentHashListWithDeterminism1 = new ContentHashListWithDeterminism(ContentHashList.Random(), CacheDeterminism.None); var contentHashListWithDeterminism2 = new ContentHashListWithDeterminism(ContentHashList.Random(), CacheDeterminism.None); return RunTestAsync(context, funcAsync: async (store, session) => { await session.AddOrGetContentHashListAsync(context, strongFingerprint1, contentHashListWithDeterminism1, Token).ShouldBeSuccess(); _clock.Increment(); // Notice we don't increment the clock here await session.AddOrGetContentHashListAsync(context, strongFingerprint2, contentHashListWithDeterminism2, Token).ShouldBeSuccess(); RocksDbContentLocationDatabase database = (store as RocksDbMemoizationStore)?.RocksDbDatabase; Contract.Assert(database != null); var ctx = new OperationContext(context); database.GarbageCollect(ctx); var r1 = database.GetContentHashList(ctx, strongFingerprint1).ShouldBeSuccess().ContentHashListWithDeterminism; r1.ContentHashList.Should().BeNull(); r1.Determinism.Should().Be(CacheDeterminism.None); var r2 = database.GetContentHashList(ctx, strongFingerprint2).ShouldBeSuccess().ContentHashListWithDeterminism; r2.Should().BeEquivalentTo(contentHashListWithDeterminism2); database.Counters[ContentLocationDatabaseCounters.GarbageCollectMetadataEntriesRemoved].Value.Should().Be(1); database.Counters[ContentLocationDatabaseCounters.GarbageCollectMetadataEntriesScanned].Value.Should().Be(2); }, createStoreFunc: createStoreInternal); // This is needed because type errors arise if you inline IMemoizationStore createStoreInternal(DisposableDirectory disposableDirectory) { return CreateStore(testDirectory: disposableDirectory, configMutator: (configuration) => { configuration.MetadataGarbageCollectionEnabled = true; configuration.MetadataGarbageCollectionMaximumNumberOfEntriesToKeep = 1; // Disables automatic GC configuration.GarbageCollectionInterval = Timeout.InfiniteTimeSpan; }); } } [Fact] public Task GarbageCollectionDeletesInLruOrder() { var context = new Context(Logger); var weakFingerprint = Fingerprint.Random(); var selector1 = Selector.Random(); var strongFingerprint1 = new StrongFingerprint(weakFingerprint, selector1); var contentHashListWithDeterminism1 = new ContentHashListWithDeterminism(ContentHashList.Random(), CacheDeterminism.None); var selector2 = Selector.Random(); var strongFingerprint2 = new StrongFingerprint(weakFingerprint, selector2); var contentHashListWithDeterminism2 = new ContentHashListWithDeterminism(ContentHashList.Random(), CacheDeterminism.None); return RunTestAsync(context, funcAsync: async (store, session) => { await session.AddOrGetContentHashListAsync(context, strongFingerprint1, contentHashListWithDeterminism1, Token).ShouldBeSuccess(); _clock.Increment(); await session.AddOrGetContentHashListAsync(context, strongFingerprint2, contentHashListWithDeterminism2, Token).ShouldBeSuccess(); _clock.Increment(); // Force update the last access time of the first fingerprint await session.GetContentHashListAsync(context, strongFingerprint1, Token).ShouldBeSuccess(); _clock.Increment(); RocksDbContentLocationDatabase database = (store as RocksDbMemoizationStore)?.RocksDbDatabase; Contract.Assert(database != null); var ctx = new OperationContext(context); database.GarbageCollect(ctx); var r1 = database.GetContentHashList(ctx, strongFingerprint1).ShouldBeSuccess().ContentHashListWithDeterminism; r1.Should().BeEquivalentTo(contentHashListWithDeterminism1); var r2 = database.GetContentHashList(ctx, strongFingerprint2).ShouldBeSuccess().ContentHashListWithDeterminism; r2.ContentHashList.Should().BeNull(); r2.Determinism.Should().Be(CacheDeterminism.None); database.Counters[ContentLocationDatabaseCounters.GarbageCollectMetadataEntriesRemoved].Value.Should().Be(1); database.Counters[ContentLocationDatabaseCounters.GarbageCollectMetadataEntriesScanned].Value.Should().Be(2); }, createStoreFunc: createStoreInternal); // This is needed because type errors arise if you inline IMemoizationStore createStoreInternal(DisposableDirectory disposableDirectory) { return CreateStore(testDirectory: disposableDirectory, configMutator: (configuration) => { configuration.MetadataGarbageCollectionEnabled = true; configuration.MetadataGarbageCollectionMaximumNumberOfEntriesToKeep = 1; // Disables automatic GC configuration.GarbageCollectionInterval = Timeout.InfiniteTimeSpan; }); } } } }
52.865217
157
0.661156
[ "MIT" ]
mmiller-msft/BuildXL
Public/Src/Cache/MemoizationStore/Test/Sessions/RocksDbMemoizationSessionTests.cs
12,161
C#
using AutoItX3Lib; namespace addresssbook_tests_autoit { public class HelperBase { protected ApplicationManager manager; protected string WINTITLE; protected AutoItX3 aux; public HelperBase(ApplicationManager manager) { this.manager = manager; this.aux = manager.Aux; WINTITLE = ApplicationManager.WINTITLE; } } }
24.176471
53
0.627737
[ "Apache-2.0" ]
omelen/csharp_training
addresssbook_tests_autoit/addresssbook_tests_autoit/appmanager/HelperBase.cs
413
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Billing.V20180709.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class BillResourceSummary : AbstractModel { /// <summary> /// 产品 /// </summary> [JsonProperty("BusinessCodeName")] public string BusinessCodeName{ get; set; } /// <summary> /// 子产品 /// </summary> [JsonProperty("ProductCodeName")] public string ProductCodeName{ get; set; } /// <summary> /// 计费模式 /// </summary> [JsonProperty("PayModeName")] public string PayModeName{ get; set; } /// <summary> /// 项目 /// </summary> [JsonProperty("ProjectName")] public string ProjectName{ get; set; } /// <summary> /// 地域 /// </summary> [JsonProperty("RegionName")] public string RegionName{ get; set; } /// <summary> /// 可用区 /// </summary> [JsonProperty("ZoneName")] public string ZoneName{ get; set; } /// <summary> /// 资源实例ID /// </summary> [JsonProperty("ResourceId")] public string ResourceId{ get; set; } /// <summary> /// 资源实例名称 /// </summary> [JsonProperty("ResourceName")] public string ResourceName{ get; set; } /// <summary> /// 交易类型 /// </summary> [JsonProperty("ActionTypeName")] public string ActionTypeName{ get; set; } /// <summary> /// 订单ID /// </summary> [JsonProperty("OrderId")] public string OrderId{ get; set; } /// <summary> /// 扣费时间 /// </summary> [JsonProperty("PayTime")] public string PayTime{ get; set; } /// <summary> /// 开始使用时间 /// </summary> [JsonProperty("FeeBeginTime")] public string FeeBeginTime{ get; set; } /// <summary> /// 结束使用时间 /// </summary> [JsonProperty("FeeEndTime")] public string FeeEndTime{ get; set; } /// <summary> /// 配置描述 /// </summary> [JsonProperty("ConfigDesc")] public string ConfigDesc{ get; set; } /// <summary> /// 扩展字段1 /// </summary> [JsonProperty("ExtendField1")] public string ExtendField1{ get; set; } /// <summary> /// 扩展字段2 /// </summary> [JsonProperty("ExtendField2")] public string ExtendField2{ get; set; } /// <summary> /// 原价,单位为元 /// </summary> [JsonProperty("TotalCost")] public string TotalCost{ get; set; } /// <summary> /// 折扣率 /// </summary> [JsonProperty("Discount")] public string Discount{ get; set; } /// <summary> /// 优惠类型 /// </summary> [JsonProperty("ReduceType")] public string ReduceType{ get; set; } /// <summary> /// 优惠后总价,单位为元 /// </summary> [JsonProperty("RealTotalCost")] public string RealTotalCost{ get; set; } /// <summary> /// 代金券支付金额,单位为元 /// </summary> [JsonProperty("VoucherPayAmount")] public string VoucherPayAmount{ get; set; } /// <summary> /// 现金账户支付金额,单位为元 /// </summary> [JsonProperty("CashPayAmount")] public string CashPayAmount{ get; set; } /// <summary> /// 赠送账户支付金额,单位为元 /// </summary> [JsonProperty("IncentivePayAmount")] public string IncentivePayAmount{ get; set; } /// <summary> /// 扩展字段3 /// </summary> [JsonProperty("ExtendField3")] public string ExtendField3{ get; set; } /// <summary> /// 扩展字段4 /// </summary> [JsonProperty("ExtendField4")] public string ExtendField4{ get; set; } /// <summary> /// 扩展字段5 /// </summary> [JsonProperty("ExtendField5")] public string ExtendField5{ get; set; } /// <summary> /// 内部实现,用户禁止调用 /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "BusinessCodeName", this.BusinessCodeName); this.SetParamSimple(map, prefix + "ProductCodeName", this.ProductCodeName); this.SetParamSimple(map, prefix + "PayModeName", this.PayModeName); this.SetParamSimple(map, prefix + "ProjectName", this.ProjectName); this.SetParamSimple(map, prefix + "RegionName", this.RegionName); this.SetParamSimple(map, prefix + "ZoneName", this.ZoneName); this.SetParamSimple(map, prefix + "ResourceId", this.ResourceId); this.SetParamSimple(map, prefix + "ResourceName", this.ResourceName); this.SetParamSimple(map, prefix + "ActionTypeName", this.ActionTypeName); this.SetParamSimple(map, prefix + "OrderId", this.OrderId); this.SetParamSimple(map, prefix + "PayTime", this.PayTime); this.SetParamSimple(map, prefix + "FeeBeginTime", this.FeeBeginTime); this.SetParamSimple(map, prefix + "FeeEndTime", this.FeeEndTime); this.SetParamSimple(map, prefix + "ConfigDesc", this.ConfigDesc); this.SetParamSimple(map, prefix + "ExtendField1", this.ExtendField1); this.SetParamSimple(map, prefix + "ExtendField2", this.ExtendField2); this.SetParamSimple(map, prefix + "TotalCost", this.TotalCost); this.SetParamSimple(map, prefix + "Discount", this.Discount); this.SetParamSimple(map, prefix + "ReduceType", this.ReduceType); this.SetParamSimple(map, prefix + "RealTotalCost", this.RealTotalCost); this.SetParamSimple(map, prefix + "VoucherPayAmount", this.VoucherPayAmount); this.SetParamSimple(map, prefix + "CashPayAmount", this.CashPayAmount); this.SetParamSimple(map, prefix + "IncentivePayAmount", this.IncentivePayAmount); this.SetParamSimple(map, prefix + "ExtendField3", this.ExtendField3); this.SetParamSimple(map, prefix + "ExtendField4", this.ExtendField4); this.SetParamSimple(map, prefix + "ExtendField5", this.ExtendField5); } } }
32.283105
93
0.56662
[ "Apache-2.0" ]
YuanXiaoLcx/tencentcloud-sdk-dotnet
TencentCloud/Billing/V20180709/Models/BillResourceSummary.cs
7,360
C#
// Copyright (c) 2019-2021 ReactiveUI Association Incorporated. All rights reserved. // ReactiveUI Association Incorporated licenses this file to you under the MIT license. // See the LICENSE file in the project root for full license information. using System.Collections.Generic; namespace ReactiveMarbles.PropertyChanged.SourceGenerator { internal sealed record ExtensionClassDatum : ClassDatum { public ExtensionClassDatum(string name, IEnumerable<MethodDatum> methodData) : base(name, methodData) { } } }
32.941176
87
0.741071
[ "MIT" ]
sucrose0413/PropertyChanged
src/ReactiveMarbles.PropertyChanged.SourceGenerator/TransientHelpers/ExtensionClassDatum.cs
562
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 importexport-2010-06-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ImportExport.Model { /// <summary> /// Output structure for the CancelJob operation. /// </summary> public partial class CancelJobResponse : AmazonWebServiceResponse { private bool? _success; /// <summary> /// Gets and sets the property Success. /// </summary> public bool Success { get { return this._success.GetValueOrDefault(); } set { this._success = value; } } // Check to see if Success property is set internal bool IsSetSuccess() { return this._success.HasValue; } } }
29.333333
111
0.646465
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/ImportExport/Generated/Model/CancelJobResponse.cs
1,584
C#
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2009, 2013 Oracle and/or its affiliates. All rights reserved. * */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using NUnit.Framework; using BerkeleyDB; namespace CsharpAPITest { [TestFixture] public class CursorTest : CSharpTestFixture { private DatabaseEnvironment paramEnv; private BTreeDatabase paramDB; private Transaction readTxn; private Transaction updateTxn; private EventWaitHandle signal; private delegate void CursorMoveFuncDelegate( Cursor cursor, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lockingInfo); private CursorMoveFuncDelegate cursorFunc; [TestFixtureSetUp] public void SetUpTestFixture() { testFixtureName = "CursorTest"; base.SetUpTestfixture(); } [Test] public void TestAdd() { BTreeDatabase db; BTreeCursor cursor; testName = "TestAdd"; SetUpTest(true); // Open a database and a cursor. GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Add a record and confirm that it exists. AddOneByCursor(db, cursor); // Intend to insert pair to a wrong position. KeyValuePair<DatabaseEntry, DatabaseEntry> pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>( new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("key")), new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("data"))); try { try { cursor.Add(pair, Cursor.InsertLocation.AFTER); throw new TestException(); } catch (ArgumentException) {} try { cursor.Add(pair, Cursor.InsertLocation.BEFORE); throw new TestException(); } catch (ArgumentException) {} } finally { cursor.Close(); db.Close(); } } [Test] public void TestCompare() { BTreeDatabase db; BTreeCursor dbc1, dbc2; DatabaseEntry data, key; testName = "TestCompare"; SetUpTest(true); // Open a database and a cursor. Then close it. GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out dbc1); dbc2 = db.Cursor(); for (int i = 0; i < 10; i++) { key = new DatabaseEntry(BitConverter.GetBytes(i)); data = new DatabaseEntry(BitConverter.GetBytes(i)); db.Put(key, data); } key = new DatabaseEntry(BitConverter.GetBytes(5)); Assert.IsTrue(dbc1.Move(key, true)); Assert.IsTrue(dbc2.Move(key, true)); Assert.IsTrue(dbc1.Compare(dbc2)); Assert.IsTrue(dbc1.MoveNext()); Assert.IsFalse(dbc1.Compare(dbc2)); dbc1.Close(); dbc2.Close(); db.Close(); } [Test] public void TestClose() { BTreeDatabase db; BTreeCursor cursor; testName = "TestClose"; SetUpTest(true); // Open a database and a cursor. Then close it. GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); cursor.Close(); db.Close(); } [Test] public void TestCloseResmgr() { testName = "TestCloseResmgr"; SetUpTest(true); TestCloseResmgr_int(true); TestCloseResmgr_int(false); } void TestCloseResmgr_int(bool havetxn) { BTreeDatabase db; BTreeCursor cursor, csr; CursorConfig cursorConfig; DatabaseEnvironment env; Transaction txn; DatabaseEntry key, data; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; txn = null; cursorConfig = new CursorConfig(); // Open an environment, a database and a cursor. if (havetxn) GetCursorInBtreeDBInTDS(testHome, testName, cursorConfig, out env, out db, out cursor, out txn); else GetCursorInBtreeDB(testHome, testName, cursorConfig, out env, out db, out cursor); // Add a record to db via cursor. key = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")); data = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("data")); pair = new KeyValuePair<DatabaseEntry,DatabaseEntry> (key, data); byte []kbytes; byte []dbytes; for (int i = 0; i < 100; i++) { kbytes = ASCIIEncoding.ASCII. GetBytes("key" + i); dbytes = ASCIIEncoding.ASCII. GetBytes("data" + i); key.Data = kbytes; data.Data = dbytes; cursor.Add(pair); } // Do not close cursor. csr = db.Cursor(cursorConfig, txn); while (csr.MoveNext()) { // Do nothing for now. } // Do not close csr. if (havetxn && txn != null) txn.Commit(); env.CloseForceSync(); } [Test] public void TestCount() { BTreeDatabase db; BTreeCursor cursor; testName = "TestCount"; SetUpTest(true); // Write one record into database with cursor. GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); AddOneByCursor(db, cursor); /* * Confirm that that the count operation returns 1 as * the number of records in the database. */ Assert.AreEqual(1, cursor.Count()); cursor.Close(); db.Close(); } [Test] public void TestCurrent() { BTreeDatabase db; BTreeCursor cursor; testName = "TestCurrent"; SetUpTest(true); // Write a record into database with cursor. GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); AddOneByCursor(db, cursor); /* * Confirm the current record that the cursor * points to is the one that just added by the * cursor. */ Assert.IsTrue(cursor.MoveFirst()); Assert.AreEqual( ASCIIEncoding.ASCII.GetBytes("key"), cursor.Current.Key.Data); Assert.AreEqual( ASCIIEncoding.ASCII.GetBytes("data"), cursor.Current.Value.Data); cursor.Close(); db.Close(); } [Test] public void TestDelete() { BTreeDatabase db; BTreeCursor cursor; testName = "TestDelete"; SetUpTest(true); // Write a record into database with cursor. GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); AddOneByCursor(db, cursor); // Delete the current record. cursor.Delete(); // Confirm that the record no longer exists in the db. Assert.AreEqual(0, cursor.Count()); cursor.Close(); db.Close(); } [Test] public void TestDispose() { BTreeDatabase db; BTreeCursor cursor; testName = "TestDispose"; SetUpTest(true); // Write a record into database with cursor. GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Dispose the cursor. cursor.Dispose(); db.Close(); } [Test] public void TestDuplicate() { DatabaseEnvironment env; BTreeDatabase db; BTreeCursor cursor; Transaction txn; testName = "TestDuplicate"; SetUpTest(true); GetCursorInBtreeDBInTDS(testHome, testName, new CursorConfig(), out env, out db, out cursor, out txn); for (int i = 0; i < 10; i++) cursor.Add(new KeyValuePair< DatabaseEntry, DatabaseEntry>( new DatabaseEntry(BitConverter.GetBytes(i)), new DatabaseEntry(BitConverter.GetBytes(i)))); // Duplicate the cursor and keep its position. BTreeCursor newCursor = cursor.Duplicate(true); Assert.AreEqual(newCursor.Current.Key, cursor.Current.Key); Assert.AreEqual(newCursor.Current.Key, cursor.Current.Key); cursor.Close(); newCursor.Close(); db.Close(); txn.Commit(); env.Close(); } [Test] public void TestIsolationDegree() { BTreeDatabase db; BTreeCursor cursor; CursorConfig cursorConfig; DatabaseEnvironment env; Transaction txn; testName = "TestIsolationDegree"; SetUpTest(true); Isolation[] isolationDegrees = new Isolation[3]; isolationDegrees[0] = Isolation.DEGREE_ONE; isolationDegrees[1] = Isolation.DEGREE_TWO; isolationDegrees[2] = Isolation.DEGREE_THREE; IsolationDelegate[] delegates = { new IsolationDelegate(CursorReadUncommited), new IsolationDelegate(CursorReadCommited), new IsolationDelegate(CursorRead)}; cursorConfig = new CursorConfig(); for (int i = 0; i < 3; i++) { cursorConfig.IsolationDegree = isolationDegrees[i]; GetCursorInBtreeDBInTDS(testHome + "/" + i.ToString(), testName, cursorConfig, out env, out db, out cursor, out txn); cursor.Close(); db.Close(); txn.Commit(); env.Close(); } } public delegate void IsolationDelegate( DatabaseEnvironment env, BTreeDatabase db, Cursor cursor, Transaction txn); /* * Configure a transactional cursor to have degree 2 * isolation, which permits data read by this cursor * to be deleted prior to the commit of the transaction * for this cursor. */ public void CursorReadCommited( DatabaseEnvironment env, BTreeDatabase db, Cursor cursor, Transaction txn) { Console.WriteLine("CursorReadCommited"); } /* * Configure a transactional cursor to have degree 1 * isolation. The cursor's read operations could return * modified but not yet commited data. */ public void CursorReadUncommited( DatabaseEnvironment env, BTreeDatabase db, Cursor cursor, Transaction txn) { Console.WriteLine("CursorReadUncommited"); } /* * Only return committed data. */ public void CursorRead( DatabaseEnvironment env, BTreeDatabase db, Cursor cursor, Transaction txn) { Console.WriteLine("CursorRead"); } [Test] public void TestMoveToExactKey() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMoveToExactKey"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Add one record into database. DatabaseEntry key = new DatabaseEntry( BitConverter.GetBytes((int)0)); DatabaseEntry data = new DatabaseEntry( BitConverter.GetBytes((int)0)); KeyValuePair<DatabaseEntry, DatabaseEntry> pair = new KeyValuePair<DatabaseEntry,DatabaseEntry>( key, data); cursor.Add(pair); // Move the cursor exactly to the specified key. MoveCursor(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMoveToExactPair() { BTreeDatabase db; BTreeCursor cursor; DatabaseEntry key, data; testName = "TestMoveToExactPair"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Add one record into database. key = new DatabaseEntry( BitConverter.GetBytes((int)0)); data = new DatabaseEntry( BitConverter.GetBytes((int)0)); KeyValuePair<DatabaseEntry, DatabaseEntry> pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data); cursor.Add(pair); // Move the cursor exactly to the specified key/data pair. MoveCursor(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMoveWithRMW() { testName = "TestMoveWithRMW"; SetUpTest(true); // Use MoveCursor() as its move function. cursorFunc = new CursorMoveFuncDelegate(MoveCursor); // Move to a specified key and a key/data pair. MoveWithRMW(testHome, testName); } [Test] public void TestMoveFirst() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMoveFirst"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); AddOneByCursor(db, cursor); // Move to the first record. MoveCursorToFirst(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMoveFirstWithRMW() { testName = "TestMoveFirstWithRMW"; SetUpTest(true); // Use MoveCursorToFirst() as its move function. cursorFunc = new CursorMoveFuncDelegate(MoveCursorToFirst); // Read the first record with write lock. MoveWithRMW(testHome, testName); } [Test] public void TestMoveLast() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMoveLast"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); AddOneByCursor(db, cursor); // Move the cursor to the last record. MoveCursorToLast(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMoveLastWithRMW() { testName = "TestMoveLastWithRMW"; SetUpTest(true); // Use MoveCursorToLast() as its move function. cursorFunc = new CursorMoveFuncDelegate(MoveCursorToLast); // Read the last recod with write lock. MoveWithRMW(testHome, testName); } [Test] public void TestMoveNext() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMoveNext"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Put ten records to the database. for (int i = 0; i < 10; i++) db.Put(new DatabaseEntry(BitConverter.GetBytes(i)), new DatabaseEntry(BitConverter.GetBytes(i))); // Move the cursor from the first record to the fifth. MoveCursorToNext(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMoveNextWithRMW() { testName = "TestMoveLastWithRMW"; SetUpTest(true); // Use MoveCursorToNext() as its move function. cursorFunc = new CursorMoveFuncDelegate( MoveCursorToNext); /* * Read the first record to the fifth record with * write lock. */ MoveWithRMW(testHome, testName); } [Test] public void TestMoveNextDuplicate() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMoveNextDuplicate"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Add ten duplicate records to the database. for (int i = 0; i < 10; i++) db.Put(new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")), new DatabaseEntry( BitConverter.GetBytes(i))); /* * Move the cursor from one duplicate record to * another duplicate one. */ MoveCursorToNextDuplicate(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMoveNextDuplicateWithRMW() { testName = "TestMoveNextDuplicateWithRMW"; SetUpTest(true); /* * Use MoveCursorToNextDuplicate() as its * move function. */ cursorFunc = new CursorMoveFuncDelegate( MoveCursorToNextDuplicate); /* * Read the first record to the fifth record with * write lock. */ MoveWithRMW(testHome, testName); } [Test] public void TestMoveNextUnique() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMoveNextUnique"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Add ten different records to the database. for (int i = 0; i < 10; i++) db.Put(new DatabaseEntry( BitConverter.GetBytes(i)), new DatabaseEntry( BitConverter.GetBytes(i))); // Move to five unique records. MoveCursorToNextUnique(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMoveNextUniqueWithRMW() { testName = "TestMoveNextUniqueWithRMW"; SetUpTest(true); /* * Use MoveCursorToNextUnique() as its * move function. */ cursorFunc = new CursorMoveFuncDelegate( MoveCursorToNextUnique); /* * Move to five unique records. */ MoveWithRMW(testHome, testName); } [Test] public void TestMovePrev() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMovePrev"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Add ten records to the database. for (int i = 0; i < 10; i++) AddOneByCursor(db, cursor); // Move the cursor to previous five records MoveCursorToPrev(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMovePrevWithRMW() { testName = "TestMovePrevWithRMW"; SetUpTest(true); /* * Use MoveCursorToNextDuplicate() as its * move function. */ cursorFunc = new CursorMoveFuncDelegate( MoveCursorToPrev); // Read previous record in write lock. MoveWithRMW(testHome, testName); } [Test] public void TestMovePrevDuplicate() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMovePrevDuplicate"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Add ten records to the database. for (int i = 0; i < 10; i++) AddOneByCursor(db, cursor); // Move the cursor to previous duplicate records. MoveCursorToPrevDuplicate(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMovePrevDuplicateWithRMW() { testName = "TestMovePrevDuplicateWithRMW"; SetUpTest(true); /* * Use MoveCursorToNextDuplicate() as its * move function. */ cursorFunc = new CursorMoveFuncDelegate( MoveCursorToPrevDuplicate); // Read the previous duplicate record in write lock. MoveWithRMW(testHome, testName); } [Test] public void TestMovePrevUnique() { BTreeDatabase db; BTreeCursor cursor; testName = "TestMovePrevUnique"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Add ten records to the database. for (int i = 0; i < 10; i++) db.Put(new DatabaseEntry(BitConverter.GetBytes(i)), new DatabaseEntry(BitConverter.GetBytes(i))); // Move the cursor to previous unique records. MoveCursorToPrevUnique(cursor, 1, 1, 2, 2, null); cursor.Close(); db.Close(); } [Test] public void TestMovePrevUniqueWithRMW() { testName = "TestMovePrevDuplicateWithRMW"; SetUpTest(true); /* * Use MoveCursorToPrevUnique() as its * move function. */ cursorFunc = new CursorMoveFuncDelegate( MoveCursorToPrevUnique); // Read the previous unique record in write lock. MoveWithRMW(testHome, testName); } [Test] public void TestPartialPut() { testName = "TestPartialPut"; SetUpTest(true); BTreeDatabaseConfig cfg = new BTreeDatabaseConfig(); cfg.Creation = CreatePolicy.IF_NEEDED; BTreeDatabase db = BTreeDatabase.Open( testHome + "/" + testName, cfg); PopulateDb(ref db); /* * Partially replace the first byte in the current * data with 'a', and verify that the first byte in * the retrieved current data is 'a'. */ BTreeCursor cursor = db.Cursor(); byte[] bytes = new byte[1]; bytes[0] = (byte)'a'; DatabaseEntry data = new DatabaseEntry(bytes, 0, 1); KeyValuePair<DatabaseEntry, DatabaseEntry> pair; while(cursor.MoveNext()) { cursor.Overwrite(data); Assert.IsTrue(cursor.Refresh()); pair = cursor.Current; Assert.AreEqual((byte)'a', pair.Value.Data[0]); } cursor.Close(); db.Close(); } private void PopulateDb(ref BTreeDatabase db) { if (db == null) { BTreeDatabaseConfig cfg = new BTreeDatabaseConfig(); cfg.Creation = CreatePolicy.IF_NEEDED; db = BTreeDatabase.Open( testHome + "/" + testName, cfg); } for (int i = 0; i < 100; i++) db.Put( new DatabaseEntry(BitConverter.GetBytes(i)), new DatabaseEntry(BitConverter.GetBytes(i))); } [Test] public void TestPriority() { CachePriority[] priorities; CursorConfig cursorConfig; testName = "TestPriority"; SetUpTest(true); cursorConfig = new CursorConfig(); priorities = new CachePriority[6]; priorities[0] = CachePriority.DEFAULT; priorities[1] = CachePriority.HIGH; priorities[2] = CachePriority.LOW; priorities[3] = CachePriority.VERY_HIGH; priorities[4] = CachePriority.VERY_LOW; priorities[5] = null; for (int i = 0; i < 6; i++) { if (priorities[i] != null) { cursorConfig.Priority = priorities[i]; Assert.AreEqual(priorities[i], cursorConfig.Priority); } GetCursorWithConfig(testHome + "/" + testName + ".db", DatabaseType.BTREE.ToString(), cursorConfig, DatabaseType.BTREE); GetCursorWithConfig(testHome + "/" + testName + ".db", DatabaseType.HASH.ToString(), cursorConfig, DatabaseType.HASH); GetCursorWithConfig(testHome + "/" + testName + ".db", DatabaseType.QUEUE.ToString(), cursorConfig, DatabaseType.QUEUE); GetCursorWithConfig(testHome + "/" + testName + ".db", DatabaseType.RECNO.ToString(), cursorConfig, DatabaseType.RECNO); } } private void GetCursorWithConfig(string dbFile, string dbName, CursorConfig cfg, DatabaseType type) { Database db; Cursor cursor; Configuration.ClearDir(testHome); if (type == DatabaseType.BTREE) { BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; db = BTreeDatabase.Open(dbFile, dbName, dbConfig); cursor = ((BTreeDatabase)db).Cursor(cfg); } else if (type == DatabaseType.HASH) { HashDatabaseConfig dbConfig = new HashDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; db = (HashDatabase)HashDatabase.Open(dbFile, dbName, dbConfig); cursor = ((HashDatabase)db).Cursor(cfg); } else if (type == DatabaseType.QUEUE) { QueueDatabaseConfig dbConfig = new QueueDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Length = 100; db = QueueDatabase.Open(dbFile, dbConfig); cursor = ((QueueDatabase)db).Cursor(cfg); } else if (type == DatabaseType.RECNO) { RecnoDatabaseConfig dbConfig = new RecnoDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; db = RecnoDatabase.Open(dbFile, dbName, dbConfig); cursor = ((RecnoDatabase)db).Cursor(cfg); } else throw new TestException(); if (cfg.Priority != null) Assert.AreEqual(cursor.Priority, cfg.Priority); else Assert.AreEqual(CachePriority.DEFAULT, cursor.Priority); Cursor dupCursor = cursor.Duplicate(false); Assert.AreEqual(cursor.Priority, dupCursor.Priority); cursor.Close(); db.Close(); } [Test] public void TestRefresh() { BTreeDatabase db; BTreeCursor cursor; DatabaseEnvironment env; Transaction txn; testName = "TestRefresh"; SetUpTest(true); GetCursorInBtreeDBWithoutEnv(testHome, testName, out db, out cursor); // Write a record with cursor and Refresh the cursor. MoveCursorToCurrentRec(cursor, 1, 1, 2, 2, null); cursor.Dispose(); db.Dispose(); Configuration.ClearDir(testHome); GetCursorInBtreeDBInTDS(testHome, testName, null, out env, out db, out cursor, out txn); LockingInfo lockingInfo = new LockingInfo(); lockingInfo.IsolationDegree = Isolation.DEGREE_ONE; MoveCursorToCurrentRec(cursor, 1, 1, 2, 2, lockingInfo); cursor.Close(); txn.Commit(); db.Close(); env.Close(); } [Test] public void TestRefreshWithRMW() { testName = "TestRefreshWithRMW"; SetUpTest(true); cursorFunc = new CursorMoveFuncDelegate( MoveCursorToCurrentRec); // Read the previous unique record in write lock. MoveWithRMW(testHome, testName); } [Test] public void TestSnapshotIsolation() { BTreeDatabaseConfig dbConfig; DatabaseEntry key, data; DatabaseEnvironmentConfig envConfig; Thread readThread, updateThread; Transaction txn; updateTxn = null; readTxn = null; paramDB = null; paramEnv = null; testName = "TestSnapshotIsolation"; SetUpTest(true); /* * Open environment with DB_MULTIVERSION * which is required by DB_TXN_SNAPSHOT. */ envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseMVCC = true; envConfig.UseTxns = true; envConfig.UseMPool = true; envConfig.UseLocking = true; envConfig.TxnTimeout = 1000; paramEnv = DatabaseEnvironment.Open( testHome, envConfig); paramEnv.DetectDeadlocks(DeadlockPolicy.YOUNGEST); /* * Open a transactional database and put 1000 records * into it within transaction. */ txn = paramEnv.BeginTransaction(); dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.UseMVCC = true; dbConfig.Env = paramEnv; paramDB = BTreeDatabase.Open( testName + ".db", dbConfig, txn); for (int i = 0; i < 256; i++) { key = new DatabaseEntry( BitConverter.GetBytes(i)); data = new DatabaseEntry( BitConverter.GetBytes(i)); paramDB.Put(key, data, txn); } txn.Commit(); /* * Begin two threads, read and update thread. * The update thread runs a update transaction * using full read/write locking. The read thread * set DB_TXN_SNAPSHOT on read-only cursor. */ readThread = new Thread(new ThreadStart(ReadTxn)); updateThread = new Thread(new ThreadStart(UpdateTxn)); updateThread.Start(); Thread.Sleep(1000); readThread.Start(); readThread.Join(); updateThread.Join(); // Commit transacion in both two threads. if (updateTxn != null) updateTxn.Commit(); if (readTxn != null) readTxn.Commit(); /* * Confirm that the overwrite operation works. */ ConfirmOverwrite(); paramDB.Close(); paramEnv.Close(); } public void ReadTxn() { // Get a new transaction for reading the db. TransactionConfig txnConfig = new TransactionConfig(); txnConfig.Snapshot = true; readTxn = paramEnv.BeginTransaction( txnConfig); // Get a new cursor for putting record into db. CursorConfig cursorConfig = new CursorConfig(); cursorConfig.WriteCursor = false; BTreeCursor cursor = paramDB.Cursor( cursorConfig, readTxn); // Continually reading record from db. try { Assert.IsTrue(cursor.MoveFirst()); int i = 0; do { Assert.AreEqual( BitConverter.ToInt32( cursor.Current.Key.Data, 0), BitConverter.ToInt32( cursor.Current.Value.Data, 0)); } while (i <= 1000 && cursor.MoveNext()); } catch (DeadlockException) { } finally { cursor.Close(); } } public void UpdateTxn() { int int32Value; DatabaseEntry data; // Get a new transaction for updating the db. TransactionConfig txnConfig = new TransactionConfig(); txnConfig.IsolationDegree = Isolation.DEGREE_THREE; updateTxn = paramEnv.BeginTransaction(txnConfig); // Continually putting record to db. BTreeCursor cursor = paramDB.Cursor(updateTxn); // Move the cursor to the first record. Assert.IsTrue(cursor.MoveFirst()); int i = 0; try { do { int32Value = BitConverter.ToInt32( cursor.Current.Value.Data, 0); data = new DatabaseEntry( BitConverter.GetBytes(int32Value - 1)); cursor.Overwrite(data); } while (i <= 1000 && cursor.MoveNext()); } catch (DeadlockException) { } finally { cursor.Close(); } } [Test] public void TestWriteCursor() { BTreeCursor cursor; BTreeDatabase db; CursorConfig cursorConfig; DatabaseEnvironment env; testName = "TestWriteCursor"; SetUpTest(true); cursorConfig = new CursorConfig(); cursorConfig.WriteCursor = true; GetCursorInBtreeDBInCDS(testHome, testName, cursorConfig, out env, out db, out cursor); /* * Add a record by cursor to the database. If the * WriteCursor doesn't work, exception will be * throwed in the environment which is configured * with DB_INIT_CDB. */ try { AddOneByCursor(db, cursor); } catch (DatabaseException) { throw new TestException(); } finally { cursor.Close(); db.Close(); env.Close(); } } public void ConfirmOverwrite() { Transaction confirmTxn = paramEnv.BeginTransaction(); BTreeCursor cursor = paramDB.Cursor(confirmTxn); int i = 0; Assert.IsTrue(cursor.MoveFirst()); do { Assert.AreNotEqual( cursor.Current.Key.Data, cursor.Current.Value.Data); } while (i <= 1000 && cursor.MoveNext()); cursor.Close(); confirmTxn.Commit(); } public static void AddOneByCursor(Database db, Cursor cursor) { DatabaseEntry key, data; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; // Add a record to db via cursor. key = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("key")); data = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("data")); pair = new KeyValuePair<DatabaseEntry,DatabaseEntry>(key, data); cursor.Add(pair); // Confirm that the record has been put to the database. Assert.IsTrue(db.Exists(key)); } public static void GetCursorInBtreeDBWithoutEnv( string home, string name, out BTreeDatabase db, out BTreeCursor cursor) { string dbFileName = home + "/" + name + ".db"; BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Duplicates = DuplicatesPolicy.UNSORTED; db = BTreeDatabase.Open(dbFileName, dbConfig); cursor = db.Cursor(); } public static void GetCursorInBtreeDBInTDS( string home, string name, CursorConfig cursorConfig, out DatabaseEnvironment env, out BTreeDatabase db, out BTreeCursor cursor, out Transaction txn) { string dbFileName = name + ".db"; Configuration.ClearDir(home); // Open an environment. DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseMPool = true; envConfig.UseTxns = true; envConfig.NoMMap = false; envConfig.UseLocking = true; env = DatabaseEnvironment.Open(home, envConfig); // Begin a transaction. txn = env.BeginTransaction(); /* * Open an btree database. The underlying database * should be opened with ReadUncommitted if the * cursor's isolation degree will be set to be 1. */ BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Env = env; if (cursorConfig != null && cursorConfig.IsolationDegree == Isolation.DEGREE_ONE) dbConfig.ReadUncommitted = true; db = BTreeDatabase.Open(dbFileName, dbConfig, txn); // Get a cursor in the transaction. if (cursorConfig != null) cursor = db.Cursor(cursorConfig, txn); else cursor = db.Cursor(txn); } public static void GetCursorInBtreeDB( string home, string name, CursorConfig cursorConfig, out DatabaseEnvironment env, out BTreeDatabase db, out BTreeCursor cursor) { string dbFileName = name + ".db"; Configuration.ClearDir(home); // Open an environment. DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseMPool = true; envConfig.UseTxns = true; envConfig.NoMMap = false; envConfig.UseLocking = true; env = DatabaseEnvironment.Open(home, envConfig); /* * Open an btree database. The underlying database * should be opened with ReadUncommitted if the * cursor's isolation degree will be set to be 1. */ BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Env = env; if (cursorConfig.IsolationDegree == Isolation.DEGREE_ONE) dbConfig.ReadUncommitted = true; db = BTreeDatabase.Open(dbFileName, dbConfig, null); // Get a cursor in the transaction. cursor = db.Cursor(cursorConfig, null); } // Get a cursor in CDS. public static void GetCursorInBtreeDBInCDS( string home, string name, CursorConfig cursorConfig, out DatabaseEnvironment env, out BTreeDatabase db, out BTreeCursor cursor) { string dbFileName = name + ".db"; Configuration.ClearDir(home); // Open an environment. DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseCDB = true; envConfig.UseMPool = true; env = DatabaseEnvironment.Open(home, envConfig); /* * Open an btree database. The underlying database * should be opened with ReadUncommitted if the * cursor's isolation degree will be set to be 1. */ BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Env = env; if (cursorConfig.IsolationDegree == Isolation.DEGREE_ONE) dbConfig.ReadUncommitted = true; db = BTreeDatabase.Open(dbFileName, dbConfig); // Get a cursor in the transaction. cursor = db.Cursor(cursorConfig); } public void RdMfWt() { Transaction txn = paramEnv.BeginTransaction(); Cursor dbc = paramDB.Cursor(txn); try { LockingInfo lck = new LockingInfo(); lck.ReadModifyWrite = true; // Read record. cursorFunc(dbc, 1, 1, 2, 2, lck); // Block the current thread until event is set. signal.WaitOne(); // Write new records into database. DatabaseEntry key = new DatabaseEntry( BitConverter.GetBytes(55)); DatabaseEntry data = new DatabaseEntry( BitConverter.GetBytes(55)); dbc.Add(new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data)); dbc.Close(); txn.Commit(); } catch (DeadlockException) { dbc.Close(); txn.Abort(); } } public void MoveWithRMW(string home, string name) { paramEnv = null; paramDB = null; // Open the environment. DatabaseEnvironmentConfig envCfg = new DatabaseEnvironmentConfig(); envCfg.Create = true; envCfg.FreeThreaded = true; envCfg.UseLocking = true; envCfg.UseLogging = true; envCfg.UseMPool = true; envCfg.UseTxns = true; paramEnv = DatabaseEnvironment.Open(home, envCfg); // Open database in transaction. Transaction openTxn = paramEnv.BeginTransaction(); BTreeDatabaseConfig cfg = new BTreeDatabaseConfig(); cfg.Creation = CreatePolicy.ALWAYS; cfg.Env = paramEnv; cfg.FreeThreaded = true; cfg.PageSize = 4096; cfg.Duplicates = DuplicatesPolicy.UNSORTED; paramDB = BTreeDatabase.Open(name + ".db", cfg, openTxn); openTxn.Commit(); /* * Put 10 different, 2 duplicate and another different * records into database. */ Transaction txn = paramEnv.BeginTransaction(); for (int i = 0; i < 14; i++) { DatabaseEntry key, data; if (i == 10 || i == 11 || i == 12) { key = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")); data = new DatabaseEntry( BitConverter.GetBytes(i)); } else { key = new DatabaseEntry( BitConverter.GetBytes(i)); data = new DatabaseEntry( BitConverter.GetBytes(i)); } paramDB.Put(key, data, txn); } txn.Commit(); // Get a event wait handle. signal = new EventWaitHandle(false, EventResetMode.ManualReset); /* * Start RdMfWt() in two threads. RdMfWt() reads * and writes data into database. */ Thread t1 = new Thread(new ThreadStart(RdMfWt)); Thread t2 = new Thread(new ThreadStart(RdMfWt)); t1.Start(); t2.Start(); /* * Give both threads time to read before signalling * them to write. */ Thread.Sleep(1000); // Invoke the write operation in both threads. signal.Set(); // Return the number of deadlocks. while (t1.IsAlive || t2.IsAlive) { /* * Give both threads time to write before * counting the number of deadlocks. */ Thread.Sleep(1000); uint deadlocks = paramEnv.DetectDeadlocks( DeadlockPolicy.DEFAULT); // Confirm that there won't be any deadlock. Assert.AreEqual(0, deadlocks); } t1.Join(); t2.Join(); paramDB.Close(); paramEnv.Close(); } /* * Move the cursor to an exisiting key and key/data * pair with LockingInfo. */ public void MoveCursor(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { DatabaseEntry key, data; KeyValuePair<DatabaseEntry, DatabaseEntry> pair; key = new DatabaseEntry( BitConverter.GetBytes((int)0)); data = new DatabaseEntry( BitConverter.GetBytes((int)0)); pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data); if (lck == null) { // Move to an existing key. Assert.IsTrue(dbc.Move(key, true)); // Move to an existing key/data pair. Assert.IsTrue(dbc.Move(pair, true)); /* Move to an existing key, and return * partial data. */ data = new DatabaseEntry(dOffset, dLen); Assert.IsTrue(dbc.Move(key, data, true)); CheckPartial(null, 0, 0, dbc.Current.Value, dOffset, dLen); // Partially key match. byte[] partbytes = new byte[kLen]; for (int i = 0; i < kLen; i++) partbytes[i] = BitConverter.GetBytes( (int)1)[kOffset + i]; key = new DatabaseEntry(partbytes, kOffset, kLen); Assert.IsTrue(dbc.Move(key, false)); Assert.AreEqual(kLen, dbc.Current.Key.Data.Length); CheckPartial(dbc.Current.Key, kOffset, kLen, null, 0, 0); } else { // Move to an existing key. Assert.IsTrue(dbc.Move(key, true, lck)); // Move to an existing key/data pair. Assert.IsTrue(dbc.Move(pair, true, lck)); /* * Move to an existing key, and return * partial data. */ data = new DatabaseEntry(dOffset, dLen); Assert.IsTrue(dbc.Move(key, data, true, lck)); CheckPartial(null, 0, 0, dbc.Current.Value, dOffset, dLen); // Partially key match. byte[] partbytes = new byte[kLen]; for (int i = 0; i < kLen; i++) partbytes[i] = BitConverter.GetBytes( (int)1)[kOffset + i]; key = new DatabaseEntry(partbytes, kOffset, kLen); Assert.IsTrue(dbc.Move(key, false, lck)); Assert.AreEqual(kLen, dbc.Current.Key.Data.Length); CheckPartial(dbc.Current.Key, kOffset, kLen, null, 0, 0); } } /* * Move the cursor to the first record in a nonempty * database. The returning value should be true. */ public void MoveCursorToFirst(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { DatabaseEntry key = new DatabaseEntry(kOffset, kLen); DatabaseEntry data = new DatabaseEntry(dOffset, dLen); if (lck == null) { Assert.IsTrue(dbc.MoveFirst()); Assert.IsTrue(dbc.MoveFirst(key, data)); } else { Assert.IsTrue(dbc.MoveFirst(lck)); Assert.IsTrue(dbc.MoveFirst(key, data, lck)); } CheckPartial(dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } /* * Move the cursor to last record in a nonempty * database. The returning value should be true. */ public void MoveCursorToLast(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { DatabaseEntry key = new DatabaseEntry(kOffset, kLen); DatabaseEntry data = new DatabaseEntry(dOffset, dLen); if (lck == null) { Assert.IsTrue(dbc.MoveLast()); Assert.IsTrue(dbc.MoveLast(key, data)); } else { Assert.IsTrue(dbc.MoveLast(lck)); Assert.IsTrue(dbc.MoveLast(key, data, lck)); } CheckPartial(dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } /* * Move the cursor to the next record in the database * with more than five records. The returning values of * every move operation should be true. */ public void MoveCursorToNext(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { DatabaseEntry key = new DatabaseEntry(kOffset, kLen); DatabaseEntry data = new DatabaseEntry(dOffset, dLen); for (int i = 0; i < 5; i++) { if (lck == null) { Assert.IsTrue(dbc.MoveNext()); Assert.IsTrue(dbc.MoveNext(key, data)); } else { Assert.IsTrue(dbc.MoveNext(lck)); Assert.IsTrue( dbc.MoveNext(key, data, lck)); } CheckPartial(dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } } /* * Move the cursor to the next duplicate record in * the database which has more than 2 duplicate * records. The returning value should be true. */ public void MoveCursorToNextDuplicate(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { DatabaseEntry key = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")); /* * The cursor should point to any record in the * database before it move to the next duplicate * record. */ if (lck == null) { dbc.Move(key, true); Assert.IsTrue(dbc.MoveNextDuplicate()); Assert.IsTrue(dbc.MoveNextDuplicate( new DatabaseEntry(kOffset, kLen), new DatabaseEntry(dOffset, dLen))); } else { /* * Both the move and move next duplicate * operation should use LockingInfo. If any * one doesn't use LockingInfo, deadlock still * occurs. */ dbc.Move(key, true, lck); Assert.IsTrue(dbc.MoveNextDuplicate(lck)); Assert.IsTrue(dbc.MoveNextDuplicate( new DatabaseEntry(kOffset, kLen), new DatabaseEntry(dOffset, dLen), lck)); } } /* * Move the cursor to next unique record in the database. * The returning value should be true. */ public void MoveCursorToNextUnique(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { for (int i = 0; i < 5; i++) { if (lck == null) { Assert.IsTrue(dbc.MoveNextUnique()); Assert.IsTrue(dbc.MoveNextUnique( new DatabaseEntry(kOffset, kLen), new DatabaseEntry(dOffset, dLen))); } else { Assert.IsTrue(dbc.MoveNextUnique(lck)); Assert.IsTrue(dbc.MoveNextUnique( new DatabaseEntry(kOffset, kLen), new DatabaseEntry(dOffset, dLen), lck)); } CheckPartial(dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } } /* * Move the cursor to previous record in the database. * The returning value should be true; */ public void MoveCursorToPrev(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { if (lck == null) { dbc.MoveLast(); for (int i = 0; i < 5; i++) { Assert.IsTrue(dbc.MovePrev()); dbc.MoveNext(); Assert.IsTrue(dbc.MovePrev( new DatabaseEntry(kOffset, kLen), new DatabaseEntry(dOffset, dLen))); CheckPartial( dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } } else { dbc.MoveLast(lck); for (int i = 0; i < 5; i++) { Assert.IsTrue(dbc.MovePrev(lck)); dbc.MoveNext(); Assert.IsTrue(dbc.MovePrev( new DatabaseEntry(kOffset, kLen), new DatabaseEntry(dOffset, dLen), lck)); CheckPartial( dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } } } /* * Move the cursor to a duplicate record and then to * another duplicate one. And finally move to it previous * one. Since the previous duplicate one exist, the return * value of move previous duplicate record should be * true; */ public void MoveCursorToPrevDuplicate(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { if (lck == null) { dbc.Move(new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")), true); dbc.MoveNextDuplicate(); Assert.IsTrue(dbc.MovePrevDuplicate()); dbc.Move(new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")), true); dbc.MoveNextDuplicate(); Assert.IsTrue(dbc.MovePrevDuplicate( new DatabaseEntry(kOffset, kLen), new DatabaseEntry(dOffset, dLen))); } else { dbc.Move(new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")), true, lck); dbc.MoveNextDuplicate(lck); Assert.IsTrue(dbc.MovePrevDuplicate(lck)); dbc.Move(new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")), true, lck); dbc.MoveNextDuplicate(lck); Assert.IsTrue(dbc.MovePrevDuplicate( new DatabaseEntry(kOffset, kLen), new DatabaseEntry(dOffset, dLen), lck)); } CheckPartial(dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } /* * Move the cursor to previous unique record in a * database with more than 2 records. The returning * value should be true. */ public void MoveCursorToPrevUnique(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { DatabaseEntry key = new DatabaseEntry(kOffset, kLen); DatabaseEntry data = new DatabaseEntry(dOffset, dLen); for (int i = 0; i < 5; i++) { if (lck == null) { Assert.IsTrue(dbc.MovePrevUnique()); Assert.IsTrue( dbc.MovePrevUnique(key, data)); } else { Assert.IsTrue(dbc.MovePrevUnique(lck)); Assert.IsTrue( dbc.MovePrevUnique(key, data, lck)); } CheckPartial(dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } } /* * Move the cursor to current existing record. The returning * value should be true. */ public void MoveCursorToCurrentRec(Cursor dbc, uint kOffset, uint kLen, uint dOffset, uint dLen, LockingInfo lck) { DatabaseEntry key, data; // Add a record to the database. KeyValuePair<DatabaseEntry, DatabaseEntry> pair; key = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")); data = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("data")); pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(key, data); dbc.Add(pair); if (lck == null) Assert.IsTrue(dbc.Refresh()); else Assert.IsTrue(dbc.Refresh(lck)); Assert.AreEqual(key.Data, dbc.Current.Key.Data); Assert.AreEqual(data.Data, dbc.Current.Value.Data); key = new DatabaseEntry(kOffset, kLen); data = new DatabaseEntry(dOffset, dLen); if (lck == null) Assert.IsTrue(dbc.Refresh(key, data)); else Assert.IsTrue(dbc.Refresh(key, data, lck)); CheckPartial(dbc.Current.Key, kOffset, kLen, dbc.Current.Value, dOffset, dLen); } public void CheckPartial( DatabaseEntry key, uint kOffset, uint kLen, DatabaseEntry data, uint dOffset, uint dLen) { if (key != null) { Assert.IsTrue(key.Partial); Assert.AreEqual(kOffset, key.PartialOffset); Assert.AreEqual(kLen, key.PartialLen); Assert.AreEqual(kLen, (uint)key.Data.Length); } if (data != null) { Assert.IsTrue(data.Partial); Assert.AreEqual(dOffset, data.PartialOffset); Assert.AreEqual(dLen, data.PartialLen); Assert.AreEqual(dLen, (uint)data.Data.Length); } } } }
25.838941
79
0.656833
[ "MIT" ]
HcashOrg/Hcash
dependence/db-5.3.28.NC/test/csharp/CursorTest.cs
46,846
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.CloudFront.Outputs { [OutputType] public sealed class ResponseHeadersPolicyContentSecurityPolicy { public readonly string ContentSecurityPolicy; public readonly bool Override; [OutputConstructor] private ResponseHeadersPolicyContentSecurityPolicy( string contentSecurityPolicy, bool @override) { ContentSecurityPolicy = contentSecurityPolicy; Override = @override; } } }
27.066667
81
0.695813
[ "Apache-2.0" ]
AaronFriel/pulumi-aws-native
sdk/dotnet/CloudFront/Outputs/ResponseHeadersPolicyContentSecurityPolicy.cs
812
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 Microsoft.EntityFrameworkCore.TestUtilities; namespace Microsoft.EntityFrameworkCore { public class NotificationEntitiesSqliteTest : NotificationEntitiesTestBase<NotificationEntitiesSqliteTest.NotificationEntitiesSqliteFixture> { public NotificationEntitiesSqliteTest(NotificationEntitiesSqliteFixture fixture) : base(fixture) { } public class NotificationEntitiesSqliteFixture : NotificationEntitiesFixtureBase { protected override ITestStoreFactory TestStoreFactory => SqliteTestStoreFactory.Instance; } } }
36.666667
144
0.75974
[ "Apache-2.0" ]
Alecu100/EntityFrameworkCore
test/EFCore.Sqlite.FunctionalTests/NotificationEntitiesSqliteTest.cs
770
C#
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Integration; using Microsoft.Bot.Builder.Integration.AspNet.Core.Handlers; using Microsoft.Bot.Schema; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Willezone.Azure.WebJobs.Extensions.DependencyInjection; namespace OrderBot { public static class MainFunction { [FunctionName("messages")] public static async Task<IActionResult> RunAsync( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)]HttpRequest req, [Inject] IAdapterIntegration adapter, [Inject] IBot bot, ILogger logger) { try { await ProcessMessageRequestAsync(req, adapter, bot.OnTurnAsync, default(CancellationToken)); return new OkResult(); } catch (Exception ex) { return new ObjectResult(ex) { StatusCode = StatusCodes.Status500InternalServerError }; } } private static async Task<InvokeResponse> ProcessMessageRequestAsync(HttpRequest request, IAdapterIntegration adapter, BotCallbackHandler botCallbackHandler, CancellationToken cancellationToken) { var requestBody = request.Body; // In the case of request buffering being enabled, we could possibly receive a Stream that needs its position reset, // but we can't _blindly_ reset in case buffering hasn't been enabled since we'll be working with a non-seekable Stream // in that case which will throw a NotSupportedException if (requestBody.CanSeek) { requestBody.Position = 0; } var activity = default(Activity); // Get the request body and deserialize to the Activity object. // NOTE: We explicitly leave the stream open here so others can still access it (in case buffering was enabled); ASP.NET runtime will always dispose of it anyway using (var bodyReader = new JsonTextReader(new StreamReader(requestBody, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: 1024, leaveOpen: true))) { activity = BotMessageHandlerBase.BotMessageSerializer.Deserialize<Activity>(bodyReader); } var invokeResponse = await adapter.ProcessActivityAsync( request.Headers["Authorization"], activity, botCallbackHandler, cancellationToken); return invokeResponse; } } }
39.708333
202
0.662469
[ "MIT" ]
weikanglim/OrderBot
src/OrderBot.Functions/MainFunction.cs
2,859
C#
namespace Lifx.Api.Cloud.Models.Request { public class FlameEffectRequest { public double? period { get; set; } = 5; public double? duration { get; set; } public bool? power_on { get; set; } = true; } }
24
51
0.591667
[ "MIT" ]
panoramicdata/Lifx.Api
Lifx.Api/Cloud/Models/Request/FlameEffectRequest.cs
242
C#
using System; namespace Shared.Library.Exceptions { public sealed class ValidateException : Exception { public ValidateException(string memberName, string errorMessage) : base(string.Format("A validation error has occurred {0}:{1}", memberName, errorMessage)) { MemberName = memberName; ErrorMessage = errorMessage; } public string MemberName { get; } public string ErrorMessage { get; } private ValidateException() { } private ValidateException(string message, Exception innerException) : base(message, innerException) { } } }
25.692308
107
0.621257
[ "MIT" ]
RomeshAbeyawardena/Shared
Shared.Library/Exceptions/ValidateException.cs
668
C#
using System.Collections.Generic; namespace Cloudtoid.Json.Schema { public class JsonSchemaAny : JsonSchemaNamedConstraints { public JsonSchemaAny(IEnumerable<JsonSchemaConstraint> constraints) : base(constraints) { } public JsonSchemaAny() : base() { } protected internal override void Accept(JsonSchemaVisitor visitor) => visitor.VisitAny(this); } }
21.904762
75
0.617391
[ "MIT" ]
cloudtoid/json-schema
src/Cloudtoid.Json.Schema/ObjectModel/Constraints/JsonSchemaAny.cs
462
C#
using System; using System.Data; using System.Linq; using BenchmarkDotNet.Attributes; using Bogus; using FluentAssertions; using FluentAssertions.Data; namespace Benchmarks; [MemoryDiagnoser] public class LargeDataTableEquivalencyBenchmarks { private DataTable dataTable1; private DataTable dataTable2; [Params(10, 100, 1_000, 10_000, 100_000)] public int RowCount { get; set; } [GlobalSetup] public void GlobalSetup() { dataTable1 = CreateDataTable(); dataTable2 = CreateDataTable(); object[] rowData = new object[dataTable1.Columns.Count]; var faker = new Faker { Random = new Randomizer(localSeed: 1) }; for (int i = 0; i < RowCount; i++) { for (int j = 0; j < dataTable1.Columns.Count; j++) { Type columnType = dataTable1.Columns[j].DataType; rowData[j] = GetData(faker, columnType); } dataTable1.Rows.Add(rowData); dataTable2.Rows.Add(rowData); } } private static object GetData(Faker faker, Type columnType) { return (Type.GetTypeCode(columnType)) switch { TypeCode.Empty or TypeCode.DBNull => null, TypeCode.Boolean => faker.Random.Bool(), TypeCode.Char => faker.Lorem.Letter().Single(), TypeCode.SByte => faker.Random.SByte(), TypeCode.Byte => faker.Random.Byte(), TypeCode.Int16 => faker.Random.Short(), TypeCode.UInt16 => faker.Random.UShort(), TypeCode.Int32 => faker.Random.Int(), TypeCode.UInt32 => faker.Random.UInt(), TypeCode.Int64 => faker.Random.Long(), TypeCode.UInt64 => faker.Random.ULong(), TypeCode.Single => faker.Random.Float(), TypeCode.Double => faker.Random.Double(), TypeCode.Decimal => faker.Random.Decimal(), TypeCode.DateTime => faker.Date.Between(DateTime.UtcNow.AddDays(-30), DateTime.UtcNow.AddDays(+30)), TypeCode.String => faker.Lorem.Lines(1), _ => GetDefault(faker, columnType), }; } private static object GetDefault(Faker faker, Type columnType) { if (columnType == typeof(TimeSpan)) return faker.Date.Future() - faker.Date.Future(); else if (columnType == typeof(Guid)) return faker.Random.Guid(); throw new Exception("Unable to populate column of type " + columnType); } private static DataTable CreateDataTable() { var table = new DataTable("Test"); table.Columns.Add("A", typeof(bool)); table.Columns.Add("B", typeof(char)); table.Columns.Add("C", typeof(sbyte)); table.Columns.Add("D", typeof(byte)); table.Columns.Add("E", typeof(short)); table.Columns.Add("F", typeof(ushort)); table.Columns.Add("G", typeof(int)); table.Columns.Add("H", typeof(uint)); table.Columns.Add("I", typeof(long)); table.Columns.Add("J", typeof(ulong)); table.Columns.Add("K", typeof(float)); table.Columns.Add("L", typeof(double)); table.Columns.Add("M", typeof(decimal)); table.Columns.Add("N", typeof(DateTime)); table.Columns.Add("O", typeof(string)); table.Columns.Add("P", typeof(TimeSpan)); table.Columns.Add("Q", typeof(Guid)); return table; } [Benchmark] public AndConstraint<DataTableAssertions<DataTable>> BeEquivalentTo() => dataTable1.Should().BeEquivalentTo(dataTable2); }
32.513514
124
0.596564
[ "Apache-2.0" ]
IT-VBFK/fluentassertions
Tests/Benchmarks/LargeDataTableEquivalency.cs
3,611
C#
using System; using System.Collections.Generic; using Bar.Models; using Bar.Tender; namespace Bar.CLI { internal class CustomerService : ICustomerService { private readonly IBartender _bartender; private readonly ICustomerInterface _customerInterface; private readonly IPresenter _presenter; private readonly List<Order> _tab = new List<Order>(); public CustomerService(IBartender bartender, ICustomerInterface customerInterface, IPresenter presenter) { _bartender = bartender ?? throw new ArgumentNullException(nameof(bartender)); _customerInterface = customerInterface ?? throw new ArgumentNullException(nameof(customerInterface)); _presenter = presenter ?? throw new ArgumentNullException(nameof(presenter)); } public void ServeCustomer() { _customerInterface.Say("Welcome to the xBar! What would you like to order?"); GetOrder(); } private void GetOrder() { // Listen to customer. var request = _customerInterface.Listen(); // If the customer wishes to leave, present the tab. if (request == "exit" || request == "no" || request == "n") { _presenter.PresentTab(_tab); _customerInterface.Say("Have a nice day!"); return; } _customerInterface.Say("Coming right up!"); // Process request. var order = _bartender.ProcessRequest(request); // Add to tab if valid. if (order.IsValid()) { _tab.Add(order); } // Present order. _presenter.PresentOrder(order); // Ask if there's anything else and get another order. _customerInterface.Pause(); _customerInterface.Say("Would you like anything else?"); GetOrder(); } } internal interface ICustomerService { void ServeCustomer(); } }
30.514706
113
0.588434
[ "MIT" ]
Foshkey/xUnit-Demo
Source/Bar.CLI/CustomerService.cs
2,077
C#
using System; namespace Earth.Renderer { internal class PixelSizePerDistanceUniform : DrawAutomaticUniform { public PixelSizePerDistanceUniform(Uniform uniform) { _uniform = (Uniform<float>)uniform; } #region DrawAutomaticUniform Members public override void Set(Context context, DrawState drawState, SceneState sceneState) { _uniform.Value = (float)(Math.Tan(0.5 * sceneState.Camera.FieldOfViewY) * 2.0 / context.Viewport.Height); } #endregion private Uniform<float> _uniform; } }
24.833333
117
0.649329
[ "MIT" ]
Shakenbake158/Earth
Assets/Scripts/Renderer/Shaders/DrawAutomaticUniforms/PixelSizePerDistanceUniform.cs
598
C#
namespace Discord.GameSDK.Store { public enum SkuType { /// <summary> /// SKU is a game /// </summary> Application = 1, /// <summary> /// SKU is a DLC /// </summary> DLC, /// <summary> /// SKU is a consumable (in-app purchase) /// </summary> Consumable, /// <summary> /// SKU is a bundle (comprising the other 3 types) /// </summary> Bundle } }
15.96
56
0.541353
[ "MIT" ]
Voltstro-Studios/Discord.GameSDKCSharp
src/Discord.GameSDK/Store/SkuType.cs
401
C#
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes; namespace Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Enums { /// <summary> /// This specifies the Open API format. /// </summary> public enum OpenApiFormatType { /// <summary> /// Identifies the JSON format. /// </summary> [Display("json")] Json = 0, /// <summary> /// Identifies the YAML format. /// </summary> [Display("yaml")] Yaml = 1 } }
22.608696
65
0.555769
[ "MIT" ]
danielabbatt/azure-functions-openapi-extension
src/Microsoft.Azure.WebJobs.Extensions.OpenApi.Core/Enums/OpenApiFormatType.cs
520
C#
using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using Newtonsoft.Json; using Formatting = System.Xml.Formatting; namespace Merchello.Core.Models { /// <summary> /// Extension methods for <see cref="IOrder"/> /// </summary> public static class OrderExtensions { /// <summary> /// Returns a constructed order number (including it's invoice number prefix - if any) /// </summary> /// <param name="order">The <see cref="IOrder"/></param> /// <returns>The prefixed order number</returns> public static string PrefixedOrderNumber(this IOrder order) { return string.IsNullOrEmpty(order.OrderNumberPrefix) ? order.OrderNumber.ToString(CultureInfo.InvariantCulture) : string.Format("{0}-{1}", order.OrderNumberPrefix, order.OrderNumber); } #region Fulfillment /// <summary> /// Gets a collection of unfulfilled (unshipped) line items /// </summary> /// <param name="order">The <see cref="IOrder"/></param> /// <returns>A collection of <see cref="IOrderLineItem"/></returns> public static IEnumerable<IOrderLineItem> UnfulfilledItems(this IOrder order) { return order.UnfulfilledItems(MerchelloContext.Current); } /// <summary> /// Gets a collection of unfulfilled (unshipped) line items /// </summary> /// <param name="order">The <see cref="IOrder"/></param> /// <param name="merchelloContext">The <see cref="IMerchelloContext"/></param> /// <returns>A collection of <see cref="IOrderLineItem"/></returns> public static IEnumerable<IOrderLineItem> UnfulfilledItems(this IOrder order, IMerchelloContext merchelloContext) { return order.UnfulfilledItems(merchelloContext, order.Items.Select(x => x as OrderLineItem)); } /// <summary> /// Gets a collection of unfulfilled (unshipped) line items /// </summary> /// <param name="order">The <see cref="IOrder"/></param> /// <param name="items">A collection of <see cref="IOrderLineItem"/></param> /// <returns>The collection of <see cref="IOrderLineItem"/></returns> public static IEnumerable<IOrderLineItem> UnfulfilledItems(this IOrder order, IEnumerable<IOrderLineItem> items) { return order.UnfulfilledItems(MerchelloContext.Current, items); } /// <summary> /// Gets a collection of unfulfilled (unshipped) line items /// </summary> /// <param name="order">The <see cref="IOrder"/></param> /// <param name="merchelloContext">The <see cref="IMerchelloContext"/></param> /// <param name="items">A collection of <see cref="IOrderLineItem"/></param> /// <returns>The collection of <see cref="IOrderLineItem"/></returns> public static IEnumerable<IOrderLineItem> UnfulfilledItems(this IOrder order, IMerchelloContext merchelloContext, IEnumerable<IOrderLineItem> items) { if (Constants.DefaultKeys.OrderStatus.Fulfilled == order.OrderStatus.Key) return new List<IOrderLineItem>(); var shippableItems = items.Where(x => x.IsShippable() && x.ShipmentKey == null).ToArray(); var inventoryItems = shippableItems.Where(x => x.ExtendedData.GetTrackInventoryValue()).ToArray(); // get the variants to check the inventory var variants = merchelloContext.Services.ProductVariantService.GetByKeys(inventoryItems.Select(x => x.ExtendedData.GetProductVariantKey())).ToArray(); foreach (var item in inventoryItems) { var variant = variants.FirstOrDefault(x => x.Key == item.ExtendedData.GetProductVariantKey()); if (variant == null) continue; // TODO refactor back ordering. //// check inventory //var inventory = variant.CatalogInventories.FirstOrDefault(x => x.CatalogKey == item.ExtendedData.GetWarehouseCatalogKey()); //if (inventory != null) // item.BackOrder = inventory.Count < item.Quantity; } return shippableItems; } /// <summary> /// Gets a collection of items that have inventory requirements /// </summary> /// <param name="order">The <see cref="IOrder"/></param> /// <returns>A collection of <see cref="IOrderLineItem"/></returns> public static IEnumerable<IOrderLineItem> InventoryTrackedItems(this IOrder order) { return order.Items.Where(x => x.ExtendedData.GetTrackInventoryValue() && x.ExtendedData.ContainsWarehouseCatalogKey()).Select(x => (OrderLineItem)x); } #endregion #region Examine /// <summary> /// Serializes <see cref="IOrder"/> object /// </summary> /// <remarks> /// Intended to be used by the Merchello.Examine.Providers.MerchelloOrderIndexer /// </remarks> internal static XDocument SerializeToXml(this IOrder order) { string xml; using (var sw = new StringWriter()) { using (var writer = new XmlTextWriter(sw)) { writer.WriteStartDocument(); writer.WriteStartElement("order"); writer.WriteAttributeString("id", ((Order)order).ExamineId.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("orderKey", order.Key.ToString()); writer.WriteAttributeString("invoiceKey", order.InvoiceKey.ToString()); writer.WriteAttributeString("orderNumberPrefix", order.OrderNumberPrefix); writer.WriteAttributeString("orderNumber", order.OrderNumber.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("prefixedOrderNumber", order.PrefixedOrderNumber()); writer.WriteAttributeString("orderDate", order.OrderDate.ToString("s")); writer.WriteAttributeString("orderStatusKey", order.OrderStatusKey.ToString()); writer.WriteAttributeString("versionKey", order.VersionKey.ToString()); writer.WriteAttributeString("exported", order.Exported.ToString()); writer.WriteAttributeString("orderStatus", GetOrderStatusJson(order.OrderStatus)); writer.WriteAttributeString("orderItems", GetGenericItemsCollection(order.Items.Select(x => (OrderLineItem)x))); writer.WriteAttributeString("createDate", order.CreateDate.ToString("s")); writer.WriteAttributeString("updateDate", order.UpdateDate.ToString("s")); writer.WriteAttributeString("allDocs", "1"); writer.WriteEndElement(); writer.WriteEndDocument(); xml = sw.ToString(); } } return XDocument.Parse(xml); } private static string GetGenericItemsCollection(IEnumerable<IOrderLineItem> items) { return JsonConvert.SerializeObject( items.Select(x => new { key = x.Key, containerKey = x.ContainerKey, name = x.Name, shipmentKey = x.ShipmentKey, lineItemTfKey = x.LineItemTfKey, lineItemType = x.LineItemType.ToString(), sku = x.Sku, price = x.Price, quantity = x.Quantity, exported = x.Exported, backOrder = x.BackOrder, extendedData = x.ExtendedData.AsEnumerable() } ), Newtonsoft.Json.Formatting.None); } private static string GetOrderStatusJson(IOrderStatus orderStatus) { return JsonConvert.SerializeObject( new { key = orderStatus.Key, name = orderStatus.Name, alias = orderStatus.Alias, reportable = orderStatus.Reportable, active = orderStatus.Active, sortOrder = orderStatus.SortOrder }, Newtonsoft.Json.Formatting.None); } #endregion } }
45.067358
162
0.586227
[ "MIT" ]
dampee/Merchello
src/Merchello.Core/Models/OrderExtensions.cs
8,700
C#
using System; using System.Collections.Generic; using System.Data.SqlClient; namespace Aurum.SQL { public interface ISqlValidator : IDisposable { bool Validate(string query, out IList<SqlError> errors); } }
20.727273
64
0.723684
[ "MIT" ]
404htm/Aurum
Project/Aurum.SQL/Readers/ISqlValidator.cs
230
C#
using Newtonsoft.Json; using PepperDash.Essentials.Core; namespace PepperDash.Essentials.Core { public class DestinationListItem { [JsonProperty("sinkKey")] public string SinkKey { get; set; } private EssentialsDevice _sinkDevice; [JsonIgnore] public EssentialsDevice SinkDevice { get { return _sinkDevice ?? (_sinkDevice = DeviceManager.GetDeviceForKey(SinkKey) as EssentialsDevice); } } [JsonProperty("preferredName")] public string PreferredName { get { if (!string.IsNullOrEmpty(Name)) { return Name; } return SinkDevice == null ? "---" : SinkDevice.Name; } } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("includeInDestinationList")] public bool IncludeInDestinationList { get; set; } [JsonProperty("order")] public int Order { get; set; } [JsonProperty("surfaceLocation")] public int SurfaceLocation { get; set; } [JsonProperty("verticalLocation")] public int VerticalLocation { get; set; } [JsonProperty("horizontalLocation")] public int HorizontalLocation { get; set; } [JsonProperty("sinkType")] public eRoutingSignalType SinkType { get; set; } } }
26.777778
117
0.570539
[ "MIT" ]
PepperDash/Essentials
essentials-framework/Essentials Core/PepperDashEssentialsBase/Devices/DestinationListItem.cs
1,448
C#
/* * Copyright (c) Contributors, http://vision-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * For an explanation of the license of each contributor and the content it * covers please see the Licenses directory. * * 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 Vision-Sim Project 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 DEVELOPERS ``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 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 System.Diagnostics; using System.Security.Cryptography; using OpenMetaverse; using OpenMetaverse.StructuredData; using ProtoBuf; using Vision.Framework.ClientInterfaces; using Vision.Framework.ConsoleFramework; using Vision.Framework.Modules; using Vision.Framework.Utilities; namespace Vision.Framework.Services.ClassHelpers.Assets { [Flags] public enum AssetFlags { Normal = 0, // Immutable asset Maptile = 1, // Deprecated, use Deletable instead: What it says Rewritable = 2, // Content can be rewritten Collectable = 4, // Can be GC'ed after some time Deletable = 8, // The asset can be deleted Local = 16, // Region-only asset, never stored in the database Temporary = 32, // Is this asset going to exist permanently in the database, or can it be purged after a set amount of time? RemotelyAccessable = 64 // Regions outside of this grid can access this asset } /// <summary> /// Asset class. All Assets are reference by this class or a class derived from this class /// </summary> [Serializable, ProtoContract(UseProtoMembersOnly = false)] public class AssetBase : IDataTransferable, IDisposable { static readonly SHA256Managed SHA256Managed = new SHA256Managed(); string idString = ""; byte[] myData = new byte[] {}; string myHashCode = ""; #region Initiation // This is needed for .NET serialization!!! // Do NOT "Optimize" away! public AssetBase() { SimpleInitialize(); } public AssetBase(string assetID) { SimpleInitialize(); IDString = assetID; } public AssetBase(UUID assetID) { SimpleInitialize(); ID = assetID; } public AssetBase(string assetID, string name, AssetType assetType, UUID creatorID) { Initiate(assetID, name, assetType, creatorID); } public AssetBase(UUID assetID, string name, AssetType assetType, UUID creatorID) { Initiate(assetID.ToString(), name, assetType, creatorID); } void SimpleInitialize() { DatabaseTable = "assets"; ID = UUID.Zero; TypeAsset = AssetType.Unknown; CreatorID = UUID.Zero; Description = ""; Name = ""; HostUri = ""; LastAccessed = DateTime.UtcNow; CreationDate = DateTime.UtcNow; HashCode = ""; LastHashCode = ""; ParentID = UUID.Zero; MetaOnly = true; Data = new byte[] {}; Flags = AssetFlags.Normal; } public void Initiate(string assetID, string name, AssetType assetType, UUID creatorID) { SimpleInitialize(); if (assetType == AssetType.Unknown) { StackTrace trace = new StackTrace(true); MainConsole.Instance.ErrorFormat( "[ASSETBASE]: Creating asset '{0}' ({1}) with an unknown asset type\n{2}", name, assetID, trace); } IDString = assetID; Name = name; TypeAsset = assetType; CreatorID = creatorID; } #endregion #region is Type asset public bool IsTextualAsset { get { return !IsBinaryAsset; } } /// <summary> /// Checks if this asset is a binary or text asset /// </summary> public bool IsBinaryAsset { get { return (TypeAsset == AssetType.Animation || TypeAsset == AssetType.Gesture || TypeAsset == AssetType.Simstate || TypeAsset == AssetType.Unknown || TypeAsset == AssetType.Object || TypeAsset == AssetType.Sound || TypeAsset == AssetType.SoundWAV || TypeAsset == AssetType.Texture || TypeAsset == AssetType.TextureTGA || TypeAsset == AssetType.Folder || TypeAsset == AssetType.ImageJPEG || TypeAsset == AssetType.ImageTGA || TypeAsset == AssetType.LSLBytecode); } } public bool ContainsReferences { get { return IsTextualAsset && ( TypeAsset != AssetType.Notecard && TypeAsset != AssetType.CallingCard && TypeAsset != AssetType.LSLText && TypeAsset != AssetType.Landmark); } } public string AssetTypeInfo() { switch (TypeAsset) { case AssetType.Animation: return "Animation"; case AssetType.Bodypart: return "Bodypart"; case AssetType.CallingCard: return "CallingCard"; case AssetType.Clothing: return "Clothing"; case AssetType.Gesture: return "Gesture"; case AssetType.Landmark: return "Landmark"; case AssetType.LSLText: return "Script"; case AssetType.Mesh: return "Mesh"; case AssetType.Notecard: return "Notecard"; case AssetType.Object: return "Object"; case AssetType.Sound: return "Sound"; case AssetType.Texture: return "Texture"; case AssetType.TextureTGA: return "TGA Texture"; case AssetType.Simstate: return "Simstate info"; case AssetType.ImageJPEG: return "JPG image"; case AssetType.ImageTGA: return "TGA image"; default: return "Unknown asset"; } } #endregion #region properties /// <summary> /// used by archive loaders to track with assets have been saved /// </summary> public bool HasBeenSaved { get; set; } public string TypeString { get { return SLUtil.SLAssetTypeToContentType((int) TypeAsset); } set { TypeAsset = (AssetType) SLUtil.ContentTypeToSLAssetType(value); } } [ProtoMember(1)] public byte[] Data { get { return myData; } set { myData = value; if (myData != null) { MetaOnly = (myData.Length == 0); if (!MetaOnly) HashCode = FillHash(myData); } else HashCode = ""; } } public UUID ID { get; set; } // This is only used for cache [ProtoMember(2)] public string IDString { get { return idString.Length > 0 ? idString : ID.ToString(); } set { UUID k; if (UUID.TryParse(value, out k)) ID = k; else if ((value.Length >= 37) && (UUID.TryParse(value.Substring(value.Length - 36), out k))) { ID = k; idString = value; } else idString = value; } } [ProtoMember(3)] public string HashCode { get { return myHashCode; } set { // ensure we keep the orginal hash from when it was loaded // so we can check if its being used anymore with any other assets if ((LastHashCode == myHashCode) || (LastHashCode == "")) LastHashCode = myHashCode; myHashCode = value; } } [ProtoMember(4)] public string LastHashCode { get; set; } [ProtoMember(5)] public string Name { get; set; } [ProtoMember(6)] public string Description { get; set; } public AssetType TypeAsset { get; set; } [ProtoMember(7)] public int Type { get { return (int) TypeAsset; } set { TypeAsset = (AssetType) value; } } [ProtoMember(8)] public AssetFlags Flags { get; set; } [ProtoMember(9)] public string DatabaseTable { get; set; } [ProtoMember(10)] public string HostUri { get; set; } [ProtoMember(11)] public DateTime LastAccessed { get; set; } [ProtoMember(12)] public DateTime CreationDate { get; set; } public UUID CreatorID { get; set; } [ProtoMember(13)] public string SerializedCreatorID { get { return CreatorID.ToString(); } set { CreatorID = UUID.Parse(value); } } public UUID ParentID { get; set; } [ProtoMember(14)] public string SerializedParentID { get { return ParentID.ToString(); } set { ParentID = UUID.Parse(value); } } [ProtoMember(15)] public bool MetaOnly { get; set; } // should run this if your filling out a new asset // ensures we don't try to pull it from the database when saving the asset // because we need to know if it changed. public static string FillHash(byte[] data) { return Convert.ToBase64String(SHA256Managed.ComputeHash(data)) + data.Length; } public override string ToString() { return ID.ToString(); } #endregion #region IDisposable Members public void Dispose() { Data = null; } #endregion #region Packing/Unpacking /// <summary> /// Pack this asset into an OSDMap /// </summary> /// <returns></returns> public OSDMap Pack() { return ToOSD(); } /// <summary> /// Pack this asset into an OSDMap /// </summary> /// <returns></returns> public override OSDMap ToOSD() { OSDMap assetMap = new OSDMap { {"AssetFlags", OSD.FromInteger((int) Flags)}, {"AssetID", ID}, {"CreationDate", OSD.FromDate(CreationDate)}, {"CreatorID", OSD.FromUUID(CreatorID)}, {"Data", OSD.FromBinary(Data)}, {"HostUri", OSD.FromString(HostUri)}, {"LastAccessed", OSD.FromDate(LastAccessed)}, {"Name", OSD.FromString(Name)}, {"ParentID", CreationDate}, {"TypeAsset", OSD.FromInteger((int) TypeAsset)}, {"Description", OSD.FromString(Description)}, {"DatabaseTable", OSD.FromString(DatabaseTable)} }; return assetMap; } public override void FromOSD(OSDMap map) { Unpack(map); } /// <summary> /// Unpack the asset from an OSDMap /// </summary> /// <param name="osd"></param> public AssetBase Unpack(OSD osd) { if (!(osd is OSDMap)) return null; OSDMap assetMap = (OSDMap) osd; if (assetMap.ContainsKey("AssetFlags")) Flags = (AssetFlags) assetMap["AssetFlags"].AsInteger(); if (assetMap.ContainsKey("AssetID")) ID = assetMap["AssetID"].AsUUID(); if (assetMap.ContainsKey("CreationDate")) CreationDate = assetMap["CreationDate"].AsDate(); if (assetMap.ContainsKey("CreatorID")) CreatorID = assetMap["CreatorID"].AsUUID(); if (assetMap.ContainsKey("Data")) Data = assetMap["Data"].AsBinary(); if (assetMap.ContainsKey("HostUri")) HostUri = assetMap["HostUri"].AsString(); if (assetMap.ContainsKey("LastAccessed")) LastAccessed = assetMap["LastAccessed"].AsDate(); if (assetMap.ContainsKey("Name")) Name = assetMap["Name"].AsString(); if (assetMap.ContainsKey("TypeAsset")) TypeAsset = (AssetType) assetMap["TypeAsset"].AsInteger(); if (assetMap.ContainsKey("Description")) Description = assetMap["Description"].AsString(); if (assetMap.ContainsKey("ParentID")) ParentID = assetMap["ParentID"].AsUUID(); if (assetMap.ContainsKey("DatabaseTable")) DatabaseTable = assetMap["DatabaseTable"].AsString(); return this; } /// <summary> /// Make an OSDMap (json) with only the needed parts for the database and then compress it /// </summary> /// <returns>A compressed (gzip) string of the data needed for the database</returns> public string CompressedPack() { OSDMap assetMap = ToOSD(); //Serialize it with json string jsonString = OSDParser.SerializeJsonString(assetMap); //Now use gzip to compress this map string compressedString = Util.Compress(jsonString); return compressedString; } public void CompressedUnpack(string compressedString) { //Decompress the info back to json format string jsonString = Util.Decompress(compressedString); //Build the OSDMap OSDMap assetMap = (OSDMap) OSDParser.DeserializeJson(jsonString); //Now unpack the contents Unpack(assetMap); } #endregion } }
35.441365
117
0.511431
[ "MIT" ]
VisionSim/Vision-Sim
Vision/Framework/Services/ClassHelpers/Assets/AssetBase.cs
16,622
C#
using System; namespace Vadavo.NEscPos.Test { public static class ConsoleHelpers { public static void WriteErrorLine(string message) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(message); Console.ResetColor(); } public static string PromptLine(string message) { Console.ForegroundColor = ConsoleColor.Green; Console.Write(message + " "); Console.ResetColor(); return Console.ReadLine(); } public static ConsoleKeyInfo PromptKey(string message) { Console.ForegroundColor = ConsoleColor.Green; Console.Write(message + " "); Console.ResetColor(); return Console.ReadKey(); } } }
25.46875
62
0.574233
[ "MIT" ]
montyclt/ESCPOS.NET
Vadavo.NEscPos.Test/ConsoleHelpers.cs
815
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from include/vulkan/vulkan_win32.h in the KhronosGroup/Vulkan-Headers repository for tag v1.2.198 // Original source is Copyright © 2015-2021 The Khronos Group Inc. using System; namespace TerraFX.Interop.Vulkan { public unsafe partial struct VkExportMemoryWin32HandleInfoNV { public VkStructureType sType; [NativeTypeName("const void *")] public void* pNext; [NativeTypeName("const SECURITY_ATTRIBUTES *")] public IntPtr pAttributes; [NativeTypeName("DWORD")] public uint dwAccess; } }
29.875
145
0.714086
[ "MIT" ]
tannergooding/terrafx.interop.vulkan
sources/Interop/Vulkan/Vulkan/vulkan/vulkan_win32/VkExportMemoryWin32HandleInfoNV.cs
719
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Reusable.Workflows { [Table("Workflow")] public partial class Workflow : BaseEntity { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Workflow() { } [Key] public int WorkflowKey { get; set; } [Required] [StringLength(150)] public string Name { get; set; } public override int id { get { return WorkflowKey; } set { WorkflowKey = value; } } public List<Step> Steps { get; set; } } }
27.346154
128
0.655415
[ "Apache-2.0" ]
JFigue27/MRO-Generated
backend/Reusable/Workflows/Workflow.cs
711
C#
using System; using System.Threading.Tasks; using FFImageLoading.Work; using System.IO; using FFImageLoading.Views; using FFImageLoading.Targets; using FFImageLoading.Drawables; namespace FFImageLoading { /// <summary> /// TaskParameterPlatformExtensions /// </summary> public static class TaskParameterPlatformExtensions { /// <summary> /// Loads the image into PNG Stream /// </summary> /// <returns>The PNG Stream async.</returns> /// <param name="parameters">Parameters.</param> public static async Task<Stream> AsPNGStreamAsync(this TaskParameter parameters) { var result = await AsBitmapDrawableAsync(parameters); var stream = await result.AsPngStreamAsync(); result.SetIsDisplayed(false); return stream; } /// <summary> /// Loads the image into JPG Stream /// </summary> /// <returns>The JPG Stream async.</returns> /// <param name="parameters">Parameters.</param> /// <param name="quality">Quality.</param> public static async Task<Stream> AsJPGStreamAsync(this TaskParameter parameters, int quality = 80) { var result = await AsBitmapDrawableAsync(parameters); var stream = await result.AsJpegStreamAsync(quality); result.SetIsDisplayed(false); return stream; } /// <summary> /// Loads and gets BitmapDrawable using defined parameters. /// IMPORTANT: you should call SetNoLongerDisplayed method if drawable is no longer displayed /// IMPORTANT: It throws image loading exceptions - you should handle them /// </summary> /// <returns>The bitmap drawable async.</returns> /// <param name="parameters">Parameters.</param> public static Task<SelfDisposingBitmapDrawable> AsBitmapDrawableAsync(this TaskParameter parameters) { var target = new BitmapTarget(); var userErrorCallback = parameters.OnError; var finishCallback = parameters.OnFinish; var tcs = new TaskCompletionSource<SelfDisposingBitmapDrawable>(); parameters .Error(ex => { tcs.TrySetException(ex); userErrorCallback?.Invoke(ex); }) .Finish(scheduledWork => { finishCallback?.Invoke(scheduledWork); tcs.TrySetResult(target.BitmapDrawable); }); if (parameters.Source != ImageSource.Stream && string.IsNullOrWhiteSpace(parameters.Path)) { target.SetAsEmpty(null); parameters.TryDispose(); return null; } var task = ImageService.CreateTask(parameters, target); ImageService.Instance.LoadImage(task); return tcs.Task; } /// <summary> /// Loads the image into given ImageViewAsync using defined parameters. /// </summary> /// <param name="parameters">Parameters for loading the image.</param> /// <param name="imageView">Image view that should receive the image.</param> public static IScheduledWork Into(this TaskParameter parameters, ImageViewAsync imageView) { var target = new ImageViewTarget(imageView); return parameters.Into(target); } /// <summary> /// Loads the image into given imageView using defined parameters. /// IMPORTANT: It throws image loading exceptions - you should handle them /// </summary> /// <returns>An awaitable Task.</returns> /// <param name="parameters">Parameters for loading the image.</param> /// <param name="imageView">Image view that should receive the image.</param> public static Task<IScheduledWork> IntoAsync(this TaskParameter parameters, ImageViewAsync imageView) { return parameters.IntoAsync(param => param.Into(imageView)); } /// <summary> /// Loads the image into given target using defined parameters. /// </summary> /// <returns>The into.</returns> /// <param name="parameters">Parameters.</param> /// <param name="target">Target.</param> /// <typeparam name="TImageView">The 1st type parameter.</typeparam> public static IScheduledWork Into<TImageView>(this TaskParameter parameters, ITarget<SelfDisposingBitmapDrawable, TImageView> target) where TImageView : class { if (parameters.Source != ImageSource.Stream && string.IsNullOrWhiteSpace(parameters.Path)) { target.SetAsEmpty(null); parameters.TryDispose(); return null; } var task = ImageService.CreateTask(parameters, target); ImageService.Instance.LoadImage(task); return task; } /// <summary> /// Loads the image into given target using defined parameters. /// IMPORTANT: It throws image loading exceptions - you should handle them /// </summary> /// <returns>The async.</returns> /// <param name="parameters">Parameters.</param> /// <param name="target">Target.</param> /// <typeparam name="TImageView">The 1st type parameter.</typeparam> public static Task<IScheduledWork> IntoAsync<TImageView>(this TaskParameter parameters, ITarget<SelfDisposingBitmapDrawable, TImageView> target) where TImageView : class { return parameters.IntoAsync(param => param.Into(target)); } private static Task<IScheduledWork> IntoAsync(this TaskParameter parameters, Action<TaskParameter> into) { var userErrorCallback = parameters.OnError; var finishCallback = parameters.OnFinish; var tcs = new TaskCompletionSource<IScheduledWork>(); parameters .Error(ex => { tcs.TrySetException(ex); userErrorCallback?.Invoke(ex); }) .Finish(scheduledWork => { finishCallback?.Invoke(scheduledWork); tcs.TrySetResult(scheduledWork); }); into(parameters); return tcs.Task; } } }
39.570552
177
0.59845
[ "MIT" ]
melimion/FFImageLoading
source/FFImageLoading.Droid/Extensions/TaskParameterPlatformExtensions.cs
6,452
C#
using System; namespace ConsoleDemo.AbstractFactory { /// <summary> /// ClientApp startup class for Real-World /// Abstract Factory Design Pattern. /// </summary> class AnimalWorldDemo { /// <summary> /// Entry point into console application. /// </summary> public static void Run() { // Create and run the African animal world ContinentFactory africa = new AfricaFactory(); AnimalWorld world = new AnimalWorld(africa); Console.Write("In Africa: "); world.RunFoodChain(); // Create and run the American animal world ContinentFactory america = new AmericaFactory(); world = new AnimalWorld(america); Console.Write("In Amerca: "); world.RunFoodChain(); } } /// <summary> /// The 'AbstractFactory' abstract class /// </summary> abstract class ContinentFactory { public abstract Herbivore CreateHerbivore(); public abstract Carnivore CreateCarnivore(); } /// <summary> /// The 'ConcreteFactory1' class /// </summary> class AfricaFactory : ContinentFactory { public override Herbivore CreateHerbivore() { return new Wildebeast(); } public override Carnivore CreateCarnivore() { return new Lion(); } } /// <summary> /// The 'ConcreteFactory2' class /// </summary> class AmericaFactory : ContinentFactory { public override Herbivore CreateHerbivore() { return new Bison(); } public override Carnivore CreateCarnivore() { return new Wolf(); } } /// <summary> /// The 'AbstractProductA' abstract class /// </summary> abstract class Herbivore { } /// <summary> /// The 'AbstractProductB' abstract class /// </summary> abstract class Carnivore { public abstract void Eat(Herbivore h); } /// <summary> /// The 'ProductA1' class /// </summary> class Wildebeast : Herbivore { } /// <summary> /// The 'ProductB1' class /// </summary> class Lion : Carnivore { public override void Eat(Herbivore h) { // Eat Wildebeest Console.WriteLine(GetType().Name + " eats " + h.GetType().Name); } } /// <summary> /// The 'ProductA2' class /// </summary> class Bison : Herbivore { } /// <summary> /// The 'ProductB2' class /// </summary> class Wolf : Carnivore { public override void Eat(Herbivore h) { // Eat Bison Console.WriteLine(GetType().Name + " eats " + h.GetType().Name); } } }
22.625
60
0.529006
[ "MIT" ]
iQuarc/Code-Design-Training
DesignPatterns/ConsoleDemo/AbstractFactory/AbstractFactory.cs
2,898
C#
using System; using System.IO; using System.Security.Permissions; using Microsoft.Win32; using TestFramework.Run; using TestFramework.Log; using TestFramework.Exceptions; using Holodeck; using TestingFaultsXML; namespace FaultXMLTest { /// <summary> /// Summary description for FaultXMLTest2. /// </summary> public class FaultXMLTest2:FaultXMLTest { string FaultsXMLFilePath; string FaultsXMLBackupFilePath; FileInfo modifyThisFile; public FaultXMLTest2() { } public override void executeTest( ) { Console.WriteLine("Test Case : Faults.xml is renamed to testingFaults.xml"); try { string holodeckPath; holodeckPath = (string) Registry.LocalMachine.OpenSubKey ("Software\\HolodeckEE", true).GetValue ("InstallPath"); FaultsXMLFilePath = string.Concat(holodeckPath,"\\function_db\\faults.xml"); FaultsXMLBackupFilePath = string.Concat(FaultsXMLFilePath,".bak"); modifyThisFile = new FileInfo(FaultsXMLFilePath); modifyThisFile.Attributes = FileAttributes.Normal; modifyThisFile.CopyTo(FaultsXMLBackupFilePath,true); modifyThisFile.MoveTo(string.Concat(holodeckPath,"\\function_db\\testingfaults.xml")); //add code here which will launch Holodeck Holodeck.HolodeckProcess.Start(); } catch(HolodeckExceptions.IncorrectRegistryException e) { Console.WriteLine(" Incorrect Registry Exception caught.... : " + e.Message); Console.WriteLine("Details: " + e.StackTrace); } catch(FileNotFoundException f) { Console.WriteLine(" File Not Found Exception caught.... : " + f.Message); Console.WriteLine("Details: " + f.StackTrace); } finally { //reverting back to original modifyThisFile.Delete(); FileInfo regainOriginal = new FileInfo(FaultsXMLBackupFilePath); regainOriginal.MoveTo(FaultsXMLFilePath); } } } }
26.391892
118
0.691756
[ "MIT" ]
SecurityInnovation/Holodeck
Test/Frameworks/ExecutionFramework/FaultXMLTest2.cs
1,953
C#
namespace Log.It.Tests { public class Generic<T, T2> { } }
10.285714
31
0.555556
[ "MIT" ]
Fresa/Log.It
tests/Log.It.Tests/Generic.cs
74
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace CommonLib.Util { public class UtilProcess { public static void SingletonUI() { try { using (Process currentP = Process.GetCurrentProcess()) { foreach (Process p in Process.GetProcessesByName(currentP.ProcessName)) { if (p.Id != currentP.Id) { WinApi.SetForegroundWindow(p.MainWindowHandle); WinApi.ShowWindowAsync(p.MainWindowHandle, WinApi.SW_RESTORE); currentP.Kill(); } } } } catch (Exception ex) { Logger.LogThrowMessage(string.Format("Failed to leave unique UI."), new StackFrame(0).GetMethod().Name, ex.Message); } } public static void StartProcessWaitForExit(string targetFullPath, string para = "") { try { using (Process p = Process.Start(targetFullPath, para)) { p.WaitForExit(); } } catch (Exception ex) { Logger.LogThrowMessage(string.Format("Failed to start process [{0} {1}].", targetFullPath, para), new StackFrame(0).GetMethod().Name, ex.Message); } } public static void StartProcess(string targetFullPath, string para = "") { try { using (Process p = Process.Start(targetFullPath, para)) { //p.Start(); } } catch (Exception ex) { Logger.LogThrowMessage(string.Format("Failed to start process [{0} {1}].", targetFullPath, para), new StackFrame(0).GetMethod().Name, ex.Message); } } public static int StartProcessGetInt(string targetFullPath, string para = "") { try { using (Process p = new Process()) { ProcessStartInfo processStartInfo = new ProcessStartInfo(targetFullPath, para); p.StartInfo = processStartInfo; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; p.Start(); while (!p.HasExited) { p.WaitForExit(); } return p.ExitCode; } } catch (Exception ex) { Logger.LogThrowMessage(string.Format("Failed to start [{0} {1}].", targetFullPath, para), new StackFrame(0).GetMethod().Name, ex.Message); return -1; } } public static string StartProcessGetString(string targetFullPath, string para = "") { try { using (Process p = new Process()) { p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; p.StartInfo.FileName = targetFullPath; p.StartInfo.Arguments = para; p.Start(); //string dosLine = @"net use " + path + " /User:" + userName + " " + passWord + " /PERSISTENT:YES"; //proc.StandardInput.WriteLine(dosLine); //proc.StandardInput.WriteLine("exit"); p.WaitForExit(); string errormsg = ""; if (p.ExitCode != 0) { errormsg = p.StandardError.ReadToEnd(); if (!string.IsNullOrEmpty(errormsg)) { throw new Exception(errormsg.Replace(System.Environment.NewLine, " ")); } } p.StandardError.Close(); return p.StandardOutput.ReadToEnd(); } } catch (Exception ex) { throw ex; } } public static string[] StartProcessGetStrings(string targetFullPath, string para = "") { try { string strlist = UtilProcess.StartProcessGetString(targetFullPath, para); return strlist.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); } catch (Exception ex) { throw ex; } } } }
37.688406
163
0.449529
[ "MIT" ]
LuffyAutomation/UIA
CommonLib/Util/UtilProcess.cs
5,203
C#
namespace ConstellationMind.Shared.Settings { public class SwaggerSettings { public bool Enabled { get; set; } public string DocumentName { get; set; } public string Title { get; set; } public string Version { get; set; } public string RoutePrefix { get; set; } } }
26.5
48
0.616352
[ "MIT" ]
ktutak1337/ConstellationMind.Api
src/ConstellationMind.Shared/Settings/SwaggerSettings.cs
318
C#
using System; using System.Collections.Generic; using System.Text; // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace BlazorWasm.Configurations { public partial class BackendRestApiConfiguration { /// <summary> /// Enable Backend rest api /// </summary> public bool Enable { get; set; } /// <summary> /// Uri to the backend rest api /// </summary> public string Uri { get; set; } /// <summary> /// The resource path pattern to determine which request to go to backend rest api. (i.e. "/api/*") /// </summary> public string ResourcePathPattern { get; set; } /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public BackendRestApiConfiguration() { } #nullable restore warnings public BackendRestApiConfiguration( string uri, string resourcePathPattern ) { Uri = uri; ResourcePathPattern = resourcePathPattern; } } }
36.52
142
0.665936
[ "MIT" ]
96malhar/aws-dotnet-deploy
src/AWS.Deploy.Recipes/CdkTemplates/BlazorWasm/Generated/Configurations/BackendRestApiConfiguration.cs
1,826
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Optimization; using System.Web.UI; namespace LibrarySystem { public class BundleConfig { // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkID=303951 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/WebFormsJs").Include( "~/Scripts/WebForms/WebForms.js", "~/Scripts/WebForms/WebUIValidation.js", "~/Scripts/WebForms/MenuStandards.js", "~/Scripts/WebForms/Focus.js", "~/Scripts/WebForms/GridView.js", "~/Scripts/WebForms/DetailsView.js", "~/Scripts/WebForms/TreeView.js", "~/Scripts/WebForms/WebParts.js")); // Order is very important for these files to work, they have explicit dependencies bundles.Add(new ScriptBundle("~/bundles/MsAjaxJs").Include( "~/Scripts/WebForms/MsAjax/MicrosoftAjax.js", "~/Scripts/WebForms/MsAjax/MicrosoftAjaxApplicationServices.js", "~/Scripts/WebForms/MsAjax/MicrosoftAjaxTimer.js", "~/Scripts/WebForms/MsAjax/MicrosoftAjaxWebForms.js")); // Use the Development version of Modernizr to develop with and learn from. Then, when you’re // ready for production, use the build tool at http://modernizr.com to pick only the tests you need bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); } } }
45.974359
111
0.581707
[ "MIT" ]
niki-funky/Telerik_Academy
Web Development/ASP.NET Web Forms/---EXAM----/LibrarySystem/LibrarySystem/App_Start/BundleConfig.cs
1,797
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.ComponentModel; using System.Reflection; using System.Collections.Generic; using NetOffice; namespace NetOffice.VisioApi { ///<summary> /// IVWindow ///</summary> public class IVWindow_ : COMObject { #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public IVWindow_(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } /// <param name="parentObject">object there has created the proxy</param> /// <param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVWindow_(COMObject parentObject, object comProxy) : base(parentObject, comProxy) { } /// <param name="parentObject">object there has created the proxy</param> /// <param name="comProxy">inner wrapped COM proxy</param> /// <param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVWindow_(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVWindow_(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } /// <param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVWindow_(COMObject replacedObject) : base(replacedObject) { } /// <summary> /// Hidden stub .ctor /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVWindow_() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVWindow_(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> /// <param name="reviewerID">optional Int32 ReviewerID</param> [SupportByVersionAttribute("Visio", 11,12,14,15)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public bool get_ReviewerMarkupVisible(object reviewerID) { object[] paramsArray = Invoker.ValidateParamsArray(reviewerID); object returnItem = Invoker.PropertyGet(this, "ReviewerMarkupVisible", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> /// <param name="reviewerID">optional Int32 ReviewerID</param> [SupportByVersionAttribute("Visio", 11,12,14,15)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public void set_ReviewerMarkupVisible(object reviewerID, bool value) { object[] paramsArray = Invoker.ValidateParamsArray(reviewerID); Invoker.PropertySet(this, "ReviewerMarkupVisible", paramsArray, value); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Alias for get_ReviewerMarkupVisible /// </summary> /// <param name="reviewerID">optional Int32 ReviewerID</param> [SupportByVersionAttribute("Visio", 11,12,14,15)] public bool ReviewerMarkupVisible(object reviewerID) { return get_ReviewerMarkupVisible(reviewerID); } #endregion #region Methods #endregion } ///<summary> /// DispatchInterface IVWindow /// SupportByVersion Visio, 11,12,14,15 ///</summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] [EntityTypeAttribute(EntityType.IsDispatchInterface)] public class IVWindow : IVWindow_ { #pragma warning disable #region Type Information private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(IVWindow); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public IVWindow(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVWindow(COMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVWindow(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVWindow(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVWindow(COMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVWindow() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IVWindow(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public NetOffice.VisioApi.IVApplication Application { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Application", paramsArray); NetOffice.VisioApi.IVApplication newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVApplication; return newObject; } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int16 Stat { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Stat", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int16 ObjectType { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ObjectType", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int16 Type { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Type", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public NetOffice.VisioApi.IVDocument Document { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Document", paramsArray); NetOffice.VisioApi.IVDocument newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVDocument; return newObject; } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public NetOffice.VisioApi.IVPage PageAsObj { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "PageAsObj", paramsArray); NetOffice.VisioApi.IVPage newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVPage; return newObject; } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public string PageFromName { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "PageFromName", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "PageFromName", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Double Zoom { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Zoom", paramsArray); return NetRuntimeSystem.Convert.ToDouble(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Zoom", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public NetOffice.VisioApi.IVSelection Selection { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Selection", paramsArray); NetOffice.VisioApi.IVSelection newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVSelection; return newObject; } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Selection", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int16 Index { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Index", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int16 SubType { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "SubType", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public NetOffice.VisioApi.IVEventList EventList { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "EventList", paramsArray); NetOffice.VisioApi.IVEventList newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVEventList; return newObject; } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int16 PersistsEvents { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "PersistsEvents", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Int16 WindowHandle { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "WindowHandle", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int32 WindowHandle32 { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "WindowHandle32", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int16 ShowRulers { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ShowRulers", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ShowRulers", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int16 ShowGrid { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ShowGrid", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ShowGrid", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int16 ShowGuides { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ShowGuides", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ShowGuides", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int16 ShowConnectPoints { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ShowConnectPoints", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ShowConnectPoints", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int16 ShowPageBreaks { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ShowPageBreaks", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ShowPageBreaks", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public object Page { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Page", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Page", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public object Master { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Master", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int16 ShowScrollBars { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ShowScrollBars", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ShowScrollBars", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public bool Visible { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Visible", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Visible", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public string Caption { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Caption", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Caption", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public NetOffice.VisioApi.IVWindows Windows { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Windows", paramsArray); NetOffice.VisioApi.IVWindows newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVWindows; return newObject; } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int32 WindowState { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "WindowState", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "WindowState", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int32 ViewFit { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ViewFit", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ViewFit", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public bool IsEditingText { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "IsEditingText", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public bool IsEditingOLE { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "IsEditingOLE", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public NetOffice.VisioApi.IVWindows Parent { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray); NetOffice.VisioApi.IVWindows newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVWindows; return newObject; } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public NetOffice.VisioApi.IVMasterShortcut MasterShortcut { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "MasterShortcut", paramsArray); NetOffice.VisioApi.IVMasterShortcut newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVMasterShortcut; return newObject; } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int32 ID { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ID", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public NetOffice.VisioApi.IVWindow ParentWindow { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ParentWindow", paramsArray); NetOffice.VisioApi.IVWindow newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVWindow; return newObject; } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public string MergeID { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "MergeID", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "MergeID", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public string MergeClass { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "MergeClass", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "MergeClass", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int32 MergePosition { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "MergePosition", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "MergePosition", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public bool AllowEditing { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "AllowEditing", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "AllowEditing", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Double PageTabWidth { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "PageTabWidth", paramsArray); return NetRuntimeSystem.Convert.ToDouble(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "PageTabWidth", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public bool ShowPageTabs { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ShowPageTabs", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ShowPageTabs", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public bool InPlace { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "InPlace", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public string MergeCaption { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "MergeCaption", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "MergeCaption", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public stdole.Picture Icon { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Icon", paramsArray); stdole.Picture newObject = Factory.CreateObjectFromComProxy(this,returnItem) as stdole.Picture; return newObject; } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Icon", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public NetOffice.VisioApi.IVShape Shape { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Shape", paramsArray); NetOffice.VisioApi.IVShape newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVShape; return newObject; } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public NetOffice.VisioApi.IVCell SelectedCell { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "SelectedCell", paramsArray); NetOffice.VisioApi.IVCell newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVCell; return newObject; } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int32 BackgroundColor { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "BackgroundColor", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "BackgroundColor", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public Int32 BackgroundColorGradient { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "BackgroundColorGradient", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "BackgroundColorGradient", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public bool ShowPageOutline { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ShowPageOutline", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ShowPageOutline", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public bool ScrollLock { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ScrollLock", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ScrollLock", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public bool ZoomLock { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ZoomLock", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ZoomLock", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public NetOffice.VisioApi.Enums.VisZoomBehavior ZoomBehavior { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ZoomBehavior", paramsArray); int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem); return (NetOffice.VisioApi.Enums.VisZoomBehavior)intReturnItem; } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ZoomBehavior", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public object[] SelectedMasters { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "SelectedMasters", paramsArray); COMObject[] newObject = Factory.CreateObjectArrayFromComProxy(this,(object[])returnItem); return newObject; } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public NetOffice.VisioApi.IVCharacters SelectedText { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "SelectedText", paramsArray); NetOffice.VisioApi.IVCharacters newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVCharacters; return newObject; } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "SelectedText", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public bool ReviewerMarkupVisible { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ReviewerMarkupVisible", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ReviewerMarkupVisible", paramsArray); } } /// <summary> /// SupportByVersion Visio 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 12,14,15)] public NetOffice.VisioApi.IVDataRecordset SelectedDataRecordset { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "SelectedDataRecordset", paramsArray); NetOffice.VisioApi.IVDataRecordset newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVDataRecordset; return newObject; } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "SelectedDataRecordset", paramsArray); } } /// <summary> /// SupportByVersion Visio 12, 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 12,14,15)] public Int32 SelectedDataRowID { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "SelectedDataRowID", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "SelectedDataRowID", paramsArray); } } /// <summary> /// SupportByVersion Visio 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Visio", 14,15)] public NetOffice.VisioApi.IVSelection SelectionForDragCopy { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "SelectionForDragCopy", paramsArray); NetOffice.VisioApi.IVSelection newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVSelection; return newObject; } } /// <summary> /// SupportByVersion Visio 14, 15 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 14,15)] public NetOffice.VisioApi.IVValidationIssue SelectedValidationIssue { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "SelectedValidationIssue", paramsArray); NetOffice.VisioApi.IVValidationIssue newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVValidationIssue; return newObject; } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "SelectedValidationIssue", paramsArray); } } #endregion #region Methods /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public void Activate() { object[] paramsArray = null; Invoker.Method(this, "Activate", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public void Close() { object[] paramsArray = null; Invoker.Method(this, "Close", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public void SelectAll() { object[] paramsArray = null; Invoker.Method(this, "SelectAll", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public void DeselectAll() { object[] paramsArray = null; Invoker.Method(this, "DeselectAll", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> /// <param name="sheetObject">NetOffice.VisioApi.IVShape SheetObject</param> /// <param name="selectAction">Int16 SelectAction</param> [SupportByVersionAttribute("Visio", 11,12,14,15)] public void Select(NetOffice.VisioApi.IVShape sheetObject, Int16 selectAction) { object[] paramsArray = Invoker.ValidateParamsArray(sheetObject, selectAction); Invoker.Method(this, "Select", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Visio", 11,12,14,15)] public void Cut() { object[] paramsArray = null; Invoker.Method(this, "Cut", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Visio", 11,12,14,15)] public void Copy() { object[] paramsArray = null; Invoker.Method(this, "Copy", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Visio", 11,12,14,15)] public void Paste() { object[] paramsArray = null; Invoker.Method(this, "Paste", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Visio", 11,12,14,15)] public void Delete() { object[] paramsArray = null; Invoker.Method(this, "Delete", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Visio", 11,12,14,15)] public void Duplicate() { object[] paramsArray = null; Invoker.Method(this, "Duplicate", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Visio", 11,12,14,15)] public void Group() { object[] paramsArray = null; Invoker.Method(this, "Group", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Visio", 11,12,14,15)] public void Union() { object[] paramsArray = null; Invoker.Method(this, "Union", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Visio", 11,12,14,15)] public void Combine() { object[] paramsArray = null; Invoker.Method(this, "Combine", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Visio", 11,12,14,15)] public void Fragment() { object[] paramsArray = null; Invoker.Method(this, "Fragment", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Visio", 11,12,14,15)] public void AddToGroup() { object[] paramsArray = null; Invoker.Method(this, "AddToGroup", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Visio", 11,12,14,15)] public void RemoveFromGroup() { object[] paramsArray = null; Invoker.Method(this, "RemoveFromGroup", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Visio", 11,12,14,15)] public void Intersect() { object[] paramsArray = null; Invoker.Method(this, "Intersect", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Visio", 11,12,14,15)] public void Subtract() { object[] paramsArray = null; Invoker.Method(this, "Subtract", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Visio", 11,12,14,15)] public void Trim() { object[] paramsArray = null; Invoker.Method(this, "Trim", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Visio", 11,12,14,15)] public void Join() { object[] paramsArray = null; Invoker.Method(this, "Join", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> /// <param name="nameArray">String[] NameArray</param> [SupportByVersionAttribute("Visio", 11,12,14,15)] public void DockedStencils(out String[] nameArray) { ParameterModifier[] modifiers = Invoker.CreateParamModifiers(true); nameArray = null; object[] paramsArray = Invoker.ValidateParamsArray((object)nameArray); Invoker.Method(this, "DockedStencils", paramsArray, modifiers); nameArray = (String[])paramsArray[0]; } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> /// <param name="nxFlags">Int32 nxFlags</param> /// <param name="nyFlags">Int32 nyFlags</param> [SupportByVersionAttribute("Visio", 11,12,14,15)] public void Scroll(Int32 nxFlags, Int32 nyFlags) { object[] paramsArray = Invoker.ValidateParamsArray(nxFlags, nyFlags); Invoker.Method(this, "Scroll", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> /// <param name="x">Double x</param> /// <param name="y">Double y</param> [SupportByVersionAttribute("Visio", 11,12,14,15)] public void ScrollViewTo(Double x, Double y) { object[] paramsArray = Invoker.ValidateParamsArray(x, y); Invoker.Method(this, "ScrollViewTo", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> /// <param name="pdLeft">Double pdLeft</param> /// <param name="pdTop">Double pdTop</param> /// <param name="pdWidth">Double pdWidth</param> /// <param name="pdHeight">Double pdHeight</param> [SupportByVersionAttribute("Visio", 11,12,14,15)] public void GetViewRect(out Double pdLeft, out Double pdTop, out Double pdWidth, out Double pdHeight) { ParameterModifier[] modifiers = Invoker.CreateParamModifiers(true,true,true,true); pdLeft = 0; pdTop = 0; pdWidth = 0; pdHeight = 0; object[] paramsArray = Invoker.ValidateParamsArray(pdLeft, pdTop, pdWidth, pdHeight); Invoker.Method(this, "GetViewRect", paramsArray, modifiers); pdLeft = (Double)paramsArray[0]; pdTop = (Double)paramsArray[1]; pdWidth = (Double)paramsArray[2]; pdHeight = (Double)paramsArray[3]; } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> /// <param name="dLeft">Double dLeft</param> /// <param name="dTop">Double dTop</param> /// <param name="dWidth">Double dWidth</param> /// <param name="dHeight">Double dHeight</param> [SupportByVersionAttribute("Visio", 11,12,14,15)] public void SetViewRect(Double dLeft, Double dTop, Double dWidth, Double dHeight) { object[] paramsArray = Invoker.ValidateParamsArray(dLeft, dTop, dWidth, dHeight); Invoker.Method(this, "SetViewRect", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> /// <param name="pnLeft">Int32 pnLeft</param> /// <param name="pnTop">Int32 pnTop</param> /// <param name="pnWidth">Int32 pnWidth</param> /// <param name="pnHeight">Int32 pnHeight</param> [SupportByVersionAttribute("Visio", 11,12,14,15)] public void GetWindowRect(out Int32 pnLeft, out Int32 pnTop, out Int32 pnWidth, out Int32 pnHeight) { ParameterModifier[] modifiers = Invoker.CreateParamModifiers(true,true,true,true); pnLeft = 0; pnTop = 0; pnWidth = 0; pnHeight = 0; object[] paramsArray = Invoker.ValidateParamsArray(pnLeft, pnTop, pnWidth, pnHeight); Invoker.Method(this, "GetWindowRect", paramsArray, modifiers); pnLeft = (Int32)paramsArray[0]; pnTop = (Int32)paramsArray[1]; pnWidth = (Int32)paramsArray[2]; pnHeight = (Int32)paramsArray[3]; } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> /// <param name="nLeft">Int32 nLeft</param> /// <param name="nTop">Int32 nTop</param> /// <param name="nWidth">Int32 nWidth</param> /// <param name="nHeight">Int32 nHeight</param> [SupportByVersionAttribute("Visio", 11,12,14,15)] public void SetWindowRect(Int32 nLeft, Int32 nTop, Int32 nWidth, Int32 nHeight) { object[] paramsArray = Invoker.ValidateParamsArray(nLeft, nTop, nWidth, nHeight); Invoker.Method(this, "SetWindowRect", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15 /// /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15)] public NetOffice.VisioApi.IVWindow NewWindow() { object[] paramsArray = null; object returnItem = Invoker.MethodReturn(this, "NewWindow", paramsArray); NetOffice.VisioApi.IVWindow newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVWindow; return newObject; } /// <summary> /// SupportByVersion Visio 14, 15 /// /// </summary> /// <param name="sheetObject">NetOffice.VisioApi.IVShape SheetObject</param> /// <param name="flags">NetOffice.VisioApi.Enums.VisCenterViewFlags Flags</param> [SupportByVersionAttribute("Visio", 14,15)] public void CenterViewOnShape(NetOffice.VisioApi.IVShape sheetObject, NetOffice.VisioApi.Enums.VisCenterViewFlags flags) { object[] paramsArray = Invoker.ValidateParamsArray(sheetObject, flags); Invoker.Method(this, "CenterViewOnShape", paramsArray); } #endregion #pragma warning restore } }
29.123575
164
0.654411
[ "MIT" ]
NetOffice/NetOffice
Source/Visio/DispatchInterfaces/IVWindow.cs
48,549
C#
namespace MassTransit.ActiveMqTransport { using System.Collections.Generic; public interface IActiveMqHostConfigurator { /// <summary> /// Sets the username for the connection to ActiveMQ /// </summary> /// <param name="username"></param> void Username(string username); /// <summary> /// Sets the password for the connection to ActiveMQ /// </summary> /// <param name="password"></param> void Password(string password); void UseSsl(); /// <summary> /// Sets a list of hosts to enable the failover transport /// </summary> /// <param name="hosts"></param> void FailoverHosts(string[] hosts); /// <summary> /// Sets options on the underlying NMS transport /// </summary> /// <param name="options"></param> void TransportOptions(IEnumerable<KeyValuePair<string, string>> options); /// <summary> /// </summary> void EnableOptimizeAcknowledge(); void SetPrefetchPolicy(int limit); void SetQueuePrefetchPolicy(int limit); } }
26.860465
81
0.578355
[ "ECL-2.0", "Apache-2.0" ]
MathiasZander/ServiceFabricPerfomanceTest
src/Transports/MassTransit.ActiveMqTransport/Configuration/IActiveMqHostConfigurator.cs
1,157
C#
using appez.constants; using appez.listeners; using appez.model; using appez.utility; using System; namespace appez.services { /// <summary> /// Performs HTTP operations. Currently supports HTTP GET and POST /// operations. Also supports feature to create a DAT file dump that holds the response of HTTP operation /// </summary> public class HttpService : SmartService, SmartNetworkListener { #region variables public static HttpService httpService = null; private SmartEvent smartEvent = null; private SmartServiceListener smartServiceListener = null; #endregion /// <summary> /// Creates the instance of HttpService /// </summary> /// <param name="smartServiceListener">SmartServiceListener</param> public HttpService(SmartServiceListener smartServiceListener) : base() { this.smartServiceListener = smartServiceListener; } public override void ShutDown() { smartServiceListener = null; } /// <summary> /// Performs HTTP action based on SmartEvent action type /// </summary> /// <param name="smartEvent">SmartEvent specifying action type for the HTTP action</param> public override void PerformAction(SmartEvent smartEvent) { this.smartEvent = smartEvent; HttpUtility service = new HttpUtility(this); bool createFile = this.smartEvent.GetServiceOperationId() == WebEvents.WEB_HTTP_REQUEST_SAVE_DATA ? true : false; service.PerformAsyncRequest(this.smartEvent.SmartEventRequest.ServiceRequestData.ToString(), createFile); } /// <summary> /// Updates SmartEventResponse and thereby SmartEvent based on the HTTP /// operation performed in NetworkService. Also notifies SmartServiceListener /// about successful completion of HTTP operation /// </summary> /// <param name="responseData">HTTP response data</param> public void OnSuccessHttpOperation(string responseData) { SmartEventResponse smEventResponse = new SmartEventResponse(); smEventResponse.IsOperationComplete=true; smEventResponse.ServiceResponse=responseData; smEventResponse.ExceptionType=0; smEventResponse.ExceptionMessage=null; smartEvent.SmartEventResponse=smEventResponse; smartServiceListener.OnCompleteServiceWithSuccess(smartEvent); } /// <summary> /// Notifies SmartServiceListener about unsuccessful completion of HTTP /// operation /// </summary> /// <param name="exceptionType">Exception type</param> /// <param name="exceptionMessage">Message describing the type of exception</param> public void OnErrorHttpOperation(int exceptionType, String exceptionMessage) { SmartEventResponse smEventResponse = new SmartEventResponse(); smEventResponse.IsOperationComplete=false; // TODO set the response string here smEventResponse.ServiceResponse=null; smEventResponse.ExceptionType=exceptionType; smEventResponse.ExceptionMessage=exceptionMessage; smartEvent.SmartEventResponse=smEventResponse; smartServiceListener.OnCompleteServiceWithError(smartEvent); } } }
39.666667
125
0.666763
[ "MIT" ]
appez/appez-wp8
appez/services/HttpService.cs
3,453
C#
/* * SimScale API * * The version of the OpenAPI document: 0.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using OpenAPIDateConverter = SimScale.Sdk.Client.OpenAPIDateConverter; namespace SimScale.Sdk.Model { /// <summary> /// CustomSolarLoad /// </summary> [DataContract] public partial class CustomSolarLoad : OneOfSolarCalculatorSolarLoad, IEquatable<CustomSolarLoad> { /// <summary> /// Initializes a new instance of the <see cref="CustomSolarLoad" /> class. /// </summary> [JsonConstructorAttribute] protected CustomSolarLoad() { } /// <summary> /// Initializes a new instance of the <see cref="CustomSolarLoad" /> class. /// </summary> /// <param name="type">Schema name: CustomSolarLoad (required) (default to &quot;CUSTOM_SOLAR_LOAD&quot;).</param> /// <param name="directSolarLoad">directSolarLoad.</param> /// <param name="diffuseSolarLoad">diffuseSolarLoad.</param> public CustomSolarLoad(string type = "CUSTOM_SOLAR_LOAD", DimensionalHeatFlux directSolarLoad = default(DimensionalHeatFlux), DimensionalHeatFlux diffuseSolarLoad = default(DimensionalHeatFlux)) { // to ensure "type" is required (not null) this.Type = type ?? throw new ArgumentNullException("type is a required property for CustomSolarLoad and cannot be null"); this.DirectSolarLoad = directSolarLoad; this.DiffuseSolarLoad = diffuseSolarLoad; } /// <summary> /// Schema name: CustomSolarLoad /// </summary> /// <value>Schema name: CustomSolarLoad</value> [DataMember(Name="type", EmitDefaultValue=false)] public string Type { get; set; } /// <summary> /// Gets or Sets DirectSolarLoad /// </summary> [DataMember(Name="directSolarLoad", EmitDefaultValue=false)] public DimensionalHeatFlux DirectSolarLoad { get; set; } /// <summary> /// Gets or Sets DiffuseSolarLoad /// </summary> [DataMember(Name="diffuseSolarLoad", EmitDefaultValue=false)] public DimensionalHeatFlux DiffuseSolarLoad { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class CustomSolarLoad {\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" DirectSolarLoad: ").Append(DirectSolarLoad).Append("\n"); sb.Append(" DiffuseSolarLoad: ").Append(DiffuseSolarLoad).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as CustomSolarLoad); } /// <summary> /// Returns true if CustomSolarLoad instances are equal /// </summary> /// <param name="input">Instance of CustomSolarLoad to be compared</param> /// <returns>Boolean</returns> public bool Equals(CustomSolarLoad input) { if (input == null) return false; return ( this.Type == input.Type || (this.Type != null && this.Type.Equals(input.Type)) ) && ( this.DirectSolarLoad == input.DirectSolarLoad || (this.DirectSolarLoad != null && this.DirectSolarLoad.Equals(input.DirectSolarLoad)) ) && ( this.DiffuseSolarLoad == input.DiffuseSolarLoad || (this.DiffuseSolarLoad != null && this.DiffuseSolarLoad.Equals(input.DiffuseSolarLoad)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Type != null) hashCode = hashCode * 59 + this.Type.GetHashCode(); if (this.DirectSolarLoad != null) hashCode = hashCode * 59 + this.DirectSolarLoad.GetHashCode(); if (this.DiffuseSolarLoad != null) hashCode = hashCode * 59 + this.DiffuseSolarLoad.GetHashCode(); return hashCode; } } } }
36.27451
202
0.575495
[ "MIT" ]
SimScaleGmbH/simscale-csharp-sdk
src/SimScale.Sdk/Model/CustomSolarLoad.cs
5,550
C#
using System; using AutoFixture.Kernel; namespace EntityFrameworkCore.AutoFixture.Core { public class BaseTypeSpecification : IRequestSpecification { public BaseTypeSpecification(Type baseType) { this.BaseType = baseType ?? throw new ArgumentNullException(nameof(baseType)); } public Type BaseType { get; } public bool IsSatisfiedBy(object request) { return request is Type type && this.BaseType.IsAssignableFrom(type); } } }
24.086957
69
0.619134
[ "MIT" ]
aivascu/AutoFixture.AutoEFCore
src/EntityFrameworkCore.AutoFixture/Core/BaseTypeSpecification.cs
556
C#
//------------------------------------------------------------------------------ // <auto-generated> // このコードはツールによって生成されました。 // ランタイム バージョン:4.0.30319.42000 // // このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 // コードが再生成されるときに損失したりします。 // </auto-generated> //------------------------------------------------------------------------------ namespace MultiScreenSample.Properties { using System; /// <summary> /// ローカライズされた文字列などを検索するための、厳密に型指定されたリソース クラスです。 /// </summary> // このクラスは StronglyTypedResourceBuilder クラスが ResGen // または Visual Studio のようなツールを使用して自動生成されました。 // メンバーを追加または削除するには、.ResX ファイルを編集して、/str オプションと共に // ResGen を実行し直すか、または VS プロジェクトをビルドし直します。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// このクラスで使用されているキャッシュされた ResourceManager インスタンスを返します。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MultiScreenSample.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 厳密に型指定されたこのリソース クラスを使用して、すべての検索リソースに対し、 /// 現在のスレッドの CurrentUICulture プロパティをオーバーライドします。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
40.75
183
0.613113
[ "MIT" ]
rasmus-z/starshipxac.ShellLibrary
Samples/MultiScreenSample/Properties/Resources.Designer.cs
3,252
C#
 using Un4seen.Bass; using Un4seen.BassWasapi; using WASApiBassNet.Components.AudioCapture; namespace WASApiBassNet.Components.SoundLevel { public class SoundLevelCapture : ISoundLevelCapture, IAudioPlugin { /// <inheritdoc/> public bool IsStarted { get; protected set; } /// <inheritdoc/> public int LevelLeft { get; protected set; } /// <inheritdoc/> public int LevelRight { get; protected set; } /// <inheritdoc/> public void HandleTick() { if (!IsStarted) return; var level = BassWasapi.BASS_WASAPI_GetLevel(); if (level == -1) { Stop(); WASApiBassNetHelper.ThrowsAudioApiErrorException("BASS_WASAPI_GetLevel failed"); } else { LevelLeft = Utils.LowWord32(level); LevelRight = Utils.HighWord32(level); } } /// <inheritdoc/> public void Start() { IsStarted = true; } /// <inheritdoc/> public void Stop() { LevelLeft = LevelRight = 0; IsStarted = false; } } }
23.519231
96
0.52085
[ "MIT" ]
franck-gaspoz/WindowsAudioSessionSample
WASApiBassNet/Components/SoundLevel/SoundLevelCapture.cs
1,225
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Security.Models { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Security Solution Aggregated Alert information /// </summary> [Rest.Serialization.JsonTransformation] public partial class IoTSecurityAggregatedAlert { /// <summary> /// Initializes a new instance of the IoTSecurityAggregatedAlert class. /// </summary> public IoTSecurityAggregatedAlert() { CustomInit(); } /// <summary> /// Initializes a new instance of the IoTSecurityAggregatedAlert class. /// </summary> /// <param name="id">Resource Id</param> /// <param name="name">Resource name</param> /// <param name="type">Resource type</param> /// <param name="tags">Resource tags</param> /// <param name="alertType">Name of the alert type.</param> /// <param name="alertDisplayName">Display name of the alert /// type.</param> /// <param name="aggregatedDateUtc">Date of detection.</param> /// <param name="vendorName">Name of the organization that raised the /// alert.</param> /// <param name="reportedSeverity">Assessed alert severity. Possible /// values include: 'Informational', 'Low', 'Medium', 'High'</param> /// <param name="remediationSteps">Recommended steps for /// remediation.</param> /// <param name="description">Description of the suspected /// vulnerability and meaning.</param> /// <param name="count">Number of alerts occurrences within the /// aggregated time window.</param> /// <param name="effectedResourceType">Azure resource ID of the /// resource that received the alerts.</param> /// <param name="systemSource">The type of the alerted resource (Azure, /// Non-Azure).</param> /// <param name="actionTaken">IoT Security solution alert /// response.</param> /// <param name="logAnalyticsQuery">Log analytics query for getting the /// list of affected devices/alerts.</param> public IoTSecurityAggregatedAlert(string id = default(string), string name = default(string), string type = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), string alertType = default(string), string alertDisplayName = default(string), System.DateTime? aggregatedDateUtc = default(System.DateTime?), string vendorName = default(string), string reportedSeverity = default(string), string remediationSteps = default(string), string description = default(string), int? count = default(int?), string effectedResourceType = default(string), string systemSource = default(string), string actionTaken = default(string), string logAnalyticsQuery = default(string)) { Id = id; Name = name; Type = type; Tags = tags; AlertType = alertType; AlertDisplayName = alertDisplayName; AggregatedDateUtc = aggregatedDateUtc; VendorName = vendorName; ReportedSeverity = reportedSeverity; RemediationSteps = remediationSteps; Description = description; Count = count; EffectedResourceType = effectedResourceType; SystemSource = systemSource; ActionTaken = actionTaken; LogAnalyticsQuery = logAnalyticsQuery; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets resource Id /// </summary> [JsonProperty(PropertyName = "id")] public string Id { get; private set; } /// <summary> /// Gets resource name /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; private set; } /// <summary> /// Gets resource type /// </summary> [JsonProperty(PropertyName = "type")] public string Type { get; private set; } /// <summary> /// Gets or sets resource tags /// </summary> [JsonProperty(PropertyName = "tags")] public IDictionary<string, string> Tags { get; set; } /// <summary> /// Gets name of the alert type. /// </summary> [JsonProperty(PropertyName = "properties.alertType")] public string AlertType { get; private set; } /// <summary> /// Gets display name of the alert type. /// </summary> [JsonProperty(PropertyName = "properties.alertDisplayName")] public string AlertDisplayName { get; private set; } /// <summary> /// Gets date of detection. /// </summary> [JsonConverter(typeof(DateJsonConverter))] [JsonProperty(PropertyName = "properties.aggregatedDateUtc")] public System.DateTime? AggregatedDateUtc { get; private set; } /// <summary> /// Gets name of the organization that raised the alert. /// </summary> [JsonProperty(PropertyName = "properties.vendorName")] public string VendorName { get; private set; } /// <summary> /// Gets assessed alert severity. Possible values include: /// 'Informational', 'Low', 'Medium', 'High' /// </summary> [JsonProperty(PropertyName = "properties.reportedSeverity")] public string ReportedSeverity { get; private set; } /// <summary> /// Gets recommended steps for remediation. /// </summary> [JsonProperty(PropertyName = "properties.remediationSteps")] public string RemediationSteps { get; private set; } /// <summary> /// Gets description of the suspected vulnerability and meaning. /// </summary> [JsonProperty(PropertyName = "properties.description")] public string Description { get; private set; } /// <summary> /// Gets number of alerts occurrences within the aggregated time /// window. /// </summary> [JsonProperty(PropertyName = "properties.count")] public int? Count { get; private set; } /// <summary> /// Gets azure resource ID of the resource that received the alerts. /// </summary> [JsonProperty(PropertyName = "properties.effectedResourceType")] public string EffectedResourceType { get; private set; } /// <summary> /// Gets the type of the alerted resource (Azure, Non-Azure). /// </summary> [JsonProperty(PropertyName = "properties.systemSource")] public string SystemSource { get; private set; } /// <summary> /// Gets ioT Security solution alert response. /// </summary> [JsonProperty(PropertyName = "properties.actionTaken")] public string ActionTaken { get; private set; } /// <summary> /// Gets log analytics query for getting the list of affected /// devices/alerts. /// </summary> [JsonProperty(PropertyName = "properties.logAnalyticsQuery")] public string LogAnalyticsQuery { get; private set; } } }
40.926702
705
0.616477
[ "MIT" ]
LingyunSu/azure-sdk-for-net
sdk/securitycenter/Microsoft.Azure.Management.SecurityCenter/src/Generated/Models/IoTSecurityAggregatedAlert.cs
7,817
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Runtime.CompilerServices; namespace Testing_CoreV2NetCore { public abstract partial class AbstractBaseClass : BaseClassWithRequiredProperties { partial void Init(); /// <summary> /// Default constructor. Protected due to being abstract. /// </summary> protected AbstractBaseClass(): base() { Init(); } /// <summary> /// Public constructor with required data /// </summary> /// <param name="_property0"></param> protected AbstractBaseClass(string _property0) { if (string.IsNullOrEmpty(_property0)) throw new ArgumentNullException(nameof(_property0)); Property0 = _property0; Init(); } } }
29.595745
99
0.606758
[ "MIT" ]
Falthazar/EFDesigner
src/Testing/Testing_CoreV2NetCore/Generated/Entities/AbstractBaseClass.generated.cs
1,391
C#
using Azure.Storage.Blobs; using Azure.Storage.Blobs.Models; using Lombiq.Tests.UI.Helpers; using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Threading.Tasks; namespace Lombiq.Tests.UI.Services { public class AzureBlobStorageConfiguration { /// <summary> /// Gets or sets the Azure Blob Storage connection string. Defaults to local development storage (Storage /// Emulator). This configuration will be automatically passed to the tested app. /// </summary> public string ConnectionString { get; set; } = "UseDevelopmentStorage=true"; /// <summary> /// Gets or sets the Azure Blob Storage container name where all the test apps' files will be stored in /// subfolders. Defaults to <c>"LombiqUITestingToolbox"</c>. Ff you want to clean up residual files after an /// interrupted test execution you can just delete the container (it'll be created if it doesn't exist). This /// configuration will be automatically passed to the tested app. /// </summary> public string ContainerName { get; set; } = "lombiquitestingtoolbox"; } public class AzureBlobStorageRunningContext { public string BasePath { get; } public AzureBlobStorageRunningContext(string basePath) => BasePath = basePath; } public sealed class AzureBlobStorageManager : IAsyncDisposable { private static readonly PortLeaseManager _portLeaseManager; private readonly AzureBlobStorageConfiguration _configuration; private int _folderId; private string _basePath; private BlobContainerClient _blobContainer; private bool _isDisposed; // Not actually unnecessary. #pragma warning disable IDE0079 // Remove unnecessary suppression [SuppressMessage( "Performance", "CA1810:Initialize reference type static fields inline", Justification = "No GetAgentIndexOrDefault() duplication this way.")] #pragma warning restore IDE0079 // Remove unnecessary suppression static AzureBlobStorageManager() { var agentIndexTimesHundred = TestConfigurationManager.GetAgentIndexOrDefault() * 100; _portLeaseManager = new PortLeaseManager(14000 + agentIndexTimesHundred, 14099 + agentIndexTimesHundred); } public AzureBlobStorageManager(AzureBlobStorageConfiguration configuration) => _configuration = configuration; public async Task<AzureBlobStorageRunningContext> SetupBlobStorageAsync() { _blobContainer = new BlobContainerClient(_configuration.ConnectionString, _configuration.ContainerName); await CreateContainerIfNotExistsAsync(); _folderId = _portLeaseManager.LeaseAvailableRandomPort(); _basePath = _folderId.ToString(CultureInfo.InvariantCulture); await DropFolderIfExistsAsync(); return new AzureBlobStorageRunningContext(_basePath); } public Task TakeSnapshotAsync(string snapshotDirectoryPath) { var mediaFolderPath = GetMediaFolderPath(snapshotDirectoryPath); DirectoryHelper.CreateDirectoryIfNotExists(mediaFolderPath); return IterateThroughBlobsAsync( blobClient => { var blobUrl = blobClient.Name[(blobClient.Name.IndexOf('/', StringComparison.OrdinalIgnoreCase) + 1)..]; var blobPath = blobUrl.ReplaceOrdinalIgnoreCase("/", Path.DirectorySeparatorChar.ToString()); var blobFullPath = Path.Combine(mediaFolderPath, blobPath); DirectoryHelper.CreateDirectoryIfNotExists(Path.GetDirectoryName(blobFullPath)); return blobClient.DownloadToAsync(blobFullPath); }); } public async Task RestoreSnapshotAsync(string snapshotDirectoryPath) { var mediaFolderPath = GetMediaFolderPath(snapshotDirectoryPath); foreach (var filePath in Directory.EnumerateFiles(mediaFolderPath, "*.*", SearchOption.AllDirectories)) { var relativePath = filePath.ReplaceOrdinalIgnoreCase(mediaFolderPath, string.Empty); var relativeBlobUrl = relativePath.ReplaceOrdinalIgnoreCase(Path.DirectorySeparatorChar.ToString(), "/"); var blobClient = _blobContainer.GetBlobClient(_basePath + relativeBlobUrl); await blobClient.UploadAsync(filePath); } } public async ValueTask DisposeAsync() { if (_isDisposed) return; _isDisposed = true; await DropFolderIfExistsAsync(); _portLeaseManager.StopLease(_folderId); } private Task CreateContainerIfNotExistsAsync() => _blobContainer.CreateIfNotExistsAsync(PublicAccessType.None); private Task DropFolderIfExistsAsync() => IterateThroughBlobsAsync(blobClient => blobClient.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots)); private async Task IterateThroughBlobsAsync(Func<BlobClient, Task> blobProcessor) { var pages = _blobContainer.GetBlobsAsync(BlobTraits.Metadata, BlobStates.None, _basePath).AsPages(); await foreach (var page in pages) { foreach (var blob in page.Values) { await blobProcessor(_blobContainer.GetBlobClient(blob.Name)); } } } private static string GetMediaFolderPath(string snapshotDirectoryPath) => Path.Combine(Path.GetFullPath(snapshotDirectoryPath), "App_Data", "Sites", "Default", "Media"); } }
42.82963
124
0.676237
[ "BSD-3-Clause" ]
hishamco/UI-Testing-Toolbox
Lombiq.Tests.UI/Services/AzureBlobStorageManager.cs
5,782
C#
using FSO.Server.Database.DA.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FSO.Server.Database.DA.Updates { public interface IUpdates { DbUpdate GetUpdate(int update_id); IEnumerable<DbUpdate> GetRecentUpdatesForBranchByID(int branch_id, int limit); IEnumerable<DbUpdate> GetRecentUpdatesForBranchByName(string branch_name, int limit); IEnumerable<DbUpdate> GetPublishableByBranchName(string branch_name); PagedList<DbUpdate> All(int offset = 0, int limit = 20, string orderBy = "date"); int AddUpdate(DbUpdate update); bool MarkUpdatePublished(int update_id); DbUpdateAddon GetAddon(int addon_id); IEnumerable<DbUpdateAddon> GetAddons(int limit); bool AddAddon(DbUpdateAddon addon); DbUpdateBranch GetBranch(int branch_id); DbUpdateBranch GetBranch(string branch_name); IEnumerable<DbUpdateBranch> GetBranches(); bool AddBranch(DbUpdateBranch branch); bool UpdateBranchLatest(int branch_id, int last_version_number, int minor_version_number); bool UpdateBranchLatestDeployed(int branch_id, int current_dist_id); bool UpdateBranchAddon(int branch_id, int addon_id); bool UpdateBranchInfo(DbUpdateBranch branch); } }
40.088235
98
0.73661
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Blayer98/FreeSO
TSOClient/FSO.Server.Database/DA/Updates/IUpdates.cs
1,365
C#
using System; using System.Collections.Generic; using System.Reflection; using FubuCore.Conversion; namespace FubuCore.CommandLine { public class Argument : TokenHandlerBase { private readonly ObjectConverter _converter; private readonly PropertyInfo _property; private bool _isLatched; public Argument(PropertyInfo property, ObjectConverter converter) : base(property) { _property = property; _converter = converter; } public ArgumentReport ToReport() { return new ArgumentReport { Description = Description, Name = _property.Name.ToLower() }; } public override bool Handle(object input, Queue<string> tokens) { if (_isLatched) return false; if (tokens.NextIsFlag()) return false; var value = _converter.FromString(tokens.Dequeue(), _property.PropertyType); _property.SetValue(input, value, null); _isLatched = true; return true; } public override string ToUsageDescription() { if (_property.PropertyType.IsEnum) { return Enum.GetNames(_property.PropertyType).Join("|"); } return "<{0}>".ToFormat(_property.Name.ToLower()); } } }
27.396226
91
0.559917
[ "Apache-2.0" ]
DovetailSoftware/fubucore
src/FubuCore/CommandLine/Argument.cs
1,452
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\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.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AndDouble() { var test = new SimpleBinaryOpTest__AndDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.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 (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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__AndDouble { 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(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (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<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, 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<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AndDouble testClass) { var result = Sse2.And(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.And( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(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<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AndDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleBinaryOpTest__AndDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.And( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_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 = Sse2.And( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.And( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_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(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.And( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse2.And( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(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<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AndDouble(); var result = Sse2.And(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__AndDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.And( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.And(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.And( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(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 = Sse2.And(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 = Sse2.And( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&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<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((BitConverter.DoubleToInt64Bits(left[0]) & BitConverter.DoubleToInt64Bits(right[0])) != BitConverter.DoubleToInt64Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((BitConverter.DoubleToInt64Bits(left[i]) & BitConverter.DoubleToInt64Bits(right[i])) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.And)}<Double>(Vector128<Double>, Vector128<Double>): {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.088737
190
0.581455
[ "MIT" ]
06needhamt/runtime
src/coreclr/tests/src/JIT/HardwareIntrinsics/X86/Sse2/And.Double.cs
24,664
C#
using System; using System.Linq; using System.Numerics; namespace BlockChain.Core.Cryptography { public static class BASE58 { private const string Digits = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; public static string Encode(byte[] data) { // Decode byte[] to BigInteger BigInteger intData = 0; for (int i = 0; i < data.Length; i++) { intData = intData * 256 + data[i]; } // Encode BigInteger to Base58 string string result = ""; while (intData > 0) { int remainder = (int)(intData % 58); intData /= 58; result = Digits[remainder] + result; } // Append `1` for each leading 0 byte for (int i = 0; i < data.Length && data[i] == 0; i++) { result = '1' + result; } return result; } public static byte[] Decode(string s) { // Decode Base58 string to BigInteger BigInteger intData = 0; for (int i = 0; i < s.Length; i++) { int digit = Digits.IndexOf(s[i]); //Slow if (digit < 0) throw new FormatException(string.Format("Invalid Base58 character `{0}` at position {1}", s[i], i)); intData = intData * 58 + digit; } // Encode BigInteger to byte[] // Leading zero bytes get encoded as leading `1` characters int leadingZeroCount = s.TakeWhile(c => c == '1').Count(); var leadingZeros = Enumerable.Repeat((byte)0, leadingZeroCount); var bytesWithoutLeadingZeros = intData.ToByteArray() .Reverse()// to big endian .SkipWhile(b => b == 0);//strip sign byte var result = leadingZeros.Concat(bytesWithoutLeadingZeros).ToArray(); return result; } } }
25.619048
105
0.636927
[ "MIT" ]
BlockSharp/BlockChain
BlockChain.Core/Cryptography/Base58.cs
1,616
C#
// ----------------------------------------------------------------------- // <copyright file="FilterExpressionParser.cs" company="Project Contributors"> // Copyright Project Contributors // // 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 // // </copyright> // ----------------------------------------------------------------------- using System; using System.Collections.Generic; using Net.Http.OData.Model; using Net.Http.OData.Query.Expressions; namespace Net.Http.OData.Query.Parsers { internal static class FilterExpressionParser { internal static QueryNode Parse(string filterValue, EdmComplexType model) { if (model is null) { throw new ArgumentNullException(nameof(model)); } var parserImpl = new FilterExpressionParserImpl(model); QueryNode queryNode = parserImpl.ParseQueryNode(new Lexer(filterValue)); return queryNode; } private sealed class FilterExpressionParserImpl { private readonly EdmComplexType _model; private readonly Stack<QueryNode> _nodeStack = new Stack<QueryNode>(); private readonly Queue<Token> _tokens = new Queue<Token>(); private int _groupingDepth; private BinaryOperatorKind _nextBinaryOperatorKind = BinaryOperatorKind.None; internal FilterExpressionParserImpl(EdmComplexType model) => _model = model; internal QueryNode ParseQueryNode(Lexer lexer) { while (lexer.MoveNext()) { Token token = lexer.Current; switch (token.TokenType) { case TokenType.And: case TokenType.Or: _nextBinaryOperatorKind = token.Value.ToBinaryOperatorKind(); UpdateExpressionTree(); break; default: _tokens.Enqueue(token); break; } } _nextBinaryOperatorKind = BinaryOperatorKind.None; UpdateExpressionTree(); if (_groupingDepth != 0 || _nodeStack.Count != 1) { throw ODataException.BadRequest(ExceptionMessage.UnableToParseFilter("an extra opening or missing closing parenthesis may be present"), "$filter"); } QueryNode node = _nodeStack.Pop(); if (node is BinaryOperatorNode binaryNode && binaryNode.Right is null) { throw ODataException.BadRequest(ExceptionMessage.UnableToParseFilter($"the binary operator {binaryNode.OperatorKind.ToString()} has no right node"), "$filter"); } return node; } private QueryNode ParseFunctionCallNode() { BinaryOperatorNode binaryNode = null; FunctionCallNode node = null; var stack = new Stack<FunctionCallNode>(); while (_tokens.Count > 0) { Token token = _tokens.Dequeue(); switch (token.TokenType) { case TokenType.Base64Binary: case TokenType.Date: case TokenType.DateTimeOffset: case TokenType.Decimal: case TokenType.Double: case TokenType.Duration: case TokenType.EdmType: case TokenType.Enum: case TokenType.False: case TokenType.Guid: case TokenType.Integer: case TokenType.Null: case TokenType.Single: case TokenType.String: case TokenType.TimeOfDay: case TokenType.True: ConstantNode constantNode = ConstantNodeParser.ParseConstantNode(token); if (stack.Count > 0) { stack.Peek().AddParameter(constantNode); } else { if (binaryNode == null) { throw ODataException.BadRequest(ExceptionMessage.GenericUnableToParseFilter, "$filter"); } binaryNode.Right = constantNode; } break; case TokenType.BinaryOperator: binaryNode = new BinaryOperatorNode(node, token.Value.ToBinaryOperatorKind(), null); break; case TokenType.CloseParentheses: if (_groupingDepth == 0) { throw ODataException.BadRequest(ExceptionMessage.UnableToParseFilter($"the closing parenthesis not expected", token.Position), "$filter"); } _groupingDepth--; if (stack.Count > 0) { FunctionCallNode lastNode = stack.Pop(); if (stack.Count > 0) { stack.Peek().AddParameter(lastNode); } else { if (binaryNode != null) { binaryNode.Right = lastNode; } else { node = lastNode; } } } break; case TokenType.Comma: if (_tokens.Count > 0 && _tokens.Peek().TokenType == TokenType.CloseParentheses) { // If there is a comma in a function call, there should be another parameter followed by a closing comma throw ODataException.BadRequest(ExceptionMessage.UnableToParseFilter($"the function {node?.Name} has a missing parameter or extra comma", token.Position), "$filter"); } break; case TokenType.FunctionName: node = new FunctionCallNode(token.Value); break; case TokenType.OpenParentheses: if (_tokens.Count > 0 && _tokens.Peek().TokenType == TokenType.CloseParentheses) { // All OData functions have at least 1 or 2 parameters throw ODataException.BadRequest(ExceptionMessage.UnableToParseFilter($"the function {node?.Name} has no parameters specified", token.Position), "$filter"); } _groupingDepth++; stack.Push(node); break; case TokenType.PropertyName: var propertyAccessNode = new PropertyAccessNode(PropertyPath.For(token.Value, _model)); if (stack.Count > 0) { stack.Peek().AddParameter(propertyAccessNode); } else { if (binaryNode == null) { throw ODataException.BadRequest(ExceptionMessage.GenericUnableToParseFilter, "$filter"); } binaryNode.Right = propertyAccessNode; } break; default: throw ODataException.BadRequest(ExceptionMessage.UnableToParseFilter($"unexpected {token.Value}", token.Position), "$filter"); } } if (binaryNode != null) { return binaryNode; } return node; } private QueryNode ParsePropertyAccessNode() { QueryNode result = null; QueryNode leftNode = null; BinaryOperatorKind operatorKind = BinaryOperatorKind.None; QueryNode rightNode = null; while (_tokens.Count > 0) { Token token = _tokens.Dequeue(); switch (token.TokenType) { case TokenType.Base64Binary: case TokenType.Date: case TokenType.DateTimeOffset: case TokenType.Decimal: case TokenType.Double: case TokenType.Duration: case TokenType.Enum: case TokenType.False: case TokenType.Guid: case TokenType.Integer: case TokenType.Null: case TokenType.Single: case TokenType.String: case TokenType.TimeOfDay: case TokenType.True: rightNode = ConstantNodeParser.ParseConstantNode(token); break; case TokenType.BinaryOperator: if (operatorKind != BinaryOperatorKind.None) { result = new BinaryOperatorNode(leftNode, operatorKind, rightNode); leftNode = null; rightNode = null; } operatorKind = token.Value.ToBinaryOperatorKind(); break; case TokenType.CloseParentheses: _groupingDepth--; break; case TokenType.FunctionName: rightNode = new FunctionCallNode(token.Value); break; case TokenType.OpenParentheses: _groupingDepth++; break; case TokenType.PropertyName: var propertyAccessNode = new PropertyAccessNode(PropertyPath.For(token.Value, _model)); if (leftNode is null) { leftNode = propertyAccessNode; } else if (rightNode is null) { rightNode = propertyAccessNode; } break; default: throw ODataException.BadRequest(ExceptionMessage.UnableToParseFilter($"unexpected {token.Value}", token.Position), "$filter"); } } result = result is null ? new BinaryOperatorNode(leftNode, operatorKind, rightNode) : new BinaryOperatorNode(result, operatorKind, leftNode ?? rightNode); return result; } private QueryNode ParseQueryNode() { if (_tokens.Count == 0) { throw ODataException.BadRequest(ExceptionMessage.UnableToParseFilter("an incomplete filter has been specified"), "$filter"); } QueryNode node; switch (_tokens.Peek().TokenType) { case TokenType.FunctionName: node = ParseFunctionCallNode(); break; case TokenType.OpenParentheses: _groupingDepth++; _tokens.Dequeue(); node = ParseQueryNode(); break; case TokenType.PropertyName: node = ParsePropertyAccessNode(); break; case TokenType.UnaryOperator: Token token = _tokens.Dequeue(); node = ParseQueryNode(); node = new UnaryOperatorNode(node, token.Value.ToUnaryOperatorKind()); break; default: throw ODataException.BadRequest(ExceptionMessage.UnableToParseFilter($"unexpected {_tokens.Peek().Value}", _tokens.Peek().Position), "$filter"); } return node; } private void UpdateExpressionTree() { int initialGroupingDepth = _groupingDepth; QueryNode node = ParseQueryNode(); if (_groupingDepth == initialGroupingDepth) { if (_nodeStack.Count == 0) { if (_nextBinaryOperatorKind == BinaryOperatorKind.None) { _nodeStack.Push(node); } else { _nodeStack.Push(new BinaryOperatorNode(node, _nextBinaryOperatorKind, null)); } } else { QueryNode leftNode = _nodeStack.Pop(); if (leftNode is BinaryOperatorNode binaryNode && binaryNode.Right is null) { binaryNode.Right = node; if (_nextBinaryOperatorKind != BinaryOperatorKind.None) { binaryNode = new BinaryOperatorNode(binaryNode, _nextBinaryOperatorKind, null); } } else { binaryNode = new BinaryOperatorNode(leftNode, _nextBinaryOperatorKind, node); } _nodeStack.Push(binaryNode); } } else if (_groupingDepth > initialGroupingDepth) { _nodeStack.Push(new BinaryOperatorNode(node, _nextBinaryOperatorKind, null)); } else { var binaryNode = (BinaryOperatorNode)_nodeStack.Pop(); binaryNode.Right = node; if (_nextBinaryOperatorKind == BinaryOperatorKind.None) { _nodeStack.Push(binaryNode); while (_nodeStack.Count > 1) { QueryNode rightNode = _nodeStack.Pop(); var binaryParent = (BinaryOperatorNode)_nodeStack.Pop(); binaryParent.Right = rightNode; _nodeStack.Push(binaryParent); } } else { if (_groupingDepth == 0 && _nodeStack.Count > 0) { var binaryParent = (BinaryOperatorNode)_nodeStack.Pop(); binaryParent.Right = binaryNode; binaryNode = binaryParent; } _nodeStack.Push(new BinaryOperatorNode(binaryNode, _nextBinaryOperatorKind, null)); } } } } } }
39.983333
198
0.42607
[ "Apache-2.0" ]
Net-Http-OData/Net.Http.OData
Net.Http.OData/Query/Parsers/FilterExpressionParser.cs
16,795
C#
/* Copyright 2017 Coin Foundry (coinfoundry.org) Authors: Oliver Weichhold (oliver@weichhold.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. */ using System; namespace Miningcore.Persistence.Model { public class BalanceChange { public long Id { get; set; } public string PoolId { get; set; } public string Coin { get; set; } public string Address { get; set; } /// <summary> /// Amount owed in pool-base-currency (ie. Bitcoin, not Satoshis) /// </summary> public decimal Amount { get; set; } public string Usage { get; set; } public DateTime Created { get; set; } } }
39.190476
103
0.72904
[ "MIT" ]
soplainjustliketofu/miningcore
src/Miningcore/Persistence/Model/BalanceChange.cs
1,646
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using FrontEnd.Data; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using FrontEnd.Filters; namespace FrontEnd.Areas.Identity.Pages.Account { [AllowAnonymous] [SkipWelcome] public class LogoutModel : PageModel { private readonly SignInManager<User> _signInManager; private readonly ILogger<LogoutModel> _logger; public LogoutModel(SignInManager<User> signInManager, ILogger<LogoutModel> logger) { _signInManager = signInManager; _logger = logger; } public async Task<IActionResult> OnPost() { await _signInManager.SignOutAsync(); _logger.LogInformation("User logged out."); return RedirectToPage("/Index"); } } }
28.571429
90
0.7
[ "MIT" ]
3arlN3t/aspnetcore-app-workshop
src/FrontEnd/Areas/Identity/Pages/Account/Logout.cshtml.cs
1,002
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Newtonsoft.Json; using Quantumart.QP8.BLL; using Quantumart.QP8.BLL.Helpers; using Quantumart.QP8.Resources; using Quantumart.QP8.WebMvc.ViewModels.Abstract; namespace Quantumart.QP8.WebMvc.ViewModels { public class DbViewModel : EntityViewModel { public DbViewModel() { OverrideRecordsFile = false; } public Db Data { get => (Db)EntityData; set => EntityData = value; } public override string EntityTypeCode => Constants.EntityTypeCode.CustomerCode; public override string ActionCode => Constants.ActionCode.DbSettings; [Display(Name = "OverrideRecordsFile", ResourceType = typeof(DBStrings))] public bool OverrideRecordsFile { get; set; } [Display(Name = "OverrideRecordsUser", ResourceType = typeof(DBStrings))] public bool OverrideRecordsUser { get; set; } public string AggregationListItemsDataAppSettings { get; set; } public override void DoCustomBinding() { base.DoCustomBinding(); if (!string.IsNullOrEmpty(AggregationListItemsDataAppSettings)) { Data.AppSettings = JsonConvert.DeserializeObject<List<AppSettingsItem>>(AggregationListItemsDataAppSettings); } } } }
30.586957
125
0.665956
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
QuantumArt/QP
siteMvc/ViewModels/DbViewModel.cs
1,407
C#
using System; using System.Threading.Tasks; using TripLog.Models; using TripLog.Services; namespace TripLog.Droid.Services { public class LocationService : ILocationService { public async Task<GeoCoords> GetGeoCoordinatesAsync() { var location = await Xamarin.Essentials.Geolocation.GetLocationAsync(); return new GeoCoords { Latitude = location.Latitude, Longitude = location.Longitude }; } } }
23.409091
83
0.619417
[ "MIT" ]
PacktPublishing/Mastering-Xamarin-Forms-Third-Edition
Chapter4/TripLog/TripLog.Android/Services/LocationService.cs
517
C#
using System; using Xunit; using TagTool.Data.Services; using TagTool.Data.Models; using System.Threading.Tasks; using System.Net.Http; namespace TagTool.Test { public class RestServiceTest { /* Service Being Tested */ private readonly IRestService svc; /* Dependencies */ private readonly HttpClient client; public RestServiceTest() { // general arrangement client = new HttpClient(); client.BaseAddress = new Uri("https://api.what3words.com/v3/"); svc = new RestService(client); }// Constructor [Fact] public async void GetWhat3WordsAsync_WhereLatitudeOutsideAPIRange_ShouldThrowException() { // Given /* Range of W3W API is -90 to 90 for both Latitude and longitude */ // When // Then Task act1() => svc.GetWhat3WordsAsync(-100.00, 45.000); Task act2() => svc.GetWhat3WordsAsync(100.00, -45.000); await Assert.ThrowsAsync<System.Exception>(act1); await Assert.ThrowsAsync<System.Exception>(act2); } [Fact] public async void GetWhat3WordsAsync_WhereLongitudeOutsideAPIRange_ShouldThrowException() { // Given /* Range of W3W API is -90 to 90 for both Latitude and longitude */ // When // Then Task act1() => svc.GetWhat3WordsAsync(45, -100.000); Task act2() => svc.GetWhat3WordsAsync(45.00, -145.000); await Assert.ThrowsAsync<System.Exception>(act1); await Assert.ThrowsAsync<System.Exception>(act2); } [Fact] public async void GetWhat3WordsAsync_WhereWithinRange_ReturnShouldBeTypeW3WResponse() { // Given /* Range of W3W API is -90 to 90 for both Latitude and longitude */ // When var Return = await svc.GetWhat3WordsAsync(45.00, 45.000); // Then Assert.NotNull(Return); Assert.IsType<What3WordsResponse>(Return); } }// Class }// Namespace
27.2375
97
0.577329
[ "MIT" ]
ConorMcErlean/HelpingHand
TagTool.Test/ServiceTests/RestSeviceTest.cs
2,179
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Collections { public class IntervalTreeTests { private readonly struct TupleIntrospector<T> : IIntervalIntrospector<Tuple<int, int, T>> { public int GetStart(Tuple<int, int, T> value) => value.Item1; public int GetLength(Tuple<int, int, T> value) => value.Item2; } private static IEnumerable<SimpleIntervalTree<Tuple<int, int, string>, TupleIntrospector<string>>> CreateTrees(params Tuple<int, int, string>[] values) => CreateTrees((IEnumerable<Tuple<int, int, string>>)values); private static IEnumerable<SimpleIntervalTree<Tuple<int, int, string>, TupleIntrospector<string>>> CreateTrees(IEnumerable<Tuple<int, int, string>> values) { yield return SimpleIntervalTree.Create(new TupleIntrospector<string>(), values); } [Fact] public void TestEmpty() { foreach (var tree in CreateTrees()) { var spans = tree.GetIntervalsThatOverlapWith(0, 1); Assert.Empty(spans); } } [Fact] public void TestBeforeSpan() { foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A"))) { var spans = tree.GetIntervalsThatOverlapWith(0, 1); Assert.Empty(spans); } } [Fact] public void TestAbuttingBeforeSpan() { foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A"))) { var spans = tree.GetIntervalsThatOverlapWith(0, 5); Assert.Empty(spans); } } [Fact] public void TestAfterSpan() { foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A"))) { var spans = tree.GetIntervalsThatOverlapWith(15, 5); Assert.Empty(spans); } } [Fact] public void TestAbuttingAfterSpan() { foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A"))) { var spans = tree.GetIntervalsThatOverlapWith(10, 5); Assert.Empty(spans); } } [Fact] public void TestMatchingSpan() { foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A"))) { var spans = tree.GetIntervalsThatOverlapWith(5, 5).Select(t => t.Item3); Assert.True(Set("A").SetEquals(spans)); } } [Fact] public void TestContainedAbuttingStart() { foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A"))) { var spans = tree.GetIntervalsThatOverlapWith(5, 2).Select(i => i.Item3); Assert.True(Set("A").SetEquals(spans)); } } [Fact] public void TestContainedAbuttingEnd() { foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A"))) { var spans = tree.GetIntervalsThatOverlapWith(8, 2).Select(i => i.Item3); Assert.True(Set("A").SetEquals(spans)); } } [Fact] public void TestCompletedContained() { foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A"))) { var spans = tree.GetIntervalsThatOverlapWith(7, 2).Select(i => i.Item3); Assert.True(Set("A").SetEquals(spans)); } } [Fact] public void TestOverlappingStart() { foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A"))) { var spans = tree.GetIntervalsThatOverlapWith(4, 2).Select(i => i.Item3); Assert.True(Set("A").SetEquals(spans)); } } [Fact] public void TestOverlappingEnd() { foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A"))) { var spans = tree.GetIntervalsThatOverlapWith(9, 2).Select(i => i.Item3); Assert.True(Set("A").SetEquals(spans)); } } [Fact] public void TestOverlappingAll() { foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A"))) { var spans = tree.GetIntervalsThatOverlapWith(4, 7).Select(i => i.Item3); Assert.True(Set("A").SetEquals(spans)); } } [Fact] public void TestNonOverlappingSpans() { foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A"), Tuple.Create(15, 5, "B"))) { // Test between the spans Assert.Empty(tree.GetIntervalsThatOverlapWith(2, 2)); Assert.Empty(tree.GetIntervalsThatOverlapWith(11, 2)); Assert.Empty(tree.GetIntervalsThatOverlapWith(22, 2)); // Test in the spans Assert.True(Set("A").SetEquals(tree.GetIntervalsThatOverlapWith(6, 2).Select(i => i.Item3))); Assert.True(Set("B").SetEquals(tree.GetIntervalsThatOverlapWith(16, 2).Select(i => i.Item3))); // Test covering both spans Assert.True(Set("A", "B").SetEquals(tree.GetIntervalsThatOverlapWith(2, 20).Select(i => i.Item3))); Assert.True(Set("A", "B").SetEquals(tree.GetIntervalsThatOverlapWith(2, 14).Select(i => i.Item3))); Assert.True(Set("A", "B").SetEquals(tree.GetIntervalsThatOverlapWith(6, 10).Select(i => i.Item3))); Assert.True(Set("A", "B").SetEquals(tree.GetIntervalsThatOverlapWith(6, 20).Select(i => i.Item3))); } } [Fact] public void TestSubsumedSpans() { var spans = List( Tuple.Create(5, 5, "a"), Tuple.Create(6, 3, "b"), Tuple.Create(7, 1, "c")); TestOverlapsAndIntersects(spans); } [Fact] public void TestOverlappingSpans() { var spans = List( Tuple.Create(5, 5, "a"), Tuple.Create(7, 5, "b"), Tuple.Create(9, 5, "c")); TestOverlapsAndIntersects(spans); } [Fact] public void TestIntersectsWith() { var spans = List( Tuple.Create(0, 2, "a")); foreach (var tree in CreateTrees(spans)) { Assert.False(tree.HasIntervalThatIntersectsWith(-1)); Assert.True(tree.HasIntervalThatIntersectsWith(0)); Assert.True(tree.HasIntervalThatIntersectsWith(1)); Assert.True(tree.HasIntervalThatIntersectsWith(2)); Assert.False(tree.HasIntervalThatIntersectsWith(3)); } } [Fact] public void LargeTest() { var spans = List( Tuple.Create(0, 3, "a"), Tuple.Create(5, 3, "b"), Tuple.Create(6, 4, "c"), Tuple.Create(8, 1, "d"), Tuple.Create(15, 8, "e"), Tuple.Create(16, 5, "f"), Tuple.Create(17, 2, "g"), Tuple.Create(19, 1, "h"), Tuple.Create(25, 5, "i")); TestOverlapsAndIntersects(spans); } [Fact] public void TestCrash1() { foreach (var _ in CreateTrees(Tuple.Create(8, 1, "A"), Tuple.Create(59, 1, "B"), Tuple.Create(52, 1, "C"))) { } } [Fact] public void TestEmptySpanAtStart() { // Make sure creating empty spans works (there was a bug here) var tree = CreateTrees(Tuple.Create(0, 0, "A")).Last(); Assert.Equal(1, tree.Count()); } private readonly struct Int32Introspector : IIntervalIntrospector<int> { public int GetLength(int value) => 0; public int GetStart(int value) => value; } private static IntervalTree<int> CreateIntTree(params int[] values) => IntervalTree<int>.Create(new Int32Introspector(), values); [Fact] public void TestSortedEnumerable1() { Assert.Equal(CreateIntTree(0, 0, 0), new[] { 0, 0, 0 }); Assert.Equal(CreateIntTree(0, 0, 1), new[] { 0, 0, 1 }); Assert.Equal(CreateIntTree(0, 0, 2), new[] { 0, 0, 2 }); Assert.Equal(CreateIntTree(0, 1, 0), new[] { 0, 0, 1 }); Assert.Equal(CreateIntTree(0, 1, 1), new[] { 0, 1, 1 }); Assert.Equal(CreateIntTree(0, 1, 2), new[] { 0, 1, 2 }); Assert.Equal(CreateIntTree(0, 2, 0), new[] { 0, 0, 2 }); Assert.Equal(CreateIntTree(0, 2, 1), new[] { 0, 1, 2 }); Assert.Equal(CreateIntTree(0, 2, 2), new[] { 0, 2, 2 }); Assert.Equal(CreateIntTree(1, 0, 0), new[] { 0, 0, 1 }); Assert.Equal(CreateIntTree(1, 0, 1), new[] { 0, 1, 1 }); Assert.Equal(CreateIntTree(1, 0, 2), new[] { 0, 1, 2 }); Assert.Equal(CreateIntTree(1, 1, 0), new[] { 0, 1, 1 }); Assert.Equal(CreateIntTree(1, 1, 1), new[] { 1, 1, 1 }); Assert.Equal(CreateIntTree(1, 1, 2), new[] { 1, 1, 2 }); Assert.Equal(CreateIntTree(1, 2, 0), new[] { 0, 1, 2 }); Assert.Equal(CreateIntTree(1, 2, 1), new[] { 1, 1, 2 }); Assert.Equal(CreateIntTree(1, 2, 2), new[] { 1, 2, 2 }); Assert.Equal(CreateIntTree(2, 0, 0), new[] { 0, 0, 2 }); Assert.Equal(CreateIntTree(2, 0, 1), new[] { 0, 1, 2 }); Assert.Equal(CreateIntTree(2, 0, 2), new[] { 0, 2, 2 }); Assert.Equal(CreateIntTree(2, 1, 0), new[] { 0, 1, 2 }); Assert.Equal(CreateIntTree(2, 1, 1), new[] { 1, 1, 2 }); Assert.Equal(CreateIntTree(2, 1, 2), new[] { 1, 2, 2 }); Assert.Equal(CreateIntTree(2, 2, 0), new[] { 0, 2, 2 }); Assert.Equal(CreateIntTree(2, 2, 1), new[] { 1, 2, 2 }); Assert.Equal(CreateIntTree(2, 2, 2), new[] { 2, 2, 2 }); } [Fact] public void TestSortedEnumerable2() { var tree = IntervalTree<int>.Create(new Int32Introspector(), new[] { 1, 0 }); Assert.Equal(tree, new[] { 0, 1 }); } private static void TestOverlapsAndIntersects(IList<Tuple<int, int, string>> spans) { foreach (var tree in CreateTrees(spans)) { var max = spans.Max(t => t.Item1 + t.Item2); for (var start = 0; start <= max; start++) { for (var length = 1; length <= max; length++) { var span = new Span(start, length); var set1 = new HashSet<string>(tree.GetIntervalsThatOverlapWith(start, length).Select(i => i.Item3)); var set2 = new HashSet<string>(spans.Where(t => { return span.OverlapsWith(new Span(t.Item1, t.Item2)); }).Select(t => t.Item3)); Assert.True(set1.SetEquals(set2)); var set3 = new HashSet<string>(tree.GetIntervalsThatIntersectWith(start, length).Select(i => i.Item3)); var set4 = new HashSet<string>(spans.Where(t => { return span.IntersectsWith(new Span(t.Item1, t.Item2)); }).Select(t => t.Item3)); Assert.True(set3.SetEquals(set4)); } } Assert.Equal(spans.Count, tree.Count()); Assert.True(new HashSet<string>(spans.Select(t => t.Item3)).SetEquals(tree.Select(i => i.Item3))); } } private static ISet<T> Set<T>(params T[] values) => new HashSet<T>(values); private static IList<T> List<T>(params T[] values) => new List<T>(values); } }
35.573034
163
0.50766
[ "MIT" ]
333fred/roslyn
src/EditorFeatures/Test/Collections/IntervalTreeTests.cs
12,666
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using AspNet.Security.OpenIdConnect.Extensions; using AspNet.Security.OpenIdConnect.Primitives; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; using OpenIddict.Abstractions; using OpenIddict.Mvc.Internal; using OpenIddict.Server; using OrchardCore.Environment.Shell; using OrchardCore.Modules; using OrchardCore.OpenId.Abstractions.Managers; using OrchardCore.OpenId.Filters; using OrchardCore.OpenId.Services; using OrchardCore.OpenId.ViewModels; using OrchardCore.Routing; using OrchardCore.Security.Services; using OrchardCore.Users.Services; namespace OrchardCore.OpenId.Controllers { [Authorize, Feature(OpenIdConstants.Features.Server), OpenIdController] public class AccessController : Controller { private readonly IOpenIdApplicationManager _applicationManager; private readonly IOpenIdAuthorizationManager _authorizationManager; private readonly IOpenIdScopeManager _scopeManager; private readonly ShellSettings _shellSettings; private readonly IStringLocalizer<AccessController> S; public AccessController( IOpenIdApplicationManager applicationManager, IOpenIdAuthorizationManager authorizationManager, IStringLocalizer<AccessController> localizer, IOpenIdScopeManager scopeManager, ShellSettings shellSettings, IOpenIdServerService serverService) { S = localizer; _applicationManager = applicationManager; _authorizationManager = authorizationManager; _scopeManager = scopeManager; _shellSettings = shellSettings; } [AllowAnonymous, HttpGet, HttpPost, IgnoreAntiforgeryToken] public async Task<IActionResult> Authorize([ModelBinder(typeof(OpenIddictMvcBinder))] OpenIdConnectRequest request) { // Retrieve the claims stored in the authentication cookie. // If they can't be extracted, redirect the user to the login page. var result = await HttpContext.AuthenticateAsync(); if (result == null || !result.Succeeded || request.HasPrompt(OpenIddictConstants.Prompts.Login)) { return RedirectToLoginPage(request); } // If a max_age parameter was provided, ensure that the cookie is not too old. // If it's too old, automatically redirect the user agent to the login page. if (request.MaxAge != null && result.Properties.IssuedUtc != null && DateTimeOffset.UtcNow - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value)) { return RedirectToLoginPage(request); } var application = await _applicationManager.FindByClientIdAsync(request.ClientId); if (application == null) { return View("Error", new ErrorViewModel { Error = OpenIddictConstants.Errors.InvalidClient, ErrorDescription = S["The specified 'client_id' parameter is invalid."] }); } var authorizations = await _authorizationManager.FindAsync( subject: result.Principal.GetUserIdentifier(), client: await _applicationManager.GetIdAsync(application), status: OpenIddictConstants.Statuses.Valid, type: OpenIddictConstants.AuthorizationTypes.Permanent, scopes: ImmutableArray.CreateRange(request.GetScopes())); switch (await _applicationManager.GetConsentTypeAsync(application)) { case OpenIddictConstants.ConsentTypes.External when authorizations.IsEmpty: return RedirectToClient(new OpenIdConnectResponse { Error = OpenIddictConstants.Errors.ConsentRequired, ErrorDescription = S["The logged in user is not allowed to access this client application."] }); case OpenIddictConstants.ConsentTypes.Implicit: case OpenIddictConstants.ConsentTypes.External when authorizations.Any(): case OpenIddictConstants.ConsentTypes.Explicit when authorizations.Any() && !request.HasPrompt(OpenIddictConstants.Prompts.Consent): var authorization = authorizations.LastOrDefault(); var ticket = await CreateUserTicketAsync(result.Principal, application, authorization, request); return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme); case OpenIddictConstants.ConsentTypes.Explicit when request.HasPrompt(OpenIddictConstants.Prompts.None): return RedirectToClient(new OpenIdConnectResponse { Error = OpenIddictConstants.Errors.ConsentRequired, ErrorDescription = S["Interactive user consent is required."] }); default: return View(new AuthorizeViewModel { ApplicationName = await _applicationManager.GetDisplayNameAsync(application), RequestId = request.RequestId, Scope = request.Scope }); } } [ActionName(nameof(Authorize))] [FormValueRequired("submit.Accept"), HttpPost] public async Task<IActionResult> AuthorizeAccept([ModelBinder(typeof(OpenIddictMvcBinder))] OpenIdConnectRequest request) { // Warning: unlike the main Authorize method, this method MUST NOT be decorated with // [IgnoreAntiforgeryToken] as we must be able to reject authorization requests // sent by a malicious client that could abuse this interactive endpoint to silently // get codes/tokens without the user explicitly approving the authorization demand. var application = await _applicationManager.FindByClientIdAsync(request.ClientId); if (application == null) { return View("Error", new ErrorViewModel { Error = OpenIddictConstants.Errors.InvalidClient, ErrorDescription = S["The specified 'client_id' parameter is invalid."] }); } var authorizations = await _authorizationManager.FindAsync( subject: User.GetUserIdentifier(), client: await _applicationManager.GetIdAsync(application), status: OpenIddictConstants.Statuses.Valid, type: OpenIddictConstants.AuthorizationTypes.Permanent, scopes: ImmutableArray.CreateRange(request.GetScopes())); // Note: the same check is already made in the GET action but is repeated // here to ensure a malicious user can't abuse this POST endpoint and // force it to return a valid response without the external authorization. switch (await _applicationManager.GetConsentTypeAsync(application)) { case OpenIddictConstants.ConsentTypes.External when authorizations.IsEmpty: return RedirectToClient(new OpenIdConnectResponse { Error = OpenIddictConstants.Errors.ConsentRequired, ErrorDescription = S["The logged in user is not allowed to access this client application."] }); default: var authorization = authorizations.LastOrDefault(); var ticket = await CreateUserTicketAsync(User, application, authorization, request); return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme); } } [ActionName(nameof(Authorize))] [FormValueRequired("submit.Deny"), HttpPost] public IActionResult AuthorizeDeny() => Forbid(OpenIddictServerDefaults.AuthenticationScheme); [AllowAnonymous, HttpGet, HttpPost, IgnoreAntiforgeryToken] public async Task<IActionResult> Logout([ModelBinder(typeof(OpenIddictMvcBinder))] OpenIdConnectRequest request) { if (!string.IsNullOrEmpty(request.PostLogoutRedirectUri)) { // If the user is not logged in, allow redirecting the user agent back to the // specified post_logout_redirect_uri without rendering a confirmation form. var result = await HttpContext.AuthenticateAsync(); if (result == null || !result.Succeeded) { return SignOut(OpenIddictServerDefaults.AuthenticationScheme); } } return View(new LogoutViewModel { RequestId = request.RequestId }); } [ActionName(nameof(Logout)), AllowAnonymous] [FormValueRequired("submit.Accept"), HttpPost] public async Task<IActionResult> LogoutAccept([ModelBinder(typeof(OpenIddictMvcBinder))] OpenIdConnectRequest request) { // Warning: unlike the main Logout method, this method MUST NOT be decorated with // [IgnoreAntiforgeryToken] as we must be able to reject end session requests // sent by a malicious client that could abuse this interactive endpoint to silently // log the user out without the user explicitly approving the log out operation. await HttpContext.SignOutAsync(); // If no post_logout_redirect_uri was specified, redirect the user agent // to the root page, that should correspond to the home page in most cases. if (string.IsNullOrEmpty(request.PostLogoutRedirectUri)) { return Redirect("~/"); } return SignOut(OpenIddictServerDefaults.AuthenticationScheme); } [ActionName(nameof(Logout)), AllowAnonymous] [FormValueRequired("submit.Deny"), HttpPost] public IActionResult LogoutDeny() => Redirect("~/"); [AllowAnonymous, HttpPost] [IgnoreAntiforgeryToken] [Produces("application/json")] public async Task<IActionResult> Token([ModelBinder(typeof(OpenIddictMvcBinder))] OpenIdConnectRequest request) { // Warning: this action is decorated with IgnoreAntiforgeryTokenAttribute to override // the global antiforgery token validation policy applied by the MVC modules stack, // which is required for this stateless OAuth2/OIDC token endpoint to work correctly. // To prevent effective CSRF/session fixation attacks, this action MUST NOT return // an authentication cookie or try to establish an ASP.NET Core user session. if (request.IsPasswordGrantType()) { return await ExchangePasswordGrantType(request); } if (request.IsClientCredentialsGrantType()) { return await ExchangeClientCredentialsGrantType(request); } if (request.IsAuthorizationCodeGrantType() || request.IsRefreshTokenGrantType()) { return await ExchangeAuthorizationCodeOrRefreshTokenGrantType(request); } throw new NotSupportedException("The specified grant type is not supported."); } private async Task<IActionResult> ExchangeClientCredentialsGrantType(OpenIdConnectRequest request) { // Note: client authentication is always enforced by OpenIddict before this action is invoked. var application = await _applicationManager.FindByClientIdAsync(request.ClientId); if (application == null) { return BadRequest(new OpenIdConnectResponse { Error = OpenIddictConstants.Errors.InvalidClient, ErrorDescription = S["The specified 'client_id' parameter is invalid."] }); } var identity = new ClaimsIdentity( OpenIddictServerDefaults.AuthenticationScheme, OpenIddictConstants.Claims.Name, OpenIddictConstants.Claims.Role); identity.AddClaim(OpenIdConstants.Claims.EntityType, OpenIdConstants.EntityTypes.Application, OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken); identity.AddClaim(OpenIddictConstants.Claims.Subject, request.ClientId, OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken); identity.AddClaim(OpenIddictConstants.Claims.Name, await _applicationManager.GetDisplayNameAsync(application), OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken); // If the role service is available, add all the role claims // associated with the application roles in the database. var roleService = HttpContext.RequestServices.GetService<IRoleService>(); foreach (var role in await _applicationManager.GetRolesAsync(application)) { identity.AddClaim(identity.RoleClaimType, role, OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken); if (roleService != null) { foreach (var claim in await roleService.GetRoleClaimsAsync(role)) { identity.AddClaim(claim.SetDestinations( OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken)); } } } var ticket = new AuthenticationTicket( new ClaimsPrincipal(identity), new AuthenticationProperties(), OpenIddictServerDefaults.AuthenticationScheme); ticket.SetResources(await GetResourcesAsync(request.GetScopes())); return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme); } private async Task<IActionResult> ExchangePasswordGrantType(OpenIdConnectRequest request) { var application = await _applicationManager.FindByClientIdAsync(request.ClientId); if (application == null) { return BadRequest(new OpenIdConnectResponse { Error = OpenIddictConstants.Errors.InvalidClient, ErrorDescription = S["The specified 'client_id' parameter is invalid."] }); } // By design, the password flow requires direct username/password validation, which is performed by // the user service. If this service is not registered, prevent the password flow from being used. var service = HttpContext.RequestServices.GetService<IUserService>(); if (service == null) { return BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.UnsupportedGrantType, ErrorDescription = S["The resource owner password credentials grant is not supported."] }); } string error = null; var user = await service.AuthenticateAsync(request.Username, request.Password, (key, message) => error = message); if (user == null) { return BadRequest(new OpenIdConnectResponse { Error = OpenIddictConstants.Errors.InvalidGrant, ErrorDescription = error }); } var principal = await service.CreatePrincipalAsync(user); Debug.Assert(principal != null, "The user principal shouldn't be null."); var authorizations = await _authorizationManager.FindAsync( subject: principal.GetUserIdentifier(), client: await _applicationManager.GetIdAsync(application), status: OpenIddictConstants.Statuses.Valid, type: OpenIddictConstants.AuthorizationTypes.Permanent, scopes: ImmutableArray.CreateRange(request.GetScopes())); // If the application is configured to use external consent, // reject the request if no existing authorization can be found. switch (await _applicationManager.GetConsentTypeAsync(application)) { case OpenIddictConstants.ConsentTypes.External when authorizations.IsEmpty: return BadRequest(new OpenIdConnectResponse { Error = OpenIddictConstants.Errors.ConsentRequired, ErrorDescription = S["The logged in user is not allowed to access this client application."] }); } var ticket = await CreateUserTicketAsync(principal, application, authorizations.LastOrDefault(), request); return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme); } private async Task<IActionResult> ExchangeAuthorizationCodeOrRefreshTokenGrantType(OpenIdConnectRequest request) { var application = await _applicationManager.FindByClientIdAsync(request.ClientId); if (application == null) { return BadRequest(new OpenIdConnectResponse { Error = OpenIddictConstants.Errors.InvalidClient, ErrorDescription = S["The specified 'client_id' parameter is invalid."] }); } // Retrieve the claims principal stored in the authorization code/refresh token. var info = await HttpContext.AuthenticateAsync(OpenIddictServerDefaults.AuthenticationScheme); Debug.Assert(info.Principal != null, "The user principal shouldn't be null."); if (request.IsRefreshTokenGrantType()) { var type = info.Principal.FindFirst(OpenIdConstants.Claims.EntityType)?.Value; if (!string.Equals(type, OpenIdConstants.EntityTypes.User)) { return BadRequest(new OpenIdConnectResponse { Error = OpenIddictConstants.Errors.UnauthorizedClient, ErrorDescription = S["The refresh token grant type is not allowed for refresh " + "tokens retrieved using the client credentials flow."] }); } } // By default, re-use the principal stored in the authorization code/refresh token. var principal = info.Principal; // If the user service is available, try to refresh the principal by retrieving // the user object from the database and creating a new claims-based principal. var service = HttpContext.RequestServices.GetService<IUserService>(); if (service != null) { var user = await service.GetUserByUniqueIdAsync(principal.GetUserIdentifier()); if (user != null) { principal = await service.CreatePrincipalAsync(user); } } // Create a new authentication ticket, but reuse the properties stored in the // authorization code/refresh token, including the scopes originally granted. var ticket = await CreateUserTicketAsync(principal, application, null, request, info.Properties); return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme); } private async Task<AuthenticationTicket> CreateUserTicketAsync( ClaimsPrincipal principal, object application, object authorization, OpenIdConnectRequest request, AuthenticationProperties properties = null) { Debug.Assert(request.IsAuthorizationRequest() || request.IsTokenRequest(), "The request should be an authorization or token request."); var identity = (ClaimsIdentity)principal.Identity; // Note: make sure this claim is not added multiple times (which may happen when the principal // was extracted from an authorization code or from a refresh token ticket is re-used as-is). if (string.IsNullOrEmpty(principal.FindFirst(OpenIdConstants.Claims.EntityType)?.Value)) { identity.AddClaim(OpenIdConstants.Claims.EntityType, OpenIdConstants.EntityTypes.User, OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken); } // Note: while ASP.NET Core Identity uses the legacy WS-Federation claims (exposed by the ClaimTypes class), // OpenIddict uses the newer JWT claims defined by the OpenID Connect specification. To ensure the mandatory // subject claim is correctly populated (and avoid an InvalidOperationException), it's manually added here. if (string.IsNullOrEmpty(principal.FindFirst(OpenIdConnectConstants.Claims.Subject)?.Value)) { identity.AddClaim(new Claim(OpenIdConnectConstants.Claims.Subject, principal.GetUserIdentifier())); } // Create a new authentication ticket holding the user identity. var ticket = new AuthenticationTicket(principal, properties, OpenIddictServerDefaults.AuthenticationScheme); if (request.IsAuthorizationRequest() || (!request.IsAuthorizationCodeGrantType() && !request.IsRefreshTokenGrantType())) { // Set the list of scopes granted to the client application. // Note: the offline_access scope must be granted // to allow OpenIddict to return a refresh token. ticket.SetScopes(request.GetScopes()); ticket.SetResources(await GetResourcesAsync(request.GetScopes())); // If the request is an authorization request, automatically create // a permanent authorization to avoid requiring explicit consent for // future authorization or token requests containing the same scopes. if (authorization == null && request.IsAuthorizationRequest()) { authorization = await _authorizationManager.CreateAsync( principal: ticket.Principal, subject: principal.GetUserIdentifier(), client: await _applicationManager.GetIdAsync(application), type: OpenIddictConstants.AuthorizationTypes.Permanent, scopes: ImmutableArray.CreateRange(ticket.GetScopes()), properties: ImmutableDictionary.CreateRange(ticket.Properties.Items)); } if (authorization != null) { // Attach the authorization identifier to the authentication ticket. ticket.SetInternalAuthorizationId(await _authorizationManager.GetIdAsync(authorization)); } } // Note: by default, claims are NOT automatically included in the access and identity tokens. // To allow OpenIddict to serialize them, you must attach them a destination, that specifies // whether they should be included in access tokens, in identity tokens or in both. foreach (var claim in ticket.Principal.Claims) { // Never include the security stamp in the access and identity tokens, as it's a secret value. if (claim.Type == "AspNet.Identity.SecurityStamp") { continue; } var destinations = new List<string> { OpenIddictConstants.Destinations.AccessToken }; // Only add the iterated claim to the id_token if the corresponding scope was granted to the client application. // The other claims will only be added to the access_token, which is encrypted when using the default format. if ((claim.Type == OpenIddictConstants.Claims.Name && ticket.HasScope(OpenIddictConstants.Scopes.Profile)) || (claim.Type == OpenIddictConstants.Claims.Email && ticket.HasScope(OpenIddictConstants.Scopes.Email)) || (claim.Type == OpenIddictConstants.Claims.Role && ticket.HasScope(OpenIddictConstants.Claims.Roles)) || (claim.Type == OpenIdConstants.Claims.EntityType)) { destinations.Add(OpenIddictConstants.Destinations.IdentityToken); } claim.SetDestinations(destinations); } return ticket; } private async Task<IEnumerable<string>> GetResourcesAsync(IEnumerable<string> scopes) { // Note: the current tenant name is always added as a valid resource/audience, // which allows the end user to use the corresponding tokens with the APIs // located in the current tenant without having to explicitly register a scope. var resources = new List<string>(1); resources.Add(OpenIdConstants.Prefixes.Tenant + _shellSettings.Name); resources.AddRange(await _scopeManager.ListResourcesAsync(scopes.ToImmutableArray())); return resources; } private IActionResult RedirectToClient(OpenIdConnectResponse response) { var properties = new AuthenticationProperties(new Dictionary<string, string> { [OpenIddictConstants.Properties.Error] = response.Error, [OpenIddictConstants.Properties.ErrorDescription] = response.ErrorDescription, [OpenIddictConstants.Properties.ErrorUri] = response.ErrorUri, }); return Forbid(properties, OpenIddictServerDefaults.AuthenticationScheme); } private IActionResult RedirectToLoginPage(OpenIdConnectRequest request) { // If the client application requested promptless authentication, // return an error indicating that the user is not logged in. if (request.HasPrompt(OpenIddictConstants.Prompts.None)) { return RedirectToClient(new OpenIdConnectResponse { Error = OpenIddictConstants.Errors.LoginRequired, ErrorDescription = S["The user is not logged in."] }); } string GetRedirectUrl() { // Override the prompt parameter to prevent infinite authentication/authorization loops. var parameters = Request.Query.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); parameters[OpenIddictConstants.Parameters.Prompt] = "continue"; return Request.PathBase + Request.Path + QueryString.Create(parameters); } return Challenge(new AuthenticationProperties { RedirectUri = GetRedirectUrl() }); } } }
49.403846
129
0.626774
[ "BSD-3-Clause" ]
Craige/OrchardCore
src/OrchardCore.Modules/OrchardCore.OpenId/Controllers/AccessController.cs
28,259
C#
#region Header // // Project: WriteableBitmapEx - Silverlight WriteableBitmap extensions // Description: App Page of WinPhone Curve demo. // // Changed by: $Author: unknown $ // Changed on: $Date: 2015-03-04 13:35:03 +0100 (Mi, 04 Mrz 2015) $ // Changed in: $Revision: 113142 $ // Project: $URL: https://writeablebitmapex.svn.codeplex.com/svn/trunk/Source/WriteableBitmapExWinPhoneCurveSample/App.xaml.cs $ // Id: $Id: App.xaml.cs 113142 2015-03-04 12:35:03Z unknown $ // // // Copyright © 2009-2015 Rene Schulte and WriteableBitmapEx Contributors // // This is code open source. Please read the License.txt for details. No worries, we won't sue you! ;) // #endregion using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; namespace WriteableBitmapExWinPhoneCurveSample { public partial class App : Application { /// <summary> /// Provides easy access to the root frame of the Phone Application. /// </summary> /// <returns>The root frame of the Phone Application.</returns> public PhoneApplicationFrame RootFrame { get; private set; } /// <summary> /// Constructor for the Application object. /// </summary> public App() { // Global handler for uncaught exceptions. UnhandledException += Application_UnhandledException; // Show graphics profiling information while debugging. if (System.Diagnostics.Debugger.IsAttached) { // Display the current frame rate counters. Application.Current.Host.Settings.EnableFrameRateCounter = true; // Show the areas of the app that are being redrawn in each frame. //Application.Current.Host.Settings.EnableRedrawRegions = true; // Enable non-production analysis visualization mode, // which shows areas of a page that are being GPU accelerated with a colored overlay. //Application.Current.Host.Settings.EnableCacheVisualization = true; } // Standard Silverlight initialization InitializeComponent(); // Phone-specific initialization InitializePhoneApplication(); } // Code to execute when the application is launching (eg, from Start) // This code will not execute when the application is reactivated private void Application_Launching(object sender, LaunchingEventArgs e) { } // Code to execute when the application is activated (brought to foreground) // This code will not execute when the application is first launched private void Application_Activated(object sender, ActivatedEventArgs e) { } // Code to execute when the application is deactivated (sent to background) // This code will not execute when the application is closing private void Application_Deactivated(object sender, DeactivatedEventArgs e) { } // Code to execute when the application is closing (eg, user hit Back) // This code will not execute when the application is deactivated private void Application_Closing(object sender, ClosingEventArgs e) { } // Code to execute if a navigation fails private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e) { if (System.Diagnostics.Debugger.IsAttached) { // A navigation has failed; break into the debugger System.Diagnostics.Debugger.Break(); } } // Code to execute on Unhandled Exceptions private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) { if (System.Diagnostics.Debugger.IsAttached) { // An unhandled exception has occurred; break into the debugger System.Diagnostics.Debugger.Break(); } } #region Phone application initialization // Avoid double-initialization private bool phoneApplicationInitialized = false; // Do not add any additional code to this method private void InitializePhoneApplication() { if (phoneApplicationInitialized) return; // Create the frame but don't set it as RootVisual yet; this allows the splash // screen to remain active until the application is ready to render. RootFrame = new PhoneApplicationFrame(); RootFrame.Navigated += CompleteInitializePhoneApplication; // Handle navigation failures RootFrame.NavigationFailed += RootFrame_NavigationFailed; // Ensure we don't initialize again phoneApplicationInitialized = true; } // Do not add any additional code to this method private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e) { // Set the root visual to allow the application to render if (RootVisual != RootFrame) RootVisual = RootFrame; // Remove this handler since it is no longer needed RootFrame.Navigated -= CompleteInitializePhoneApplication; } #endregion } }
37.176471
141
0.655063
[ "MIT" ]
Chriscolm/WriteableBitmapEx
Source/WriteableBitmapExWinPhoneCurveSample/App.xaml.cs
5,691
C#
using System.ComponentModel.DataAnnotations; using WeLearn.Data.Common.Models; using static WeLearn.Data.Common.Validation.DataValidation.Video; namespace WeLearn.Data.Models.LessonModule { public class Video : BaseDeletableModel<int> { [Required] [MaxLength(MaxNameLength)] public string Name { get; set; } [Required] public string ContentType { get; set; } [Required] [MaxLength(MaxLinkLength)] public string Link { get; set; } public string PublicId { get; set; } public int LessonId { get; set; } public Lesson Lesson { get; set; } } }
22.37931
65
0.637904
[ "MIT" ]
kristiyanivanovx/WeLearn
src/Data/WeLearn.Data.Models/LessonModule/Video.cs
651
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="LanguageFileToNameConverter.cs" company="Slash Games"> // Copyright (c) Slash Games. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace BlueprintEditor.Converters { using System; using System.Globalization; using System.Windows.Data; using Slash.Tools.BlueprintEditor.Logic.Context; public class LanguageFileToNameConverter : IValueConverter { #region Public Methods and Operators public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { LanguageFile languageFile = (LanguageFile)value; return string.Format("{0}: {1}", languageFile.LanguageTag, languageFile.Path); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } #endregion } }
35.90625
120
0.5396
[ "MIT" ]
SlashGames/slash-framework
Tools/BlueprintEditor/Slash.Tools.BlueprintEditor.WPF/Source/Converters/LanguageFileToNameConverter.cs
1,151
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20 { using Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.PowerShell; /// <summary> /// The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location /// </summary> [System.ComponentModel.TypeConverter(typeof(ProxyResourceTypeConverter))] public partial class ProxyResource { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// <c>OverrideToString</c> will be called if it is implemented. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="stringResult">/// instance serialized to a string, normally it is a Json</param> /// <param name="returnNow">/// set returnNow to true if you provide a customized OverrideToString function</param> partial void OverrideToString(ref string stringResult, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.ProxyResource" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.IProxyResource" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.IProxyResource DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new ProxyResource(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.ProxyResource" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.IProxyResource" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.IProxyResource DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new ProxyResource(content); } /// <summary> /// Creates a new instance of <see cref="ProxyResource" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.IProxyResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.ProxyResource" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal ProxyResource(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("Id")) { ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.IResourceInternal)this).Id, global::System.Convert.ToString); } if (content.Contains("Name")) { ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.IResourceInternal)this).Name, global::System.Convert.ToString); } if (content.Contains("Type")) { ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.IResourceInternal)this).Type, global::System.Convert.ToString); } AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.ProxyResource" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal ProxyResource(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("Id")) { ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.IResourceInternal)this).Id, global::System.Convert.ToString); } if (content.Contains("Name")) { ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.IResourceInternal)this).Name, global::System.Convert.ToString); } if (content.Contains("Type")) { ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.IResourceInternal)this).Type, global::System.Convert.ToString); } AfterDeserializePSObject(content); } /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.SerializationMode.IncludeAll)?.ToString(); public override string ToString() { var returnNow = false; var result = global::System.String.Empty; OverrideToString(ref result, ref returnNow); if (returnNow) { return result; } return ToJsonString(); } } /// The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location [System.ComponentModel.TypeConverter(typeof(ProxyResourceTypeConverter))] public partial interface IProxyResource { } }
60.288889
289
0.669738
[ "MIT" ]
Agazoth/azure-powershell
src/ConnectedNetwork/generated/api/Models/Api20/ProxyResource.PowerShell.cs
10,673
C#
using UnityEngine; using System.Collections; using UnityEngine.UI; namespace Imperio { /// <summary> /// Efecto que muestra el daño hecho a minions o players /// </summary> public class DamageEffect : MonoBehaviour { /// <summary> /// Referencia para poder modificar el alpha el objeto /// </summary> [SerializeField] private CanvasGroup cg; /// <summary> /// Referencia al texto /// </summary> [SerializeField] private Text AmountText; /// <summary> /// Crea el damage effect en la posición y con el daño establecido /// </summary> /// <param name="position">Position.</param> /// <param name="amount">Amount.</param> public static void CreateDamageEffect(Vector3 position, int amount) { if (amount == 0) return; GameObject newDamageEffect = GameObject.Instantiate(GameManager.Instance.DamageEffectPrefab, position, Quaternion.identity, GameManager.Instance.GlobalCanvas.transform); DamageEffect de = newDamageEffect.GetComponent<DamageEffect>(); de.AmountText.text = amount.ToString(); //Iniciamos la corrutina que lo vuelve transparente de.StartCoroutine(de.ShowDamageEffect()); } //Corrutina que controla el Fading private IEnumerator ShowDamageEffect() { //Opaco cg.alpha = 1f; yield return new WaitForSeconds(1f); //Modificamos gradualmente el alpha while (cg.alpha > 0) { cg.alpha -= 0.05f; yield return new WaitForSeconds(0.05f); } //Cuando se vuelve transparente, se destruye Destroy(gameObject); } } }
29.380952
181
0.578066
[ "Unlicense" ]
RaulSerranoDev/CardGame
ProjectImperio/Assets/Scripts/Visual/DamageEffect.cs
1,856
C#
//----------------------------------------------------------------------------- // Filename: RTPSession.cs // // Description: Represents an RTP session constituted of a single media stream. The session // does not control the sockets as they may be shared by multiple sessions. // // Author(s): // Aaron Clauson (aaron@sipsorcery.com) // // History: // 25 Aug 2019 Aaron Clauson Created, Montreux, Switzerland. // 12 Nov 2019 Aaron Clauson Added send event method. // 07 Dec 2019 Aaron Clauson Big refactor. Brought in a lot of functions previously // in the RTPChannel class. // // License: // BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file. //----------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using SIPSorcery.SIP.App; using SIPSorcery.Sys; using SIPSorceryMedia.Abstractions; namespace SIPSorcery.Net { public delegate int ProtectRtpPacket(byte[] payload, int length, out int outputBufferLength); public enum SetDescriptionResultEnum { /// <summary> /// At least one media stream with a compatible format was available. /// </summary> OK, /// <summary> /// Both parties had audio but no compatible format was available. /// </summary> AudioIncompatible, /// <summary> /// Both parties had video but no compatible format was available. /// </summary> VideoIncompatible, /// <summary> /// No media tracks are available on the local session. /// </summary> NoLocalMedia, /// <summary> /// The remote description did not contain any media announcements. /// </summary> NoRemoteMedia, /// <summary> /// Indicates there was no media type match. For example only have audio locally /// but video remote or vice-versa. /// </summary> NoMatchingMediaType, /// <summary> /// An unknown error. /// </summary> Error, /// <summary> /// A required DTLS fingerprint was missing from the session description. /// </summary> DtlsFingerprintMissing, /// <summary> /// The DTLS fingerprint was present but the format was not recognised. /// </summary> DtlsFingerprintInvalid, /// <summary> /// The DTLS fingerprint was provided with an unsupported digest. It won't /// be possible to check that the certificate supplied during the DTLS handshake /// matched the fingerprint. /// </summary> DtlsFingerprintDigestNotSupported, /// <summary> /// An unsupported data channel transport was requested (at the time of writing only /// SCTP over DTLS is supported, no TCP option). /// </summary> DataChannelTransportNotSupported, /// <summary> /// An SDP offer was received when the local agent had already entered have local offer state. /// </summary> WrongSdpTypeOfferAfterOffer, } /// <summary> /// The RTPSession class is the primary point for interacting with the Real-Time /// Protocol. It manages all the resources required for setting up and then sending /// and receiving RTP packets. This class IS designed to be inherited by child /// classes and for child classes to add audio and video processing logic. /// </summary> /// <remarks> /// The setting up of an RTP stream involved the exchange of Session Descriptions /// (SDP) with the remote party. This class has adopted the mechanism used by WebRTC. /// The steps are: /// 1. If acting as the initiator: /// a. Create offer, /// b. Send offer to remote party and get their answer (external to this class, requires signalling), /// c. Set remote description, /// d. Optionally perform any additional set up, such as negotiating SRTP keying material, /// e. Call Start to commence RTCP reporting. /// 2. If acting as the recipient: /// a. Receive offer, /// b. Set remote description. This step MUST be done before an SDP answer can be generated. /// This step can also result in an error condition if the codecs/formats offered aren't supported, /// c. Create answer, /// d. Send answer to remote party (external to this class, requires signalling), /// e. Optionally perform any additional set up, such as negotiating SRTP keying material, /// f. Call Start to commence RTCP reporting. /// </remarks> public class RTPSession : IMediaSession, IDisposable { private const int RTP_MAX_PAYLOAD = 1400; /// <summary> /// From libsrtp: SRTP_MAX_TRAILER_LEN is the maximum length of the SRTP trailer /// (authentication tag and MKI) supported by libSRTP.This value is /// the maximum number of octets that will be added to an RTP packet by /// srtp_protect(). /// /// srtp_protect(): /// @warning This function assumes that it can write SRTP_MAX_TRAILER_LEN /// into the location in memory immediately following the RTP packet. /// Callers MUST ensure that this much writable memory is available in /// the buffer that holds the RTP packet. /// /// srtp_protect_rtcp(): /// @warning This function assumes that it can write SRTP_MAX_TRAILER_LEN+4 /// to the location in memory immediately following the RTCP packet. /// Callers MUST ensure that this much writable memory is available in /// the buffer that holds the RTCP packet. /// </summary> public const int SRTP_MAX_PREFIX_LENGTH = 148; private const int DEFAULT_AUDIO_CLOCK_RATE = 8000; public const int RTP_EVENT_DEFAULT_SAMPLE_PERIOD_MS = 50; // Default sample period for an RTP event as specified by RFC2833. public const SDPMediaTypesEnum DEFAULT_MEDIA_TYPE = SDPMediaTypesEnum.audio; // If we can't match an RTP payload ID assume it's audio. public const int DEFAULT_DTMF_EVENT_PAYLOAD_ID = 101; public const string RTP_MEDIA_PROFILE = "RTP/AVP"; private const int SDP_SESSIONID_LENGTH = 10; // The length of the pseudo-random string to use for the session ID. public const int DTMF_EVENT_DURATION = 1200; // Default duration for a DTMF event. public const int DTMF_EVENT_PAYLOAD_ID = 101; private static ILogger logger = Log.Logger; private bool m_isMediaMultiplexed = false; // Indicates whether audio and video are multiplexed on a single RTP channel or not. private bool m_isRtcpMultiplexed = false; // Indicates whether the RTP channel is multiplexing RTP and RTCP packets on the same port. private IPAddress m_bindAddress = null; // If set the address to use for binding the RTP and control sockets. private int m_bindPort = 0; // If non-zero specifies the port number to attempt to bind the first RTP socket on. private bool m_rtpEventInProgress; // Gets set to true when an RTP event is being sent and the normal stream is interrupted. private uint m_lastRtpTimestamp; // The last timestamp used in an RTP packet. private RtpVideoFramer _rtpVideoFramer; private string m_sdpSessionID = null; // Need to maintain the same SDP session ID for all offers and answers. private int m_sdpAnnouncementVersion = 0; // The SDP version needs to increase whenever the local SDP is modified (see https://tools.ietf.org/html/rfc6337#section-5.2.5). internal Dictionary<SDPMediaTypesEnum, RTPChannel> m_rtpChannels = new Dictionary<SDPMediaTypesEnum, RTPChannel>(); /// <summary> /// The local audio stream for this session. Will be null if we are not sending audio. /// </summary> public virtual MediaStreamTrack AudioLocalTrack { get; private set; } /// <summary> /// The remote audio track for this session. Will be null if the remote party is not sending audio. /// </summary> public virtual MediaStreamTrack AudioRemoteTrack { get; private set; } /// <summary> /// The reporting session for the audio stream. Will be null if only video is being sent. /// </summary> public RTCPSession AudioRtcpSession { get; private set; } /// <summary> /// The local video track for this session. Will be null if we are not sending video. /// </summary> public MediaStreamTrack VideoLocalTrack { get; private set; } /// <summary> /// The remote video track for this session. Will be null if the remote party is not sending video. /// </summary> public MediaStreamTrack VideoRemoteTrack { get; private set; } /// <summary> /// The reporting session for the video stream. Will be null if only audio is being sent. /// </summary> public RTCPSession VideoRtcpSession { get; private set; } /// <summary> /// The SDP offered by the remote call party for this session. /// </summary> public SDP RemoteDescription { get; protected set; } /// <summary> /// Function pointer to an SRTP context that encrypts an RTP packet. /// </summary> private ProtectRtpPacket m_srtpProtect; /// <summary> /// Function pointer to an SRTP context that decrypts an RTP packet. /// </summary> private ProtectRtpPacket m_srtpUnprotect; /// <summary> /// Function pointer to an SRTCP context that encrypts an RTP packet. /// </summary> private ProtectRtpPacket m_srtcpControlProtect; /// <summary> /// Function pointer to an SRTP context that decrypts an RTP packet. /// </summary> private ProtectRtpPacket m_srtcpControlUnprotect; /// <summary> /// Indicates whether this session is using a secure SRTP context to encrypt RTP and /// RTCP packets. /// </summary> public bool IsSecure { get; private set; } = false; /// <summary> /// If this session is using a secure context this flag MUST be set to indicate /// the security delegate (SrtpProtect, SrtpUnprotect etc) have been set. /// </summary> public bool IsSecureContextReady { get; private set; } = false; /// <summary> /// The remote RTP end point this session is sending audio to. /// </summary> public IPEndPoint AudioDestinationEndPoint { get; protected set; } /// <summary> /// The remote RTP control end point this session is sending to RTCP reports /// for the audio stream to. /// </summary> public IPEndPoint AudioControlDestinationEndPoint { get; private set; } /// <summary> /// The remote RTP end point this session is sending video to. /// </summary> public IPEndPoint VideoDestinationEndPoint { get; private set; } /// <summary> /// The remote RTP control end point this session is sending to RTCP reports /// for the video stream to. /// </summary> public IPEndPoint VideoControlDestinationEndPoint { get; private set; } /// <summary> /// In order to detect RTP events from the remote party this property needs to /// be set to the payload ID they are using. /// </summary> public int RemoteRtpEventPayloadID { get; set; } = DEFAULT_DTMF_EVENT_PAYLOAD_ID; /// <summary> /// Indicates whether the session has been closed. Once a session is closed it cannot /// be restarted. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Indicates whether the session has been started. Starting a session tells the RTP /// socket to start receiving, /// </summary> public bool IsStarted { get; private set; } /// <summary> /// Indicates whether this session is using audio. /// </summary> public bool HasAudio { get { return AudioLocalTrack != null && AudioLocalTrack.StreamStatus != MediaStreamStatusEnum.Inactive && AudioRemoteTrack != null && AudioRemoteTrack.StreamStatus != MediaStreamStatusEnum.Inactive; } } /// <summary> /// Indicates whether this session is using video. /// </summary> public bool HasVideo { get { return VideoLocalTrack != null && VideoLocalTrack.StreamStatus != MediaStreamStatusEnum.Inactive && VideoRemoteTrack != null && VideoRemoteTrack.StreamStatus != MediaStreamStatusEnum.Inactive; } } /// <summary> /// If set to true RTP will be accepted from ANY remote end point. If false /// certain rules are used to determine whether RTP should be accepted for /// a particular audio or video stream. It is recommended to leave the /// value to false unless a specific need exists. /// </summary> public bool AcceptRtpFromAny { get; set; } = false; /// <summary> /// Gets fired when an RTP packet is received from a remote party. /// Parameters are: /// - Remote endpoint packet was received from, /// - The media type the packet contains, will be audio or video, /// - The full RTP packet. /// </summary> public event Action<IPEndPoint, SDPMediaTypesEnum, RTPPacket> OnRtpPacketReceived; /// <summary> /// Gets fired when an RTP event is detected on the remote call party's RTP stream. /// </summary> public event Action<IPEndPoint, RTPEvent, RTPHeader> OnRtpEvent; /// <summary> /// Gets fired when the RTP session and underlying channel are closed. /// </summary> public event Action<string> OnRtpClosed; /// <summary> /// Gets fired when an RTCP BYE packet is received from the remote party. /// The string parameter contains the BYE reason. Normally a BYE /// report means the RTP session is finished. But... cases have been observed where /// an RTCP BYE is received when a remote party is put on hold and then the session /// resumes when take off hold. It's up to the application to decide what action to /// take when n RTCP BYE is received. /// </summary> public event Action<string> OnRtcpBye; /// <summary> /// Fires when the connection for a media type is classified as timed out due to not /// receiving any RTP or RTCP packets within the given period. /// </summary> public event Action<SDPMediaTypesEnum> OnTimeout; /// <summary> /// Gets fired when an RTCP report is received. This event is for diagnostics only. /// </summary> public event Action<IPEndPoint, SDPMediaTypesEnum, RTCPCompoundPacket> OnReceiveReport; /// <summary> /// Gets fired when an RTCP report is sent. This event is for diagnostics only. /// </summary> public event Action<SDPMediaTypesEnum, RTCPCompoundPacket> OnSendReport; /// <summary> /// Gets fired when the start method is called on the session. This is the point /// audio and video sources should commence generating samples. /// </summary> public event Action OnStarted; /// <summary> /// Gets fired when the session is closed. This is the point audio and video /// source should stop generating samples. /// </summary> public event Action OnClosed; /// <summary> /// Gets fired when the remote SDP is received and the set of common audio formats is set. /// </summary> public event Action<List<AudioFormat>> OnAudioFormatsNegotiated; /// <summary> /// Gets fired when the remote SDP is received and the set of common video formats is set. /// </summary> public event Action<List<VideoFormat>> OnVideoFormatsNegotiated; /// <summary> /// Gets fired when a full video frame is reconstructed from one or more RTP packets /// received from the remote party. /// </summary> /// <remarks> /// - Received from end point, /// - The frame timestamp, /// - The encoded video frame payload. /// - The video format of the encoded frame. /// </remarks> public event Action<IPEndPoint, uint, byte[], VideoFormat> OnVideoFrameReceived; /// <summary> /// Creates a new RTP session. The synchronisation source and sequence number are initialised to /// pseudo random values. /// </summary> /// <param name="isRtcpMultiplexed">If true RTCP reports will be multiplexed with RTP on a single channel. /// If false (standard mode) then a separate socket is used to send and receive RTCP reports.</param> /// <param name="isSecure">If true indicated this session is using SRTP to encrypt and authorise /// RTP and RTCP packets. No communications or reporting will commence until the /// is explicitly set as complete.</param> /// <param name="isMediaMultiplexed">If true only a single RTP socket will be used for both audio /// and video (standard case for WebRTC). If false two separate RTP sockets will be used for /// audio and video (standard case for VoIP).</param> /// <param name="bindAddress">Optional. If specified this address will be used as the bind address for any RTP /// and control sockets created. Generally this address does not need to be set. The default behaviour /// is to bind to [::] or 0.0.0.0,d depending on system support, which minimises network routing /// causing connection issues.</param> /// <param name="bindPort">Optional. If specified a single attempt will be made to bind the RTP socket /// on this port. It's recommended to leave this parameter as the default of 0 to let the Operating /// System select the port number.</param> public RTPSession( bool isMediaMultiplexed, bool isRtcpMultiplexed, bool isSecure, IPAddress bindAddress = null, int bindPort = 0) { m_isMediaMultiplexed = isMediaMultiplexed; m_isRtcpMultiplexed = isRtcpMultiplexed; IsSecure = isSecure; m_bindAddress = bindAddress; m_bindPort = bindPort; m_sdpSessionID = Crypto.GetRandomInt(SDP_SESSIONID_LENGTH).ToString(); } /// <summary> /// Used for child classes that require a single RTP channel for all RTP (audio and video) /// and RTCP communications. /// </summary> protected void addSingleTrack() { // We use audio as the media type when multiplexing. CreateRtpChannel(SDPMediaTypesEnum.audio); AudioRtcpSession = CreateRtcpSession(SDPMediaTypesEnum.audio); } /// <summary> /// Adds a media track to this session. A media track represents an audio or video /// stream and can be a local (which means we're sending) or remote (which means /// we're receiving). /// </summary> /// <param name="track">The media track to add to the session.</param> public virtual void addTrack(MediaStreamTrack track) { if (track.IsRemote) { AddRemoteTrack(track); } else { AddLocalTrack(track); } } /// <summary> /// Generates the SDP for an offer that can be made to a remote user agent. /// </summary> /// <param name="connectionAddress">Optional. If specified this IP address /// will be used as the address advertised in the SDP offer. If not provided /// the kernel routing table will be used to determine the local IP address used /// for Internet access.</param> /// <returns>A task that when complete contains the SDP offer.</returns> public virtual SDP CreateOffer(IPAddress connectionAddress) { if (AudioLocalTrack == null && VideoLocalTrack == null) { logger.LogWarning("No local media tracks available for create offer."); return null; } else { List<MediaStreamTrack> localTracks = GetLocalTracks(); var offerSdp = GetSessionDesciption(localTracks, connectionAddress); return offerSdp; } } /// <summary> /// Generates an SDP answer in response to an offer. The remote description MUST be set /// prior to calling this method. /// </summary> /// <param name="connectionAddress">Optional. If set this address will be used as /// the SDP Connection address. If not specified the Operating System routing table /// will be used to lookup the address used to connect to the SDP connection address /// from the remote offer.</param> /// <returns>A task that when complete contains the SDP answer.</returns> /// <remarks>As specified in https://tools.ietf.org/html/rfc3264#section-6.1. /// "If the answerer has no media formats in common for a particular /// offered stream, the answerer MUST reject that media stream by setting /// the port to zero." /// </remarks> public virtual SDP CreateAnswer(IPAddress connectionAddress) { if (RemoteDescription == null) { throw new ApplicationException("The remote description is not set, cannot create SDP answer."); } else { var offer = RemoteDescription; List<MediaStreamTrack> tracks = new List<MediaStreamTrack>(); // The order of the announcements in the answer must match the order in the offer. foreach (var announcement in offer.Media) { // Adjust the local audio tracks to only include compatible capabilities. if (announcement.Media == SDPMediaTypesEnum.audio) { if (AudioLocalTrack != null) { tracks.Add(AudioLocalTrack); } } else if (announcement.Media == SDPMediaTypesEnum.video) { if (VideoLocalTrack != null) { tracks.Add(VideoLocalTrack); } } } if (connectionAddress == null) { // No specific connection address supplied. Lookup the local address to connect to the offer address. var offerConnectionAddress = (offer.Connection?.ConnectionAddress != null) ? IPAddress.Parse(offer.Connection.ConnectionAddress) : null; if (offerConnectionAddress == null || offerConnectionAddress == IPAddress.Any || offerConnectionAddress == IPAddress.IPv6Any) { connectionAddress = NetServices.InternetDefaultAddress; } else { connectionAddress = NetServices.GetLocalAddressForRemote(offerConnectionAddress); } } var answerSdp = GetSessionDesciption(tracks, connectionAddress); return answerSdp; } } /// <summary> /// Sets the remote SDP description for this session. /// </summary> /// <param name="sdpType">Whether the remote SDP is an offer or answer.</param> /// <param name="sessionDescription">The SDP that will be set as the remote description.</param> /// <returns>If successful an OK enum result. If not an enum result indicating the failure cause.</returns> public virtual SetDescriptionResultEnum SetRemoteDescription(SdpType sdpType, SDP sessionDescription) { if (sessionDescription == null) { throw new ArgumentNullException("sessionDescription", "The session description cannot be null for SetRemoteDescription."); } try { if (sessionDescription.Media?.Count == 0) { return SetDescriptionResultEnum.NoRemoteMedia; } else if (sessionDescription.Media?.Count == 1) { var remoteMediaType = sessionDescription.Media.First().Media; if (remoteMediaType == SDPMediaTypesEnum.audio && AudioLocalTrack == null) { return SetDescriptionResultEnum.NoMatchingMediaType; } else if (remoteMediaType == SDPMediaTypesEnum.video && VideoLocalTrack == null) { return SetDescriptionResultEnum.NoMatchingMediaType; } } // Pre-flight checks have passed. Move onto matching up the local and remote media streams. IPAddress connectionAddress = null; if (sessionDescription.Connection != null && !String.IsNullOrEmpty(sessionDescription.Connection.ConnectionAddress)) { connectionAddress = IPAddress.Parse(sessionDescription.Connection.ConnectionAddress); } IPEndPoint remoteAudioRtpEP = null; IPEndPoint remoteAudioRtcpEP = null; IPEndPoint remoteVideoRtpEP = null; IPEndPoint remoteVideoRtcpEP = null; foreach (var announcement in sessionDescription.Media.Where(x => x.Media == SDPMediaTypesEnum.audio || x.Media == SDPMediaTypesEnum.video)) { MediaStreamStatusEnum mediaStreamStatus = announcement.MediaStreamStatus.HasValue ? announcement.MediaStreamStatus.Value : MediaStreamStatusEnum.SendRecv; var remoteTrack = new MediaStreamTrack(announcement.Media, true, announcement.MediaFormats.Values.ToList(), mediaStreamStatus, announcement.SsrcAttributes); addTrack(remoteTrack); if (announcement.Media == SDPMediaTypesEnum.audio) { if (AudioLocalTrack == null) { // We don't have an audio track BUT we must have another track (which has to be video). The choices are // to reject the offer or to set audio stream as inactive and accept the video. We accept the video. var inactiveLocalAudioTrack = new MediaStreamTrack(SDPMediaTypesEnum.audio, false, remoteTrack.Capabilities, MediaStreamStatusEnum.Inactive); addTrack(inactiveLocalAudioTrack); } else { AudioLocalTrack.Capabilities = SDPAudioVideoMediaFormat.GetCompatibleFormats(announcement.MediaFormats.Values.ToList(), AudioLocalTrack?.Capabilities); remoteAudioRtpEP = GetAnnouncementRTPDestination(announcement, connectionAddress); // Check whether RTP events can be supported and adjust our parameters to match the remote party if we can. SDPAudioVideoMediaFormat commonEventFormat = SDPAudioVideoMediaFormat.GetCommonRtpEventFormat(announcement.MediaFormats.Values.ToList(), AudioLocalTrack.Capabilities); if (!commonEventFormat.IsEmpty()) { RemoteRtpEventPayloadID = commonEventFormat.ID; } SetLocalTrackStreamStatus(AudioLocalTrack, remoteTrack.StreamStatus, remoteAudioRtpEP); if (remoteTrack.StreamStatus != MediaStreamStatusEnum.Inactive && AudioLocalTrack.StreamStatus != MediaStreamStatusEnum.Inactive) { remoteAudioRtcpEP = (m_isRtcpMultiplexed) ? remoteAudioRtpEP : new IPEndPoint(remoteAudioRtpEP.Address, remoteAudioRtpEP.Port + 1); } } } else if (announcement.Media == SDPMediaTypesEnum.video) { if (VideoLocalTrack == null) { // We don't have a video track BUT we must have another track (which has to be audio). The choices are // to reject the offer or to set video stream as inactive and accept the audio. We accept the audio. var inactiveLocalVideoTrack = new MediaStreamTrack(SDPMediaTypesEnum.video, false, remoteTrack.Capabilities, MediaStreamStatusEnum.Inactive); addTrack(inactiveLocalVideoTrack); } else { VideoLocalTrack.Capabilities = SDPAudioVideoMediaFormat.GetCompatibleFormats(announcement.MediaFormats.Values.ToList(), VideoLocalTrack?.Capabilities); remoteVideoRtpEP = GetAnnouncementRTPDestination(announcement, connectionAddress); SetLocalTrackStreamStatus(VideoLocalTrack, remoteTrack.StreamStatus, remoteVideoRtpEP); if (remoteTrack.StreamStatus != MediaStreamStatusEnum.Inactive && VideoLocalTrack.StreamStatus != MediaStreamStatusEnum.Inactive) { remoteVideoRtcpEP = (m_isRtcpMultiplexed) ? remoteVideoRtpEP : new IPEndPoint(remoteVideoRtpEP.Address, remoteVideoRtpEP.Port + 1); } } } } if (VideoLocalTrack == null && AudioLocalTrack != null && AudioLocalTrack.Capabilities?.Where(x => x.Name().ToLower() != SDP.TELEPHONE_EVENT_ATTRIBUTE).Count() == 0) { return SetDescriptionResultEnum.AudioIncompatible; } else if (AudioLocalTrack == null && VideoLocalTrack != null && VideoLocalTrack.Capabilities?.Count == 0) { return SetDescriptionResultEnum.VideoIncompatible; } else { if (AudioLocalTrack != null && AudioLocalTrack.Capabilities.Where(x => x.Name().ToLower() != SDP.TELEPHONE_EVENT_ATTRIBUTE).Count() > 0) { OnAudioFormatsNegotiated?.Invoke( AudioLocalTrack.Capabilities .Where(x => x.Name().ToLower() != SDP.TELEPHONE_EVENT_ATTRIBUTE) .Select(x => x.ToAudioFormat()).ToList()); } if (VideoLocalTrack != null && VideoLocalTrack.Capabilities?.Count() > 0) { OnVideoFormatsNegotiated?.Invoke( VideoLocalTrack.Capabilities .Select(x => x.ToVideoFormat()).ToList()); } // If we get to here then the remote description was compatible with the local media tracks. // Set the remote description and end points. RemoteDescription = sessionDescription; AudioDestinationEndPoint = remoteAudioRtpEP ?? AudioDestinationEndPoint; AudioControlDestinationEndPoint = remoteAudioRtcpEP ?? AudioControlDestinationEndPoint; VideoDestinationEndPoint = remoteVideoRtpEP ?? VideoDestinationEndPoint; VideoControlDestinationEndPoint = remoteVideoRtcpEP ?? VideoControlDestinationEndPoint; return SetDescriptionResultEnum.OK; } } catch (Exception excp) { logger.LogError($"Exception in RTPSession SetRemoteDescription. {excp.Message}."); return SetDescriptionResultEnum.Error; } } /// <summary> /// Sets the stream status on a local audio or video media track. /// </summary> /// <param name="kind">The type of the media track. Must be audio or video.</param> /// <param name="status">The stream status for the media track.</param> public void SetMediaStreamStatus(SDPMediaTypesEnum kind, MediaStreamStatusEnum status) { if (kind == SDPMediaTypesEnum.audio && AudioLocalTrack != null) { AudioLocalTrack.StreamStatus = status; m_sdpAnnouncementVersion++; } else if (kind == SDPMediaTypesEnum.video && VideoLocalTrack != null) { VideoLocalTrack.StreamStatus = status; m_sdpAnnouncementVersion++; } } /// <summary> /// Gets the RTP end point for an SDP media announcement from the remote peer. /// </summary> /// <param name="announcement">The media announcement to get teh connection address for.</param> /// <param name="connectionAddress">The remote SDP session level connection address. Will be null if not available.</param> /// <returns>An IP end point for an SDP media announcement from the remote peer.</returns> private IPEndPoint GetAnnouncementRTPDestination( SDPMediaAnnouncement announcement, IPAddress connectionAddress) { SDPMediaTypesEnum kind = announcement.Media; IPEndPoint rtpEndPoint = null; var remoteAddr = (announcement.Connection != null) ? IPAddress.Parse(announcement.Connection.ConnectionAddress) : connectionAddress; if (remoteAddr != null) { if (announcement.Port < IPEndPoint.MinPort || announcement.Port > IPEndPoint.MaxPort) { logger.LogWarning($"Remote {kind} announcement contained an invalid port number {announcement.Port}."); // Set the remote port number to "9" which means ignore and wait for it be set some other way // such as when a remote RTP packet or arrives or ICE negotiation completes. rtpEndPoint = new IPEndPoint(remoteAddr, SDP.IGNORE_RTP_PORT_NUMBER); } else { rtpEndPoint = new IPEndPoint(remoteAddr, announcement.Port); } } return rtpEndPoint; } /// <summary> /// Adds a local media stream to this session. Local media tracks should be added by the /// application to control what session description offers and answers can be made as /// well as being used to match up with remote tracks. /// </summary> /// <param name="track">The local track to add.</param> private void AddLocalTrack(MediaStreamTrack track) { if (track.Kind == SDPMediaTypesEnum.audio && AudioLocalTrack != null) { throw new ApplicationException("A local audio track has already been set on this session."); } else if (track.Kind == SDPMediaTypesEnum.video && VideoLocalTrack != null) { throw new ApplicationException("A local video track has already been set on this session."); } if (track.StreamStatus == MediaStreamStatusEnum.Inactive) { // Inactive tracks don't use/require any local resources. Instead they are placeholders // so that the session description offers/answers can be balanced with the remote party. // For example if the remote party offers audio and video but we only support audio we // can reject the call or we can accept the audio and answer with an inactive video // announcement. if (track.Kind == SDPMediaTypesEnum.audio) { AudioLocalTrack = track; } else if (track.Kind == SDPMediaTypesEnum.video) { VideoLocalTrack = track; } } else { if (m_isMediaMultiplexed && m_rtpChannels.Count == 0) { // We use audio as the media type when multiplexing. CreateRtpChannel(SDPMediaTypesEnum.audio); AudioRtcpSession = CreateRtcpSession(SDPMediaTypesEnum.audio); } if (track.Kind == SDPMediaTypesEnum.audio) { if (!m_isMediaMultiplexed && !m_rtpChannels.ContainsKey(SDPMediaTypesEnum.audio)) { CreateRtpChannel(SDPMediaTypesEnum.audio); } if (AudioRtcpSession == null) { AudioRtcpSession = CreateRtcpSession(SDPMediaTypesEnum.audio); } // Need to create a sending SSRC and set it on the RTCP session. AudioRtcpSession.Ssrc = track.Ssrc; AudioLocalTrack = track; if (AudioLocalTrack.Capabilities != null && !AudioLocalTrack.NoDtmfSupport && !AudioLocalTrack.Capabilities.Any(x => x.ID == DTMF_EVENT_PAYLOAD_ID)) { SDPAudioVideoMediaFormat rtpEventFormat = new SDPAudioVideoMediaFormat( SDPMediaTypesEnum.audio, DTMF_EVENT_PAYLOAD_ID, SDP.TELEPHONE_EVENT_ATTRIBUTE, DEFAULT_AUDIO_CLOCK_RATE, SDPAudioVideoMediaFormat.DEFAULT_AUDIO_CHANNEL_COUNT, "0-16"); AudioLocalTrack.Capabilities.Add(rtpEventFormat); } } else if (track.Kind == SDPMediaTypesEnum.video) { // Only create the RTP socket, RTCP session etc. if a non-inactive local track is added // to the session. if (!m_isMediaMultiplexed && !m_rtpChannels.ContainsKey(SDPMediaTypesEnum.video)) { CreateRtpChannel(SDPMediaTypesEnum.video); } if (VideoRtcpSession == null) { VideoRtcpSession = CreateRtcpSession(SDPMediaTypesEnum.video); } // Need to create a sending SSRC and set it on the RTCP session. VideoRtcpSession.Ssrc = track.Ssrc; VideoLocalTrack = track; } } } /// <summary> /// Adds a remote media stream to this session. Typically the only way remote tracks /// should get added is from setting the remote session description. Adding a remote /// track does not cause the creation of any local resources. /// </summary> /// <param name="track">The remote track to add.</param> private void AddRemoteTrack(MediaStreamTrack track) { if (track.Kind == SDPMediaTypesEnum.audio) { if (AudioRemoteTrack != null) { //throw new ApplicationException("A remote audio track has already been set on this session."); logger.LogDebug($"Replacing existing remote audio track for ssrc {AudioRemoteTrack.Ssrc}."); } AudioRemoteTrack = track; // Even if there's no local audio track an RTCP session can still be required // in case the remote party send reports (presumably in case we decide we do want // to send or receive audio on this session at some later stage). if (AudioRtcpSession == null) { AudioRtcpSession = CreateRtcpSession(SDPMediaTypesEnum.audio); } } else if (track.Kind == SDPMediaTypesEnum.video) { if (VideoRemoteTrack != null) { logger.LogDebug($"Replacing existing remote video track for ssrc {VideoRemoteTrack.Ssrc}."); } VideoRemoteTrack = track; // Even if there's no local video track an RTCP session can still be required // in case the remote party send reports (presumably in case we decide we do want // to send or receive video on this session at some later stage). if (VideoRtcpSession == null) { VideoRtcpSession = CreateRtcpSession(SDPMediaTypesEnum.video); } } } /// <summary> /// Adjust the stream status of the local media tracks based on the remote tracks. /// </summary> private void SetLocalTrackStreamStatus(MediaStreamTrack localTrack, MediaStreamStatusEnum remoteTrackStatus, IPEndPoint remoteRTPEndPoint) { if (localTrack != null) { if (remoteTrackStatus == MediaStreamStatusEnum.Inactive) { // The remote party does not support this media type. Set the local stream status to inactive. localTrack.StreamStatus = MediaStreamStatusEnum.Inactive; } else if (remoteRTPEndPoint != null) { if (IPAddress.Any.Equals(remoteRTPEndPoint.Address) || IPAddress.IPv6Any.Equals(remoteRTPEndPoint.Address)) { // A connection address of 0.0.0.0 or [::], which is unreachable, means the media is inactive, except // if a special port number is used (defined as "9") which indicates that the media announcement is not // responsible for setting the remote end point for the audio stream. Instead it's most likely being set // using ICE. if (remoteRTPEndPoint.Port != SDP.IGNORE_RTP_PORT_NUMBER) { localTrack.StreamStatus = MediaStreamStatusEnum.Inactive; } } else if (remoteRTPEndPoint.Port == 0) { localTrack.StreamStatus = MediaStreamStatusEnum.Inactive; } } } } /// <summary> /// Generates a session description from the provided list of tracks. /// </summary> /// <param name="tracks">The list of tracks to generate the session description for.</param> /// <param name="connectionAddress">Optional. If set this address will be used as /// the SDP Connection address. If not specified the Internet facing address will /// be used.</param> /// <returns>A session description payload.</returns> private SDP GetSessionDesciption(List<MediaStreamTrack> tracks, IPAddress connectionAddress) { IPAddress localAddress = connectionAddress; if (localAddress == null) { if (m_bindAddress != null) { localAddress = m_bindAddress; } else if (AudioDestinationEndPoint != null && AudioDestinationEndPoint.Address != null) { if (IPAddress.Any.Equals(AudioDestinationEndPoint.Address) || IPAddress.IPv6Any.Equals(AudioDestinationEndPoint.Address)) { // If the remote party has set an inactive media stream via the connection address then we do the same. localAddress = AudioDestinationEndPoint.Address; } else { localAddress = NetServices.GetLocalAddressForRemote(AudioDestinationEndPoint.Address); } } else if (VideoDestinationEndPoint != null && VideoDestinationEndPoint.Address != null) { if (IPAddress.Any.Equals(VideoDestinationEndPoint.Address) || IPAddress.IPv6Any.Equals(VideoDestinationEndPoint.Address)) { // If the remote party has set an inactive media stream via the connection address then we do the same. localAddress = VideoDestinationEndPoint.Address; } else { localAddress = NetServices.GetLocalAddressForRemote(VideoDestinationEndPoint.Address); } } else { localAddress = NetServices.InternetDefaultAddress; } } SDP sdp = new SDP(IPAddress.Loopback); sdp.SessionId = m_sdpSessionID; sdp.AnnouncementVersion = m_sdpAnnouncementVersion; sdp.Connection = new SDPConnectionInformation(localAddress); int mediaIndex = 0; foreach (var track in tracks) { int mindex = RemoteDescription == null ? mediaIndex++ : RemoteDescription.GetIndexForMediaType(track.Kind); int rtpPort = 0; // A port of zero means the media type is not supported. if (track.Capabilities != null && track.Capabilities.Count() > 0 && track.StreamStatus != MediaStreamStatusEnum.Inactive) { rtpPort = (m_isMediaMultiplexed) ? m_rtpChannels.Single().Value.RTPPort : m_rtpChannels[track.Kind].RTPPort; } SDPMediaAnnouncement announcement = new SDPMediaAnnouncement( track.Kind, rtpPort, track.Capabilities); announcement.Transport = RTP_MEDIA_PROFILE; announcement.MediaStreamStatus = track.StreamStatus; announcement.MLineIndex = mindex; if(track.MaximumBandwidth > 0) { announcement.TIASBandwidth = track.MaximumBandwidth; } sdp.Media.Add(announcement); } return sdp; } /// <summary> /// Gets the RTP channel being used to send and receive the specified media type for this session. /// If media multiplexing is being used there will only a single RTP channel. /// </summary> public RTPChannel GetRtpChannel(SDPMediaTypesEnum mediaType) { if (m_isMediaMultiplexed) { return m_rtpChannels.FirstOrDefault().Value; } else if (m_rtpChannels.ContainsKey(mediaType)) { return m_rtpChannels[mediaType]; } else { return null; } } /// <summary> /// Creates a new RTP channel (which manages the UDP socket sending and receiving RTP /// packets) for use with this session. /// </summary> /// <param name="mediaType">The type of media the RTP channel is for. Must be audio or video.</param> /// <returns>A new RTPChannel instance.</returns> protected virtual RTPChannel CreateRtpChannel(SDPMediaTypesEnum mediaType) { // If RTCP is multiplexed we don't need a control socket. int bindPort = (m_bindPort == 0) ? 0 : m_bindPort + m_rtpChannels.Count() * 2; var rtpChannel = new RTPChannel(!m_isRtcpMultiplexed, m_bindAddress, bindPort); m_rtpChannels.Add(mediaType, rtpChannel); rtpChannel.OnRTPDataReceived += OnReceive; rtpChannel.OnControlDataReceived += OnReceive; // RTCP packets could come on RTP or control socket. rtpChannel.OnClosed += OnRTPChannelClosed; // Start the RTP, and if required the Control, socket receivers and the RTCP session. rtpChannel.Start(); return rtpChannel; } /// <summary> /// Creates a new RTCP session for a media track belonging to this RTP session. /// </summary> /// <param name="mediaType">The media type to create the RTP session for. Must be /// audio or video.</param> /// <returns>A new RTCPSession object. The RTCPSession must have its Start method called /// in order to commence sending RTCP reports.</returns> private RTCPSession CreateRtcpSession(SDPMediaTypesEnum mediaType) { var rtcpSession = new RTCPSession(mediaType, 0); rtcpSession.OnTimeout += (mt) => OnTimeout?.Invoke(mt); rtcpSession.OnReportReadyToSend += SendRtcpReport; return rtcpSession; } /// <summary> /// Sets the Secure RTP (SRTP) delegates and marks this session as ready for communications. /// </summary> /// <param name="protectRtp">SRTP encrypt RTP packet delegate.</param> /// <param name="unprotectRtp">SRTP decrypt RTP packet delegate.</param> /// <param name="protectRtcp">SRTP encrypt RTCP packet delegate.</param> /// <param name="unprotectRtcp">SRTP decrypt RTCP packet delegate.</param> public virtual void SetSecurityContext( ProtectRtpPacket protectRtp, ProtectRtpPacket unprotectRtp, ProtectRtpPacket protectRtcp, ProtectRtpPacket unprotectRtcp) { m_srtpProtect = protectRtp; m_srtpUnprotect = unprotectRtp; m_srtcpControlProtect = protectRtcp; m_srtcpControlUnprotect = unprotectRtcp; IsSecureContextReady = true; logger.LogDebug("Secure context successfully set on RTPSession."); } /// <summary> /// Gets the local tracks available in this session. Will only be audio, video or both. /// Local tracks represent an audio or video source that we are sending to the remote party. /// </summary> /// <returns>A list of the local tracks that have been added to this session.</returns> protected List<MediaStreamTrack> GetLocalTracks() { List<MediaStreamTrack> localTracks = new List<MediaStreamTrack>(); if (AudioLocalTrack != null) { localTracks.Add(AudioLocalTrack); } if (VideoLocalTrack != null) { localTracks.Add(VideoLocalTrack); } return localTracks; } /// <summary> /// Sets the remote end points for a media type supported by this RTP session. /// </summary> /// <param name="mediaType">The media type, must be audio or video, to set the remote end point for.</param> /// <param name="rtpEndPoint">The remote end point for RTP packets corresponding to the media type.</param> /// <param name="rtcpEndPoint">The remote end point for RTCP packets corresponding to the media type.</param> public void SetDestination(SDPMediaTypesEnum mediaType, IPEndPoint rtpEndPoint, IPEndPoint rtcpEndPoint) { if (m_isMediaMultiplexed) { AudioDestinationEndPoint = rtpEndPoint; VideoDestinationEndPoint = rtpEndPoint; AudioControlDestinationEndPoint = rtcpEndPoint; VideoControlDestinationEndPoint = rtcpEndPoint; } else { if (mediaType == SDPMediaTypesEnum.audio) { AudioDestinationEndPoint = rtpEndPoint; AudioControlDestinationEndPoint = rtcpEndPoint; } else if (mediaType == SDPMediaTypesEnum.video) { VideoDestinationEndPoint = rtpEndPoint; VideoControlDestinationEndPoint = rtcpEndPoint; } } } /// <summary> /// Starts the RTCP session(s) that monitor this RTP session. /// </summary> public virtual Task Start() { if (!IsStarted) { IsStarted = true; if (HasAudio && AudioRtcpSession != null && AudioLocalTrack.StreamStatus != MediaStreamStatusEnum.Inactive) { // The local audio track may have been disabled if there were no matching capabilities with // the remote party. AudioRtcpSession.Start(); } if (HasVideo && VideoRtcpSession != null && VideoLocalTrack.StreamStatus != MediaStreamStatusEnum.Inactive) { // The local video track may have been disabled if there were no matching capabilities with // the remote party. VideoRtcpSession.Start(); } OnStarted?.Invoke(); } return Task.CompletedTask; } /// <summary> /// Attempts to get the highest priority sending format for the remote call party. /// </summary> /// <param name="mediaType">The media type to get the sending format for.</param> /// <returns>The first compatible media format found for the specified media type.</returns> public SDPAudioVideoMediaFormat GetSendingFormat(SDPMediaTypesEnum mediaType) { if (mediaType == SDPMediaTypesEnum.audio) { if (AudioLocalTrack != null && AudioRemoteTrack != null) { var format = SDPAudioVideoMediaFormat.GetCompatibleFormats(AudioLocalTrack.Capabilities, AudioRemoteTrack.Capabilities) .Where(x => x.ID != RemoteRtpEventPayloadID).FirstOrDefault(); if (format.IsEmpty()) { // It's not expected that this occurs as a compatibility check is done when the remote session description // is set. By this point a compatible codec should be available. throw new ApplicationException($"No compatible sending format could be found for media {mediaType}."); } else { return format; } } else { throw new ApplicationException($"Cannot get the {mediaType} sending format, missing either local or remote {mediaType} track."); } } else if (mediaType == SDPMediaTypesEnum.video) { if (VideoLocalTrack != null && VideoRemoteTrack != null) { return SDPAudioVideoMediaFormat.GetCompatibleFormats(VideoLocalTrack.Capabilities, VideoRemoteTrack.Capabilities).First(); } else { throw new ApplicationException($"Cannot get the {mediaType} sending format, missing wither local or remote {mediaType} track."); } } else { throw new ApplicationException($"Sending of {mediaType} is not supported."); } } /// <summary> /// Sends an audio sample to the remote peer. /// </summary> /// <param name="durationRtpUnits">The duration in RTP timestamp units of the audio sample. This /// value is added to the previous RTP timestamp when building the RTP header.</param> /// <param name="sample">The audio sample to set as the RTP packet payload.</param> public void SendAudio(uint durationRtpUnits, byte[] sample) { if (AudioDestinationEndPoint != null && (!IsSecure || IsSecureContextReady)) { var audioFormat = GetSendingFormat(SDPMediaTypesEnum.audio); SendAudioFrame(durationRtpUnits, audioFormat.ID, sample); } } /// <summary> /// Sends a video sample to the remote peer. /// </summary> /// <param name="durationRtpUnits">The duration in RTP timestamp units of the video sample. This /// value is added to the previous RTP timestamp when building the RTP header.</param> /// <param name="sample">The video sample to set as the RTP packet payload.</param> public void SendVideo(uint durationRtpUnits, byte[] sample) { if (VideoDestinationEndPoint != null || (m_isMediaMultiplexed && AudioDestinationEndPoint != null) && (!IsSecure || IsSecureContextReady)) { var videoSendingFormat = GetSendingFormat(SDPMediaTypesEnum.video); switch (videoSendingFormat.Name()) { case "VP8": int vp8PayloadID = Convert.ToInt32(VideoLocalTrack.Capabilities.Single(x => x.Name() == "VP8").ID); SendVp8Frame(durationRtpUnits, vp8PayloadID, sample); break; case "H264": int h264PayloadID = Convert.ToInt32(VideoLocalTrack.Capabilities.Single(x => x.Name() == "H264").ID); SendH264Frame(durationRtpUnits, h264PayloadID, sample); break; default: throw new ApplicationException($"Unsupported video format selected {videoSendingFormat.Name()}."); } } } /// <summary> /// Sends an audio packet to the remote party. /// </summary> /// <param name="duration">The duration of the audio payload in timestamp units. This value /// gets added onto the timestamp being set in the RTP header.</param> /// <param name="payloadTypeID">The payload ID to set in the RTP header.</param> /// <param name="buffer">The audio payload to send.</param> public void SendAudioFrame(uint duration, int payloadTypeID, byte[] buffer) { if (IsClosed || m_rtpEventInProgress || AudioDestinationEndPoint == null) { return; } try { var audioTrack = AudioLocalTrack; if (audioTrack == null) { logger.LogWarning("SendAudio was called on an RTP session without an audio stream."); } else if (audioTrack.StreamStatus == MediaStreamStatusEnum.Inactive || audioTrack.StreamStatus == MediaStreamStatusEnum.RecvOnly) { return; } else { for (int index = 0; index * RTP_MAX_PAYLOAD < buffer.Length; index++) { int offset = (index == 0) ? 0 : (index * RTP_MAX_PAYLOAD); int payloadLength = (offset + RTP_MAX_PAYLOAD < buffer.Length) ? RTP_MAX_PAYLOAD : buffer.Length - offset; byte[] payload = new byte[payloadLength]; Buffer.BlockCopy(buffer, offset, payload, 0, payloadLength); // RFC3551 specifies that for audio the marker bit should always be 0 except for when returning // from silence suppression. For video the marker bit DOES get set to 1 for the last packet // in a frame. int markerBit = 0; var audioRtpChannel = GetRtpChannel(SDPMediaTypesEnum.audio); SendRtpPacket(audioRtpChannel, AudioDestinationEndPoint, payload, audioTrack.Timestamp, markerBit, payloadTypeID, audioTrack.Ssrc, audioTrack.SeqNum, AudioRtcpSession); //logger.LogDebug($"send audio { audioRtpChannel.RTPLocalEndPoint}->{AudioDestinationEndPoint}."); audioTrack.SeqNum = (audioTrack.SeqNum == UInt16.MaxValue) ? (ushort)0 : (ushort)(audioTrack.SeqNum + 1); } audioTrack.Timestamp += duration; } } catch (SocketException sockExcp) { logger.LogError("SocketException SendAudioFrame. " + sockExcp.Message); } } /// <summary> /// Sends a VP8 frame as one or more RTP packets. /// </summary> /// <param name="timestamp">The timestamp to place in the RTP header. Needs /// to be based on a 90Khz clock.</param> /// <param name="payloadTypeID">The payload ID to place in the RTP header.</param> /// <param name="buffer">The VP8 encoded payload.</param> public void SendVp8Frame(uint duration, int payloadTypeID, byte[] buffer) { var dstEndPoint = m_isMediaMultiplexed ? AudioDestinationEndPoint : VideoDestinationEndPoint; if (IsClosed || m_rtpEventInProgress || dstEndPoint == null) { return; } try { var videoTrack = VideoLocalTrack; if (videoTrack == null) { logger.LogWarning("SendVp8Frame was called on an RTP session without a video stream."); } else if (videoTrack.StreamStatus == MediaStreamStatusEnum.Inactive || videoTrack.StreamStatus == MediaStreamStatusEnum.RecvOnly) { return; } else { for (int index = 0; index * RTP_MAX_PAYLOAD < buffer.Length; index++) { int offset = index * RTP_MAX_PAYLOAD; int payloadLength = (offset + RTP_MAX_PAYLOAD < buffer.Length) ? RTP_MAX_PAYLOAD : buffer.Length - offset; byte[] vp8HeaderBytes = (index == 0) ? new byte[] { 0x10 } : new byte[] { 0x00 }; byte[] payload = new byte[payloadLength + vp8HeaderBytes.Length]; Buffer.BlockCopy(vp8HeaderBytes, 0, payload, 0, vp8HeaderBytes.Length); Buffer.BlockCopy(buffer, offset, payload, vp8HeaderBytes.Length, payloadLength); int markerBit = ((offset + payloadLength) >= buffer.Length) ? 1 : 0; // Set marker bit for the last packet in the frame. var videoChannel = GetRtpChannel(SDPMediaTypesEnum.video); SendRtpPacket(videoChannel, dstEndPoint, payload, videoTrack.Timestamp, markerBit, payloadTypeID, videoTrack.Ssrc, videoTrack.SeqNum, VideoRtcpSession); //logger.LogDebug($"send VP8 {videoChannel.RTPLocalEndPoint}->{dstEndPoint} timestamp {videoTrack.Timestamp}, sample length {buffer.Length}."); videoTrack.SeqNum = (videoTrack.SeqNum == UInt16.MaxValue) ? (ushort)0 : (ushort)(videoTrack.SeqNum + 1); } videoTrack.Timestamp += duration; } } catch (SocketException sockExcp) { logger.LogError("SocketException SendVp8Frame. " + sockExcp.Message); } } /// <summary> /// Helper method to send a low quality JPEG image over RTP. This method supports a very abbreviated version of RFC 2435 "RTP Payload Format for JPEG-compressed Video". /// It's intended as a quick convenient way to send something like a test pattern image over an RTSP connection. More than likely it won't be suitable when a high /// quality image is required since the header used in this method does not support quantization tables. /// </summary> /// <param name="jpegBytes">The raw encoded bytes of the JPEG image to transmit.</param> /// <param name="jpegQuality">The encoder quality of the JPEG image.</param> /// <param name="jpegWidth">The width of the JPEG image.</param> /// <param name="jpegHeight">The height of the JPEG image.</param> /// <param name="framesPerSecond">The rate at which the JPEG frames are being transmitted at. used to calculate the timestamp.</param> public void SendJpegFrame(uint duration, int payloadTypeID, byte[] jpegBytes, int jpegQuality, int jpegWidth, int jpegHeight) { var dstEndPoint = m_isMediaMultiplexed ? AudioDestinationEndPoint : VideoDestinationEndPoint; if (IsClosed || m_rtpEventInProgress || dstEndPoint == null) { return; } try { var videoTrack = VideoLocalTrack; if (videoTrack == null) { logger.LogWarning("SendJpegFrame was called on an RTP session without a video stream."); } else if (videoTrack.StreamStatus == MediaStreamStatusEnum.Inactive || videoTrack.StreamStatus == MediaStreamStatusEnum.RecvOnly) { return; } else { for (int index = 0; index * RTP_MAX_PAYLOAD < jpegBytes.Length; index++) { uint offset = Convert.ToUInt32(index * RTP_MAX_PAYLOAD); int payloadLength = ((index + 1) * RTP_MAX_PAYLOAD < jpegBytes.Length) ? RTP_MAX_PAYLOAD : jpegBytes.Length - index * RTP_MAX_PAYLOAD; byte[] jpegHeader = RtpVideoFramer.CreateLowQualityRtpJpegHeader(offset, jpegQuality, jpegWidth, jpegHeight); List<byte> packetPayload = new List<byte>(); packetPayload.AddRange(jpegHeader); packetPayload.AddRange(jpegBytes.Skip(index * RTP_MAX_PAYLOAD).Take(payloadLength)); int markerBit = ((index + 1) * RTP_MAX_PAYLOAD < jpegBytes.Length) ? 0 : 1; SendRtpPacket(GetRtpChannel(SDPMediaTypesEnum.video), dstEndPoint, packetPayload.ToArray(), videoTrack.Timestamp, markerBit, payloadTypeID, videoTrack.Ssrc, videoTrack.SeqNum, VideoRtcpSession); videoTrack.SeqNum = (videoTrack.SeqNum == UInt16.MaxValue) ? (ushort)0 : (ushort)(videoTrack.SeqNum + 1); } videoTrack.Timestamp += duration; } } catch (SocketException sockExcp) { logger.LogError("SocketException SendJpegFrame. " + sockExcp.Message); } } /// <summary> /// Sends a H264 frame, represented by an Access Unit, to the remote party. /// </summary> /// <param name="duration">The duration in timestamp units of the payload (e.g. 3000 for 30fps).</param> /// <param name="payloadTypeID">The payload type ID being used for H264 and that will be set on the RTP header.</param> /// <param name="accessUnit">The encoded H264 access unit to transmit. An access unit can contain one or more /// NAL's.</param> /// <remarks> /// An Access Unit can contain one or more NAL's. The NAL's have to be parsed in order to be able to package /// in RTP packets. /// /// See https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-H.264-201602-S!!PDF-E&type=items Annex B for byte stream specification. /// </remarks> public void SendH264Frame(uint duration, int payloadTypeID, byte[] accessUnit) { var dstEndPoint = m_isMediaMultiplexed ? AudioDestinationEndPoint : VideoDestinationEndPoint; if (IsClosed || m_rtpEventInProgress || dstEndPoint == null || accessUnit == null || accessUnit.Length == 0) { return; } var videoTrack = VideoLocalTrack; if (videoTrack == null) { logger.LogWarning("SendH264Frame was called on an RTP session without a video stream."); } else if (videoTrack.StreamStatus == MediaStreamStatusEnum.Inactive || videoTrack.StreamStatus == MediaStreamStatusEnum.RecvOnly) { return; } else { foreach (var nal in H264Packetiser.ParseNals(accessUnit)) { SendH264Nal(duration, payloadTypeID, nal.NAL, nal.IsLast, dstEndPoint, videoTrack); } } } /// <summary> /// Sends a single H264 NAL to the remote party. /// </summary> /// <param name="duration">The duration in timestamp units of the payload (e.g. 3000 for 30fps).</param> /// <param name="payloadTypeID">The payload type ID being used for H264 and that will be set on the RTP header.</param> /// <param name="nal">The buffer containing the NAL to send.</param> /// <param name="isLastNal">Should be set for the last NAL in the H264 access unit. Determines when the markbit gets set /// and the timestamp incremented.</param> /// <param name="dstEndPoint">The destination end point to send to.</param> /// <param name="videoTrack">The video track to send on.</param> private void SendH264Nal(uint duration, int payloadTypeID, byte[] nal, bool isLastNal, IPEndPoint dstEndPoint, MediaStreamTrack videoTrack) { //logger.LogDebug($"Send NAL {nal.Length}, is last {isLastNal}, timestamp {videoTrack.Timestamp}."); //logger.LogDebug($"nri {nalNri:X2}, type {nalType:X2}."); byte nal0 = nal[0]; if (nal.Length <= RTP_MAX_PAYLOAD) { // Send as Single-Time Aggregation Packet (STAP-A). byte[] payload = new byte[nal.Length]; int markerBit = isLastNal ? 1 : 0; // There is only ever one packet in a STAP-A. Buffer.BlockCopy(nal, 0, payload, 0, nal.Length); var videoChannel = GetRtpChannel(SDPMediaTypesEnum.video); SendRtpPacket(videoChannel, dstEndPoint, payload, videoTrack.Timestamp, markerBit, payloadTypeID, videoTrack.Ssrc, videoTrack.SeqNum, VideoRtcpSession); //logger.LogDebug($"send H264 {videoChannel.RTPLocalEndPoint}->{dstEndPoint} timestamp {videoTrack.Timestamp}, payload length {payload.Length}, seqnum {videoTrack.SeqNum}, marker {markerBit}."); //logger.LogDebug($"send H264 {videoChannel.RTPLocalEndPoint}->{dstEndPoint} timestamp {videoTrack.Timestamp}, STAP-A {h264RtpHdr.HexStr()}, payload length {payload.Length}, seqnum {videoTrack.SeqNum}, marker {markerBit}."); videoTrack.SeqNum = (videoTrack.SeqNum == UInt16.MaxValue) ? (ushort)0 : (ushort)(videoTrack.SeqNum + 1); } else { nal = nal.Skip(1).ToArray(); // Send as Fragmentation Unit A (FU-A): for (int index = 0; index * RTP_MAX_PAYLOAD < nal.Length; index++) { int offset = index * RTP_MAX_PAYLOAD; int payloadLength = ((index + 1) * RTP_MAX_PAYLOAD < nal.Length) ? RTP_MAX_PAYLOAD : nal.Length - index * RTP_MAX_PAYLOAD; bool isFirstPacket = index == 0; bool isFinalPacket = (index + 1) * RTP_MAX_PAYLOAD >= nal.Length; int markerBit = (isLastNal && isFinalPacket) ? 1 : 0; byte[] h264RtpHdr = H264Packetiser.GetH264RtpHeader(nal0, isFirstPacket, isFinalPacket); byte[] payload = new byte[payloadLength + h264RtpHdr.Length]; Buffer.BlockCopy(h264RtpHdr, 0, payload, 0, h264RtpHdr.Length); Buffer.BlockCopy(nal, offset, payload, h264RtpHdr.Length, payloadLength); var videoChannel = GetRtpChannel(SDPMediaTypesEnum.video); SendRtpPacket(videoChannel, dstEndPoint, payload, videoTrack.Timestamp, markerBit, payloadTypeID, videoTrack.Ssrc, videoTrack.SeqNum, VideoRtcpSession); //logger.LogDebug($"send H264 {videoChannel.RTPLocalEndPoint}->{dstEndPoint} timestamp {videoTrack.Timestamp}, FU-A {h264RtpHdr.HexStr()}, payload length {payloadLength}, seqnum {videoTrack.SeqNum}, marker {markerBit}."); videoTrack.SeqNum = (videoTrack.SeqNum == UInt16.MaxValue) ? (ushort)0 : (ushort)(videoTrack.SeqNum + 1); } } if (isLastNal) { videoTrack.Timestamp += duration; } } /// <summary> /// Sends a DTMF tone as an RTP event to the remote party. /// </summary> /// <param name="key">The DTMF tone to send.</param> /// <param name="ct">RTP events can span multiple RTP packets. This token can /// be used to cancel the send.</param> public virtual Task SendDtmf(byte key, CancellationToken ct) { var dtmfEvent = new RTPEvent(key, false, RTPEvent.DEFAULT_VOLUME, DTMF_EVENT_DURATION, DTMF_EVENT_PAYLOAD_ID); return SendDtmfEvent(dtmfEvent, ct); } /// <summary> /// Sends an RTP event for a DTMF tone as per RFC2833. Sending the event requires multiple packets to be sent. /// This method will hold onto the socket until all the packets required for the event have been sent. The send /// can be cancelled using the cancellation token. /// </summary> /// <param name="rtpEvent">The RTP event to send.</param> /// <param name="cancellationToken">CancellationToken to allow the operation to be cancelled prematurely.</param> /// <param name="clockRate">To send an RTP event the clock rate of the underlying stream needs to be known.</param> /// <param name="streamID">For multiplexed sessions the ID of the stream to send the event on. Defaults to 0 /// for single stream sessions.</param> public async Task SendDtmfEvent( RTPEvent rtpEvent, CancellationToken cancellationToken, int clockRate = DEFAULT_AUDIO_CLOCK_RATE) { var dstEndPoint = AudioDestinationEndPoint; if (IsClosed || m_rtpEventInProgress == true || dstEndPoint == null) { logger.LogWarning("SendDtmfEvent request ignored as an RTP event is already in progress."); } try { var audioTrack = AudioLocalTrack; if (audioTrack == null) { logger.LogWarning("SendDtmfEvent was called on an RTP session without an audio stream."); } else if (audioTrack.StreamStatus == MediaStreamStatusEnum.Inactive || audioTrack.StreamStatus == MediaStreamStatusEnum.RecvOnly) { return; } else { m_rtpEventInProgress = true; uint startTimestamp = m_lastRtpTimestamp; // The sample period in milliseconds being used for the media stream that the event // is being inserted into. Should be set to 50ms if main media stream is dynamic or // sample period is unknown. int samplePeriod = RTP_EVENT_DEFAULT_SAMPLE_PERIOD_MS; // The RTP timestamp step corresponding to the sampling period. This can change depending // on the codec being used. For example using PCMU with a sampling frequency of 8000Hz and a sample period of 50ms // the timestamp step is 400 (8000 / (1000 / 50)). For a sample period of 20ms it's 160 (8000 / (1000 / 20)). ushort rtpTimestampStep = (ushort)(clockRate * samplePeriod / 1000); // If only the minimum number of packets are being sent then they are both the start and end of the event. rtpEvent.EndOfEvent = (rtpEvent.TotalDuration <= rtpTimestampStep); // The DTMF tone is generally multiple RTP events. Each event has a duration of the RTP timestamp step. rtpEvent.Duration = rtpTimestampStep; // Send the start of event packets. for (int i = 0; i < RTPEvent.DUPLICATE_COUNT && !cancellationToken.IsCancellationRequested; i++) { byte[] buffer = rtpEvent.GetEventPayload(); int markerBit = (i == 0) ? 1 : 0; // Set marker bit for the first packet in the event. SendRtpPacket(GetRtpChannel(SDPMediaTypesEnum.audio), dstEndPoint, buffer, startTimestamp, markerBit, rtpEvent.PayloadTypeID, audioTrack.Ssrc, audioTrack.SeqNum, AudioRtcpSession); audioTrack.SeqNum = (audioTrack.SeqNum == UInt16.MaxValue) ? (ushort)0 : (ushort)(audioTrack.SeqNum + 1); } await Task.Delay(samplePeriod, cancellationToken).ConfigureAwait(false); if (!rtpEvent.EndOfEvent) { // Send the progressive event packets while ((rtpEvent.Duration + rtpTimestampStep) < rtpEvent.TotalDuration && !cancellationToken.IsCancellationRequested) { rtpEvent.Duration += rtpTimestampStep; byte[] buffer = rtpEvent.GetEventPayload(); SendRtpPacket(GetRtpChannel(SDPMediaTypesEnum.audio), dstEndPoint, buffer, startTimestamp, 0, rtpEvent.PayloadTypeID, audioTrack.Ssrc, audioTrack.SeqNum, AudioRtcpSession); audioTrack.SeqNum = (audioTrack.SeqNum == UInt16.MaxValue) ? (ushort)0 : (ushort)(audioTrack.SeqNum + 1); await Task.Delay(samplePeriod, cancellationToken).ConfigureAwait(false); } // Send the end of event packets. for (int j = 0; j < RTPEvent.DUPLICATE_COUNT && !cancellationToken.IsCancellationRequested; j++) { rtpEvent.EndOfEvent = true; rtpEvent.Duration = rtpEvent.TotalDuration; byte[] buffer = rtpEvent.GetEventPayload(); SendRtpPacket(GetRtpChannel(SDPMediaTypesEnum.audio), dstEndPoint, buffer, startTimestamp, 0, rtpEvent.PayloadTypeID, audioTrack.Ssrc, audioTrack.SeqNum, AudioRtcpSession); audioTrack.SeqNum = (audioTrack.SeqNum == UInt16.MaxValue) ? (ushort)0 : (ushort)(audioTrack.SeqNum + 1); } } } } catch (SocketException sockExcp) { logger.LogError("SocketException SendDtmfEvent. " + sockExcp.Message); } catch (TaskCanceledException) { logger.LogWarning("SendDtmfEvent was cancelled by caller."); } finally { m_rtpEventInProgress = false; } } /// <summary> /// Allows additional control for sending raw RTP payloads. No framing or other processing is carried out. /// </summary> /// <param name="mediaType">The media type of the RTP packet being sent. Must be audio or video.</param> /// <param name="payload">The RTP packet payload.</param> /// <param name="timestamp">The timestamp to set on the RTP header.</param> /// <param name="markerBit">The value to set on the RTP header marker bit, should be 0 or 1.</param> /// <param name="payloadTypeID">The payload ID to set in the RTP header.</param> public void SendRtpRaw(SDPMediaTypesEnum mediaType, byte[] payload, uint timestamp, int markerBit, int payloadTypeID) { if (mediaType == SDPMediaTypesEnum.audio && AudioLocalTrack == null) { logger.LogWarning("SendRtpRaw was called for an audio packet on an RTP session without a local audio stream."); } else if (mediaType == SDPMediaTypesEnum.video && VideoLocalTrack == null) { logger.LogWarning("SendRtpRaw was called for a video packet on an RTP session without a local video stream."); } else { var rtpChannel = GetRtpChannel(mediaType); RTCPSession rtcpSession = (mediaType == SDPMediaTypesEnum.video) ? VideoRtcpSession : AudioRtcpSession; IPEndPoint dstEndPoint = (mediaType == SDPMediaTypesEnum.audio || m_isMediaMultiplexed) ? AudioDestinationEndPoint : VideoDestinationEndPoint; MediaStreamTrack track = (mediaType == SDPMediaTypesEnum.video) ? VideoLocalTrack : AudioLocalTrack; if (dstEndPoint != null) { SendRtpPacket(rtpChannel, dstEndPoint, payload, timestamp, markerBit, payloadTypeID, track.Ssrc, track.SeqNum, rtcpSession); track.SeqNum = (track.SeqNum == UInt16.MaxValue) ? (ushort)0 : (ushort)(track.SeqNum + 1); } } } /// <summary> /// Allows sending of RTCP feedback reports. /// </summary> /// <param name="mediaType">The media type of the RTCP report being sent. Must be audio or video.</param> /// <param name="feedback">The feedback report to send.</param> public void SendRtcpFeedback(SDPMediaTypesEnum mediaType, RTCPFeedback feedback) { var reportBytes = feedback.GetBytes(); SendRtcpReport(mediaType, reportBytes); } /// <summary> /// Close the session and RTP channel. /// </summary> public virtual void Close(string reason) { if (!IsClosed) { IsClosed = true; AudioRtcpSession?.Close(reason); VideoRtcpSession?.Close(reason); foreach (var rtpChannel in m_rtpChannels.Values) { rtpChannel.OnRTPDataReceived -= OnReceive; rtpChannel.OnControlDataReceived -= OnReceive; rtpChannel.OnClosed -= OnRTPChannelClosed; rtpChannel.Close(reason); } OnRtpClosed?.Invoke(reason); OnClosed?.Invoke(); } } /// <summary> /// Event handler for receiving data on the RTP and Control channels. For multiplexed /// sessions both RTP and RTCP packets will be received on the RTP channel. /// </summary> /// <param name="localPort">The local port the data was received on.</param> /// <param name="remoteEndPoint">The remote end point the data was received from.</param> /// <param name="buffer">The data received.</param> protected void OnReceive(int localPort, IPEndPoint remoteEndPoint, byte[] buffer) { if (remoteEndPoint.Address.IsIPv4MappedToIPv6) { // Required for matching existing RTP end points (typically set from SDP) and // whether or not the destination end point should be switched. remoteEndPoint.Address = remoteEndPoint.Address.MapToIPv4(); } // Quick sanity check on whether this is not an RTP or RTCP packet. if (buffer?.Length > RTPHeader.MIN_HEADER_LEN && buffer[0] >= 128 && buffer[0] <= 191) { if (IsSecure && !IsSecureContextReady) { logger.LogWarning("RTP or RTCP packet received before secure context ready."); } else if (buffer[1] == 0xC8 /* RTCP SR */ || buffer[1] == 0xC9 /* RTCP RR */) { //logger.LogDebug($"RTCP packet received from {remoteEndPoint} {buffer.HexStr()}"); #region RTCP packet. if (m_srtcpControlUnprotect != null) { int outBufLen = 0; int res = m_srtcpControlUnprotect(buffer, buffer.Length, out outBufLen); if (res != 0) { logger.LogWarning($"SRTCP unprotect failed, result {res}."); return; } else { buffer = buffer.Take(outBufLen).ToArray(); } } var rtcpPkt = new RTCPCompoundPacket(buffer); if (rtcpPkt != null) { if (rtcpPkt.Bye != null) { logger.LogDebug($"RTCP BYE received for SSRC {rtcpPkt.Bye.SSRC}, reason {rtcpPkt.Bye.Reason}."); OnRtcpBye?.Invoke(rtcpPkt.Bye.Reason); // In some cases, such as a SIP re-INVITE, it's possible the RTP session // will keep going with a new remote SSRC. if (AudioRemoteTrack != null && rtcpPkt.Bye.SSRC == AudioRemoteTrack.Ssrc) { AudioRtcpSession?.RemoveReceptionReport(rtcpPkt.Bye.SSRC); //AudioDestinationEndPoint = null; //AudioControlDestinationEndPoint = null; AudioRemoteTrack.Ssrc = 0; } else if (VideoRemoteTrack != null && rtcpPkt.Bye.SSRC == VideoRemoteTrack.Ssrc) { VideoRtcpSession?.RemoveReceptionReport(rtcpPkt.Bye.SSRC); //VideoDestinationEndPoint = null; //VideoControlDestinationEndPoint = null; VideoRemoteTrack.Ssrc = 0; } } else if (!IsClosed) { var rtcpSession = GetRtcpSession(rtcpPkt); if (rtcpSession != null) { if (rtcpSession.LastActivityAt == DateTime.MinValue) { // On the first received RTCP report for a session check whether the remote end point matches the // expected remote end point. If not it's "likely" that a private IP address was specified in the SDP. // Take the risk and switch the remote control end point to the one we are receiving from. if (rtcpSession == AudioRtcpSession && (AudioControlDestinationEndPoint == null || !AudioControlDestinationEndPoint.Address.Equals(remoteEndPoint.Address) || AudioControlDestinationEndPoint.Port != remoteEndPoint.Port)) { logger.LogDebug($"Audio control end point switched from {AudioControlDestinationEndPoint} to {remoteEndPoint}."); AudioControlDestinationEndPoint = remoteEndPoint; } else if (rtcpSession == VideoRtcpSession && (VideoControlDestinationEndPoint == null || !VideoControlDestinationEndPoint.Address.Equals(remoteEndPoint.Address) || VideoControlDestinationEndPoint.Port != remoteEndPoint.Port)) { logger.LogDebug($"Video control end point switched from {VideoControlDestinationEndPoint} to {remoteEndPoint}."); VideoControlDestinationEndPoint = remoteEndPoint; } } rtcpSession.ReportReceived(remoteEndPoint, rtcpPkt); OnReceiveReport?.Invoke(remoteEndPoint, rtcpSession.MediaType, rtcpPkt); } else if (AudioRtcpSession?.PacketsReceivedCount > 0 || VideoRtcpSession?.PacketsReceivedCount > 0) { // Only give this warning if we've received at least one RTP packet. logger.LogWarning("Could not match an RTCP packet against any SSRC's in the session."); } } } else { logger.LogWarning("Failed to parse RTCP compound report."); } #endregion } else { #region RTP packet. if (!IsClosed) { if (m_srtpUnprotect != null) { int res = m_srtpUnprotect(buffer, buffer.Length, out int outBufLen); if (res != 0) { logger.LogWarning($"SRTP unprotect failed, result {res}."); return; } else { buffer = buffer.Take(outBufLen).ToArray(); } } var rtpPacket = new RTPPacket(buffer); var hdr = rtpPacket.Header; //logger.LogDebug($"rtp recv, seqnum {hdr.SequenceNumber}, ts {hdr.Timestamp}, marker {hdr.MarkerBit}, payload {rtpPacket.Payload.Length}."); //SDPMediaTypesEnum? rtpMediaType = null; // Check whether this is an RTP event. if (RemoteRtpEventPayloadID != 0 && rtpPacket.Header.PayloadType == RemoteRtpEventPayloadID) { RTPEvent rtpEvent = new RTPEvent(rtpPacket.Payload); OnRtpEvent?.Invoke(remoteEndPoint, rtpEvent, rtpPacket.Header); } else { // Attempt to determine the media type for the RTP packet. //rtpMediaType = GetMediaTypeForRtpPacket(rtpPacket.Header); //if (rtpMediaType == null) //{ // if (AudioLocalTrack != null && VideoLocalTrack == null) // { // rtpMediaType = SDPMediaTypesEnum.audio; // } // else if (AudioLocalTrack == null && VideoLocalTrack != null) // { // rtpMediaType = SDPMediaTypesEnum.video; // } // else // { // rtpMediaType = GetMediaTypeForLocalPort(localPort); // } //} var avFormat = GetFormatForRtpPacket(rtpPacket.Header); if (avFormat != null) { // Set the remote track SSRC so that RTCP reports can match the media type. if (avFormat.Value.Kind == SDPMediaTypesEnum.audio && AudioRemoteTrack != null && AudioRemoteTrack.Ssrc == 0 && AudioDestinationEndPoint != null) { bool isValidSource = AdjustRemoteEndPoint(SDPMediaTypesEnum.audio, rtpPacket.Header.SyncSource, remoteEndPoint); if (isValidSource) { logger.LogDebug($"Set remote audio track SSRC to {rtpPacket.Header.SyncSource}."); AudioRemoteTrack.Ssrc = rtpPacket.Header.SyncSource; } } else if (avFormat.Value.Kind == SDPMediaTypesEnum.video && VideoRemoteTrack != null && VideoRemoteTrack.Ssrc == 0 && (m_isMediaMultiplexed || VideoDestinationEndPoint != null)) { bool isValidSource = AdjustRemoteEndPoint(SDPMediaTypesEnum.video, rtpPacket.Header.SyncSource, remoteEndPoint); if (isValidSource) { logger.LogDebug($"Set remote video track SSRC to {rtpPacket.Header.SyncSource}."); VideoRemoteTrack.Ssrc = rtpPacket.Header.SyncSource; } } // Note AC 24 Dec 2020: The probelm with waiting until the remote description is set is that the remote peer often starts sending // RTP packets at the same time it signals its SDP offer or answer. Generally this is not a problem for audio but for video streams // the first RTP packet(s) are the key frame and if they are ignored the video stream will take addtional time or manual // intervention to synchronise. //if (RemoteDescription != null) //{ // Don't hand RTP packets to the application until the remote description has been set. Without it // things like the common codec, DTMF support etc. are not known. //SDPMediaTypesEnum mediaType = (rtpMediaType.HasValue) ? rtpMediaType.Value : DEFAULT_MEDIA_TYPE; // For video RTP packets an attempt will be made to collate into frames. It's up to the application // whether it wants to subscribe to frames of RTP packets. if (avFormat.Value.Kind == SDPMediaTypesEnum.video) { if (VideoRemoteTrack != null) { if (VideoRemoteTrack.LastRemoteSeqNum != 0 && rtpPacket.Header.SequenceNumber != (VideoRemoteTrack.LastRemoteSeqNum + 1) && !(rtpPacket.Header.SequenceNumber == 0 && VideoRemoteTrack.LastRemoteSeqNum == UInt16.MaxValue)) { logger.LogWarning($"Video stream sequence number jumped from {VideoRemoteTrack.LastRemoteSeqNum} to {rtpPacket.Header.SequenceNumber}."); } VideoRemoteTrack.LastRemoteSeqNum = rtpPacket.Header.SequenceNumber; } if (_rtpVideoFramer != null) { var frame = _rtpVideoFramer.GotRtpPacket(rtpPacket); if (frame != null) { OnVideoFrameReceived?.Invoke(remoteEndPoint, rtpPacket.Header.Timestamp, frame, avFormat.Value.ToVideoFormat()); } } else { var videoFormat = avFormat.Value; //GetSendingFormat(SDPMediaTypesEnum.video); if (videoFormat.ToVideoFormat().Codec == VideoCodecsEnum.VP8 || videoFormat.ToVideoFormat().Codec == VideoCodecsEnum.H264) { logger.LogDebug($"Video depacketisation codec set to {videoFormat.ToVideoFormat().Codec} for SSRC {rtpPacket.Header.SyncSource}."); _rtpVideoFramer = new RtpVideoFramer(videoFormat.ToVideoFormat().Codec); var frame = _rtpVideoFramer.GotRtpPacket(rtpPacket); if (frame != null) { OnVideoFrameReceived?.Invoke(remoteEndPoint, rtpPacket.Header.Timestamp, frame, avFormat.Value.ToVideoFormat()); } } else { logger.LogWarning($"Video depacketisation logic for codec {videoFormat.Name()} has not been implemented, PR's welcome!"); } } } else if (avFormat.Value.Kind == SDPMediaTypesEnum.audio && AudioRemoteTrack != null) { if (AudioRemoteTrack.LastRemoteSeqNum != 0 && rtpPacket.Header.SequenceNumber != (AudioRemoteTrack.LastRemoteSeqNum + 1) && !(rtpPacket.Header.SequenceNumber == 0 && AudioRemoteTrack.LastRemoteSeqNum == UInt16.MaxValue)) { logger.LogWarning($"Audio stream sequence number jumped from {AudioRemoteTrack.LastRemoteSeqNum} to {rtpPacket.Header.SequenceNumber}."); } AudioRemoteTrack.LastRemoteSeqNum = rtpPacket.Header.SequenceNumber; } OnRtpPacketReceived?.Invoke(remoteEndPoint, avFormat.Value.Kind, rtpPacket); //} // Used for reporting purposes. if (avFormat.Value.Kind == SDPMediaTypesEnum.audio && AudioRtcpSession != null) { AudioRtcpSession.RecordRtpPacketReceived(rtpPacket); } else if (avFormat.Value.Kind == SDPMediaTypesEnum.video && VideoRtcpSession != null) { VideoRtcpSession.RecordRtpPacketReceived(rtpPacket); } } } } #endregion } } } /// <summary> /// Adjusts the expected remote end point for a particular media type. /// </summary> /// <param name="mediaType">The media type of the RTP packet received.</param> /// <param name="ssrc">The SSRC from the RTP packet header.</param> /// <param name="receivedOnEndPoint">The actual remote end point that the RTP packet came from.</param> /// <returns>True if remote end point for this media type was th expected one or it was adjusted. False if /// the remote end point was deemed to be invalid for this media type.</returns> private bool AdjustRemoteEndPoint(SDPMediaTypesEnum mediaType, uint ssrc, IPEndPoint receivedOnEndPoint) { bool isValidSource = false; IPEndPoint expectedEndPoint = (mediaType == SDPMediaTypesEnum.audio || m_isMediaMultiplexed) ? AudioDestinationEndPoint : VideoDestinationEndPoint; if (expectedEndPoint.Address.Equals(receivedOnEndPoint.Address) && expectedEndPoint.Port == receivedOnEndPoint.Port) { // Exact match on actual and expected destination. isValidSource = true; } else if (AcceptRtpFromAny || (expectedEndPoint.Address.IsPrivate() && !receivedOnEndPoint.Address.IsPrivate()) //|| (IPAddress.Loopback.Equals(receivedOnEndPoint.Address) || IPAddress.IPv6Loopback.Equals(receivedOnEndPoint.Address ) { // The end point doesn't match BUT we were supplied a private address in the SDP and the remote source is a public address // so high probability there's a NAT on the network path. Switch to the remote end point (note this can only happen once // and only if the SSRV is 0, i.e. this is the first RTP packet. // If the remote end point is a loopback address then it's likely that this is a test/development // scenario and the source can be trusted. // AC 12 Jul 2020: Commented out the expression that allows the end point to be change just because it's a loopback address. // A breaking case is doing an attended transfer test where two different agents are using loopback addresses. // The expression allows an older session to override the destination set by a newer remote SDP. // AC 18 Aug 2020: Despite the carefully crafted rules below and https://github.com/sipsorcery/sipsorcery/issues/197 // there are still cases that were a problem in one scenario but acceptable in another. To accommodate a new property // was added to allow the application to decide whether the RTP end point switches should be liberal or not. logger.LogDebug($"{mediaType} end point switched for RTP ssrc {ssrc} from {expectedEndPoint} to {receivedOnEndPoint}."); if (mediaType == SDPMediaTypesEnum.audio) { AudioDestinationEndPoint = receivedOnEndPoint; if (m_isRtcpMultiplexed) { AudioControlDestinationEndPoint = AudioDestinationEndPoint; } else { AudioControlDestinationEndPoint = new IPEndPoint(AudioDestinationEndPoint.Address, AudioDestinationEndPoint.Port + 1); } } else { VideoDestinationEndPoint = receivedOnEndPoint; if (m_isRtcpMultiplexed) { VideoControlDestinationEndPoint = VideoDestinationEndPoint; } else { VideoControlDestinationEndPoint = new IPEndPoint(VideoControlDestinationEndPoint.Address, VideoControlDestinationEndPoint.Port + 1); } } isValidSource = true; } else { logger.LogWarning($"RTP packet with SSRC {ssrc} received from unrecognised end point {receivedOnEndPoint}."); } return isValidSource; } /// <summary> /// Attempts to determine which media stream a received RTP packet is for based on the RTP socket /// it was received on. This is for cases where media multiplexing is not in use (i.e. legacy RTP). /// </summary> /// <param name="localPort">The local port the RTP packet was received on.</param> /// <returns>The media type for the received packet or null if it could not be determined.</returns> private SDPMediaTypesEnum? GetMediaTypeForLocalPort(int localPort) { if (m_rtpChannels.ContainsKey(SDPMediaTypesEnum.audio) && m_rtpChannels[SDPMediaTypesEnum.audio].RTPPort == localPort) { return SDPMediaTypesEnum.audio; } else if (m_rtpChannels.ContainsKey(SDPMediaTypesEnum.video) && m_rtpChannels[SDPMediaTypesEnum.video].RTPPort == localPort) { return SDPMediaTypesEnum.video; } else { return null; } } /// <summary> /// Attempts to get the audio or video media format for an RTP packet. /// </summary> /// <param name="header">The header of the received RTP packet.</param> /// <returns>The audio or video format for the received packet or null if it could not be determined.</returns> private SDPAudioVideoMediaFormat? GetFormatForRtpPacket(RTPHeader header) { MediaStreamTrack matchingTrack = null; if (AudioRemoteTrack != null && AudioRemoteTrack.IsSsrcMatch(header.SyncSource)) { matchingTrack = AudioRemoteTrack; } else if (VideoRemoteTrack != null && VideoRemoteTrack.IsSsrcMatch(header.SyncSource)) { matchingTrack = VideoRemoteTrack; } else if (AudioRemoteTrack != null && AudioRemoteTrack.IsPayloadIDMatch(header.PayloadType)) { matchingTrack = AudioRemoteTrack; } else if (VideoRemoteTrack != null && VideoRemoteTrack.IsPayloadIDMatch(header.PayloadType)) { matchingTrack = VideoRemoteTrack; } else if (AudioLocalTrack != null && AudioLocalTrack.IsPayloadIDMatch(header.PayloadType)) { matchingTrack = AudioLocalTrack; } else if (VideoLocalTrack != null && VideoLocalTrack.IsPayloadIDMatch(header.PayloadType)) { matchingTrack = VideoLocalTrack; } if (matchingTrack != null) { var format = matchingTrack.GetFormatForPayloadID(header.PayloadType); if (format != null) { return format; } else { logger.LogWarning($"An RTP packet with SSRC {header.SyncSource} matched the {matchingTrack.Kind} track but no capabiltity exists for payload ID {header.PayloadType}."); return null; } } else { logger.LogWarning($"An RTP packet with SSRC {header.SyncSource} and payload ID {header.PayloadType} was received that could not be matched to an audio or video stream."); return null; } } /// <summary> /// Attempts to get the RTCP session that matches a received RTCP report. /// </summary> /// <param name="rtcpPkt">The RTCP compound packet received from the remote party.</param> /// <returns>If a match could be found an SSRC the RTCP session otherwise null.</returns> private RTCPSession GetRtcpSession(RTCPCompoundPacket rtcpPkt) { if (rtcpPkt.SenderReport != null) { if (AudioRemoteTrack != null && AudioRemoteTrack.IsSsrcMatch(rtcpPkt.SenderReport.SSRC)) { return AudioRtcpSession; } else if (VideoRemoteTrack != null && VideoRemoteTrack.IsSsrcMatch(rtcpPkt.SenderReport.SSRC)) { return VideoRtcpSession; } } else if (rtcpPkt.ReceiverReport != null) { if (AudioRemoteTrack != null && AudioRemoteTrack.IsSsrcMatch(rtcpPkt.ReceiverReport.SSRC)) { return AudioRtcpSession; } else if (VideoRemoteTrack != null && VideoRemoteTrack.IsSsrcMatch(rtcpPkt.ReceiverReport.SSRC)) { return VideoRtcpSession; } } // No match on SR/RR SSRC. Check the individual reception reports for a known SSRC. List<ReceptionReportSample> receptionReports = null; if (rtcpPkt.SenderReport != null) { receptionReports = rtcpPkt.SenderReport.ReceptionReports; } else if (rtcpPkt.ReceiverReport != null) { receptionReports = rtcpPkt.ReceiverReport.ReceptionReports; } if (receptionReports != null && receptionReports.Count > 0) { foreach (var recRep in receptionReports) { if (AudioLocalTrack != null && recRep.SSRC == AudioLocalTrack.Ssrc) { return AudioRtcpSession; } else if (VideoLocalTrack != null && recRep.SSRC == VideoLocalTrack.Ssrc) { return VideoRtcpSession; } } } return null; } /// <summary> /// Does the actual sending of an RTP packet using the specified data and header values. /// </summary> /// <param name="rtpChannel">The RTP channel to send from.</param> /// <param name="dstRtpSocket">Destination to send to.</param> /// <param name="data">The RTP packet payload.</param> /// <param name="timestamp">The RTP header timestamp.</param> /// <param name="markerBit">The RTP header marker bit.</param> /// <param name="payloadType">The RTP header payload type.</param> private void SendRtpPacket(RTPChannel rtpChannel, IPEndPoint dstRtpSocket, byte[] data, uint timestamp, int markerBit, int payloadType, uint ssrc, ushort seqNum, RTCPSession rtcpSession) { if (IsSecure && !IsSecureContextReady) { logger.LogWarning("SendRtpPacket cannot be called on a secure session before calling SetSecurityContext."); } else { int srtpProtectionLength = (m_srtpProtect != null) ? SRTP_MAX_PREFIX_LENGTH : 0; RTPPacket rtpPacket = new RTPPacket(data.Length + srtpProtectionLength); rtpPacket.Header.SyncSource = ssrc; rtpPacket.Header.SequenceNumber = seqNum; rtpPacket.Header.Timestamp = timestamp; rtpPacket.Header.MarkerBit = markerBit; rtpPacket.Header.PayloadType = payloadType; Buffer.BlockCopy(data, 0, rtpPacket.Payload, 0, data.Length); var rtpBuffer = rtpPacket.GetBytes(); if (m_srtpProtect == null) { rtpChannel.Send(RTPChannelSocketsEnum.RTP, dstRtpSocket, rtpBuffer); } else { int outBufLen = 0; int rtperr = m_srtpProtect(rtpBuffer, rtpBuffer.Length - srtpProtectionLength, out outBufLen); if (rtperr != 0) { logger.LogError("SendRTPPacket protection failed, result " + rtperr + "."); } else { rtpChannel.Send(RTPChannelSocketsEnum.RTP, dstRtpSocket, rtpBuffer.Take(outBufLen).ToArray()); } } m_lastRtpTimestamp = timestamp; rtcpSession?.RecordRtpPacketSend(rtpPacket); } } /// <summary> /// Sends the RTCP report to the remote call party. /// </summary> /// <param name="report">RTCP report to send.</param> private void SendRtcpReport(SDPMediaTypesEnum mediaType, RTCPCompoundPacket report) { if (IsSecure && !IsSecureContextReady && report.Bye != null) { // Do nothing. The RTCP BYE gets generated when an RTP session is closed. // If that occurs before the connection was able to set up the secure context // there's no point trying to send it. } else { var reportBytes = report.GetBytes(); SendRtcpReport(mediaType, reportBytes); OnSendReport?.Invoke(mediaType, report); } } /// <summary> /// Sends the RTCP report to the remote call party. /// </summary> /// <param name="report">The serialised RTCP report to send.</param> private void SendRtcpReport(SDPMediaTypesEnum mediaType, byte[] reportBuffer) { IPEndPoint controlDstEndPoint = null; if (m_isMediaMultiplexed || mediaType == SDPMediaTypesEnum.audio) { controlDstEndPoint = AudioControlDestinationEndPoint; } else if (mediaType == SDPMediaTypesEnum.video) { controlDstEndPoint = VideoControlDestinationEndPoint; } if (IsSecure && !IsSecureContextReady) { logger.LogWarning("SendRtcpReport cannot be called on a secure session before calling SetSecurityContext."); } else if (controlDstEndPoint != null) { //logger.LogDebug($"SendRtcpReport: {reportBytes.HexStr()}"); var sendOnSocket = (m_isRtcpMultiplexed) ? RTPChannelSocketsEnum.RTP : RTPChannelSocketsEnum.Control; var rtpChannel = GetRtpChannel(mediaType); if (m_srtcpControlProtect == null) { rtpChannel.Send(sendOnSocket, controlDstEndPoint, reportBuffer); } else { byte[] sendBuffer = new byte[reportBuffer.Length + SRTP_MAX_PREFIX_LENGTH]; Buffer.BlockCopy(reportBuffer, 0, sendBuffer, 0, reportBuffer.Length); int outBufLen = 0; int rtperr = m_srtcpControlProtect(sendBuffer, sendBuffer.Length - SRTP_MAX_PREFIX_LENGTH, out outBufLen); if (rtperr != 0) { logger.LogWarning("SRTP RTCP packet protection failed, result " + rtperr + "."); } else { rtpChannel.Send(sendOnSocket, controlDstEndPoint, sendBuffer.Take(outBufLen).ToArray()); } } } } /// <summary> /// Event handler for the RTP channel closure. /// </summary> private void OnRTPChannelClosed(string reason) { Close(reason); } /// <summary> /// Close the session if the instance is out of scope. /// </summary> protected virtual void Dispose(bool disposing) { Close("disposed"); } /// <summary> /// Close the session if the instance is out of scope. /// </summary> public virtual void Dispose() { Close("disposed"); } } }
50.423465
242
0.542646
[ "Apache-2.0" ]
xljiulang/sipsorcery
src/net/RTP/RTPSession.cs
119,909
C#
namespace Calabonga.TemplateProcessor.Engine.Transformer { public interface ITemplateTransform:ITemplateError { void Save(); } }
21.285714
57
0.718121
[ "MIT" ]
Calabonga/TemplateProcessor
Calabonga.TemplateProcessor.Engine/Transformer/ITemplateTransform.cs
151
C#
using Cauldron.Activator; using Cauldron.XAML; using Cauldron.XAML.Navigation; using StandardApplication.ViewModels; using System.Threading.Tasks; using Windows.ApplicationModel.Activation; namespace StandardApplication { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> public sealed partial class App : ApplicationBase { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); } protected override async Task OnStartup(LaunchActivatedEventArgs e) { await this.Navigator.NavigateAsync(typeof(MainViewModel)); } } }
30.931034
98
0.671126
[ "MIT" ]
Capgemini/Cauldron
Old/UWP/Samples/StandardApplication/App.xaml.cs
899
C#
using TestWrapper.Workers; using Unity.Collections; namespace TestCase.Basic.Division.Simple { public struct SimpleDivisionByteJobParallelFor : IJobParallelForExt<NativeArray<byte>, NativeArray<byte>, NativeArray<byte>> { private NativeArray<byte> _data1; private NativeArray<byte> _data2; private NativeArray<byte> _data3; public int DataSize { get; set; } public NativeArray<byte> Data1 { get => _data1; set => _data1 = value; } public NativeArray<byte> Data2 { get => _data2; set => _data2 = value; } public NativeArray<byte> Data3 { get => _data3; set => _data3 = value; } public void Execute(int i) { _data3[i] = (byte) (_data1[i] / _data2[i]); } public void CustomSetUp() { } public void CustomCleanUp() { } } }
22.177778
128
0.532064
[ "MIT" ]
ErikMoczi/Unity.TestRunner.Jobs
Assets/TestCase/Basic/Division/Simple/SimpleAdditionByteJobParallelFor.cs
1,000
C#
using System; using LiteDB; namespace ExperimentationLite.Domain.Entities { public interface IEntity<TKey> { [BsonId] TKey Id { get; set; } } public interface IEntity : IEntity<Guid> { string Name { get; set; } int FriendlyId { get; set; } } }
17.764706
45
0.582781
[ "MIT" ]
iby-dev/ExperimentationLite-API
src/ExperimentationLite.Domain/Entities/IEntity.cs
304
C#
using UnityEngine; using UnityEditor; using FairyGUI; namespace FairyGUIEditor { /// <summary> /// /// </summary> [CustomEditor(typeof(UIConfig))] public class UIConfigEditor : Editor { #if UNITY_5 string[] propertyToExclude; #endif bool itemsFoldout; bool packagesFoldOut; int errorState; private const float kButtonWidth = 18f; void OnEnable() { #if UNITY_5 propertyToExclude = new string[] { "m_Script", "Items", "PreloadPackages" }; #endif itemsFoldout = EditorPrefs.GetBool("itemsFoldOut"); packagesFoldOut = EditorPrefs.GetBool("packagesFoldOut"); errorState = 0; } public override void OnInspectorGUI() { serializedObject.Update(); #if UNITY_5 DrawPropertiesExcluding(serializedObject, propertyToExclude); #endif UIConfig config = (UIConfig)target; EditorGUILayout.BeginHorizontal(); EditorGUI.BeginChangeCheck(); itemsFoldout = EditorGUILayout.Foldout(itemsFoldout, "Config Items"); if (EditorGUI.EndChangeCheck()) EditorPrefs.SetBool("itemsFoldOut", itemsFoldout); EditorGUILayout.EndHorizontal(); if (itemsFoldout) { Undo.RecordObject(config, "Items"); int len = config.Items.Count; EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Add"); UIConfig.ConfigKey selectedKey = (UIConfig.ConfigKey)EditorGUILayout.EnumPopup((System.Enum)UIConfig.ConfigKey.PleaseSelect); if (selectedKey != UIConfig.ConfigKey.PleaseSelect) { int index = (int)selectedKey; if (index > len - 1) { for (int i = len; i < index; i++) config.Items.Add(new UIConfig.ConfigValue()); UIConfig.ConfigValue value = new UIConfig.ConfigValue(); value.valid = true; InitDefaultValue(selectedKey, value); config.Items.Add(value); } else { UIConfig.ConfigValue value = config.Items[index]; if (value == null) { value = new UIConfig.ConfigValue(); value.valid = true; InitDefaultValue(selectedKey, value); config.Items[index] = value; } else if (!value.valid) { value.valid = true; InitDefaultValue(selectedKey, value); } } } EditorGUILayout.EndHorizontal(); for (int i = 0; i < len; i++) { UIConfig.ConfigValue value = config.Items[i]; if (value == null || !value.valid) continue; EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(((UIConfig.ConfigKey)i).ToString()); switch ((UIConfig.ConfigKey)i) { case UIConfig.ConfigKey.ClickDragSensitivity: case UIConfig.ConfigKey.DefaultComboBoxVisibleItemCount: case UIConfig.ConfigKey.DefaultScrollStep: case UIConfig.ConfigKey.TouchDragSensitivity: case UIConfig.ConfigKey.TouchScrollSensitivity: case UIConfig.ConfigKey.InputCaretSize: value.i = EditorGUILayout.IntField(value.i); break; case UIConfig.ConfigKey.ButtonSound: case UIConfig.ConfigKey.GlobalModalWaiting: case UIConfig.ConfigKey.HorizontalScrollBar: case UIConfig.ConfigKey.LoaderErrorSign: case UIConfig.ConfigKey.PopupMenu: case UIConfig.ConfigKey.PopupMenu_seperator: case UIConfig.ConfigKey.TooltipsWin: case UIConfig.ConfigKey.VerticalScrollBar: case UIConfig.ConfigKey.WindowModalWaiting: case UIConfig.ConfigKey.DefaultFont: value.s = EditorGUILayout.TextField(value.s); break; case UIConfig.ConfigKey.DefaultScrollBounceEffect: case UIConfig.ConfigKey.DefaultScrollTouchEffect: case UIConfig.ConfigKey.RenderingTextBrighterOnDesktop: case UIConfig.ConfigKey.AllowSoftnessOnTopOrLeftSide: value.b = EditorGUILayout.Toggle(value.b); break; case UIConfig.ConfigKey.ButtonSoundVolumeScale: value.f = EditorGUILayout.Slider(value.f, 0, 1); break; case UIConfig.ConfigKey.ModalLayerColor: case UIConfig.ConfigKey.InputHighlightColor: value.c = EditorGUILayout.ColorField(value.c); break; } if (GUILayout.Button(new GUIContent("X", "Delete Item"), EditorStyles.miniButtonRight, GUILayout.Width(30))) config.Items[i].Reset(); EditorGUILayout.EndHorizontal(); } } EditorGUILayout.BeginHorizontal(); EditorGUI.BeginChangeCheck(); packagesFoldOut = EditorGUILayout.Foldout(packagesFoldOut, "Preload Packages"); if (EditorGUI.EndChangeCheck()) EditorPrefs.SetBool("packagesFoldOut", packagesFoldOut); EditorGUILayout.EndHorizontal(); if (packagesFoldOut) { Undo.RecordObject(config, "PreloadPackages"); EditorToolSet.LoadPackages(); if (EditorToolSet.packagesPopupContents != null) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Add"); int selected = EditorGUILayout.Popup(EditorToolSet.packagesPopupContents.Length - 1, EditorToolSet.packagesPopupContents); EditorGUILayout.EndHorizontal(); if (selected != EditorToolSet.packagesPopupContents.Length - 1) { UIPackage pkg = UIPackage.GetPackages()[selected]; string tmp = pkg.assetPath.ToLower(); int pos = tmp.LastIndexOf("resources/"); if (pos != -1) { string packagePath = pkg.assetPath.Substring(pos + 10); if (config.PreloadPackages.IndexOf(packagePath) == -1) config.PreloadPackages.Add(packagePath); errorState = 0; } else { errorState = 10; } } } if (errorState > 0) { errorState--; EditorGUILayout.HelpBox("Package is not in resources folder.", MessageType.Warning); } int cnt = config.PreloadPackages.Count; int pi = 0; while (pi < cnt) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("" + pi + "."); config.PreloadPackages[pi] = EditorGUILayout.TextField(config.PreloadPackages[pi]); if (GUILayout.Button(new GUIContent("X", "Delete Item"), EditorStyles.miniButtonRight, GUILayout.Width(30))) { config.PreloadPackages.RemoveAt(pi); cnt--; } else pi++; EditorGUILayout.EndHorizontal(); } } else errorState = 0; if (serializedObject.ApplyModifiedProperties()) (target as UIConfig).ApplyModifiedProperties(); } void InitDefaultValue(UIConfig.ConfigKey key, UIConfig.ConfigValue value) { switch ((UIConfig.ConfigKey)key) { case UIConfig.ConfigKey.ButtonSoundVolumeScale: value.f = 1; break; case UIConfig.ConfigKey.ClickDragSensitivity: value.i = 2; break; case UIConfig.ConfigKey.DefaultComboBoxVisibleItemCount: value.i = 10; break; case UIConfig.ConfigKey.DefaultScrollBarDisplay: value.i = (int)ScrollBarDisplayType.Default; break; case UIConfig.ConfigKey.DefaultScrollBounceEffect: case UIConfig.ConfigKey.DefaultScrollTouchEffect: value.b = true; break; case UIConfig.ConfigKey.DefaultScrollStep: value.i = 25; break; case UIConfig.ConfigKey.ModalLayerColor: value.c = new Color(0f, 0f, 0f, 0.4f); break; case UIConfig.ConfigKey.RenderingTextBrighterOnDesktop: value.b = true; break; case UIConfig.ConfigKey.TouchDragSensitivity: value.i = 10; break; case UIConfig.ConfigKey.TouchScrollSensitivity: value.i = 20; break; case UIConfig.ConfigKey.InputCaretSize: value.i = 1; break; case UIConfig.ConfigKey.InputHighlightColor: value.c = new Color32(255, 223, 141, 128); break; } } } }
27.753676
129
0.682474
[ "MIT" ]
corefan/CatLib
CatLib.Unity/Assets/CatLib/Lib/FairyGUI/FairyGUI/Editor/UIConfigEditor.cs
7,551
C#
namespace NiceHashMiner.Enums { /// <summary> /// Do not delete obsolete enums! Always add new ones before the END enum. /// </summary> public enum MinerBaseType { NONE = 0, cpuminer, ccminer, sgminer, nheqminer, eqm, ethminer, Claymore, OptiminerAMD, excavator, XmrStackCPU, ccminer_alexis, experimental, EWBF, Prospector, Xmrig, XmrStakAMD, Claymore_old, END } }
18.689655
78
0.51107
[ "MIT" ]
tong181567/minin
NiceHashMiner/Enums/MinerBaseType.cs
544
C#
#pragma checksum "D:\Projects\C# DB - September 2019\Entity Framework Core - October 2019\07. C# Auto Mapping Objects\FastFood.Web\Views\Items\Create.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "0df4409144170315fe55a4a03420f7366032a928" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Items_Create), @"mvc.1.0.view", @"/Views/Items/Create.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Items/Create.cshtml", typeof(AspNetCore.Views_Items_Create))] 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; #line 1 "D:\Projects\C# DB - September 2019\Entity Framework Core - October 2019\07. C# Auto Mapping Objects\FastFood.Web\Views\_ViewImports.cshtml" using FastFood.Web; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"0df4409144170315fe55a4a03420f7366032a928", @"/Views/Items/Create.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"6e2355b4d2dd102d586b09f0f668ac669855f614", @"/Views/_ViewImports.cshtml")] public class Views_Items_Create : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<IList<FastFood.Web.ViewModels.Items.CreateItemViewModel>> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("mx-auto half-width"), 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("asp-controller", "Items", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Create", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "post", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); 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.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { BeginContext(65, 2, true); WriteLiteral("\r\n"); EndContext(); #line 3 "D:\Projects\C# DB - September 2019\Entity Framework Core - October 2019\07. C# Auto Mapping Objects\FastFood.Web\Views\Items\Create.cshtml" ViewData["Title"] = "Create Item"; #line default #line hidden BeginContext(114, 82, true); WriteLiteral("<h1 class=\"text-center\">Create Item</h1>\r\n<hr class=\"bg-secondary half-width\" />\r\n"); EndContext(); BeginContext(196, 999, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "c501f480afa3453dac57dc3c1629d278", async() => { BeginContext(286, 540, true); WriteLiteral(@" <div class=""form-group""> <label for=""name"">Name</label> <input type=""text"" class=""form-control"" id=""name"" placeholder=""Name..."" name=""name""> </div> <div class=""form-group""> <label for=""price"">Price</label> <input type=""number"" step=""0.01"" min=""0.01"" class=""form-control"" id=""price"" placeholder=""Price..."" name=""price""> </div> <div class=""form-group""> <label for=""category"">Category Name</label> <select id=""category"" class=""form-control"" name=""CategoryName""> "); EndContext(); #line 20 "D:\Projects\C# DB - September 2019\Entity Framework Core - October 2019\07. C# Auto Mapping Objects\FastFood.Web\Views\Items\Create.cshtml" foreach (var item in Model) { #line default #line hidden BeginContext(883, 16, true); WriteLiteral(" "); EndContext(); BeginContext(899, 62, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("option", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "cd7a5728453f413bbf8d6906f8044a19", async() => { BeginContext(935, 17, false); #line 22 "D:\Projects\C# DB - September 2019\Entity Framework Core - October 2019\07. C# Auto Mapping Objects\FastFood.Web\Views\Items\Create.cshtml" Write(item.CategoryName); #line default #line hidden EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper); BeginWriteTagHelperAttribute(); #line 22 "D:\Projects\C# DB - September 2019\Entity Framework Core - October 2019\07. C# Auto Mapping Objects\FastFood.Web\Views\Items\Create.cshtml" WriteLiteral(item.CategoryName); #line default #line hidden __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); __Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper.Value = __tagHelperStringValueBuffer; __tagHelperExecutionContext.AddTagHelperAttribute("value", __Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper.Value, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(961, 2, true); WriteLiteral("\r\n"); EndContext(); #line 23 "D:\Projects\C# DB - September 2019\Entity Framework Core - October 2019\07. C# Auto Mapping Objects\FastFood.Web\Views\Items\Create.cshtml" } #line default #line hidden BeginContext(978, 210, true); WriteLiteral(" </select>\r\n </div>\r\n <hr class=\"bg-secondary half-width\" />\r\n <div class=\"button-holder d-flex justify-content-center\">\r\n <button type=\"submit\" class=\"btn \">Create</button>\r\n </div>\r\n"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Controller = (string)__tagHelperAttribute_1.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_2.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); } #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<IList<FastFood.Web.ViewModels.Items.CreateItemViewModel>> Html { get; private set; } } } #pragma warning restore 1591
68.988095
356
0.718205
[ "MIT" ]
MertYumer/C-DB---September-2019
Entity Framework Core - October 2019/07. C# Auto Mapping Objects/FastFood.Web/obj/Debug/netcoreapp2.1/Razor/Views/Items/Create.cshtml.g.cs
11,590
C#
using System.Collections; using UnityEngine; namespace DCL.Tutorial { /// <summary> /// Class that represents the onboarding tutorial step related to how to Jump In the Genesis Plaza and become a DCL Citizen. /// </summary> public class TutorialStep_Tooltip_GoToGenesisButton : TutorialStep_Tooltip { protected override void SetTooltipPosition() { base.SetTooltipPosition(); if (tutorialController != null && tutorialController.hudController != null && tutorialController.hudController.taskbarHud.goToGenesisTooltipReference) { tutorialController.hudController.taskbarHud.ShowGoToGenesisPlazaButton(); tooltipTransform.position = tutorialController.hudController.taskbarHud.goToGenesisTooltipReference.position; } } } }
36.708333
128
0.675369
[ "Apache-2.0" ]
maraoz/explorer
unity-client/Assets/Tutorial/Scripts/Steps/TutorialStep_Tooltip_GoToGenesisButton.cs
881
C#
using Microsoft.EntityFrameworkCore; using ORMIntegrator; using System; namespace Microsoft.Extensions.DependencyInjection; public static class ServiceCollectionExtensionLibrary { public static IServiceCollection AddSqlManager<TDbContext>(this IServiceCollection serviceDescriptors, Func<string, TDbContext> dbContextFactoryMethod, string connectionString) where TDbContext : DbContext, new() { serviceDescriptors.AddScoped(_ => new SqlManager<TDbContext>( dbContextFactoryMethod, connectionString )); return serviceDescriptors.AddScoped( serviceProvider => new ScopedTransactionBuilder<TDbContext>(serviceProvider.GetRequiredService<SqlManager<TDbContext>>())); } }
40
218
0.75
[ "MIT" ]
CreatioVitae/ORMIntegrator
src/ORMIntegrator.Extensions.DependencyInjection/ServiceCollectionExtensionLibrary.cs
760
C#
using Funeral.Core.IRepository; using Funeral.Core.IRepository.UnitOfWork; using Funeral.Core.Model.Models; using Funeral.Core.Repository.Base; namespace Funeral.Core.Repository { /// <summary> /// AchFgpRepository /// </summary> public class AchFgpRepository : BaseRepository<AchFgp>, IAchFgpRepository { public AchFgpRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } } }
25.235294
77
0.703963
[ "Apache-2.0" ]
15958105063/FuneralVue
Funeral.Core.Repository/Ach/AchFgpRepository.cs
429
C#
using System; using System.Configuration; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; using Timer = System.Windows.Forms.Timer; namespace ACNHPoker { public partial class Form1 : Form { private void villagerBtn_Click(object sender, EventArgs e) { this.inventoryBtn.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(114)))), ((int)(((byte)(137)))), ((int)(((byte)(218))))); this.critterBtn.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(114)))), ((int)(((byte)(137)))), ((int)(((byte)(218))))); this.otherBtn.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(114)))), ((int)(((byte)(137)))), ((int)(((byte)(218))))); this.villagerBtn.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(80)))), ((int)(((byte)(80)))), ((int)(((byte)(255))))); inventoryLargePanel.Visible = false; otherLargePanel.Visible = false; critterLargePanel.Visible = false; villagerLargePanel.Visible = true; closeVariationMenu(); int player = 0; if (V == null && !firstload) { firstload = true; Thread LoadAllVillagerThread = new Thread(delegate () { loadAllVillager(player); }); LoadAllVillagerThread.Start(); } } private void loadAllVillager(int player) { lock (villagerLock) { if (bot == null) showVillagerWait(25000, "Acquiring villager data..."); else showVillagerWait(15000, "Acquiring villager data..."); if ((s == null || s.Connected == false) & bot == null) return; blocker = true; selectedVillagerButton = null; HouseList = new int[10]; for (int i = 0; i < 10; i++) { byte b = Utilities.GetHouseOwner(s, bot, i, ref counter); if (b == 0xDD) { hideVillagerWait(); return; } HouseList[i] = Convert.ToInt32(b); } Debug.Print(string.Join(" ", HouseList)); V = new Villager[10]; villagerButton = new Button[10]; for (int i = 0; i < 10; i++) { byte[] b = Utilities.GetVillager(s, bot, i, (int)(Utilities.VillagerMemoryTinySize), ref counter); V[i] = new Villager(b, i) { HouseIndex = Utilities.FindHouseIndex(i, HouseList) }; byte f = Utilities.GetVillagerHouseFlag(s, bot, V[i].HouseIndex, 0x8, ref counter); V[i].MoveInFlag = Convert.ToInt32(f); byte[] move = Utilities.GetMoveout(s, bot, i, (int)0x33, ref counter); V[i].AbandonedHouseFlag = Convert.ToInt32(move[0]); V[i].InvitedFlag = Convert.ToInt32(move[0x14]); V[i].ForceMoveOutFlag = Convert.ToInt32(move[move.Length - 1]); byte[] catchphrase = Utilities.GetCatchphrase(s, bot, i, ref counter); V[i].catchphrase = catchphrase; villagerButton[i] = new Button(); villagerButton[i].TextAlign = System.Drawing.ContentAlignment.TopCenter; villagerButton[i].ForeColor = System.Drawing.Color.White; villagerButton[i].Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Bold); int friendship = V[i].Friendship[player]; villagerButton[i].BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(friendship)))), ((int)(((byte)(friendship / 2)))), ((int)(((byte)(friendship))))); villagerButton[i].FlatAppearance.BorderSize = 0; villagerButton[i].FlatStyle = System.Windows.Forms.FlatStyle.Flat; if (i < 5) villagerButton[i].Location = new System.Drawing.Point((i * 128) + (i * 10) + 50, 54); else villagerButton[i].Location = new System.Drawing.Point(((i - 5) * 128) + ((i - 5) * 10) + 50, 192); villagerButton[i].Name = "villagerBtn" + i.ToString(); villagerButton[i].Tag = i; villagerButton[i].Size = new System.Drawing.Size(128, 128); villagerButton[i].UseVisualStyleBackColor = false; Image img; if (V[i].GetRealName() == "ERROR") { string path = Utilities.GetVillagerImage(V[i].GetRealName()); if (!path.Equals(string.Empty)) img = Image.FromFile(path); else img = new Bitmap(Properties.Resources.Leaf, new Size(110, 110)); } else { string path = Utilities.GetVillagerImage(V[i].GetInternalName()); if (!path.Equals(string.Empty)) img = Image.FromFile(path); else img = new Bitmap(Properties.Resources.Leaf, new Size(110, 110)); } villagerButton[i].Text = V[i].GetRealName() + " : " + V[i].GetInternalName(); if (V[i].MoveInFlag == 0xC || V[i].MoveInFlag == 0xB) { if (V[i].IsReal()) { if (V[i].IsInvited()) villagerButton[i].Text += "\n(Tom Nook Invited)"; else villagerButton[i].Text += "\n(Moving In)"; } else villagerButton[i].Text += "\n(Just Move Out)"; } else if (V[i].InvitedFlag == 0x2) villagerButton[i].Text += "\n(Invited by Visitor)"; else if (V[i].AbandonedHouseFlag == 0x1 && V[i].ForceMoveOutFlag == 0x0) villagerButton[i].Text += "\n(Floor Sweeping)"; else if (V[i].AbandonedHouseFlag == 0x2 && V[i].ForceMoveOutFlag == 0x1) villagerButton[i].Text += "\n(Moving Out 1)"; else if (V[i].AbandonedHouseFlag == 0x2 && V[i].ForceMoveOutFlag == 0x0) villagerButton[i].Text += "\n(Moving Out 2)"; villagerButton[i].Image = (Image)(new Bitmap(img, new Size(110, 110))); villagerButton[i].ImageAlign = ContentAlignment.BottomCenter; villagerButton[i].MouseDown += new System.Windows.Forms.MouseEventHandler(this.VillagerButton_MouseDown); } this.Invoke((MethodInvoker)delegate { for (int i = 0; i < 10; i++) { this.villagerLargePanel.Controls.Add(villagerButton[i]); villagerButton[i].BringToFront(); //overlay.BringToFront(); } IndexValue.Text = ""; NameValue.Text = ""; InternalNameValue.Text = ""; PersonalityValue.Text = ""; FriendShipValue.Text = ""; HouseIndexValue.Text = ""; MoveInFlag.Text = ""; MoveOutValue.Text = ""; ForceMoveOutValue.Text = ""; CatchphraseValue.Text = ""; FullAddress.Text = ""; RefreshVillagerBtn.Enabled = true; }); if (sound) System.Media.SystemSounds.Asterisk.Play(); blocker = false; hideVillagerWait(); } } private void RefreshVillagerBtn_Click(object sender, EventArgs e) { if ((s == null || s.Connected == false) & bot == null) { return; } if (villagerButton != null) { for (int i = 0; i < 10; i++) this.villagerLargePanel.Controls.Remove(villagerButton[i]); } int player = 0; Thread LoadAllVillagerThread = new Thread(delegate () { loadAllVillager(player); }); LoadAllVillagerThread.Start(); } public void RefreshVillagerUI(bool clear) { for (int j = 0; j < 10; j++) { int friendship = V[j].Friendship[0]; if (villagerButton[j] != selectedVillagerButton) villagerButton[j].BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(friendship)))), ((int)(((byte)(friendship / 2)))), ((int)(((byte)(friendship))))); villagerButton[j].Text = V[j].GetRealName() + " : " + V[j].GetInternalName(); if (V[j].MoveInFlag == 0xC || V[j].MoveInFlag == 0xB) { if (V[j].IsReal()) { if (V[j].IsInvited()) villagerButton[j].Text += "\n(Tom Nook Invited)"; else villagerButton[j].Text += "\n(Moving In)"; } else villagerButton[j].Text += "\n(Just Move Out)"; } else if (V[j].InvitedFlag == 0x2) villagerButton[j].Text += "\n(Invited by Visitor)"; else if (V[j].AbandonedHouseFlag == 0x1 && V[j].ForceMoveOutFlag == 0x0) villagerButton[j].Text += "\n(Floor Sweeping)"; else if (V[j].AbandonedHouseFlag == 0x2 && V[j].ForceMoveOutFlag == 0x1) villagerButton[j].Text += "\n(Moving Out 1)"; else if (V[j].AbandonedHouseFlag == 0x2 && V[j].ForceMoveOutFlag == 0x0) villagerButton[j].Text += "\n(Moving Out 2)"; Image img; if (V[j].GetRealName() == "ERROR") { string path = Utilities.GetVillagerImage(V[j].GetRealName()); if (!path.Equals(string.Empty)) img = Image.FromFile(path); else img = new Bitmap(Properties.Resources.Leaf, new Size(110, 110)); } else { string path = Utilities.GetVillagerImage(V[j].GetInternalName()); if (!path.Equals(string.Empty)) img = Image.FromFile(path); else img = new Bitmap(Properties.Resources.Leaf, new Size(110, 110)); } villagerButton[j].Image = (Image)(new Bitmap(img, new Size(110, 110))); } if (!clear) { if (selectedVillagerButton != null) { selectedVillagerButton.BackColor = System.Drawing.Color.LightSeaGreen; int i = Int16.Parse(selectedVillagerButton.Tag.ToString()); if (blocker == false) VillagerControl.Enabled = true; else VillagerControl.Enabled = false; if (V[i].MoveInFlag == 0xC || V[i].MoveInFlag == 0xB) { if (V[i].IsReal()) VillagerControl.Enabled = false; } IndexValue.Text = V[i].Index.ToString(); NameValue.Text = V[i].GetRealName(); InternalNameValue.Text = V[i].GetInternalName(); PersonalityValue.Text = V[i].GetPersonality(); FriendShipValue.Text = V[i].Friendship[0].ToString(); HouseIndexValue.Text = V[i].HouseIndex.ToString(); MoveInFlag.Text = "0x" + V[i].MoveInFlag.ToString("X"); MoveOutValue.Text = "0x" + V[i].AbandonedHouseFlag.ToString("X"); ForceMoveOutValue.Text = "0x" + V[i].ForceMoveOutFlag.ToString("X"); CatchphraseValue.Text = Encoding.Unicode.GetString(V[i].catchphrase, 0, 44); FullAddress.Text = Utilities.ByteToHexString(V[i].GetHeader()); //PlayerName.Text = V[i].GetPlayerName(playerSelectorVillager.SelectedIndex); } } /* if (sound) System.Media.SystemSounds.Asterisk.Play(); */ } private void VillagerButton_MouseDown(object sender, MouseEventArgs e) { selectedVillagerButton = (Button)sender; RefreshVillagerUI(false); } private void DumpVillagerBtn_Click(object sender, EventArgs e) { if (IndexValue.Text == "") return; int i = Int16.Parse(IndexValue.Text); SaveFileDialog file = new SaveFileDialog() { Filter = "New Horizons Villager (*.nhv2)|*.nhv2", FileName = V[i].GetInternalName() + ".nhv2", }; Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); string savepath; if (config.AppSettings.Settings["LastSave"].Value.Equals(string.Empty)) savepath = Directory.GetCurrentDirectory() + @"\save"; else savepath = config.AppSettings.Settings["LastSave"].Value; if (Directory.Exists(savepath)) { file.InitialDirectory = savepath; } else { file.InitialDirectory = @"C:\"; } if (file.ShowDialog() != DialogResult.OK) return; string[] temp = file.FileName.Split('\\'); string path = ""; for (int j = 0; j < temp.Length - 1; j++) path = path + temp[j] + "\\"; config.AppSettings.Settings["LastSave"].Value = path; config.Save(ConfigurationSaveMode.Minimal); Thread dumpThread = new Thread(delegate () { dumpVillager(i, file); }); dumpThread.Start(); } private void dumpVillager(int i, SaveFileDialog file) { showVillagerWait((int)Utilities.VillagerSize, "Dumping " + V[i].GetRealName() + " ..."); blocker = true; byte[] VillagerData = Utilities.GetVillager(s, bot, i, (int)Utilities.VillagerSize, ref counter); File.WriteAllBytes(file.FileName, VillagerData); byte[] CheckData = File.ReadAllBytes(file.FileName); byte[] CheckHeader = new byte[52]; if (header[0] != 0x0 && header[1] != 0x0 && header[2] != 0x0) { Buffer.BlockCopy(CheckData, 0x4, CheckHeader, 0x0, 52); } if (!CheckHeader.SequenceEqual(header)) { Debug.Print(Utilities.ByteToHexString(CheckHeader)); Debug.Print(Utilities.ByteToHexString(header)); MessageBox.Show("Wait something is wrong here!? \n\n Header Mismatch!", "Warning"); } if (sound) System.Media.SystemSounds.Asterisk.Play(); blocker = false; hideVillagerWait(); } private void ProgressTimer_Tick(object sender, EventArgs e) { Invoke((MethodInvoker)delegate { if (counter <= VillagerProgressBar.Maximum) VillagerProgressBar.Value = counter; else VillagerProgressBar.Value = VillagerProgressBar.Maximum; }); } private void DumpMoveOutBtn_Click(object sender, EventArgs e) { if (IndexValue.Text == "") return; int i = Int16.Parse(IndexValue.Text); byte[] move = Utilities.GetMoveout(s, bot, i, (int)(0x33), ref counter); File.WriteAllBytes(V[i].GetInternalName() + "MOVEOUT.bin", move); } private void MoveOutBtn_Click(object sender, EventArgs e) { if (IndexValue.Text == "") return; int i = Int16.Parse(IndexValue.Text); if (checkMultipleMoveOut() && !firstWarning) { DialogResult dialogResult = myMessageBox.Show("It seems you alreadly have someone moving out." + " \nAre you sure you want to force another moveout?" + " \nNote that multiple moveout on the same day is not recommended.", "Multiple moveout detected!", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (dialogResult == DialogResult.No) return; if (dialogResult == DialogResult.Yes) firstWarning = true; } Utilities.SetMoveout(s, bot, i); V[i].AbandonedHouseFlag = 2; V[i].ForceMoveOutFlag = 1; V[i].InvitedFlag = 0; RefreshVillagerUI(false); } private void StayMoveBtn_Click(object sender, EventArgs e) { if (IndexValue.Text == "") return; int i = Int16.Parse(IndexValue.Text); if (checkMultipleMoveOut() && !firstWarning) { DialogResult dialogResult = myMessageBox.Show("It seems you alreadly have someone moving out." + " \nAre you sure you want to force another moveout?" + " \nNote that multiple moveout on the same day is not recommended.", "Multiple moveout detected!", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (dialogResult == DialogResult.No) return; if (dialogResult == DialogResult.Yes) firstWarning = true; } Utilities.SetMoveout(s, bot, i, "2", "0"); V[i].AbandonedHouseFlag = 2; V[i].ForceMoveOutFlag = 0; V[i].InvitedFlag = 0; RefreshVillagerUI(false); } private void CancelMoveOutBtn_Click(object sender, EventArgs e) { if (IndexValue.Text == "") return; int i = Int16.Parse(IndexValue.Text); Utilities.SetMoveout(s, bot, i, "0", "0"); V[i].AbandonedHouseFlag = 0; V[i].ForceMoveOutFlag = 0; V[i].InvitedFlag = 0; RefreshVillagerUI(false); } private void MoveOutAllBtn_Click(object sender, EventArgs e) { for (int i = 0; i < 10; i++) { Utilities.SetMoveout(s, bot, i); V[i].AbandonedHouseFlag = 2; V[i].ForceMoveOutFlag = 1; V[i].InvitedFlag = 0; } RefreshVillagerUI(false); if (sound) System.Media.SystemSounds.Asterisk.Play(); } private void StayMoveAllBtn_Click(object sender, EventArgs e) { for (int i = 0; i < 10; i++) { Utilities.SetMoveout(s, bot, i, "2", "0"); V[i].AbandonedHouseFlag = 2; V[i].ForceMoveOutFlag = 0; V[i].InvitedFlag = 0; } RefreshVillagerUI(false); if (sound) System.Media.SystemSounds.Asterisk.Play(); } private void CancelMoveOutAllBtn_Click(object sender, EventArgs e) { for (int i = 0; i < 10; i++) { Utilities.SetMoveout(s, bot, i, "0", "0"); V[i].AbandonedHouseFlag = 0; V[i].ForceMoveOutFlag = 0; V[i].InvitedFlag = 0; } RefreshVillagerUI(false); if (sound) System.Media.SystemSounds.Asterisk.Play(); } private void MaxFriendshipBtn_Click(object sender, EventArgs e) { if (IndexValue.Text == "") return; int i = Int16.Parse(IndexValue.Text); int player = 0; Utilities.SetFriendship(s, bot, i, player); V[i].Friendship[player] = 255; RefreshVillagerUI(false); } private void SetFriendshipBtn_Click(object sender, EventArgs e) { if (IndexValue.Text == "") return; int i = Int16.Parse(IndexValue.Text); Image img; string path; if (V[i].GetRealName() == "ERROR") { path = Utilities.GetVillagerImage(V[i].GetRealName()); } else { path = Utilities.GetVillagerImage(V[i].GetInternalName()); } if (!path.Equals(string.Empty)) img = Image.FromFile(path); else img = new Bitmap(Properties.Resources.Leaf, new Size(128, 128)); friendship = new Friendship(this, i, s, bot, img, V[i].GetRealName(), sound); friendship.Show(); friendship.Location = new System.Drawing.Point(this.Location.X + 30, this.Location.Y + 30); } public string PassPlayerName(int i, int p) { return V[i].GetPlayerName(p); } public void SetFriendship(int i, int p, int value) { V[i].Friendship[p] = (byte)value; } private void DumpAllHouseBtn_Click(object sender, EventArgs e) { for (int i = 0; i < 10; i++) { byte[] house = Utilities.GetHouse(s, bot, i, ref counter); File.WriteAllBytes("House" + i + ".nhvh", house); } } private void DumpAllHouseBufferBtn_Click(object sender, EventArgs e) { for (int i = 0; i < 10; i++) { byte[] house = Utilities.GetHouse(s, bot, i, ref counter, Utilities.VillagerHouseBufferDiff); File.WriteAllBytes("HouseBuffer" + i + ".nhvh", house); } } private void DumpHouseBtn_Click(object sender, EventArgs e) { if (IndexValue.Text == "") return; int i = Int16.Parse(IndexValue.Text); int j = V[i].HouseIndex; if (j < 0 || j > 9) return; SaveFileDialog file = new SaveFileDialog() { Filter = "New Horizons Villager House (*.nhvh)|*.nhvh", FileName = V[i].GetInternalName() + ".nhvh", }; Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); string savepath; if (config.AppSettings.Settings["LastSave"].Value.Equals(string.Empty)) savepath = Directory.GetCurrentDirectory() + @"\save"; else savepath = config.AppSettings.Settings["LastSave"].Value; if (Directory.Exists(savepath)) { file.InitialDirectory = savepath; } else { file.InitialDirectory = @"C:\"; } if (file.ShowDialog() != DialogResult.OK) return; string[] temp = file.FileName.Split('\\'); string path = ""; for (int k = 0; k < temp.Length - 1; k++) path = path + temp[k] + "\\"; config.AppSettings.Settings["LastSave"].Value = path; config.Save(ConfigurationSaveMode.Minimal); Thread dumpThread = new Thread(delegate () { dumpHouse(i, j, file); }); dumpThread.Start(); } private void dumpHouse(int i, int j, SaveFileDialog file) { showVillagerWait((int)Utilities.VillagerHouseSize, "Dumping " + V[i].GetRealName() + "'s House ..."); byte[] house = Utilities.GetHouse(s, bot, j, ref counter); File.WriteAllBytes(file.FileName, house); if (sound) System.Media.SystemSounds.Asterisk.Play(); hideVillagerWait(); } private void ReadMysVillagerBtn_Click(object sender, EventArgs e) { byte[] IName = Utilities.GetMysVillagerName(s, bot); string StrName = Encoding.ASCII.GetString(Utilities.ByteTrim(IName)); string RealName = Utilities.GetVillagerRealName(StrName); Image img; if (RealName == "ERROR") { string path = Utilities.GetVillagerImage(RealName); if (!path.Equals(string.Empty)) img = Image.FromFile(path); else img = new Bitmap(Properties.Resources.Leaf, new Size(110, 110)); MysVillagerBtn.Text = ""; } else { string path = Utilities.GetVillagerImage(StrName); if (!path.Equals(string.Empty)) img = Image.FromFile(path); else img = new Bitmap(Properties.Resources.Leaf, new Size(110, 110)); MysIName.Text = StrName; MysRealName.Text = RealName; MysVillagerBtn.Text = RealName + " : " + StrName; } MysVillagerBtn.Image = (Image)(new Bitmap(img, new Size(110, 110))); if (sound) System.Media.SystemSounds.Asterisk.Play(); } private void TransformBtn_Click(object sender, EventArgs e) { if (MysSelector.SelectedIndex < 0) return; string[] lines = MysSelector.SelectedItem.ToString().Split(new string[] { " " }, StringSplitOptions.None); byte[] IName = Encoding.Default.GetBytes(lines[lines.Length - 1]); byte[] species = new byte[1]; species[0] = Utilities.CheckSpecies[(lines[lines.Length - 1]).Substring(0, 3)]; Utilities.SetMysVillager(s, bot, IName, species, ref counter); Image img; string path = Utilities.GetVillagerImage(lines[lines.Length - 1]); if (!path.Equals(String.Empty)) img = Image.FromFile(path); else img = new Bitmap(Properties.Resources.Leaf, new Size(110, 110)); MysIName.Text = lines[lines.Length - 1]; MysRealName.Text = lines[0]; MysVillagerBtn.Text = lines[0] + " : " + lines[lines.Length - 1]; MysVillagerBtn.Image = (Image)(new Bitmap(img, new Size(110, 110))); if (sound) System.Media.SystemSounds.Asterisk.Play(); } private void SetCatchphraseBtn_Click(object sender, EventArgs e) { if (IndexValue.Text == "") return; int i = Int16.Parse(IndexValue.Text); byte[] phrase = new byte[44]; byte[] temp = Encoding.Unicode.GetBytes(CatchphraseValue.Text); for (int j = 0; j < temp.Length; j++) { phrase[j] = temp[j]; } Utilities.SetCatchphrase(s, bot, i, phrase); V[i].catchphrase = phrase; RefreshVillagerUI(false); } private void ResetCatchphraseBtn_Click(object sender, EventArgs e) { if (IndexValue.Text == "") return; int i = Int16.Parse(IndexValue.Text); byte[] phrase = new byte[44]; Utilities.SetCatchphrase(s, bot, i, phrase); V[i].catchphrase = phrase; RefreshVillagerUI(false); } private void showVillagerWait(int size, string msg = "") { this.Invoke((MethodInvoker)delegate { VillagerControl.Enabled = false; //overlay.Visible = true; //overlay.BringToFront(); WaitMessagebox.SelectionAlignment = HorizontalAlignment.Center; WaitMessagebox.Text = msg; counter = 0; if (bot == null) VillagerProgressBar.Maximum = size / 500 + 5; else VillagerProgressBar.Maximum = size / 300 + 5; Debug.Print("Max : " + VillagerProgressBar.Maximum.ToString()); VillagerProgressBar.Value = counter; PleaseWaitPanel.Visible = true; ProgressTimer.Start(); }); } private void hideVillagerWait() { if (InvokeRequired) { MethodInvoker method = new MethodInvoker(hideVillagerWait); Invoke(method); return; } if (!blocker) { Debug.Print("Counter : " + counter.ToString()); PleaseWaitPanel.Visible = false; VillagerControl.Enabled = true; //overlay.Visible = false; if (PleaseWaitPanel.Location.X != 780) PleaseWaitPanel.Location = new Point(780, 330); ProgressTimer.Stop(); } } private void LoadVillagerBtn_Click(object sender, EventArgs e) { if (IndexValue.Text == "") return; int i = Int16.Parse(IndexValue.Text); OpenFileDialog file = new OpenFileDialog() { Filter = "New Horizons Villager (*.nhv2)|*.nhv2|New Horizons Villager (*.nhv)|*.nhv", //FileName = V[i].GetInternalName() + ".nhv", }; Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); string savepath; if (config.AppSettings.Settings["LastLoad"].Value.Equals(string.Empty)) savepath = Directory.GetCurrentDirectory() + @"\save"; else savepath = config.AppSettings.Settings["LastLoad"].Value; if (Directory.Exists(savepath)) { file.InitialDirectory = savepath; } else { file.InitialDirectory = @"C:\"; } if (file.ShowDialog() != DialogResult.OK) return; string[] temp = file.FileName.Split('\\'); string path = ""; for (int j = 0; j < temp.Length - 1; j++) path = path + temp[j] + "\\"; config.AppSettings.Settings["LastLoad"].Value = path; config.Save(ConfigurationSaveMode.Minimal); byte[] data = File.ReadAllBytes(file.FileName); if (data.Length == Utilities.VillagerOldSize) { data = ConvertToNew(data); } if (data.Length != Utilities.VillagerSize) { MessageBox.Show("Villager file size incorrect!", "Villager file invalid"); return; } string msg = "Loading villager..."; Thread LoadVillagerThread = new Thread(delegate () { loadvillager(i, data, msg); }); LoadVillagerThread.Start(); } private void loadvillager(int i, byte[] villager, string msg) { showVillagerWait((int)Utilities.VillagerSize * 2, msg); blocker = true; byte[] modifiedVillager = villager; if (!ignoreHeader.Checked) { if (header[0] != 0x0 && header[1] != 0x0 && header[2] != 0x0) { Buffer.BlockCopy(header, 0x0, modifiedVillager, 0x4, 52); } } V[i].LoadData(modifiedVillager); //byte[] move = Utilities.GetMoveout(s, bot, i, (int)0x33, ref counter); V[i].AbandonedHouseFlag = Convert.ToInt32(villager[Utilities.VillagerMoveoutOffset]); V[i].ForceMoveOutFlag = Convert.ToInt32(villager[Utilities.VillagerForceMoveoutOffset]); byte[] phrase = new byte[44]; //buffer.BlockCopy(Bank01to20, slotOffset, slotBytes, 0x0, 0x4); Buffer.BlockCopy(villager, (int)Utilities.VillagerCatchphraseOffset, phrase, 0x0, 44); V[i].catchphrase = phrase; Utilities.LoadVillager(s, bot, i, modifiedVillager, ref counter); this.Invoke((MethodInvoker)delegate { RefreshVillagerUI(false); }); blocker = false; hideVillagerWait(); } private void LoadHouseBtn_Click(object sender, EventArgs e) { if (IndexValue.Text == "") return; int i = Int16.Parse(IndexValue.Text); int j = V[i].HouseIndex; if (j < 0 || j > 9) return; OpenFileDialog file = new OpenFileDialog() { Filter = "New Horizons Villager House (*.nhvh)|*.nhvh", //FileName = V[i].GetInternalName() + ".nhvh", }; Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); string savepath; if (config.AppSettings.Settings["LastLoad"].Value.Equals(string.Empty)) savepath = Directory.GetCurrentDirectory() + @"\save"; else savepath = config.AppSettings.Settings["LastLoad"].Value; if (Directory.Exists(savepath)) { file.InitialDirectory = savepath; } else { file.InitialDirectory = @"C:\"; } if (file.ShowDialog() != DialogResult.OK) return; string[] temp = file.FileName.Split('\\'); string path = ""; for (int k = 0; k < temp.Length - 1; k++) path = path + temp[k] + "\\"; config.AppSettings.Settings["LastLoad"].Value = path; config.Save(ConfigurationSaveMode.Minimal); byte[] data = File.ReadAllBytes(file.FileName); if (data.Length != Utilities.VillagerHouseSize) { MessageBox.Show("House file size incorrect!", "House file invalid"); return; } string msg = "Loading house..."; Thread LoadHouseThread = new Thread(delegate () { loadhouse(i, j, data, msg); }); LoadHouseThread.Start(); } private void loadhouse(int i, int j, byte[] house, string msg) { showVillagerWait((int)Utilities.VillagerHouseSize * 2, msg); byte[] modifiedHouse = house; byte h = (Byte)i; modifiedHouse[Utilities.VillagerHouseOwnerOffset] = h; V[i].HouseIndex = j; HouseList[j] = i; Utilities.LoadHouse(s, bot, j, modifiedHouse, ref counter); this.Invoke((MethodInvoker)delegate { RefreshVillagerUI(false); }); hideVillagerWait(); } private void ReplaceBtn_Click(object sender, EventArgs e) { if (IndexValue.Text == "") return; int i = Int16.Parse(IndexValue.Text); int j = V[i].HouseIndex; if (j > 9) return; int EmptyHouseNumber; if (j < 0) { EmptyHouseNumber = findEmptyHouse(); if (EmptyHouseNumber >= 0) j = EmptyHouseNumber; else return; } if (ReplaceSelector.SelectedIndex < 0) return; string[] lines = ReplaceSelector.SelectedItem.ToString().Split(new string[] { " " }, StringSplitOptions.None); //byte[] IName = Encoding.Default.GetBytes(lines[lines.Length - 1]); string IName = lines[lines.Length - 1]; string RealName = lines[0]; string IVpath = Utilities.villagerPath + IName + ".nhv2"; string RVpath = Utilities.villagerPath + RealName + ".nhv2"; byte[] villagerData; byte[] houseData; if (checkDuplicate(IName)) { DialogResult dialogResult = myMessageBox.Show(RealName + " is currently living on your island!" + " \nAre you sure you want to continue the replacement?" + " \nNote that the game will attempt to remove any duplicated villager!", "Villager already exists!", MessageBoxButtons.YesNo, MessageBoxIcon.Error); if (dialogResult == DialogResult.No) { return; } } if (File.Exists(IVpath)) { Debug.Print("FOUND: " + IVpath); villagerData = File.ReadAllBytes(IVpath); } else if (File.Exists(RVpath)) { Debug.Print("FOUND: " + RVpath); villagerData = File.ReadAllBytes(RVpath); } else { MessageBox.Show("Villager files \"" + IName + ".nhv2\" " + "/ \"" + RealName + ".nhv2\" " + "not found!", "Villager file not found"); return; } string IHpath = Utilities.villagerPath + IName + ".nhvh"; string RHpath = Utilities.villagerPath + RealName + ".nhvh"; if (File.Exists(IHpath)) { Debug.Print("FOUND: " + IHpath); houseData = File.ReadAllBytes(IHpath); } else if (File.Exists(RHpath)) { Debug.Print("FOUND: " + RHpath); houseData = File.ReadAllBytes(RHpath); } else { MessageBox.Show("Villager house files \"" + IName + ".nhvh\" " + "/ \"" + RealName + ".nhvh\" " + "not found!", "House file not found"); return; } string msg = "Replacing Villager..."; Thread LoadBothThread = new Thread(delegate () { loadBoth(i, j, villagerData, houseData, msg); }); LoadBothThread.Start(); } private void loadBoth(int i, int j, byte[] villager, byte[] house, string msg) { if (villager.Length != Utilities.VillagerSize) { MessageBox.Show("Villager file size incorrect!", "Villager file invalid"); return; } if (house.Length != Utilities.VillagerHouseSize) { MessageBox.Show("House file size incorrect!", "House file invalid"); return; } showVillagerWait((int)Utilities.VillagerSize * 2 + (int)Utilities.VillagerHouseSize * 2, msg); blocker = true; byte[] modifiedVillager = villager; if (!ignoreHeader.Checked) { if (header[0] != 0x0 && header[1] != 0x0 && header[2] != 0x0) { Buffer.BlockCopy(header, 0x0, modifiedVillager, 0x4, 52); } } V[i].LoadData(modifiedVillager); V[i].AbandonedHouseFlag = Convert.ToInt32(villager[Utilities.VillagerMoveoutOffset]); V[i].ForceMoveOutFlag = Convert.ToInt32(villager[Utilities.VillagerForceMoveoutOffset]); byte[] phrase = new byte[44]; Buffer.BlockCopy(villager, (int)Utilities.VillagerCatchphraseOffset, phrase, 0x0, 44); V[i].catchphrase = phrase; byte[] modifiedHouse = house; byte h = (Byte)i; modifiedHouse[Utilities.VillagerHouseOwnerOffset] = h; V[i].HouseIndex = j; HouseList[j] = i; Utilities.LoadVillager(s, bot, i, modifiedVillager, ref counter); Utilities.LoadHouse(s, bot, j, modifiedHouse, ref counter); this.Invoke((MethodInvoker)delegate { RefreshVillagerUI(false); }); blocker = false; hideVillagerWait(); } private void LockTimer_Tick(object sender, EventArgs e) { if (LockBox.Checked) { try { Utilities.pokeAddress(s, bot, "0x0BA1E858", "3"); } catch { LockBox.Checked = false; } } } private void LockBox_CheckedChanged(object sender, EventArgs e) { Timer LockTimer = new Timer(); if (LockBox.Checked) { LockTimer.Tick += new EventHandler(LockTimer_Tick); LockTimer.Interval = 500; // in miliseconds LockTimer.Start(); } else { LockTimer.Stop(); } } private void cleanVillagerPage() { if (villagerButton != null) { for (int i = 0; i < 10; i++) this.villagerLargePanel.Controls.Remove(villagerButton[i]); } V = null; villagerButton = null; firstload = false; PleaseWaitPanel.Location = new Point(170, 150); } private bool checkDuplicate(string iName) { for (int i = 0; i < 10; i++) { if (V[i].GetInternalName() == iName) return true; } return false; } private bool checkMultipleMoveOut() { /* int num = 0; for (int i = 0; i < 10; i++) { if (V[i].AbandonedHouseFlag == 0x2) num++; } if (num > 0) return true; else */ return false; } private int findEmptyHouse() { for (int i = 0; i < 10; i++) { if (HouseList[i] == 255) return i; } return -1; } private void VillagerSearch_Click(object sender, EventArgs e) { VillagerSearch.Text = ""; VillagerSearch.ForeColor = Color.White; } private void VillagerSearch_Leave(object sender, EventArgs e) { if (VillagerSearch.Text == "") { VillagerSearch.Text = "Search..."; VillagerSearch.ForeColor = Color.FromArgb(255, 114, 118, 125); } } private void VillagerSearch_TextChanged(object sender, EventArgs e) { for (int i = 0; i < ReplaceSelector.Items.Count; i++) { string[] lines = ReplaceSelector.Items[i].ToString().Split(new string[] { " " }, StringSplitOptions.None); //byte[] IName = Encoding.Default.GetBytes(lines[lines.Length - 1]); //string IName = lines[lines.Length - 1]; string RealName = lines[0]; if (VillagerSearch.Text.ToLower() == RealName.ToLower()) { ReplaceSelector.SelectedIndex = i; break; } } } private void IslandSearch_Click(object sender, EventArgs e) { IslandSearch.Text = ""; IslandSearch.ForeColor = Color.White; } private void IslandSearch_Leave(object sender, EventArgs e) { if (IslandSearch.Text == "") { IslandSearch.Text = "Search..."; IslandSearch.ForeColor = Color.FromArgb(255, 114, 118, 125); } } private void IslandSearch_TextChanged(object sender, EventArgs e) { for (int i = 0; i < MysSelector.Items.Count; i++) { string[] lines = MysSelector.Items[i].ToString().Split(new string[] { " " }, StringSplitOptions.None); //byte[] IName = Encoding.Default.GetBytes(lines[lines.Length - 1]); //string IName = lines[lines.Length - 1]; string RealName = lines[0]; if (IslandSearch.Text.ToLower() == RealName.ToLower()) { MysSelector.SelectedIndex = i; break; } } } private void button2_Click(object sender, EventArgs e) { string folderPath = @"villager/"; foreach (string file in Directory.EnumerateFiles(folderPath, "*.nhv")) { byte[] data = File.ReadAllBytes(file); if (data.Length != Utilities.VillagerOldSize) { MessageBox.Show("Villager file size incorrect!", "Villager file invalid"); } else { byte[] newdata = ConvertToNew(data); File.WriteAllBytes(file + "2", newdata); } } } private static byte[] ConvertToNew(byte[] oldVillager) { byte[] newVillager = new byte[Utilities.VillagerSize]; Array.Copy(oldVillager, 0, newVillager, 0, 0x2f84); for (int i = 0; i < 160; i++) { var src = 0x2f84 + (0x14C * i); var dest = 0x2f84 + (0x158 * i); Array.Copy(oldVillager, src, newVillager, dest, 0x14C); } Array.Copy(oldVillager, 0xff04, newVillager, 0x10684, oldVillager.Length - 0xff04); return newVillager; } /* private void loadFriendship(int player) { showVillagerWait(10, "Acquiring Friendship data..."); if ((s == null || s.Connected == false) & bot == null) return; blocker = true; for (int i = 0; i < 10; i++) { //byte[] b = Utilities.GetVillager(s, bot, i, (int)(Utilities.VillagerMemoryTinySize), ref counter); byte[] b = Utilities.GetPlayerDataVillager(s, bot, i, player, (int)(Utilities.VillagerMemoryTinySize), ref counter); V[i].TempData[player] = b; V[i].Friendship[player] = b[70]; } this.Invoke((MethodInvoker)delegate { RefreshVillagerUI(false); }); blocker = false; hideVillagerWait(); } */ public void loadFriendship(byte[] b, int i, int player) { V[i].TempData[player] = b; V[i].Friendship[player] = b[70]; } private bool checkFriendshipInit(int player) { for (int i = 0; i < 10; i++) { if (V[i].Friendship[player] != 0) return true; } return false; } } }
36.512158
218
0.487888
[ "BSD-2-Clause" ]
ye4241/ACNHPoker
acnhpoker/Form1.Villager.cs
48,052
C#
using System; using ChromaWrapper.Keyboard; namespace ChromaWrapper.Sdk { /// <summary> /// Represents a 2-dimensional grid of keyboard LEDs. Implemented by <see cref="IKeyGridEffect"/>.<see cref="IKeyGridEffect.Key"/>. /// </summary> public interface IKeyGrid { /// <summary> /// Gets the number of rows of the grid. /// </summary> int Rows { get; } /// <summary> /// Gets the number of columns of the grid. /// </summary> int Columns { get; } /// <summary> /// Gets the number of LEDs in the grid. /// </summary> int Count { get; } /// <summary> /// Gets or sets the LED color at the specified row and column. /// </summary> /// <param name="row">The LED grid row.</param> /// <param name="column">The LED grid column.</param> /// <returns>The color of the LED, or <see cref="ChromaColor.Transparent"/> if no color has been set.</returns> ChromaKeyColor this[int row, int column] { get; set; } /// <summary> /// Gets or sets the LED color at the specified index. /// </summary> /// <param name="index">The index of the LED.</param> /// <returns>The color of the LED, or <see cref="ChromaColor.Transparent"/> if no color has been set.</returns> ChromaKeyColor this[int index] { get; set; } /// <summary> /// Gets an editable subset of the LED colors in the specified range. /// </summary> /// <param name="range">The range.</param> /// <returns>The subset of LED colors.</returns> Span<ChromaKeyColor> this[Range range] { get; } /// <summary> /// Gets or sets the LED color of the specified key. /// </summary> /// <param name="key">The keyboard key.</param> /// <returns>The color of the LED, or <see cref="ChromaColor.Transparent"/> if no color has been set.</returns> ChromaKeyColor this[KeyboardKey key] { get; set; } /// <summary> /// Sets all LEDs to their default value (no color set). /// </summary> void Clear(); /// <summary> /// Sets all LEDs to the specified color, or clears them. /// </summary> /// <param name="color">To color to set all LEDs to, or <see cref="ChromaColor.Transparent"/> to clear all LEDs.</param> void Fill(ChromaKeyColor color); } }
36.865672
135
0.568016
[ "MIT" ]
poveden/ChromaWrapper
src/Sdk/IKeyGrid.cs
2,472
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace I._02.Hornet_Comm_RegEx { class Program { static void Main(string[] args) { var messagePattern = @"^([0-9]+) <-> ([a-zA-Z0-9]+)$"; var broadcastPattern = @"^([^0-9]+) <-> ([a-zA-Z0-9]+)$"; Regex messageRegex = new Regex(messagePattern); Regex broadcastRegex = new Regex(broadcastPattern); List<string> messages = new List<string>(); List<string> broadcasts = new List<string>(); string inputLine = Console.ReadLine(); while (inputLine != "Hornet is Green") { if (messageRegex.IsMatch(inputLine)) { Match match = messageRegex.Match(inputLine); //NOTICE HOW WE USE THE GROUPS FROM THE REGEX TO EXTRACT THE 2 QUERIES //TAKE THE FIRST QUERY, REVERSE THE STRING => IT TURNS INTO A COLLECTION OF CHARACTER "char" //THEN STRING JOIN IT BY NOTHING "", AND IT TURNS INTO A STRING (CLEVER EYH) string recipientCode = string.Join("", match.Groups[1].Value.Reverse()); string message = match.Groups[2].Value; messages.Add(recipientCode + " -> " + message); } if (broadcastRegex.IsMatch(inputLine)) { Match match = broadcastRegex.Match(inputLine); string message = match.Groups[1].Value; string frequency = DecryptFrequency(match.Groups[2].Value); broadcasts.Add(frequency + " -> " + message); } inputLine = Console.ReadLine(); } //PRINT BROADCASTS Console.WriteLine("Broadcasts:"); if (broadcasts.Count > 0) { Console.WriteLine(string.Join("\n", broadcasts)); } else { Console.WriteLine("None"); } //THE COOL WAY - WITH LINQ AND TERNARY OPERATOR //Console.WriteLine(broadcasts.Any() ? string.Join("\n", broadcasts) : "None"); //PRINT MESSAGES Console.WriteLine("Messages:"); if (messages.Count > 0) { Console.WriteLine(string.Join("\n", messages)); } else { Console.WriteLine("None"); } //THE COOL WAY - WITH LINQ AND TERNARY OPERATOR //Console.WriteLine(messages.Any() ? string.Join("\n", messages) : "None"); } private static string DecryptFrequency(string rightPart) { StringBuilder result = new StringBuilder(); for (int i = 0; i < rightPart.Length; i++) { if (char.IsUpper(rightPart[i])) { result.Append(char.ToLower(rightPart[i])); } else if (char.IsLower(rightPart[i])) { result.Append(char.ToUpper(rightPart[i])); } else { result.Append(rightPart[i]); } } return result.ToString(); } } }
24.009091
97
0.639909
[ "MIT" ]
stanislaviv/Programming-Fundamentals-May-2017
16_ExamPreparations/16_ExamPrep1/I.02. Hornet Comm_RegEx/I.02. Hornet Comm_RegEx.cs
2,643
C#
using System; using System.IO; using System.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Xamarin.MacDev; using Xamarin.MacDev.Tasks; using Xamarin.Utils; namespace Xamarin.iOS.Tasks { public abstract class ValidateAppBundleTaskBase : Task { #region Inputs public string SessionId { get; set; } [Required] public string AppBundlePath { get; set; } [Required] public bool SdkIsSimulator { get; set; } [Required] public string TargetFrameworkIdentifier { get; set; } #endregion public ApplePlatform Framework { get { return PlatformFrameworkHelper.GetFramework (TargetFrameworkIdentifier); } } void ValidateAppExtension (string path, string mainBundleIdentifier, string mainShortVersionString, string mainVersion) { var name = Path.GetFileNameWithoutExtension (path); var info = Path.Combine (path, "Info.plist"); if (!File.Exists (info)) { Log.LogError (7003, path, $"The App Extension '{name}' does not contain an Info.plist."); return; } var plist = PDictionary.FromFile (info); var bundleIdentifier = plist.GetCFBundleIdentifier (); if (string.IsNullOrEmpty (bundleIdentifier)) { Log.LogError (7004, info, $"The App Extension '{name}' does not specify a CFBundleIdentifier."); return; } // The filename of the extension path is the extension's bundle identifier, which turns out ugly // in error messages. Try to get something more friendly-looking. name = plist.GetCFBundleDisplayName () ?? name; var executable = plist.GetCFBundleExecutable (); if (string.IsNullOrEmpty (executable)) Log.LogError (7005, info, $"The App Extension '{name}' does not specify a CFBundleExecutable."); if (!bundleIdentifier.StartsWith (mainBundleIdentifier + ".", StringComparison.Ordinal)) Log.LogError (7006, info, $"The App Extension '{name}' has an invalid CFBundleIdentifier ({bundleIdentifier}), it does not begin with the main app bundle's CFBundleIdentifier ({mainBundleIdentifier})."); if (bundleIdentifier.EndsWith (".key", StringComparison.Ordinal)) Log.LogError (7007, info, $"The App Extension '{name}' has a CFBundleIdentifier ({bundleIdentifier}) that ends with the illegal suffix \".key\"."); var shortVersionString = plist.GetCFBundleShortVersionString (); if (string.IsNullOrEmpty (shortVersionString)) Log.LogError (7008, info, $"The App Extension '{name}' does not specify a CFBundleShortVersionString."); if (shortVersionString != mainShortVersionString) Log.LogWarning ("The App Extension '{0}' has a CFBundleShortVersionString ({1}) that does not match the main app bundle's CFBundleShortVersionString ({2})", name, shortVersionString, mainShortVersionString); var version = plist.GetCFBundleVersion (); if (string.IsNullOrEmpty (version)) Log.LogWarning ("The App Extension '{0}' does not specify a CFBundleVersion", name); if (version != mainVersion) Log.LogWarning ("The App Extension '{0}' has a CFBundleVersion ({1}) that does not match the main app bundle's CFBundleVersion ({2})", name, version, mainVersion); var extension = plist.Get<PDictionary> ("NSExtension"); if (extension == null) { Log.LogError (7009, info, $"The App Extension '{name}' has an invalid Info.plist: it does not contain an NSExtension dictionary."); return; } var extensionPointIdentifier = extension.GetString ("NSExtensionPointIdentifier").Value; if (string.IsNullOrEmpty (extensionPointIdentifier)) { Log.LogError (7010, info, $"The App Extension '{name}' has an invalid Info.plist: the NSExtension dictionary does not contain an NSExtensionPointIdentifier value."); return; } // https://developer.apple.com/library/prerelease/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/SystemExtensionKeys.html#//apple_ref/doc/uid/TP40014212-SW9 switch (extensionPointIdentifier) { case "com.apple.ui-services": // iOS+OSX case "com.apple.services": // iOS case "com.apple.keyboard-service": // iOS case "com.apple.fileprovider-ui": // iOS case "com.apple.fileprovider-nonui": // iOS case "com.apple.FinderSync": // OSX case "com.apple.photo-editing": // iOS case "com.apple.share-services": // iOS+OSX case "com.apple.widget-extension": // iOS+OSX case "com.apple.Safari.content-blocker": // iOS case "com.apple.Safari.sharedlinks-service": // iOS case "com.apple.spotlight.index": // iOS case "com.apple.AudioUnit": // iOS case "com.apple.AudioUnit-UI": // iOS case "com.apple.tv-services": // tvOS case "com.apple.broadcast-services": // iOS+tvOS case "com.apple.callkit.call-directory": // iOS case "com.apple.message-payload-provider": // iOS case "com.apple.intents-service": // iOS case "com.apple.intents-ui-service": // iOS case "com.apple.usernotifications.content-extension": // iOS case "com.apple.usernotifications.service": // iOS case "com.apple.networkextension.packet-tunnel": // iOS+OSX break; case "com.apple.watchkit": // iOS8.2 var attributes = extension.Get<PDictionary> ("NSExtensionAttributes"); if (attributes == null) { Log.LogError (7011, info, $"The WatchKit Extension '{name}' has an invalid Info.plist: the NSExtension dictionary does not contain an NSExtensionAttributes dictionary."); return; } var wkAppBundleIdentifier = attributes.GetString ("WKAppBundleIdentifier").Value; var apps = Directory.GetDirectories (path, "*.app"); if (apps.Length == 0) { Log.LogError (7012, info, $"The WatchKit Extension '{name}' does not contain any watch apps."); } else if (apps.Length > 1) { Log.LogError (7012, info, $"The WatchKit Extension '{name}' contain more than one watch apps."); } else { PObject requiredDeviceCapabilities; if (plist.TryGetValue ("UIRequiredDeviceCapabilities", out requiredDeviceCapabilities)) { var requiredDeviceCapabilitiesDictionary = requiredDeviceCapabilities as PDictionary; var requiredDeviceCapabilitiesArray = requiredDeviceCapabilities as PArray; if (requiredDeviceCapabilitiesDictionary != null) { PBoolean watchCompanion; if (!requiredDeviceCapabilitiesDictionary.TryGetValue ("watch-companion", out watchCompanion) || !watchCompanion.Value) Log.LogError (7013, info, $"The WatchKit Extension '{name}' has an invalid Info.plist: the UIRequiredDeviceCapabilities dictionary must contain the 'watch-companion' capability with a value of 'true'."); } else if (requiredDeviceCapabilitiesArray != null) { if (!requiredDeviceCapabilitiesArray.OfType<PString> ().Any (x => x.Value == "watch-companion")) Log.LogError (7013, info, $"The WatchKit Extension '{name}' has an invalid Info.plist: the UIRequiredDeviceCapabilities array must contain the 'watch-companion' capability."); } else { Log.LogError (7013, info, $"The WatchKit Extension '{name}' has an invalid Info.plist: the UIRequiredDeviceCapabilities key must be present and contain the 'watch-companion' capability."); } } else { Log.LogError (7013, info, $"The WatchKit Extension '{name}' has an invalid Info.plist: the UIRequiredDeviceCapabilities key must be present and contain the 'watch-companion' capability."); } ValidateWatchOS1App (apps[0], name, mainBundleIdentifier, wkAppBundleIdentifier); } break; default: Log.LogWarning ("The App Extension '{0}' has an unrecognized NSExtensionPointIdentifier value ('{1}').", name, extensionPointIdentifier); break; } } void ValidateWatchApp (string path, string mainBundleIdentifier, string mainShortVersionString, string mainVersion) { var name = Path.GetFileNameWithoutExtension (path); var info = Path.Combine (path, "Info.plist"); if (!File.Exists (info)) { Log.LogError (7014, path, $"The Watch App '{name}' does not contain an Info.plist."); return; } var plist = PDictionary.FromFile (info); var bundleIdentifier = plist.GetCFBundleIdentifier (); if (string.IsNullOrEmpty (bundleIdentifier)) { Log.LogError (7015, info, $"The Watch App '{name}' does not specify a CFBundleIdentifier."); return; } if (!bundleIdentifier.StartsWith (mainBundleIdentifier + ".", StringComparison.Ordinal)) Log.LogError (7016, info, $"The Watch App '{name}' has an invalid CFBundleIdentifier ({bundleIdentifier}), it does not begin with the main app bundle's CFBundleIdentifier ({mainBundleIdentifier})."); var shortVersionString = plist.GetCFBundleShortVersionString (); if (string.IsNullOrEmpty (shortVersionString)) Log.LogWarning ("The Watch App '{0}' does not specify a CFBundleShortVersionString", name); if (shortVersionString != mainShortVersionString) Log.LogWarning ("The Watch App '{0}' has a CFBundleShortVersionString ({1}) that does not match the main app bundle's CFBundleShortVersionString ({2})", name, shortVersionString, mainShortVersionString); var version = plist.GetCFBundleVersion (); if (string.IsNullOrEmpty (version)) Log.LogWarning ("The Watch App '{0}' does not specify a CFBundleVersion", name); if (version != mainVersion) Log.LogWarning ("The Watch App '{0}' has a CFBundleVersion ({1}) that does not match the main app bundle's CFBundleVersion ({2})", name, version, mainVersion); var watchDeviceFamily = plist.GetUIDeviceFamily (); if (watchDeviceFamily != IPhoneDeviceType.Watch) Log.LogError (7017, info, $"The Watch App '{name}' does not have a valid UIDeviceFamily value. Expected 'Watch (4)' but found '{watchDeviceFamily.ToString ()} ({(int)watchDeviceFamily})'."); var watchExecutable = plist.GetCFBundleExecutable (); if (string.IsNullOrEmpty (watchExecutable)) Log.LogError (7018, info, $"The Watch App '{name}' does not specify a CFBundleExecutable"); var wkCompanionAppBundleIdentifier = plist.GetString ("WKCompanionAppBundleIdentifier").Value; if (wkCompanionAppBundleIdentifier != mainBundleIdentifier) Log.LogError (7019, info, $"The Watch App '{name}' has an invalid WKCompanionAppBundleIdentifier value ('{wkCompanionAppBundleIdentifier}'), it does not match the main app bundle's CFBundleIdentifier ('{mainBundleIdentifier}')."); PBoolean watchKitApp; if (!plist.TryGetValue ("WKWatchKitApp", out watchKitApp) || !watchKitApp.Value) Log.LogError (7020, info, $"The Watch App '{name}' has an invalid Info.plist: the WKWatchKitApp key must be present and have a value of 'true'."); if (plist.ContainsKey ("LSRequiresIPhoneOS")) Log.LogError (7021, info, $"The Watch App '{name}' has an invalid Info.plist: the LSRequiresIPhoneOS key must not be present."); var pluginsDir = Path.Combine (path, "PlugIns"); if (!Directory.Exists (pluginsDir)) { Log.LogError (7022, path, $"The Watch App '{name}' does not contain any Watch Extensions."); return; } int count = 0; foreach (var plugin in Directory.EnumerateDirectories (pluginsDir, "*.appex")) { ValidateWatchExtension (plugin, bundleIdentifier, shortVersionString, version); count++; } if (count == 0) Log.LogError (7022, pluginsDir, $"The Watch App '{name}' does not contain a Watch Extension."); } void ValidateWatchExtension (string path, string watchAppBundleIdentifier, string mainShortVersionString, string mainVersion) { var name = Path.GetFileNameWithoutExtension (path); var info = Path.Combine (path, "Info.plist"); if (!File.Exists (info)) { Log.LogError (7023, path, $"The Watch Extension '{name}' does not contain an Info.plist."); return; } var plist = PDictionary.FromFile (info); var bundleIdentifier = plist.GetCFBundleIdentifier (); if (string.IsNullOrEmpty (bundleIdentifier)) { Log.LogError (7024, info, $"The Watch Extension '{name}' does not specify a CFBundleIdentifier."); return; } // The filename of the extension path is the extension's bundle identifier, which turns out ugly // in error messages. Try to get something more friendly-looking. name = plist.GetCFBundleDisplayName () ?? name; var executable = plist.GetCFBundleExecutable (); if (string.IsNullOrEmpty (executable)) Log.LogError (7025, info, $"The Watch Extension '{name}' does not specify a CFBundleExecutable."); if (!bundleIdentifier.StartsWith (watchAppBundleIdentifier + ".", StringComparison.Ordinal)) Log.LogError (7026, info, $"The Watch Extension '{name}' has an invalid CFBundleIdentifier ({bundleIdentifier}), it does not begin with the main app bundle's CFBundleIdentifier ({watchAppBundleIdentifier})."); if (bundleIdentifier.EndsWith (".key", StringComparison.Ordinal)) Log.LogError (7027, info, $"The Watch Extension '{name}' has a CFBundleIdentifier ({bundleIdentifier}) that ends with the illegal suffix \".key\"."); var shortVersionString = plist.GetCFBundleShortVersionString (); if (string.IsNullOrEmpty (shortVersionString)) Log.LogWarning ("The Watch Extension '{0}' does not specify a CFBundleShortVersionString", name); if (shortVersionString != mainShortVersionString) Log.LogWarning ("The Watch Extension '{0}' has a CFBundleShortVersionString ({1}) that does not match the main app bundle's CFBundleShortVersionString ({2})", name, shortVersionString, mainShortVersionString); var version = plist.GetCFBundleVersion (); if (string.IsNullOrEmpty (version)) Log.LogWarning ("The Watch Extension '{0}' does not specify a CFBundleVersion", name); if (version != mainVersion) Log.LogWarning ("The Watch Extension '{0}' has a CFBundleVersion ({1}) that does not match the main app bundle's CFBundleVersion ({2})", name, version, mainVersion); var extension = plist.Get<PDictionary> ("NSExtension"); if (extension == null) { Log.LogError (7028, info, $"The Watch Extension '{name}' has an invalid Info.plist: it does not contain an NSExtension dictionary."); return; } var extensionPointIdentifier = extension.Get<PString> ("NSExtensionPointIdentifier"); if (extensionPointIdentifier != null) { if (extensionPointIdentifier.Value != "com.apple.watchkit") Log.LogError (7029, info, $"The Watch Extension '{name}' has an invalid Info.plist: the NSExtensionPointIdentifier must be \"com.apple.watchkit\"."); } else { Log.LogError (7029, info, $"The Watch Extension '{name}' has an invalid Info.plist: the NSExtension dictionary must contain an NSExtensionPointIdentifier."); } PDictionary attributes; if (!extension.TryGetValue ("NSExtensionAttributes", out attributes)) { Log.LogError (7030, info, $"The Watch Extension '{name}' has an invalid Info.plist: the NSExtension dictionary must contain NSExtensionAttributes."); return; } var appBundleIdentifier = attributes.Get<PString> ("WKAppBundleIdentifier"); if (appBundleIdentifier != null) { if (appBundleIdentifier.Value != watchAppBundleIdentifier) Log.LogError (7031, info, $"The Watch Extension '{name}' has an invalid WKAppBundleIdentifier value ('{appBundleIdentifier.Value}'), it does not match the parent Watch App bundle's CFBundleIdentifier ('{watchAppBundleIdentifier}')."); } else { Log.LogError (7031, info, $"The Watch Extension '{name}' has an invalid Info.plist: the NSExtensionAttributes dictionary must contain a WKAppBundleIdentifier."); } PObject requiredDeviceCapabilities; if (plist.TryGetValue ("UIRequiredDeviceCapabilities", out requiredDeviceCapabilities)) { var requiredDeviceCapabilitiesDictionary = requiredDeviceCapabilities as PDictionary; var requiredDeviceCapabilitiesArray = requiredDeviceCapabilities as PArray; if (requiredDeviceCapabilitiesDictionary != null) { PBoolean watchCompanion; if (requiredDeviceCapabilitiesDictionary.TryGetValue ("watch-companion", out watchCompanion)) Log.LogError (7032, info, $"The WatchKit Extension '{name}' has an invalid Info.plist: the UIRequiredDeviceCapabilities dictionary should not contain the 'watch-companion' capability."); } else if (requiredDeviceCapabilitiesArray != null) { if (requiredDeviceCapabilitiesArray.OfType<PString> ().Any (x => x.Value == "watch-companion")) Log.LogError (7032, info, $"The WatchKit Extension '{name}' has an invalid Info.plist: the UIRequiredDeviceCapabilities array should not contain the 'watch-companion' capability."); } } } void ValidateWatchOS1App (string path, string extensionName, string mainBundleIdentifier, string wkAppBundleIdentifier) { var name = Path.GetFileNameWithoutExtension (path); var info = Path.Combine (path, "Info.plist"); if (!File.Exists (info)) { Log.LogError (7033, path, $"The Watch App '{name}' does not contain an Info.plist."); return; } var plist = PDictionary.FromFile (info); var bundleIdentifier = plist.GetCFBundleIdentifier (); if (string.IsNullOrEmpty (bundleIdentifier)) { Log.LogError (7034, info, $"The Watch App '{name}' does not specify a CFBundleIdentifier."); return; } var deviceFamily = plist.GetUIDeviceFamily (); IPhoneDeviceType expectedDeviceFamily; string expectedDeviceFamilyString; if (SdkIsSimulator) { expectedDeviceFamily = IPhoneDeviceType.Watch | IPhoneDeviceType.IPhone; expectedDeviceFamilyString = "IPhone, Watch (1, 4)"; } else { expectedDeviceFamily = IPhoneDeviceType.Watch; expectedDeviceFamilyString = "Watch (4)"; } if (deviceFamily != expectedDeviceFamily) Log.LogError (7035, info, $"The Watch App '{name}' does not have a valid UIDeviceFamily value. Expected '{expectedDeviceFamilyString}' but found '{deviceFamily.ToString ()} ({(int)deviceFamily})'."); var executable = plist.GetCFBundleExecutable (); if (string.IsNullOrEmpty (executable)) Log.LogError (7036, info, $"The Watch App '{name}' does not specify a CFBundleExecutable."); if (bundleIdentifier != wkAppBundleIdentifier) Log.LogError (7037, info, $"The WatchKit Extension '{extensionName}' has an invalid WKAppBundleIdentifier value ('{wkAppBundleIdentifier}'), it does not match the Watch App's CFBundleIdentifier ('{bundleIdentifier}')."); var companionAppBundleIdentifier = plist.Get<PString> ("WKCompanionAppBundleIdentifier"); if (companionAppBundleIdentifier != null) { if (companionAppBundleIdentifier.Value != mainBundleIdentifier) Log.LogError (7038, info, $"The Watch App '{name}' has an invalid WKCompanionAppBundleIdentifier value ('{companionAppBundleIdentifier.Value}'), it does not match the main app bundle's CFBundleIdentifier ('{mainBundleIdentifier}')."); } else { Log.LogError (7038, info, $"The Watch App '{name}' has an invalid Info.plist: the WKCompanionAppBundleIdentifier must exist and must match the main app bundle's CFBundleIdentifier."); } if (plist.ContainsKey ("LSRequiresIPhoneOS")) Log.LogError (7039, info, $"The Watch App '{name}' has an invalid Info.plist: the LSRequiresIPhoneOS key must not be present."); } public override bool Execute () { var mainInfoPath = Path.Combine (AppBundlePath, "Info.plist"); if (!File.Exists (mainInfoPath)) { Log.LogError (7040, AppBundlePath, $"The app bundle {AppBundlePath} does not contain an Info.plist."); return false; } var plist = PDictionary.FromFile (mainInfoPath); var bundleIdentifier = plist.GetCFBundleIdentifier (); if (string.IsNullOrEmpty (bundleIdentifier)) { Log.LogError (7041, mainInfoPath, $"{mainInfoPath} does not specify a CFBundleIdentifier."); return false; } var executable = plist.GetCFBundleExecutable (); if (string.IsNullOrEmpty (executable)) Log.LogError (7042, mainInfoPath, $"{mainInfoPath} does not specify a CFBundleExecutable."); var supportedPlatforms = plist.GetArray (ManifestKeys.CFBundleSupportedPlatforms); var platform = string.Empty; if (supportedPlatforms == null || supportedPlatforms.Count == 0) { Log.LogError (7043, mainInfoPath, $"{mainInfoPath} does not specify a CFBundleSupportedPlatforms."); } else { platform = (PString) supportedPlatforms[0]; } // Validate UIDeviceFamily var deviceTypes = plist.GetUIDeviceFamily (); var deviceFamilies = deviceTypes.ToDeviceFamily (); AppleDeviceFamily[] validFamilies = null; switch (Framework) { case ApplePlatform.iOS: validFamilies = new AppleDeviceFamily[] { AppleDeviceFamily.IPhone, AppleDeviceFamily.IPad, AppleDeviceFamily.Watch }; break; case ApplePlatform.WatchOS: validFamilies = new AppleDeviceFamily[] { AppleDeviceFamily.Watch }; break; case ApplePlatform.TVOS: validFamilies = new AppleDeviceFamily[] { AppleDeviceFamily.TV }; break; default: Log.LogError ("Invalid framework: {0}", Framework); break; } if (validFamilies != null) { if (validFamilies.Length == 0) { Log.LogError (7044, mainInfoPath, $"{mainInfoPath} does not specify a UIDeviceFamily."); } else { foreach (var family in deviceFamilies) { if (Array.IndexOf (validFamilies, family) == -1) { Log.LogError (7044, mainInfoPath, $"{mainInfoPath} is invalid: the UIDeviceFamily key must contain a value for '{family}'."); } } } } var mainShortVersionString = plist.GetCFBundleShortVersionString (); var mainVersion = plist.GetCFBundleVersion (); if (Directory.Exists (Path.Combine (AppBundlePath, "PlugIns"))) { foreach (var plugin in Directory.GetDirectories (Path.Combine (AppBundlePath, "PlugIns"), "*.appex")) ValidateAppExtension (plugin, bundleIdentifier, mainShortVersionString, mainVersion); } if (Directory.Exists (Path.Combine (AppBundlePath, "Watch"))) { foreach (var watchApp in Directory.GetDirectories (Path.Combine (AppBundlePath, "Watch"), "*.app")) ValidateWatchApp (watchApp, bundleIdentifier, mainShortVersionString, mainVersion); } return !Log.HasLoggedErrors; } } }
48.459161
239
0.723715
[ "BSD-3-Clause" ]
silvrwolfboy/xamarin-macios
msbuild/Xamarin.iOS.Tasks.Core/Tasks/ValidateAppBundleTaskBase.cs
21,954
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type InformationProtectionPolicyRequest. /// </summary> public partial class InformationProtectionPolicyRequest : BaseRequest, IInformationProtectionPolicyRequest { /// <summary> /// Constructs a new InformationProtectionPolicyRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public InformationProtectionPolicyRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified InformationProtectionPolicy using POST. /// </summary> /// <param name="informationProtectionPolicyToCreate">The InformationProtectionPolicy to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created InformationProtectionPolicy.</returns> public async System.Threading.Tasks.Task<InformationProtectionPolicy> CreateAsync(InformationProtectionPolicy informationProtectionPolicyToCreate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.POST; var newEntity = await this.SendAsync<InformationProtectionPolicy>(informationProtectionPolicyToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Creates the specified InformationProtectionPolicy using POST and returns a <see cref="GraphResponse{InformationProtectionPolicy}"/> object. /// </summary> /// <param name="informationProtectionPolicyToCreate">The InformationProtectionPolicy to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{InformationProtectionPolicy}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<InformationProtectionPolicy>> CreateResponseAsync(InformationProtectionPolicy informationProtectionPolicyToCreate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.POST; return this.SendAsyncWithGraphResponse<InformationProtectionPolicy>(informationProtectionPolicyToCreate, cancellationToken); } /// <summary> /// Deletes the specified InformationProtectionPolicy. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.DELETE; await this.SendAsync<InformationProtectionPolicy>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes the specified InformationProtectionPolicy and returns a <see cref="GraphResponse"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task of <see cref="GraphResponse"/> to await.</returns> public System.Threading.Tasks.Task<GraphResponse> DeleteResponseAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.DELETE; return this.SendAsyncWithGraphResponse(null, cancellationToken); } /// <summary> /// Gets the specified InformationProtectionPolicy. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The InformationProtectionPolicy.</returns> public async System.Threading.Tasks.Task<InformationProtectionPolicy> GetAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.GET; var retrievedEntity = await this.SendAsync<InformationProtectionPolicy>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Gets the specified InformationProtectionPolicy and returns a <see cref="GraphResponse{InformationProtectionPolicy}"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{InformationProtectionPolicy}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<InformationProtectionPolicy>> GetResponseAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.GET; return this.SendAsyncWithGraphResponse<InformationProtectionPolicy>(null, cancellationToken); } /// <summary> /// Updates the specified InformationProtectionPolicy using PATCH. /// </summary> /// <param name="informationProtectionPolicyToUpdate">The InformationProtectionPolicy to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The updated InformationProtectionPolicy.</returns> public async System.Threading.Tasks.Task<InformationProtectionPolicy> UpdateAsync(InformationProtectionPolicy informationProtectionPolicyToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PATCH; var updatedEntity = await this.SendAsync<InformationProtectionPolicy>(informationProtectionPolicyToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Updates the specified InformationProtectionPolicy using PATCH and returns a <see cref="GraphResponse{InformationProtectionPolicy}"/> object. /// </summary> /// <param name="informationProtectionPolicyToUpdate">The InformationProtectionPolicy to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The <see cref="GraphResponse{InformationProtectionPolicy}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<InformationProtectionPolicy>> UpdateResponseAsync(InformationProtectionPolicy informationProtectionPolicyToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PATCH; return this.SendAsyncWithGraphResponse<InformationProtectionPolicy>(informationProtectionPolicyToUpdate, cancellationToken); } /// <summary> /// Updates the specified InformationProtectionPolicy using PUT. /// </summary> /// <param name="informationProtectionPolicyToUpdate">The InformationProtectionPolicy object to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task<InformationProtectionPolicy> PutAsync(InformationProtectionPolicy informationProtectionPolicyToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PUT; var updatedEntity = await this.SendAsync<InformationProtectionPolicy>(informationProtectionPolicyToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Updates the specified InformationProtectionPolicy using PUT and returns a <see cref="GraphResponse{InformationProtectionPolicy}"/> object. /// </summary> /// <param name="informationProtectionPolicyToUpdate">The InformationProtectionPolicy object to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await of <see cref="GraphResponse{InformationProtectionPolicy}"/>.</returns> public System.Threading.Tasks.Task<GraphResponse<InformationProtectionPolicy>> PutResponseAsync(InformationProtectionPolicy informationProtectionPolicyToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PUT; return this.SendAsyncWithGraphResponse<InformationProtectionPolicy>(informationProtectionPolicyToUpdate, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IInformationProtectionPolicyRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IInformationProtectionPolicyRequest Expand(Expression<Func<InformationProtectionPolicy, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IInformationProtectionPolicyRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IInformationProtectionPolicyRequest Select(Expression<Func<InformationProtectionPolicy, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="informationProtectionPolicyToInitialize">The <see cref="InformationProtectionPolicy"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(InformationProtectionPolicy informationProtectionPolicyToInitialize) { if (informationProtectionPolicyToInitialize != null) { if (informationProtectionPolicyToInitialize.Labels != null && informationProtectionPolicyToInitialize.Labels.CurrentPage != null) { informationProtectionPolicyToInitialize.Labels.InitializeNextPageRequest(this.Client, informationProtectionPolicyToInitialize.LabelsNextLink); // Copy the additional data collection to the page itself so that information is not lost informationProtectionPolicyToInitialize.Labels.AdditionalData = informationProtectionPolicyToInitialize.AdditionalData; } } } } }
54.851145
218
0.673996
[ "MIT" ]
ScriptBox99/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/InformationProtectionPolicyRequest.cs
14,371
C#
using System; using System.Collections.Generic; using System.ComponentModel; using UnityEngine; namespace UnityEditor.Recorder.Input { /// <summary> /// Sets which level of multisample anti-aliasing (MSAA) to use for the capture. /// </summary> public enum SuperSamplingCount { /// <summary> /// MSAA level 1 /// </summary> X1 = 1, /// <summary> /// MSAA level 2 /// </summary> X2 = 2, /// <summary> /// MSAA level 4 /// </summary> X4 = 4, /// <summary> /// MSAA level 8 /// </summary> X8 = 8, /// <summary> /// MSAA level 16 /// </summary> X16 = 16, } [DisplayName("Texture Sampling")] [Serializable] public class RenderTextureSamplerSettings : ImageInputSettings { [SerializeField] internal ImageSource source = ImageSource.ActiveCamera; [SerializeField] int m_RenderWidth = 1280; [SerializeField] int m_RenderHeight = (int)ImageHeight.x720p_HD; [SerializeField] int m_OutputWidth = 1280; [SerializeField] int m_OutputHeight = (int)ImageHeight.x720p_HD; [SerializeField] internal AspectRatio outputAspectRatio = new AspectRatio(); /// <summary> /// Indicates the multisample anti-aliasing (MSAA) level used for this Recorder input. /// </summary> public SuperSamplingCount SuperSampling { get { return superSampling; } set { superSampling = value; } } [SerializeField] SuperSamplingCount superSampling = SuperSamplingCount.X1; [SerializeField]internal float superKernelPower = 16f; [SerializeField]internal float superKernelScale = 1f; /// <summary> /// Stores the GameObject tag that defines the Camera used for the recording. /// </summary> public string CameraTag { get => cameraTag; set => cameraTag = value; } [SerializeField] string cameraTag; /// <summary> /// Indicates the color space used for this Recorder input. /// </summary> public ColorSpace ColorSpace { get { return colorSpace; } set { colorSpace = value; } } [SerializeField] ColorSpace colorSpace = ColorSpace.Gamma; /// <summary> /// Use this property if you need to vertically flip the final output. /// </summary> public bool FlipFinalOutput { get { return flipFinalOutput; } set { flipFinalOutput = value; } } [SerializeField] bool flipFinalOutput; internal readonly int kMaxSupportedSize = (int)ImageHeight.x2160p_4K; /// <inheritdoc/> protected internal override Type InputType { get { return typeof(RenderTextureSampler); } } /// <inheritdoc/> protected internal override bool ValidityCheck(List<string> errors) { var ok = true; var h = OutputHeight; if (h > kMaxSupportedSize) { ok = false; errors.Add("Output size exceeds maximum supported size: " + kMaxSupportedSize); } return ok; } /// <inheritdoc/> public override int OutputWidth { get { return m_OutputWidth; } set { m_OutputWidth = Mathf.Min(16 * 1024, value); } } /// <inheritdoc/> public override int OutputHeight { get { return m_OutputHeight; } set { m_OutputHeight = value; } } /// <summary> /// Use this property to specify a different render width from the output (overscan). /// </summary> public int RenderWidth { get { return m_RenderWidth; } set { m_RenderWidth = value; } } /// <summary> /// Use this property to specify a different render height from the output (overscan). /// </summary> public int RenderHeight { get { return m_RenderHeight; } set { m_RenderHeight = value; } } } }
28.959459
95
0.55273
[ "MIT" ]
AbelEnklaar/BehaviourExperiments
Boids 3D/Library/PackageCache/com.unity.recorder@2.2.0-preview.4/Editor/Sources/Recorders/_Inputs/RenderTextureSampler/RenderTextureSamplerSettings.cs
4,288
C#
using ACQREditor.Class; using ACQREditor.Models; using System.Text; using Xamarin.Essentials; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace ACQREditor.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SavePage : ContentPage { public SavePage(DesignInfo design) { InitializeComponent(); var writer = new QRWriter(); QRCode.BarcodeOptions.Width = (int)DeviceDisplay.MainDisplayInfo.Width; QRCode.BarcodeOptions.Height = (int)DeviceDisplay.MainDisplayInfo.Width; QRCode.BarcodeOptions.PureBarcode = true; //ISO-8859-1 ???? QRCode.BarcodeValue = Encoding.GetEncoding("ISO-8859-1").GetString(writer.Write(design)); } } }
29.037037
101
0.672194
[ "MIT" ]
santerinogelainen/ACQREditor
ACQREditor/ACQREditor/Views/SavePage.xaml.cs
786
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using static UnityEngine.InputSystem.InputAction; /// <summary> /// All input for the project should pass through here /// </summary> public class InputManager : MonoBehaviour { [SerializeField] public Action<Vector3> OnCameraPan; public Action<float> OnCameraRotation; public Action<float> OnCameraZoom; // Keyboard Actions public Action<int> OnNumberPressed; public Action<Key> OnMenuKeyPress; public Action OnCPressed; public Action OnTabPressed; public Action OnPlaceTile; public Action OnEndPlaceTile; private bool isMoving = false; private bool isPanDisabled; private bool isRotationDisabled; private bool isZoomDisabled; private bool isInTopDown; Vector3 moveBy; private void Update() { if (isMoving == true && !UIManager.DashboardMode) { if (!isPanDisabled && !isInTopDown) OnCameraPan.Invoke(moveBy); } } public void OnPlace(CallbackContext context) { if (UIManager.DashboardMode) return; if (context.started) OnPlaceTile?.Invoke(); else if (context.performed) OnEndPlaceTile?.Invoke(); } public void OnMouseMovement(CallbackContext context) { if (UIManager.DashboardMode) return; Vector2 mousePosition = context.ReadValue<Vector2>(); float xUpperBound = Screen.width - Config.boundaryFraction * Screen.width; float xLowerBound = Config.boundaryFraction * Screen.width; float yUpperBound = Screen.height - Config.boundaryFraction * Screen.height; float yLowerBound = Config.boundaryFraction * Screen.height; Vector3 movementDelta = Vector3.zero; if (mousePosition.x > xUpperBound) { movementDelta.x = (mousePosition.x - xUpperBound) / xLowerBound; } else if (mousePosition.x < xLowerBound) { movementDelta.x = -(xLowerBound - mousePosition.x) / xLowerBound; } if (mousePosition.y > yUpperBound) { movementDelta.z = (mousePosition.y - yUpperBound) / yLowerBound; } else if (mousePosition.y < yLowerBound) { movementDelta.z = -(yLowerBound - mousePosition.y) / yLowerBound; } if (movementDelta != Vector3.zero) { isMoving = true; if (movementDelta.x != 0 && movementDelta.z != 0) { moveBy = new Vector3(Mathf.Clamp(movementDelta.x, -.71f, .71f), 0, Mathf.Clamp(movementDelta.z, -.71f, .71f)); } else { moveBy = movementDelta; } } else { isMoving = false; } } public void OnRotation(CallbackContext context) { if (UIManager.DashboardMode) return; if (!isRotationDisabled) { float direciton = context.ReadValue<float>(); OnCameraRotation?.Invoke(direciton); } } public void OnZoom(CallbackContext context) { if (UIManager.DashboardMode) return; if (!isZoomDisabled) { Vector2 zoom = context.ReadValue<Vector2>(); OnCameraZoom?.Invoke(zoom.y / 3); } } public void OnNumberKeyPressed(CallbackContext context) { if (UIManager.DashboardMode) return; if (context.started) { OnNumberPressed?.Invoke(((KeyControl)context.control).keyCode - UnityEngine.InputSystem.Key.Digit1); } } public void OnMenuKeyPressed(CallbackContext context) { if (context.started) { KeyControl control = (KeyControl)context.control; OnMenuKeyPress?.Invoke(control.keyCode); } } public void OnCKeyPressed(CallbackContext context) { if (UIManager.DashboardMode) return; if (context.started) { OnCPressed?.Invoke(); } } public void OnTabKeyPressed(CallbackContext context) { if (UIManager.DashboardMode) return; if (context.started) { OnTabPressed?.Invoke(); } } // Used as an event handler in Game manager. This way UI manager can talk to this manager public void DisableCameraPan(bool active) { isPanDisabled = active; } public void SetTopDownMode(bool active) { isInTopDown = active; } public void DisableCameraRotation(bool active) { isRotationDisabled = active; } public void DisableCameraZoom(bool active) { isZoomDisabled = active; } }
27.716763
126
0.613556
[ "MIT" ]
Jaren-Taylor/Smart-City-Dashboard
Smart City Dashboard/Assets/Scripts/Inputs/InputManager.cs
4,795
C#
using System; using Data.Entities.Common.LocalBase; namespace Data.Sources.LocalStorage.Sqlite.Context { public class SqliteIssue { public int Id { get; set; } public string Head { get; set; } public string Body { get; set; } public int? RowId { get; set; } public RowInfo Row { get; set; } public int? ColumnId { get; set; } public ColumnInfo Column { get; set; } public string Color { get; set; } public DateTime Created { get; set; } public DateTime Modified { get; set; } } }
25.086957
50
0.592721
[ "MIT" ]
LavrentyAfanasiev/Kanban.Desktop
Kanban.Desktop/Data.Sources.LocalStorage.Sqlite/Context/SqliteIssue.cs
579
C#
using Bhp.Cryptography.ECC; using Bhp.SmartContract; using Bhp.Wallets; using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace Bhp.UI { internal partial class CreateMultiSigContractDialog : Form { private ECPoint[] publicKeys; public CreateMultiSigContractDialog() { InitializeComponent(); } public Contract GetContract() { publicKeys = listBox1.Items.OfType<string>().Select(p => ECPoint.DecodePoint(p.HexToBytes(), ECCurve.Secp256r1)).ToArray(); return Contract.CreateMultiSigContract((int)numericUpDown2.Value, publicKeys); } public KeyPair GetKey() { HashSet<ECPoint> hashSet = new HashSet<ECPoint>(publicKeys); return Program.CurrentWallet.GetAccounts().FirstOrDefault(p => p.HasKey && hashSet.Contains(p.GetKey().PublicKey))?.GetKey(); } private void numericUpDown2_ValueChanged(object sender, EventArgs e) { button6.Enabled = numericUpDown2.Value > 0; } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { button5.Enabled = listBox1.SelectedIndices.Count > 0; } private void textBox5_TextChanged(object sender, EventArgs e) { button4.Enabled = textBox5.TextLength > 0; } private void button4_Click(object sender, EventArgs e) { listBox1.Items.Add(textBox5.Text); textBox5.Clear(); numericUpDown2.Maximum = listBox1.Items.Count; } private void button5_Click(object sender, EventArgs e) { listBox1.Items.RemoveAt(listBox1.SelectedIndex); numericUpDown2.Maximum = listBox1.Items.Count; } } }
30.245902
137
0.633062
[ "MIT" ]
BHPCash/bhp-gui
bhp-gui/UI/CreateMultiSigContractDialog.cs
1,847
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; using SBAdmin.Web.Data; namespace SBAdmin.Web.Migrations { [DbContext(typeof(AppDbContext))] partial class AppDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .UseIdentityByDefaultColumns() .HasAnnotation("Relational:MaxIdentifierLength", 63) .HasAnnotation("ProductVersion", "5.0.2"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("text"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("text"); b.Property<string>("Name") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<string>("NormalizedName") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasDatabaseName("RoleNameIndex"); b.ToTable("AspNetRoles"); b.HasData( new { Id = "716289aa-98e0-4355-ad28-5b2a44409523", ConcurrencyStamp = "6bf8bf61-b168-4d7a-b5ec-920ef4e87959", Name = "Admin", NormalizedName = "ADMIN" }, new { Id = "c45f45b0-8a11-416f-a136-b372d4b366b0", ConcurrencyStamp = "37dbec96-8489-480d-9bb0-68b7491a810c", Name = "User", NormalizedName = "USER" }); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .UseIdentityByDefaultColumn(); b.Property<string>("ClaimType") .HasColumnType("text"); b.Property<string>("ClaimValue") .HasColumnType("text"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .UseIdentityByDefaultColumn(); b.Property<string>("ClaimType") .HasColumnType("text"); b.Property<string>("ClaimValue") .HasColumnType("text"); b.Property<string>("UserId") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("text"); b.Property<string>("ProviderKey") .HasColumnType("text"); b.Property<string>("ProviderDisplayName") .HasColumnType("text"); b.Property<string>("UserId") .IsRequired() .HasColumnType("text"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("text"); b.Property<string>("RoleId") .HasColumnType("text"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("text"); b.Property<string>("LoginProvider") .HasColumnType("text"); b.Property<string>("Name") .HasColumnType("text"); b.Property<string>("Value") .HasColumnType("text"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("SBAdmin.Web.Models.User", b => { b.Property<string>("Id") .HasColumnType("text"); b.Property<int>("AccessFailedCount") .HasColumnType("integer"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("text"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<bool>("EmailConfirmed") .HasColumnType("boolean"); b.Property<string>("FirstName") .IsRequired() .HasMaxLength(25) .HasColumnType("character varying(25)"); b.Property<string>("LastName") .IsRequired() .HasMaxLength(25) .HasColumnType("character varying(25)"); b.Property<bool>("LockoutEnabled") .HasColumnType("boolean"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("timestamp with time zone"); b.Property<string>("NormalizedEmail") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<string>("NormalizedUserName") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<string>("PasswordHash") .HasColumnType("text"); b.Property<string>("PhoneNumber") .HasColumnType("text"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("boolean"); b.Property<string>("SecurityStamp") .HasColumnType("text"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("boolean"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasDatabaseName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasDatabaseName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("SBAdmin.Web.Models.User", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("SBAdmin.Web.Models.User", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("SBAdmin.Web.Models.User", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("SBAdmin.Web.Models.User", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
36.402027
95
0.442599
[ "MIT" ]
YuraMishin/SBAdmin
src/SBAdmin.Web/Migrations/AppDbContextModelSnapshot.cs
10,777
C#
#region License /*---------------------------------------------------------------------------------*\ Distributed under the terms of an MIT-style license: The MIT License Copyright (c) 2006-2010 Stephen M. McKamey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*---------------------------------------------------------------------------------*/ #endregion License using System; using System.Collections.Generic; using System.Globalization; using System.IO; using JsonFx.Model; using JsonFx.Serialization; using JsonFx.Utils; namespace JsonFx.Json { public partial class JsonWriter { #region Constants private const string ErrorUnexpectedToken = "Unexpected token ({0})"; #endregion Constants /// <summary> /// Outputs JSON text from an input stream of tokens /// </summary> public class JsonFormatter : ITextFormatter<ModelTokenType> { #region Constants #if WINDOWS_PHONE private static readonly JsonFx.CodeGen.ProxyDelegate EnumGetValues = JsonFx.CodeGen.DynamicMethodGenerator.GetMethodProxy(typeof(Enum), "GetValues"); #elif SILVERLIGHT private static readonly JsonFx.CodeGen.ProxyDelegate EnumGetValues = JsonFx.CodeGen.DynamicMethodGenerator.GetMethodProxy(typeof(Enum), "InternalGetValues"); #endif #endregion Constants #region Fields private readonly DataWriterSettings Settings; // TODO: find a way to generalize this setting private bool encodeLessThan; #endregion Fields #region Init /// <summary> /// Ctor /// </summary> /// <param name="settings"></param> public JsonFormatter(DataWriterSettings settings) { if (settings == null) { throw new ArgumentNullException("settings"); } this.Settings = settings; } #endregion Init #region Properties /// <summary> /// Gets and sets if '&lt;' should be encoded in strings /// Useful for when emitting directly into page /// </summary> public bool EncodeLessThan { get { return this.encodeLessThan; } set { this.encodeLessThan = value; } } #endregion Properties #region ITextFormatter<T> Methods /// <summary> /// Formats the token sequence as a string /// </summary> /// <param name="tokens"></param> public string Format(IEnumerable<Token<ModelTokenType>> tokens) { using (StringWriter writer = new StringWriter()) { this.Format(tokens, writer); return writer.GetStringBuilder().ToString(); } } /// <summary> /// Formats the token sequence to the writer /// </summary> /// <param name="writer"></param> /// <param name="tokens"></param> public void Format(IEnumerable<Token<ModelTokenType>> tokens, TextWriter writer) { if (tokens == null) { throw new ArgumentNullException("tokens"); } bool prettyPrint = this.Settings.PrettyPrint; // allows us to keep basic context without resorting to a push-down automata bool pendingNewLine = false; bool needsValueDelim = false; int depth = 0; foreach (Token<ModelTokenType> token in tokens) { switch (token.TokenType) { case ModelTokenType.ArrayBegin: { if (needsValueDelim) { writer.Write(JsonGrammar.OperatorValueDelim); if (prettyPrint) { this.WriteLine(writer, depth); } } if (pendingNewLine) { if (prettyPrint) { this.WriteLine(writer, ++depth); } pendingNewLine = false; } writer.Write(JsonGrammar.OperatorArrayBegin); pendingNewLine = true; needsValueDelim = false; continue; } case ModelTokenType.ArrayEnd: { if (pendingNewLine) { pendingNewLine = false; } else if (prettyPrint) { this.WriteLine(writer, --depth); } writer.Write(JsonGrammar.OperatorArrayEnd); needsValueDelim = true; continue; } case ModelTokenType.Primitive: { if (needsValueDelim) { writer.Write(JsonGrammar.OperatorValueDelim); if (prettyPrint) { this.WriteLine(writer, depth); } } if (pendingNewLine) { if (prettyPrint) { this.WriteLine(writer, ++depth); } pendingNewLine = false; } Type valueType = (token.Value == null) ? null : token.Value.GetType(); TypeCode typeCode = Type.GetTypeCode(valueType); switch (typeCode) { case TypeCode.Boolean: { writer.Write(true.Equals(token.Value) ? JsonGrammar.KeywordTrue : JsonGrammar.KeywordFalse); break; } case TypeCode.Byte: case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.SByte: case TypeCode.Single: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: { if (valueType.IsEnum) { goto default; } this.WriteNumber(writer, token.Value, typeCode); break; } case TypeCode.DBNull: case TypeCode.Empty: { writer.Write(JsonGrammar.KeywordNull); break; } default: { ITextFormattable<ModelTokenType> formattable = token.Value as ITextFormattable<ModelTokenType>; if (formattable != null) { formattable.Format(this, writer); break; } this.WritePrimitive(writer, token.Value); break; } } needsValueDelim = true; continue; } case ModelTokenType.ObjectBegin: { if (needsValueDelim) { writer.Write(JsonGrammar.OperatorValueDelim); if (prettyPrint) { this.WriteLine(writer, depth); } } if (pendingNewLine) { if (prettyPrint) { this.WriteLine(writer, ++depth); } pendingNewLine = false; } writer.Write(JsonGrammar.OperatorObjectBegin); pendingNewLine = true; needsValueDelim = false; continue; } case ModelTokenType.ObjectEnd: { if (pendingNewLine) { pendingNewLine = false; } else if (prettyPrint) { this.WriteLine(writer, --depth); } writer.Write(JsonGrammar.OperatorObjectEnd); needsValueDelim = true; continue; } case ModelTokenType.Property: { if (needsValueDelim) { writer.Write(JsonGrammar.OperatorValueDelim); if (prettyPrint) { this.WriteLine(writer, depth); } } if (pendingNewLine) { if (prettyPrint) { this.WriteLine(writer, ++depth); } pendingNewLine = false; } this.WritePropertyName(writer, token.Name.LocalName); if (prettyPrint) { writer.Write(" "); writer.Write(JsonGrammar.OperatorPairDelim); writer.Write(" "); } else { writer.Write(JsonGrammar.OperatorPairDelim); } needsValueDelim = false; continue; } case ModelTokenType.None: default: { throw new TokenException<ModelTokenType>( token, String.Format(ErrorUnexpectedToken, token.TokenType)); } } } } #endregion ITextFormatter<T> Methods #region Write Methods protected virtual void WritePrimitive(TextWriter writer, object value) { if (value is TimeSpan) { this.WriteNumber(writer, ((TimeSpan)value).Ticks, TypeCode.Int64); return; } this.WriteString(writer, this.FormatString(value)); } protected virtual void WritePropertyName(TextWriter writer, string propertyName) { this.WriteString(writer, this.FormatString(propertyName)); } protected virtual void WriteNumber(TextWriter writer, object value, TypeCode typeCode) { bool overflowsIEEE754 = false; string number; switch (typeCode) { case TypeCode.Byte: { number = ((byte)value).ToString("g", CultureInfo.InvariantCulture); break; } case TypeCode.Boolean: { number = true.Equals(value) ? "1" : "0"; break; } case TypeCode.Decimal: { overflowsIEEE754 = true; number = ((decimal)value).ToString("g", CultureInfo.InvariantCulture); break; } case TypeCode.Double: { double doubleValue = (double)value; if (Double.IsNaN(doubleValue)) { this.WriteNaN(writer); return; } if (Double.IsInfinity(doubleValue)) { if (Double.IsNegativeInfinity(doubleValue)) { this.WriteNegativeInfinity(writer); } else { this.WritePositiveInfinity(writer); } return; } // round-trip format has a few more digits than general // http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#RFormatString number = doubleValue.ToString("r", CultureInfo.InvariantCulture); break; } case TypeCode.Int16: { number = ((short)value).ToString("g", CultureInfo.InvariantCulture); break; } case TypeCode.Int32: { number = ((int)value).ToString("g", CultureInfo.InvariantCulture); break; } case TypeCode.Int64: { overflowsIEEE754 = true; number = ((long)value).ToString("g", CultureInfo.InvariantCulture); break; } case TypeCode.SByte: { number = ((sbyte)value).ToString("g", CultureInfo.InvariantCulture); break; } case TypeCode.Single: { float floatValue = (float)value; if (Single.IsNaN(floatValue)) { this.WriteNaN(writer); return; } if (Single.IsInfinity(floatValue)) { if (Single.IsNegativeInfinity(floatValue)) { this.WriteNegativeInfinity(writer); } else { this.WritePositiveInfinity(writer); } return; } // round-trip format has a few more digits than general // http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#RFormatString number = floatValue.ToString("r", CultureInfo.InvariantCulture); break; } case TypeCode.UInt16: { number = ((ushort)value).ToString("g", CultureInfo.InvariantCulture); break; } case TypeCode.UInt32: { overflowsIEEE754 = true; number = ((uint)value).ToString("g", CultureInfo.InvariantCulture); break; } case TypeCode.UInt64: { overflowsIEEE754 = true; number = ((ulong)value).ToString("g", CultureInfo.InvariantCulture); break; } default: { throw new TokenException<ModelTokenType>(ModelGrammar.TokenPrimitive(value), "Invalid number token"); } } if (overflowsIEEE754 && this.InvalidIEEE754(Convert.ToDecimal(value))) { // checks for IEEE-754 overflow and emit as strings this.WriteString(writer, number); } else { // fits within an IEEE-754 floating point so emit directly writer.Write(number); } } protected virtual void WriteNegativeInfinity(TextWriter writer) { writer.Write(JsonGrammar.KeywordNull); } protected virtual void WritePositiveInfinity(TextWriter writer) { writer.Write(JsonGrammar.KeywordNull); } protected virtual void WriteNaN(TextWriter writer) { writer.Write(JsonGrammar.KeywordNull); } protected virtual void WriteString(TextWriter writer, string value) { int start = 0, length = value.Length; writer.Write(JsonGrammar.OperatorStringDelim); for (int i=start; i<length; i++) { char ch = value[i]; if (ch <= '\u001F' || ch >= '\u007F' || (this.encodeLessThan && ch == '<') || // improves compatibility within script blocks ch == JsonGrammar.OperatorStringDelim || ch == JsonGrammar.OperatorCharEscape) { if (i > start) { writer.Write(value.Substring(start, i-start)); } start = i+1; switch (ch) { case JsonGrammar.OperatorStringDelim: case JsonGrammar.OperatorCharEscape: { writer.Write(JsonGrammar.OperatorCharEscape); writer.Write(ch); continue; } case '\b': { writer.Write("\\b"); continue; } case '\f': { writer.Write("\\f"); continue; } case '\n': { writer.Write("\\n"); continue; } case '\r': { writer.Write("\\r"); continue; } case '\t': { writer.Write("\\t"); continue; } default: { writer.Write("\\u"); writer.Write(CharUtility.ConvertToUtf32(value, i).ToString("X4")); continue; } } } } if (length > start) { writer.Write(value.Substring(start, length-start)); } writer.Write(JsonGrammar.OperatorStringDelim); } private void WriteLine(TextWriter writer, int depth) { // emit CRLF writer.Write(this.Settings.NewLine); for (int i=0; i<depth; i++) { // indent next line accordingly writer.Write(this.Settings.Tab); } } #endregion Write Methods #region String Methods /// <summary> /// Converts an object to its string representation /// </summary> /// <param name="value"></param> /// <returns></returns> protected virtual string FormatString(object value) { if (value is Enum) { return this.FormatEnum((Enum)value); } return Token<ModelTokenType>.ToString(value); } #endregion String Methods #region Enum Methods /// <summary> /// Converts an enum to its string representation /// </summary> /// <param name="value"></param> /// <returns></returns> private string FormatEnum(Enum value) { Type type = value.GetType(); IDictionary<Enum, string> map = this.Settings.Resolver.LoadEnumMaps(type); string enumName; if (type.IsDefined(typeof(FlagsAttribute), true) && !Enum.IsDefined(type, value)) { Enum[] flags = JsonFormatter.GetFlagList(type, value); string[] flagNames = new string[flags.Length]; for (int i=0; i<flags.Length; i++) { if (!map.TryGetValue(flags[i], out flagNames[i]) || String.IsNullOrEmpty(flagNames[i])) { flagNames[i] = flags[i].ToString("f"); } } enumName = String.Join(", ", flagNames); } else { if (!map.TryGetValue(value, out enumName) || String.IsNullOrEmpty(enumName)) { enumName = value.ToString("f"); } } return enumName; } /// <summary> /// Splits a bitwise-OR'd set of enums into a list. /// </summary> /// <param name="enumType">the enum type</param> /// <param name="value">the combined value</param> /// <returns>list of flag enums</returns> /// <remarks> /// from PseudoCode.EnumHelper /// </remarks> private static Enum[] GetFlagList(Type enumType, object value) { ulong longVal = Convert.ToUInt64(value); #if SILVERLIGHT ulong[] enumValues = (ulong[])JsonFormatter.EnumGetValues(enumType); #else Array enumValues = Enum.GetValues(enumType); #endif List<Enum> enums = new List<Enum>(enumValues.Length); // check for empty if (longVal == 0L) { // Return the value of empty, or zero if none exists enums.Add((Enum)Convert.ChangeType(value, enumType, CultureInfo.InvariantCulture)); return enums.ToArray(); } for (int i = enumValues.Length-1; i >= 0; i--) { ulong enumValue = Convert.ToUInt64(enumValues.GetValue(i)); if ((i == 0) && (enumValue == 0L)) { continue; } // matches a value in enumeration if ((longVal & enumValue) == enumValue) { // remove from val longVal -= enumValue; // add enum to list enums.Add(enumValues.GetValue(i) as Enum); } } if (longVal != 0x0L) { enums.Add(Enum.ToObject(enumType, longVal) as Enum); } return enums.ToArray(); } #endregion Enum Methods #region Number Methods /// <summary> /// Determines if a numeric value cannot be represented as IEEE-754. /// </summary> /// <param name="value"></param> /// <returns></returns> /// <remarks> /// http://stackoverflow.com/questions/1601646 /// </remarks> protected virtual bool InvalidIEEE754(decimal value) { try { return (decimal)(Decimal.ToDouble(value)) != value; } catch { return true; } } #endregion Number Methods } } }
24.175202
160
0.597558
[ "MIT" ]
Ciastex/Distance-Server
ServerUnity/Assets/Plugins/JsonFx/Json/JsonFormatter.cs
17,938
C#
using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms; namespace XFFurniture.Models { public class MenuApp { public string MenuTitle { get; set; } public string MenuDetail { get; set; } public ImageSource icon { get; set; } public Page Page { get; set; } } }
14.705882
33
0.436
[ "MIT" ]
joseluishl123/Ordenes
XFFurniture/XFFurniture/Models/MenuApp.cs
502
C#
#nullable enable namespace System.Linq { // TODO: Consider to rename to OptionalLinqDictionaryExtensions in v2.0 public static partial class OptionalLinqDictionariesExtensions { } }
20
75
0.75
[ "MIT" ]
pfpack/pfpack-core
src/core-taggeds-optional/Optional/Optional.T.Linq.Dictionaries/Extensions.cs
202
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("ThrottlingDemo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ThrottlingDemo")] [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("9b2fb317-112f-4e8a-b2ec-690036cda41b")] // 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.864865
84
0.745896
[ "MIT" ]
philiplaureano/AkkaDotNetThrottlingDemo
ThrottlingDemo/Properties/AssemblyInfo.cs
1,404
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.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; namespace Microsoft.EntityFrameworkCore.Query.Internal { /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public class EntityQueryProvider : IAsyncQueryProvider { private static readonly MethodInfo _genericCreateQueryMethod = typeof(EntityQueryProvider).GetRuntimeMethods() .Single(m => (m.Name == "CreateQuery") && m.IsGenericMethod); private readonly IQueryCompiler _queryCompiler; /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public EntityQueryProvider([NotNull] IQueryCompiler queryCompiler) { _queryCompiler = queryCompiler; } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual IQueryable<TElement> CreateQuery<TElement>(Expression expression) => new EntityQueryable<TElement>(this, expression); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual IQueryable CreateQuery(Expression expression) => (IQueryable)_genericCreateQueryMethod .MakeGenericMethod(expression.Type.GetSequenceType()) .Invoke(this, new object[] { expression }); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual TResult Execute<TResult>(Expression expression) => _queryCompiler.Execute<TResult>(expression); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual object Execute(Expression expression) => Execute<object>(expression); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual IAsyncEnumerable<TResult> ExecuteAsync<TResult>(Expression expression) => _queryCompiler.ExecuteAsync<TResult>(expression); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual Task<TResult> ExecuteAsync<TResult>(Expression expression, CancellationToken cancellationToken) => _queryCompiler.ExecuteAsync<TResult>(expression, cancellationToken); } }
47.901235
118
0.667784
[ "Apache-2.0" ]
joshcomley/EntityFramework-archive
src/Microsoft.EntityFrameworkCore/Query/Internal/EntityQueryProvider.cs
3,880
C#
using System; using System.Numerics; namespace _02_CrookedStairs { public class StartUp { public static void Main() { BigInteger firstNum = BigInteger.Parse(Console.ReadLine()); BigInteger secondNum = BigInteger.Parse(Console.ReadLine()); BigInteger thurdNum = BigInteger.Parse(Console.ReadLine()); <<<<<<< HEAD int rowsCount = int.Parse(Console.ReadLine()); ======= BigInteger rowsCount = BigInteger.Parse(Console.ReadLine()); >>>>>>> 64fbe466e16e0b7f8bf1be026aca7dfe5910ed20 for (int row = 0; row < rowsCount; row++) { if (row == 0) { Console.Write(firstNum); } else if (row == 1) { Console.Write(secondNum + " " + thurdNum); } else { for (int i = 0; i <= row; i++) { Console.Write(firstNum + secondNum + thurdNum + " "); BigInteger temp = firstNum; firstNum = secondNum; secondNum = thurdNum; thurdNum = temp + firstNum + secondNum; } <<<<<<< HEAD } ======= } >>>>>>> 64fbe466e16e0b7f8bf1be026aca7dfe5910ed20 Console.WriteLine(); } } } }
29.588235
77
0.434725
[ "MIT" ]
VeselinovStf/Telerik_Alpha_NET_Prep
AlphaExamPrep/TAA_EntranceExam11Oct/02_CrookedStairs/StartUp.cs
1,511
C#
using System.Diagnostics.CodeAnalysis; using BluffinMuffin.Protocol.DataTypes.Enums; using BluffinMuffin.Server.DataTypes.Attributes; namespace BluffinMuffin.Server.Logic.GameVariants { [GameVariant(GameSubTypeEnum.TexasHoldem)] [SuppressMessage("ReSharper", "UnusedMember.Global")] public class TexasHoldemVariant : AbstractHoldemGameVariant { } }
27
63
0.780423
[ "MIT" ]
BluffinMuffin/BluffinMuffin.Server
C#/BluffinMuffin.Server.Logic/GameVariants/TexasHoldemVariant.cs
380
C#