content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Copyright (c) 2017 AB4D d.o.o. // // 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. // // Based on OculusWrap project created by MortInfinite and licensed as Ms-PL (https://oculuswrap.codeplex.com/) using System; using System.Runtime.InteropServices; namespace CableGuardian { /// <summary> /// Specifies status information for the current session. /// </summary> /// <see cref="OvrWrap.GetSessionStatus"/> [StructLayout(LayoutKind.Sequential)] public struct SessionStatus { /// <summary> /// True if the process has VR focus and thus is visible in the HMD. /// </summary> [MarshalAs(UnmanagedType.U1)] // Marshal byte to bool (0 = false, all other = true) public bool IsVisible; /// <summary> /// True if an HMD is present. /// </summary> [MarshalAs(UnmanagedType.U1)] public bool HmdPresent; /// <summary> /// True if the HMD is on the user's head. /// </summary> [MarshalAs(UnmanagedType.U1)] public bool HmdMounted; /// <summary> /// True if the session is in a display-lost state. /// /// The session has become invalid (such as due to a device removal) /// and the shared resources need to be released (ovr_DestroyTextureSwapChain), the session /// needs to destroyed (ovr_Destroy) and recreated (ovr_Create), and new resources need to be /// created (ovr_CreateTextureSwapChainXXX). The application's existing private graphics /// resources do not need to be recreated unless the new ovr_Create call returns a different /// GraphicsLuid. /// </summary> [MarshalAs(UnmanagedType.U1)] public bool DisplayLost; /// <summary> /// True if the application should initiate shutdown. /// </summary> [MarshalAs(UnmanagedType.U1)] public bool ShouldQuit; /// <summary> /// True if UX has requested re-centering. /// Must call ovr_ClearShouldRecenterFlag or ovr_RecenterTrackingOrigin. /// </summary> [MarshalAs(UnmanagedType.U1)] public bool ShouldRecenter; [MarshalAs(UnmanagedType.U1)] public bool Internal0; [MarshalAs(UnmanagedType.U1)] public bool Internal1; } }
40.811765
112
0.648314
[ "MIT" ]
Bitslo/CableGuardian
Source/OculusWrap/Base/SessionStatus.cs
3,471
C#
/// <summary> ///Problem 3. Range Exceptions /// ///Define a class InvalidRangeException<T> that holds information about an error condition related to invalid range. It should hold error message and a range definition [start … end]. ///Write a sample application that demonstrates the InvalidRangeException<int> and InvalidRangeException<DateTime> by entering numbers in the range [1..100] and dates in the range [1.1.1980 … 31.12.2013]. /// </summary> /// namespace RangeExceptions { using System; using System.Globalization; public class ExceptionTests { public static void Main() { Console.WriteLine("Please enter number: "); int number = int.Parse(Console.ReadLine()); if (number < 1 || number > 100) { throw new InvalidRangeException<int>("Number must be in range [1..100]", 1, 100); } DateTime date = DateTime.ParseExact(Console.ReadLine(), "dd/MM/yyyy", CultureInfo.InvariantCulture); var startDate = new DateTime(1980, 1, 1); var endDate = new DateTime(2013, 12, 31); if (date < startDate || date > endDate) { throw new InvalidRangeException<DateTime>("Date must be in range [1.1.1980] - [31.12.2013]", startDate, endDate); } } } }
37.611111
204
0.619645
[ "MIT" ]
Nayaata/Object-Oriented-Programming-C-
OOPPrinciplesPartTwo/RangeExceptions/ExceptionTests.cs
1,360
C#
using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.CommandWpf; using GalaSoft.MvvmLight.Ioc; using Squirrel; using System; using System.Configuration; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows.Input; namespace Sample_Crunch.ViewModel { public class UpdateViewModel : ViewModelBase { public UpdateViewModel() { } public Task CheckForUpdates(int timeout) { var task = CheckForUpdate(); return Task.Run(async () => { if (await Task.WhenAny(task, Task.Delay(timeout)) != task) { CurrentState = State.Timedout; } }); } public enum State { Idle, Checking, UpdateAvailable, NoUpdateAvailable, Downloading, Installing, Installed, Timedout, Failed } public bool PreRelease { get { return Properties.Settings.Default.PreRelease; } set { Properties.Settings.Default.PreRelease = value; Properties.Settings.Default.Save(); RaisePropertyChanged<bool>(nameof(PreRelease)); CheckForUpdates(10000).Start(); } } private State state = State.Idle; public State CurrentState { get { return state; } private set { this.state = value; RaisePropertyChanged<bool>(nameof(CurrentState)); } } public string AvailableVersion { get { return (lastVersion == null ? "Checking..." : lastVersion.Version.ToString()); } } private ICommand updateCommand; private ReleaseEntry lastVersion = null; public ICommand UpdateCommand { get { return updateCommand ?? (updateCommand = new RelayCommand(Execute_UpdateCommand, () => { return this.CurrentState == State.UpdateAvailable && !this.Updating; })); } } private bool updating = false; public bool Updating { get { return this.updating; } private set { this.updating = value; RaisePropertyChanged<bool>(nameof(Updating)); } } private async void Execute_UpdateCommand() { if (this.updating) return; Updating = true; CurrentState = State.Checking; try { Stopwatch watch = Stopwatch.StartNew(); using (var manager = await UpdateManager.GitHubUpdateManager("https://github.com/wolkesson/SampleCrunch", null, null, null, Properties.Settings.Default.PreRelease)) { var updates = await manager.CheckForUpdate(); var lastVersion = updates?.ReleasesToApply?.OrderBy(x => x.Version).LastOrDefault(); CurrentState = State.Downloading; await manager.DownloadReleases(new[] { lastVersion }); #if DEBUG System.Windows.Forms.MessageBox.Show("DEBUG: Don't actually perform the update in debug mode"); #else CurrentState = State.Installing; //manager.CreateShortcutForThisExe(); MainViewModel main = SimpleIoc.Default.GetInstance<MainViewModel>(); // Send Telemetry System.Collections.Specialized.NameValueCollection data = new System.Collections.Specialized.NameValueCollection { { "from", main.Version }, { "to", this.lastVersion.Version.ToString() }, { "elapse", watch.ElapsedMilliseconds.ToString() } }; AppTelemetry.ReportEvent("Updating", data); //System.Windows.Forms.MessageBox.Show("The application has been updated - please restart the app."); await manager.ApplyReleases(updates); await manager.UpdateApp(); BackupSettings(); CurrentState = State.Installed; #endif } } catch (Exception e) { AppTelemetry.ReportError("Update", e); CurrentState = State.Failed; } finally { if (CurrentState == State.Installed) { UpdateManager.RestartApp(); } Updating = false; } } private async Task CheckForUpdate() { try { CurrentState = State.Checking; using (var manager = await UpdateManager.GitHubUpdateManager("https://github.com/wolkesson/SampleCrunch", null, null, null, Properties.Settings.Default.PreRelease)) { var updates = await manager.CheckForUpdate(); this.lastVersion = updates?.ReleasesToApply?.OrderBy(x => x.Version).LastOrDefault(); if (this.lastVersion == null) { CurrentState = State.NoUpdateAvailable; } else { CurrentState = State.UpdateAvailable; RaisePropertyChanged<string>(nameof(AvailableVersion)); } } } catch (Exception e) { AppTelemetry.ReportError("Update", e); CurrentState = State.Failed; } } /// <summary> /// Make a backup of our settings. /// Used to persist settings across updates. /// </summary> public static void BackupSettings() { // Backup settings string appDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); string settingsFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath; string settingsBackup = Path.Combine(appDir, "..\\last.config"); File.Copy(settingsFile, settingsBackup, true); // Backup plugins var pluginManager = SimpleIoc.Default.GetInstance<ViewModel.PluginManagerViewModel>(); string destDir = Path.Combine(appDir, "..\\Plugin_backup"); Directory.Move(pluginManager.PluginPath, destDir); } /// <summary> /// Restore our settings backup if any. /// Used to persist settings across updates. /// </summary> public static void RestoreSettings() { //Restore settings after application update string appDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); string settingsFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath; string settingsBackup = Path.Combine(appDir, "..\\last.config"); // Check if we have settings that we need to restore if (File.Exists(settingsBackup)) { try { // Create directory as needed Directory.CreateDirectory(Path.GetDirectoryName(settingsFile)); // Copy our backup file in place File.Copy(settingsBackup, settingsFile, true); File.Delete(settingsBackup); } catch (Exception) { } } // Move plugins to plugin path string srcDir = Path.Combine(appDir, "..\\Plugin_backup"); string dstDir = Path.Combine(appDir, "Plugins"); // pluginManager not available yet string stdFile = Path.Combine(srcDir, "StandardPanels.dll"); // We don't want to overwrite the StandardPlugins.dll from this release. if (File.Exists(stdFile)) File.Delete(stdFile); try { if (Directory.Exists(srcDir) && !Directory.Exists(dstDir)) { Directory.Move(srcDir, dstDir); } } catch (Exception) { } } } }
34.793522
180
0.530719
[ "MIT" ]
wolkesson/SampleCrunch
Sample Crunch/ViewModel/UpdateViewModel.cs
8,596
C#
using System.ComponentModel.Composition; using Caliburn.Micro; using LiteDbExplorer.Framework.Shell; namespace LiteDbExplorer.Modules.Main { [Export(typeof(IShellRightMenu))] [PartCreationPolicy (CreationPolicy.Shared)] public class ShellRightMenuViewModel : PropertyChangedBase, IShellRightMenu { } }
25.538462
79
0.76506
[ "MIT" ]
Dissociable/LiteDbExplorer
source/LiteDbExplorer/Modules/Main/ShellRightMenuViewModel.cs
334
C#
using System; using System.Collections.Generic; using System.Linq; namespace _02.LadyBugs { public class LadyBugs { public static void Main() { var sizeOfField = int.Parse(Console.ReadLine()); var ladyBugsIndexes = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); var command = Console.ReadLine(); var field = new List<int>(sizeOfField); for (int i = 0; i < sizeOfField; i++) { field.Add(0); } for (int i = 0; i < ladyBugsIndexes.Length; i++) { for (int j = 0; j < field.Count; j++) { if (ladyBugsIndexes[i] == j) { field[j] = 1; } } } while (!command.Equals("end")) { string[] commandLine = command.Split(' ').ToArray(); var startIndex = int.Parse(commandLine[0]); var direction = commandLine[1]; var flyingNumber = int.Parse(commandLine[2]); if (direction == "right") { MoveToRight(field, startIndex, flyingNumber); } else if (direction == "left") { MoveToLeft(field, startIndex, flyingNumber); } command = Console.ReadLine(); } Console.WriteLine(string.Join(" ", field)); } private static void MoveToLeft(List<int> field, int startIndex, int flyingNumber) { bool replaced = false; for (int i = startIndex; i >= 0; i--) { if (replaced == true) { break; } if (startIndex < 0 || startIndex >= field.Count) { break; } if (field[startIndex] == 1) { field[startIndex] = 0; var ladybugNewPlace = startIndex - flyingNumber; if (ladybugNewPlace < 0 && ladybugNewPlace >= field.Count) { replaced = true; break; } if (field[ladybugNewPlace] == 0) { field[ladybugNewPlace] = 1; break; } else { if (startIndex < ladybugNewPlace) { for (int j = ladybugNewPlace; j < field.Count; j += flyingNumber) { if (field[j] == 0) { field[j] = 1; replaced = true; break; } } } else { for (int j = ladybugNewPlace; j >= 0; j -= flyingNumber) { if (field[j] == 0) { field[j] = 1; replaced = true; break; } } } } } else { break; } } } private static void MoveToRight(List<int> field, int startIndex, int flyingNumber) { bool replaced = false; for (int i = startIndex; i < field.Count; i++) { if (replaced == true) { break; } if (startIndex < 0 || startIndex >= field.Count) { break; } if (field[startIndex] == 1) { field[startIndex] = 0; var ladybugNewPlace = startIndex + flyingNumber; if (!(ladybugNewPlace >= 0 && ladybugNewPlace < field.Count)) { replaced = true; break; } if (field[ladybugNewPlace] == 0) { field[ladybugNewPlace] = 1; break; } else { for (int j = ladybugNewPlace; j < field.Count; j += flyingNumber) { if (field[j] == 0) { field[j] = 1; replaced = true; break; } } } } else { break; } } } } }
31.928144
93
0.312453
[ "MIT" ]
nikolaydechev/Programming-Fundamentals
Exam Preparation/02.LadyBugs/LadyBugs.cs
5,334
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AT7View { public class AT7FileTypes { public static List<string> fileTypes = new List<string> { {".bin"}, {".breff"}, {".breft"}, {".brres"}, {".dat"}, {".fsb"}, {".ini"}, {".jpg"}, {".lvp"}, {".md"}, {".pb"}, {".sed"}, {".smd"}, {".srl"}, {".swd" }, {".tbl"}, {".tex"}, {".tlk"}, {".txt"}, {".utf16"}, {"???"} }; public static IDictionary<string, string> fileTypesDict = new Dictionary<string, string> { {".bin", ".bin is an ambiguous extension given to binary data. "}, {".breff", ".breff is a collection of particle data. The format is used an various first-party Wii titles."}, {".breft", ".breft is an image format that can be found in various first-party Wii titles."}, {".brres", ".brres is a collection of graphical data such as models, textures, palettes, ands animations. Many first-party Wii games use this format."}, {".dat", "Like .bin, .dat is a vague extension. In PMD WiiWare, it is used to blueprint mechanics such as attacks."}, {".fsb", ".fsb seems to be a scripting collection for overworld events."}, {".ini", ".ini is a longtime standard for configuration files. In PMD WiiWare, it is seemingly only used for debug-related content."}, {".jpg", ".jpg is the infamous standard in lossily-compressed image files."}, {".lvp", ".lvp seems to be related to storing Pokémon data. It has multiple AT7P blocks."}, {".md", ".md seems to be another format for storing Pokémon data. Not to be confused with plaintext markdown."}, {".pb", ".pb seems to be used for storing gameplay-related data, as implied by the one file that uses the extension."}, {".srl", ".srl is the format for DS Download Play apps, like PMD WiiWare's option to use a DS as a controller."}, {".smd", ".smd is a sequenced music format very much like MIDI."}, {".tex", ".tex is an SIR0 container which stores uncompressed image data."}, {".tbl", ".tbl is a binary text tabling format. Not the same .tbl format born out of the romhacking community."}, {".tlk", ".tlk seems to be related to text/dialogue."}, {".txt", ".txt is the number one standard in plain text file extensions. In PMD WiiWare, it is used not only for the game's Shift-JIS text, but also some dungeon-related data."}, {".utf16", ".utf16 is an extension named for the text encoding standard. In PMD WiiWare, it is only used for the save banner data."}, {".sed", ".sed is a format for sequenced sound effects."}, {".swd", ".swd is the collection of presets and samples utilized by .smd music files."}, {"???", "This file extension does not exist in the PMD WiiWare games." } }; } }
50.75
190
0.563732
[ "MIT" ]
kkzero241/AT7View
AT7View/AT7FileTypes.cs
3,252
C#
// Copyright (c) 2016, SolidCP // SolidCP is distributed under the Creative Commons Share-alike license // // SolidCP is a fork of WebsitePanel: // Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System.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("SolidCP.EnterpriseServer.Base")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("SolidCP.EnterpriseServer.Base")] [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(true)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("674c7f66-6e55-4cd5-be83-1ac8831539b6")]
50.481481
84
0.757153
[ "BSD-3-Clause" ]
Alirexaa/SolidCP
SolidCP/Sources/SolidCP.EnterpriseServer.Base/Properties/AssemblyInfo.cs
2,726
C#
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Security.Principal; using System.Text; using System.Threading.Tasks; namespace System.Web.Security { /// <summary> /// Extensions of ComBoostPrincipal. /// </summary> public static class ComBoostPrincipalExtensions { /// <summary> /// Get role entity from principal. /// </summary> /// <typeparam name="TUser">Type of user.</typeparam> /// <param name="principal">Principal.</param> /// <returns></returns> public static TUser GetUser<TUser>(this IPrincipal principal) where TUser : class, IRoleEntity { ComBoostPrincipal cp = principal as ComBoostPrincipal; return GetUser<TUser>(cp); } /// <summary> /// Get role entity from principal. /// </summary> /// <typeparam name="TUser">Type of user.</typeparam> /// <param name="principal">Principal.</param> /// <returns></returns> public static TUser GetUser<TUser>(this ComBoostPrincipal principal) where TUser : class, IRoleEntity { if (principal == null) return null; TUser roleEntity = principal.RoleEntity as TUser; return roleEntity; } /// <summary> /// Determines whether the current principal belongs to the specified role. /// </summary> /// <param name="principal">Comboost principal.</param> /// <param name="role">Role.</param> /// <returns></returns> public static bool IsInRole(this IPrincipal principal, object role) { ComBoostPrincipal item = principal as ComBoostPrincipal; if (item == null) throw new NotSupportedException("Only support with comboost principal."); return item.IsInRole(role); } } }
33.322034
89
0.592574
[ "MIT" ]
alexyjian/Core3.0
Wodsoft.ComBoost.Mvc/Web/Security/ComBoostPrincipalExtensions.cs
1,968
C#
// Copyright © 2017-2020 Chromely Projects. All rights reserved. // Use of this source code is governed by Chromely MIT licensed and CefSharp BSD-style license that can be found in the LICENSE file. using Chromely.Core.Logging; using Microsoft.Extensions.Logging; using System; using System.Diagnostics; namespace Chromely.CefSharp { public static class BrowserLauncher { public static void Open(string url) { try { try { Process.Start(url); } catch { try { // hack because of this: https://github.com/dotnet/corefx/issues/10361 url = url.Replace("&", "^&"); Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true }); } catch (Exception exception) { Logger.Instance.Log.LogError(exception, "BrowserLauncher:Open"); } } } catch (Exception exception) { Logger.Instance.Log.LogError(exception, "BrowserLauncher:Open"); } } } }
31.261905
133
0.486672
[ "MIT" ]
GerHobbelt/Chromely.CefSharp
src/Chromely.CefSharp/BrowserLauncher.cs
1,316
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; namespace Azure.AI.MetricsAdvisor.Models { /// <summary> The AzureTableDataFeed. </summary> internal partial class AzureTableDataFeed : DataFeedDetail { /// <summary> Initializes a new instance of AzureTableDataFeed. </summary> /// <param name="dataFeedName"> data feed name. </param> /// <param name="granularityName"> granularity of the time series. </param> /// <param name="metrics"> measure list. </param> /// <param name="dataStartFrom"> ingestion start time. </param> /// <param name="dataSourceParameter"> . </param> /// <exception cref="ArgumentNullException"> <paramref name="dataFeedName"/>, <paramref name="metrics"/>, or <paramref name="dataSourceParameter"/> is null. </exception> public AzureTableDataFeed(string dataFeedName, DataFeedGranularityType granularityName, IEnumerable<DataFeedMetric> metrics, DateTimeOffset dataStartFrom, AzureTableParameter dataSourceParameter) : base(dataFeedName, granularityName, metrics, dataStartFrom) { if (dataFeedName == null) { throw new ArgumentNullException(nameof(dataFeedName)); } if (metrics == null) { throw new ArgumentNullException(nameof(metrics)); } if (dataSourceParameter == null) { throw new ArgumentNullException(nameof(dataSourceParameter)); } DataSourceParameter = dataSourceParameter; DataSourceType = DataFeedSourceType.AzureTable; } /// <summary> Initializes a new instance of AzureTableDataFeed. </summary> /// <param name="dataSourceType"> data source type. </param> /// <param name="dataFeedId"> data feed unique id. </param> /// <param name="dataFeedName"> data feed name. </param> /// <param name="dataFeedDescription"> data feed description. </param> /// <param name="granularityName"> granularity of the time series. </param> /// <param name="granularityAmount"> if granularity is custom,it is required. </param> /// <param name="metrics"> measure list. </param> /// <param name="dimension"> dimension list. </param> /// <param name="timestampColumn"> user-defined timestamp column. if timestampColumn is null, start time of every time slice will be used as default value. </param> /// <param name="dataStartFrom"> ingestion start time. </param> /// <param name="startOffsetInSeconds"> the time that the beginning of data ingestion task will delay for every data slice according to this offset. </param> /// <param name="maxConcurrency"> the max concurrency of data ingestion queries against user data source. 0 means no limitation. </param> /// <param name="minRetryIntervalInSeconds"> the min retry interval for failed data ingestion tasks. </param> /// <param name="stopRetryAfterInSeconds"> stop retry data ingestion after the data slice first schedule time in seconds. </param> /// <param name="needRollup"> mark if the data feed need rollup. </param> /// <param name="rollUpMethod"> roll up method. </param> /// <param name="rollUpColumns"> roll up columns. </param> /// <param name="allUpIdentification"> the identification value for the row of calculated all-up value. </param> /// <param name="fillMissingPointType"> the type of fill missing point for anomaly detection. </param> /// <param name="fillMissingPointValue"> the value of fill missing point for anomaly detection. </param> /// <param name="viewMode"> data feed access mode, default is Private. </param> /// <param name="admins"> data feed administrator. </param> /// <param name="viewers"> data feed viewer. </param> /// <param name="isAdmin"> the query user is one of data feed administrator or not. </param> /// <param name="creator"> data feed creator. </param> /// <param name="status"> data feed status. </param> /// <param name="createdTime"> data feed created time. </param> /// <param name="actionLinkTemplate"> action link for alert. </param> /// <param name="dataSourceParameter"> . </param> internal AzureTableDataFeed(DataFeedSourceType dataSourceType, string dataFeedId, string dataFeedName, string dataFeedDescription, DataFeedGranularityType granularityName, int? granularityAmount, IList<DataFeedMetric> metrics, IList<MetricDimension> dimension, string timestampColumn, DateTimeOffset dataStartFrom, long? startOffsetInSeconds, int? maxConcurrency, long? minRetryIntervalInSeconds, long? stopRetryAfterInSeconds, DataFeedRollupType? needRollup, DataFeedAutoRollupMethod? rollUpMethod, IList<string> rollUpColumns, string allUpIdentification, DataFeedMissingDataPointFillType? fillMissingPointType, double? fillMissingPointValue, DataFeedAccessMode? viewMode, IList<string> admins, IList<string> viewers, bool? isAdmin, string creator, DataFeedStatus? status, DateTimeOffset? createdTime, string actionLinkTemplate, AzureTableParameter dataSourceParameter) : base(dataSourceType, dataFeedId, dataFeedName, dataFeedDescription, granularityName, granularityAmount, metrics, dimension, timestampColumn, dataStartFrom, startOffsetInSeconds, maxConcurrency, minRetryIntervalInSeconds, stopRetryAfterInSeconds, needRollup, rollUpMethod, rollUpColumns, allUpIdentification, fillMissingPointType, fillMissingPointValue, viewMode, admins, viewers, isAdmin, creator, status, createdTime, actionLinkTemplate) { DataSourceParameter = dataSourceParameter; DataSourceType = dataSourceType; } public AzureTableParameter DataSourceParameter { get; set; } } }
73.740741
1,319
0.700653
[ "MIT" ]
ChrisMissal/azure-sdk-for-net
sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Generated/Models/AzureTableDataFeed.cs
5,973
C#
using Domain.Entities.Insurance; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Infrastructure.Persistence.EntityConfigurations.Insurance { public class TitelConfiguration : IEntityTypeConfiguration<Titel> { public void Configure(EntityTypeBuilder<Titel> builder) { builder.Property(t => t.BezeichnungKurz) .IsRequired(); builder.Property(t => t.Beschreibung) .IsRequired(); builder.Property(t => t.RowVersion) .IsRowVersion(); } } }
30.285714
69
0.627358
[ "MIT" ]
RotterAxel/NettoAPI-Github
Infrastructure/Persistence/EntityConfigurations/Insurance/TitelConfiguration.cs
638
C#
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Labs_68_API.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
42.314856
167
0.579019
[ "MIT" ]
Lidinh26/Sparta-C-Sharp-Course
Labs_68_API/Areas/HelpPage/ModelDescriptions/ModelDescriptionGenerator.cs
19,084
C#
// // MSCompatUnicodeTable.cs : Utility for MSCompatUnicodeTable class. // // Author: // Atsushi Enomoto <atsushi@ximian.com> // // Copyright (C) 2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Globalization; using System.Text; namespace Mono.Globalization.Unicode { internal /*static*/ class MSCompatUnicodeTableUtil { public const byte ResourceVersion = 3; public static readonly CodePointIndexer Ignorable; public static readonly CodePointIndexer Category; public static readonly CodePointIndexer Level1; public static readonly CodePointIndexer Level2; public static readonly CodePointIndexer Level3; // public static readonly CodePointIndexer WidthCompat; public static readonly CodePointIndexer CjkCHS; public static readonly CodePointIndexer Cjk; static MSCompatUnicodeTableUtil () { // FIXME: those ranges could be more compact, but since // I haven't filled all the table yet, I keep it safer. int [] ignoreStarts = new int [] { 0, 0xA000, 0xF900}; int [] ignoreEnds = new int [] { 0x3400, 0xA500, 0x10000}; int [] catStarts = new int [] { 0, 0x1E00, 0x3000, 0x4E00, 0xAC00, 0xF900}; int [] catEnds = new int [] { 0x1200, 0x2800, 0x3400, 0xA000, 0xD7B0, 0x10000}; int [] lv1Starts = new int [] { 0, 0x1E00, 0x3000, 0x4E00, 0xAC00, 0xF900}; int [] lv1Ends = new int [] { 0x1200, 0x2800, 0x3400, 0xA000, 0xD7B0, 0x10000}; int [] lv2Starts = new int [] {0, 0x1E00, 0x3000, 0xFB00}; int [] lv2Ends = new int [] {0xF00, 0x2800, 0x3400, 0x10000}; int [] lv3Starts = new int [] {0, 0x1E00, 0x3000, 0xFB00}; int [] lv3Ends = new int [] {0x1200, 0x2800, 0x3400, 0x10000}; // int [] widthStarts = new int [] {0, 0x2000, 0x3100, 0xFF00}; // int [] widthEnds = new int [] {0x300, 0x2200, 0x3200, 0x10000}; int [] chsStarts = new int [] { 0x3100, 0x4E00, 0xE800}; // FIXME: really? int [] chsEnds = new int [] { 0x3400, 0xA000, 0x10000}; int [] cjkStarts = new int [] {0x3100, 0x4E00, 0xF900}; int [] cjkEnds = new int [] {0x3400, 0xA000, 0xFB00}; Ignorable = new CodePointIndexer (ignoreStarts, ignoreEnds, -1, -1); Category = new CodePointIndexer (catStarts, catEnds, 0, 0); Level1 = new CodePointIndexer (lv1Starts, lv1Ends, 0, 0); Level2 = new CodePointIndexer (lv2Starts, lv2Ends, 0, 0); Level3 = new CodePointIndexer (lv3Starts, lv3Ends, 0, 0); // WidthCompat = new CodePointIndexer (widthStarts, widthEnds, 0, 0); CjkCHS = new CodePointIndexer (chsStarts, chsEnds, -1, -1); Cjk = new CodePointIndexer (cjkStarts, cjkEnds, -1, -1); } } }
43.287356
74
0.688794
[ "MIT" ]
GrapeCity/pagefx
mono/mcs/class/corlib/Mono.Globalization.Unicode/MSCompatUnicodeTableUtil.cs
3,766
C#
#region Copyright Teference // ************************************************************************************ // <copyright file="WebhookField.cs" company="Teference"> // Copyright © Teference 2015. All right reserved. // </copyright> // ************************************************************************************ // <author>Jaspalsinh Chauhan</author> // <email>jachauhan@gmail.com</email> // <project>Teference - Shopify API - C#.NET SDK</project> // ************************************************************************************ #endregion namespace Teference.Shopify.Api.Models { using System; [Flags] public enum WebhookField { None = 0, Id = 1, Address = 1 << 1, Topic = 1 << 2, CreatedAt = 1 << 3, UpdatedAt = 1 << 4, Format = 1 << 5, Fields = 1 << 6, MetafieldNamespace = 1 << 7 } }
30.2
87
0.4117
[ "MIT" ]
inkfrog/shopify-dotnet
source/Shopify.Api/Models/Enums/WebhookField.cs
909
C#
 using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using System.Reflection; using System.Text.RegularExpressions; using System.Diagnostics; public class LogLocation { // [UnityEditor.Callbacks.OnOpenAssetAttribute(0)] static bool OnOpenAsset(int instanceID, int line) { string stackTrace = GetStackTrace(); /*这里与LuaException里一样,也需要根据自己的log格式去修改解析的正则 * 我这里是按照下面的异常格式解析 LuaException: X:/ tolua - master / Assets / ToLua / Examples / 02_ScriptsFromFile / ScriptsFromFile.lua:22: attempt to perform arithmetic on local 'luaClass1'(a table value) stack traceback: ScriptsFromFile.lua:22: in main chunk LUA: dddddd stack traceback: GameMain.lua:38: in function 'GameMain.Start' xlua.access, no field __Hotfix0_TestHotfix stack traceback: [C]: in field 'access' [string "Init"]:101: in field 'hotfix' XLua/Hotfix/HotfixTest.lua:25: in function 'XLua.Hotfix.HotfixTest.Register' */ //Match match = Regex.Match(stackTrace, "LuaException: (.*?.lua:\\d+)"); Match match = Regex.Match(stackTrace, "stack traceback:\n(.*?.lua:\\d+)"); // Match match = Regex.Match(match1.ToString().Replace("stack traceback:\n\t", ""), ".*"); // UnityEngine.Debug.LogError("===================: " +match.ToString()); if (OpenLuaLocation(match)) { return true; } match = Regex.Match(stackTrace, @"file:line:column (.+):0", RegexOptions.IgnoreCase); if (FindLocation(match, true)) { return true; } match = Regex.Match(stackTrace, @"\(at (.+)\)", RegexOptions.IgnoreCase); if (FindLocation(match, false)) { return true; } return false; } static bool OpenLuaLocation(Match match) { if (!match.Success) { return false; } int luaIDETypeIndex = EditorPrefs.GetInt("LUA_IDE_TYPE"); LuaIDEType luaIDEType = (LuaIDEType)luaIDETypeIndex; string idePath = string.Empty; if (luaIDEType == LuaIDEType.IDEA) { idePath = EditorPrefs.GetString("IDEA_IDE_Path"); } else if (luaIDEType == LuaIDEType.VSCode) { idePath = EditorPrefs.GetString("VSCode_IDE_Path"); } if (string.IsNullOrEmpty(idePath) || !System.IO.File.Exists(idePath)) { return false; } while (match.Success) { string pathLine = match.Groups[1].Value; // UnityEngine. Debug.LogError(pathLine); if (!pathLine.Contains("LogSubsystem.cs"))//一直为true { int spliteIndex = pathLine.LastIndexOf(':'); string path = pathLine.Substring(0, spliteIndex); int line = System.Convert.ToInt32(pathLine.Substring(spliteIndex + 1)); string s = path.Replace("\t", ""); for (int i = 0; i < XLuaManager.m_path.Count; i++) { // UnityEngine.Debug.LogError(XLuaManager.m_path[i] + "==s==" + s); if (XLuaManager.m_path[i].Contains(s))//xlua 里所有lua 文件地址合集 { path = XLuaManager.m_path[i]; break; } } string args = string.Empty; // if (luaIDEType == LuaIDEType.IDEA) // { // args = string.Format("{0}:{1}", path.Replace("\\", "/"), line); // } // else if (luaIDEType == LuaIDEType.VSCode) { args = string.Format("-g {0}:{1}", path.Replace("\\", "/"), line); } // UnityEngine.Debug.LogError(args); Process process = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = idePath; startInfo.Arguments = args; startInfo.UseShellExecute = false; startInfo.CreateNoWindow = false; startInfo.RedirectStandardOutput = false; process.StartInfo = startInfo; process.Start(); return true; } match = match.NextMatch(); } return false; } static bool FindLocation(Match match, bool bFullPath) { while (match.Success) { string pathLine = match.Groups[1].Value; if (!pathLine.Contains("LogSubsystem.cs")) { int spliteIndex = pathLine.LastIndexOf(':'); string path = pathLine.Substring(0, spliteIndex); int Line = System.Convert.ToInt32(pathLine.Substring(spliteIndex + 1)); if (!bFullPath) { path = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf("Assets")) + path; } UnityEditorInternal.InternalEditorUtility.OpenFileAtLineExternal(path, Line); return true; } match = match.NextMatch(); } return false; } static string GetStackTrace() { System.Type consoleWindowType = typeof(EditorWindow).Assembly.GetType("UnityEditor.ConsoleWindow"); FieldInfo ms_ConsoleWindow_fieldInfo = consoleWindowType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic); EditorWindow consoleWindowInstance = ms_ConsoleWindow_fieldInfo.GetValue(null) as EditorWindow; if (null != consoleWindowInstance) { if (EditorWindow.focusedWindow == consoleWindowInstance) { FieldInfo m_ActiveText_fieldInfo = consoleWindowType.GetField("m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic); return m_ActiveText_fieldInfo.GetValue(consoleWindowInstance).ToString(); } } return string.Empty; } }
36.375
181
0.561774
[ "Apache-2.0" ]
fqkw6/ILRuntimeMyFrame
Assets/Editor/Tools/LogLocation.cs
6,217
C#
/***********************************************************************************************\ * (C) KAL ATM Software GmbH, 2021 * KAL ATM Software GmbH licenses this file to you under the MIT license. * See the LICENSE file in the project root for more information. \***********************************************************************************************/ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Text; using System.Linq; using XFS4IoT; using XFS4IoTFramework.Dispenser; using XFS4IoTFramework.CashManagement; using XFS4IoTFramework.Common; using XFS4IoT.Common.Commands; using XFS4IoT.Common.Completions; using XFS4IoT.Common; using XFS4IoT.Dispenser.Events; using XFS4IoT.Dispenser; using XFS4IoT.Dispenser.Commands; using XFS4IoT.Dispenser.Completions; using XFS4IoT.Completions; using XFS4IoTServer; namespace KAL.XFS4IoTSP.CashDispenser.Sample { /// <summary> /// Sample CashDispenser device class to implement /// </summary> public class CashDispenserSample : ICashManagementDevice, IDispenserDevice, ICommonDevice { /// <summary> /// RunAync /// Handle unsolic events /// Here is an example of handling ItemsTakenEvent after card is presented and taken by customer. /// </summary> /// <returns></returns> public async Task RunAsync() { for (; ; ) { // Check if presented cash is taken. When cash is taken, set output position empty, shutter closed and fire ItemsTakenEvent await cashTakenSignal?.WaitAsync(); OutputPositionStatus = OutposClass.PositionStatusEnum.Empty; ShutterStatus = OutposClass.ShutterEnum.Closed; DispenserServiceProvider cashDispenserServiceProvider = SetServiceProvider as DispenserServiceProvider; await cashDispenserServiceProvider.IsNotNull().ItemsTakenEvent(new ItemsTakenEvent.PayloadData(ItemsTakenEvent.PayloadData.PositionEnum.Center)); } } /// <summary> /// Constructor /// </summary> /// <param name="Logger"></param> public CashDispenserSample(ILogger Logger) { Logger.IsNotNull($"Invalid parameter received in the {nameof(CashDispenserSample)} constructor. {nameof(Logger)}"); this.Logger = Logger; } /// <summary> /// This command is used to obtain the overall status of any XFS4IoT service. The status includes common status information and can include zero or more interface specific status objects, depending on the implemented interfaces of the service. It may also return vendor-specific status information. /// </summary> public StatusCompletion.PayloadData Status() { StatusPropertiesClass common = new( Device: DeviceStatus, Extra: new List<string>(), GuideLights: new List<StatusPropertiesClass.GuideLightsClass>(){ new StatusPropertiesClass.GuideLightsClass( StatusPropertiesClass.GuideLightsClass.FlashRateEnum.Off, StatusPropertiesClass.GuideLightsClass.ColorEnum.Green, StatusPropertiesClass.GuideLightsClass.DirectionEnum.Off) }, DevicePosition: PositionStatusEnum.Inposition, PowerSaveRecoveryTime: 0, AntiFraudModule: StatusPropertiesClass.AntiFraudModuleEnum.Ok); List<OutposClass> Positions = new List<OutposClass>(); OutposClass OutPos = new(Position: OutposClass.PositionEnum.Center, Shutter: ShutterStatus, PositionStatus: OutputPositionStatus, Transport: Transport, TransportStatus: TransportStatus, JammedShutterPosition: OutposClass.JammedShutterPositionEnum.NotSupported); Positions.Add(OutPos); XFS4IoT.Dispenser.StatusClass cashDispenser = new( IntermediateStacker: StackerStatus, Positions: Positions); XFS4IoT.CashManagement.StatusClass cashManagement = new( SafeDoor: SafeDoorStatus, Dispenser: DispenserStatus); return new StatusCompletion.PayloadData(MessagePayload.CompletionCodeEnum.Success, null, common, null, null, cashDispenser, cashManagement); } public CapabilitiesCompletion.PayloadData Capabilities() { List<CapabilityPropertiesClass.GuideLightsClass> guideLights = new() { new(new CapabilityPropertiesClass.GuideLightsClass.FlashRateClass(true, true, true, true), new CapabilityPropertiesClass.GuideLightsClass.ColorClass(true, true, true, true, true, true, true), new CapabilityPropertiesClass.GuideLightsClass.DirectionClass(false, false)) }; CapabilityPropertiesClass common = new( ServiceVersion: "1.0", DeviceInformation: new List<DeviceInformationClass>() { new DeviceInformationClass( ModelName: "Simulator", SerialNumber: "123456-78900001", RevisionNumber: "1.0", ModelDescription: "KAL simualtor", Firmware: new List<FirmwareClass>() {new FirmwareClass( FirmwareName: "XFS4 SP", FirmwareVersion: "1.0", HardwareRevision: "1.0") }, Software: new List<SoftwareClass>(){ new SoftwareClass( SoftwareName: "XFS4 SP", SoftwareVersion: "1.0") }) }, VendorModeIformation: new VendorModeInfoClass( AllowOpenSessions: true, AllowedExecuteCommands: new List<string>() { "CashDispenser.Dispense", "CashDispenser.Reset", "CashDispenser.PresentCash", "CashDispenser.Reject", "CashDispenser.Retract", "CashDispenser.OpenShutter", "CashDispenser.CloseShutter", "CashDispenser.TestCashUnits", "CashDispenser.Count", }), Extra: new List<string>(), GuideLights: guideLights, PowerSaveControl: false, AntiFraudModule: false, SynchronizableCommands: new List<string>(), EndToEndSecurity: false, HardwareSecurityElement: false, ResponseSecurityEnabled: false); XFS4IoT.Dispenser.CapabilitiesClass cashDispenser = new( Type: XFS4IoT.Dispenser.CapabilitiesClass.TypeEnum.SelfServiceBill, MaxDispenseItems: 200, Shutter: true, ShutterControl: false, RetractAreas: new XFS4IoT.Dispenser.CapabilitiesClass.RetractAreasClass(true, true, true, true, true), RetractTransportActions: new XFS4IoT.Dispenser.CapabilitiesClass.RetractTransportActionsClass(true, true, true, true), RetractStackerActions: new XFS4IoT.Dispenser.CapabilitiesClass.RetractStackerActionsClass(true, true, true, true), IntermediateStacker: true, ItemsTakenSensor: true, Positions: new XFS4IoT.Dispenser.CapabilitiesClass.PositionsClass(false, false, true), MoveItems: new XFS4IoT.Dispenser.CapabilitiesClass.MoveItemsClass(true, false, false, true), PrepareDispense: false); XFS4IoT.CashManagement.CapabilitiesClass cashManagement = new( SafeDoor: true, CashBox: null, ExchangeType: new(true)); List<InterfaceClass> interfaces = new() { new InterfaceClass( Name: InterfaceClass.NameEnum.Common, Commands: new List<string>() { "Common.Status", "Common.Capabilities" }, Events: new List<string>(), MaximumRequests: 1000, AuthenticationRequired: new List<string>()), new InterfaceClass( Name: InterfaceClass.NameEnum.CashDispenser, Commands: new List<string> { "CashDispenser.Dispense", "CashDispenser.Reset", "CashDispenser.PresentCash", "CashDispenser.Reject", "CashDispenser.Retract", "CashDispenser.OpenShutter", "CashDispenser.CloseShutter", "CashDispenser.TestCashUnits", "CashDispenser.Count", }, Events: new List<string> { "CashDispenser.CashUnitErrorEvent", "CashDispenser.NoteErrorEvent", }, MaximumRequests: 1000, AuthenticationRequired: new List<string>()), new InterfaceClass( Name: InterfaceClass.NameEnum.CashManagement, Commands: new List<string>() { "CashManagement.GetCashUnitStatus", "CashManagement.SetCashUnitInfo", "CashManagement.UnlockSafe", "CashManagement.InitiateExchange", "CashManagement.CompleteExchange", "CashManagement.CalibrateCashUnit", }, Events: new List<string>() { "CashManagement.CashUnitErrorEvent", "CashManagement.CashUnitErrorEvent", "CashManagement.NoteErrorEvent", }, MaximumRequests: 1000, AuthenticationRequired: new List<string>()) }; return new CapabilitiesCompletion.PayloadData(MessagePayload.CompletionCodeEnum.Success, null, interfaces, common, null, null, cashDispenser, cashManagement); } public async Task<DispenseResult> DispenseAsync(IDispenseEvents events, DispenseRequest dispenseInfo, CancellationToken cancellation) { await Task.Delay(1000, cancellation); StackerStatus = XFS4IoT.Dispenser.StatusClass.IntermediateStackerEnum.NotEmpty; if (dispenseInfo.Values is null || dispenseInfo.Values.Count == 0) { return new DispenseResult(MessagePayload.CompletionCodeEnum.Success, $"Empty denominate value received from the framework.", DispenseCompletion.PayloadData.ErrorCodeEnum.NotDispensable); } foreach (var item in dispenseInfo.Values) { ItemMovement movement = new(item.Value); // set dispensed count. If necessary, need to set reject count too if (LastDispenseResult.ContainsKey(item.Key)) LastDispenseResult[item.Key].DispensedCount += item.Value; else LastDispenseResult.Add(item.Key, movement); } return new DispenseResult(MessagePayload.CompletionCodeEnum.Success, dispenseInfo.Values, LastDispenseResult); } public async Task<PresentCashResult> PresentCashAsync(IPresentEvents events, PresentCashRequest presentInfo, CancellationToken cancellation) { await Task.Delay(1000, cancellation); if (StackerStatus == XFS4IoT.Dispenser.StatusClass.IntermediateStackerEnum.Empty || LastDispenseResult.Count == 0) { return new PresentCashResult(MessagePayload.CompletionCodeEnum.Success, "No cash to present", PresentCompletion.PayloadData.ErrorCodeEnum.NoItems); } // When cash is presented successfully, set StackerStatus, OutputpoistionStatus and shutter status StackerStatus = XFS4IoT.Dispenser.StatusClass.IntermediateStackerEnum.Empty; OutputPositionStatus = OutposClass.PositionStatusEnum.NotEmpty; ShutterStatus = OutposClass.ShutterEnum.Open; LastPresentResult.Clear(); foreach (var item in LastDispenseResult) { ItemMovement movement = new(null, item.Value.DispensedCount); // set presented count. LastPresentResult.Add(item.Key, movement); } LastDispenseResult.Clear(); // Dispensed cash is now presented return new PresentCashResult(MessagePayload.CompletionCodeEnum.Success, 0, LastPresentResult); } public async Task<RejectResult> RejectAsync(IRejectEvents events, CancellationToken cancellation) { await Task.Delay(1000, cancellation); if ((StackerStatus == XFS4IoT.Dispenser.StatusClass.IntermediateStackerEnum.Empty && OutputPositionStatus == OutposClass.PositionStatusEnum.Empty) || LastDispenseResult.Count == 0) { return new RejectResult(MessagePayload.CompletionCodeEnum.Success, "No cash to reject", RejectCompletion.PayloadData.ErrorCodeEnum.NoItems); } StackerStatus = XFS4IoT.Dispenser.StatusClass.IntermediateStackerEnum.Empty; OutputPositionStatus = OutposClass.PositionStatusEnum.Empty; ShutterStatus = OutposClass.ShutterEnum.Closed; Dictionary<string, ItemMovement> ItemMovementResult = new(LastDispenseResult); LastDispenseResult.Clear(); return new RejectResult(MessagePayload.CompletionCodeEnum.Success, ItemMovementResult); } /// <summary> /// This method will retract items which may have been in customer access from an output position or from internal areas within the CashDispenser. /// Retracted items will be moved to either a retract cash unit, a reject cash unit, item cash units, the transport or the intermediate stacker. /// After the items are retracted the shutter is closed automatically, even if the ShutterControl capability is set to false. /// </summary> public async Task<RetractResult> RetractAsync(IRetractEvents events, RetractRequest retractInfo, CancellationToken cancellation) { await Task.Delay(1000, cancellation); if ((StackerStatus == XFS4IoT.Dispenser.StatusClass.IntermediateStackerEnum.Empty && OutputPositionStatus == OutposClass.PositionStatusEnum.Empty) || LastPresentResult.Count == 0) { return new RetractResult(MessagePayload.CompletionCodeEnum.Success, "No cash to retract", RetractCompletion.PayloadData.ErrorCodeEnum.NoItems); } StackerStatus = XFS4IoT.Dispenser.StatusClass.IntermediateStackerEnum.Empty; OutputPositionStatus = OutposClass.PositionStatusEnum.Empty; ShutterStatus = OutposClass.ShutterEnum.Closed; List<RetractResult.BankNoteItem> CashMovement = new(); RetractResult.BankNoteItem NoteItem1 = new("EUR", 10.00, 5, 0); CashMovement.Add(NoteItem1); RetractResult.BankNoteItem NoteItem2 = new("EUR", 20.00, 8, 0); CashMovement.Add(NoteItem2); RetractResult.BankNoteItem NoteItem3 = new("", 0.00, 7, 0); // Unkown item CashMovement.Add(NoteItem3); StackerStatus = XFS4IoT.Dispenser.StatusClass.IntermediateStackerEnum.Empty; OutputPositionStatus = OutposClass.PositionStatusEnum.Empty; ShutterStatus = OutposClass.ShutterEnum.Closed; return new RetractResult(MessagePayload.CompletionCodeEnum.Success, CashMovement); } /// <summary> /// OpenCloseShutterAsync /// Perform shutter operation to open or close. /// </summary> public async Task<OpenCloseShutterResult> OpenCloseShutterAsync(OpenCloseShutterRequest shutterInfo, CancellationToken cancellation) { await Task.Delay(1000, cancellation); if (shutterInfo.Action == OpenCloseShutterRequest.ActionEnum.Open) ShutterStatus = OutposClass.ShutterEnum.Open; if (shutterInfo.Action == OpenCloseShutterRequest.ActionEnum.Close) ShutterStatus = OutposClass.ShutterEnum.Closed; return new OpenCloseShutterResult(MessagePayload.CompletionCodeEnum.Success); } /// <summary> /// ResetDeviceAsync /// Perform a hardware reset which will attempt to return the CashDispenser device to a known good state. /// </summary> public async Task<ResetDeviceResult> ResetDeviceAsync(IResetEvents events, ResetDeviceRequest resetDeviceInfo, CancellationToken cancellation) { await Task.Delay(1000, cancellation); Dictionary<string, ItemMovement> CashMovement = null; if (StackerStatus == XFS4IoT.Dispenser.StatusClass.IntermediateStackerEnum.NotEmpty || OutputPositionStatus == OutposClass.PositionStatusEnum.NotEmpty || TransportStatus == OutposClass.TransportStatusEnum.NotEmpty) { OutputPositionStatus = OutposClass.PositionStatusEnum.Empty; StackerStatus = XFS4IoT.Dispenser.StatusClass.IntermediateStackerEnum.Empty; TransportStatus = OutposClass.TransportStatusEnum.Empty; if (resetDeviceInfo.Position.OutputPosition != null) { OutputPositionStatus = OutposClass.PositionStatusEnum.NotEmpty; } else if (!string.IsNullOrEmpty(resetDeviceInfo.Position.CashUnit)) { // Update cash unit count and status: CashUnitCounts, CashUnitStatus } else { switch (resetDeviceInfo.Position.RetractArea.RetractArea) { case CashDispenserCapabilitiesClass.RetractAreaEnum.Stacker: StackerStatus = XFS4IoT.Dispenser.StatusClass.IntermediateStackerEnum.NotEmpty; break; case CashDispenserCapabilitiesClass.RetractAreaEnum.Transport: TransportStatus = OutposClass.TransportStatusEnum.NotEmpty; break; case CashDispenserCapabilitiesClass.RetractAreaEnum.Reject: // Update reject cassette count and status break; case CashDispenserCapabilitiesClass.RetractAreaEnum.Retract: // Update retract cassette count and status break; case CashDispenserCapabilitiesClass.RetractAreaEnum.ItemCassette: // Update cash cassettes count and status break; default: break; } } } Transport = OutposClass.TransportEnum.Ok; ShutterStatus = OutposClass.ShutterEnum.Closed; return new ResetDeviceResult(MessagePayload.CompletionCodeEnum.Success, CashMovement); } /// <summary> /// This method is used to test cash units following replenishment. /// All physical cash units which are testable (i.e. that have a status of ok or low and no application lock in the the physical cash unit) are tested. /// If the hardware is able to do so tests are continued even if an error occurs while testing one of the cash units. /// The method completes with success if the device successfully manages to test all of the testable cash units regardless of the outcome of the test. /// This is the case if all testable cash units could be tested and a dispense was possible from at least one of the cash units. /// </summary> public async Task<TestCashUnitsResult> TestCashUnitsAsync(ITestCashUnitsEvents events, TestCashUnitsRequest testCashUnitsInfo, CancellationToken cancellation) { await Task.Delay(1000, cancellation); // TesCash normally moves dispensed cash to Reject cassette, but can be other supported position // If it is reject cassette, dispense one item from each cash unit // In the end update count and status of tested cash units and the reject cassette Dictionary<string, ItemMovement> MovementResult = new(); ItemMovement im = new(1); // dispensed 1 item MovementResult.Add("CASS1", im); MovementResult.Add("CASS2", im); MovementResult.Add("CASS3", im); // .... return new TestCashUnitsResult(MessagePayload.CompletionCodeEnum.Success, MovementResult); } /// <summary> /// CountAsync /// Perform count operation to empty the specified physical cash unit(s). /// All items dispensed from the cash unit are counted and moved to the specified output location. /// </summary> public async Task<CountResult> CountAsync(ICountEvents events, CountRequest countInfo, CancellationToken cancellation) { await Task.Delay(1000, cancellation); Dictionary<string, ItemMovement> MovementResult = new(); if (countInfo.EmptyAll) { // Empty all cash units // Set all cash unit count to 0 and status to empty // For example, if 2000 items in each cash unit, the cash movement result will be ItemMovement im = new(2000, 0, 0, 0); MovementResult.Add("PHP3", im); MovementResult.Add("PHP4", im); MovementResult.Add("PHP5", im); MovementResult.Add("PHP6", im); } else { // empty the specified cash unit ItemMovement im = new(2000, 0, 0, 0); MovementResult.Add(countInfo.PhysicalPositionName, im); // Set the physical cassette status to empty } return new CountResult(MessagePayload.CompletionCodeEnum.Success, MovementResult); } /// <summary> /// PrepareDispenseAsync /// On some hardware it can take a significant amount of time for the dispenser to get ready to dispense media. /// On this type of hardware the this method can be used to improve transaction performance. /// </summary> public async Task<PrepareDispenseResult> PrepareDispenseAsync(PrepareDispenseRequest prepareDispenseInfo, CancellationToken cancellation) { await Task.Delay(1000, cancellation); return new PrepareDispenseResult(MessagePayload.CompletionCodeEnum.UnsupportedCommand); } /// <summary> /// GetPresentStatus /// This method returns the status of the most recent attempt to dispense and/or present items to the customer from a specified output position. /// Throw NotImplementedException if the device specific class doesn't support to manage present status. /// </summary> public PresentStatus GetPresentStatus(CashDispenserCapabilitiesClass.OutputPositionEnum position) { // If USD 500 was presented Dictionary<string, double> Amounts = new(); Amounts.Add("EUR", 500.00); Dictionary<string, int> Values = new(); Values.Add("PHP3", 2); // USD 50 x 2 Values.Add("PHP4", 4); // USD 100 x 4 Denomination Denom = new(Amounts, Values); return new PresentStatus(PresentStatus.PresentStatusEnum.Presented, Denom); } // CASH MANAGEMENT SP interfaces /// <summary> /// This method is called when the client application send CashUnitInfo command first time since executable runs or while exchange is in progress. /// Return true if the cash unit configuration is being changed since last call, otherwise false /// The key representing physical position name associated with the CashUnit structure. /// The key name should be unique to identify Physical Cash Unit /// </summary> public bool GetCashUnitConfiguration(out Dictionary<string, CashUnitConfiguration> CashUnits) { if (AllBanknoteIDs.Count == 0) AllBanknoteIDs = new List<int> { 0x0001, 0x0002, 0x0003, 0x0004 }; if (CashUnitConfig.Count == 0) { CashUnitConfiguration reject = new(CashUnit.TypeEnum.RejectCassette, // Type "", // CurrencyID 0, // Value 2000, // Maximum false, // AppLock "REJECT", // CashUnitName 0, // Minimum "PHP1", // PhysicalPositionName "REJECT", // UnitID 2000, // MaximumCapacity, true, // HardwareSensor, CashUnit.ItemTypesEnum.All, // ItemTypes, AllBanknoteIDs); CashUnitConfig.Add("PHP1", reject); CashUnitConfiguration retract = new(CashUnit.TypeEnum.RetractCassette, // Type "", // CurrencyID 0, // Value 2000, // Maximum false, // AppLock "RETRACT", // CashUnitName 0, // Minimum "PHP2", // PhysicalPositionName "RETRACT", // UnitID 2000, // MaximumCapacity, true, // HardwareSensor, CashUnit.ItemTypesEnum.All, // ItemTypes, AllBanknoteIDs); CashUnitConfig.Add("PHP2", retract); CashUnitConfiguration usd10 = new(CashUnit.TypeEnum.BillCassette, // Type "EUR", // CurrencyID 10.0, // Value 2000, // Maximum false, // AppLock "EUR10", // CashUnitName 0, // Minimum "PHP3", // PhysicalPositionName "EUR10", // UnitID 2000, // MaximumCapacity, true, // HardwareSensor, CashUnit.ItemTypesEnum.Individual, // ItemTypes, new List<int> { 0x0001 }); CashUnitConfig.Add("PHP3", usd10); CashUnitConfiguration usd20 = new(CashUnit.TypeEnum.BillCassette, // Type "EUR", // CurrencyID 20.0, // Value 2000, // Maximum false, // AppLock "EUR20", // CashUnitName 0, // Minimum "PHP4", // PhysicalPositionName "EUR20", // UnitID 2000, // MaximumCapacity, true, // HardwareSensor, CashUnit.ItemTypesEnum.Individual, // ItemTypes, new List<int> { 0x0002 }); CashUnitConfig.Add("PHP4", usd20); CashUnitConfiguration usd50 = new(CashUnit.TypeEnum.BillCassette, // Type "EUR", // CurrencyID 50.0, // Value 2000, // Maximum false, // AppLock "EUR50", // CashUnitName 0, // Minimum "PHP5", // PhysicalPositionName "EUR50", // UnitID 2000, // MaximumCapacity, true, // HardwareSensor, CashUnit.ItemTypesEnum.Individual, // ItemTypes, new List<int> { 0x0003 }); CashUnitConfig.Add("PHP5", usd50); CashUnitConfiguration usd100 = new(CashUnit.TypeEnum.BillCassette, // Type "EUR", // CurrencyID 100.0, // Value 2000, // Maximum false, // AppLock "EUR100", // CashUnitName 0, // Minimum "PHP6", // PhysicalPositionName "EUR100", // UnitID 2000, // MaximumCapacity, true, // HardwareSensor, CashUnit.ItemTypesEnum.Individual, // ItemTypes, new List<int> { 0x0004 }); CashUnitConfig.Add("PHP6", usd100); } CashUnits = new(CashUnitConfig); return true; } /// <summary> /// This method is called after device operation is completed involving cash movement /// returning false if the device doesn't support maintaining counters and framework will maintain counters. /// However if the device doesn't support maintaining counters, the counts are not guaranteed. /// The key name should be used for the GetCashUnitConfiguration output. /// </summary> public Dictionary<string, CashUnitAccounting> GetCashUnitAccounting() { if (CashUnitCounts.Count == 0) { CashUnitCounts.Add("PHP1", new(0, 0, 0, 0, 0, 0, 0, 0, new List<BankNoteNumber>())); // Reject cassette CashUnitCounts.Add("PHP2", new(0, 0, 0, 0, 0, 0, 0, 0, new List<BankNoteNumber>())); // Retract cassette CashUnitCounts.Add("PHP3", new(1000, 2000, 1000, 1000, 0, 0, 1000, 0, new List<BankNoteNumber>() { new(0x0001, 1000) })); // USD10 cassette CashUnitCounts.Add("PHP4", new(1000, 2000, 1000, 1000, 0, 0, 1000, 0, new List<BankNoteNumber>() { new(0x0002, 1000) })); // USD20 cassette CashUnitCounts.Add("PHP5", new(1000, 2000, 1000, 1000, 0, 0, 1000, 0, new List<BankNoteNumber>() { new(0x0003, 1000) })); // USD50 cassette CashUnitCounts.Add("PHP6", new(1000, 2000, 1000, 1000, 0, 0, 1000, 0, new List<BankNoteNumber>() { new(0x0004, 1000) })); // USD100 cassette } return CashUnitCounts; } /// <summary> /// This method is called after device operation is completed involving cash movement /// Return false if the device doesn't support handware sensor to detect cash unit status. /// The framework will use decide the cash unit status from the counts maintained by the framework. /// The key name should be used for the GetCashUnitConfiguration output. /// </summary> public Dictionary<string, CashUnit.StatusEnum> GetCashUnitStatus() { if (CashUnitStatus.Count == 0) { CashUnitStatus.Add("PHP1", CashUnit.StatusEnum.Empty); // Reject cassette CashUnitStatus.Add("PHP2", CashUnit.StatusEnum.Empty); // Retract cassette CashUnitStatus.Add("PHP3", CashUnit.StatusEnum.Ok); // USD10 cassette CashUnitStatus.Add("PHP4", CashUnit.StatusEnum.Ok); // USD20 cassette CashUnitStatus.Add("PHP5", CashUnit.StatusEnum.Ok); // USD50 cassette CashUnitStatus.Add("PHP6", CashUnit.StatusEnum.Ok); // USD100 cassette } return CashUnitStatus; } /// <summary> /// This method is used to adjust information about the status and contents of the cash units present in the CashDispenser or CashAcceptor device. /// </summary> public async Task<SetCashUnitInfoResult> SetCashUnitInfoAsync(ISetCashUnitInfoEvents events, SetCashUnitInfoRequest setCashUnitInfo, CancellationToken cancellation) { await Task.Delay(1000, cancellation); CashUnitConfig.Clear(); CashUnitCounts.Clear(); AllBanknoteIDs.Clear(); CashUnitStatus.Clear(); foreach (var config in setCashUnitInfo.CashUnitConfigurations) { CashUnitConfig.Add(config.Key, new CashUnitConfiguration(config.Value.Type.Value, config.Value.CurrencyID, config.Value.Value.Value, config.Value.Maximum.Value, config.Value.AppLock.Value, config.Value.CashUnitName, config.Value.Minimum.Value, config.Value.PhysicalPositionName, config.Value.UnitID, config.Value.MaximumCapacity.Value, config.Value.HardwareSensor.Value, config.Value.ItemTypes.Value, config.Value.BanknoteIDs)); if (config.Value.BanknoteIDs != null && config.Value.BanknoteIDs.Count > 0) { foreach (var id in config.Value.BanknoteIDs) { if (!AllBanknoteIDs.Contains(id)) AllBanknoteIDs.Add(id); } } } foreach (var count in setCashUnitInfo.CashUnitAccountings) { CashUnitCounts.Add(count.Key, new CashUnitAccounting(count.Value.LogicalCount.Value, count.Value.InitialCount.Value, count.Value.DispensedCount.Value, count.Value.PresentedCount.Value, count.Value.RetractedCount.Value, count.Value.RejectCount.Value, count.Value.Count.Value, count.Value.CashInCount.Value, count.Value.BankNoteNumberList)); } return new SetCashUnitInfoResult(MessagePayload.CompletionCodeEnum.Success); } /// <summary> /// This method unlocks the safe door or starts the timedelay count down prior to unlocking the safe door, /// if the device supports it. The command completes when the door is unlocked or the timer has started. /// </summary> public async Task<UnlockSafeResult> UnlockSafeAsync(CancellationToken cancellation) { await Task.Delay(1000, cancellation); // Unlock the safe door if it is supported, if door is open after unlock, set SafeDoor status // SafeDoorStatus = StatusClass.SafeDoorEnum.DoorOpen; return new UnlockSafeResult(MessagePayload.CompletionCodeEnum.Success); } /// <summary> /// InitiateExchange /// This method is called when the application initiated cash unit exchange by hand /// </summary> public async Task<InitiateExchangeResult> InitiateExchangeAsync(IStartExchangeEvents events, InitiateExchangeRequest exchangeInfo, CancellationToken cancellation) { await Task.Delay(1000, cancellation); // start cash unit exchange return new InitiateExchangeResult(MessagePayload.CompletionCodeEnum.Success); } /// <summary> /// InitiateClearRecyclerRequest /// This method is called when the application initiated to empty recycler units /// </summary> public async Task<InitiateExchangeResult> InitiateExchangeClearRecyclerAsync(IStartExchangeEvents events, InitiateClearRecyclerRequest exchangeInfo, CancellationToken cancellation) { await Task.Delay(1000, cancellation); return new InitiateExchangeResult(MessagePayload.CompletionCodeEnum.UnsupportedCommand, "It is not a recycler"); } /// <summary> /// InitiateExchangeDepositIntoAsync /// This method is called when the application initiated to filling cash into the cash units via cash-in operation. /// Items will be moved from the deposit entrance to the bill cash units. /// </summary> public async Task<InitiateExchangeResult> InitiateExchangeDepositIntoAsync(IStartExchangeEvents events, CancellationToken cancellation) { await Task.Delay(1000, cancellation); return new InitiateExchangeResult(MessagePayload.CompletionCodeEnum.UnsupportedCommand, "It does not have an accetpor device"); } /// <summary> /// CompleteExchangeAsync /// This method will end the exchange state /// </summary> public async Task<CompleteExchangeResult> CompleteExchangeAsync(IEndExchangeEvents events, CompleteExchangeRequest exchangeInfo, CancellationToken cancellation) { await Task.Delay(1000, cancellation); // If safe door can be locked, lock it here // Complete cash unit exchange return new CompleteExchangeResult(MessagePayload.CompletionCodeEnum.Success); } /// <summary> /// This method will cause a vendor dependent sequence of hardware events which will calibrate one or more physical cash units associated with a logical cash unit. /// </summary> public async Task<CalibrateCashUnitResult> CalibrateCashUnitAsync(ICalibrateCashUnitEvents events, CalibrateCashUnitRequest calibrationInfo, CancellationToken cancellation) { await Task.Delay(1000, cancellation); return new CalibrateCashUnitResult(MessagePayload.CompletionCodeEnum.UnsupportedCommand); } public Task<PowerSaveControlCompletion.PayloadData> PowerSaveControl(PowerSaveControlCommand.PayloadData payload) => throw new NotImplementedException(); public Task<SynchronizeCommandCompletion.PayloadData> SynchronizeCommand(SynchronizeCommandCommand.PayloadData payload) => throw new NotImplementedException(); public Task<SetTransactionStateCompletion.PayloadData> SetTransactionState(SetTransactionStateCommand.PayloadData payload) => throw new NotImplementedException(); public GetTransactionStateCompletion.PayloadData GetTransactionState() => throw new NotImplementedException(); public Task<GetCommandRandomNumberResult> GetCommandRandomNumber() => throw new NotImplementedException(); public StatusPropertiesClass.DeviceEnum DeviceStatus { get; private set; } = StatusPropertiesClass.DeviceEnum.Online; public XFS4IoT.Dispenser.StatusClass.IntermediateStackerEnum StackerStatus { get; private set; } = XFS4IoT.Dispenser.StatusClass.IntermediateStackerEnum.Empty; private XFS4IoT.CashManagement.StatusClass.SafeDoorEnum SafeDoorStatus { get; set; } = XFS4IoT.CashManagement.StatusClass.SafeDoorEnum.DoorClosed; private XFS4IoT.CashManagement.StatusClass.DispenserEnum DispenserStatus { get; set; } = XFS4IoT.CashManagement.StatusClass.DispenserEnum.Ok; public OutposClass.ShutterEnum ShutterStatus { get; private set; } = OutposClass.ShutterEnum.Closed; public OutposClass.PositionStatusEnum OutputPositionStatus { get; private set; } = OutposClass.PositionStatusEnum.Empty; public OutposClass.TransportEnum Transport { get; private set; } = OutposClass.TransportEnum.Ok; public OutposClass.TransportStatusEnum TransportStatus { get; private set; } = OutposClass.TransportStatusEnum.Empty; public XFS4IoTServer.IServiceProvider SetServiceProvider { get; set; } = null; private Dictionary<string, ItemMovement> LastDispenseResult = new(); private Dictionary<string, ItemMovement> LastPresentResult = new(); private Dictionary<string, CashUnitConfiguration> CashUnitConfig = new(); private Dictionary<string, CashUnitAccounting> CashUnitCounts = new(); private Dictionary<string, CashUnit.StatusEnum> CashUnitStatus = new(); private List<int> AllBanknoteIDs = new(); private ILogger Logger { get; } private readonly SemaphoreSlim cashTakenSignal = new(0, 1); } }
54.825
306
0.531496
[ "MIT" ]
BridgetKhursheed/KAL_XFS4IoT_SP-Dev-Samples
Devices/SampleCashDispenser/CashDispenserSample.cs
46,055
C#
namespace Automatonymous { using System; public delegate DateTime ScheduleTimeExceptionProvider<in TInstance, in TException>(ConsumeExceptionEventContext<TInstance, TException> context); public delegate DateTime ScheduleTimeExceptionProvider<in TInstance, in TData, in TException>( ConsumeExceptionEventContext<TInstance, TData, TException> context) where TData : class; }
32.076923
150
0.760192
[ "ECL-2.0", "Apache-2.0" ]
Aerodynamite/MassTrans
src/MassTransit/Automatonymous/ScheduleTimeExceptionProvider.cs
417
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("OdeToFood.Data")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Release")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("OdeToFood.Data")] [assembly: System.Reflection.AssemblyTitleAttribute("OdeToFood.Data")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.416667
80
0.648893
[ "MIT" ]
Mlira02/CSharpFoodProj
OdeToFood/OdeToFood.Data/obj/Release/netcoreapp3.1/OdeToFood.Data.AssemblyInfo.cs
994
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Net.WebSockets; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace WatsonWebsocket { /// <summary> /// Watson Websocket server. /// </summary> public class WatsonWsServer : IDisposable { #region Public-Members /// <summary> /// Determine if the server is listening for new connections. /// </summary> public bool IsListening { get { if (_Listener != null) { return _Listener.IsListening; } return false; } } /// <summary> /// Event fired when a client connects. /// </summary> public event EventHandler<ClientConnectedEventArgs> ClientConnected; /// <summary> /// Event fired when a client disconnects. /// </summary> public event EventHandler<ClientDisconnectedEventArgs> ClientDisconnected; /// <summary> /// Event fired when the server stops. /// </summary> public event EventHandler ServerStopped; /// <summary> /// Event fired when a message is received. /// </summary> public event EventHandler<MessageReceivedEventArgs> MessageReceived; /// <summary> /// Indicate whether or not invalid or otherwise unverifiable certificates should be accepted. Default is true. /// </summary> public bool AcceptInvalidCertificates { get { return _AcceptInvalidCertificates; } set { _AcceptInvalidCertificates = value; } } /// <summary> /// Specify the IP addresses that are allowed to connect. If none are supplied, all IP addresses are permitted. /// </summary> public List<string> PermittedIpAddresses = new List<string>(); /// <summary> /// Method to invoke when sending a log message. /// </summary> public Action<string> Logger = null; /// <summary> /// Method to invoke when receiving a raw (non-websocket) HTTP request. /// </summary> public Action<HttpListenerContext> HttpHandler = null; /// <summary> /// Statistics. /// </summary> public Statistics Stats { get { return _Stats; } } #endregion #region Private-Members private string _Header = "[WatsonWsServer] "; private bool _AcceptInvalidCertificates = true; private string _ListenerPrefix; private HttpListener _Listener; private readonly object _PermittedIpsLock = new object(); private ConcurrentDictionary<string, ClientMetadata> _Clients; private CancellationTokenSource _TokenSource; private CancellationToken _Token; private Task _AcceptConnectionsTask; private Statistics _Stats = new Statistics(); #endregion #region Constructors-and-Factories /// <summary> /// Initializes the Watson websocket server. /// Be sure to call 'Start()' to start the server. /// </summary> /// <param name="listenerIp">The IP address upon which to listen.</param> /// <param name="listenerPort">The TCP port upon which to listen.</param> /// <param name="ssl">Enable or disable SSL.</param> public WatsonWsServer( string listenerIp, int listenerPort, bool ssl) { if (listenerPort < 0) throw new ArgumentOutOfRangeException(nameof(listenerPort)); string host; if (String.IsNullOrEmpty(listenerIp)) { host = IPAddress.Loopback.ToString(); } else if (listenerIp == "*" || listenerIp == "+") { host = listenerIp; } else { if (!IPAddress.TryParse(listenerIp, out _)) { var dnsLookup = Dns.GetHostEntry(listenerIp); if (dnsLookup.AddressList.Length > 0) { host = dnsLookup.AddressList.First().ToString(); } else { throw new ArgumentException("Cannot resolve address to IP."); } } else { host = listenerIp; } } if (ssl) _ListenerPrefix = "https://" + host + ":" + listenerPort + "/"; else _ListenerPrefix = "http://" + host + ":" + listenerPort + "/"; _Listener = new HttpListener(); _Listener.Prefixes.Add(_ListenerPrefix); _TokenSource = new CancellationTokenSource(); _Token = _TokenSource.Token; _Clients = new ConcurrentDictionary<string, ClientMetadata>(); } /// <summary> /// Initializes the Watson websocket server. /// Be sure to call 'Start()' to start the server. /// </summary> /// <param name="uri">The URI on which you wish to listen, i.e. http://localhost:9090.</param> public WatsonWsServer(Uri uri) { if (uri == null) throw new ArgumentNullException(nameof(uri)); if (uri.Port < 0) throw new ArgumentException("Port must be zero or greater."); string host; if (!IPAddress.TryParse(uri.Host, out _)) { var dnsLookup = Dns.GetHostEntry(uri.Host); if (dnsLookup.AddressList.Length > 0) { host = dnsLookup.AddressList.First().ToString(); } else { throw new ArgumentException("Cannot resolve address to IP."); } } else { host = uri.Host; } var listenerUri = new UriBuilder(uri) { Host = host }; _ListenerPrefix = listenerUri.ToString(); _Listener = new HttpListener(); _Listener.Prefixes.Add(_ListenerPrefix); _TokenSource = new CancellationTokenSource(); _Token = _TokenSource.Token; _Clients = new ConcurrentDictionary<string, ClientMetadata>(); } #endregion #region Public-Methods /// <summary> /// Tear down the server and dispose of background workers. /// </summary> public void Dispose() { Dispose(true); } /// <summary> /// Start accepting new connections. /// </summary> public void Start() { if (IsListening) throw new InvalidOperationException("Watson websocket server is already running."); _Stats = new Statistics(); Logger?.Invoke(_Header + "starting " + _ListenerPrefix); if (_AcceptInvalidCertificates) ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; _TokenSource = new CancellationTokenSource(); _Token = _TokenSource.Token; _AcceptConnectionsTask = Task.Run(AcceptConnections, _Token); } /// <summary> /// Stop accepting new connections. /// </summary> public void Stop() { if (!IsListening) throw new InvalidOperationException("Watson websocket server is not running."); Logger?.Invoke(_Header + "stopping " + _ListenerPrefix); _Listener.Stop(); } /// <summary> /// Send text data to the specified client, asynchronously. /// </summary> /// <param name="ipPort">IP:port of the recipient client.</param> /// <param name="data">String containing data.</param> /// <param name="token">Cancellation token allowing for termination of this request.</param> /// <returns>Task with Boolean indicating if the message was sent successfully.</returns> public Task<bool> SendAsync(string ipPort, string data, CancellationToken token = default) { if (String.IsNullOrEmpty(data)) throw new ArgumentNullException(nameof(data)); if (!_Clients.TryGetValue(ipPort, out ClientMetadata client)) { Logger?.Invoke(_Header + "unable to find client " + ipPort); return Task.FromResult(false); } return MessageWriteAsync(client, Encoding.UTF8.GetBytes(data), WebSocketMessageType.Text, token); } /// <summary> /// Send binary data to the specified client, asynchronously. /// </summary> /// <param name="ipPort">IP:port of the recipient client.</param> /// <param name="data">Byte array containing data.</param> /// <param name="token">Cancellation token allowing for termination of this request.</param> /// <returns>Task with Boolean indicating if the message was sent successfully.</returns> public Task<bool> SendAsync(string ipPort, byte[] data, CancellationToken token = default) { if (data == null || data.Length < 1) throw new ArgumentNullException(nameof(data)); if (!_Clients.TryGetValue(ipPort, out ClientMetadata client)) { Logger?.Invoke(_Header + "unable to find client " + ipPort); return Task.FromResult(false); } return MessageWriteAsync(client, data, WebSocketMessageType.Binary, token); } /// <summary> /// Send binary data to the specified client, asynchronously. /// </summary> /// <param name="ipPort">IP:port of the recipient client.</param> /// <param name="data">Byte array containing data.</param> /// <param name="msgType">Web socket message type.</param> /// <param name="token">Cancellation token allowing for termination of this request.</param> /// <returns>Task with Boolean indicating if the message was sent successfully.</returns> public Task<bool> SendAsync(string ipPort, byte[] data, WebSocketMessageType msgType, CancellationToken token = default) { if (data == null || data.Length < 1) throw new ArgumentNullException(nameof(data)); if (!_Clients.TryGetValue(ipPort, out ClientMetadata client)) { Logger?.Invoke(_Header + "unable to find client " + ipPort); return Task.FromResult(false); } return MessageWriteAsync(client, data, msgType, token); } /// <summary> /// Determine whether or not the specified client is connected to the server. /// </summary> /// <param name="ipPort">IP:port of the recipient client.</param> /// <returns>Boolean indicating if the client is connected to the server.</returns> public bool IsClientConnected(string ipPort) { return _Clients.TryGetValue(ipPort, out _); } /// <summary> /// List the IP:port of each connected client. /// </summary> /// <returns>A string list containing each client IP:port.</returns> public IEnumerable<string> ListClients() { return _Clients.Keys.ToArray(); } /// <summary> /// Forcefully disconnect a client. /// </summary> /// <param name="ipPort">IP:port of the client.</param> public void DisconnectClient(string ipPort) { // force disconnect of client if (_Clients.TryGetValue(ipPort, out var client)) { client.Ws.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", client.TokenSource.Token).Wait(); // client.Ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", client.TokenSource.Token).Wait(); client.TokenSource.Cancel(); } } /// <summary> /// Retrieve the awaiter. /// </summary> /// <returns>TaskAwaiter.</returns> public TaskAwaiter GetAwaiter() { return _AcceptConnectionsTask.GetAwaiter(); } #endregion #region Private-Methods /// <summary> /// Tear down the server and dispose of background workers. /// </summary> /// <param name="disposing">Disposing.</param> protected virtual void Dispose(bool disposing) { if (disposing) { if (_Clients != null) { foreach (KeyValuePair<string, ClientMetadata> client in _Clients) { client.Value.Ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", client.Value.TokenSource.Token); client.Value.TokenSource.Cancel(); } } if (_Listener != null) { if (_Listener.IsListening) _Listener.Stop(); _Listener.Close(); } _TokenSource.Cancel(); } } private async Task AcceptConnections() { try { _Listener.Start(); while (true) { if (_Token.IsCancellationRequested) break; if (!_Listener.IsListening) { Task.Delay(100).Wait(); continue; } HttpListenerContext ctx = await _Listener.GetContextAsync().ConfigureAwait(false); string ip = ctx.Request.RemoteEndPoint.Address.ToString(); int port = ctx.Request.RemoteEndPoint.Port; string ipPort = ip + ":" + port; lock (_PermittedIpsLock) { if (PermittedIpAddresses != null && PermittedIpAddresses.Count > 0 && !PermittedIpAddresses.Contains(ip)) { Logger?.Invoke(_Header + "rejecting " + ipPort + " (not permitted)"); ctx.Response.StatusCode = 401; ctx.Response.Close(); continue; } } if (!ctx.Request.IsWebSocketRequest) { if (HttpHandler == null) { Logger?.Invoke(_Header + "non-websocket request rejected from " + ipPort); ctx.Response.StatusCode = 400; ctx.Response.Close(); } else { Logger?.Invoke(_Header + "non-websocket request from " + ipPort + " HTTP-forwarded: " + ctx.Request.HttpMethod.ToString() + " " + ctx.Request.RawUrl); HttpHandler.Invoke(ctx); } continue; } else { /* HttpListenerRequest req = ctx.Request; Console.WriteLine(Environment.NewLine + req.HttpMethod.ToString() + " " + req.RawUrl); if (req.Headers != null && req.Headers.Count > 0) { Console.WriteLine("Headers:"); var items = req.Headers.AllKeys.SelectMany(req.Headers.GetValues, (k, v) => new { key = k, value = v }); foreach (var item in items) { Console.WriteLine(" {0}: {1}", item.key, item.value); } } */ } await Task.Run(() => { Logger?.Invoke(_Header + "starting data receiver for " + ipPort); CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; Task.Run(async () => { WebSocketContext wsContext = await ctx.AcceptWebSocketAsync(subProtocol: null); WebSocket ws = wsContext.WebSocket; ClientMetadata md = new ClientMetadata(ctx, ws, wsContext, tokenSource); _Clients.TryAdd(md.IpPort, md); ClientConnected?.Invoke(this, new ClientConnectedEventArgs(md.IpPort, ctx.Request)); await Task.Run(() => DataReceiver(md), token); }, token); }, _Token).ConfigureAwait(false); } } catch (HttpListenerException) { // thrown when disposed } catch (TaskCanceledException) { // thrown when disposed } catch (OperationCanceledException) { // thrown when disposed } catch (ObjectDisposedException) { // thrown when disposed } catch (Exception e) { Logger?.Invoke(_Header + "listener exception:" + Environment.NewLine + e.ToString()); } finally { ServerStopped?.Invoke(this, EventArgs.Empty); } } private async Task DataReceiver(ClientMetadata md) { string header = "[WatsonWsServer " + md.IpPort + "] "; Logger?.Invoke(header + "starting data receiver"); try { while (true) { MessageReceivedEventArgs msg = await MessageReadAsync(md).ConfigureAwait(false); if (msg != null) { _Stats.IncrementReceivedMessages(); _Stats.AddReceivedBytes(msg.Data.Length); if (msg.Data != null) { Task unawaited = Task.Run(() => MessageReceived?.Invoke(this, msg), md.TokenSource.Token); } else { await Task.Delay(10).ConfigureAwait(false); } } } } catch (TaskCanceledException) { // thrown when disposed } catch (OperationCanceledException) { // thrown when disposed } catch (WebSocketException) { // thrown by MessageReadAsync } catch (Exception e) { Logger?.Invoke(header + "exception: " + Environment.NewLine + e.ToString()); } finally { string ipPort = md.IpPort; ClientDisconnected?.Invoke(this, new ClientDisconnectedEventArgs(md.IpPort)); md.Ws.Dispose(); Logger?.Invoke(header + "disconnected"); _Clients.TryRemove(ipPort, out _); } } private async Task<MessageReceivedEventArgs> MessageReadAsync(ClientMetadata md) { string header = "[WatsonWsServer " + md.IpPort + "] "; using (MemoryStream stream = new MemoryStream()) { byte[] buffer = new byte[65536]; ArraySegment<byte> seg = new ArraySegment<byte>(buffer); while (true) { WebSocketReceiveResult result = await md.Ws.ReceiveAsync(seg, md.TokenSource.Token).ConfigureAwait(false); /* Console.WriteLine("Websocket state : " + md.Ws.State); Console.WriteLine("Close status : " + result.CloseStatus); Console.WriteLine("Message type : " + result.MessageType); */ if (result.CloseStatus != null) { Logger?.Invoke(header + "close received"); await md.Ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); throw new WebSocketException("Websocket closed."); } if (md.Ws.State != WebSocketState.Open) { Logger?.Invoke(header + "websocket no longer open"); throw new WebSocketException("Websocket closed."); } if (md.TokenSource.Token.IsCancellationRequested) { Logger?.Invoke(header + "cancel requested"); } if (result.Count > 0) { stream.Write(buffer, 0, result.Count); } if (result.EndOfMessage) { return new MessageReceivedEventArgs(md.IpPort, stream.ToArray(), result.MessageType); } } } } private async Task<bool> MessageWriteAsync(ClientMetadata md, byte[] data, WebSocketMessageType msgType, CancellationToken token) { string header = "[WatsonWsServer " + md.IpPort + "] "; CancellationToken[] tokens = new CancellationToken[3]; tokens[0] = _Token; tokens[1] = token; tokens[2] = md.TokenSource.Token; using (CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(tokens)) { try { #region Send-Message await md.SendLock.WaitAsync(md.TokenSource.Token).ConfigureAwait(false); try { await md.Ws.SendAsync(new ArraySegment<byte>(data, 0, data.Length), msgType, true, linkedCts.Token).ConfigureAwait(false); } finally { md.SendLock.Release(); } _Stats.IncrementSentMessages(); _Stats.AddSentBytes(data.Length); return true; #endregion } catch (TaskCanceledException) { if (_Token.IsCancellationRequested) { Logger?.Invoke(header + "server canceled"); } else if (token.IsCancellationRequested) { Logger?.Invoke(header + "message send canceled"); } else if (md.TokenSource.Token.IsCancellationRequested) { Logger?.Invoke(header + "client canceled"); } } catch (OperationCanceledException) { if (_Token.IsCancellationRequested) { Logger?.Invoke(header + "canceled"); } else if (token.IsCancellationRequested) { Logger?.Invoke(header + "message send canceled"); } else if (md.TokenSource.Token.IsCancellationRequested) { Logger?.Invoke(header + "client canceled"); } } catch (ObjectDisposedException) { Logger?.Invoke(header + "disposed"); } catch (WebSocketException) { Logger?.Invoke(header + "websocket disconnected"); } catch (SocketException) { Logger?.Invoke(header + "socket disconnected"); } catch (InvalidOperationException) { Logger?.Invoke(header + "disconnected due to invalid operation"); } catch (IOException) { Logger?.Invoke(header + "IO disconnected"); } catch (Exception e) { Logger?.Invoke(header + "exception: " + Environment.NewLine + e.ToString()); } } return false; } #endregion } }
36.585816
178
0.487497
[ "MIT" ]
tersers/WatsonWebsocket
WatsonWebsocket/WatsonWsServer.cs
25,795
C#
// Copyright (c) Josef Pihrt and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Data; namespace Roslynator.VisualStudio { public partial class BaseOptionsPageControl : UserControl { private GridViewColumnHeader _lastClickedHeader; private ListSortDirection _lastDirection; public BaseOptionsPageControl() { InitializeComponent(); DataContext = this; } public string NameColumnHeaderText { get; set; } = "Id"; public string TitleColumnHeaderText { get; set; } = "Title"; public string CheckBoxColumnHeaderText { get; set; } = "Enabled"; public string Comment { get; set; } public ListSortDirection DefaultSortDirection { get; set; } = ListSortDirection.Descending; public ObservableCollection<BaseModel> Items { get; } = new(); private void GridViewColumnHeader_Click(object sender, RoutedEventArgs e) { if (e.OriginalSource is not GridViewColumnHeader clickedHeader) return; if (clickedHeader.Role == GridViewColumnHeaderRole.Padding) return; ListSortDirection direction; if (clickedHeader != _lastClickedHeader) { direction = ListSortDirection.Ascending; } else if (_lastDirection == ListSortDirection.Ascending) { direction = ListSortDirection.Descending; } else { direction = ListSortDirection.Ascending; } Sort(clickedHeader, direction); } private void Sort(GridViewColumnHeader columnHeader, ListSortDirection direction) { ICollectionView dataView = CollectionViewSource.GetDefaultView(lsvItems.ItemsSource); SortDescriptionCollection sortDescriptions = dataView.SortDescriptions; sortDescriptions.Clear(); if (columnHeader == checkBoxGridViewColumnHeader) { sortDescriptions.Add(new SortDescription("Enabled", direction)); sortDescriptions.Add(new SortDescription("Id", ListSortDirection.Ascending)); } else { string propertyName = columnHeader.Content.ToString(); if (propertyName != "Id") propertyName = "Title"; sortDescriptions.Add(new SortDescription(propertyName, direction)); } dataView.Refresh(); if (direction == ListSortDirection.Ascending) { columnHeader.Column.HeaderTemplate = Resources["gridViewHeaderArrowUpTemplate"] as DataTemplate; } else { columnHeader.Column.HeaderTemplate = Resources["gridViewHeaderArrowDownTemplate"] as DataTemplate; } if (_lastClickedHeader != null && _lastClickedHeader != columnHeader) { _lastClickedHeader.Column.HeaderTemplate = null; } _lastClickedHeader = columnHeader; _lastDirection = direction; } private bool FilterItems(object item) { string s = tbxFilter.Text; if (!string.IsNullOrWhiteSpace(s)) { s = s.Trim(); var model = (BaseModel)item; return model.Id.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) != -1 || model.Title.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) != -1; } return true; } private void EnableDisableAllButton_Click(object sender, RoutedEventArgs e) { if (Items.All(f => f.Enabled == null)) { SetAll(false); } else if (Items.All(f => f.Enabled == false)) { SetAll(true); } else { SetAll(null); } void SetAll(bool? value) { foreach (BaseModel model in Items) model.Enabled = value; } } private void FilterTextBox_TextChanged(object sender, TextChangedEventArgs e) { var view = (CollectionView)CollectionViewSource.GetDefaultView(lsvItems.ItemsSource); view.Filter ??= f => FilterItems(f); view.Refresh(); } private void ListView_Loaded(object sender, RoutedEventArgs e) { if (_lastClickedHeader == null) Sort(checkBoxGridViewColumnHeader, DefaultSortDirection); } } }
30.987578
156
0.576067
[ "Apache-2.0" ]
ProphetLamb-Organistion/Roslynator
src/VisualStudio/BaseOptionsPageControl.xaml.cs
4,991
C#
using NUnit.Framework; using Playnite; using Playnite.Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Playnite.Tests.Settings { [TestFixture] public class FilterSettingsTests { [Test] public void ShouldSerializeTest() { var settings = new FilterSettings(); var json = Serialization.ToJson(settings); StringAssert.DoesNotContain(nameof(FilterSettings.Name), json); StringAssert.DoesNotContain(nameof(FilterSettings.Series), json); StringAssert.DoesNotContain(nameof(FilterSettings.Source), json); StringAssert.DoesNotContain(nameof(FilterSettings.AgeRating), json); StringAssert.DoesNotContain(nameof(FilterSettings.Region), json); StringAssert.DoesNotContain(nameof(FilterSettings.Genre), json); StringAssert.DoesNotContain(nameof(FilterSettings.Publisher), json); StringAssert.DoesNotContain(nameof(FilterSettings.Developer), json); StringAssert.DoesNotContain(nameof(FilterSettings.Category), json); StringAssert.DoesNotContain(nameof(FilterSettings.Tag), json); StringAssert.DoesNotContain(nameof(FilterSettings.Platform), json); StringAssert.DoesNotContain(nameof(FilterSettings.Library), json); settings.Name = "test"; settings.Series = new FilterItemProperites() { Text = "test" }; settings.Source = new FilterItemProperites() { Text = "test" }; settings.AgeRating = new FilterItemProperites() { Text = "test" }; settings.Region = new FilterItemProperites() { Text = "test" }; settings.Genre = new FilterItemProperites() { Text = "test" }; settings.Publisher = new FilterItemProperites() { Text = "test" }; settings.Developer = new FilterItemProperites() { Text = "test" }; settings.Category = new FilterItemProperites() { Text = "test" }; settings.Tag = new FilterItemProperites() { Text = "test" }; settings.Platform = new FilterItemProperites() { Text = "test" }; settings.Library = new FilterItemProperites() { Text = "test" }; json = Serialization.ToJson(settings); StringAssert.Contains(nameof(FilterSettings.Name), json); StringAssert.Contains(nameof(FilterSettings.Series), json); StringAssert.Contains(nameof(FilterSettings.Source), json); StringAssert.Contains(nameof(FilterSettings.AgeRating), json); StringAssert.Contains(nameof(FilterSettings.Region), json); StringAssert.Contains(nameof(FilterSettings.Genre), json); StringAssert.Contains(nameof(FilterSettings.Publisher), json); StringAssert.Contains(nameof(FilterSettings.Developer), json); StringAssert.Contains(nameof(FilterSettings.Category), json); StringAssert.Contains(nameof(FilterSettings.Tag), json); StringAssert.Contains(nameof(FilterSettings.Platform), json); StringAssert.Contains(nameof(FilterSettings.Library), json); } } }
52.063492
81
0.656098
[ "MIT" ]
Bobsans/Playnite
source/Tests/Playnite.Tests/Settings/FilterSettingsTests.cs
3,282
C#
namespace MBBSDASM.Analysis.Artifacts { public class TrackedVariable { public ushort Segment { get; set; } public ulong Offset { get; set; } public ushort Address { get; set; } public string Name { get; set; } public string Comment { get; set; } } }
27.454545
43
0.596026
[ "BSD-2-Clause" ]
enusbaum/MBBSDASM
MBBSDASM/Analysis/Artifacts/TrackedVariable.cs
304
C#
using System.Threading; using log4net; namespace ACTransit.CusRel.ServiceHost.Tasks { public class Cancellation { private readonly CancellationTokenSource TokenSource; private static readonly ILog log = LogManager.GetLogger(nameof(Cancellation)); public CancellationToken Token; public Cancellation() { TokenSource = new CancellationTokenSource(); Token = TokenSource.Token; } public bool IsCancelled => TokenSource.IsCancellationRequested; public void Cancel() { log.Debug("Begin TokenSource.Cancel"); TokenSource.Cancel(); log.Debug("End TokenSource.Cancel"); } } }
26.857143
87
0.610372
[ "MIT" ]
actransitorg/ACTransit.CusRel
CusRel/ACTransit.CusRel.ServiceHost/Tasks/Cancellation.cs
754
C#
using System.Diagnostics; using WireC.Common; namespace WireC.AST.TypeSignatures { public class TypeName : ITypeSignature { public TypeName(string name, SourceSpan span) { Name = name; Span = span; } public string Name { get; } public SourceSpan Span { get; } public T Accept<T>(ITypeSignatureVisitor<T> visitor) => visitor.VisitTypeName(this); public static TypeName FromToken(Token token) { Debug.Assert(token.Kind == TokenKind.Identifier); return new TypeName(token.Lexeme, token.Span); } public override string ToString() => Name; } }
23.655172
92
0.600583
[ "MIT" ]
Daouki/wire
WireC.AST/TypeSignatures/TypeName.cs
688
C#
using System; using System.Xml.Serialization; namespace Alipay.AopSdk.Core.Domain { /// <summary> /// RegionInfo Data Structure. /// </summary> [Serializable] public class RegionInfo : AopObject { /// <summary> /// 地址所属区代码 /// </summary> [XmlElement("area_code")] public string AreaCode { get; set; } /// <summary> /// 地址所属区名称 /// </summary> [XmlElement("area_name")] public string AreaName { get; set; } /// <summary> /// 地址所属市代码 /// </summary> [XmlElement("city_code")] public string CityCode { get; set; } /// <summary> /// 地址所属市名称 /// </summary> [XmlElement("city_name")] public string CityName { get; set; } /// <summary> /// 地址所属省份代码 /// </summary> [XmlElement("province_code")] public string ProvinceCode { get; set; } /// <summary> /// 地址所属省份名称 /// </summary> [XmlElement("province_name")] public string ProvinceName { get; set; } } }
22.795918
48
0.503133
[ "MIT" ]
leixf2005/Alipay.AopSdk.Core
Alipay.AopSdk.Core/Domain/RegionInfo.cs
1,205
C#
using Lucene.Net.Analysis.Core; using Lucene.Net.Analysis.Miscellaneous; using Lucene.Net.Analysis.Snowball; using Lucene.Net.Analysis.Standard; using Lucene.Net.Analysis.Util; using Lucene.Net.Support; using Lucene.Net.Util; using System; using System.IO; using System.Text; namespace Lucene.Net.Analysis.Fr { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// <see cref="Analyzer"/> for French language. /// <para> /// Supports an external list of stopwords (words that /// will not be indexed at all) and an external list of exclusions (word that will /// not be stemmed, but indexed). /// A default set of stopwords is used unless an alternative list is specified, but the /// exclusion list is empty by default. /// </para> /// <para>You must specify the required <see cref="LuceneVersion"/> /// compatibility when creating FrenchAnalyzer: /// <list type="bullet"> /// <item><description> As of 3.6, <see cref="FrenchLightStemFilter"/> is used for less aggressive stemming.</description></item> /// <item><description> As of 3.1, Snowball stemming is done with <see cref="SnowballFilter"/>, /// <see cref="LowerCaseFilter"/> is used prior to <see cref="StopFilter"/>, and <see cref="ElisionFilter"/> and /// Snowball stopwords are used by default.</description></item> /// <item><description> As of 2.9, <see cref="StopFilter"/> preserves position /// increments</description></item> /// </list> /// /// </para> /// <para><b>NOTE</b>: This class uses the same <see cref="LuceneVersion"/> /// dependent settings as <see cref="StandardAnalyzer"/>.</para> /// </summary> public sealed class FrenchAnalyzer : StopwordAnalyzerBase { /// <summary> /// Extended list of typical French stopwords. </summary> /// @deprecated (3.1) remove in Lucene 5.0 (index bw compat) [Obsolete("(3.1) remove in Lucene 5.0 (index bw compat)")] private static readonly string[] FRENCH_STOP_WORDS = new string[] { "a", "afin", "ai", "ainsi", "après", "attendu", "au", "aujourd", "auquel", "aussi", "autre", "autres", "aux", "auxquelles", "auxquels", "avait", "avant", "avec", "avoir", "c", "car", "ce", "ceci", "cela", "celle", "celles", "celui", "cependant", "certain", "certaine", "certaines", "certains", "ces", "cet", "cette", "ceux", "chez", "ci", "combien", "comme", "comment", "concernant", "contre", "d", "dans", "de", "debout", "dedans", "dehors", "delà", "depuis", "derrière", "des", "désormais", "desquelles", "desquels", "dessous", "dessus", "devant", "devers", "devra", "divers", "diverse", "diverses", "doit", "donc", "dont", "du", "duquel", "durant", "dès", "elle", "elles", "en", "entre", "environ", "est", "et", "etc", "etre", "eu", "eux", "excepté", "hormis", "hors", "hélas", "hui", "il", "ils", "j", "je", "jusqu", "jusque", "l", "la", "laquelle", "le", "lequel", "les", "lesquelles", "lesquels", "leur", "leurs", "lorsque", "lui", "là", "ma", "mais", "malgré", "me", "merci", "mes", "mien", "mienne", "miennes", "miens", "moi", "moins", "mon", "moyennant", "même", "mêmes", "n", "ne", "ni", "non", "nos", "notre", "nous", "néanmoins", "nôtre", "nôtres", "on", "ont", "ou", "outre", "où", "par", "parmi", "partant", "pas", "passé", "pendant", "plein", "plus", "plusieurs", "pour", "pourquoi", "proche", "près", "puisque", "qu", "quand", "que", "quel", "quelle", "quelles", "quels", "qui", "quoi", "quoique", "revoici", "revoilà", "s", "sa", "sans", "sauf", "se", "selon", "seront", "ses", "si", "sien", "sienne", "siennes", "siens", "sinon", "soi", "soit", "son", "sont", "sous", "suivant", "sur", "ta", "te", "tes", "tien", "tienne", "tiennes", "tiens", "toi", "ton", "tous", "tout", "toute", "toutes", "tu", "un", "une", "va", "vers", "voici", "voilà", "vos", "votre", "vous", "vu", "vôtre", "vôtres", "y", "à", "ça", "ès", "été", "être", "ô" }; /// <summary> /// File containing default French stopwords. </summary> public const string DEFAULT_STOPWORD_FILE = "french_stop.txt"; /// <summary> /// Default set of articles for <see cref="ElisionFilter"/> </summary> public static readonly CharArraySet DEFAULT_ARTICLES = CharArraySet.UnmodifiableSet(new CharArraySet( #pragma warning disable 612, 618 LuceneVersion.LUCENE_CURRENT, #pragma warning restore 612, 618 new string[] { "l", "m", "t", "qu", "n", "s", "j", "d", "c", "jusqu", "quoiqu", "lorsqu", "puisqu" }, true)); /// <summary> /// Contains words that should be indexed but not stemmed. /// </summary> private readonly CharArraySet excltable; /// <summary> /// Returns an unmodifiable instance of the default stop-words set. </summary> /// <returns> an unmodifiable instance of the default stop-words set. </returns> public static CharArraySet DefaultStopSet { get { return DefaultSetHolder.DEFAULT_STOP_SET; } } private class DefaultSetHolder { /// @deprecated (3.1) remove this in Lucene 5.0, index bw compat [Obsolete("(3.1) remove this in Lucene 5.0, index bw compat")] internal static readonly CharArraySet DEFAULT_STOP_SET_30 = CharArraySet.UnmodifiableSet(new CharArraySet(LuceneVersion.LUCENE_CURRENT, Arrays.AsList(FRENCH_STOP_WORDS), false)); internal static readonly CharArraySet DEFAULT_STOP_SET; static DefaultSetHolder() { try { DEFAULT_STOP_SET = WordlistLoader.GetSnowballWordSet( IOUtils.GetDecodingReader(typeof(SnowballFilter), DEFAULT_STOPWORD_FILE, Encoding.UTF8), #pragma warning disable 612, 618 LuceneVersion.LUCENE_CURRENT); #pragma warning restore 612, 618 } catch (IOException) { // default set should always be present as it is part of the // distribution (JAR) throw new Exception("Unable to load default stopword set"); } } } /// <summary> /// Builds an analyzer with the default stop words (<see cref="DefaultStopSet"/>). /// </summary> public FrenchAnalyzer(LuceneVersion matchVersion) #pragma warning disable 612, 618 : this(matchVersion, matchVersion.OnOrAfter(LuceneVersion.LUCENE_31) ? DefaultSetHolder.DEFAULT_STOP_SET : DefaultSetHolder.DEFAULT_STOP_SET_30) #pragma warning restore 612, 618 { } /// <summary> /// Builds an analyzer with the given stop words /// </summary> /// <param name="matchVersion"> /// lucene compatibility version </param> /// <param name="stopwords"> /// a stopword set </param> public FrenchAnalyzer(LuceneVersion matchVersion, CharArraySet stopwords) : this(matchVersion, stopwords, CharArraySet.EMPTY_SET) { } /// <summary> /// Builds an analyzer with the given stop words /// </summary> /// <param name="matchVersion"> /// lucene compatibility version </param> /// <param name="stopwords"> /// a stopword set </param> /// <param name="stemExclutionSet"> /// a stemming exclusion set </param> public FrenchAnalyzer(LuceneVersion matchVersion, CharArraySet stopwords, CharArraySet stemExclutionSet) : base(matchVersion, stopwords) { this.excltable = CharArraySet.UnmodifiableSet(CharArraySet.Copy(matchVersion, stemExclutionSet)); } /// <summary> /// Creates /// <see cref="TokenStreamComponents"/> /// used to tokenize all the text in the provided <see cref="TextReader"/>. /// </summary> /// <returns> <see cref="TokenStreamComponents"/> /// built from a <see cref="StandardTokenizer"/> filtered with /// <see cref="StandardFilter"/>, <see cref="ElisionFilter"/>, /// <see cref="LowerCaseFilter"/>, <see cref="StopFilter"/>, /// <see cref="SetKeywordMarkerFilter"/> if a stem exclusion set is /// provided, and <see cref="FrenchLightStemFilter"/> </returns> /// protected override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { #pragma warning disable 612, 618 if (m_matchVersion.OnOrAfter(LuceneVersion.LUCENE_31)) #pragma warning restore 612, 618 { Tokenizer source = new StandardTokenizer(m_matchVersion, reader); TokenStream result = new StandardFilter(m_matchVersion, source); result = new ElisionFilter(result, DEFAULT_ARTICLES); result = new LowerCaseFilter(m_matchVersion, result); result = new StopFilter(m_matchVersion, result, m_stopwords); if (excltable.Count > 0) { result = new SetKeywordMarkerFilter(result, excltable); } #pragma warning disable 612, 618 if (m_matchVersion.OnOrAfter(LuceneVersion.LUCENE_36)) #pragma warning restore 612, 618 { result = new FrenchLightStemFilter(result); } else { result = new SnowballFilter(result, new Tartarus.Snowball.Ext.FrenchStemmer()); } return new TokenStreamComponents(source, result); } else { Tokenizer source = new StandardTokenizer(m_matchVersion, reader); TokenStream result = new StandardFilter(m_matchVersion, source); result = new StopFilter(m_matchVersion, result, m_stopwords); if (excltable.Count > 0) { result = new SetKeywordMarkerFilter(result, excltable); } #pragma warning disable 612, 618 result = new FrenchStemFilter(result); #pragma warning restore 612, 618 // Convert to lowercase after stemming! return new TokenStreamComponents(source, new LowerCaseFilter(m_matchVersion, result)); } } } }
49.643777
190
0.582001
[ "Apache-2.0" ]
b9chris/lucenenet
src/Lucene.Net.Analysis.Common/Analysis/Fr/FrenchAnalyzer.cs
11,597
C#
/* Copyright (c) 2006 - 2008 The Open Toolkit library. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Runtime.InteropServices; namespace ShenmueDKSharp { /// <summary> /// Represents a 4x4 matrix containing 3D rotation, scale, transform, and projection with double-precision components. /// </summary> /// <seealso cref="Matrix4"/> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Matrix4d : IEquatable<Matrix4d> { /// <summary> /// Top row of the matrix /// </summary> public Vector4d Row0; /// <summary> /// 2nd row of the matrix /// </summary> public Vector4d Row1; /// <summary> /// 3rd row of the matrix /// </summary> public Vector4d Row2; /// <summary> /// Bottom row of the matrix /// </summary> public Vector4d Row3; /// <summary> /// The identity matrix /// </summary> public static Matrix4d Identity = new Matrix4d(Vector4d .UnitX, Vector4d .UnitY, Vector4d .UnitZ, Vector4d .UnitW); /// <summary> /// Constructs a new instance. /// </summary> /// <param name="row0">Top row of the matrix</param> /// <param name="row1">Second row of the matrix</param> /// <param name="row2">Third row of the matrix</param> /// <param name="row3">Bottom row of the matrix</param> public Matrix4d(Vector4d row0, Vector4d row1, Vector4d row2, Vector4d row3) { Row0 = row0; Row1 = row1; Row2 = row2; Row3 = row3; } /// <summary> /// Constructs a new instance. /// </summary> /// <param name="m00">First item of the first row.</param> /// <param name="m01">Second item of the first row.</param> /// <param name="m02">Third item of the first row.</param> /// <param name="m03">Fourth item of the first row.</param> /// <param name="m10">First item of the second row.</param> /// <param name="m11">Second item of the second row.</param> /// <param name="m12">Third item of the second row.</param> /// <param name="m13">Fourth item of the second row.</param> /// <param name="m20">First item of the third row.</param> /// <param name="m21">Second item of the third row.</param> /// <param name="m22">Third item of the third row.</param> /// <param name="m23">First item of the third row.</param> /// <param name="m30">Fourth item of the fourth row.</param> /// <param name="m31">Second item of the fourth row.</param> /// <param name="m32">Third item of the fourth row.</param> /// <param name="m33">Fourth item of the fourth row.</param> public Matrix4d( double m00, double m01, double m02, double m03, double m10, double m11, double m12, double m13, double m20, double m21, double m22, double m23, double m30, double m31, double m32, double m33) { Row0 = new Vector4d(m00, m01, m02, m03); Row1 = new Vector4d(m10, m11, m12, m13); Row2 = new Vector4d(m20, m21, m22, m23); Row3 = new Vector4d(m30, m31, m32, m33); } /// <summary> /// Constructs a new instance. /// </summary> /// <param name="topLeft">The top left 3x3 of the matrix.</param> public Matrix4d(Matrix3d topLeft) { Row0.X = topLeft.Row0.X; Row0.Y = topLeft.Row0.Y; Row0.Z = topLeft.Row0.Z; Row0.W = 0; Row1.X = topLeft.Row1.X; Row1.Y = topLeft.Row1.Y; Row1.Z = topLeft.Row1.Z; Row1.W = 0; Row2.X = topLeft.Row2.X; Row2.Y = topLeft.Row2.Y; Row2.Z = topLeft.Row2.Z; Row2.W = 0; Row3.X = 0; Row3.Y = 0; Row3.Z = 0; Row3.W = 1; } /// <summary> /// The determinant of this matrix /// </summary> public double Determinant { get { return Row0.X * Row1.Y * Row2.Z * Row3.W - Row0.X * Row1.Y * Row2.W * Row3.Z + Row0.X * Row1.Z * Row2.W * Row3.Y - Row0.X * Row1.Z * Row2.Y * Row3.W + Row0.X * Row1.W * Row2.Y * Row3.Z - Row0.X * Row1.W * Row2.Z * Row3.Y - Row0.Y * Row1.Z * Row2.W * Row3.X + Row0.Y * Row1.Z * Row2.X * Row3.W - Row0.Y * Row1.W * Row2.X * Row3.Z + Row0.Y * Row1.W * Row2.Z * Row3.X - Row0.Y * Row1.X * Row2.Z * Row3.W + Row0.Y * Row1.X * Row2.W * Row3.Z + Row0.Z * Row1.W * Row2.X * Row3.Y - Row0.Z * Row1.W * Row2.Y * Row3.X + Row0.Z * Row1.X * Row2.Y * Row3.W - Row0.Z * Row1.X * Row2.W * Row3.Y + Row0.Z * Row1.Y * Row2.W * Row3.X - Row0.Z * Row1.Y * Row2.X * Row3.W - Row0.W * Row1.X * Row2.Y * Row3.Z + Row0.W * Row1.X * Row2.Z * Row3.Y - Row0.W * Row1.Y * Row2.Z * Row3.X + Row0.W * Row1.Y * Row2.X * Row3.Z - Row0.W * Row1.Z * Row2.X * Row3.Y + Row0.W * Row1.Z * Row2.Y * Row3.X; } } /// <summary> /// The first column of this matrix /// </summary> public Vector4d Column0 { get { return new Vector4d (Row0.X, Row1.X, Row2.X, Row3.X); } set { Row0.X = value.X; Row1.X = value.Y; Row2.X = value.Z; Row3.X = value.W; } } /// <summary> /// The second column of this matrix /// </summary> public Vector4d Column1 { get { return new Vector4d (Row0.Y, Row1.Y, Row2.Y, Row3.Y); } set { Row0.Y = value.X; Row1.Y = value.Y; Row2.Y = value.Z; Row3.Y = value.W; } } /// <summary> /// The third column of this matrix /// </summary> public Vector4d Column2 { get { return new Vector4d (Row0.Z, Row1.Z, Row2.Z, Row3.Z); } set { Row0.Z = value.X; Row1.Z = value.Y; Row2.Z = value.Z; Row3.Z = value.W; } } /// <summary> /// The fourth column of this matrix /// </summary> public Vector4d Column3 { get { return new Vector4d (Row0.W, Row1.W, Row2.W, Row3.W); } set { Row0.W = value.X; Row1.W = value.Y; Row2.W = value.Z; Row3.W = value.W; } } /// <summary> /// Gets or sets the value at row 1, column 1 of this instance. /// </summary> public double M11 { get { return Row0.X; } set { Row0.X = value; } } /// <summary> /// Gets or sets the value at row 1, column 2 of this instance. /// </summary> public double M12 { get { return Row0.Y; } set { Row0.Y = value; } } /// <summary> /// Gets or sets the value at row 1, column 3 of this instance. /// </summary> public double M13 { get { return Row0.Z; } set { Row0.Z = value; } } /// <summary> /// Gets or sets the value at row 1, column 4 of this instance. /// </summary> public double M14 { get { return Row0.W; } set { Row0.W = value; } } /// <summary> /// Gets or sets the value at row 2, column 1 of this instance. /// </summary> public double M21 { get { return Row1.X; } set { Row1.X = value; } } /// <summary> /// Gets or sets the value at row 2, column 2 of this instance. /// </summary> public double M22 { get { return Row1.Y; } set { Row1.Y = value; } } /// <summary> /// Gets or sets the value at row 2, column 3 of this instance. /// </summary> public double M23 { get { return Row1.Z; } set { Row1.Z = value; } } /// <summary> /// Gets or sets the value at row 2, column 4 of this instance. /// </summary> public double M24 { get { return Row1.W; } set { Row1.W = value; } } /// <summary> /// Gets or sets the value at row 3, column 1 of this instance. /// </summary> public double M31 { get { return Row2.X; } set { Row2.X = value; } } /// <summary> /// Gets or sets the value at row 3, column 2 of this instance. /// </summary> public double M32 { get { return Row2.Y; } set { Row2.Y = value; } } /// <summary> /// Gets or sets the value at row 3, column 3 of this instance. /// </summary> public double M33 { get { return Row2.Z; } set { Row2.Z = value; } } /// <summary> /// Gets or sets the value at row 3, column 4 of this instance. /// </summary> public double M34 { get { return Row2.W; } set { Row2.W = value; } } /// <summary> /// Gets or sets the value at row 4, column 1 of this instance. /// </summary> public double M41 { get { return Row3.X; } set { Row3.X = value; } } /// <summary> /// Gets or sets the value at row 4, column 2 of this instance. /// </summary> public double M42 { get { return Row3.Y; } set { Row3.Y = value; } } /// <summary> /// Gets or sets the value at row 4, column 3 of this instance. /// </summary> public double M43 { get { return Row3.Z; } set { Row3.Z = value; } } /// <summary> /// Gets or sets the value at row 4, column 4 of this instance. /// </summary> public double M44 { get { return Row3.W; } set { Row3.W = value; } } /// <summary> /// Gets or sets the values along the main diagonal of the matrix. /// </summary> public Vector4d Diagonal { get { return new Vector4d(Row0.X, Row1.Y, Row2.Z, Row3.W); } set { Row0.X = value.X; Row1.Y = value.Y; Row2.Z = value.Z; Row3.W = value.W; } } /// <summary> /// Gets the trace of the matrix, the sum of the values along the diagonal. /// </summary> public double Trace { get { return Row0.X + Row1.Y + Row2.Z + Row3.W; } } /// <summary> /// Gets or sets the value at a specified row and column. /// </summary> public double this[int rowIndex, int columnIndex] { get { if (rowIndex == 0) { return Row0[columnIndex]; } else if (rowIndex == 1) { return Row1[columnIndex]; } else if (rowIndex == 2) { return Row2[columnIndex]; } else if (rowIndex == 3) { return Row3[columnIndex]; } throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")"); } set { if (rowIndex == 0) { Row0[columnIndex] = value; } else if (rowIndex == 1) { Row1[columnIndex] = value; } else if (rowIndex == 2) { Row2[columnIndex] = value; } else if (rowIndex == 3) { Row3[columnIndex] = value; } else { throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")"); } } } /// <summary> /// Converts this instance into its inverse. /// </summary> public void Invert() { this = Matrix4d.Invert(this); } /// <summary> /// Converts this instance into its transpose. /// </summary> public void Transpose() { this = Matrix4d.Transpose(this); } /// <summary> /// Returns a normalised copy of this instance. /// </summary> public Matrix4d Normalized() { Matrix4d m = this; m.Normalize(); return m; } /// <summary> /// Divides each element in the Matrix by the <see cref="Determinant"/>. /// </summary> public void Normalize() { var determinant = this.Determinant; Row0 /= determinant; Row1 /= determinant; Row2 /= determinant; Row3 /= determinant; } /// <summary> /// Returns an inverted copy of this instance. /// </summary> public Matrix4d Inverted() { Matrix4d m = this; if (m.Determinant != 0) { m.Invert(); } return m; } /// <summary> /// Returns a copy of this Matrix4d without translation. /// </summary> public Matrix4d ClearTranslation() { Matrix4d m = this; m.Row3.Xyz = Vector3d.Zero; return m; } /// <summary> /// Returns a copy of this Matrix4d without scale. /// </summary> public Matrix4d ClearScale() { Matrix4d m = this; m.Row0.Xyz = m.Row0.Xyz.Normalized(); m.Row1.Xyz = m.Row1.Xyz.Normalized(); m.Row2.Xyz = m.Row2.Xyz.Normalized(); return m; } /// <summary> /// Returns a copy of this Matrix4d without rotation. /// </summary> public Matrix4d ClearRotation() { Matrix4d m = this; m.Row0.Xyz = new Vector3d(m.Row0.Xyz.Length, 0, 0); m.Row1.Xyz = new Vector3d(0, m.Row1.Xyz.Length, 0); m.Row2.Xyz = new Vector3d(0, 0, m.Row2.Xyz.Length); return m; } /// <summary> /// Returns a copy of this Matrix4d without projection. /// </summary> public Matrix4d ClearProjection() { Matrix4d m = this; m.Column3 = Vector4d.Zero; return m; } /// <summary> /// Returns the translation component of this instance. /// </summary> public Vector3d ExtractTranslation() { return Row3.Xyz; } /// <summary> /// Returns the scale component of this instance. /// </summary> public Vector3d ExtractScale() { return new Vector3d(Row0.Xyz.Length, Row1.Xyz.Length, Row2.Xyz.Length); } /// <summary> /// Returns the rotation component of this instance. Quite slow. /// </summary> /// <param name="row_normalise">Whether the method should row-normalise (i.e. remove scale from) the Matrix. Pass false if you know it's already normalised.</param> public Quaterniond ExtractRotation(bool row_normalise = true) { var row0 = Row0.Xyz; var row1 = Row1.Xyz; var row2 = Row2.Xyz; if (row_normalise) { row0 = row0.Normalized(); row1 = row1.Normalized(); row2 = row2.Normalized(); } // code below adapted from Blender Quaterniond q = new Quaterniond(); double trace = 0.25 * (row0[0] + row1[1] + row2[2] + 1.0); if (trace > 0) { double sq = Math.Sqrt(trace); q.W = sq; sq = 1.0 / (4.0 * sq); q.X = (row1[2] - row2[1]) * sq; q.Y = (row2[0] - row0[2]) * sq; q.Z = (row0[1] - row1[0]) * sq; } else if (row0[0] > row1[1] && row0[0] > row2[2]) { double sq = 2.0 * Math.Sqrt(1.0 + row0[0] - row1[1] - row2[2]); q.X = 0.25 * sq; sq = 1.0 / sq; q.W = (row2[1] - row1[2]) * sq; q.Y = (row1[0] + row0[1]) * sq; q.Z = (row2[0] + row0[2]) * sq; } else if (row1[1] > row2[2]) { double sq = 2.0 * Math.Sqrt(1.0 + row1[1] - row0[0] - row2[2]); q.Y = 0.25 * sq; sq = 1.0 / sq; q.W = (row2[0] - row0[2]) * sq; q.X = (row1[0] + row0[1]) * sq; q.Z = (row2[1] + row1[2]) * sq; } else { double sq = 2.0 * Math.Sqrt(1.0 + row2[2] - row0[0] - row1[1]); q.Z = 0.25 * sq; sq = 1.0 / sq; q.W = (row1[0] - row0[1]) * sq; q.X = (row2[0] + row0[2]) * sq; q.Y = (row2[1] + row1[2]) * sq; } q.Normalize(); return q; } /// <summary> /// Returns the projection component of this instance. /// </summary> public Vector4d ExtractProjection() { return Column3; } /// <summary> /// Build a rotation matrix from the specified axis/angle rotation. /// </summary> /// <param name="axis">The axis to rotate about.</param> /// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param> /// <param name="result">A matrix instance.</param> public static void CreateFromAxisAngle(Vector3d axis, double angle, out Matrix4d result) { // normalize and create a local copy of the vector. axis.Normalize(); double axisX = axis.X, axisY = axis.Y, axisZ = axis.Z; // calculate angles double cos = System.Math.Cos(-angle); double sin = System.Math.Sin(-angle); double t = 1.0f - cos; // do the conversion math once double tXX = t * axisX * axisX, tXY = t * axisX * axisY, tXZ = t * axisX * axisZ, tYY = t * axisY * axisY, tYZ = t * axisY * axisZ, tZZ = t * axisZ * axisZ; double sinX = sin * axisX, sinY = sin * axisY, sinZ = sin * axisZ; result.Row0.X = tXX + cos; result.Row0.Y = tXY - sinZ; result.Row0.Z = tXZ + sinY; result.Row0.W = 0; result.Row1.X = tXY + sinZ; result.Row1.Y = tYY + cos; result.Row1.Z = tYZ - sinX; result.Row1.W = 0; result.Row2.X = tXZ - sinY; result.Row2.Y = tYZ + sinX; result.Row2.Z = tZZ + cos; result.Row2.W = 0; result.Row3 = Vector4d.UnitW; } /// <summary> /// Build a rotation matrix from the specified axis/angle rotation. /// </summary> /// <param name="axis">The axis to rotate about.</param> /// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param> /// <returns>A matrix instance.</returns> public static Matrix4d CreateFromAxisAngle(Vector3d axis, double angle) { Matrix4d result; CreateFromAxisAngle(axis, angle, out result); return result; } /// <summary> /// Builds a rotation matrix for a rotation around the x-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix4d instance.</param> public static void CreateRotationX(double angle, out Matrix4d result) { double cos = System.Math.Cos(angle); double sin = System.Math.Sin(angle); result.Row0 = Vector4d.UnitX; result.Row1 = new Vector4d(0, cos, sin, 0); result.Row2 = new Vector4d(0, -sin, cos, 0); result.Row3 = Vector4d.UnitW; } /// <summary> /// Builds a rotation matrix for a rotation around the x-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix4d instance.</returns> public static Matrix4d CreateRotationX(double angle) { Matrix4d result; CreateRotationX(angle, out result); return result; } /// <summary> /// Builds a rotation matrix for a rotation around the y-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix4d instance.</param> public static void CreateRotationY(double angle, out Matrix4d result) { double cos = System.Math.Cos(angle); double sin = System.Math.Sin(angle); result.Row0 = new Vector4d(cos, 0, -sin, 0); result.Row1 = Vector4d.UnitY; result.Row2 = new Vector4d(sin, 0, cos, 0); result.Row3 = Vector4d.UnitW; } /// <summary> /// Builds a rotation matrix for a rotation around the y-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix4d instance.</returns> public static Matrix4d CreateRotationY(double angle) { Matrix4d result; CreateRotationY(angle, out result); return result; } /// <summary> /// Builds a rotation matrix for a rotation around the z-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix4d instance.</param> public static void CreateRotationZ(double angle, out Matrix4d result) { double cos = System.Math.Cos(angle); double sin = System.Math.Sin(angle); result.Row0 = new Vector4d(cos, sin, 0, 0); result.Row1 = new Vector4d(-sin, cos, 0, 0); result.Row2 = Vector4d.UnitZ; result.Row3 = Vector4d.UnitW; } /// <summary> /// Builds a rotation matrix for a rotation around the z-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix4d instance.</returns> public static Matrix4d CreateRotationZ(double angle) { Matrix4d result; CreateRotationZ(angle, out result); return result; } /// <summary> /// Creates a translation matrix. /// </summary> /// <param name="x">X translation.</param> /// <param name="y">Y translation.</param> /// <param name="z">Z translation.</param> /// <param name="result">The resulting Matrix4d instance.</param> public static void CreateTranslation(double x, double y, double z, out Matrix4d result) { result = Identity; result.Row3 = new Vector4d(x, y, z, 1); } /// <summary> /// Creates a translation matrix. /// </summary> /// <param name="vector">The translation vector.</param> /// <param name="result">The resulting Matrix4d instance.</param> public static void CreateTranslation(ref Vector3d vector, out Matrix4d result) { result = Identity; result.Row3 = new Vector4d(vector.X, vector.Y, vector.Z, 1); } /// <summary> /// Creates a translation matrix. /// </summary> /// <param name="x">X translation.</param> /// <param name="y">Y translation.</param> /// <param name="z">Z translation.</param> /// <returns>The resulting Matrix4d instance.</returns> public static Matrix4d CreateTranslation(double x, double y, double z) { Matrix4d result; CreateTranslation(x, y, z, out result); return result; } /// <summary> /// Creates a translation matrix. /// </summary> /// <param name="vector">The translation vector.</param> /// <returns>The resulting Matrix4d instance.</returns> public static Matrix4d CreateTranslation(Vector3d vector) { Matrix4d result; CreateTranslation(vector.X, vector.Y, vector.Z, out result); return result; } /// <summary> /// Creates an orthographic projection matrix. /// </summary> /// <param name="width">The width of the projection volume.</param> /// <param name="height">The height of the projection volume.</param> /// <param name="zNear">The near edge of the projection volume.</param> /// <param name="zFar">The far edge of the projection volume.</param> /// <param name="result">The resulting Matrix4d instance.</param> public static void CreateOrthographic(double width, double height, double zNear, double zFar, out Matrix4d result) { CreateOrthographicOffCenter(-width / 2, width / 2, -height / 2, height / 2, zNear, zFar, out result); } /// <summary> /// Creates an orthographic projection matrix. /// </summary> /// <param name="width">The width of the projection volume.</param> /// <param name="height">The height of the projection volume.</param> /// <param name="zNear">The near edge of the projection volume.</param> /// <param name="zFar">The far edge of the projection volume.</param> /// <rereturns>The resulting Matrix4d instance.</rereturns> public static Matrix4d CreateOrthographic(double width, double height, double zNear, double zFar) { Matrix4d result; CreateOrthographicOffCenter(-width / 2, width / 2, -height / 2, height / 2, zNear, zFar, out result); return result; } /// <summary> /// Creates an orthographic projection matrix. /// </summary> /// <param name="left">The left edge of the projection volume.</param> /// <param name="right">The right edge of the projection volume.</param> /// <param name="bottom">The bottom edge of the projection volume.</param> /// <param name="top">The top edge of the projection volume.</param> /// <param name="zNear">The near edge of the projection volume.</param> /// <param name="zFar">The far edge of the projection volume.</param> /// <param name="result">The resulting Matrix4d instance.</param> public static void CreateOrthographicOffCenter(double left, double right, double bottom, double top, double zNear, double zFar, out Matrix4d result) { result = new Matrix4d(); double invRL = 1 / (right - left); double invTB = 1 / (top - bottom); double invFN = 1 / (zFar - zNear); result.M11 = 2 * invRL; result.M22 = 2 * invTB; result.M33 = -2 * invFN; result.M41 = -(right + left) * invRL; result.M42 = -(top + bottom) * invTB; result.M43 = -(zFar + zNear) * invFN; result.M44 = 1; } /// <summary> /// Creates an orthographic projection matrix. /// </summary> /// <param name="left">The left edge of the projection volume.</param> /// <param name="right">The right edge of the projection volume.</param> /// <param name="bottom">The bottom edge of the projection volume.</param> /// <param name="top">The top edge of the projection volume.</param> /// <param name="zNear">The near edge of the projection volume.</param> /// <param name="zFar">The far edge of the projection volume.</param> /// <returns>The resulting Matrix4d instance.</returns> public static Matrix4d CreateOrthographicOffCenter(double left, double right, double bottom, double top, double zNear, double zFar) { Matrix4d result; CreateOrthographicOffCenter(left, right, bottom, top, zNear, zFar, out result); return result; } /// <summary> /// Creates a perspective projection matrix. /// </summary> /// <param name="fovy">Angle of the field of view in the y direction (in radians)</param> /// <param name="aspect">Aspect ratio of the view (width / height)</param> /// <param name="zNear">Distance to the near clip plane</param> /// <param name="zFar">Distance to the far clip plane</param> /// <param name="result">A projection matrix that transforms camera space to raster space</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown under the following conditions: /// <list type="bullet"> /// <item>fovy is zero, less than zero or larger than Math.PI</item> /// <item>aspect is negative or zero</item> /// <item>zNear is negative or zero</item> /// <item>zFar is negative or zero</item> /// <item>zNear is larger than zFar</item> /// </list> /// </exception> public static void CreatePerspectiveFieldOfView(double fovy, double aspect, double zNear, double zFar, out Matrix4d result) { if (fovy <= 0 || fovy > Math.PI) { throw new ArgumentOutOfRangeException("fovy"); } if (aspect <= 0) { throw new ArgumentOutOfRangeException("aspect"); } if (zNear <= 0) { throw new ArgumentOutOfRangeException("zNear"); } if (zFar <= 0) { throw new ArgumentOutOfRangeException("zFar"); } double yMax = zNear * System.Math.Tan(0.5 * fovy); double yMin = -yMax; double xMin = yMin * aspect; double xMax = yMax * aspect; CreatePerspectiveOffCenter(xMin, xMax, yMin, yMax, zNear, zFar, out result); } /// <summary> /// Creates a perspective projection matrix. /// </summary> /// <param name="fovy">Angle of the field of view in the y direction (in radians)</param> /// <param name="aspect">Aspect ratio of the view (width / height)</param> /// <param name="zNear">Distance to the near clip plane</param> /// <param name="zFar">Distance to the far clip plane</param> /// <returns>A projection matrix that transforms camera space to raster space</returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown under the following conditions: /// <list type="bullet"> /// <item>fovy is zero, less than zero or larger than Math.PI</item> /// <item>aspect is negative or zero</item> /// <item>zNear is negative or zero</item> /// <item>zFar is negative or zero</item> /// <item>zNear is larger than zFar</item> /// </list> /// </exception> public static Matrix4d CreatePerspectiveFieldOfView(double fovy, double aspect, double zNear, double zFar) { Matrix4d result; CreatePerspectiveFieldOfView(fovy, aspect, zNear, zFar, out result); return result; } /// <summary> /// Creates an perspective projection matrix. /// </summary> /// <param name="left">Left edge of the view frustum</param> /// <param name="right">Right edge of the view frustum</param> /// <param name="bottom">Bottom edge of the view frustum</param> /// <param name="top">Top edge of the view frustum</param> /// <param name="zNear">Distance to the near clip plane</param> /// <param name="zFar">Distance to the far clip plane</param> /// <param name="result">A projection matrix that transforms camera space to raster space</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown under the following conditions: /// <list type="bullet"> /// <item>zNear is negative or zero</item> /// <item>zFar is negative or zero</item> /// <item>zNear is larger than zFar</item> /// </list> /// </exception> public static void CreatePerspectiveOffCenter(double left, double right, double bottom, double top, double zNear, double zFar, out Matrix4d result) { if (zNear <= 0) { throw new ArgumentOutOfRangeException("zNear"); } if (zFar <= 0) { throw new ArgumentOutOfRangeException("zFar"); } if (zNear >= zFar) { throw new ArgumentOutOfRangeException("zNear"); } double x = (2.0 * zNear) / (right - left); double y = (2.0 * zNear) / (top - bottom); double a = (right + left) / (right - left); double b = (top + bottom) / (top - bottom); double c = -(zFar + zNear) / (zFar - zNear); double d = -(2.0 * zFar * zNear) / (zFar - zNear); result = new Matrix4d(x, 0, 0, 0, 0, y, 0, 0, a, b, c, -1, 0, 0, d, 0); } /// <summary> /// Creates an perspective projection matrix. /// </summary> /// <param name="left">Left edge of the view frustum</param> /// <param name="right">Right edge of the view frustum</param> /// <param name="bottom">Bottom edge of the view frustum</param> /// <param name="top">Top edge of the view frustum</param> /// <param name="zNear">Distance to the near clip plane</param> /// <param name="zFar">Distance to the far clip plane</param> /// <returns>A projection matrix that transforms camera space to raster space</returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown under the following conditions: /// <list type="bullet"> /// <item>zNear is negative or zero</item> /// <item>zFar is negative or zero</item> /// <item>zNear is larger than zFar</item> /// </list> /// </exception> public static Matrix4d CreatePerspectiveOffCenter(double left, double right, double bottom, double top, double zNear, double zFar) { Matrix4d result; CreatePerspectiveOffCenter(left, right, bottom, top, zNear, zFar, out result); return result; } /// <summary> /// Build a rotation matrix from the specified quaternion. /// </summary> /// <param name="q">Quaternion to translate.</param> /// <param name="result">Matrix result.</param> public static void CreateFromQuaternion(ref Quaterniond q, out Matrix4d result) { Vector3d axis; double angle; q.ToAxisAngle(out axis, out angle); CreateFromAxisAngle(axis, angle, out result); } /// <summary> /// Builds a rotation matrix from a quaternion. /// </summary> /// <param name="q">The quaternion to rotate by.</param> /// <returns>A matrix instance.</returns> public static Matrix4d CreateFromQuaternion(Quaterniond q) { Matrix4d result; CreateFromQuaternion(ref q, out result); return result; } /// <summary> /// Build a scaling matrix /// </summary> /// <param name="scale">Single scale factor for x,y and z axes</param> /// <returns>A scaling matrix</returns> public static Matrix4d Scale(double scale) { return Scale(scale, scale, scale); } /// <summary> /// Build a scaling matrix /// </summary> /// <param name="scale">Scale factors for x,y and z axes</param> /// <returns>A scaling matrix</returns> public static Matrix4d Scale(Vector3d scale) { return Scale(scale.X, scale.Y, scale.Z); } /// <summary> /// Build a scaling matrix /// </summary> /// <param name="x">Scale factor for x-axis</param> /// <param name="y">Scale factor for y-axis</param> /// <param name="z">Scale factor for z-axis</param> /// <returns>A scaling matrix</returns> public static Matrix4d Scale(double x, double y, double z) { Matrix4d result; result.Row0 = Vector4d .UnitX * x; result.Row1 = Vector4d .UnitY * y; result.Row2 = Vector4d .UnitZ * z; result.Row3 = Vector4d .UnitW; return result; } /// <summary> /// Build a rotation matrix that rotates about the x-axis /// </summary> /// <param name="angle">angle in radians to rotate counter-clockwise around the x-axis</param> /// <returns>A rotation matrix</returns> public static Matrix4d RotateX(double angle) { double cos = System.Math.Cos(angle); double sin = System.Math.Sin(angle); Matrix4d result; result.Row0 = Vector4d .UnitX; result.Row1 = new Vector4d (0.0, cos, sin, 0.0); result.Row2 = new Vector4d (0.0, -sin, cos, 0.0); result.Row3 = Vector4d .UnitW; return result; } /// <summary> /// Build a rotation matrix that rotates about the y-axis /// </summary> /// <param name="angle">angle in radians to rotate counter-clockwise around the y-axis</param> /// <returns>A rotation matrix</returns> public static Matrix4d RotateY(double angle) { double cos = System.Math.Cos(angle); double sin = System.Math.Sin(angle); Matrix4d result; result.Row0 = new Vector4d (cos, 0.0, -sin, 0.0); result.Row1 = Vector4d .UnitY; result.Row2 = new Vector4d (sin, 0.0, cos, 0.0); result.Row3 = Vector4d .UnitW; return result; } /// <summary> /// Build a rotation matrix that rotates about the z-axis /// </summary> /// <param name="angle">angle in radians to rotate counter-clockwise around the z-axis</param> /// <returns>A rotation matrix</returns> public static Matrix4d RotateZ(double angle) { double cos = System.Math.Cos(angle); double sin = System.Math.Sin(angle); Matrix4d result; result.Row0 = new Vector4d (cos, sin, 0.0, 0.0); result.Row1 = new Vector4d (-sin, cos, 0.0, 0.0); result.Row2 = Vector4d .UnitZ; result.Row3 = Vector4d .UnitW; return result; } /// <summary> /// Build a rotation matrix to rotate about the given axis /// </summary> /// <param name="axis">the axis to rotate about</param> /// <param name="angle">angle in radians to rotate counter-clockwise (looking in the direction of the given axis)</param> /// <returns>A rotation matrix</returns> public static Matrix4d Rotate(Vector3d axis, double angle) { double cos = System.Math.Cos(-angle); double sin = System.Math.Sin(-angle); double t = 1.0 - cos; axis.Normalize(); Matrix4d result; result.Row0 = new Vector4d (t * axis.X * axis.X + cos, t * axis.X * axis.Y - sin * axis.Z, t * axis.X * axis.Z + sin * axis.Y, 0.0); result.Row1 = new Vector4d (t * axis.X * axis.Y + sin * axis.Z, t * axis.Y * axis.Y + cos, t * axis.Y * axis.Z - sin * axis.X, 0.0); result.Row2 = new Vector4d (t * axis.X * axis.Z - sin * axis.Y, t * axis.Y * axis.Z + sin * axis.X, t * axis.Z * axis.Z + cos, 0.0); result.Row3 = Vector4d .UnitW; return result; } /// <summary> /// Build a rotation matrix from a quaternion /// </summary> /// <param name="q">the quaternion</param> /// <returns>A rotation matrix</returns> public static Matrix4d Rotate(Quaterniond q) { Vector3d axis; double angle; q.ToAxisAngle(out axis, out angle); return Rotate(axis, angle); } /// <summary> /// Build a world space to camera space matrix /// </summary> /// <param name="eye">Eye (camera) position in world space</param> /// <param name="target">Target position in world space</param> /// <param name="up">Up vector in world space (should not be parallel to the camera direction, that is target - eye)</param> /// <returns>A Matrix that transforms world space to camera space</returns> public static Matrix4d LookAt(Vector3d eye, Vector3d target, Vector3d up) { Vector3d z = Vector3d.Normalize(eye - target); Vector3d x = Vector3d.Normalize(Vector3d.Cross(up, z)); Vector3d y = Vector3d.Normalize(Vector3d.Cross(z, x)); Matrix4d rot = new Matrix4d(new Vector4d (x.X, y.X, z.X, 0.0), new Vector4d (x.Y, y.Y, z.Y, 0.0), new Vector4d (x.Z, y.Z, z.Z, 0.0), Vector4d .UnitW); Matrix4d trans = Matrix4d.CreateTranslation(-eye); return trans * rot; } /// <summary> /// Build a world space to camera space matrix /// </summary> /// <param name="eyeX">Eye (camera) position in world space</param> /// <param name="eyeY">Eye (camera) position in world space</param> /// <param name="eyeZ">Eye (camera) position in world space</param> /// <param name="targetX">Target position in world space</param> /// <param name="targetY">Target position in world space</param> /// <param name="targetZ">Target position in world space</param> /// <param name="upX">Up vector in world space (should not be parallel to the camera direction, that is target - eye)</param> /// <param name="upY">Up vector in world space (should not be parallel to the camera direction, that is target - eye)</param> /// <param name="upZ">Up vector in world space (should not be parallel to the camera direction, that is target - eye)</param> /// <returns>A Matrix4 that transforms world space to camera space</returns> public static Matrix4d LookAt(double eyeX, double eyeY, double eyeZ, double targetX, double targetY, double targetZ, double upX, double upY, double upZ) { return LookAt(new Vector3d(eyeX, eyeY, eyeZ), new Vector3d(targetX, targetY, targetZ), new Vector3d(upX, upY, upZ)); } /// <summary> /// Build a projection matrix /// </summary> /// <param name="left">Left edge of the view frustum</param> /// <param name="right">Right edge of the view frustum</param> /// <param name="bottom">Bottom edge of the view frustum</param> /// <param name="top">Top edge of the view frustum</param> /// <param name="near">Distance to the near clip plane</param> /// <param name="far">Distance to the far clip plane</param> /// <returns>A projection matrix that transforms camera space to raster space</returns> public static Matrix4d Frustum(double left, double right, double bottom, double top, double near, double far) { double invRL = 1.0 / (right - left); double invTB = 1.0 / (top - bottom); double invFN = 1.0 / (far - near); return new Matrix4d(new Vector4d (2.0 * near * invRL, 0.0, 0.0, 0.0), new Vector4d (0.0, 2.0 * near * invTB, 0.0, 0.0), new Vector4d ((right + left) * invRL, (top + bottom) * invTB, -(far + near) * invFN, -1.0), new Vector4d (0.0, 0.0, -2.0 * far * near * invFN, 0.0)); } /// <summary> /// Build a projection matrix /// </summary> /// <param name="fovy">Angle of the field of view in the y direction (in radians)</param> /// <param name="aspect">Aspect ratio of the view (width / height)</param> /// <param name="near">Distance to the near clip plane</param> /// <param name="far">Distance to the far clip plane</param> /// <returns>A projection matrix that transforms camera space to raster space</returns> public static Matrix4d Perspective(double fovy, double aspect, double near, double far) { double yMax = near * System.Math.Tan(0.5f * fovy); double yMin = -yMax; double xMin = yMin * aspect; double xMax = yMax * aspect; return Frustum(xMin, xMax, yMin, yMax, near, far); } /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The left operand of the addition.</param> /// <param name="right">The right operand of the addition.</param> /// <returns>A new instance that is the result of the addition.</returns> public static Matrix4d Add(Matrix4d left, Matrix4d right) { Matrix4d result; Add(ref left, ref right, out result); return result; } /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The left operand of the addition.</param> /// <param name="right">The right operand of the addition.</param> /// <param name="result">A new instance that is the result of the addition.</param> public static void Add(ref Matrix4d left, ref Matrix4d right, out Matrix4d result) { result.Row0 = left.Row0 + right.Row0; result.Row1 = left.Row1 + right.Row1; result.Row2 = left.Row2 + right.Row2; result.Row3 = left.Row3 + right.Row3; } /// <summary> /// Subtracts one instance from another. /// </summary> /// <param name="left">The left operand of the subraction.</param> /// <param name="right">The right operand of the subraction.</param> /// <returns>A new instance that is the result of the subraction.</returns> public static Matrix4d Subtract(Matrix4d left, Matrix4d right) { Matrix4d result; Subtract(ref left, ref right, out result); return result; } /// <summary> /// Subtracts one instance from another. /// </summary> /// <param name="left">The left operand of the subraction.</param> /// <param name="right">The right operand of the subraction.</param> /// <param name="result">A new instance that is the result of the subraction.</param> public static void Subtract(ref Matrix4d left, ref Matrix4d right, out Matrix4d result) { result.Row0 = left.Row0 - right.Row0; result.Row1 = left.Row1 - right.Row1; result.Row2 = left.Row2 - right.Row2; result.Row3 = left.Row3 - right.Row3; } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <returns>A new instance that is the result of the multiplication</returns> public static Matrix4d Mult(Matrix4d left, Matrix4d right) { Matrix4d result; Mult(ref left, ref right, out result); return result; } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <param name="result">A new instance that is the result of the multiplication</param> public static void Mult(ref Matrix4d left, ref Matrix4d right, out Matrix4d result) { double lM11 = left.Row0.X, lM12 = left.Row0.Y, lM13 = left.Row0.Z, lM14 = left.Row0.W, lM21 = left.Row1.X, lM22 = left.Row1.Y, lM23 = left.Row1.Z, lM24 = left.Row1.W, lM31 = left.Row2.X, lM32 = left.Row2.Y, lM33 = left.Row2.Z, lM34 = left.Row2.W, lM41 = left.Row3.X, lM42 = left.Row3.Y, lM43 = left.Row3.Z, lM44 = left.Row3.W, rM11 = right.Row0.X, rM12 = right.Row0.Y, rM13 = right.Row0.Z, rM14 = right.Row0.W, rM21 = right.Row1.X, rM22 = right.Row1.Y, rM23 = right.Row1.Z, rM24 = right.Row1.W, rM31 = right.Row2.X, rM32 = right.Row2.Y, rM33 = right.Row2.Z, rM34 = right.Row2.W, rM41 = right.Row3.X, rM42 = right.Row3.Y, rM43 = right.Row3.Z, rM44 = right.Row3.W; result.Row0.X = (((lM11 * rM11) + (lM12 * rM21)) + (lM13 * rM31)) + (lM14 * rM41); result.Row0.Y = (((lM11 * rM12) + (lM12 * rM22)) + (lM13 * rM32)) + (lM14 * rM42); result.Row0.Z = (((lM11 * rM13) + (lM12 * rM23)) + (lM13 * rM33)) + (lM14 * rM43); result.Row0.W = (((lM11 * rM14) + (lM12 * rM24)) + (lM13 * rM34)) + (lM14 * rM44); result.Row1.X = (((lM21 * rM11) + (lM22 * rM21)) + (lM23 * rM31)) + (lM24 * rM41); result.Row1.Y = (((lM21 * rM12) + (lM22 * rM22)) + (lM23 * rM32)) + (lM24 * rM42); result.Row1.Z = (((lM21 * rM13) + (lM22 * rM23)) + (lM23 * rM33)) + (lM24 * rM43); result.Row1.W = (((lM21 * rM14) + (lM22 * rM24)) + (lM23 * rM34)) + (lM24 * rM44); result.Row2.X = (((lM31 * rM11) + (lM32 * rM21)) + (lM33 * rM31)) + (lM34 * rM41); result.Row2.Y = (((lM31 * rM12) + (lM32 * rM22)) + (lM33 * rM32)) + (lM34 * rM42); result.Row2.Z = (((lM31 * rM13) + (lM32 * rM23)) + (lM33 * rM33)) + (lM34 * rM43); result.Row2.W = (((lM31 * rM14) + (lM32 * rM24)) + (lM33 * rM34)) + (lM34 * rM44); result.Row3.X = (((lM41 * rM11) + (lM42 * rM21)) + (lM43 * rM31)) + (lM44 * rM41); result.Row3.Y = (((lM41 * rM12) + (lM42 * rM22)) + (lM43 * rM32)) + (lM44 * rM42); result.Row3.Z = (((lM41 * rM13) + (lM42 * rM23)) + (lM43 * rM33)) + (lM44 * rM43); result.Row3.W = (((lM41 * rM14) + (lM42 * rM24)) + (lM43 * rM34)) + (lM44 * rM44); } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <returns>A new instance that is the result of the multiplication</returns> public static Matrix4d Mult(Matrix4d left, double right) { Matrix4d result; Mult(ref left, right, out result); return result; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <param name="result">A new instance that is the result of the multiplication</param> public static void Mult(ref Matrix4d left, double right, out Matrix4d result) { result.Row0 = left.Row0 * right; result.Row1 = left.Row1 * right; result.Row2 = left.Row2 * right; result.Row3 = left.Row3 * right; } /// <summary> /// Calculate the inverse of the given matrix /// </summary> /// <param name="mat">The matrix to invert</param> /// <returns>The inverse of the given matrix if it has one, or the input if it is singular</returns> /// <exception cref="InvalidOperationException">Thrown if the Matrix4d is singular.</exception> public static Matrix4d Invert(Matrix4d mat) { int[] colIdx = { 0, 0, 0, 0 }; int[] rowIdx = { 0, 0, 0, 0 }; int[] pivotIdx = { -1, -1, -1, -1 }; // convert the matrix to an array for easy looping double[,] inverse = {{mat.Row0.X, mat.Row0.Y, mat.Row0.Z, mat.Row0.W}, {mat.Row1.X, mat.Row1.Y, mat.Row1.Z, mat.Row1.W}, {mat.Row2.X, mat.Row2.Y, mat.Row2.Z, mat.Row2.W}, {mat.Row3.X, mat.Row3.Y, mat.Row3.Z, mat.Row3.W} }; int icol = 0; int irow = 0; for (int i = 0; i < 4; i++) { // Find the largest pivot value double maxPivot = 0.0; for (int j = 0; j < 4; j++) { if (pivotIdx[j] != 0) { for (int k = 0; k < 4; ++k) { if (pivotIdx[k] == -1) { double absVal = System.Math.Abs(inverse[j, k]); if (absVal > maxPivot) { maxPivot = absVal; irow = j; icol = k; } } else if (pivotIdx[k] > 0) { return mat; } } } } ++(pivotIdx[icol]); // Swap rows over so pivot is on diagonal if (irow != icol) { for (int k = 0; k < 4; ++k) { double f = inverse[irow, k]; inverse[irow, k] = inverse[icol, k]; inverse[icol, k] = f; } } rowIdx[i] = irow; colIdx[i] = icol; double pivot = inverse[icol, icol]; // check for singular matrix if (pivot == 0.0) { throw new InvalidOperationException("Matrix is singular and cannot be inverted."); //return mat; } // Scale row so it has a unit diagonal double oneOverPivot = 1.0 / pivot; inverse[icol, icol] = 1.0; for (int k = 0; k < 4; ++k) { inverse[icol, k] *= oneOverPivot; } // Do elimination of non-diagonal elements for (int j = 0; j < 4; ++j) { // check this isn't on the diagonal if (icol != j) { double f = inverse[j, icol]; inverse[j, icol] = 0.0; for (int k = 0; k < 4; ++k) { inverse[j, k] -= inverse[icol, k] * f; } } } } for (int j = 3; j >= 0; --j) { int ir = rowIdx[j]; int ic = colIdx[j]; for (int k = 0; k < 4; ++k) { double f = inverse[k, ir]; inverse[k, ir] = inverse[k, ic]; inverse[k, ic] = f; } } mat.Row0 = new Vector4d (inverse[0, 0], inverse[0, 1], inverse[0, 2], inverse[0, 3]); mat.Row1 = new Vector4d (inverse[1, 0], inverse[1, 1], inverse[1, 2], inverse[1, 3]); mat.Row2 = new Vector4d (inverse[2, 0], inverse[2, 1], inverse[2, 2], inverse[2, 3]); mat.Row3 = new Vector4d (inverse[3, 0], inverse[3, 1], inverse[3, 2], inverse[3, 3]); return mat; } /// <summary> /// Calculate the transpose of the given matrix /// </summary> /// <param name="mat">The matrix to transpose</param> /// <returns>The transpose of the given matrix</returns> public static Matrix4d Transpose(Matrix4d mat) { return new Matrix4d(mat.Column0, mat.Column1, mat.Column2, mat.Column3); } /// <summary> /// Calculate the transpose of the given matrix /// </summary> /// <param name="mat">The matrix to transpose</param> /// <param name="result">The result of the calculation</param> public static void Transpose(ref Matrix4d mat, out Matrix4d result) { result.Row0 = mat.Column0; result.Row1 = mat.Column1; result.Row2 = mat.Column2; result.Row3 = mat.Column3; } /// <summary> /// Matrix multiplication /// </summary> /// <param name="left">left-hand operand</param> /// <param name="right">right-hand operand</param> /// <returns>A new Matrix4d which holds the result of the multiplication</returns> public static Matrix4d operator *(Matrix4d left, Matrix4d right) { return Matrix4d.Mult(left, right); } /// <summary> /// Matrix-scalar multiplication /// </summary> /// <param name="left">left-hand operand</param> /// <param name="right">right-hand operand</param> /// <returns>A new Matrix4d which holds the result of the multiplication</returns> public static Matrix4d operator *(Matrix4d left, float right) { return Matrix4d.Mult(left, right); } /// <summary> /// Matrix addition /// </summary> /// <param name="left">left-hand operand</param> /// <param name="right">right-hand operand</param> /// <returns>A new Matrix4d which holds the result of the addition</returns> public static Matrix4d operator +(Matrix4d left, Matrix4d right) { return Matrix4d.Add(left, right); } /// <summary> /// Matrix subtraction /// </summary> /// <param name="left">left-hand operand</param> /// <param name="right">right-hand operand</param> /// <returns>A new Matrix4d which holds the result of the subtraction</returns> public static Matrix4d operator -(Matrix4d left, Matrix4d right) { return Matrix4d.Subtract(left, right); } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left equals right; false otherwise.</returns> public static bool operator ==(Matrix4d left, Matrix4d right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left does not equal right; false otherwise.</returns> public static bool operator !=(Matrix4d left, Matrix4d right) { return !left.Equals(right); } /// <summary> /// Returns a System.String that represents the current Matrix44. /// </summary> /// <returns></returns> public override string ToString() { return String.Format("{0}\n{1}\n{2}\n{3}", Row0, Row1, Row2, Row3); } /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { unchecked { var hashCode = this.Row0.GetHashCode(); hashCode = (hashCode * 397) ^ this.Row1.GetHashCode(); hashCode = (hashCode * 397) ^ this.Row2.GetHashCode(); hashCode = (hashCode * 397) ^ this.Row3.GetHashCode(); return hashCode; } } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Matrix4d)) { return false; } return this.Equals((Matrix4d)obj); } /// <summary>Indicates whether the current matrix is equal to another matrix.</summary> /// <param name="other">A matrix to compare with this matrix.</param> /// <returns>true if the current matrix is equal to the matrix parameter; otherwise, false.</returns> public bool Equals(Matrix4d other) { return Row0 == other.Row0 && Row1 == other.Row1 && Row2 == other.Row2 && Row3 == other.Row3; } } }
41.208877
172
0.522762
[ "MIT" ]
Kaplas80/ShenmueDKSharp
Math/Matrix4d.cs
63,132
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using PhoneNumberLoginSample.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore; namespace PhoneNumberLoginSample.Migrations { [DbContext(typeof(PhoneNumberLoginSampleMigrationsDbContext))] [Migration("20200810022238_Initial")] partial class Initial { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("_Abp_DatabaseProvider", EfCoreDatabaseProvider.SqlServer) .HasAnnotation("ProductVersion", "3.1.6") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLog", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ApplicationName") .HasColumnName("ApplicationName") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("BrowserInfo") .HasColumnName("BrowserInfo") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("ClientId") .HasColumnName("ClientId") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientIpAddress") .HasColumnName("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnName("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Comments") .HasColumnName("Comments") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<string>("CorrelationId") .HasColumnName("CorrelationId") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Exceptions") .HasColumnName("Exceptions") .HasColumnType("nvarchar(4000)") .HasMaxLength(4000); b.Property<int>("ExecutionDuration") .HasColumnName("ExecutionDuration") .HasColumnType("int"); b.Property<DateTime>("ExecutionTime") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<string>("HttpMethod") .HasColumnName("HttpMethod") .HasColumnType("nvarchar(16)") .HasMaxLength(16); b.Property<int?>("HttpStatusCode") .HasColumnName("HttpStatusCode") .HasColumnType("int"); b.Property<Guid?>("ImpersonatorTenantId") .HasColumnName("ImpersonatorTenantId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("ImpersonatorUserId") .HasColumnName("ImpersonatorUserId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.Property<string>("TenantName") .HasColumnType("nvarchar(max)"); b.Property<string>("Url") .HasColumnName("Url") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<Guid?>("UserId") .HasColumnName("UserId") .HasColumnType("uniqueidentifier"); b.Property<string>("UserName") .HasColumnName("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId", "ExecutionTime"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLogAction", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("AuditLogId") .HasColumnName("AuditLogId") .HasColumnType("uniqueidentifier"); b.Property<int>("ExecutionDuration") .HasColumnName("ExecutionDuration") .HasColumnType("int"); b.Property<DateTime>("ExecutionTime") .HasColumnName("ExecutionTime") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<string>("MethodName") .HasColumnName("MethodName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Parameters") .HasColumnName("Parameters") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<string>("ServiceName") .HasColumnName("ServiceName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("AuditLogId"); b.HasIndex("TenantId", "ServiceName", "MethodName", "ExecutionTime"); b.ToTable("AbpAuditLogActions"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityChange", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("AuditLogId") .HasColumnName("AuditLogId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("ChangeTime") .HasColumnName("ChangeTime") .HasColumnType("datetime2"); b.Property<byte>("ChangeType") .HasColumnName("ChangeType") .HasColumnType("tinyint"); b.Property<string>("EntityId") .IsRequired() .HasColumnName("EntityId") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<Guid?>("EntityTenantId") .HasColumnType("uniqueidentifier"); b.Property<string>("EntityTypeFullName") .IsRequired() .HasColumnName("EntityTypeFullName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("AuditLogId"); b.HasIndex("TenantId", "EntityTypeFullName", "EntityId"); b.ToTable("AbpEntityChanges"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityPropertyChange", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("EntityChangeId") .HasColumnType("uniqueidentifier"); b.Property<string>("NewValue") .HasColumnName("NewValue") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("OriginalValue") .HasColumnName("OriginalValue") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("PropertyName") .IsRequired() .HasColumnName("PropertyName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("PropertyTypeFullName") .IsRequired() .HasColumnName("PropertyTypeFullName") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("EntityChangeId"); b.ToTable("AbpEntityPropertyChanges"); }); modelBuilder.Entity("Volo.Abp.BackgroundJobs.BackgroundJobRecord", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsAbandoned") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false); b.Property<string>("JobArgs") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("JobName") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime?>("LastTryTime") .HasColumnType("datetime2"); b.Property<DateTime>("NextTryTime") .HasColumnType("datetime2"); b.Property<byte>("Priority") .ValueGeneratedOnAdd() .HasColumnType("tinyint") .HasDefaultValue((byte)15); b.Property<short>("TryCount") .ValueGeneratedOnAdd() .HasColumnType("smallint") .HasDefaultValue((short)0); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Volo.Abp.FeatureManagement.FeatureValue", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ProviderName") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.HasKey("Id"); b.HasIndex("Name", "ProviderName", "ProviderKey"); b.ToTable("AbpFeatureValues"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityClaimType", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<string>("Description") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsStatic") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("Regex") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("RegexDescription") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("Required") .HasColumnType("bit"); b.Property<int>("ValueType") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("AbpClaimTypes"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRole", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDefault") .HasColumnName("IsDefault") .HasColumnType("bit"); b.Property<bool>("IsPublic") .HasColumnName("IsPublic") .HasColumnType("bit"); b.Property<bool>("IsStatic") .HasColumnName("IsStatic") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedName") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("ClaimType") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentitySecurityLog", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Action") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("ApplicationName") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("ClientId") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<string>("CorrelationId") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<string>("Identity") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.Property<string>("TenantName") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<Guid?>("UserId") .HasColumnType("uniqueidentifier"); b.Property<string>("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("TenantId", "Action"); b.HasIndex("TenantId", "ApplicationName"); b.HasIndex("TenantId", "Identity"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpSecurityLogs"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUser", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<int>("AccessFailedCount") .ValueGeneratedOnAdd() .HasColumnName("AccessFailedCount") .HasColumnType("int") .HasDefaultValue(0); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Email") .IsRequired() .HasColumnName("Email") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .ValueGeneratedOnAdd() .HasColumnName("EmailConfirmed") .HasColumnType("bit") .HasDefaultValue(false); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("bit") .HasDefaultValue(false); b.Property<bool>("IsExternal") .ValueGeneratedOnAdd() .HasColumnName("IsExternal") .HasColumnType("bit") .HasDefaultValue(false); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime2"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("uniqueidentifier"); b.Property<bool>("LockoutEnabled") .ValueGeneratedOnAdd() .HasColumnName("LockoutEnabled") .HasColumnType("bit") .HasDefaultValue(false); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("Name") .HasColumnName("Name") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("NormalizedEmail") .IsRequired() .HasColumnName("NormalizedEmail") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .IsRequired() .HasColumnName("NormalizedUserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnName("PasswordHash") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("PhoneNumber") .HasColumnName("PhoneNumber") .HasColumnType("nvarchar(16)") .HasMaxLength(16); b.Property<bool>("PhoneNumberConfirmed") .ValueGeneratedOnAdd() .HasColumnName("PhoneNumberConfirmed") .HasColumnType("bit") .HasDefaultValue(false); b.Property<string>("SecurityStamp") .IsRequired() .HasColumnName("SecurityStamp") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("Surname") .HasColumnName("Surname") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.Property<bool>("TwoFactorEnabled") .ValueGeneratedOnAdd() .HasColumnName("TwoFactorEnabled") .HasColumnType("bit") .HasDefaultValue(false); b.Property<string>("UserName") .IsRequired() .HasColumnName("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("Email"); b.HasIndex("NormalizedEmail"); b.HasIndex("NormalizedUserName"); b.HasIndex("UserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("ClaimType") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasColumnType("nvarchar(196)") .HasMaxLength(196); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("UserId", "LoginProvider"); b.HasIndex("LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserOrganizationUnit", b => { b.Property<Guid>("OrganizationUnitId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("OrganizationUnitId", "UserId"); b.HasIndex("UserId", "OrganizationUnitId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Name") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnit", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Code") .IsRequired() .HasColumnName("Code") .HasColumnType("nvarchar(95)") .HasMaxLength(95); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnName("DisplayName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("bit") .HasDefaultValue(false); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime2"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("ParentId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("Code"); b.HasIndex("ParentId"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnitRole", b => { b.Property<Guid>("OrganizationUnitId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("OrganizationUnitId", "RoleId"); b.HasIndex("RoleId", "OrganizationUnitId"); b.ToTable("AbpOrganizationUnitRoles"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResource", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(1000)") .HasMaxLength(1000); b.Property<string>("DisplayName") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<bool>("Enabled") .HasColumnType("bit"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("bit") .HasDefaultValue(false); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime2"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("Properties") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("IdentityServerApiResources"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceClaim", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.HasKey("ApiResourceId", "Type"); b.ToTable("IdentityServerApiClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiScope", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("Description") .HasColumnType("nvarchar(1000)") .HasMaxLength(1000); b.Property<string>("DisplayName") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<bool>("Emphasize") .HasColumnType("bit"); b.Property<bool>("Required") .HasColumnType("bit"); b.Property<bool>("ShowInDiscoveryDocument") .HasColumnType("bit"); b.HasKey("ApiResourceId", "Name"); b.ToTable("IdentityServerApiScopes"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiScopeClaim", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("Type") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.HasKey("ApiResourceId", "Name", "Type"); b.ToTable("IdentityServerApiScopeClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiSecret", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("Value") .HasColumnType("nvarchar(4000)") .HasMaxLength(4000); b.Property<string>("Description") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<DateTime?>("Expiration") .HasColumnType("datetime2"); b.HasKey("ApiResourceId", "Type", "Value"); b.ToTable("IdentityServerApiSecrets"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.Client", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<int>("AbsoluteRefreshTokenLifetime") .HasColumnType("int"); b.Property<int>("AccessTokenLifetime") .HasColumnType("int"); b.Property<int>("AccessTokenType") .HasColumnType("int"); b.Property<bool>("AllowAccessTokensViaBrowser") .HasColumnType("bit"); b.Property<bool>("AllowOfflineAccess") .HasColumnType("bit"); b.Property<bool>("AllowPlainTextPkce") .HasColumnType("bit"); b.Property<bool>("AllowRememberConsent") .HasColumnType("bit"); b.Property<bool>("AlwaysIncludeUserClaimsInIdToken") .HasColumnType("bit"); b.Property<bool>("AlwaysSendClientClaims") .HasColumnType("bit"); b.Property<int>("AuthorizationCodeLifetime") .HasColumnType("int"); b.Property<bool>("BackChannelLogoutSessionRequired") .HasColumnType("bit"); b.Property<string>("BackChannelLogoutUri") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<string>("ClientClaimsPrefix") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ClientName") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ClientUri") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<int?>("ConsentLifetime") .HasColumnType("int"); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(1000)") .HasMaxLength(1000); b.Property<int>("DeviceCodeLifetime") .HasColumnType("int"); b.Property<bool>("EnableLocalLogin") .HasColumnType("bit"); b.Property<bool>("Enabled") .HasColumnType("bit"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("FrontChannelLogoutSessionRequired") .HasColumnType("bit"); b.Property<string>("FrontChannelLogoutUri") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<int>("IdentityTokenLifetime") .HasColumnType("int"); b.Property<bool>("IncludeJwtId") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("bit") .HasDefaultValue(false); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime2"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("uniqueidentifier"); b.Property<string>("LogoUri") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<string>("PairWiseSubjectSalt") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ProtocolType") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<int>("RefreshTokenExpiration") .HasColumnType("int"); b.Property<int>("RefreshTokenUsage") .HasColumnType("int"); b.Property<bool>("RequireClientSecret") .HasColumnType("bit"); b.Property<bool>("RequireConsent") .HasColumnType("bit"); b.Property<bool>("RequirePkce") .HasColumnType("bit"); b.Property<int>("SlidingRefreshTokenLifetime") .HasColumnType("int"); b.Property<bool>("UpdateAccessTokenClaimsOnRefresh") .HasColumnType("bit"); b.Property<string>("UserCodeType") .HasColumnType("nvarchar(100)") .HasMaxLength(100); b.Property<int?>("UserSsoLifetime") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ClientId"); b.ToTable("IdentityServerClients"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientClaim", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("Value") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.HasKey("ClientId", "Type", "Value"); b.ToTable("IdentityServerClientClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientCorsOrigin", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Origin") .HasColumnType("nvarchar(150)") .HasMaxLength(150); b.HasKey("ClientId", "Origin"); b.ToTable("IdentityServerClientCorsOrigins"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientGrantType", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("GrantType") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.HasKey("ClientId", "GrantType"); b.ToTable("IdentityServerClientGrantTypes"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientIdPRestriction", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Provider") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.HasKey("ClientId", "Provider"); b.ToTable("IdentityServerClientIdPRestrictions"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientPostLogoutRedirectUri", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("PostLogoutRedirectUri") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("ClientId", "PostLogoutRedirectUri"); b.ToTable("IdentityServerClientPostLogoutRedirectUris"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientProperty", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Key") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("ClientId", "Key"); b.ToTable("IdentityServerClientProperties"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientRedirectUri", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("RedirectUri") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("ClientId", "RedirectUri"); b.ToTable("IdentityServerClientRedirectUris"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientScope", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Scope") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.HasKey("ClientId", "Scope"); b.ToTable("IdentityServerClientScopes"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientSecret", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("Value") .HasColumnType("nvarchar(4000)") .HasMaxLength(4000); b.Property<string>("Description") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<DateTime?>("Expiration") .HasColumnType("datetime2"); b.HasKey("ClientId", "Type", "Value"); b.ToTable("IdentityServerClientSecrets"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Devices.DeviceFlowCodes", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<string>("Data") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(50000); b.Property<string>("DeviceCode") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<DateTime?>("Expiration") .IsRequired() .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<string>("SubjectId") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("UserCode") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.HasKey("Id"); b.HasIndex("DeviceCode") .IsUnique(); b.HasIndex("Expiration"); b.HasIndex("UserCode") .IsUnique(); b.ToTable("IdentityServerDeviceFlowCodes"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Grants.PersistedGrant", b => { b.Property<string>("Key") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("Data") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(50000); b.Property<DateTime?>("Expiration") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("SubjectId") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("Type") .IsRequired() .HasColumnType("nvarchar(50)") .HasMaxLength(50); b.HasKey("Key"); b.HasIndex("Expiration"); b.HasIndex("SubjectId", "ClientId", "Type"); b.ToTable("IdentityServerPersistedGrants"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityClaim", b => { b.Property<Guid>("IdentityResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.HasKey("IdentityResourceId", "Type"); b.ToTable("IdentityServerIdentityClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(1000)") .HasMaxLength(1000); b.Property<string>("DisplayName") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<bool>("Emphasize") .HasColumnType("bit"); b.Property<bool>("Enabled") .HasColumnType("bit"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("bit") .HasDefaultValue(false); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime2"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("Properties") .HasColumnType("nvarchar(max)"); b.Property<bool>("Required") .HasColumnType("bit"); b.Property<bool>("ShowInDiscoveryDocument") .HasColumnType("bit"); b.HasKey("Id"); b.ToTable("IdentityServerIdentityResources"); }); modelBuilder.Entity("Volo.Abp.PermissionManagement.PermissionGrant", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ProviderName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<Guid?>("TenantId") .HasColumnName("TenantId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("Name", "ProviderName", "ProviderKey"); b.ToTable("AbpPermissionGrants"); }); modelBuilder.Entity("Volo.Abp.SettingManagement.Setting", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ProviderName") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(2048)") .HasMaxLength(2048); b.HasKey("Id"); b.HasIndex("Name", "ProviderName", "ProviderKey"); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Volo.Abp.TenantManagement.Tenant", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("bit") .HasDefaultValue(false); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime2"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.HasKey("Id"); b.HasIndex("Name"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("Volo.Abp.TenantManagement.TenantConnectionString", b => { b.Property<Guid>("TenantId") .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.HasKey("TenantId", "Name"); b.ToTable("AbpTenantConnectionStrings"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLogAction", b => { b.HasOne("Volo.Abp.AuditLogging.AuditLog", null) .WithMany("Actions") .HasForeignKey("AuditLogId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityChange", b => { b.HasOne("Volo.Abp.AuditLogging.AuditLog", null) .WithMany("EntityChanges") .HasForeignKey("AuditLogId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityPropertyChange", b => { b.HasOne("Volo.Abp.AuditLogging.EntityChange", null) .WithMany("PropertyChanges") .HasForeignKey("EntityChangeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b => { b.HasOne("Volo.Abp.Identity.IdentityRole", null) .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b => { b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b => { b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserOrganizationUnit", b => { b.HasOne("Volo.Abp.Identity.OrganizationUnit", null) .WithMany() .HasForeignKey("OrganizationUnitId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("OrganizationUnits") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b => { b.HasOne("Volo.Abp.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b => { b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnit", b => { b.HasOne("Volo.Abp.Identity.OrganizationUnit", null) .WithMany() .HasForeignKey("ParentId"); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnitRole", b => { b.HasOne("Volo.Abp.Identity.OrganizationUnit", null) .WithMany("Roles") .HasForeignKey("OrganizationUnitId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Volo.Abp.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceClaim", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null) .WithMany("UserClaims") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiScope", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null) .WithMany("Scopes") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiScopeClaim", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiScope", null) .WithMany("UserClaims") .HasForeignKey("ApiResourceId", "Name") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiSecret", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null) .WithMany("Secrets") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientClaim", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("Claims") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientCorsOrigin", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("AllowedCorsOrigins") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientGrantType", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("AllowedGrantTypes") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientIdPRestriction", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("IdentityProviderRestrictions") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientPostLogoutRedirectUri", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("PostLogoutRedirectUris") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientProperty", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("Properties") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientRedirectUri", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("RedirectUris") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientScope", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("AllowedScopes") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientSecret", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("ClientSecrets") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityClaim", b => { b.HasOne("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", null) .WithMany("UserClaims") .HasForeignKey("IdentityResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.TenantManagement.TenantConnectionString", b => { b.HasOne("Volo.Abp.TenantManagement.Tenant", null) .WithMany("ConnectionStrings") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
38.730315
117
0.441753
[ "MIT" ]
Vktun/Abp.PhoneNumberLogin
samples/PhoneNumberLoginSample/src/PhoneNumberLoginSample.EntityFrameworkCore.DbMigrations/Migrations/20200810022238_Initial.Designer.cs
78,702
C#
using System; using DomainEventsDemo.Model.Events; using DomainEventsDemo.SharedKernel.StaticApproach; namespace DomainEventsDemo.Model { public class Counter { public string Name { get; private set; } public int Count { get; private set; } public Counter(string name) { Name = name; } // Raise events directly from objects public void Increment() { Count++; DomainEvents.Raise(new CounterIncrementedEvent(this, DateTime.Now)); } } }
23.208333
80
0.605027
[ "MIT" ]
ardalis/DomainEventsDemo
DomainEventsDemo/Model/Counter.cs
559
C#
using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace CeresECL.Misc { public static class EditorHelpers { public static Texture2D GetColoredTexture(Color color) { var texture = new Texture2D(1, 1); texture.SetPixel(0, 0, color); texture.Apply(); return texture; } public static void LoadAssetsToList<T>(List<T> listToAddIn, string searchFilter) where T : UnityEngine.Object { listToAddIn.Clear(); var assets = AssetDatabase.FindAssets(searchFilter); for (int i = 0; i < assets.Length; i++) { var asset = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(assets[i]), typeof(T)) as T; listToAddIn.Add(asset); } } } }
28.322581
117
0.572893
[ "MIT" ]
InsaneOneHub/CeresECL
Sources/Extensions/Editor/EditorHelpers.cs
880
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Invincibility : PowerUpBase { [SerializeField] Material _currentlyPoweredMat; Material[] _originalMat = new Material[4]; MeshRenderer[] _mesh; Collider playerCol; protected override void PowerUp(Player player) { _mesh = player.GetComponentsInChildren<MeshRenderer>(); player._invincible = true; for (int i = 0; i < _mesh.Length; i++) { _originalMat[i] = _mesh[i].material; } for (int i = 0; i < _originalMat.Length; i++) { _mesh[i].material = _currentlyPoweredMat; } } protected override void PowerDown(Player player) { player._invincible = false; for (int i = 0; i < _originalMat.Length; i++) { _mesh[i].material = _originalMat[i]; } } }
22.463415
63
0.592834
[ "MIT" ]
whroberts/SFG_Homework_01
Assets/Scripts/Powerups/Invincibility.cs
921
C#
using System.ComponentModel; using System.Drawing; using Runes.Net.Db; using Runes.Net.Shared; namespace RunesDataBase.TableObjects { public class SpellObject : BasicVisualTableObject { public SpellObject(BasicObject obj) : base(obj) { } [Category("Spell Properties")] [DisplayName("Magic Level")] [Description("Some kind of a level (?)")] public int MagicLv { get { return DbObject.GetFieldAsInt("magiclv"); } set { DbObject.SetField("magiclv", value); } } [Category("Spell Properties")] [DisplayName("Effect type")] [Description("Type of the effect, that spell does")] public SpellEffectType EffectType { get { return (SpellEffectType) DbObject.GetFieldAsInt("effecttype"); } set { DbObject.SetField("effecttype", (int) value); } } [Category("Spell Properties")] [DisplayName("Target type")] [Description("Type of the target")] public Relation TargetType { get { return (Relation)DbObject.GetFieldAsInt("targettype"); } set { DbObject.SetField("targettype", (int)value); } } [Category("Spell Properties")] [DisplayName("Attack distance")] [Description("Maxmum range between caster and target")] public int AttackDistance { get { return DbObject.GetFieldAsInt("attackdistance"); } set { DbObject.SetField("attackdistance", value); } } [Category("AOE Spell Properties")] [DisplayName("Effect range")] [Description("Maxmum range between main target and other targets (?)")] public int EffectRange { get { return DbObject.GetFieldAsInt("effectrange"); } set { DbObject.SetField("effectrange", value); } } [Category("AOE Spell Properties")] [DisplayName("Effect range type")] [Description("Type of the effect range (?)")] public EffectRangeType RangeType { get { return (EffectRangeType)DbObject.GetFieldAsInt("rangetype"); } set { DbObject.SetField("rangetype", (int)value); } } [Category("AOE Spell Properties")] [DisplayName("Effect selection type")] [Description("Describes how to select targets in range")] public SpellSellectType SelectType { get { return (SpellSellectType)DbObject.GetFieldAsInt("rangeselecttype"); } set { DbObject.SetField("rangeselecttype", (int)value); } } [Category("AOE Spell Properties")] [DisplayName("Targets count")] [Description("Maximum amount of victims of the effect")] public int TargetsCount { get { return DbObject.GetFieldAsInt("effectcount"); } set { DbObject.SetField("effectcount", value); } } [Category("Uncategorized Spell Properties")] [DisplayName("Hitrate function")] [Description("Not sure how it works")] public HitRateFunc HitRate { get { return (HitRateFunc)DbObject.GetFieldAsInt("hitratefunc"); } set { DbObject.SetField("hitratefunc", (int)value); } } [Category("Uncategorized Spell Properties")] [DisplayName("Hitrate function argument [0]")] [Description("Not sure how it works")] public float HitRateArg1 { get { return DbObject.GetFieldAsFloat("hitratearg1"); } set { DbObject.SetField("hitratearg1", value); } } [Category("Uncategorized Spell Properties")] [DisplayName("Hitrate function argument [1]")] [Description("Not sure how it works")] public float HitRateArg2 { get { return DbObject.GetFieldAsFloat("hitratearg2"); } set { DbObject.SetField("hitratearg2", value); } } [Category("Spell Properties")] [DisplayName("Cost[0]")] [Description("How and what it costs to cast this spell")] public SpellCost SpellCost1 => new SpellCost(this, 0); [Category("Spell Properties")] [DisplayName("Cost[1]")] [Description("How and what it costs to cast this spell")] public SpellCost SpellCost2 => new SpellCost(this, 1); [Category("Spell Properties")] [DisplayName("Magic")] [Description("Magic the spell does")] public SpellMagic[] Magic { get { var a = new SpellMagic[12]; for (var i = 0; i < 12; ++i) a[i] = new SpellMagic(this, i); return a; } } [Category("Spell Properties")] [DisplayName("Need[0]")] [Description("Requirements for spell")] public SpellNeed SpellNeed1 => new SpellNeed(this, 0); [Category("Spell Properties")] [DisplayName("Need[1]")] [Description("Requirements for spell")] public SpellNeed SpellNeed2 => new SpellNeed(this, 1); [Category("Cooldown")] [DisplayName("Cooldown class")] public CooldownClass CoolDownClass { get { return (CooldownClass)DbObject.GetFieldAsInt("coldownclass"); } set { DbObject.SetField("coldownclass", (int)value); } } [Category("Cooldown")] [DisplayName("Cooldown type")] public int CoolDownType { get { return DbObject.GetFieldAsInt("coldowntype"); } set { DbObject.SetField("coldowntype", value); } } [Category("Cooldown")] [DisplayName("Cooldown time")] public int CoolDownTime { get { return DbObject.GetFieldAsInt("coldowntime"); } set { DbObject.SetField("coldowntime", value); } } [Category("Cooldown")] [DisplayName("Cooldown time (global)")] public int CoolDownTimeAllMagic { get { return DbObject.GetFieldAsInt("coldowntimeallmagic"); } set { DbObject.SetField("coldowntimeallmagic", value); } } [Category("Spell Properties")] [DisplayName("Flags")] public SpellFlags Flags { get { return (SpellFlags)DbObject.GetFieldAsInt("flag"); } set { DbObject.SetField("flag", (int)value); } } [Category("Spell Properties")] [DisplayName("Cast time")] [Description("Requirements for spell")] public float SpellTime { get { return DbObject.GetFieldAsFloat("spelltime"); } set { DbObject.SetField("spelltime", value); } } [Category("Spell Properties")] [DisplayName("Magic attack delay")] [Description("??")] public float MagicAttackDelay { get { return DbObject.GetFieldAsFloat("magicattackdelay"); } set { DbObject.SetField("magicattackdelay", value); } } [Category("Spell Properties")] [DisplayName("Spell count")] [Description("??")] public int SpellCount { get { return DbObject.GetFieldAsInt("spellcount"); } set { DbObject.SetField("spellcount", value); } } [Category("Spell Properties")] [DisplayName("Limit Level")] [Description("Max char level?")] public int LimitLevel { get { return DbObject.GetFieldAsInt("limitlv"); } set { DbObject.SetField("limitlv", value); } } [Category("Spell Properties")] [DisplayName("Max spell level")] [Description("Max spell level")] public int MaxLevel { get { return DbObject.GetFieldAsInt("maxskilllv"); } set { DbObject.SetField("maxskilllv", value); } } [Category("Spell Properties")] [DisplayName("Next spell time")] [Description("??")] public float NextSpellTime { get { return DbObject.GetFieldAsFloat("nextspelltime"); } set { DbObject.SetField("nextspelltime", value); } } public override string GetDescription() { return ("" + ShortNote); } public override Color GetColor() { return Color.Aqua; } public override string GetIconName() { return "spell"; } } public class SpellCost : StructuredField { private int _id; [DisplayName("Cost type")] public SpellCostType CostType { get { return (SpellCostType)Object.GetFieldAsInt(_id > 0 ? "costtype1" :"costtype"); } set { Object.SetField(_id > 0 ? "costtype1" : "costtype", (int)value); } } [DisplayName("Value")] public int Value { get { return Object.GetFieldAsInt(_id > 0 ? "costvalue1" : "costvalue"); } set { Object.SetField(_id > 0 ? "costvalue1" : "costvalue", (int)value); } } public SpellCost(BasicTableObject o, int i) : base(o) { _id = i; } public override string ToString() { return Value + " of " + CostType; } } public class SpellNeed : StructuredField { private int _id; [DisplayName("Need type")] public SpellNeedType NeedType { get { return (SpellNeedType)Object.GetFieldAsInt(_id > 0 ? "needtype2" : "needtype1"); } set { Object.SetField(_id > 0 ? "needtype2" : "needtype1", (int)value); } } [DisplayName("Value")] public int Value { get { return Object.GetFieldAsInt(_id > 0 ? "needvalue2" : "needvalue1"); } set { Object.SetField(_id > 0 ? "needvalue2" : "needvalue1", (int)value); } } public SpellNeed(BasicTableObject o, int i) : base(o) { _id = i; } public override string ToString() => NeedType == SpellNeedType.None ? "<empty>" : $"{Value} of {NeedType}"; } public class SpellMagic : StructuredField { private int _id; [DisplayName("Check function type")] public MagicCheckFunction CheckFuncType { get { return (MagicCheckFunction)Object.GetFieldAsInt("magiccheckfunctype" + (_id + 1)); } set { Object.SetField("magiccheckfunctype" + (_id + 1), (int)value); } } [DisplayName("Magic base GUID")] public int MagicBaseID { get { return Object.GetFieldAsInt("magicbaseid" + (_id + 1)); } set { Object.SetField("magicbaseid" + (_id + 1), value); } } [DisplayName("Argument[0]")] public int Arg0 { get { return Object.GetFieldAsInt("magiccheckarg1" + (_id + 1)); } set { Object.SetField("magiccheckarg1" + (_id + 1), value); } } [DisplayName("Argument[1]")] public int Arg1 { get { return Object.GetFieldAsInt("magiccheckarg2" + (_id+1)); } set { Object.SetField("magiccheckarg2" + (_id + 1), value); } } public SpellMagic(BasicTableObject o, int i) : base(o) { _id = i; } public override string ToString() { if (CheckFuncType == MagicCheckFunction.None) return MagicBaseID.ToString(); return $"{MagicBaseID}, checkfunc: {CheckFuncType}({Arg0}, {Arg1})"; } } }
33.531609
102
0.554889
[ "MIT" ]
ROM-II/rom_db_editor
RunesDataBase/TableObjects/SpellObject.cs
11,671
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : Character { //private float ContagionLevel; private int ContagionLevel = 0; private bool HasCertification; private bool HasToiletPaper; private bool ItsMyTurn = false; private bool HasValidInput = false; private GridTile.TileIndex DesiredTileIndex; public bool TestHasCertification() { return HasCertification; } public void RemoveCertification() { HasCertification = false; GameManager.Instance.SetCertificationHUDActive(false); } public void AddCertification() { HasCertification = true; GameManager.Instance.SetCertificationHUDActive(true); } public void GoHome() { CurrentTileIndex = GameManager.Instance.GridMap.GetHomeTileIndex(); } private void OnEnable() { InputManager.OnClicked += OnTileClicked; } private void OnDisable() { InputManager.OnClicked -= OnTileClicked; } public bool IsWaitingForInput() { return ItsMyTurn && !HasValidInput; } public void OnTileClicked(string tileName, GridTile.TileIndex tileIndex) { if (!ItsMyTurn || HasValidInput) { return; } GridTile targetTile = GameManager.Instance.GridMap.GetTileAt(tileIndex); List<GridTile> tilesAround = GameManager.Instance.GridMap.GetCardinalTilesAround(CurrentTileIndex); bool isValidTile(GridTile gridTile) { return (gridTile.isWalkable || gridTile.isBuilding) && gridTile.Index.X == tileIndex.X && gridTile.Index.Y == tileIndex.Y; } bool tileIsValid = tilesAround.Find(isValidTile) != null; if (!tileIsValid) { return; } HasValidInput = true; DesiredTileIndex = targetTile.Index; } public override void OnOtherOccupantCollided(Occupant other) { base.OnOtherOccupantCollided(other); if (other is Character) { Character otherCharacter = other as Character; if (otherCharacter.IsInfected) { IncreaseContagionLevel(); } } } public override IEnumerator UpdateTurn() { ItsMyTurn = true; while (IsWaitingForInput()) { yield return new WaitForFixedUpdate(); } yield return MoveToTile(DesiredTileIndex); CheckBuildingEffect(); HasValidInput = false; ItsMyTurn = false; } private void CheckBuildingEffect() { GridTile currentTile = GetCurrentTile(); if (!currentTile.isBuilding) { return; } if (currentTile.CompareTag("House") && HasToiletPaper) { GameManager.Instance.GameWon(); return; } if (currentTile.CompareTag("SuperMarket")) { HasToiletPaper = true; GameManager.Instance.SetToiletPaperHUDActive(true); return; } } public void IncreaseContagionLevel() { ContagionLevel ++; GameManager.Instance.SetMaskHUDActive(false, ContagionLevel); if (ContagionLevel >= 3) { GameManager.Instance.GameOver(); } } }
23.825175
107
0.599061
[ "MIT" ]
alessiocali/StayAtHomeGameJam
Assets/Scripts/Engine/Occupants/Player.cs
3,409
C#
using Miharu.BackEnd.Helper; using OpenQA.Selenium; using System; using System.Threading.Tasks; namespace Miharu.BackEnd.Translation.WebCrawlers { public class WCDeepLTranslator : WebCrawlerTranslator { private readonly string _URL; public WCDeepLTranslator(WebDriverManager webDriverManager, TesseractSourceLanguage tesseractSourceLanguage, TranslationTargetLanguage translationTargetLanguage) : base(webDriverManager) { _URL = string.Format("https://www.deepl.com/translator#{0}/{1}/", tesseractSourceLanguage.ToTranslationSourceLanguageParameter(), translationTargetLanguage.ToTranslationTargetLanguageParameter()); } public override TranslationType Type { get { return TranslationType.DeepL_Web; } } protected override By FetchBy { get { return By.XPath("//p[@class='lmt__translations_as_text__item lmt__translations_as_text__main_translation']"); } } protected override string GetUri(string text) { return _URL + Uri.EscapeDataString(text); } public override async Task<string> Translate(string text) { string res = ""; if (text == "") return res; res = _webDriverManager.NavigateAndFetch(GetUri(text), FetchBy, ProcessResult, OverrideNavigation); return res; } public IWebElement OverrideNavigation(IWebDriver driver, string url) { IWebElement result = null; string res = ""; driver.Navigate().GoToUrl(url); int i = 0; for (i = 0; i < 20 && res == ""; i++) { result = driver.FindElement(By.XPath("//textarea[@class='lmt__textarea lmt__target_textarea lmt__textarea_base_style']")); result.SendKeys(" \b"); var results = result.FindElements(By.XPath("//div[@class='lmt__textarea_base_style']")); if (results.Count > 0) result = results[results.Count - 1]; var words = result.FindElements(By.XPath(".//*")); foreach (IWebElement w in words) res += w.GetAttribute("textContent"); } return result; } public override string ProcessResult(IWebElement result) { string res = ""; var words = result.FindElements(By.XPath(".//*")); foreach (IWebElement w in words) res += w.GetAttribute("textContent"); int index = -1; while ((index = res.IndexOf(" \b")) != -1) res = res.Substring(0, index) + res.Substring(index + 2, res.Length - (index + 2)); return res; } } }
34
138
0.556795
[ "MIT" ]
aelbuz/MiharuScanHelper
Miharu Scan Helper/BackEnd/Translation/WebCrawlers/WCDeepLTranslator.cs
2,960
C#
using Tizen.NUI; using Tizen.NUI.BaseComponents; using Tizen.NUI.CommonUI; namespace NuiCommonUiSamples { public class CheckBox : IExample { private SampleLayout root; private static readonly int Height = 150; private static readonly int Width = 216; private uint colNum; private uint rowNum; private Tizen.NUI.CommonUI.CheckBoxGroup[] group; private static string[] styles = new string[] { "enabled", "enabled", "disabled", "disabledSelected", }; private static string[] applications = new string[] { "Group1", "Group2", "Group3", "Group4", }; private TableView table; public void Activate() { Window.Instance.BackgroundColor = Color.White; root = new SampleLayout(); root.HeaderText = "CheckBox"; if (styles.Length == 0 || applications.Length == 0) { return; } colNum = (uint)applications.Length + 1; rowNum = (uint)styles.Length + 1; table = new TableView(rowNum, colNum) { Size2D = new Size2D(1080, 1920), }; for (uint i = 1; i < rowNum; i++) { TextLabel text = new TextLabel(); text.Size2D = new Size2D(Width, Height); text.PointSize = 12; text.Focusable = true; text.HorizontalAlignment = HorizontalAlignment.Center; text.VerticalAlignment = VerticalAlignment.Center; text.Text = styles[i - 1]; table.AddChild(text, new TableView.CellPosition(i, 0)); } for (uint i = 1; i < colNum; i++) { TextLabel text = new TextLabel(); text.Size2D = new Size2D(Width, Height); text.PointSize = 12; text.HorizontalAlignment = HorizontalAlignment.Center; text.VerticalAlignment = VerticalAlignment.Center; text.Text = applications[i - 1]; text.Focusable = true; table.AddChild(text, new TableView.CellPosition(0, i)); } group = new CheckBoxGroup[4]; for (uint j = 1; j < colNum; j++) { group[j - 1] = new CheckBoxGroup(); for (uint i = 1; i < rowNum; i++) { Tizen.NUI.CommonUI.CheckBox checkBox = new Tizen.NUI.CommonUI.CheckBox("CheckBox"); checkBox.Size2D = new Size2D(48, 48); if (i == 3) { checkBox.IsEnabled = false; } else if (i == 4) { checkBox.IsEnabled = false; checkBox.IsSelected = true; } else { group[j - 1].Add(checkBox); } checkBox.Focusable = true; //checkBox.Text = checkBox.IsSelected.ToString(); checkBox.SelectedEvent += CheckBoxSelectedEvent; table.AddChild(checkBox, new TableView.CellPosition(i, j)); } } for (uint i = 0; i < rowNum; i++) { table.SetFixedHeight(i, Height); for (uint j = 0; j < colNum; j++) { table.SetFixedWidth(j, Width); table.SetCellAlignment(new TableView.CellPosition(i, j), HorizontalAlignmentType.Center, VerticalAlignmentType.Center); } } root.Add(table); } private void CheckBoxSelectedEvent(object sender, SelectButton.SelectEventArgs e) { Tizen.NUI.CommonUI.CheckBox obj = sender as Tizen.NUI.CommonUI.CheckBox; for (uint i = 0; i < rowNum; i++) { for (uint j = 0; j < colNum; j++) { Tizen.NUI.CommonUI.CheckBox child = table.GetChildAt(new TableView.CellPosition(i, j)) as Tizen.NUI.CommonUI.CheckBox; if (child != null) { //child.Text = child.IsSelected.ToString(); } } } } public void Deactivate() { for (uint i = 0; i < rowNum; i++) { for (uint j = 0; j < colNum; j++) { View child = table.GetChildAt(new TableView.CellPosition(i, j)); if (child != null) { table.RemoveChildAt(new TableView.CellPosition(i, j)); child.Dispose(); } } } if (root != null) { if (table != null) { root.Remove(table); table.Dispose(); } root.Dispose(); } } } }
32.666667
139
0.4435
[ "Apache-2.0", "MIT" ]
AchoWang/TizenFX
test/NUITestSample/CommonUI_Samples/Samples/CheckBoxSample.cs
5,294
C#
using NUnit.Framework; namespace MLAgents.Tests { public class EditModeTestActionMasker { [Test] public void Contruction() { var bp = new BrainParameters(); var masker = new ActionMasker(bp); Assert.IsNotNull(masker); } [Test] public void FailsWithContinuous() { var bp = new BrainParameters(); bp.vectorActionSpaceType = SpaceType.Continuous; bp.vectorActionSize = new[] {4}; var masker = new ActionMasker(bp); masker.SetActionMask(0, new[] {0}); Assert.Catch<UnityAgentsException>(() => masker.GetMask()); } [Test] public void NullMask() { var bp = new BrainParameters(); bp.vectorActionSpaceType = SpaceType.Discrete; var masker = new ActionMasker(bp); var mask = masker.GetMask(); Assert.IsNull(mask); } [Test] public void FirstBranchMask() { var bp = new BrainParameters(); bp.vectorActionSpaceType = SpaceType.Discrete; bp.vectorActionSize = new[] {4, 5, 6}; var masker = new ActionMasker(bp); var mask = masker.GetMask(); Assert.IsNull(mask); masker.SetActionMask(0, new[] {1, 2, 3}); mask = masker.GetMask(); Assert.IsFalse(mask[0]); Assert.IsTrue(mask[1]); Assert.IsTrue(mask[2]); Assert.IsTrue(mask[3]); Assert.IsFalse(mask[4]); Assert.AreEqual(mask.Length, 15); } [Test] public void SecondBranchMask() { var bp = new BrainParameters { vectorActionSpaceType = SpaceType.Discrete, vectorActionSize = new[] { 4, 5, 6 } }; var masker = new ActionMasker(bp); masker.SetActionMask(1, new[] {1, 2, 3}); var mask = masker.GetMask(); Assert.IsFalse(mask[0]); Assert.IsFalse(mask[4]); Assert.IsTrue(mask[5]); Assert.IsTrue(mask[6]); Assert.IsTrue(mask[7]); Assert.IsFalse(mask[8]); Assert.IsFalse(mask[9]); } [Test] public void MaskReset() { var bp = new BrainParameters { vectorActionSpaceType = SpaceType.Discrete, vectorActionSize = new[] { 4, 5, 6 } }; var masker = new ActionMasker(bp); masker.SetActionMask(1, new[] {1, 2, 3}); masker.ResetMask(); var mask = masker.GetMask(); for (var i = 0; i < 15; i++) { Assert.IsFalse(mask[i]); } } [Test] public void ThrowsError() { var bp = new BrainParameters { vectorActionSpaceType = SpaceType.Discrete, vectorActionSize = new[] { 4, 5, 6 } }; var masker = new ActionMasker(bp); Assert.Catch<UnityAgentsException>( () => masker.SetActionMask(0, new[] {5})); Assert.Catch<UnityAgentsException>( () => masker.SetActionMask(1, new[] {5})); masker.SetActionMask(2, new[] {5}); Assert.Catch<UnityAgentsException>( () => masker.SetActionMask(3, new[] {1})); masker.GetMask(); masker.ResetMask(); masker.SetActionMask(0, new[] {0, 1, 2, 3}); Assert.Catch<UnityAgentsException>( () => masker.GetMask()); } [Test] public void MultipleMaskEdit() { var bp = new BrainParameters(); bp.vectorActionSpaceType = SpaceType.Discrete; bp.vectorActionSize = new[] {4, 5, 6}; var masker = new ActionMasker(bp); masker.SetActionMask(0, new[] {0, 1}); masker.SetActionMask(0, new[] {3}); masker.SetActionMask(2, new[] {1}); var mask = masker.GetMask(); for (var i = 0; i < 15; i++) { if ((i == 0) || (i == 1) || (i == 3) || (i == 10)) { Assert.IsTrue(mask[i]); } else { Assert.IsFalse(mask[i]); } } } } }
31.760563
71
0.469401
[ "Apache-2.0" ]
107587084/ml-agents
com.unity.ml-agents/Tests/Editor/EditModeTestActionMasker.cs
4,510
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace VideoManager.iOS { public class Application { // This is the main entry point of the application. static void Main (string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main (args, null, "AppDelegate"); } } }
20.285714
82
0.720657
[ "MIT" ]
TVGSoft/Architecture-Xamarin
Apps/iOS/Main.cs
428
C#
using System; using System.Collections.Generic; using System.Linq; namespace CsDebugScript.DwarfSymbolProvider { /// <summary> /// Common information entry shared across frame description entries. /// </summary> internal class DwarfCommonInformationEntry { /// <summary> /// Initializes a new instance of the <see cref="DwarfCommonInformationEntry"/> class. /// </summary> /// <param name="data">The data memory reader.</param> /// <param name="defaultAddressSize">Default size of the address.</param> /// <param name="endPosition">The end position in the memory stream.</param> private DwarfCommonInformationEntry(DwarfMemoryReader data, byte defaultAddressSize, int endPosition) { ParseData(data, defaultAddressSize, endPosition); } /// <summary> /// Initializes a new instance of the <see cref="DwarfCommonInformationEntry"/> class. /// </summary> protected DwarfCommonInformationEntry() { } /// <summary> /// Gets or sets the version. /// </summary> public byte Version { get; set; } /// <summary> /// Gets or sets the augmentation string. /// </summary> public string Augmentation { get; set; } /// <summary> /// Gets or sets the size of the address. /// </summary> public byte AddressSize { get; set; } /// <summary> /// Gets or sets the size of the segment selector. /// </summary> public byte SegmentSelectorSize { get; set; } /// <summary> /// Gets or sets the code alignment factor. /// </summary> public ulong CodeAlignmentFactor { get; set; } /// <summary> /// Gets or sets the data alignment factor. /// </summary> public ulong DataAlignmentFactor { get; set; } /// <summary> /// Gets or sets the return address register. /// </summary> public ulong ReturnAddressRegister { get; set; } /// <summary> /// Gets or sets the initial instructions stream to be executed before instructions in frame description entry. /// </summary> public byte[] InitialInstructions { get; set; } /// <summary> /// Gets or sets the list of frame description entries that share this common information entry. /// </summary> public List<DwarfFrameDescriptionEntry> FrameDescriptionEntries { get; set; } = new List<DwarfFrameDescriptionEntry>(); /// <summary> /// Parses the specified data for all common information entries and frame description entries. /// </summary> /// <param name="data">The data memory reader.</param> /// <param name="defaultAddressSize">Default size of the address.</param> /// <returns>All the parsed common information entries</returns> public static DwarfCommonInformationEntry[] ParseAll(DwarfMemoryReader data, byte defaultAddressSize) { Dictionary<int, DwarfCommonInformationEntry> entries = new Dictionary<int, DwarfCommonInformationEntry>(); while (!data.IsEnd) { bool is64bit; int startPosition = data.Position; ulong length = data.ReadLength(out is64bit); int endPosition = data.Position + (int)length; int offset = data.ReadOffset(is64bit); DwarfCommonInformationEntry entry; if (offset == -1) { entry = new DwarfCommonInformationEntry(data, defaultAddressSize, endPosition); entries.Add(startPosition, entry); } else { if (!entries.TryGetValue(offset, out entry)) { entry = ParseEntry(data, defaultAddressSize, offset); entries.Add(offset, entry); } DwarfFrameDescriptionEntry description = new DwarfFrameDescriptionEntry(data, entry, endPosition); entry.FrameDescriptionEntries.Add(description); } } return entries.Values.ToArray(); } /// <summary> /// Parses the single entry from the specified data. /// </summary> /// <param name="data">The data memory reader.</param> /// <param name="defaultAddressSize">Default size of the address.</param> /// <param name="startPosition">The start position.</param> /// <returns>Parsed common information entry.</returns> private static DwarfCommonInformationEntry ParseEntry(DwarfMemoryReader data, byte defaultAddressSize, int startPosition) { int position = data.Position; data.Position = startPosition; bool is64bit; ulong length = data.ReadLength(out is64bit); int endPosition = data.Position + (int)length; int offset = data.ReadOffset(is64bit); if (offset != -1) { throw new Exception("Expected CommonInformationEntry"); } DwarfCommonInformationEntry entry = new DwarfCommonInformationEntry(data, defaultAddressSize, endPosition); data.Position = position; return entry; } /// <summary> /// Parses the data for this instance. /// </summary> /// <param name="data">The data memory reader.</param> /// <param name="defaultAddressSize">Default size of the address.</param> /// <param name="endPosition">The end position.</param> private void ParseData(DwarfMemoryReader data, byte defaultAddressSize, int endPosition) { Version = data.ReadByte(); Augmentation = data.ReadString(); if (!string.IsNullOrEmpty(Augmentation)) { AddressSize = 4; SegmentSelectorSize = 0; CodeAlignmentFactor = 0; DataAlignmentFactor = 0; ReturnAddressRegister = 0; } else { if (Version >= 4) { AddressSize = data.ReadByte(); SegmentSelectorSize = data.ReadByte(); } else { AddressSize = defaultAddressSize; SegmentSelectorSize = 0; } CodeAlignmentFactor = data.LEB128(); DataAlignmentFactor = data.LEB128(); ReturnAddressRegister = data.LEB128(); } InitialInstructions = data.ReadBlock((uint)(endPosition - data.Position)); } } /// <summary> /// Input data structure for parsing exception handling frames stream. /// </summary> internal struct DwarfExceptionHandlingFrameParsingInput { /// <summary> /// Initializes a new instance of the <see cref="DwarfExceptionHandlingFrameParsingInput"/> class. /// </summary> /// <param name="image">The dwarf image used to initialize input data.</param> public DwarfExceptionHandlingFrameParsingInput(IDwarfImage image) : this() { DefaultAddressSize = (byte)(image.Is64bit ? 8 : 4); PcRelativeAddress = image.EhFrameAddress; TextAddress = image.TextSectionAddress; DataAddress = image.DataSectionAddress; } /// <summary> /// Deafult address size that should be used. /// </summary> public byte DefaultAddressSize; /// <summary> /// Address of the .eh_frame section when loaded into memory. /// </summary> public ulong PcRelativeAddress; /// <summary> /// Address of the .text section when loaded into memory. /// </summary> public ulong TextAddress; /// <summary> /// Address of the .data section when loaded into memory. /// </summary> public ulong DataAddress; } /// <summary> /// Common information entry shared across frame description entries. /// This class is being parsed from <see cref="IDwarfImage.EhFrame"/> stream. /// </summary> internal class DwarfExceptionHandlingCommonInformationEntry : DwarfCommonInformationEntry { /// <summary> /// Initializes a new instance of the <see cref="DwarfExceptionHandlingCommonInformationEntry"/> class. /// </summary> /// <param name="data">The data memory reader.</param> /// <param name="endPosition">The end position in the memory stream.</param> /// <param name="input">The input data for parsing configuration.</param> public DwarfExceptionHandlingCommonInformationEntry(DwarfMemoryReader data, int endPosition, DwarfExceptionHandlingFrameParsingInput input) { ParseData(data, endPosition, input); } /// <summary> /// Encoding used for storing language specific data area. /// </summary> public DwarfExceptionHandlingEncoding LanguageSpecificDataAreaEncoding { get; set; } = DwarfExceptionHandlingEncoding.Omit; /// <summary> /// Encoding used for storing frame description addresses. /// </summary> public DwarfExceptionHandlingEncoding FrameDescriptionAddressEncoding { get; set; } = DwarfExceptionHandlingEncoding.Omit; /// <summary> /// Encoding used for storing personality location. /// </summary> public DwarfExceptionHandlingEncoding PersonalityEncoding { get; set; } = DwarfExceptionHandlingEncoding.Omit; /// <summary> /// The personality location. /// </summary> public ulong PersonalityLocation { get; set; } = 0; /// <summary> /// Flag that indicates if CIE represents a stack frame for the invocation of a signal handler. /// When unwinding the stack, signal stack frames are handled slightly differently: /// the instruction pointer is assumed to be before the next instruction to execute rather than after it. /// </summary> public bool StackFrame { get; set; } = false; /// <summary> /// Parses the specified data for all common information entries and frame description entries. /// </summary> /// <param name="data">The data memory reader.</param> /// <param name="input">The input data for parsing configuration.</param> /// <returns>All the parsed common information entries</returns> public static DwarfExceptionHandlingCommonInformationEntry[] ParseAll(DwarfMemoryReader data, DwarfExceptionHandlingFrameParsingInput input) { Dictionary<int, DwarfExceptionHandlingCommonInformationEntry> entries = new Dictionary<int, DwarfExceptionHandlingCommonInformationEntry>(); while (!data.IsEnd) { bool is64bit; int startPosition = data.Position; ulong length = data.ReadLength(out is64bit); int endPosition = data.Position + (int)length; if (length == 0 || endPosition >= data.Data.Length) { break; } int offsetBase = data.Position; int offset = data.ReadOffset(is64bit); DwarfExceptionHandlingCommonInformationEntry entry; if (offset == 0) { entry = new DwarfExceptionHandlingCommonInformationEntry(data, endPosition, input); entries.Add(startPosition, entry); } else { int entryOffset = offsetBase - offset; if (!entries.TryGetValue(entryOffset, out entry)) { entry = ParseEntry(data, entryOffset, input); entries.Add(entryOffset, entry); } DwarfFrameDescriptionEntry description = ParseDescription(data, entry, endPosition, input); entry.FrameDescriptionEntries.Add(description); } } return entries.Values.ToArray(); } /// <summary> /// Parses frame description from the specified data memory reader. /// </summary> /// <param name="data">The data memory reader.</param> /// <param name="entry">Common information entry for parsed frame description.</param> /// <param name="endPosition">Position in the data reader where parsed frame description ends.</param> /// <param name="input">The input data for parsing configuration.</param> /// <returns>Parsed frame description.</returns> private static DwarfFrameDescriptionEntry ParseDescription(DwarfMemoryReader data, DwarfExceptionHandlingCommonInformationEntry entry, int endPosition, DwarfExceptionHandlingFrameParsingInput input) { DwarfFrameDescriptionEntry description = new DwarfFrameDescriptionEntry(); description.InitialLocation = ReadEncodedAddress(data, entry.FrameDescriptionAddressEncoding, input); description.AddressRange = ReadEncodedAddress(data, entry.FrameDescriptionAddressEncoding & DwarfExceptionHandlingEncoding.Mask, input); description.CommonInformationEntry = entry; int instructionsStart = -1; if (entry.Augmentation.Length >= 1 && entry.Augmentation[0] == 'z') { uint length = data.LEB128(); instructionsStart = data.Position + (int)length; if (entry.LanguageSpecificDataAreaEncoding != DwarfExceptionHandlingEncoding.Omit) { ulong lsdaDataFileAddress = ReadEncodedAddress(data, entry.LanguageSpecificDataAreaEncoding, input); } } if (instructionsStart >= 0) { data.Position = instructionsStart; } description.Instructions = data.ReadBlock((uint)(endPosition - data.Position)); return description; } /// <summary> /// Reads encoded address from the specified data memory reader. /// </summary> /// <param name="data">The data memory reader.</param> /// <param name="encoding">Encoding used for storing address value.</param> /// <param name="input">The input data for parsing configuration.</param> /// <returns>Decoded address value.</returns> private static ulong ReadEncodedAddress(DwarfMemoryReader data, DwarfExceptionHandlingEncoding encoding, DwarfExceptionHandlingFrameParsingInput input) { bool signExtendValue = false; ulong baseAddress = 0; switch (encoding & DwarfExceptionHandlingEncoding.Modifiers) { case DwarfExceptionHandlingEncoding.PcRelative: signExtendValue = true; baseAddress = (ulong)data.Position; if (input.PcRelativeAddress != ulong.MaxValue) { baseAddress += input.PcRelativeAddress; } break; case DwarfExceptionHandlingEncoding.TextRelative: signExtendValue = true; if (input.TextAddress != ulong.MaxValue) { baseAddress = input.TextAddress; } break; case DwarfExceptionHandlingEncoding.DataRelative: signExtendValue = true; if (input.DataAddress != ulong.MaxValue) { baseAddress = input.DataAddress; } break; case DwarfExceptionHandlingEncoding.FunctionRelative: signExtendValue = true; break; case DwarfExceptionHandlingEncoding.Aligned: { int alignment = data.Position % input.DefaultAddressSize; if (alignment > 0) { data.Position += input.DefaultAddressSize - alignment; } } break; } ulong address = 0; switch (encoding & DwarfExceptionHandlingEncoding.Mask) { case DwarfExceptionHandlingEncoding.Signed: case DwarfExceptionHandlingEncoding.AbsolutePointer: address = data.ReadUlong(input.DefaultAddressSize); break; case DwarfExceptionHandlingEncoding.UnsignedData2: address = data.ReadUshort(); break; case DwarfExceptionHandlingEncoding.UnsignedData4: address = data.ReadUint(); break; case DwarfExceptionHandlingEncoding.SignedData8: case DwarfExceptionHandlingEncoding.UnsignedData8: address = data.ReadUlong(); break; case DwarfExceptionHandlingEncoding.Uleb128: address = data.LEB128(); break; case DwarfExceptionHandlingEncoding.Sleb128: address = data.SLEB128(); break; case DwarfExceptionHandlingEncoding.SignedData2: address = (ulong)(long)(short)data.ReadUshort(); break; case DwarfExceptionHandlingEncoding.SignedData4: address = (ulong)(long)(int)data.ReadUint(); break; } if (signExtendValue && input.DefaultAddressSize < System.Runtime.InteropServices.Marshal.SizeOf(address.GetType())) { ulong sign_bit = 1UL << ((input.DefaultAddressSize * 8) -1); if ((sign_bit & address) != 0) { ulong mask = ~sign_bit + 1; address |= mask; } } return baseAddress + address; } /// <summary> /// Parses the single entry from the specified data. /// </summary> /// <param name="data">The data memory reader.</param> /// <param name="startPosition">The start position.</param> /// <param name="input">The input data for parsing configuration.</param> /// <returns>Parsed common information entry.</returns> private static DwarfExceptionHandlingCommonInformationEntry ParseEntry(DwarfMemoryReader data, int startPosition, DwarfExceptionHandlingFrameParsingInput input) { int position = data.Position; data.Position = startPosition; bool is64bit; ulong length = data.ReadLength(out is64bit); int endPosition = data.Position + (int)length; int offset = data.ReadOffset(is64bit); if (offset != 0) { throw new Exception("Expected CommonInformationEntry"); } DwarfExceptionHandlingCommonInformationEntry entry = new DwarfExceptionHandlingCommonInformationEntry(data, endPosition, input); data.Position = position; return entry; } /// <summary> /// Parses the data for this instance. /// </summary> /// <param name="data">The data memory reader.</param> /// <param name="endPosition">The end position.</param> /// <param name="input">The input data for parsing configuration.</param> private void ParseData(DwarfMemoryReader data, int endPosition, DwarfExceptionHandlingFrameParsingInput input) { Version = data.ReadByte(); Augmentation = data.ReadString(); CodeAlignmentFactor = data.LEB128(); DataAlignmentFactor = data.SLEB128(); if (Version == 1) { ReturnAddressRegister = data.ReadByte(); } else { ReturnAddressRegister = data.LEB128(); } AddressSize = input.DefaultAddressSize; SegmentSelectorSize = 0; int instructionsStart = -1; for (int i = 0; i < Augmentation.Length; i++) { if (Augmentation[i] == 'z') { uint length = data.LEB128(); instructionsStart = data.Position + (int)length; } else if (Augmentation[i] == 'L') { LanguageSpecificDataAreaEncoding = (DwarfExceptionHandlingEncoding)data.ReadByte(); } else if (Augmentation[i] == 'R') { FrameDescriptionAddressEncoding = (DwarfExceptionHandlingEncoding)data.ReadByte(); } else if (Augmentation[i] == 'S') { StackFrame = true; } else if (Augmentation[i] == 'P') { PersonalityEncoding = (DwarfExceptionHandlingEncoding)data.ReadByte(); PersonalityLocation = ReadEncodedAddress(data, PersonalityEncoding, input); } else { break; } } if (instructionsStart >= 0) { data.Position = instructionsStart; } InitialInstructions = data.ReadBlock((uint)(endPosition - data.Position)); } } }
40.907236
206
0.56506
[ "Apache-2.0" ]
rdev0/PadAnalyzer
Source/CsDebugScript.DwarfSymbolProvider/DwarfCommonInformationEntry.cs
22,051
C#
using System; using System.Threading.Tasks; namespace DesignPatterns.Structural.Adapters { public class AppleIPhone : Phone, ILightningChargeable { public async Task Recharge() { if (!CableConnected) { Console.WriteLine("Please, connect the lightning cable to recharge your Iphone."); return; } Console.WriteLine("Iphone is recharging..."); await Task.Delay(10000); Recharged = true; Console.WriteLine("Iphone battery is at 100%!"); } public void ConnectedToLightningCable() { CableConnected = true; } public void DisconnectedToLightingCable() { CableConnected = false; } } }
25.125
98
0.554726
[ "MIT" ]
luizmotta01/dotnet-design-patterns
src/DesignPatterns/Structural/Adapters/AppleIPhone.cs
806
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace WPFQ21 { /// <summary> /// App.xaml 的交互逻辑 /// </summary> public partial class App : Application { } }
16.888889
42
0.690789
[ "MIT" ]
zmrbak/WPFqa1
配套代码/WPFQ21/WPFQ21/App.xaml.cs
316
C#
using System.Linq; using System.Threading.Tasks; using Telegram.Bot.Exceptions; using Telegram.Bot.Tests.Integ.Framework; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; using Xunit; namespace Telegram.Bot.Tests.Integ.Exceptions { [Collection(Constants.TestCollections.Exceptions)] [TestCaseOrderer(Constants.TestCaseOrderer, Constants.AssemblyName)] public class ApiExceptionsTests { private ITelegramBotClient BotClient => _fixture.BotClient; private readonly TestsFixture _fixture; public ApiExceptionsTests(TestsFixture fixture) { _fixture = fixture; } [Fact(DisplayName = FactTitles.ShouldThrowChatNotFoundException)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SendMessage)] [ExecutionOrder(1)] public async Task Should_Throw_Exception_ChatNotFoundException() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldThrowChatNotFoundException); BadRequestException e = await Assert.ThrowsAnyAsync<BadRequestException>(() => BotClient.SendTextMessageAsync(0, "test")); Assert.IsType<ChatNotFoundException>(e); } [Fact(DisplayName = FactTitles.ShouldThrowInvalidUserIdException)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SendMessage)] [ExecutionOrder(2)] public async Task Should_Throw_Exception_InvalidUserIdException() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldThrowInvalidUserIdException); BadRequestException e = await Assert.ThrowsAnyAsync<BadRequestException>(() => BotClient.PromoteChatMemberAsync(_fixture.SupergroupChat.Id, 123456)); Assert.IsType<InvalidUserIdException>(e); } [Fact(DisplayName = FactTitles.ShouldThrowExceptionChatNotInitiatedException)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SendMessage)] [ExecutionOrder(3)] public async Task Should_Throw_Exception_ChatNotInitiatedException() { //ToDo add exception. forward message from another bot. Forbidden: bot can't send messages to bots await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldThrowExceptionChatNotInitiatedException, "Forward a message to this chat from a user that never started a chat with this bot"); Update forwardedMessageUpdate = (await _fixture.UpdateReceiver.GetUpdatesAsync(u => u.Message.IsForwarded, updateTypes: UpdateType.Message )).Single(); await _fixture.UpdateReceiver.DiscardNewUpdatesAsync(); ForbiddenException e = await Assert.ThrowsAnyAsync<ForbiddenException>(() => BotClient.SendTextMessageAsync(forwardedMessageUpdate.Message.ForwardFrom.Id, $"Error! If you see this message, talk to @{forwardedMessageUpdate.Message.From.Username}")); Assert.IsType<ChatNotInitiatedException>(e); } [Fact(DisplayName = FactTitles.ShouldThrowExceptionContactRequestException)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SendMessage)] [ExecutionOrder(4)] public async Task Should_Throw_Exception_ContactRequestException() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldThrowExceptionContactRequestException); ReplyKeyboardMarkup replyMarkup = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestContact("Share Contact"), }); BadRequestException e = await Assert.ThrowsAnyAsync<BadRequestException>(() => BotClient.SendTextMessageAsync(_fixture.SupergroupChat.Id, "You should never see this message", replyMarkup: replyMarkup)); Assert.IsType<ContactRequestException>(e); } private static class FactTitles { public const string ShouldThrowChatNotFoundException = "Should throw ChatNotFoundException while trying to send message to an invalid chat"; public const string ShouldThrowInvalidUserIdException = "Should throw InvalidUserIdException while trying to promote an invalid user id"; public const string ShouldThrowExceptionChatNotInitiatedException = "Should throw ChatNotInitiatedException while trying to send message to a user who hasn't " + "started a chat with bot but bot knows about him/her."; public const string ShouldThrowExceptionContactRequestException = "Should throw ContactRequestException while asking for user's phone number in non-private " + "chat via reply keyboard markup"; } } }
45.796296
114
0.700364
[ "MIT" ]
Akshay-Gupta/Telegram.Bot
test/Telegram.Bot.Tests.Integ/Exceptions/ApiExceptionsTests.cs
4,948
C#
namespace Microsoft.Protocols.TestSuites.SharedTestSuite { using System.Collections.Generic; using System.Globalization; using System.Linq; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestSuites.SharedAdapter; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// A class which contains test cases used to capture the requirements related with PutChanges operation. /// </summary> [TestClass] public abstract class S13_PutChanges : SharedTestSuiteBase { #region Test Suite Initialization /// <summary> /// A method used to initialize this class. /// </summary> /// <param name="testContext">A parameter represents the context of the test suite.</param> [ClassInitialize] public static new void ClassInitialize(TestContext testContext) { SharedTestSuiteBase.ClassInitialize(testContext); } /// <summary> /// A method used to clean up the test environment. /// </summary> [ClassCleanup] public static new void ClassCleanup() { SharedTestSuiteBase.ClassCleanup(); } #endregion #region Test Case Initialization /// <summary> /// A method used to initialize the test class. /// </summary> [TestInitialize] public void S13_PutChangesInitialization() { // Initialize the default file URL. this.DefaultFileUrl = this.PrepareFile(); } #endregion #region Test Cases /// <summary> /// A method used to test the Put Changes subRequest processing. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC01_PutChanges_ValidExpectedStorageIndexExtendedGUID() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Query changes from the protocol server CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID()); CellStorageResponse queryResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { queryChange }); CellSubResponseType querySubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(queryResponse, 0, 0, this.Site); this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(querySubResponse.ErrorCode, this.Site), "The operation QueryChanges should succeed."); FsshttpbResponse fsshttpbResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(querySubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(fsshttpbResponse, this.Site); ExGuid storageIndex = fsshttpbResponse.CellSubResponses[0].GetSubResponseData<QueryChangesSubResponseData>().StorageIndexExtendedGUID; // Create a putChanges cellSubRequest FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(SharedTestSuiteHelper.GenerateRandomFileContent(this.Site), out storageIndexExGuid); PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); putChange.ExpectedStorageIndexExtendedGUID = storageIndex; dataElements.AddRange(fsshttpbResponse.DataElementPackage.DataElements); cellRequest.AddSubRequest(putChange, dataElements); CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); // Put changes to the protocol server CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); // Expect the operation succeeds this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The PutChanges operation should succeed."); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R936 Site.CaptureRequirementIfAreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "MS-FSSHTTPB", 936, @"[In Put Changes] Expected Storage Index Extended GUID (variable): If the expected Storage Index was specified and the key that is to be updated in the protocol server’s StorageIindex exists in the expected storage index, the corresponding values in the protocol server’s storage index and the expected Storage Index MUST match."); } else { Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), @"[In Put Changes] Expected Storage Index Extended GUID (variable): If the expected storage index was specified and the key that is to be updated in the protocol server’s storage index exists in the expected storage index, the corresponding values in the protocol server’s storage index and the expected storage index MUST match."); } fsshttpbResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(fsshttpbResponse, this.Site); // Create a putChanges cellSubRequest ExGuid storageIndexExGuid2; List<DataElement> dataElements1 = DataElementUtils.BuildDataElements(SharedTestSuiteHelper.GenerateRandomFileContent(this.Site), out storageIndexExGuid2); putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid2); putChange.ExpectedStorageIndexExtendedGUID = storageIndex; cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); cellRequest.AddSubRequest(putChange, null); CellSubRequestType cellSubRequest1 = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); // Put changes to the protocol server response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest1 }); cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); fsshttpbResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R4050 Site.CaptureRequirementIfAreEqual<CellErrorCode>( CellErrorCode.Referenceddataelementnotfound, fsshttpbResponse.CellSubResponses[0].ResponseError.GetErrorData<CellError>().ErrorCode, "MS-FSSHTTPB", 4050, @"[In Put Changes] If the Extended GUID does not have the corresponding data element in the Data Element Package of the request, the protocol server MUST return a Cell Error failure value of 16 indicating the referenced data element not found failure, as specified in section 2.2"); } } /// <summary> /// A method used to verify the protocol server processes the PutChanges subRequest successfully when the ExpectedStorageIndexExtendedGUID attribute is specified and Imply Null Expected if No Mapping flag set to one. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC02_PutChanges_InvalidExpectedStorageIndexExtendedGUID() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Query changes from the protocol server CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID()); CellStorageResponse queryResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { queryChange }); CellSubResponseType querySubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(queryResponse, 0, 0, this.Site); this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(querySubResponse.ErrorCode, this.Site), "The operation QueryChanges should succeed."); FsshttpbResponse queryChangeResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(querySubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(queryChangeResponse, this.Site); // Put changes to upload the content once to change the server state. In this case, the server expected the storage index value is different with previous returned. CellSubRequestType putChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedPutChanges((ulong)SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), System.Text.Encoding.UTF8.GetBytes(SharedTestSuiteHelper.GenerateRandomString(5))); CellStorageResponse putResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { putChange }); CellSubResponseType putSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(putResponse, 0, 0, this.Site); this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(putSubResponse.ErrorCode, this.Site), "The operation PutChanges should succeed."); FsshttpbResponse putChangeResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(putSubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(putChangeResponse, this.Site); // Create a putChanges cellSubRequest with specified ExpectedStorageIndexExtendedGUID value as the step 1 returned. FsshttpbCellRequest cellRequestSecond = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(System.Text.Encoding.UTF8.GetBytes(SharedTestSuiteHelper.GenerateRandomString(5)), out storageIndexExGuid); PutChangesCellSubRequest putChangeSecond = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); // Specify ExpectedStorageIndexExtendedGUID putChangeSecond.ExpectedStorageIndexExtendedGUID = queryChangeResponse.CellSubResponses[0].GetSubResponseData<QueryChangesSubResponseData>().StorageIndexExtendedGUID; dataElements.AddRange(queryChangeResponse.DataElementPackage.DataElements); cellRequestSecond.AddSubRequest(putChangeSecond, dataElements); // Put changes to the protocol server CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequestSecond.ToBase64()); CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreNotEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "Due to the Invalid Expected StorageIndexExtendedGUID, the put changes should fail."); FsshttpbResponse fsshttpbResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R937 Site.CaptureRequirementIfAreEqual<CellErrorCode>( CellErrorCode.Coherencyfailure, fsshttpbResponse.CellSubResponses[0].ResponseError.GetErrorData<CellError>().ErrorCode, "MS-FSSHTTPB", 937, @"[In Put Changes structure] Expected Storage Index Extended GUID (variable): otherwise[If the expected Storage Index was specified and the key that is to be updated in the protocol server’s Storage Index exists in the expected Storage Index but the corresponding values in the protocol server’s Storage Index and the expected Storage Index doesn't match] the protocol server MUST return a Cell Error Coherency failure value of 12 indicating a coherency failure as specified in section 2.2.3.2.1."); } else { Site.Assert.AreEqual<CellErrorCode>( CellErrorCode.Coherencyfailure, fsshttpbResponse.CellSubResponses[0].ResponseError.GetErrorData<CellError>().ErrorCode, @"[In Put Changes structure] Expected Storage Index Extended GUID (variable): otherwise[If the expected storage index was specified and the key that is to be updated in the protocol server’s storage index exists in the expected storage index but the corresponding values in the protocol server’s storage index and the expected storage index doesn't match] the protocol server MUST return a Cell Error Coherency failure value of 12 indicating a coherency failure as specified in section 2.2.3.2.1."); } } /// <summary> /// A method used to test the protocol server apply the change successfully when the ExpectedStorageIndexExtendedGUID attribute is not specified and Imply Null Expected if No Mapping flag set to zero. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC03_PutChanges_NotSpecifiedExpectedStorageIndexExtendedGUID_ImplyFlagZero() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Create a putChanges cellSubRequest without specified Expected Storage Index Extended GUID attribute and Imply Null Expected if No Mapping flag set to zero FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(System.Text.Encoding.Unicode.GetBytes(Common.GenerateResourceName(this.Site, "FileContent")), out storageIndexExGuid); PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); // Assign the ImplyNullExpectedIfNoMapping equal to 0 to make apply the change without checking the expected storage index value. putChange.ImplyNullExpectedIfNoMapping = 0; cellRequest.AddSubRequest(putChange, dataElements); CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); // Put changes to the protocol server CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "Test case cannot continue unless the put changes operation on the file {0} succeed.", this.DefaultFileUrl); FsshttpbResponse putChangeResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(putChangeResponse, this.Site); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // If the PutChanges operation succeeds, then capture MS-FSSHTTPB_R939 Site.CaptureRequirement( "MS-FSSHTTPB", 939, @"[In Put Changes structure] Expected Storage Index Extended GUID (variable): If this flag[Imply Null Expected if No Mapping] is zero, the protocol server MUST apply the change without checking the current value."); } } /// <summary> /// A method used to test the protocol server apply the change successfully when a mapping exists and Imply Null Expected if No Mapping flag set to zero. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC04_PutChanges_MappingExist_ImplyFlagZero() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Query changes from the protocol server to get the current server storage index extended guid for the specified file. CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID()); CellStorageResponse queryResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { queryChange }); CellSubResponseType querySubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(queryResponse, 0, 0, this.Site); this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(querySubResponse.ErrorCode, this.Site), "The operation QueryChanges should succeed."); FsshttpbResponse queryChangeResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(querySubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(queryChangeResponse, this.Site); // Restore the current server storage index extended guid. ExGuid storageIndex = queryChangeResponse.CellSubResponses[0].GetSubResponseData<QueryChangesSubResponseData>().StorageIndexExtendedGUID; // Create a putChanges cellSubRequest specified the Expected Storage Index Extended GUID tribute and Imply Null Expected if No Mapping flag set to one // Also use the server returns the data elements, in this case the key will exist. FsshttpbCellRequest cellRequestFirst = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndex); // Assign the ImplyNullExpectedIfNoMapping to 0. putChange.ImplyNullExpectedIfNoMapping = 0; putChange.ExpectedStorageIndexExtendedGUID = storageIndex; cellRequestFirst.AddSubRequest(putChange, queryChangeResponse.DataElementPackage.DataElements); CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequestFirst.ToBase64()); // Put changes to the protocol server to expect the server responds the success. CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The first PutChanges operation should succeed."); } /// <summary> /// A method used to test the protocol server returns a coherency failure when a mapping exists and Imply Null Expected if No Mapping flag set to one. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC05_PutChanges_MappingExist_ImplyFlagOne() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Query changes from the protocol server to get the current server storage index extended guid for the specified file. CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID()); CellStorageResponse queryResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { queryChange }); CellSubResponseType querySubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(queryResponse, 0, 0, this.Site); this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(querySubResponse.ErrorCode, this.Site), "The operation QueryChanges should succeed."); FsshttpbResponse queryChangeResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(querySubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(queryChangeResponse, this.Site); // Restore the current server storage index extended guid. ExGuid storageIndex = queryChangeResponse.CellSubResponses[0].GetSubResponseData<QueryChangesSubResponseData>().StorageIndexExtendedGUID; // Create a putChanges cellSubRequest specified the Expected Storage Index Extended GUID tribute and Imply Null Expected if No Mapping flag set to one // Also use the server returns the data elements, in this case the key will exist. FsshttpbCellRequest cellRequestFirst = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndex); // Assign the ImplyNullExpectedIfNoMapping to 1. putChange.ImplyNullExpectedIfNoMapping = 1; putChange.ExpectedStorageIndexExtendedGUID = storageIndex; cellRequestFirst.AddSubRequest(putChange, queryChangeResponse.DataElementPackage.DataElements); CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequestFirst.ToBase64()); // Put changes to the protocol server to expect the server responds the Coherency failure error. CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The PutChanges operation should succeed."); } /// <summary> /// A method used to test the protocol server apply the change failed when the ExpectedStorageIndexExtendedGUID attribute is not specified and Imply Null Expected if No Mapping flag set to zero. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC06_PutChanges_NotSpecifiedExpectedStorageIndexExtendedGUID_ImplyFlagOne() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Create a putChanges cellSubRequest without specified Expected Storage Index Extended GUID attribute and Imply Null Expected if No Mapping flag set to zero FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(System.Text.Encoding.Unicode.GetBytes(Common.GenerateResourceName(this.Site, "FileContent")), out storageIndexExGuid); PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); // Assign the ImplyNullExpectedIfNoMapping equal to 1 to make apply the change with checking the expected storage index value. putChange.ImplyNullExpectedIfNoMapping = 1; cellRequest.AddSubRequest(putChange, dataElements); CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); // Put changes to the protocol server CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreNotEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "Test case cannot continue unless the put changes operation on the file {0} failed.", this.DefaultFileUrl); FsshttpbResponse putChangeResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); CellError cellError = (CellError)putChangeResponse.CellSubResponses[0].ResponseError.ErrorData; if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTP requirement: MS-FSSHTTPB_R941 Site.CaptureRequirementIfAreEqual<CellErrorCode>( CellErrorCode.Coherencyfailure, cellError.ErrorCode, "MS-FSSHTTPB", 941, @"[In Put Changes structure] Expected Storage Index Extended GUID (variable): [if Imply Null Expected if No Mapping flag specifies 1,] If a mapping exists, the protocol server MUST return a Cell Error failure value of 12 indicating a coherency failure as specified in section 2.2.3.2.1."); } else { Site.Assert.AreEqual<CellErrorCode>( CellErrorCode.Coherencyfailure, cellError.ErrorCode, @"[In Put Changes structure] Expected Storage Index Extended GUID (variable): [if Imply Null Expected if No Mapping flag specifies 1,] If the Expected Storage Index Extended GUID is not specified, the protocol server returns a Cell Error failure value of 12 indicating a coherency failure as specified in section 2.2.3.2.1."); } } /// <summary> /// A method used to verify the requirements related with Priority. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC07_PutChanges_Prioriy() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Create the first Put changes subRequest with Priority attribute value set to 0. FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuidFirst; List<DataElement> dataElementsFirst = DataElementUtils.BuildDataElements(System.Text.Encoding.UTF8.GetBytes("First Content"), out storageIndexExGuidFirst); PutChangesCellSubRequest putChangeFirst = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuidFirst); putChangeFirst.Priority = 0; cellRequest.AddSubRequest(putChangeFirst, dataElementsFirst); // Create the second Put changes subRequest with Priority attribute value set to 100. ExGuid storageIndexExGuidSecond; List<DataElement> dataElementsSecond = DataElementUtils.BuildDataElements(System.Text.Encoding.UTF8.GetBytes("Second Content"), out storageIndexExGuidSecond); PutChangesCellSubRequest putChangeSecond = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuidSecond); putChangeSecond.Priority = 100; cellRequest.AddSubRequest(putChangeSecond, dataElementsSecond); // Send PutChanges subRequest to the protocol server. CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "Test case cannot continue unless the put changes succeed."); // Query changes from the protocol server. CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID()); response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { queryChange }); cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "Test case cannot continue unless the put changes succeed."); if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 4110, this.Site)) { Site.CaptureRequirement( "MS-FSSHTTPB", 4110, @"[In Appendix B: Product Behavior] Implementation does execute Sub-requests with different or same Priority in any order with respect to each other. (<8> Section 2.2.2.1: SharePoint Server 2010 and SharePoint Server 2013 execute Sub-requests with different or same Priority in any order with respect to each other.)"); } } /// <summary> /// A method used to test the protocol server returns a coherency failure instead of Referenced Data Element Not Found when the D - Favor Coherency Failure Over Not Found attribute is specified. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC08_PutChanges_FavorCoherencyFailureOverNotFound() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Query changes from the protocol server CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID()); CellStorageResponse queryResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { queryChange }); CellSubResponseType querySubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(queryResponse, 0, 0, this.Site); this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(querySubResponse.ErrorCode, this.Site), "The operation QueryChanges should succeed."); FsshttpbResponse fsshttpbResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(querySubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(fsshttpbResponse, this.Site); // Put changes to upload the content once. CellSubRequestType putChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedPutChanges((ulong)SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), System.Text.Encoding.UTF8.GetBytes(SharedTestSuiteHelper.GenerateRandomString(5))); CellStorageResponse putResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { putChange }); CellSubResponseType putSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(putResponse, 0, 0, this.Site); this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(putSubResponse.ErrorCode, this.Site), "The operation PutChanges should succeed."); FsshttpbResponse putChangeResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(putSubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(putChangeResponse, this.Site); // Create a putChanges cellSubRequest with nonexistent ExpectedStorageIndexExtendedGUID FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(System.Text.Encoding.Unicode.GetBytes(Common.GenerateResourceName(this.Site, this.DefaultFileUrl)), out storageIndexExGuid); PutChangesCellSubRequest putChangeSecond = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); putChangeSecond.ExpectedStorageIndexExtendedGUID = fsshttpbResponse.CellSubResponses[0].GetSubResponseData<QueryChangesSubResponseData>().StorageIndexExtendedGUID; // Favor the coherency failure other than not found element. putChangeSecond.FavorCoherencyFailureOverNotFound = 1; cellRequest.AddSubRequest(putChangeSecond, dataElements); CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); // Put changes to the protocol server CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); fsshttpbResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); // For Microsoft product, in this case the server still responses Referenceddataelementnotfound. if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 51701, SharedContext.Current.Site)) { Site.CaptureRequirementIfAreEqual<string>( "referenceddataelementnotfound".ToLower(CultureInfo.CurrentCulture), fsshttpbResponse.CellSubResponses[0].ResponseError.ErrorData.ErrorDetail.ToLower(CultureInfo.CurrentCulture), "MS-FSSHTTPB", 51701, @"[In Put Changes] Implementation does return a Referenced Data Element Not Found failure, when D - Favor Coherency Failure Over Not Found is set to 1 and a Referenced Data Element Not Found (section 2.2.3.2.1) failure occurred. (SharePoint 2010 and above follow this behavior.)"); } } else { this.Site.Assert.AreEqual<string>( "Referenceddataelementnotfound".ToLower(CultureInfo.CurrentCulture), fsshttpbResponse.CellSubResponses[0].ResponseError.ErrorData.ErrorDetail.ToLower(CultureInfo.CurrentCulture), "For Microsoft, the server still responses Referenceddataelementnotfound even the FavorCoherencyFailureOverNotFound is set to 1."); } } /// <summary> /// A method used to test the protocol server returns rough same put changes response when the DataPackage's reserved value is different in the request. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC09_PutChanges_DataPackageReservedIgnore() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Create a putChanges cellSubRequest without specified ExpectedStorageIndexExtendedGUID attribute and Imply Null Expected if No Mapping flag set to zero FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(SharedTestSuiteHelper.GenerateRandomFileContent(this.Site), out storageIndexExGuid); PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); cellRequest.AddSubRequest(putChange, dataElements); // Make the DataElementPackage reserved value to 0. cellRequest.DataElementPackage.Reserved = 0; CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "Test case cannot continue unless the put changes operation on the file {0} succeed.", this.DefaultFileUrl); FsshttpbResponse putChangeResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(putChangeResponse, this.Site); // Create a putChanges cellSubRequest without specified ExpectedStorageIndexExtendedGUID attribute and Imply Null Expected if No Mapping flag set to zero FsshttpbCellRequest cellRequestSecond = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuidSecond; List<DataElement> dataElementsSecond = DataElementUtils.BuildDataElements(SharedTestSuiteHelper.GenerateRandomFileContent(this.Site), out storageIndexExGuidSecond); PutChangesCellSubRequest putChangeSecond = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuidSecond); cellRequestSecond.AddSubRequest(putChangeSecond, dataElementsSecond); // Make the DataElementPackage reserved value to 1. cellRequestSecond.DataElementPackage.Reserved = 1; CellSubRequestType cellSubRequestSecond = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequestSecond.ToBase64()); CellStorageResponse responseSecond = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequestSecond }); CellSubResponseType cellSubResponseSecond = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(responseSecond, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponseSecond.ErrorCode, this.Site), "Test case cannot continue unless the put changes operation on the file {0} succeed.", this.DefaultFileUrl); FsshttpbResponse putChangeResponseSecond = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponseSecond, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(putChangeResponseSecond, this.Site); // Compare this two responses roughly, and if these two response are identical in main part, then capture the requirement MS-FSSHTTPB_R371 bool isVerifyR371 = SharedTestSuiteHelper.CompareSucceedFsshttpbPutChangesResponse(putChangeResponse, putChangeResponseSecond, this.Site); this.Site.Log.Add(TestTools.LogEntryKind.Debug, "Expect the two put changes responses are same, actual {0}", isVerifyR371); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R371 Site.CaptureRequirementIfIsTrue( isVerifyR371, "MS-FSSHTTPB", 371, @"[In Data Element Package] Whenever the Reserved field is set to 0 or 1, the protocol server must return the same response."); } else { Site.Assert.IsTrue( isVerifyR371, @"[In Data Element Package] Whenever the Reserved field is set to 0 or 1, the protocol server must return the same response."); } } /// <summary> /// A method used to test the protocol server can accept partial creating file contents. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC10_PutChanges_Partial() { string fileUrl = Common.GetConfigurationPropertyValue("BigFile", this.Site); // Initialize the service this.InitializeContext(fileUrl, this.UserName01, this.Password01, this.Domain); CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID()); CellStorageResponse response = Adapter.CellStorageRequest(fileUrl, new SubRequestType[] { queryChange }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), @"Test case cannot continue unless the query change operation succeeds."); FsshttpbResponse fsshttpbResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(fsshttpbResponse, this.Site); // Get the file contents byte[] bytes = new IntermediateNodeObject.RootNodeObjectBuilder() .Build(fsshttpbResponse.DataElementPackage.DataElements, fsshttpbResponse.CellSubResponses[0].GetSubResponseData<QueryChangesSubResponseData>().StorageIndexExtendedGUID) .GetContent() .ToArray(); // Update file contents byte[] newBytes = SharedTestSuiteHelper.GenerateRandomFileContent(Site); System.Array.Copy(newBytes, 0, bytes, 0, newBytes.Length); FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(bytes, out storageIndexExGuid); // Send the first partial put changes sub request null storageIndexExGuid. PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), null); cellRequest.AddSubRequest(putChange, dataElements.Take(4).ToList()); putChange.Partial = 1; CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); response = Adapter.CellStorageRequest(fileUrl, new SubRequestType[] { cellSubRequest }); cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); // Expect the operation succeeds this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The PutChanges operation should succeed."); fsshttpbResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(fsshttpbResponse, this.Site); // Send the last partial put changes sub request cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); putChange.PartialLast = 1; cellRequest.AddSubRequest(putChange, dataElements.Skip(4).ToList()); cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); cellSubRequest.SubRequestData.CoalesceSpecified = true; cellSubRequest.SubRequestData.Coalesce = true; response = Adapter.CellStorageRequest(fileUrl, new SubRequestType[] { cellSubRequest }); cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The PutChanges operation should succeed."); fsshttpbResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(fsshttpbResponse, this.Site); } /// <summary> /// A method used to verify whether A–Reserved (1 bit) is set to zero or 1, the protocol server returns the same response. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC11_PutChanges_AReserved() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Create a putChanges cellSubRequest A-Reserved (1 bit) set to zero. FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(SharedTestSuiteHelper.GenerateRandomFileContent(this.Site), out storageIndexExGuid); PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); cellRequest.AddSubRequest(putChange, dataElements); cellRequest.Reserve1 = 0; cellRequest.IsRequestHashingOptionsUsed = true; CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); CellStorageResponse response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The first PutChanges operation should succeed."); // Extract the Fsshttpb response FsshttpbResponse fsshttpbResponseFirst = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); // Create a putChanges cellSubRequest A-Reserved (1 bit) set to 1. cellRequest.Reserve1 = 1; cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The second PutChanges operation should succeed."); // Extract the fsshttpb response FsshttpbResponse fsshttpbResponseSecond = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); // If the main part of the two subResponse is same, then capture MS-FSSHTTPB requirement: MS-FSSHTTPB_R990251 bool isVerifiedR990251 = SharedTestSuiteHelper.CompareSucceedFsshttpbPutChangesResponse(fsshttpbResponseFirst, fsshttpbResponseSecond, this.Site); this.Site.Log.Add(TestTools.LogEntryKind.Debug, "Expect the two put changes responses are same, actual {0}", isVerifiedR990251); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { Site.CaptureRequirementIfIsTrue( isVerifiedR990251, "MS-FSSHTTPB", 990251, @"[In Request Message Syntax] Whenever the[A – Reserved (1 bit, optional) field is set to 0 or 1, the protocol server must return the same response."); } else { Site.Assert.IsTrue(isVerifiedR990251, @"[In Request Message Syntax] Whenever the[A – Reserved (1 bit) field is set to 0 or 1, the protocol server must return the same response."); } } /// <summary> /// A method used to verify whether B–Reserved (1 bit) is set to zero or 1, the protocol server returns the same response. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC12_PutChanges_BReserved() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Create a putChanges cellSubRequest B-Reserved (1 bit) set to zero. FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(SharedTestSuiteHelper.GenerateRandomFileContent(this.Site), out storageIndexExGuid); PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); cellRequest.AddSubRequest(putChange, dataElements); cellRequest.Reserve2 = 0; cellRequest.IsRequestHashingOptionsUsed = true; CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); CellStorageResponse response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The first PutChanges operation should succeed."); // Extract the fsshttpb response FsshttpbResponse fsshttpbResponseFirst = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); // Create a putChanges cellSubRequest B-Reserved (1 bit) set to 1. cellRequest.Reserve2 = 1; cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The second PutChanges operation should succeed."); // Extract the fsshttpb response FsshttpbResponse fsshttpbResponseSecond = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); // If the main part of the two subResponse is same, then capture MS-FSSHTTPB requirement: MS-FSSHTTPB_R990271 bool isVerifiedR990271 = SharedTestSuiteHelper.CompareSucceedFsshttpbPutChangesResponse(fsshttpbResponseFirst, fsshttpbResponseSecond, this.Site); this.Site.Log.Add(TestTools.LogEntryKind.Debug, "Expect the two put changes responses are same, actual {0}", isVerifiedR990271); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { Site.CaptureRequirementIfIsTrue( isVerifiedR990271, "MS-FSSHTTPB", 990271, @"[In Request Message Syntax] Whenever the[B – Reserved (1 bit, optional) field is set to 0 or 1, the protocol server must return the same response."); } else { Site.Assert.IsTrue(isVerifiedR990271, @"[In Request Message Syntax] Whenever the[B – Reserved (1 bit) field is set to 0 or 1, the protocol server must return the same response."); } } /// <summary> /// A method used to verify whether E–Reserved (1 bit) is set to zero or 1, the protocol server returns the same response. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC13_PutChanges_EReserved() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Create a putChanges cellSubRequest E-Reserved (1 bit) set to zero. FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(SharedTestSuiteHelper.GenerateRandomFileContent(this.Site), out storageIndexExGuid); PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); cellRequest.AddSubRequest(putChange, dataElements); cellRequest.Reserve3 = 0; cellRequest.IsRequestHashingOptionsUsed = true; CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); CellStorageResponse response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The first PutChanges operation should succeed."); // Extract the fsshttpb response FsshttpbResponse fsshttpbResponseFirst = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); // Create a putChanges cellSubRequest E-Reserved (1 bit) set to 1. cellRequest.Reserve3 = 1; cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The second PutChanges operation should succeed."); // Extract the fsshttpb response FsshttpbResponse fsshttpbResponseSecond = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); // If the main part of the two subResponse is same, then capture MS-FSSHTTPB requirement: MS-FSSHTTPB_R990271 bool isVerifiedR990341 = SharedTestSuiteHelper.CompareSucceedFsshttpbPutChangesResponse(fsshttpbResponseFirst, fsshttpbResponseSecond, this.Site); this.Site.Log.Add(TestTools.LogEntryKind.Debug, "Expect the two put changes responses are same, actual {0}", isVerifiedR990341); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { Site.CaptureRequirementIfIsTrue( isVerifiedR990341, "MS-FSSHTTPB", 990341, @"[In Request Message Syntax] Whenever the[E – Reserved (4 bit, optional) field is set to 0 or 1, the protocol server must return the same response."); } else { Site.Assert.IsTrue(isVerifiedR990341, @"[In Request Message Syntax] Whenever the[E – Reserved (4 bit) field is set to 0 or 1, the protocol server must return the same response."); } } /// <summary> /// A method used to verify whether E-Abort Remaining Put Changes on Failure (1 bit) is set to zero or 1, the protocol server returns the same response. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC14_PutChanges_EAbort() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Create a putChanges cellSubRequest E-Abort Remaining Put Changes On Failure (1 bit) set to zero. FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(SharedTestSuiteHelper.GenerateRandomFileContent(this.Site), out storageIndexExGuid); PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); putChange.AbortRemainingPutChangesOnFailure = 0; cellRequest.AddSubRequest(putChange, dataElements); CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); CellStorageResponse response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The first PutChanges operation should succeed."); // Extract the fsshttpb response FsshttpbResponse fsshttpbResponseFirst = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); // Create a putChanges cellSubRequest E-Abort Remaining Put Changes On Failure (1 bit) set to 1. cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); putChange.AbortRemainingPutChangesOnFailure = 1; cellRequest.AddSubRequest(putChange, dataElements); cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The second PutChanges operation should succeed."); // Extract the fsshttpb response FsshttpbResponse fsshttpbResponseSecond = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); // If the main part of the two subResponse is same, then capture MS-FSSHTTPB requirement: MS-FSSHTTPB_R990271 bool isVerifiedR51801 = SharedTestSuiteHelper.CompareSucceedFsshttpbPutChangesResponse(fsshttpbResponseFirst, fsshttpbResponseSecond, this.Site); this.Site.Log.Add(TestTools.LogEntryKind.Debug, "Expect the two put changes responses are same, actual {0}", isVerifiedR51801); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { Site.CaptureRequirementIfIsTrue( isVerifiedR51801, "MS-FSSHTTPB", 51801, @"[In Put Changes] Whenever the E - Abort Remaining Put Changes on Failure field is set to 0 or 1, the protocol server must return the same response."); } else { Site.Assert.IsTrue(isVerifiedR51801, @"[In Put Changes] Whenever the E - Abort Remaining Put Changes on Failure field is set to 0 or 1, the protocol server must return the same response."); } } /// <summary> /// A method used to verify whether Reserved (11 bits) Flag is set to zero or 1, the protocol server returns the same response. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC15_PutChanges_Reserved() { if (!Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 99108, this.Site)) { Site.Assume.Inconclusive("Implementation does not support the Additional Flags."); } // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Create a putChanges cellSubRequest Reserved set to zero. FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(SharedTestSuiteHelper.GenerateRandomFileContent(this.Site), out storageIndexExGuid); PutChangesCellSubRequest putChangeFirst = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); putChangeFirst.IsAdditionalFlagsUsed = true; putChangeFirst.Reserve = 0; cellRequest.AddSubRequest(putChangeFirst, dataElements); CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); CellStorageResponse response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The first PutChanges operation should succeed."); // Extract the first fsshttpb subResponse FsshttpbResponse fsshttpbResponseFirst = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); // Create another putChanges subRequest with Reserved set to 1. cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); PutChangesCellSubRequest putChangeSecond = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); putChangeSecond.IsAdditionalFlagsUsed = true; putChangeSecond.Reserve = 1; cellRequest.AddSubRequest(putChangeSecond, dataElements); cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); response = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); // Extract the second fsshttpb subResponse cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The second PutChanges operation should succeed."); FsshttpbResponse fsshttpbResponseSecond = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); // If the main part of the two subResponse is same, then capture MS-FSSHTTPB requirement: MS-FSSHTTPB_R990271 bool isVerifiedR99054 = SharedTestSuiteHelper.CompareSucceedFsshttpbPutChangesResponse(fsshttpbResponseFirst, fsshttpbResponseSecond, this.Site); this.Site.Log.Add(TestTools.LogEntryKind.Debug, "Expect the two put changes responses are same, actual {0}", isVerifiedR99054); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { Site.CaptureRequirementIfIsTrue( isVerifiedR99054, "MS-FSSHTTPB", 99054, @"[Additional Flags] The server response is the same whether the Reserved (11 bits) Flag is set to 0 or 1."); } else { Site.Assert.IsTrue( isVerifiedR99054, "[Additional Flags] The server response is the same whether the Reserved (11 bits) Flag is set to 0 or 1."); } } /// <summary> /// A method used to verify the protocol server does not return the Applied Storage Index Id when the ReturnAppliedStorageIndexIdEntries set to 0. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC16_PutChanges_ReturnAppliedStorageIndexIdEntries_Zero() { if (!Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 99108, this.Site)) { Site.Assume.Inconclusive("Implementation does not support the Additional Flags."); } // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Create a putChanges cellSubRequest without specified ExpectedStorageIndexExtendedGUID attribute and Imply Null Expected if No Mapping flag set to zero FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(SharedTestSuiteHelper.GenerateRandomFileContent(this.Site), out storageIndexExGuid); PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); // Make the ReturnAppliedStorageIndexIdEntries value to 0. putChange.IsAdditionalFlagsUsed = true; putChange.ReturnAppliedStorageIndexIdEntries = 0; cellRequest.AddSubRequest(putChange, dataElements); CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "Test case cannot continue unless the put changes operation on the file {0} succeed.", this.DefaultFileUrl); FsshttpbResponse putChangeResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(putChangeResponse, this.Site); bool notInlcudeStorageIndex = putChangeResponse.CellSubResponses[0].GetSubResponseData<PutChangesSubResponseData>().PutChangesResponse != null && new ExGuid().Equals(putChangeResponse.CellSubResponses[0].GetSubResponseData<PutChangesSubResponseData>().PutChangesResponse.AppliedStorageIndexID); Site.Log.Add( TestTools.LogEntryKind.Debug, "When the ReturnAppliedStorageIndexIdEntries flag is not set, the server will not return AppliedStorageIndexID, actually it {0} return", notInlcudeStorageIndex ? "does not" : "does"); Site.Assert.IsTrue( notInlcudeStorageIndex, "When the ReturnAppliedStorageIndexIdEntries flag is not set, the server will not return AppliedStorageIndexID"); } /// <summary> /// A method used to verify the protocol server return the Applied Storage Index Id successfully when the ReturnAppliedStorageIndexIdEntries set to 1. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC17_PutChanges_ReturnAppliedStorageIndexIdEntries_One() { if (!Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 99108, this.Site)) { Site.Assume.Inconclusive("Implementation does not support the Additional Flags."); } // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Create a putChanges cellSubRequest without specified ExpectedStorageIndexExtendedGUID attribute and Imply Null Expected if No Mapping flag set to zero FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(SharedTestSuiteHelper.GenerateRandomFileContent(this.Site), out storageIndexExGuid); PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); // Make the ReturnAppliedStorageIndexIdEntries value to 1. putChange.IsAdditionalFlagsUsed = true; putChange.ReturnAppliedStorageIndexIdEntries = 1; cellRequest.AddSubRequest(putChange, dataElements); CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "Test case cannot continue unless the put changes operation on the file {0} succeed.", this.DefaultFileUrl); FsshttpbResponse putChangeResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(putChangeResponse, this.Site); bool isVerifyR99044 = putChangeResponse.CellSubResponses[0].GetSubResponseData<PutChangesSubResponseData>().PutChangesResponse != null && !new ExGuid().Equals(putChangeResponse.CellSubResponses[0].GetSubResponseData<PutChangesSubResponseData>().PutChangesResponse.AppliedStorageIndexID); Site.Log.Add( TestTools.LogEntryKind.Debug, "When the ReturnAppliedStorageIndexIdEntries flag is set, the server will return AppliedStorageIndexID, actually it {0} return", isVerifyR99044 ? "does" : "does not"); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R99044 Site.CaptureRequirementIfIsTrue( isVerifyR99044, "MS-FSSHTTPB", 99044, @"[Additional Flags] A – Return Applied Storage Index Id Entries (1 bit): A bit that specifies that the Storage Indexes that are applied to the storage as part of the Put Changes will be returned in a Storage Index specified in the Put Changes response by the Applied Storage Index Id (section 2.2.3.1.3)."); // Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R99108 Site.CaptureRequirement( "MS-FSSHTTPB", 99108, @"[Appendix B: Product Behavior] Additional Flags is supported by SharePoint Server 2013 and SharePoint Server 2016."); } else { Site.Assert.IsTrue( isVerifyR99044, @"[Additional Flags] A – Return Applied Storage Index Id Entries (1 bit): A bit that specifies that the Storage Indexes that are applied to the storage as part of the Put Changes will be returned in a Storage Index specified in the Put Changes response by the Applied Storage Index Id (section 2.2.3.1.3)."); } } /// <summary> /// A method used to verify the protocol server return in a Data Element Collection successfully when the Return Data Elements Added set to 1. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC18_PutChanges_ReturnDataElementsAddedFlag_One() { if (!Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 99108, this.Site)) { Site.Assume.Inconclusive("Implementation does not support the Additional Flags."); } // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Create a putChanges cellSubRequest without specified ExpectedStorageIndexExtendedGUID attribute and Imply Null Expected if No Mapping flag set to zero FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(SharedTestSuiteHelper.GenerateRandomFileContent(this.Site), out storageIndexExGuid); PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); // Make the ReturnDataElementsAdded value to 1. putChange.IsAdditionalFlagsUsed = true; putChange.ReturnDataElementsAdded = 1; cellRequest.AddSubRequest(putChange, dataElements); CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "Test case cannot continue unless the put changes operation on the file {0} succeed.", this.DefaultFileUrl); FsshttpbResponse putChangeResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(putChangeResponse, this.Site); bool isVerifyR99045002 = putChangeResponse.CellSubResponses[0].GetSubResponseData<PutChangesSubResponseData>().PutChangesResponse != null && putChangeResponse.CellSubResponses[0].GetSubResponseData<PutChangesSubResponseData>().PutChangesResponse.DataElementAdded != null && putChangeResponse.CellSubResponses[0].GetSubResponseData<PutChangesSubResponseData>().PutChangesResponse.DataElementAdded.Count.DecodedValue != 0; Site.Log.Add( TestTools.LogEntryKind.Debug, "When the ReturnDataElementsAdded flag is set, the server will return the added data elements, actually it {0} return", isVerifyR99045002 ? "does" : "does not"); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R99045002 Site.CaptureRequirementIfIsTrue( isVerifyR99045002, "MS-FSSHTTPB", 99045002, @"[Additional Flags] B – Return Data Elements Added (1 bit): When the ReturnDataElementsAdded flag is set, the server will return the added data elements."); } else { Site.Assert.IsTrue( isVerifyR99045002, @"[Additional Flags] B – Return Data Elements Added (1 bit): When the ReturnDataElementsAdded flag is set, the server will return the added data elements."); } } /// <summary> /// A method used to verify the protocol server does not return in a Data Element Collection when the Return Data Elements Added set to 0. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC19_PutChanges_ReturnDataElementsAddedFlag_Zero() { if (!Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 99108, this.Site)) { Site.Assume.Inconclusive("Implementation does not support the Additional Flags."); } // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Create a putChanges cellSubRequest without specified ExpectedStorageIndexExtendedGUID attribute and Imply Null Expected if No Mapping flag set to zero FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(SharedTestSuiteHelper.GenerateRandomFileContent(this.Site), out storageIndexExGuid); PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); // Make the ReturnDataElementsAdded value to 0. putChange.IsAdditionalFlagsUsed = true; putChange.ReturnDataElementsAdded = 0; cellRequest.AddSubRequest(putChange, dataElements); CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "Test case cannot continue unless the put changes operation on the file {0} succeed.", this.DefaultFileUrl); FsshttpbResponse putChangeResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(putChangeResponse, this.Site); bool notIncludeAddedDataElements = putChangeResponse.CellSubResponses[0].GetSubResponseData<PutChangesSubResponseData>().PutChangesResponse != null && putChangeResponse.CellSubResponses[0].GetSubResponseData<PutChangesSubResponseData>().PutChangesResponse.DataElementAdded != null && putChangeResponse.CellSubResponses[0].GetSubResponseData<PutChangesSubResponseData>().PutChangesResponse.DataElementAdded.Count.DecodedValue == 0; Site.Log.Add( TestTools.LogEntryKind.Debug, "When the ReturnDataElementsAdded flag is set, the server will not return the added data elements, actually it {0} return", notIncludeAddedDataElements ? "does not" : "does"); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 99045001, this.Site)) { Site.CaptureRequirementIfIsTrue( notIncludeAddedDataElements, 99045001, @"[Additional Flags] B – Return Data Elements Added (1 bit): When the ReturnDataElementsAdded flag is not set, the server will not return the added data elements."); } } else { if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 99045001, this.Site)) { Site.Assert.IsTrue( notIncludeAddedDataElements, @"When the ReturnDataElementsAdded flag is not set, the server will not return the added data elements"); } } } /// <summary> /// A method used to verify server check the index entry that is actually applied when Coherency Check Only Applied Index Entries set to 1. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC20_PutChanges_CheckForIdReuse() { if (!Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 99108, this.Site)) { Site.Assume.Inconclusive("Implementation does not support the Additional Flags."); } // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Query changes from the protocol server CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID()); CellStorageResponse queryResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { queryChange }); CellSubResponseType querySubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(queryResponse, 0, 0, this.Site); this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(querySubResponse.ErrorCode, this.Site), "The operation QueryChanges should succeed."); FsshttpbResponse fsshttpbResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(querySubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(fsshttpbResponse, this.Site); var preGroupData = fsshttpbResponse.DataElementPackage.DataElements.First(e => e.DataElementType == DataElementType.ObjectGroupDataElementData); // Change the new object group data element's element id as the previous step returned id, this will make the data element id for reusing. ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(SharedTestSuiteHelper.GenerateRandomFileContent(this.Site), out storageIndexExGuid); var groupData = dataElements.First(e => e.DataElementType == DataElementType.ObjectGroupDataElementData); groupData.DataElementExtendedGUID = preGroupData.DataElementExtendedGUID; // Send the upload put changes request with CheckForIdReuse value as 1. FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); cellRequest.AddSubRequest(putChange, dataElements); putChange.IsAdditionalFlagsUsed = true; putChange.CheckForIdReuse = 1; CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); fsshttpbResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); Site.Assert.AreEqual<CellErrorCode>( CellErrorCode.ExtendedGuidCollision, fsshttpbResponse.CellSubResponses[0].ResponseError.GetErrorData<CellError>().ErrorCode, "When the data element id is reused, the server will respond the error code ExtendedGuidCollision"); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R99049 Site.CaptureRequirementIfAreEqual<ErrorCodeType>( ErrorCodeType.CellRequestFail, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "MS-FSSHTTPB", 99049, @"[Additional Flags] When D – Coherency Check Only Applied Index Entries (1 bit) is set, the server check the index entry that is actually applied and an index entry that is not applied is not checked."); Site.CaptureRequirementIfAreEqual<ErrorCodeType>( ErrorCodeType.CellRequestFail, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "MS-FSSHTTPB", 99046, @"[Additional Flags] C – Check for Id Reuse (1 bit): A bit that specifies that the server will attempt to check the Put Changes request for the re-use of previously used IDs. "); Site.CaptureRequirementIfAreEqual<ErrorCodeType>( ErrorCodeType.CellRequestFail, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "MS-FSSHTTPB", 99047, @"[Additional Flags] This [check the Put Changes Request for the re-use of previously used Ids] might occur when ID allocations are used and a client rollback occurs."); } else { Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.CellRequestFail, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), @"[Additional Flags] When D - Coherency Check Only Applied Index Entries (1 bit) is set, the server check the index entry that is actually applied and an index entry that is not applied is not checked."); } } /// <summary> /// A method used to verify server will not bypass the necessary checks when the FullFileReplacePut flag is true. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC21_PutChanges_FullFileReplacePut() { if (!Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 99108, this.Site)) { Site.Assume.Inconclusive("Implementation does not support the Additional Flags."); } // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Query changes from the protocol server CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID()); CellStorageResponse queryResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { queryChange }); CellSubResponseType querySubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(queryResponse, 0, 0, this.Site); this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(querySubResponse.ErrorCode, this.Site), "The operation QueryChanges should succeed."); FsshttpbResponse queryChangeResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(querySubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(queryChangeResponse, this.Site); // Put changes to upload the content once to change the server state. In this case, the server expected the storage index value is different with previous returned. CellSubRequestType putChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedPutChanges((ulong)SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), System.Text.Encoding.UTF8.GetBytes(SharedTestSuiteHelper.GenerateRandomString(5))); CellStorageResponse putResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { putChange }); CellSubResponseType putSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(putResponse, 0, 0, this.Site); this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(putSubResponse.ErrorCode, this.Site), "The operation PutChanges should succeed."); FsshttpbResponse putChangeResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(putSubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(putChangeResponse, this.Site); // Create a putChanges cellSubRequest with specified ExpectedStorageIndexExtendedGUID value as the step 1 returned and with the full file replace put flag as 1. FsshttpbCellRequest cellRequestSecond = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(System.Text.Encoding.UTF8.GetBytes(SharedTestSuiteHelper.GenerateRandomString(5)), out storageIndexExGuid); PutChangesCellSubRequest putChangeSecond = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); // Specify ExpectedStorageIndexExtendedGUID and FullFileReplacePut flag. putChangeSecond.ExpectedStorageIndexExtendedGUID = queryChangeResponse.CellSubResponses[0].GetSubResponseData<QueryChangesSubResponseData>().StorageIndexExtendedGUID; putChangeSecond.IsAdditionalFlagsUsed = true; putChangeSecond.FullFileReplacePut = 1; dataElements.AddRange(queryChangeResponse.DataElementPackage.DataElements); cellRequestSecond.AddSubRequest(putChangeSecond, dataElements); // Put changes to the protocol server CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequestSecond.ToBase64()); CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreNotEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "Due to the Invalid Expected StorageIndexExtendedGUID, the put changes should fail."); FsshttpbResponse fsshttpbResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 9905101, SharedContext.Current.Site)) { Site.CaptureRequirementIfAreEqual<CellErrorCode>( CellErrorCode.Coherencyfailure, fsshttpbResponse.CellSubResponses[0].ResponseError.GetErrorData<CellError>().ErrorCode, "MS-FSSHTTPB", 9905101, @"[In Appendix B: Product Behavior] Implementation does not bypass a full file save and related checks that would otherwise be unnecessary, when his flag [E – Full File Replace Put (1 bit)] is set. (Microsoft SharePoint Server 2010 and Microsoft SharePoint Workspace 2010 and above follow this behavior.)"); } } else { Site.Assert.AreEqual<CellErrorCode>( CellErrorCode.Coherencyfailure, fsshttpbResponse.CellSubResponses[0].ResponseError.GetErrorData<CellError>().ErrorCode, @"[In Appendix B: Product Behavior] Implementation does not bypass a full file save and related checks that would otherwise be unnecessary, when his flag [E – Full File Replace Put (1 bit)] is set. (Microsoft SharePoint Server 2010 and Microsoft SharePoint Workspace 2010 and above follow this behavior.)"); } } /// <summary> /// A method used to verify server will not bypass the necessary checks when the ForceRevisionChainOptimization flag is false. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC22_PutChanges_ForceRevisionChainOptimization_Zero() { if (!Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 4130, this.Site)) { Site.Assume.Inconclusive("Implementation does not support the Diagnostic Request Option Output field."); } // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Create a putChanges cellSubRequest with specified DiagnosticRequestOptionInput attribute and ForceRevisionChainOptimization set to zero FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(SharedTestSuiteHelper.GenerateRandomFileContent(this.Site), out storageIndexExGuid); PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); putChange.IsDiagnosticRequestOptionInputUsed = true; putChange.ForceRevisionChainOptimization = 0; cellRequest.AddSubRequest(putChange, dataElements); CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "Test case cannot continue unless the put changes operation on the file {0} succeed.", this.DefaultFileUrl); FsshttpbResponse putChangeResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(putChangeResponse, this.Site); bool isForced = putChangeResponse.CellSubResponses[0].GetSubResponseData<PutChangesSubResponseData>().DiagnosticRequestOptionOutput.IsDiagnosticRequestOptionOutput; if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R409502 Site.CaptureRequirementIfIsFalse( isForced, "MS-FSSHTTPB", 409502, @"[In Put Changes] F – Forced (1 bit): [False] specifies whether a forced Revision Chain optimization [does not] occurred."); } else { Site.Assert.IsFalse( isForced, @"[In Put Changes] F – Forced (1 bit): [False] specifies whether a forced Revision Chain optimization [does not] occurred."); } } /// <summary> /// A method used to verify if the key that is to be updated in the protocol server's Storage Index does not exist in the /// expected Storage Index, the Imply Null Expected if No Mapping flag MUST be evaluated. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC23_PutChanges_ImplyFlagWithKeyNotExist() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Query changes from the protocol server CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID()); CellStorageResponse queryResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { queryChange }); CellSubResponseType querySubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(queryResponse, 0, 0, this.Site); this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(querySubResponse.ErrorCode, this.Site), "The operation QueryChanges should succeed."); FsshttpbResponse fsshttpbResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(querySubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(fsshttpbResponse, this.Site); ExGuid storageIndex = fsshttpbResponse.CellSubResponses[0].GetSubResponseData<QueryChangesSubResponseData>().StorageIndexExtendedGUID; // Create a putChanges cellSubRequest with specify expected Storage Index and ImplyNullExpectedIfNoMapping set to 0. FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(SharedTestSuiteHelper.GenerateRandomFileContent(this.Site), out storageIndexExGuid); PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); putChange.ExpectedStorageIndexExtendedGUID = storageIndex; putChange.ImplyNullExpectedIfNoMapping = 0; dataElements.AddRange(fsshttpbResponse.DataElementPackage.DataElements); cellRequest.AddSubRequest(putChange, dataElements); CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); // Put changes to the protocol server CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); // If the key that is to be updated in the protocol server’s Storage Index does not exist in the expected Storage Index, the Imply Null Expected if No Mapping flag MUST be evaluated. // If this flag is zero, the protocol server MUST apply the change without checking the current value. this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The PutChanges operation should succeed."); queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID()); queryResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { queryChange }); querySubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(queryResponse, 0, 0, this.Site); this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(querySubResponse.ErrorCode, this.Site), "The operation QueryChanges should succeed."); fsshttpbResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(querySubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(fsshttpbResponse, this.Site); ExGuid index2 = storageIndex; storageIndex = fsshttpbResponse.CellSubResponses[0].GetSubResponseData<QueryChangesSubResponseData>().StorageIndexExtendedGUID; // Create a putChanges cellSubRequest with specify expected Storage Index and ImplyNullExpectedIfNoMapping set to 1. cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); dataElements = DataElementUtils.BuildDataElements(SharedTestSuiteHelper.GenerateRandomFileContent(this.Site), out storageIndexExGuid); putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); putChange.ExpectedStorageIndexExtendedGUID = storageIndex; putChange.ImplyNullExpectedIfNoMapping = 1; dataElements.AddRange(fsshttpbResponse.DataElementPackage.DataElements); cellRequest.AddSubRequest(putChange, dataElements); cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64()); // Put changes to the protocol server response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); // If the key that is to be updated in the protocol server’s Storage Index does not exist in the expected Storage Index, the Imply Null Expected if No Mapping flag MUST be evaluated. // If this flag is one, the protocol server MUST only apply the change if no mapping exists. this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The PutChanges operation should succeed."); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R2168 // This requirement can be captured directly after above steps. Site.CaptureRequirement( "MS-FSSHTTPB", 2168, @"[In Put Changes] Expected Storage Index Extended GUID (variable): If the key that is to be updated in the protocol server’s Storage Index does not exist in the expected Storage Index, the Imply Null Expected if No Mapping flag MUST be evaluated."); // If the PutChanges operation succeeds, then capture MS-FSSHTTPB_R940 Site.CaptureRequirement( "MS-FSSHTTPB", 940, @"[In Put Changes structure] Expected Storage Index Extended GUID (variable): otherwise[If Imply Null Expected if No Mapping is not zero], if the flag[Imply Null Expected if No Mapping] specifies one, the protocol server MUST only apply the change if no mapping exists (the key that is to be updated in the protocol server’s Storage Index doesn't exist or it maps to nil)."); } } /// <summary> /// A method used to verify the Put Changes request will fail coherency if any of the supplied Storage Indexes are unrooted. /// </summary> [TestCategory("SHAREDTESTCASE"), TestMethod()] public void TestCase_S13_TC24_PutChanges_RequireStorageMappingsRooted() { if (!Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 99108, this.Site)) { Site.Assume.Inconclusive("Implementation does not support the Additional Flags."); } // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Query changes from the protocol server CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID()); CellStorageResponse queryResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { queryChange }); CellSubResponseType querySubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(queryResponse, 0, 0, this.Site); this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(querySubResponse.ErrorCode, this.Site), "The operation QueryChanges should succeed."); FsshttpbResponse queryChangeResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(querySubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(queryChangeResponse, this.Site); // Put changes to upload the content once to change the server state. In this case, the server expected the storage index value is different with previous returned. CellSubRequestType putChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedPutChanges((ulong)SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), System.Text.Encoding.UTF8.GetBytes(SharedTestSuiteHelper.GenerateRandomString(5))); CellStorageResponse putResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { putChange }); CellSubResponseType putSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(putResponse, 0, 0, this.Site); this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(putSubResponse.ErrorCode, this.Site), "The operation PutChanges should succeed."); FsshttpbResponse putChangeResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(putSubResponse, this.Site); SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(putChangeResponse, this.Site); // Create a putChanges cellSubRequest with specified ExpectedStorageIndexExtendedGUID value as the step 1 returned and with the Require Storage Mappings Rooted flag as 1. FsshttpbCellRequest cellRequestSecond = SharedTestSuiteHelper.CreateFsshttpbCellRequest(); ExGuid storageIndexExGuid; List<DataElement> dataElements = DataElementUtils.BuildDataElements(System.Text.Encoding.UTF8.GetBytes(SharedTestSuiteHelper.GenerateRandomString(5)), out storageIndexExGuid); PutChangesCellSubRequest putChangeSecond = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid); // Specify ExpectedStorageIndexExtendedGUID and RequireStorageMappingsRooted flag. putChangeSecond.ExpectedStorageIndexExtendedGUID = queryChangeResponse.CellSubResponses[0].GetSubResponseData<QueryChangesSubResponseData>().StorageIndexExtendedGUID; putChangeSecond.IsAdditionalFlagsUsed = true; putChangeSecond.RequireStorageMappingsRooted = 1; dataElements.AddRange(queryChangeResponse.DataElementPackage.DataElements); cellRequestSecond.AddSubRequest(putChangeSecond, dataElements); // Put changes to the protocol server CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequestSecond.ToBase64()); CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreNotEqual<ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "Due to the Invalid Expected StorageIndexExtendedGUID, the put changes should fail."); FsshttpbResponse fsshttpbResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { Site.CaptureRequirementIfAreEqual<CellErrorCode>( CellErrorCode.Coherencyfailure, fsshttpbResponse.CellSubResponses[0].ResponseError.GetErrorData<CellError>().ErrorCode, "MS-FSSHTTPB", 4054, @"[Additional Flags] F – Require Storage Mappings Rooted (1 bit): A bit that specifies that the Put Changes request will fail coherency if any of the supplied Storage Indexes are unrooted."); } else { Site.Assert.AreEqual<CellErrorCode>( CellErrorCode.Coherencyfailure, fsshttpbResponse.CellSubResponses[0].ResponseError.GetErrorData<CellError>().ErrorCode, @"[Additional Flags] F – Require Storage Mappings Rooted (1 bit): A bit that specifies that the Put Changes request will fail coherency if any of the supplied Storage Indexes are unrooted."); } } #endregion } }
74.744036
525
0.699796
[ "MIT" ]
ChangDu2021/Interop-TestSuites
FileSyncandWOPI/Source/SharedTestSuite/SharedTestCase/S13_PutChanges.cs
115,996
C#
/* * Copyright (c) 2016, InWorldz Halcyon Developers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text.RegularExpressions; using InWorldz.JWT; using LitJson; using log4net; using OpenSim.Framework.Communications.JWT; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Grid.Framework; namespace OpenSim.Grid.UserServer.Modules { public class JWTAuthenticator { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IGridServiceCore m_coreService; private UserDataBaseService m_userDataBaseService = null; private BaseHttpServer m_httpServer; private readonly Dictionary<string, int> m_levelsAllowedPerScope = new Dictionary<string, int> { {"remote-console", 250}, {"remote-admin", 250}, }; private JWTUserAuthenticationGateway m_authGateway = null; public JWTAuthenticator() { } #region Setup public void Initialize(IGridServiceCore core) { m_coreService = core; } public void PostInitialize(string privateKeyPath, string publicKeyPath) { if (m_coreService.TryGet(out m_userDataBaseService)) { m_authGateway = new JWTUserAuthenticationGateway(m_userDataBaseService, privateKeyPath, publicKeyPath); } else { m_userDataBaseService = null; } } public void RegisterHandlers(BaseHttpServer httpServer) { m_httpServer = httpServer; m_httpServer.AddStreamHandler(new RestStreamHandler("POST", "/auth/jwt/", RESTRequestToken)); } #endregion #region Handlers public string RESTRequestToken(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { httpResponse.ContentType = "application/json"; if (m_authGateway == null) { m_log.Error("[JWTAUTH] Hit a bug check: the JWT gatway is not initialized... Why?"); return JWTAuthErrors.BadAuthGateway; } if (httpRequest.ContentType != "application/json") { return JWTAuthErrors.BadJsonRead; } if (httpRequest.ContentLength <= 1) { return JWTAuthErrors.BadJsonRead; } if (!m_levelsAllowedPerScope.ContainsKey(param)) { return JWTAuthErrors.BadScope; } var username = string.Empty; var password = string.Empty; try { var data = JsonMapper.ToObject(request); username = data["username"].ToString().Trim(); password = data["password"].ToString(); } catch (Exception) { return JWTAuthErrors.BadJsonRead; } var payload = new PayloadOptions(); payload.Exp = DateTime.UtcNow.AddDays(1); payload.Scope = param; payload.Username = username; var nameSplit = Regex.Replace(username.ToLower(), @"[\s]+", " ").Split(' '); var firstname = nameSplit[0]; var lastname = nameSplit.Length > 1 ? nameSplit[1] : "resident"; try { var response = new Dictionary<string, string> { {"token", m_authGateway.Authenticate(firstname, lastname, password, m_levelsAllowedPerScope[param], payload).ToString()} }; return JsonMapper.ToJson(response); } catch (AuthenticationException ae) { m_log.Warn($"[JWTAUTH] Failed attempt to get token from {httpRequest.RemoteIPEndPoint} for user '{username}'. Error: {ae.Cause}"); return JWTAuthErrors.AuthFailed(ae.Cause.ToString()); } } #endregion static class JWTAuthErrors { public static string BadAuthGateway = JsonMapper.ToJson(new Dictionary<string, string> {{"denied","Authentication gateway not set up correctly."},}); public static string BadJsonRead = JsonMapper.ToJson(new Dictionary<string, string> {{"denied","Received bad JSON."},}); public static string BadScope = JsonMapper.ToJson(new Dictionary<string, string> {{"denied","Unrecognized scope request."},}); public static string AuthFailed(string reason) {return JsonMapper.ToJson(new Dictionary<string, string> { { "denied", reason }, });} public static string Unexpected = JsonMapper.ToJson(new Dictionary<string, string> {{"denied","Unexpected error."},}); } } }
38.532934
161
0.634654
[ "BSD-3-Clause" ]
Ana-Green/halcyon-1
OpenSim/Grid/UserServer.Modules/JWTAuthenticator.cs
6,437
C#
namespace Dec.DiscordIPC.Commands.Interfaces { public interface IDummyCommandArgs : ICommandArgs {} }
35
56
0.8
[ "Apache-2.0" ]
GStefanowich/DiscordIPC
Commands/Interfaces/IDummyCommandArgs.cs
105
C#
// // Authors: // Marek Habersack (mhabersack@novell.com) // // (C) 2010 Novell, Inc (http://www.novell.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace System.Web.UI { #if NET_2_0 sealed class MainDirectiveAttribute <T> #else sealed class MainDirectiveAttribute #endif { string unparsedValue; #if NET_2_0 T value; #else object value; #endif bool isExpression; bool isDataBound; public string UnparsedValue { get { return unparsedValue; } } public bool IsExpression { get { return isExpression; } } #if NET_2_0 public T Value { get { return value; } } #else public object Value { get { return value; } } #endif public MainDirectiveAttribute (string value) { this.unparsedValue = value; #if NET_2_0 if (value != null) this.isExpression = BaseParser.IsExpression (value); #endif } #if NET_2_0 public MainDirectiveAttribute (T value, bool unused) #else public MainDirectiveAttribute (object value) #endif { this.value = value; } } }
25.62963
73
0.725434
[ "MIT" ]
zlxy/Genesis-3D
Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/System.Web/System.Web.UI/MainDirectiveAttribute.cs
2,076
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PwrSwitch { public class PowerPlan { public Guid guid { get; } public string name { get; } public PowerPlan(Guid guid, string name) { this.guid = guid; this.name = name; } } }
18.238095
48
0.590078
[ "MIT" ]
ohnx/PwrSwitch
PowerPlan.cs
385
C#
namespace GitVersion { using System; using System.Linq; using System.Reflection; class VersionWriter { public static void Write(Assembly assembly) { WriteTo(assembly, Console.WriteLine); } public static void WriteTo(Assembly assembly, Action<string> writeAction) { var version = GetAssemblyVersion(assembly); writeAction(version); } private static string GetAssemblyVersion(Assembly assembly) { if (assembly .GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false) .FirstOrDefault() is AssemblyInformationalVersionAttribute attribute) { return attribute.InformationalVersion; } return assembly.GetName().Version.ToString(); } } }
27.636364
91
0.582237
[ "MIT" ]
Bankers88/GitVersion
src/GitVersionExe/VersionWriter.cs
880
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; namespace InvoluteGears { /// <summary> /// Describe the shape of an escape wheel /// with inclined sharp teeth. /// </summary> public class EscapeGearParameters : IGearProfile { public EscapeGearParameters( int toothCount, double module, double undercutAngle, double toothFaceLength, double tipPitch, double cutDiameter, double maxErr) { ToothCount = toothCount; Module = module; UndercutAngle = undercutAngle; ToothFaceLength = toothFaceLength; TipPitch = tipPitch; CutDiameter = cutDiameter; MaxError = maxErr; SetInformation(); CalculatePoints(); } private void SetInformation() { Information = $"Escape: {ToothCount} teeth, module = {Module}mm, undercut angle = {UndercutAngle * 180 / Math.PI:N1}\u00b0\r\n"; Information += $"tooth face = {ToothFaceLength}mm, precision = {MaxError}mm\r\n"; Information += $"tip width = {TipPitch}mm, tooth gap diameter = {CutDiameter}mm\r\n"; } public string ShortName => $"Et{ToothCount}m{Module:N2}u{UndercutAngle * 180 / Math.PI:N1}f{ToothFaceLength:N2}" + $"e{MaxError:N2}p{TipPitch:N2}c{CutDiameter:N2}.svg"; /// <summary> /// Used for warning or information messages when methods invoked /// </summary> public string Information { get; private set; } /// <summary> /// The accuracy of the points in the profile /// </summary> public double MaxError { get; private set; } /// <summary> /// The diameter of the curved part of the /// cut into the gear. Must be larger than /// the bit used to cut out the gear. /// </summary> public double CutDiameter { get; private set; } /// <summary> /// The number of teeth around the outside of the /// gear wheel. These are evenly spaced obviously. /// </summary> public int ToothCount { get; private set; } /// <summary> /// The angle between the radial from the centre of /// the gear and the surface of the tooth end. Note /// that unlike the pressure angle of an involute /// gear, this angle is the undercut angle as the /// escape wheel teeth are oblique. /// </summary> public double UndercutAngle { get; private set; } /// <summary> /// The length of the flat face of a tooth from /// the tooth tip to the point at which it curves /// back for the next tooth trailing edge. /// </summary> public double ToothFaceLength { get; private set; } /// <summary> /// The extra diameter needed per extra tooth for a /// given tooth width. In practice this value is often /// used to determine pitch circle diameter and tooth /// separation, rather than the other way round. /// Units in mm. /// </summary> public double Module { get; private set; } /// <summary> /// The distance round the pitch circle for /// the thickness of the tooth tip. /// </summary> public double TipPitch { get; private set; } // --- DERIVED PROPERTIES --- // /// <summary> /// The pitch circle diameter for an escape /// wheel is its true diameter to the ends of /// the teeth. /// </summary> public double PitchCircleDiameter => Module * ToothCount; /// <summary> /// The distance between adjacent teeth around the pitch circle /// </summary> public double Pitch => Math.PI * Module; /// <summary> /// The angle occupied by one tooth and one gap /// </summary> public double ToothAngle => 2 * Math.PI / ToothCount; /// <summary> /// The angle at the centre of the gear subtended by /// the width of the tip of a tooth. /// </summary> public double TipAngle => 2 * TipPitch / (ToothCount * Module); /// <summary> /// The angle at the centre of the gear subtended by /// the width of the gap between two teeth. /// </summary> public double GapAngle => ToothAngle - TipAngle; private PointF ToothTip; private PointF UnderCutCentre; private PointF FaceEnd; private PointF BackTip; private double BackAngle; private List<PointF> OneToothProfile; private void CalculatePoints() { // Unrotated tooth tip is on the X axis ToothTip = Involutes.CreatePt(PitchCircleDiameter / 2, 0); // Navigate down the slope of the tooth face FaceEnd = Involutes.CreatePt( PitchCircleDiameter / 2 - ToothFaceLength * Math.Cos(UndercutAngle), -ToothFaceLength * Math.Sin(UndercutAngle)); // Now find the centre of the undercut circle UnderCutCentre = Involutes.CreatePt (FaceEnd.X - CutDiameter * Math.Sin(UndercutAngle) / 2, FaceEnd.Y + CutDiameter * Math.Cos(UndercutAngle) / 2); // Find the coordinates of the back tip corner of // the next tooth in an anticlockwise direction BackTip = Involutes.CreatePt(ToothTip.X * Math.Cos(GapAngle), ToothTip.X * Math.Sin(GapAngle)); // Find the coordinates of the tangent to the // undercut circle of a line drawn from the // back of the tooth tip double tipToEndAngle = Math.Asin(CutDiameter / (2 * Involutes.DistanceBetween(BackTip, UnderCutCentre))); double tiptoCtrAngle = Math.Atan2(BackTip.Y - UnderCutCentre.Y, BackTip.X - UnderCutCentre.X); BackAngle = tiptoCtrAngle + Math.PI / 2 - tipToEndAngle; OneToothProfile = ComputeOnePitch(); } private List<PointF> ComputeOnePitch() { List<PointF> points = new() { ToothTip, FaceEnd }; double startAngle = -Math.PI / 2 + UndercutAngle; points.AddRange( Involutes.CirclePoints( BackAngle, 2 * Math.PI + startAngle, Involutes.AngleStep, CutDiameter / 2, UnderCutCentre) .Reverse()); points.Add(BackTip); points.AddRange( Involutes.CirclePoints( GapAngle, ToothAngle, Involutes.AngleStep, PitchCircleDiameter / 2)); return Involutes.LinearReduction(points, (float)MaxError); } /// <summary> /// Generate the sequence of points describing the /// shape of a single tooth profile /// </summary> /// <param name="gap">Which tooth profile we want. /// For gap = 0, we generate the tooth whose /// tip lies on the positive X axis. Teeth rotate /// anticlockwise from there for increasing /// values of gap.</param> /// <returns>The set of points describing the /// profile of the selected tooth.</returns> public IEnumerable<PointF> ToothProfile(int gap) => Involutes.RotateAboutOrigin ((gap % ToothCount) * ToothAngle, OneToothProfile); /// <summary> /// Generate the complete path of /// points for the whole escape wheel /// </summary> /// <returns>The set of points describing the escape wheel /// </returns> public IEnumerable<PointF> GenerateCompleteGearPath() => Enumerable .Range(0, ToothCount) .Select(i => ToothProfile(i)) .SelectMany(p => p); /// <summary> /// The distance from the centre of the gear to the /// closest part of the curve between leading and /// trailing faces of the teeth. /// </summary> public double InnerDiameter => 2 * Involutes.DistanceBetween(UnderCutCentre, PointF.Empty) - CutDiameter; } }
34.028
140
0.56189
[ "MIT", "Unlicense" ]
RopleyIT/InvoluteGears
InvoluteGears/EscapeGearParameters.cs
8,509
C#
using System; using System.Collections.Generic; using System.Text; using Newtonsoft.Json; using System.IO; namespace BotDiscord { class Config { private const string configFolder = "Resources"; private const string configFile = "config.json"; static BotConfig bot; static Config() { if (!Directory.Exists(configFolder)) Directory.CreateDirectory(configFolder); if(!File.Exists(configFolder + "/" + configFile)) { bot = new BotConfig(); string json = JsonConvert.SerializeObject(bot, Formatting.Indented); File.WriteAllText(configFolder + "/" + configFile, json); } else { string json = File.ReadAllText(configFolder + "/" + configFile); var data = JsonConvert.DeserializeObject<BotConfig>(json); } } } public struct BotConfig { public string token; public string cmdPrefix; } }
25.071429
84
0.565052
[ "MIT" ]
Dakusy/BotDiscord
Config.cs
1,055
C#
using System; using System.IO; using System.Reactive.Concurrency; using System.Reactive.Linq; namespace Akavache { public class SimpleFilesystemProvider : IFilesystemProvider { public IObservable<Stream> SafeOpenFileAsync(string path, FileMode mode, FileAccess access, FileShare share, IScheduler scheduler) { return Utility.SafeOpenFileAsync(path, mode, access, share, scheduler).Select(x => (Stream) x); } public void CreateRecursive(string path) { Utility.CreateRecursive(new DirectoryInfo(path)); } public void Delete(string path) { File.Delete(path); } } }
27.36
138
0.654971
[ "MIT" ]
anurse/Akavache
Akavache/SimpleFilesystemProvider.cs
684
C#
using System; using NpcService.Ai.NpcType; namespace NpcService.Ai.NpcCitizen { public class Malcom10 : Citizen { } }
13.1
35
0.70229
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
dr3dd/L2Interlude
NpcService/Ai/NpcCitizen/Malcom10.cs
131
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Diagnostics; using System.IO; using System.Threading; // make sure that using System.Drawing.Imaging; is included using System.Drawing.Imaging; namespace Color_to_Gray { public partial class FormColorToGray : Form { Bitmap bit; Image file; public FormColorToGray() { InitializeComponent(); } Bitmap grayScaleBP = new System.Drawing.Bitmap(2, 2, System.Drawing.Imaging.PixelFormat.Format16bppGrayScale); private void lblLink_Click(object sender, EventArgs e) { Process.Start("http://www.vclexamples.com/"); } private void button1_Click(object sender, EventArgs e) { if (pictureBox1.Image == null) { return; } pictureBox1.Image = bit; for (int x = 0; x < bit.Width; x++) { for (int y = 0; y < bit.Height; y++) { Color originalColor = bit.GetPixel(x, y); int grayScale = (int)((originalColor.R * .3) + (originalColor.G * .59) + (originalColor.B * .11)); Color newColor = Color.FromArgb(grayScale, grayScale, grayScale); bit.SetPixel(x, y, newColor); } } pictureBox1.Image = bit; } private void button2_Click(object sender, EventArgs e) { openFileDialog1.FileName = ""; DialogResult dr = openFileDialog1.ShowDialog(); if (dr == DialogResult.OK) { file = Image.FromFile(openFileDialog1.FileName.ToString()); pictureBox1.Image = file; bit = new Bitmap(openFileDialog1.FileName.ToString()); } } } }
29.797101
118
0.55642
[ "Apache-2.0" ]
coderserdar/CSharpExamples
SourceCode/Color to Gray/Color to Gray/FormColorToGray.cs
2,058
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.ContainerService.V20200301.Outputs { [OutputType] public sealed class ManagedClusterServicePrincipalProfileResponse { /// <summary> /// The ID for the service principal. /// </summary> public readonly string ClientId; /// <summary> /// The secret password associated with the service principal in plain text. /// </summary> public readonly string? Secret; [OutputConstructor] private ManagedClusterServicePrincipalProfileResponse( string clientId, string? secret) { ClientId = clientId; Secret = secret; } } }
27.833333
84
0.647705
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/ContainerService/V20200301/Outputs/ManagedClusterServicePrincipalProfileResponse.cs
1,002
C#
using Microsoft.Extensions.Configuration; namespace dFakto.States.Workers.FileStores { public class FileStoreConfig { public string Name { get; set; } public string Type { get; set; } public IConfigurationSection Config { get; set; } } }
24.909091
57
0.671533
[ "MIT" ]
depfac/dFakto.States.Workers
dFakto.States.Workers/FileStores/FileStoreConfig.cs
274
C#
// __ _ __ __ ___ __ ___ ___ // | \| |/__\ /' _/ / _//__\| _ \ __| // | | ' | \/ |`._`.| \_| \/ | v / _| // |_|\__|\__/ |___/ \__/\__/|_|_\___| // ----------------------------------- using System.Collections.Generic; using NosCore.Packets.Attributes; using NosCore.Packets.Enumerations; using NosCore.Packets.Interfaces; namespace NosCore.Packets.ServerPackets.Shop { [PacketHeader("pidx", Scope.InGame)] public class PidxPacket : PacketBase { [PacketIndex(0)] public long GroupId { get; set; } [PacketListIndex(1)] public List<PidxSubPacket?>? SubPackets { get; set; } } }
27.608696
61
0.55748
[ "MIT" ]
Fizo55/NosCore.Packets
src/NosCore.Packets/ServerPackets/Shop/PidxPacket.cs
637
C#
// <copyright company="Benjamin Abt ( http://www.benjamin-abt.com - http://quickIO.NET )"> // Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT // </copyright> // <author>Benjamin Abt</author> using System; using SchwabenCode.QuickIO.Engine; namespace SchwabenCode.QuickIO { /// <summary> /// Provides static methods to access folders. For example creating, deleting and retrieving content and security information such as the owner. /// </summary> public static partial class QuickIODirectory { #region GetStatistics /// <summary> /// Gets the directory statistics: total files, folders and bytes /// </summary> /// <param name="path"></param> /// <returns>A <see cref="QuickIOFolderStatisticResult"/> object that holds the folder statistics such as number of folders, files and total bytes</returns> /// <example> /// This example shows how to call <see> /// <cref>GetStatistics</cref> /// </see> /// and write the result to the console. /// <code> /// public static void GetStatistics_With_StringPath_Example() /// { /// const string targetDirectoryPath = @"C:\temp\QuickIOTest"; /// /// // Get statistics /// QuickIOFolderStatisticResult statsResult = QuickIODirectory.GetStatistics( targetDirectoryPath ); /// /// // Output /// Console.WriteLine( "[Stats] Folders: '{0}' Files: '{1}' Total TotalBytes '{2}'", statsResult.FolderCount, statsResult.FileCount, statsResult.TotalBytes ); /// } /// </code> /// </example> public static QuickIOFolderStatisticResult GetStatistics( String path ) { return GetStatistics( new QuickIOPathInfo( path ) ); } /// <summary> /// Gets the directory statistics: total files, folders and bytes /// </summary> /// <param name="pathInfo"></param> /// <returns>A <see cref="QuickIOFolderStatisticResult"/> object that holds the folder statistics such as number of folders, files and total bytes</returns> /// <example> /// This example shows how to call <see> /// <cref>GetStatistics</cref> /// </see> /// with <see cref="QuickIOPathInfo"/> and write the result to the console. /// <code> ///public static void GetStatistics_With_PathInfo_Example() ///{ /// QuickIOPathInfo targetDirectoryPathInfo = new QuickIOPathInfo( @"C:\temp\QuickIOTest" ); /// /// // Get statistics /// QuickIOFolderStatisticResult stats = QuickIODirectory.GetStatistics( targetDirectoryPathInfo ); /// /// // Output /// Console.WriteLine( "[Stats] Folders: '{0}' Files: '{1}' Total TotalBytes '{2}'", stats.FolderCount, stats.FileCount, stats.TotalBytes ); ///} /// </code> /// </example> public static QuickIOFolderStatisticResult GetStatistics( QuickIOPathInfo pathInfo ) { return QuickIOEngine.GetDirectoryStatistics( pathInfo ); } /// <summary> /// Gets the directory statistics: total files, folders and bytes /// </summary> /// <param name="directoryInfo"></param> /// <returns>A <see cref="QuickIOFolderStatisticResult"/> object that holds the folder statistics such as number of folders, files and total bytes</returns> /// <example> /// This example shows how to call <see> /// <cref>GetStatistics</cref> /// </see> /// with <see cref="QuickIODirectoryInfo"/> and write the result to the console. /// <code> ///public static void GetStatistics_With_DirectoryInfo_Example() ///{ /// QuickIODirectoryInfo targetDirectoryPathInfo = new QuickIODirectoryInfo( @"C:\temp\QuickIOTest" ); /// /// // Get statistics /// QuickIOFolderStatisticResult stats = QuickIODirectory.GetStatistics( targetDirectoryPathInfo ); /// /// // Output /// Console.WriteLine( "[Stats] Folders: '{0}' Files: '{1}' Total TotalBytes '{2}'", stats.FolderCount, stats.FileCount, stats.TotalBytes ); ///} /// </code> /// </example> public static QuickIOFolderStatisticResult GetStatistics( QuickIODirectoryInfo directoryInfo ) { return QuickIOEngine.GetDirectoryStatistics( directoryInfo.PathInfo ); } #endregion } }
44.596154
169
0.599828
[ "MIT" ]
SVemulapalli/QuickIO
src/SchwabenCode.QuickIO/QuickIODirectory.Statistics.cs
4,640
C#
// ----------------------------------------------------------------------- // <copyright file="DocumentNavigator.cs" company=""> // TODO: Update copyright text. // </copyright> // ----------------------------------------------------------------------- using DjvuNet.DataChunks.Navigation.Interfaces; namespace DjvuNet.DataChunks.Navigation { using System; using System.Collections.Generic; using System.Linq; using System.Text; /// <summary> /// TODO: Update summary. /// </summary> public class DocumentNavigator : INavigation { #region Public Properties #region Bookmarks private Bookmark[] _bookmarks; /// <summary> /// Gets the list of document bookmarks /// </summary> public Bookmark[] Bookmarks { get { return _bookmarks; } private set { if (Bookmarks != value) { _bookmarks = value; } } } #endregion Bookmarks #endregion Public Properties #region Constructors public DocumentNavigator(DjvuDocument document) { BuildNavigation(document); } #endregion Constructors #region Private Methods private void BuildNavigation(DjvuDocument document) { List<Bookmark> bookmarks = new List<Bookmark>(); for (int x = 0; x < document.Pages.Length; x++) { DjvuPage page = document.Pages[x]; int pageNum = x + 1; bookmarks.Add(new Bookmark(document, null, string.Format("Page {0}", pageNum), string.Format("#{0}", pageNum), new Bookmark[0])); } _bookmarks = bookmarks.ToArray(); } #endregion Private Methods } }
25.714286
146
0.472222
[ "MIT" ]
Telavian/DjvuNet
DjvuNet/DjvuNet/DataChunks/Navigation/DocumentNavigator.cs
1,982
C#
using System; using System.Linq; using Inventor.Semantics; using Inventor.Semantics.Questions; namespace Samples.Semantics.Sample05.CustomStatement { public class GetShorterQuestion : Question { public IConcept Person { get; } public GetShorterQuestion(IConcept person) { if (person == null) throw new ArgumentNullException(nameof(person)); Person = person; } public override IAnswer Process(IQuestionProcessingContext context) { return context .From<GetShorterQuestion, IsTallerThanStatement>() .WithTransitives( statements => true, c => c.SemanticNetwork.Statements .OfType<IsTallerThanStatement>() .Where(s => s.TallerPerson == c.Question.Person) .Select(s => new NestedQuestion( new GetShorterQuestion(s.ShorterPerson), new IStatement[] { s })), true) .Where(s => s.TallerPerson == Person) .SelectAllConcepts( statement => statement.ShorterPerson, question => question.Person, "#TALLER#", language => $"#TALLER# is taller than", concepts => concepts.Distinct()); } } }
24.886364
71
0.686758
[ "MIT" ]
CourageAndrey/AI
Code/Samples/Inventor.Semantics.Sample05.CustomStatement/GetShorterQuestion.cs
1,097
C#
using System; using System.Xml; class Program { static void Main() { var catalogue = new XmlDocument(); catalogue.Load("../../../catalogue.xml"); int targetYear = DateTime.Now.Year - 5; string xPathQuery = "/catalogue/album[year <= " + targetYear + "]"; XmlNodeList albumsOlderThanFourYears = catalogue.SelectNodes(xPathQuery); foreach (XmlNode album in albumsOlderThanFourYears) { Console.WriteLine("Album name: {0}, Artist: {1} Year: {2}, Price: {3}", album["name"].InnerText, album["artist"].InnerText, album["year"].InnerText, album["price"].InnerText); } } }
28.083333
119
0.599407
[ "MIT" ]
GeorgiPetrovGH/TelerikAcademy
11.Databases/02.XML Processing in .NET/XMLProcessing/ExtractAlbumPrices/Program.cs
676
C#
using System; using System.Collections.Generic; using OpenRasta.TypeSystem.ReflectionBased; namespace OpenRasta.TypeSystem.Surrogates.Static { public class CollectionIndexerSurrogateBuilder : AbstractStaticSurrogateBuilder { public override bool CanCreateFor(Type type) { return type.FindInterface(typeof(ICollection<>)) != null && type.FindInterface(typeof(IList<>)) == null; } public override Type Create(Type type) { return typeof(CollectionIndexerSurrogate<>).MakeGenericType( type.FindInterface(typeof(ICollection<>)).GetGenericArguments()[0]); } } }
33
85
0.649351
[ "MIT" ]
openrasta/openrasta-core
src/OpenRasta/TypeSystem/Surrogates/Static/CollectionIndexerSurrogateBuilder.cs
693
C#
/* * Copyright(c) 2016 - 2019 Puma Security, LLC (https://www.pumascan.com) * * Project Leader: Eric Johnson (eric.johnson@pumascan.com) * Lead Developer: Eric Mead (eric.mead@pumascan.com) * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Puma.Security.Rules.Analyzer.Core; using Puma.Security.Rules.Common; using Puma.Security.Rules.Common.Extensions; namespace Puma.Security.Rules.Analyzer.Validation.Path.Core { internal class MvcFileResultExpressionAnalyzer : IMvcFileResultExpressionAnalyzer { public SyntaxNode Source { get; set; } public bool IsVulnerable(SemanticModel model, ObjectCreationExpressionSyntax syntax, DiagnosticId ruleId) { if (!containsCommands(syntax)) return false; var symbol = model.GetSymbolInfo(syntax).Symbol as IMethodSymbol; if (!isConstructor(symbol)) return false; if (syntax.ArgumentList.Arguments.Count == 0) return false; var arg = syntax.ArgumentList.Arguments[0].Expression; //var argSyntax = arg.Expression; var expressionAnalyzer = SyntaxNodeAnalyzerFactory.Create(arg); if (expressionAnalyzer.CanIgnore(model, arg)) return false; if (expressionAnalyzer.CanSuppress(model, arg, ruleId)) return false; Source = arg; return true; } private bool containsCommands(ObjectCreationExpressionSyntax syntax) { return syntax.ToString().Contains("FilePathResult") || syntax.ToString().Contains("FileStreamResult"); } private bool isConstructor(IMethodSymbol symbol) { return symbol.IsCtorFor("System.Web.Mvc.FilePathResult") || symbol.IsCtorFor("System.Web.Mvc.FileStreamResult"); } } }
33.40625
113
0.648737
[ "MPL-2.0" ]
gregpakes/puma-scan
Puma.Security.Rules/Analyzer/Validation/Path/Core/MvcFileResultExpressionAnalyzer.cs
2,138
C#
using System; using System.Collections.Generic; using System.Text; namespace Department.Base.Model.Recommendations { public partial class UsageEvent { public DateTime? CreatedDate { get; set; } public string CustomerId { get; set; } public string StoreId { get; set; } public string ItemId { get; set; } public string EventType { get; set; } public string Id { get; set; } } }
24.388889
50
0.640091
[ "Apache-2.0" ]
takemurakimio/department-store
DepartmentStoreOne.Base.Model/Recommendations/UsageEvent.cs
439
C#
using Spoondrift.Code.Config; using Spoondrift.Code.Config.Form; using Spoondrift.Code.Util; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; namespace Spoondrift.Code.Data { public abstract class ListDataTable : IListDataTable, IDisposable { public const string PAGE_SYS = "PAGE_SYS"; public const string KEYVALUE = "KeyValue"; public string CodePlugName { get; set; } private string fRegName; // private string fDataXmlPath; //private DataBaseConfig fDataBase; public List<string> UniqueList { get; set; } public List<ColumnConfig> FullColumns { get; set; } public string Order { get; set; } public bool IsFillEmpty { get; set; } public abstract Type ObjectType { get; set; } public virtual string ForeignKey { get; set; } public DataFormConfig DataFormConfig { get; set; } public HashSet<string> ColumnLegalHashTable { get; set; } public PageStyle PageStyle { get; set; } public FormConfig ModuleFormConfig { get; set; } public virtual ColumnKind GetColumnKind(string feildName) { return DataFormConfig.Columns.Where(a => a.Name == feildName).FirstOrDefault().Kind; } public virtual void setGroupShow(DataTable dt, List<string> groupColumnList) { Dictionary<string, DataRow> _dict = new Dictionary<string, DataRow>(); for (int i = 0; i < dt.Rows.Count; i++) { DataRow row = dt.Rows[i]; foreach (string col in groupColumnList) { if (dt.Columns.Contains(col)) { this.setColGroup(dt, "_" + col + "_group_"); if (i == 0) { row["_" + col + "_group_"] = 1; _dict[col] = row; } else { var _lastVal = dt.Rows[i - 1][col]; if (_lastVal.Equals(row[col])) { row["_" + col + "_group_"] = dt.Rows[i - 1]["_" + col + "_group_"].Value<int>() + 1; if (i == dt.Rows.Count - 1) { this.setColGroup(dt, "_" + col + "_group_max_"); row["_" + col + "_group_max_"] = row["_" + col + "_group_"]; } string _groupKey = "_" + col + "_group_key_"; this.setColGroup(dt, _groupKey); row[_groupKey] = _dict[col][_dict[col].Table.PrimaryKey[0].ColumnName]; } else { if (_dict.ContainsKey(col)) { this.setColGroup(dt, "_" + col + "_group_max_"); _dict[col]["_" + col + "_group_max_"] = dt.Rows[i - 1]["_" + col + "_group_"]; } _dict[col] = row; row["_" + col + "_group_"] = 1; } } } } } } private void setColGroup(DataTable dt, string colName) { if (!dt.Columns.Contains(colName)) { dt.Columns.Add(colName); } } public virtual IEnumerable<ObjectData> List { get; set; } public virtual List<string> GroupColList { get; set; } public virtual void AppendTo(DataSet ds) { var list = List.ToList(); if (list != null && list.Count > 0) { DataTable table = list.ToDataTable<ObjectData>(); table.PrimaryKey = new DataColumn[] { table.Columns[PrimaryKey] }; if (!string.IsNullOrEmpty(RegName)) table.TableName = RegName; ds.Tables.Add(table); if (this.GroupColList != null && this.GroupColList.Count > 0) { this.setGroupShow(table, this.GroupColList); } } } public virtual string RegName { get { return fRegName; } } public abstract string PrimaryKey { get; set; } public DataSet PostDataSet { get; set; } public virtual void InsertForeach(ObjectData data, DataRow row, string key) { } public virtual void UpdateForeach(ObjectData data, DataRow row, string key) { } //Foreach public virtual void DeleteForeach(string key, string data) { } protected HashSet<string> XmlColumns { get; set; } // public virtual void MergeTable(bool isBat, bool isInsert) { //this.SubmitFilterEvent += ListDataTable_SubmitFilterEvent; //this.SubmitFilterEvent(null); } //SubmitData ListDataTable_SubmitFilterEvent(ResponseResult arg) //{ // throw new NotImplementedException(); //} public virtual void Merge(bool isBat) { DataTable dt = this.PostDataSet.Tables[RegName]; var _editorColumns = DataFormConfig.Columns.FindAll(a => a.ControlType == ControlType.Editor); if (dt != null) { for (int i = 0; i < dt.Rows.Count; i++) { _editorColumns.ForEach( a => { if (dt.Columns.Contains(a.Name)) { dt.Rows[i][a.Name] = StringUtil.HexToString(dt.Rows[i][a.Name].ToString()); } } ); } } var sysDt = this.PostDataSet.Tables[PAGE_SYS]; //该表存放主从表的主表主键值 if (sysDt != null) ForeignKeyValue = sysDt.Rows[0][KEYVALUE].ToString(); List<ObjectDataView> InsertDataViewList = new List<ObjectDataView>(); List<ObjectDataView> UpdateDataViewList = new List<ObjectDataView>(); List<string> DeleteStringList = new List<string>(); if (dt != null) { this.ObjectType = this.ObjectType ?? typeof(ObjectData); List<ObjectData> list = DataSetUtil.FillModel(dt, this.ObjectType, XmlColumns); foreach (ObjectData objectData in list) { DataRow row = objectData.Row; // DataFormConfig.Columns.Find(a=>a.Name == row.BeginEdit(); bool isInsert = !row.Table.Columns.Contains(PrimaryKey) || (row.Table.Columns.Contains(PrimaryKey) && row[PrimaryKey].Value<string>().IsEmpty()); MergeTable(isBat, isInsert); if (isInsert) { string _insertKey = GetInsertKey(objectData); //if (string.IsNullOrEmpty(ForeignKey)) //{ // var insertKeys = AppContext.Current.PageFlyweight.PageItems["InsertKeys"] as List<string>; // if (insertKeys == null) // { // AppContext.Current.PageFlyweight.PageItems.Add("InsertKeys", new List<string> { _insertKey }); // } // else // { // insertKeys.Add(_insertKey); // } //} SetPostDataRow(objectData, DataAction.Insert, _insertKey); InsertForeach(objectData, row, _insertKey); InsertDataViewList.Add(new ObjectDataView() { KeyId = _insertKey, objectData = objectData }); } else { string key = row[PrimaryKey].Value<string>(); SetPostDataRow(objectData, DataAction.Update, key); UpdateForeach(objectData, row, key); UpdateDataViewList.Add( new ObjectDataView() { KeyId = key, objectData = objectData } ); } row.EndEdit(); } } DataTable opdt = this.PostDataSet.Tables[RegName + "_OPERATION"]; if (opdt != null && opdt.Rows.Count > 0) { foreach (DataRow row in opdt.Rows) { string _key = row["KeyValue"].ToString(); if (row["OperationName"].ToString() == "Delete") { DeleteForeach(_key, ""); DeleteStringList.Add(_key); } } } bool isCheck = CheckPostData(InsertDataViewList, UpdateDataViewList, DeleteStringList); //Debug.Assert(isCheck, "数据源插件{0},的提交数据验证不通过".AkFormat(RegName), this); } public virtual bool CheckPostData(List<ObjectDataView> insertDataViewList, List<ObjectDataView> updateDataViewList, List<string> deleteStringList) { return true; } public virtual void Initialize(ModuleFormInfo info) { Order = info.Order; // fDataBase = info.DataBase; ModuleFormConfig = info.ModuleFormConfig; FullColumns = info.FullColumns; InternalInitialize(info.DataSet, info.PageSize, info.KeyValue, info.ForeignKeyValue, info.TableName, info.PrimaryKey, info.ForeignKey, info.IsFillEmpty, info.DataFormConfig); } private void InternalInitialize(DataSet dataSet, int pageSize, string keyValue, string foreignKeyValue, string tableName, string primaryKey, string foreignKey, bool isFillEmpty, DataFormConfig dataFormConfig) { // ColumnLegalHashTable = new HashSet<string>(); this.DataFormConfig = dataFormConfig; UniqueList = this.DataFormConfig.Columns.Where(a => a.IsUniqueKey).Select(a => a.Name).ToList(); //SingleUploadColumns = this.DataFormConfig.Columns.FindAll( // a => (a.ControlType == ControlType.SingleImageUpload || a.ControlType == ControlType.SingleFileUpload) && (a.Upload != null && a.Upload.HasKey)).ToList(); //MultiUploadColumns = this.DataFormConfig.Columns.FindAll( // a => (a.ControlType == ControlType.MultiImageUpload || a.ControlType == ControlType.MultiFileUpload) && (a.Upload != null && a.Upload.HasKey)).ToList(); MomeryColumns = this.DataFormConfig.Columns.FindAll( a => (a.ControlType == ControlType.Momery && !a.RegName.IsEmpty()) ).ToList(); this.KeyValues = new List<string>(); this.IsFillEmpty = isFillEmpty; this.PostDataSet = dataSet; this.KeyValue = keyValue; if (dataSet != null) { var _dtPageSys = dataSet.Tables["PAGE_SYS"]; if (_dtPageSys != null && _dtPageSys.Rows.Count > 0) { if (_dtPageSys.Columns.Contains("PageStyle")) { this.PageStyle = _dtPageSys.Rows[0]["PageStyle"].Value<PageStyle>(); } } var dt = dataSet.Tables["_KEY"]; if (dt != null && dt.Rows.Count > 0) { List<string> keyValueList = new List<string>(); foreach (DataRow row in dt.Rows) { string _key = row["KeyValue"].ToString(); keyValueList.Add(_key); } KeyValues = keyValueList; } } // if (dataSet.Tables["PAGE"]) if (RegName.IsEmpty()) { fRegName = tableName; } if (PrimaryKey.IsEmpty()) { PrimaryKey = primaryKey; } if (ForeignKey.IsEmpty()) ForeignKey = foreignKey; if (!ForeignKey.IsEmpty()) { if (foreignKeyValue.IsEmpty()) { this.ForeignKeyValue = KeyValues.Count() == 1 ? KeyValues.First() : foreignKeyValue; } else this.ForeignKeyValue = foreignKeyValue; } if (dataSet != null) { this.Pagination = new Pagination().FormDataTable(dataSet.Tables["PAGER"]); } else this.Pagination = new Pagination() { //TableName = RegName, DataTime = DateTime.Now, PageSize = pageSize }; this.Pagination.TableName = RegName; if (this.Pagination.PageSize == 0) { this.Pagination.PageSize = pageSize; } if (this.Pagination.PageSize == 0) { this.Pagination.PageSize = 20; } } public Pagination Pagination { get; set; } public string KeyValue { get; set; } public IEnumerable<string> KeyValues { get; set; } public string ForeignKeyValue { get; set; } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { if (PostDataSet != null) PostDataSet.Dispose(); } //base.Dispose(disposing); } public void AppendToEmptyRow(DataSet ds) { var list = new List<ObjectData>(); list.Add(new ObjectData()); if (list != null && list.Count > 0) { var _type = list[0].GetType(); DataTable table =list.ToDataTable<ObjectData>(); table.PrimaryKey = new DataColumn[] { table.Columns[PrimaryKey] }; if (!string.IsNullOrEmpty(RegName)) table.TableName = RegName; ds.Tables.Add(table); } } //public virtual DataBaseConfig DataBase //{ // get // { // return fDataBase; // } //} // private void FileS private List<ColumnConfig> SingleUploadColumns { get; set; } private List<ColumnConfig> MultiUploadColumns { get; set; } private List<ColumnConfig> MomeryColumns { get; set; } ///// <summary> ///// 若一条记录里有多个单上传控件字段,则每个上传控件的文件名和主键需保持一致 ///// </summary> ///// <param name="path"></param> ///// <param name="fileStorageName"></param> ///// <returns></returns> //protected string GetSingleResourceInfo(string path, string fileStorageName) //{ // if (!path.IsEmpty()) // { // var pathInfo = path.Split('&'); // string fileName = pathInfo[0].Substring(pathInfo[0].LastIndexOf('/') + 1); // string fileID = fileName.Split('.')[0]; // string pathID = fileName.Substring(0, 8); // string fileExt = Path.GetExtension(fileName); // if (FileID.IsEmpty()) // { // FileID = fileID; // } // else // { // //重命名 // string fullPath = new Uri(Path.Combine(FileManagementUtil.GetRootPath(fileStorageName, FilePathScheme.Physical), path)).LocalPath; // string dir = Path.GetDirectoryName(fullPath); // string newPath = new Uri(Path.Combine(dir, "\\" + FileID + fileExt)).LocalPath; // File.Move(fullPath, newPath); // File.Delete(fullPath); // fileID = FileID; // } // var resourceInfo = new ResourceInfo(); // resourceInfo.InfoType = ResourceInfoType.Config; // resourceInfo.FileId = fileID; // resourceInfo.PathID = pathID.Value<int>(); // resourceInfo.ExtName = fileExt; // resourceInfo.FileNameTitle = pathInfo[1]; // resourceInfo.FileSizeK = pathInfo[2].Value<int>(); // resourceInfo.StorageConfigName = fileStorageName; // return AppContext.Current.FastJson.ToJSON(resourceInfo); // } // return ""; //} //protected string GetMultiResourceInfo(string pathList, string fileStorageName) //{ // //string fileExtension = Path.GetExtension(fileName); // //string fileID = AppContext.Current.UnitOfData.GetUniId(); // //int pathID = fileID.Substring(0, 8).Value<int>(); // //string relativePath = Path.Combine(FileManagementUtil.GetRelativePath(fileStorageName, pathID), // // FileManagementUtil.GetFileName(fileStorageName, fileID, fileExtension)); // //string fullPath = new Uri(Path.Combine(FileManagementUtil.GetRootPath(fileStorageName, FilePathScheme.Physical), relativePath)).LocalPath; // //FileManagementUtil.ForeDirectories(FileManagementUtil.GetParentDirectory(fullPath)); // //string tempfile = Path.Combine(AppContext.Current.MapPath, Callback.Src(tempPath)); // //if (File.Exists(tempfile)) // //{ // // File.Copy(tempfile, fullPath, false); // // File.Delete(tempfile); // //} // if (pathList.IsEmpty()) // return ""; // var pathArr = pathList.Split(','); // string fileName = ""; // List<ResourceInfo> infoList = new List<ResourceInfo>(); // pathArr.ToList().ForEach(a => // { // if (!a.IsEmpty()) // { // var path = a.Split('&'); // fileName = path[0].Substring(path[0].LastIndexOf('\\') + 1); // string fileID = fileName.Split('.')[0]; // string pathID = fileName.Substring(0, 8); // string fileExt = Path.GetExtension(fileName); // var resourceInfo = new ResourceInfo(); // resourceInfo.InfoType = ResourceInfoType.Config; // resourceInfo.FileId = fileID; // resourceInfo.PathID = pathID.Value<int>(); // resourceInfo.ExtName = fileExt; // resourceInfo.FileNameTitle = path[1]; // resourceInfo.FileSizeK = path[2].Value<int>(); // resourceInfo.StorageConfigName = fileStorageName; // infoList.Add(resourceInfo); // } // }); // //var pathInfo = new FilePathInfo { PathID = pathID.ToString(), FileID = fileID, FileExtension = fileExtension }; // return AppContext.Current.FastJson.ToJSON(infoList); //} public virtual void SetPostDataRow(ObjectData data, DataAction dataAction, string key) { // throw new NotImplementedException(); // if(data.) if (SingleUploadColumns != null && SingleUploadColumns.Count > 0) { SingleUploadColumns.ForEach(a => { //if (data.MODEFY_COLUMNS.Contains(a.Name)) //{ // string storange = a.Upload.StorageName; // string fpath = data.Row[a.Name].ToString(); // if (!fpath.IsEmpty()) // { // ResourceArrange arrange = AppContext.Current.FastJson.ToObject<ResourceArrange>(fpath); // if (arrange != null) // { // arrange.MoveKeyPath(key, storange); // data.Row[a.Name] = AppContext.Current.FastJson.ToJSON(arrange); // } // } // //data.Row[a.Name] = GetSingleResourceInfo(fpath, a.Upload.StorageName); //} }); } if (MultiUploadColumns != null && MultiUploadColumns.Count > 0) { MultiUploadColumns.ForEach(a => { //if (data.MODEFY_COLUMNS.Contains(a.Name)) //{ // string storange = a.Upload.StorageName; // string fpath = data.Row[a.Name].ToString(); // if (!fpath.IsEmpty()) // { // ResourceArrange arrange = AppContext.Current.FastJson.ToObject<ResourceArrange>(fpath); // arrange.MoveKeyPath(key, storange); // if (arrange != null) // { // data.Row[a.Name] = AppContext.Current.FastJson.ToJSON(arrange); // } // } // // data.Row[a.Name] = GetMultiResourceInfo(fpath, a.Upload.StorageName); //} }); } if (MomeryColumns != null && MomeryColumns.Count > 0) { MomeryColumns.ForEach(a => { if (data.MODEFY_COLUMNS.Contains(a.Name)) { //string _regname = a.RegName; //IMomery rr = IocContext.Current.FetchInstance<IMomery>(_regname); //rr.AddText(data.Row[a.Name].ToString(), AppContext.Current.UnitOfData); } }); } } ///// <summary> ///// 当前的新增行中,若存在字段控件类型为单文件/图片上传控件时,该值为当前行的主键值和上传文件的文件名,该行新增后,需要清空 ///// </summary> //protected string FileID { get; set; } public abstract string GetInsertKey(ObjectData data); //private Func<SubmitData, SubmitData> fSubmitFilterFun = (a) => a; //public virtual Func<SubmitData, SubmitData> SubmitFilterFun //{ // get // { // return fSubmitFilterFun; // } //} } }
34.645207
216
0.45625
[ "MIT" ]
RookieXie/spoondrift.core
src/Spoondrift.Code/Data/ListDataTable.cs
24,473
C#
using Pluto.Domain.Events.Common; using System; namespace Pluto.Domain.Events.User { public class DeleteUserEvent : Event { public DeleteUserEvent(Guid id) { Id = id; AggregateId = Id; } public Guid Id { get; private set; } } }
16.666667
44
0.563333
[ "MIT" ]
mswinner/Pluto
Pluto.Domain/Events/User/DeleteUserEvent.cs
302
C#
using UnityEngine; using System.Collections; public class Blinking : MonoBehaviour { private bool isBlinking = false; public float TimeOn = 1f; public float TimeOff = 0.5f; IEnumerator Start() { while(true) { if (isBlinking) renderer.enabled = false; yield return new WaitForSeconds(TimeOff); renderer.enabled = true; yield return new WaitForSeconds(TimeOn); } } public void StartBlinking() { isBlinking = true; } public void StopBlinking() { isBlinking = false; } }
19.645161
53
0.582923
[ "MIT" ]
hagish/tektix
taktik/Assets/Scripts/Blinking.cs
611
C#
using System; using System.Collections.Generic; using System.Net; using System.Text; using System.Threading; namespace Downloader { public abstract class AbstractDownload : IDownload { public event DownloadDelegates.DownloadDataReceivedHandler DataReceived; public event DownloadDelegates.DownloadStartedHandler DownloadStarted; public event DownloadDelegates.DownloadCompletedHandler DownloadCompleted; public event DownloadDelegates.DownloadStoppedHandler DownloadStopped; public event DownloadDelegates.DownloadCancelledHandler DownloadCancelled; protected DownloadState state = DownloadState.Undefined; protected Uri url; protected int bufferSize; protected long? offset; protected long? maxReadBytes; protected IWebRequestBuilder requestBuilder; protected IDownloadChecker downloadChecker; protected bool stopping = false; protected readonly object monitor = new object(); public AbstractDownload(Uri url, int bufferSize, long? offset, long? maxReadBytes, IWebRequestBuilder requestBuilder, IDownloadChecker downloadChecker) { if (url == null) throw new ArgumentNullException("url"); if (bufferSize < 0) throw new ArgumentException("bufferSize < 0"); if (offset.HasValue && offset.Value < 0) throw new ArgumentException("offset < 0"); if (maxReadBytes.HasValue && maxReadBytes.Value < 0) throw new ArgumentException("maxReadBytes < 0"); this.url = url; this.bufferSize = bufferSize; this.offset = offset; this.maxReadBytes = maxReadBytes; this.requestBuilder = requestBuilder; this.downloadChecker = downloadChecker; this.state = DownloadState.Initialized; } public DownloadState State { get { return this.state; } } public virtual void Start() { lock (this.monitor) { if (this.state != DownloadState.Initialized) { throw new InvalidOperationException("Invalid state: " + this.state); } this.state = DownloadState.Running; } this.OnStart(); } public virtual void Stop() { this.DoStop(DownloadStopType.WithNotification); } protected virtual void DoStop(DownloadStopType stopType) { lock (this.monitor) { this.stopping = true; } this.OnStop(); if (stopType == DownloadStopType.WithNotification) { this.OnDownloadStopped(new DownloadEventArgs(this)); } } public virtual void Dispose() { this.Stop(); } public virtual void DetachAllHandlers() { if (this.DataReceived != null) { foreach (var i in this.DataReceived.GetInvocationList()) { this.DataReceived -= (DownloadDelegates.DownloadDataReceivedHandler)i; } } if (this.DownloadCancelled != null) { foreach (var i in this.DownloadCancelled.GetInvocationList()) { this.DownloadCancelled -= (DownloadDelegates.DownloadCancelledHandler)i; } } if (this.DownloadCompleted != null) { foreach (var i in this.DownloadCompleted.GetInvocationList()) { this.DownloadCompleted -= (DownloadDelegates.DownloadCompletedHandler)i; } } if (this.DownloadStopped != null) { foreach (var i in this.DownloadStopped.GetInvocationList()) { this.DownloadStopped -= (DownloadDelegates.DownloadStoppedHandler)i; } } if (this.DownloadStarted != null) { foreach (var i in this.DownloadStarted.GetInvocationList()) { this.DownloadStarted -= (DownloadDelegates.DownloadStartedHandler)i; } } } protected virtual void OnStart() { // Implementations should start their work here. } protected virtual void OnStop() { // This happens, when the Stop method is called. // Implementations should clean up and free their ressources here. // The stop event must not be triggered in here, it is triggered in the context of the Stop method. } protected virtual void StartThread(DownloadDelegates.VoidAction func, string name) { var thread = new Thread(new ThreadStart(func)) { Name = name }; thread.Start(); } protected virtual void OnDataReceived(DownloadDataReceivedEventArgs args) { if (this.DataReceived != null) { this.DataReceived(args); } } protected virtual void OnDownloadStarted(DownloadStartedEventArgs args) { if (this.DownloadStarted != null) { this.DownloadStarted(args); } } protected virtual void OnDownloadCompleted(DownloadEventArgs args) { if (this.DownloadCompleted != null) { this.DownloadCompleted(args); } } protected virtual void OnDownloadStopped(DownloadEventArgs args) { if (this.DownloadStopped != null) { this.DownloadStopped(args); } } protected virtual void OnDownloadCancelled(DownloadCancelledEventArgs args) { if (this.DownloadCancelled != null) { this.DownloadCancelled(args); } } } }
29.607656
159
0.555268
[ "MIT" ]
suntabu/UnityDownloader
Assets/Downloader/AbstractDownload.cs
6,190
C#
namespace Frontend.ViewModels { public class WindowControlsViewModel : ViewModelBase { } }
15.5
53
0.795699
[ "MIT" ]
p-barski/TodoListApp
Frontend/ViewModels/WindowControlsViewModel.cs
93
C#
using System; using System.Collections; using System.Collections.Generic; using Games; using NUnit.Framework; using Storage; using UnityEngine; using UnityEngine.TestTools; using Assert = UnityEngine.Assertions.Assert; namespace PlayModeTests { namespace SystemTests { namespace BackendConnectionTests { public class ElasticsearchStorageManagerTests : MonoBehaviour { // Sample battery session storage used for the test. static BatterySessionStorage batterySessionToStore = new BatterySessionStorage { BatterySessionId = new Guid(), Player = new PlayerStorage { Name = "Alan Turing", Age = 108, KeyBoard = true, Mouse = false, UserId = new Guid() }, SubScoreSeq = new List<SubscoreStorage> { new SubscoreStorage { AbilityName = Measurement.AbilityName.TIME_TO_CONTACT, GameName = Games.GameName.CATCH_THE_BALL, Score = 50, Weight = 1 }, new SubscoreStorage { AbilityName = Measurement.AbilityName.VISUOSPATIAL_SKETCHPAD, GameName = Games.GameName.SQUARES, Score = 80, Weight = 1 } }, OverallScoreSeq = new List<OverallScoreStorage> { new OverallScoreStorage { AbilityName = Measurement.AbilityName.TIME_TO_CONTACT, Score = 50, Level = Measurement.AbilityLevel.POOR }, new OverallScoreStorage { AbilityName = Measurement.AbilityName.VISUOSPATIAL_SKETCHPAD, Score = 80, Level = Measurement.AbilityLevel.GOOD } }, MiniGameOrder = new List<GameName> { GameName.CATCH_THE_BALL, GameName.BALLOONS, GameName.IMAGE_HIT, GameName.SQUARES, GameName.CATCH_THE_THIEF } }; static BatterySessionStorage retrievedBatterySession; [Description(@" <ul> <li><b>Test type:</b> System Test</li> <li><b>Associated SRS requirements:</b> None</li> <li><b>Test description:</b> This test checks a number of things: <ol> <li>It checks that a battery session storage can be successfully saved to the remote Elasticsearch.</li> <li>It checks that a battery session storage can be successfully retrieved from the remote Elasticsearch.</li> <li>It checks that there is no information lost (during JSON conversion) in the battery session when it is stored in Elasticsearch by seeing if the saved BatterySessionStorage object is equal to that which is retrieved after the former is saved.</li> </ol> </li> </ul> ")] [UnityTest] public IEnumerator WHEN_BatterySessionStoredToElasticsearchAndThenRetrieved_THEN_BatterySessionsAreEqual() { // When yielded back, the retrieved battery session will be stored in // retrievedBatterySession. yield return new MonoBehaviourTest<ElasticsearchStorageThenRetrieval>(); Assert.AreEqual(batterySessionToStore, retrievedBatterySession); } /// <summary> /// Since UnityWebRequest relies on MonoBehaviour, we need this throwaway /// class for the test. See: https://docs.unity3d.com/Packages/com.unity.test-framework@1.1/manual/reference-tests-monobehaviour.html /// </summary> class ElasticsearchStorageThenRetrieval : MonoBehaviour, IMonoBehaviourTest { public bool IsTestFinished { set; get; } = false; /// <summary> /// Stores the batterySessionToStore to Elasticsearch, and upon successful confirmation /// that it has been saved, retrieves it back from Elasticsearch by /// looking it up using its BatterySessionId. /// </summary> void Start() { IStorage storage = gameObject.AddComponent<ElasticsearchStorageManager>(); storage.Store(batterySessionToStore, () => storage.Retrieve(batterySessionToStore.BatterySessionId, retrieved => { retrievedBatterySession = retrieved; IsTestFinished = true; }) ); } } } } } }
41.630769
149
0.501663
[ "MIT" ]
lim147/capstone-mini-game-battery-project
Assets/Tests/PlayModeTests/SystemTests/ElasticsearchStorageManagerTests.cs
5,414
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using static Pidgin.Parser<char>; namespace Pidgin; public static partial class Parser { /// <summary> /// A parser that parses and returns a single digit character (0-9) /// </summary> /// <returns>A parser that parses and returns a single digit character</returns> public static Parser<char, char> Digit { get; } = Token(c => char.IsDigit(c)).Labelled("digit"); /// <summary> /// A parser that parses and returns a single letter character /// </summary> /// <returns>A parser that parses and returns a single letter character</returns> public static Parser<char, char> Letter { get; } = Token(c => char.IsLetter(c)).Labelled("letter"); /// <summary> /// A parser that parses and returns a single letter or digit character /// </summary> /// <returns>A parser that parses and returns a single letter or digit character</returns> public static Parser<char, char> LetterOrDigit { get; } = Token(c => char.IsLetterOrDigit(c)).Labelled("letter or digit"); /// <summary> /// A parser that parses and returns a single lowercase letter character /// </summary> /// <returns>A parser that parses and returns a single lowercase letter character</returns> public static Parser<char, char> Lowercase { get; } = Token(c => char.IsLower(c)).Labelled("lowercase letter"); /// <summary> /// A parser that parses and returns a single Unicode punctuation character /// </summary> /// <returns>A parser that parses and returns a single Unicode punctuation character</returns> public static Parser<char, char> Punctuation { get; } = Token(c => char.IsPunctuation(c)).Labelled("punctuation"); /// <summary> /// A parser that parses and returns a single Unicode separator character /// </summary> /// <returns>A parser that parses and returns a single Unicode separator character</returns> public static Parser<char, char> Separator { get; } = Token(c => char.IsSeparator(c)).Labelled("separator"); /// <summary> /// A parser that parses and returns a single Unicode symbol character /// </summary> /// <returns>A parser that parses and returns a single Unicode symbol character</returns> public static Parser<char, char> Symbol { get; } = Token(c => char.IsSymbol(c)).Labelled("symbol"); /// <summary> /// A parser that parses and returns a single uppercase letter character /// </summary> /// <returns>A parser that parses and returns a single uppercase letter character</returns> public static Parser<char, char> Uppercase { get; } = Token(c => char.IsUpper(c)).Labelled("uppercase letter"); /// <summary> /// Creates a parser which parses and returns a character if it is not one of the specified characters. /// When the character is one of the given characters, the parser fails without consuming input. /// </summary> /// <param name="chars">A sequence of characters that should not be matched</param> /// <returns>A parser which parses and returns a character that does not match one of the specified characters</returns> public static Parser<char, char> AnyCharExcept( params char[] chars ) { ArgumentNullException.ThrowIfNull(chars); return AnyCharExcept(chars.AsEnumerable()); } /// <summary> /// Creates a parser which parses and returns a character if it is not one of the specified characters. /// When the character is one of the given characters, the parser fails without consuming input. /// </summary> /// <param name="chars">A sequence of characters that should not be matched</param> /// <returns>A parser which parses and returns a character that does not match one of the specified characters</returns> public static Parser<char, char> AnyCharExcept( IEnumerable<char> chars ) { if( chars == null ) { throw new ArgumentNullException(nameof(chars)); } var cs = chars.ToArray(); return Parser<char>.Token(c => Array.IndexOf(cs, c) == -1); } /// <summary> /// Creates a parser which parses and returns a single character. /// </summary> /// <param name="character">The character to parse</param> /// <returns>A parser which parses and returns a single character</returns> public static Parser<char, char> Char( char character ) => Token(character); /// <summary> /// Creates a parser which parses and returns a single character, in a case insensitive manner. /// The parser returns the actual character parsed. /// </summary> /// <param name="character">The character to parse</param> /// <returns>A parser which parses and returns a single character</returns> public static Parser<char, char> CIChar( char character ) { var theChar = char.ToLowerInvariant(character); var expected = ImmutableArray.Create( new Expected<char>(ImmutableArray.Create(char.ToUpperInvariant(character))), new Expected<char>(ImmutableArray.Create(char.ToLowerInvariant(character))) ); return Token(c => char.ToLowerInvariant(c) == theChar) .WithExpected(expected); } }
45.981481
123
0.721708
[ "MIT" ]
getkks/Pidgin
Pidgin/Parser.Char.cs
4,966
C#
namespace System.Runtime { // Custom attribute that the compiler understands that instructs it // to export the method under the given symbolic name. internal sealed class RuntimeExportAttribute : Attribute { public RuntimeExportAttribute(string entry) { } } }
32
71
0.725694
[ "MIT" ]
nifanfa/BootTo.NET
Corlib/System/Runtime/RuntimeExportAttribute.cs
288
C#
using System.Collections.ObjectModel; using System.Windows.Input; using Level_Exporter.Commands; using Level_Exporter.Models; using System.Collections.Generic; namespace Level_Exporter.ViewModels { /// <summary> /// Level info view model, for use in datagrid /// </summary> public class LevelInfoViewModel : BaseViewModel { #region Construction public LevelInfoViewModel() { ReadMastercamLevels = new DelegateCommand(OnReadMastercamLevels, CanReadMastercamLevels); SelectAll = new DelegateCommand(OnSelectAll, CanSelectAll); } #endregion #region Private fields private bool _isSelectAll; private bool _isSyncButton; private bool _isSelected; private string _name; private readonly ObservableCollection<Level> _levels = LevelInfoHelper.Levels; private delegate int EntityHandler(int n); private delegate Dictionary<int, string> LevelInfoHandler(); #endregion #region Public Properties /// <summary> /// Gets and sets Interface for getting Mastercam level info /// </summary> public static ILevelInfo LevelInfoHelper { get; set; } = new LevelInfoHelper(); /// <summary> /// Gets and sets List of levels for view /// </summary> public IEnumerable<Level> Levels => _levels; //TODO Only allow numbers and letters in level datagrid cell /// <summary> /// Gets and sets name property for level name /// </summary> public string Name { get => _name; set { if (_name == value) return; _name = value; OnPropertyChanged(nameof(Name)); } } /// <summary> /// Gets and sets IsSelectAll for datagrid column header /// </summary> public bool IsSelectAll { get => _isSelectAll; set { _isSelectAll = value; OnPropertyChanged(nameof(IsSelectAll)); } } /// <summary> /// Gets and sets IsSelected for level checkboxes, mirrored for setting Levels class /// </summary> public bool IsSelected { get => _isSelected; set { _isSelected = value; OnPropertyChanged(nameof(IsSelected)); } } /// <summary> /// Gets and Sets bool for button state /// </summary> public bool IsSyncButton { get => _isSyncButton; set { _isSyncButton = value; OnPropertyChanged(nameof(IsSyncButton)); } } #endregion #region Public Commands /// <summary> /// Gets ICommand for read mastercam levels button command /// </summary> public ICommand ReadMastercamLevels { get; } /// <summary> /// Gets ICommand for checking all level checkboxes /// </summary> public ICommand SelectAll { get; } #endregion #region Private Methods /// <summary> /// Can Read Mastercam levels command, checks to do before execution. /// </summary> /// <returns></returns> private bool CanReadMastercamLevels() { // Refresh Level manager in Mastercam to get rid of empty levels, named levels are not removed LevelInfoHelper.RefreshLevelsManager(); return LevelInfoHelper.GetLevelsWithGeometry().Count != 0; } /// <summary> /// Command for button to read Mc Levels /// </summary> private void OnReadMastercamLevels() { // Get Level Info- Key: level num , Value: level name LevelInfoHandler levels = LevelInfoHelper.GetLevelsWithGeometry; EntityHandler entities = LevelInfoHelper.GetLevelEntityCount; IsSyncButton = true; _levels.Clear(); // Clear instead of comparing and doing a 'proper sync'/compare foreach (KeyValuePair<int, string> lvl in levels()) { _levels.Add(new Level { Name = lvl.Value, Number = lvl.Key, EntityCount = entities(lvl.Key) }); } } /// <summary> /// Can Select All command bool, checks done before execution. /// </summary> /// <returns>bool indicating if corresponding command can execute</returns> private bool CanSelectAll() => _levels.Count != 0; /// <summary> /// Command for Checkbox in header, sets IsSelected property of each level in levels collection /// </summary> private void OnSelectAll() { foreach (var lvl in _levels) { if (lvl.IsSelected != IsSelectAll) lvl.IsSelected = IsSelectAll; } } #endregion } }
29.067416
106
0.548319
[ "MIT" ]
MarkRoldan88/Mastercam-Level-Exporter
Level-Exporter/ViewModels/LevelInfoViewModel.cs
5,176
C#
using System; using System.Collections.Generic; using System.Net.Mime; using GraphicsLibrary; using GraphicsLibrary.Hud; using GraphicsLibrary.Input; using OpenTK; using OpenTK.Input; namespace Resim { public static class ActionTrigger { public static float maxDistance = 300f; public static TextField textField; public static bool enable = false; private static bool prevDown = false; private static string _actionName = ""; public static string actionName { get { return _actionName; } } static ActionTrigger() { textField = new TextField("actionTrigger"); textField.sizeX = 16; textField.sizeY = 24; _actionName = "ASDF"; } public static void Display(string action) { enable = true; _actionName = action; textField.text = "Press E to " + action; textField.position.X = (RenderWindow.Instance.Width - textField.sizeX * textField.text.Length) / 2; } public static bool onActive = false; public static void Update() { textField.isVisible = enable; enable = false; onActive = InputManager.IsKeyDown(Key.E) && !prevDown; prevDown = InputManager.IsKeyDown(Key.E); } } }
21.886792
102
0.706897
[ "MIT" ]
fonsp/resim
Resim/ActionTrigger.cs
1,162
C#
using System; namespace ReportPortal.Shared.Reporter { public interface IReporterInfo { string Uuid { get; } string Name { get; } DateTime StartTime { get; } DateTime? FinishTime { get; } } }
15.0625
38
0.585062
[ "Apache-2.0" ]
Bakanych/commons-net
src/ReportPortal.Shared/Reporter/IReporterInfo.cs
243
C#
#region License // Copyright 2015-2018 John Källén // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Pytocs.Core; using Pytocs.Core.Translate; using Pytocs.Core.TypeInference; using Pytocs.Core.Types; namespace Pytocs.Cli { class Program { static void Main(string[] args) { var fs = new FileSystem(); var logger = new ConsoleLogger(); if (args.Length == 0) { var xlator = new Translator("", "module_name", fs, logger); xlator.Translate("-", Console.In, Console.Out); Console.Out.Flush(); return; } var options = new Dictionary<string, object>(); var typeAnalysis = new AnalyzerImpl(fs, logger, options, DateTime.Now); if (args[0].ToLower() == "-r") { var startDir = args.Length == 2 ? args[1] : Directory.GetCurrentDirectory(); typeAnalysis.Analyze(startDir); typeAnalysis.Finish(); var types = new TypeReferenceTranslator( typeAnalysis.BuildTypeDictionary()); //Console.WriteLine($"== Type dictionary: {types.Count}"); //foreach (var de in types.OrderBy(d => d.Key.ToString())) //{ // Console.WriteLine("{0}: {1} {2}", de.Key, de.Key.Start, de.Value); //} var walker = new DirectoryWalker(fs, startDir, "*.py"); walker.Enumerate(state => { foreach (var file in fs.GetFiles(state.DirectoryName, "*.py", SearchOption.TopDirectoryOnly)) { var path = fs.GetFullPath(file); var xlator = new Translator( state.Namespace, fs.GetFileNameWithoutExtension(file), fs, logger); var module = typeAnalysis.GetAstForFile(path); xlator.TranslateModuleStatements( module.body.stmts, types, Path.ChangeExtension(path, ".py.cs")); } }); } else { foreach (var file in args) { typeAnalysis.LoadFileRecursive(file); } typeAnalysis.Finish(); var types = new TypeReferenceTranslator( typeAnalysis.BuildTypeDictionary()); foreach (var file in args) { var path = fs.GetFullPath(file); var xlator = new Translator( "", fs.GetFileNameWithoutExtension(file), fs, logger); var module = typeAnalysis.GetAstForFile(path); xlator.TranslateModuleStatements( module.body.stmts, types, Path.ChangeExtension(path, ".py.cs")); } } } } }
37.12037
113
0.496882
[ "Apache-2.0" ]
powerdev0510/pythonc
src/Cli/Program.cs
4,013
C#
/* Copyright 2017 James Craig 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 Mirage.Generators.BaseClasses; using Mirage.Interfaces; using System; using System.Collections.Generic; namespace Mirage.Generators.Default.Nullable { /// <summary> /// long generator /// </summary> /// <seealso cref="GeneratorAttributeBase"/> /// <seealso cref="IGenerator{Int}"/> public sealed class NullableShortGeneratorAttribute : GeneratorAttributeBase, IGenerator<short?> { /// <summary> /// Initializes a new instance of the <see cref="NullableShortGeneratorAttribute"/> class. /// </summary> /// <param name="min">The minimum.</param> /// <param name="max">The maximum.</param> public NullableShortGeneratorAttribute(short min, short max) : base(min == 0 && max == 0 ? short.MinValue : min, min == 0 && max == 0 ? short.MaxValue : max) { } /// <summary> /// Initializes a new instance of the <see cref="NullableShortGeneratorAttribute"/> class. /// </summary> public NullableShortGeneratorAttribute() : this(short.MinValue, short.MaxValue) { } /// <summary> /// Gets a value indicating whether this <see cref="IGenerator"/> is a default one. /// </summary> /// <value><c>true</c> if default; otherwise, <c>false</c>.</value> public override bool Default => true; /// <summary> /// Gets the type generated. /// </summary> /// <value>The type generated.</value> public override Type TypeGenerated => typeof(short?); /// <summary> /// Generates a random value of the specified type /// </summary> /// <param name="rand">Random number generator that it can use</param> /// <returns>A randomly generated object of the specified type</returns> public short? Next(Random rand) { return !(rand?.Next<bool>() ?? false) ? null : (short?)rand.Next<short>(); } /// <summary> /// Generates a random value of the specified type /// </summary> /// <param name="rand">Random number generator that it can use</param> /// <param name="min">Minimum value (inclusive)</param> /// <param name="max">Maximum value (inclusive)</param> /// <returns>A randomly generated object of the specified type</returns> public short? Next(Random rand, short? min, short? max) { if (!(rand?.Next<bool>() ?? false)) return null; min ??= short.MinValue; max ??= short.MaxValue; return rand.Next(min.Value, max.Value); } /// <summary> /// Generates next object /// </summary> /// <param name="rand">The rand.</param> /// <param name="previouslySeen">The previously seen.</param> /// <returns>The next object</returns> public override object? NextObj(Random rand, List<object> previouslySeen) { return Next(rand); } } }
37.857143
109
0.589488
[ "Apache-2.0" ]
JaCraig/Mirage
src/Mirage/Generators/Default/Nullable/NullableShortGenerator.cs
3,712
C#
namespace TileBeautify { partial class FormAboutMe { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormAboutMe)); this.tabDonate = new System.Windows.Forms.TabPage(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.tabAbout = new System.Windows.Forms.TabPage(); this.label6 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.llbBiliBili = new System.Windows.Forms.LinkLabel(); this.label5 = new System.Windows.Forms.Label(); this.llbGitHub = new System.Windows.Forms.LinkLabel(); this.label4 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.tabDescription = new System.Windows.Forms.TabPage(); this.label1 = new System.Windows.Forms.Label(); this.tab = new System.Windows.Forms.TabControl(); this.tabDonate.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.tabAbout.SuspendLayout(); this.tabDescription.SuspendLayout(); this.tab.SuspendLayout(); this.SuspendLayout(); // // tabDonate // this.tabDonate.Controls.Add(this.pictureBox1); this.tabDonate.Location = new System.Drawing.Point(4, 34); this.tabDonate.Name = "tabDonate"; this.tabDonate.Size = new System.Drawing.Size(405, 197); this.tabDonate.TabIndex = 0; this.tabDonate.Text = "捐赠"; this.tabDonate.UseVisualStyleBackColor = true; // // pictureBox1 // this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(0, 0); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(405, 197); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; // // tabAbout // this.tabAbout.Controls.Add(this.label6); this.tabAbout.Controls.Add(this.label3); this.tabAbout.Controls.Add(this.llbBiliBili); this.tabAbout.Controls.Add(this.label5); this.tabAbout.Controls.Add(this.llbGitHub); this.tabAbout.Controls.Add(this.label4); this.tabAbout.Controls.Add(this.label2); this.tabAbout.Location = new System.Drawing.Point(4, 34); this.tabAbout.Name = "tabAbout"; this.tabAbout.Padding = new System.Windows.Forms.Padding(3); this.tabAbout.Size = new System.Drawing.Size(405, 197); this.tabAbout.TabIndex = 1; this.tabAbout.Text = "关于"; this.tabAbout.UseVisualStyleBackColor = true; // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Microsoft YaHei UI", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label6.Location = new System.Drawing.Point(8, 162); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(233, 20); this.label6.TabIndex = 8; this.label6.Text = "我的第一个正式意义上的开源软件!"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft YaHei UI", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label3.Location = new System.Drawing.Point(8, 126); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(215, 20); this.label3.TabIndex = 7; this.label3.Text = "有钱的可以酌情捐赠一下q(≧▽≦q)"; // // llbBiliBili // this.llbBiliBili.AutoSize = true; this.llbBiliBili.Font = new System.Drawing.Font("Microsoft YaHei UI", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.llbBiliBili.Location = new System.Drawing.Point(172, 90); this.llbBiliBili.Name = "llbBiliBili"; this.llbBiliBili.Size = new System.Drawing.Size(51, 20); this.llbBiliBili.TabIndex = 6; this.llbBiliBili.TabStop = true; this.llbBiliBili.Text = "Bilibili"; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Microsoft YaHei UI", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label5.Location = new System.Drawing.Point(8, 90); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(168, 20); this.label5.TabIndex = 5; this.label5.Text = "B站视频教程(欢迎关注):"; // // llbGitHub // this.llbGitHub.AutoSize = true; this.llbGitHub.Font = new System.Drawing.Font("Microsoft YaHei UI", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.llbGitHub.Location = new System.Drawing.Point(129, 53); this.llbGitHub.Name = "llbGitHub"; this.llbGitHub.Size = new System.Drawing.Size(55, 20); this.llbGitHub.TabIndex = 4; this.llbGitHub.TabStop = true; this.llbGitHub.Text = "Github"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Microsoft YaHei UI", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label4.Location = new System.Drawing.Point(8, 53); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(125, 20); this.label4.TabIndex = 3; this.label4.Text = "Github项目开源:"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft YaHei UI", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label2.Location = new System.Drawing.Point(8, 19); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(297, 20); this.label2.TabIndex = 1; this.label2.Text = "最后编译时间:2020.2.7 语言:C# winform"; // // tabDescription // this.tabDescription.Controls.Add(this.label1); this.tabDescription.Location = new System.Drawing.Point(4, 34); this.tabDescription.Name = "tabDescription"; this.tabDescription.Padding = new System.Windows.Forms.Padding(3); this.tabDescription.Size = new System.Drawing.Size(405, 197); this.tabDescription.TabIndex = 0; this.tabDescription.Text = "说明"; this.tabDescription.UseVisualStyleBackColor = true; // // label1 // this.label1.Dock = System.Windows.Forms.DockStyle.Fill; this.label1.Font = new System.Drawing.Font("Microsoft YaHei UI", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label1.Location = new System.Drawing.Point(3, 3); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(399, 191); this.label1.TabIndex = 0; this.label1.Text = resources.GetString("label1.Text"); // // tab // this.tab.Controls.Add(this.tabDescription); this.tab.Controls.Add(this.tabAbout); this.tab.Controls.Add(this.tabDonate); this.tab.Dock = System.Windows.Forms.DockStyle.Fill; this.tab.Font = new System.Drawing.Font("Microsoft YaHei UI", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.tab.ItemSize = new System.Drawing.Size(60, 30); this.tab.Location = new System.Drawing.Point(0, 0); this.tab.Name = "tab"; this.tab.SelectedIndex = 0; this.tab.Size = new System.Drawing.Size(413, 235); this.tab.TabIndex = 0; // // FormAboutMe // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit; this.ClientSize = new System.Drawing.Size(413, 235); this.Controls.Add(this.tab); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FormAboutMe"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "使用说明"; this.TopMost = true; this.tabDonate.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.tabAbout.ResumeLayout(false); this.tabAbout.PerformLayout(); this.tabDescription.ResumeLayout(false); this.tab.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TabPage tabDonate; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.TabPage tabAbout; private System.Windows.Forms.LinkLabel llbBiliBili; private System.Windows.Forms.Label label5; private System.Windows.Forms.LinkLabel llbGitHub; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label2; private System.Windows.Forms.TabPage tabDescription; private System.Windows.Forms.Label label1; private System.Windows.Forms.TabControl tab; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label3; } }
49.608696
173
0.591674
[ "MIT" ]
BluePointLilac/TileBeautify
TileBeautify/FormAboutMe.Designer.cs
11,542
C#
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PureCloudPlatform.Client.V2.Client; namespace PureCloudPlatform.Client.V2.Model { /// <summary> /// SetUuiDataRequest /// </summary> [DataContract] public partial class SetUuiDataRequest : IEquatable<SetUuiDataRequest> { /// <summary> /// Initializes a new instance of the <see cref="SetUuiDataRequest" /> class. /// </summary> /// <param name="UuiData">The value of the uuiData to set..</param> public SetUuiDataRequest(string UuiData = null) { this.UuiData = UuiData; } /// <summary> /// The value of the uuiData to set. /// </summary> /// <value>The value of the uuiData to set.</value> [DataMember(Name="uuiData", EmitDefaultValue=false)] public string UuiData { 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 SetUuiDataRequest {\n"); sb.Append(" UuiData: ").Append(UuiData).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 string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as SetUuiDataRequest); } /// <summary> /// Returns true if SetUuiDataRequest instances are equal /// </summary> /// <param name="other">Instance of SetUuiDataRequest to be compared</param> /// <returns>Boolean</returns> public bool Equals(SetUuiDataRequest other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return true && ( this.UuiData == other.UuiData || this.UuiData != null && this.UuiData.Equals(other.UuiData) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.UuiData != null) hash = hash * 59 + this.UuiData.GetHashCode(); return hash; } } } }
29.455285
85
0.524979
[ "MIT" ]
nmusco/platform-client-sdk-dotnet
build/src/PureCloudPlatform.Client.V2/Model/SetUuiDataRequest.cs
3,623
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("ArcGISEarth.AutoAPI.Examples")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Esri Inc.")] [assembly: AssemblyProduct("ArcGISEarth.AutoAPI.Examples")] [assembly: AssemblyCopyright("Copyright © Esri Inc. 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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")]
40.714286
96
0.756579
[ "Apache-2.0" ]
Esri/arcgisearth-automation-api
src/ArcGISEarth.AutoAPI.Examples/Properties/AssemblyInfo.cs
2,283
C#
namespace AppliedAlgebra.WaveletCodesTools.Decoding.ListDecoderForFixedDistanceCodes.GsBasedDecoderDependencies { using System; using System.Collections.Concurrent; using System.Collections.Generic; using GfPolynoms; /// <summary> /// Contract for telemetry reciver for wavelet code's list decoder based on Guruswami–Sudan algorithm /// </summary> public interface IGsBasedDecoderTelemetryCollector { /// <summary> /// Count of processed samples /// </summary> int ProcessedSamplesCount { get; } /// <summary> /// Samples count stored by lists sizes in frequency and time domains /// </summary> ConcurrentDictionary<Tuple<int, int>, int> ProcessingResults { get; } /// <summary> /// Important samples stored by lists sizes in frequency and time domains /// </summary> ConcurrentDictionary<Tuple<int, int>, List<Tuple<FieldElement, FieldElement>[]>> InterestingSamples { get; } /// <summary> /// Method for registering result of decoding /// </summary> /// <param name="decodedCodeword">Decoded codeword</param> /// <param name="frequencyDecodingListSize">List size in frequency domain</param> /// <param name="timeDecodingListSize">List size in time domain</param> void ReportDecodingListsSizes(Tuple<FieldElement, FieldElement>[] decodedCodeword, int frequencyDecodingListSize, int timeDecodingListSize); } }
44.264706
148
0.676412
[ "MIT" ]
FeodorFitsner/GfPolynoms
src/WaveletCodesTools/Decoding/ListDecoderForFixedDistanceCodes/GsBasedDecoderDependencies/IGsBasedDecoderTelemetryCollector.cs
1,509
C#
using System.Collections.Immutable; using System.Composition; using System.Threading.Tasks; using Entia.Analyze.Analyzers; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Entia.Analyze.Fixers { [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AddInModifier)), Shared] public sealed class AddInModifier : CodeFixProvider { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(Parameter.Rules.MissingParameterRefOrIn.Id); public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; public override async Task RegisterCodeFixesAsync(CodeFixContext context) { static Solution FixParameter(Document document, SyntaxNode root, ParameterSyntax declaration) { var replaced = root.ReplaceNode(declaration, declaration.ToIn()); var solution = document.Project.Solution; return solution.WithDocumentSyntaxRoot(document.Id, replaced); } await context.RegisterCodeAction<ParameterSyntax>("Add 'in' modifier.", Parameter.Rules.MissingParameterRefOrIn.Id, FixParameter); } } }
42.2
142
0.736967
[ "MIT" ]
Magicolo/Entia
Entia.Analyze/Fixers/AddInModifier.cs
1,266
C#
// Copyright (c) 2022 TrakHound Inc., All Rights Reserved. // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using MTConnect.Observations; using System; namespace MTConnect.Devices.Events { /// <summary> /// The direction of motion. /// </summary> public class DirectionDataItem : DataItem { public const DataItemCategory CategoryId = DataItemCategory.EVENT; public const string TypeId = "DIRECTION"; public const string NameId = "direction"; public new const string DescriptionText = "The direction of motion."; public override string TypeDescription => DescriptionText; public enum SubTypes { /// <summary> /// The direction of rotary motion using the right-hand rule convention. /// </summary> ROTARY, /// <summary> /// The direction of linear motion. /// </summary> LINEAR } public DirectionDataItem() { Category = CategoryId; Type = TypeId; } public DirectionDataItem( string parentId, SubTypes subType ) { Id = CreateId(parentId, NameId, GetSubTypeId(subType)); Category = CategoryId; Type = TypeId; SubType = subType.ToString(); Name = NameId; } /// <summary> /// Determine if the DataItem with the specified Observation is valid in the specified MTConnectVersion /// </summary> /// <param name="mtconnectVersion">The Version of the MTConnect Standard</param> /// <param name="observation">The Observation to validate</param> /// <returns>A DataItemValidationResult indicating if Validation was successful and a Message</returns> protected override DataItemValidationResult OnValidation(Version mtconnectVersion, IObservation observation) { if (observation != null && !observation.Values.IsNullOrEmpty()) { // Get the CDATA Value for the Observation var cdata = observation.GetValue(ValueTypes.CDATA); if (cdata != null) { // Check if Unavailable if (cdata == Streams.DataItem.Unavailable) return new DataItemValidationResult(true); if (SubType == SubTypes.LINEAR.ToString()) { // Check Valid values in Enum var validValues = Enum.GetValues(typeof(Streams.Events.LinearDirection)); foreach (var validValue in validValues) { if (cdata == validValue.ToString()) { return new DataItemValidationResult(true); } } return new DataItemValidationResult(false, "'" + cdata + "' is not a valid value"); } else if (SubType == SubTypes.ROTARY.ToString()) { // Check Valid values in Enum var validValues = Enum.GetValues(typeof(Streams.Events.RotaryDirection)); foreach (var validValue in validValues) { if (cdata == validValue.ToString()) { return new DataItemValidationResult(true); } } return new DataItemValidationResult(false, "'" + cdata + "' is not a valid value"); } } else { return new DataItemValidationResult(false, "No CDATA is specified for the Observation"); } } return new DataItemValidationResult(false, "No Observation is Specified"); } public override string GetSubTypeDescription() => GetSubTypeDescription(SubType); public static string GetSubTypeDescription(string subType) { var s = subType.ConvertEnum<SubTypes>(); switch (s) { case SubTypes.ROTARY: return "The direction of rotary motion using the right-hand rule convention."; case SubTypes.LINEAR: return "The direction of linear motion."; } return null; } public static string GetSubTypeId(SubTypes subType) { switch (subType) { case SubTypes.ROTARY: return "rotary"; case SubTypes.LINEAR: return "linear"; } return null; } } }
35.956204
116
0.522533
[ "Apache-2.0" ]
halitcan/MTConnect.NET
src/MTConnect.NET/Devices/Events/DirectionDataItem.cs
4,926
C#
// <auto-generated /> namespace MUnique.OpenMU.Persistence.EntityFramework.Migrations { using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; [DbContext(typeof(EntityDataContext))] [Migration("00000000000000_Initial")] partial class Initial { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .UseIdentityByDefaultColumns() .HasAnnotation("Relational:MaxIdentifierLength", 63) .HasAnnotation("ProductVersion", "5.0.0"); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.Account", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<string>("EMail") .IsRequired() .HasColumnType("text"); b.Property<bool>("IsVaultExtended") .HasColumnType("boolean"); b.Property<string>("LoginName") .IsRequired() .HasMaxLength(10) .HasColumnType("character varying(10)"); b.Property<string>("PasswordHash") .IsRequired() .HasColumnType("text"); b.Property<DateTime>("RegistrationDate") .ValueGeneratedOnAdd() .HasColumnType("timestamp without time zone") .HasDefaultValueSql("CURRENT_TIMESTAMP"); b.Property<string>("SecurityCode") .IsRequired() .HasColumnType("text"); b.Property<int>("State") .HasColumnType("integer"); b.Property<short>("TimeZone") .HasColumnType("smallint"); b.Property<Guid?>("VaultId") .HasColumnType("uuid"); b.Property<string>("VaultPassword") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("LoginName") .IsUnique(); b.HasIndex("VaultId"); b.ToTable("Account", "data"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.AccountCharacterClass", b => { b.Property<Guid>("AccountId") .HasColumnType("uuid"); b.Property<Guid>("CharacterClassId") .HasColumnType("uuid"); b.HasKey("AccountId", "CharacterClassId"); b.HasIndex("CharacterClassId"); b.ToTable("AccountCharacterClass", "data"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.AppearanceData", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("CharacterClassId") .HasColumnType("uuid"); b.Property<bool>("FullAncientSetEquipped") .HasColumnType("boolean"); b.Property<byte>("Pose") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("CharacterClassId"); b.ToTable("AppearanceData", "data"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeDefinition", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<string>("Description") .HasColumnType("text"); b.Property<string>("Designation") .HasColumnType("text"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("GameConfigurationId"); b.ToTable("AttributeDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeRelationship", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("CharacterClassId") .HasColumnType("uuid"); b.Property<Guid?>("InputAttributeId") .HasColumnType("uuid"); b.Property<float>("InputOperand") .HasColumnType("real"); b.Property<int>("InputOperator") .HasColumnType("integer"); b.Property<Guid?>("PowerUpDefinitionValueId") .HasColumnType("uuid"); b.Property<Guid?>("TargetAttributeId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("CharacterClassId"); b.HasIndex("InputAttributeId"); b.HasIndex("PowerUpDefinitionValueId"); b.HasIndex("TargetAttributeId"); b.ToTable("AttributeRelationship", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeRequirement", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("AttributeId") .HasColumnType("uuid"); b.Property<Guid?>("GameMapDefinitionId") .HasColumnType("uuid"); b.Property<Guid?>("ItemDefinitionId") .HasColumnType("uuid"); b.Property<int>("MinimumValue") .HasColumnType("integer"); b.Property<Guid?>("SkillId") .HasColumnType("uuid"); b.Property<Guid?>("SkillId1") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("AttributeId"); b.HasIndex("GameMapDefinitionId"); b.HasIndex("ItemDefinitionId"); b.HasIndex("SkillId"); b.HasIndex("SkillId1"); b.ToTable("AttributeRequirement", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.Character", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("AccountId") .HasColumnType("uuid"); b.Property<Guid?>("CharacterClassId") .IsRequired() .HasColumnType("uuid"); b.Property<byte>("CharacterSlot") .HasColumnType("smallint"); b.Property<int>("CharacterStatus") .HasColumnType("integer"); b.Property<DateTime>("CreateDate") .ValueGeneratedOnAdd() .HasColumnType("timestamp without time zone") .HasDefaultValueSql("CURRENT_TIMESTAMP"); b.Property<Guid?>("CurrentMapId") .HasColumnType("uuid"); b.Property<long>("Experience") .HasColumnType("bigint"); b.Property<int>("InventoryExtensions") .HasColumnType("integer"); b.Property<Guid?>("InventoryId") .HasColumnType("uuid"); b.Property<byte[]>("KeyConfiguration") .HasColumnType("bytea"); b.Property<int>("LevelUpPoints") .HasColumnType("integer"); b.Property<long>("MasterExperience") .HasColumnType("bigint"); b.Property<int>("MasterLevelUpPoints") .HasColumnType("integer"); b.Property<string>("Name") .IsRequired() .HasMaxLength(10) .HasColumnType("character varying(10)"); b.Property<int>("PlayerKillCount") .HasColumnType("integer"); b.Property<byte>("Pose") .HasColumnType("smallint"); b.Property<byte>("PositionX") .HasColumnType("smallint"); b.Property<byte>("PositionY") .HasColumnType("smallint"); b.Property<byte[]>("QuestInfo") .HasColumnType("bytea"); b.Property<int>("State") .HasColumnType("integer"); b.Property<int>("StateRemainingSeconds") .HasColumnType("integer"); b.Property<int>("UsedFruitPoints") .HasColumnType("integer"); b.Property<int>("UsedNegFruitPoints") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("AccountId"); b.HasIndex("CharacterClassId"); b.HasIndex("CurrentMapId"); b.HasIndex("InventoryId"); b.HasIndex("Name") .IsUnique(); b.ToTable("Character", "data"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterClass", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<bool>("CanGetCreated") .HasColumnType("boolean"); b.Property<byte>("CreationAllowedFlag") .HasColumnType("smallint"); b.Property<int>("FruitCalculation") .HasColumnType("integer"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.Property<Guid?>("HomeMapId") .HasColumnType("uuid"); b.Property<bool>("IsMasterClass") .HasColumnType("boolean"); b.Property<short>("LevelRequirementByCreation") .HasColumnType("smallint"); b.Property<int>("LevelWarpRequirementReductionPercent") .HasColumnType("integer"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.Property<Guid?>("NextGenerationClassId") .HasColumnType("uuid"); b.Property<byte>("Number") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("GameConfigurationId"); b.HasIndex("HomeMapId"); b.HasIndex("NextGenerationClassId"); b.ToTable("CharacterClass", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterDropItemGroup", b => { b.Property<Guid>("CharacterId") .HasColumnType("uuid"); b.Property<Guid>("DropItemGroupId") .HasColumnType("uuid"); b.HasKey("CharacterId", "DropItemGroupId"); b.HasIndex("DropItemGroupId"); b.ToTable("CharacterDropItemGroup", "data"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterQuestState", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("ActiveQuestId") .HasColumnType("uuid"); b.Property<Guid?>("CharacterId") .HasColumnType("uuid"); b.Property<bool>("ClientActionPerformed") .HasColumnType("boolean"); b.Property<short>("Group") .HasColumnType("smallint"); b.Property<Guid?>("LastFinishedQuestId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("ActiveQuestId"); b.HasIndex("CharacterId"); b.HasIndex("LastFinishedQuestId"); b.ToTable("CharacterQuestState", "data"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ChatServerDefinition", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<TimeSpan>("ClientCleanUpInterval") .HasColumnType("interval"); b.Property<TimeSpan>("ClientTimeout") .HasColumnType("interval"); b.Property<string>("Description") .IsRequired() .HasColumnType("text"); b.Property<int>("MaximumConnections") .HasColumnType("integer"); b.Property<TimeSpan>("RoomCleanUpInterval") .HasColumnType("interval"); b.Property<byte>("ServerId") .HasColumnType("smallint"); b.HasKey("Id"); b.ToTable("ChatServerDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ChatServerEndpoint", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("ChatServerDefinitionId") .HasColumnType("uuid"); b.Property<Guid?>("ClientId") .HasColumnType("uuid"); b.Property<int>("NetworkPort") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("ChatServerDefinitionId"); b.HasIndex("ClientId"); b.ToTable("ChatServerEndpoint", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.CombinationBonusRequirement", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("ItemOptionCombinationBonusId") .HasColumnType("uuid"); b.Property<int>("MinimumCount") .HasColumnType("integer"); b.Property<Guid?>("OptionTypeId") .HasColumnType("uuid"); b.Property<int>("SubOptionType") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("ItemOptionCombinationBonusId"); b.HasIndex("OptionTypeId"); b.ToTable("CombinationBonusRequirement", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ConnectServerDefinition", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<bool>("CheckMaxConnectionsPerAddress") .HasColumnType("boolean"); b.Property<Guid?>("ClientId") .HasColumnType("uuid"); b.Property<int>("ClientListenerPort") .HasColumnType("integer"); b.Property<byte[]>("CurrentPatchVersion") .HasColumnType("bytea"); b.Property<string>("Description") .IsRequired() .HasColumnType("text"); b.Property<bool>("DisconnectOnUnknownPacket") .HasColumnType("boolean"); b.Property<int>("ListenerBacklog") .HasColumnType("integer"); b.Property<int>("MaxConnections") .HasColumnType("integer"); b.Property<int>("MaxConnectionsPerAddress") .HasColumnType("integer"); b.Property<int>("MaxFtpRequests") .HasColumnType("integer"); b.Property<int>("MaxIpRequests") .HasColumnType("integer"); b.Property<int>("MaxServerListRequests") .HasColumnType("integer"); b.Property<byte>("MaximumReceiveSize") .HasColumnType("smallint"); b.Property<string>("PatchAddress") .IsRequired() .HasColumnType("text"); b.Property<byte>("ServerId") .HasColumnType("smallint"); b.Property<TimeSpan>("Timeout") .HasColumnType("interval"); b.HasKey("Id"); b.HasIndex("ClientId"); b.ToTable("ConnectServerDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ConstValueAttribute", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid>("CharacterClassId") .HasColumnType("uuid"); b.Property<Guid?>("DefinitionId") .HasColumnType("uuid"); b.Property<float>("Value") .HasColumnType("real"); b.HasKey("Id"); b.HasIndex("CharacterClassId"); b.HasIndex("DefinitionId"); b.ToTable("ConstValueAttribute", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.DropItemGroup", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<double>("Chance") .HasColumnType("double precision"); b.Property<string>("Description") .IsRequired() .HasColumnType("text"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.Property<byte?>("ItemLevel") .HasColumnType("smallint"); b.Property<int>("ItemType") .HasColumnType("integer"); b.Property<byte?>("MaximumMonsterLevel") .HasColumnType("smallint"); b.Property<byte?>("MinimumMonsterLevel") .HasColumnType("smallint"); b.Property<Guid?>("MonsterId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("GameConfigurationId"); b.HasIndex("MonsterId"); b.ToTable("DropItemGroup", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.DropItemGroupItemDefinition", b => { b.Property<Guid>("DropItemGroupId") .HasColumnType("uuid"); b.Property<Guid>("ItemDefinitionId") .HasColumnType("uuid"); b.HasKey("DropItemGroupId", "ItemDefinitionId"); b.HasIndex("ItemDefinitionId"); b.ToTable("DropItemGroupItemDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.EnterGate", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("GameMapDefinitionId") .HasColumnType("uuid"); b.Property<short>("LevelRequirement") .HasColumnType("smallint"); b.Property<short>("Number") .HasColumnType("smallint"); b.Property<Guid?>("TargetGateId") .HasColumnType("uuid"); b.Property<byte>("X1") .HasColumnType("smallint"); b.Property<byte>("X2") .HasColumnType("smallint"); b.Property<byte>("Y1") .HasColumnType("smallint"); b.Property<byte>("Y2") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("GameMapDefinitionId"); b.HasIndex("TargetGateId"); b.ToTable("EnterGate", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ExitGate", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<int>("Direction") .HasColumnType("integer"); b.Property<bool>("IsSpawnGate") .HasColumnType("boolean"); b.Property<Guid?>("MapId") .HasColumnType("uuid"); b.Property<byte>("X1") .HasColumnType("smallint"); b.Property<byte>("X2") .HasColumnType("smallint"); b.Property<byte>("Y1") .HasColumnType("smallint"); b.Property<byte>("Y2") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("MapId"); b.ToTable("ExitGate", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.Friend", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<bool>("Accepted") .HasColumnType("boolean"); b.Property<Guid>("CharacterId") .HasColumnType("uuid"); b.Property<Guid>("FriendId") .HasColumnType("uuid"); b.Property<bool>("RequestOpen") .HasColumnType("boolean"); b.HasKey("Id"); b.HasAlternateKey("CharacterId", "FriendId"); b.ToTable("Friend", "friend"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GameClientDefinition", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<string>("Description") .IsRequired() .HasColumnType("text"); b.Property<byte>("Episode") .HasColumnType("smallint"); b.Property<int>("Language") .HasColumnType("integer"); b.Property<byte>("Season") .HasColumnType("smallint"); b.Property<byte[]>("Serial") .HasColumnType("bytea"); b.Property<byte[]>("Version") .HasColumnType("bytea"); b.HasKey("Id"); b.ToTable("GameClientDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<bool>("AreaSkillHitsPlayer") .HasColumnType("boolean"); b.Property<string>("CharacterNameRegex") .HasColumnType("text"); b.Property<float>("ExperienceRate") .HasColumnType("real"); b.Property<byte>("InfoRange") .HasColumnType("smallint"); b.Property<int>("LetterSendPrice") .HasColumnType("integer"); b.Property<byte>("MaximumCharactersPerAccount") .HasColumnType("smallint"); b.Property<int>("MaximumInventoryMoney") .HasColumnType("integer"); b.Property<int>("MaximumLetters") .HasColumnType("integer"); b.Property<short>("MaximumLevel") .HasColumnType("smallint"); b.Property<byte>("MaximumPartySize") .HasColumnType("smallint"); b.Property<int>("MaximumPasswordLength") .HasColumnType("integer"); b.Property<int>("MaximumVaultMoney") .HasColumnType("integer"); b.Property<int>("RecoveryInterval") .HasColumnType("integer"); b.Property<bool>("ShouldDropMoney") .HasColumnType("boolean"); b.HasKey("Id"); b.ToTable("GameConfiguration", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GameMapDefinition", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<double>("ExpMultiplier") .HasColumnType("double precision"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.Property<short>("Number") .HasColumnType("smallint"); b.Property<Guid?>("SafezoneMapId") .HasColumnType("uuid"); b.Property<byte[]>("TerrainData") .HasColumnType("bytea"); b.HasKey("Id"); b.HasIndex("GameConfigurationId"); b.HasIndex("SafezoneMapId"); b.ToTable("GameMapDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GameMapDefinitionDropItemGroup", b => { b.Property<Guid>("GameMapDefinitionId") .HasColumnType("uuid"); b.Property<Guid>("DropItemGroupId") .HasColumnType("uuid"); b.HasKey("GameMapDefinitionId", "DropItemGroupId"); b.HasIndex("DropItemGroupId"); b.ToTable("GameMapDefinitionDropItemGroup", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GameServerConfiguration", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<short>("MaximumPlayers") .HasColumnType("smallint"); b.HasKey("Id"); b.ToTable("GameServerConfiguration", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GameServerConfigurationGameMapDefinition", b => { b.Property<Guid>("GameServerConfigurationId") .HasColumnType("uuid"); b.Property<Guid>("GameMapDefinitionId") .HasColumnType("uuid"); b.HasKey("GameServerConfigurationId", "GameMapDefinitionId"); b.HasIndex("GameMapDefinitionId"); b.ToTable("GameServerConfigurationGameMapDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GameServerDefinition", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<string>("Description") .IsRequired() .HasColumnType("text"); b.Property<float>("ExperienceRate") .HasColumnType("real"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.Property<Guid?>("ServerConfigurationId") .HasColumnType("uuid"); b.Property<byte>("ServerID") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("GameConfigurationId"); b.HasIndex("ServerConfigurationId"); b.ToTable("GameServerDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GameServerEndpoint", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<int>("AlternativePublishedPort") .HasColumnType("integer"); b.Property<Guid?>("ClientId") .HasColumnType("uuid"); b.Property<Guid?>("GameServerDefinitionId") .HasColumnType("uuid"); b.Property<int>("NetworkPort") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("ClientId"); b.HasIndex("GameServerDefinitionId"); b.ToTable("GameServerEndpoint", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.Guild", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("AllianceGuildId") .HasColumnType("uuid"); b.Property<Guid?>("HostilityId") .HasColumnType("uuid"); b.Property<byte[]>("Logo") .HasColumnType("bytea"); b.Property<string>("Name") .IsRequired() .HasMaxLength(8) .HasColumnType("character varying(8)"); b.Property<string>("Notice") .HasColumnType("text"); b.Property<int>("Score") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("AllianceGuildId"); b.HasIndex("HostilityId"); b.HasIndex("Name") .IsUnique(); b.ToTable("Guild", "guild"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GuildMember", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<Guid>("GuildId") .HasColumnType("uuid"); b.Property<byte>("Status") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("GuildId"); b.ToTable("GuildMember", "guild"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.IncreasableItemOption", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("ItemOptionDefinitionId") .HasColumnType("uuid"); b.Property<Guid?>("ItemSetGroupId") .HasColumnType("uuid"); b.Property<int>("LevelType") .HasColumnType("integer"); b.Property<int>("Number") .HasColumnType("integer"); b.Property<Guid?>("OptionTypeId") .HasColumnType("uuid"); b.Property<Guid?>("PowerUpDefinitionId") .HasColumnType("uuid"); b.Property<int>("SubOptionType") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("ItemOptionDefinitionId"); b.HasIndex("ItemSetGroupId"); b.HasIndex("OptionTypeId"); b.HasIndex("PowerUpDefinitionId"); b.ToTable("IncreasableItemOption", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.Item", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("DefinitionId") .HasColumnType("uuid"); b.Property<byte>("Durability") .HasColumnType("smallint"); b.Property<bool>("HasSkill") .HasColumnType("boolean"); b.Property<byte>("ItemSlot") .HasColumnType("smallint"); b.Property<Guid?>("ItemStorageId") .HasColumnType("uuid"); b.Property<byte>("Level") .HasColumnType("smallint"); b.Property<int>("SocketCount") .HasColumnType("integer"); b.Property<int?>("StorePrice") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("DefinitionId"); b.HasIndex("ItemStorageId"); b.ToTable("Item", "data"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemAppearance", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("AppearanceDataId") .HasColumnType("uuid"); b.Property<Guid?>("DefinitionId") .HasColumnType("uuid"); b.Property<byte>("ItemSlot") .HasColumnType("smallint"); b.Property<byte>("Level") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("AppearanceDataId"); b.HasIndex("DefinitionId"); b.ToTable("ItemAppearance", "data"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemAppearanceItemOptionType", b => { b.Property<Guid>("ItemAppearanceId") .HasColumnType("uuid"); b.Property<Guid>("ItemOptionTypeId") .HasColumnType("uuid"); b.HasKey("ItemAppearanceId", "ItemOptionTypeId"); b.HasIndex("ItemOptionTypeId"); b.ToTable("ItemAppearanceItemOptionType", "data"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemBasePowerUpDefinition", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<float>("BaseValue") .HasColumnType("real"); b.Property<Guid?>("ItemDefinitionId") .HasColumnType("uuid"); b.Property<Guid?>("TargetAttributeId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("ItemDefinitionId"); b.HasIndex("TargetAttributeId"); b.ToTable("ItemBasePowerUpDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemCrafting", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<string>("ItemCraftingHandlerClassName") .IsRequired() .HasColumnType("text"); b.Property<Guid?>("MonsterDefinitionId") .HasColumnType("uuid"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.Property<byte>("Number") .HasColumnType("smallint"); b.Property<Guid?>("SimpleCraftingSettingsId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("MonsterDefinitionId"); b.HasIndex("SimpleCraftingSettingsId"); b.ToTable("ItemCrafting", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemCraftingRequiredItem", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<byte>("AddPercentage") .HasColumnType("smallint"); b.Property<int>("FailResult") .HasColumnType("integer"); b.Property<byte>("MaximumAmount") .HasColumnType("smallint"); b.Property<byte>("MaximumItemLevel") .HasColumnType("smallint"); b.Property<byte>("MinimumAmount") .HasColumnType("smallint"); b.Property<byte>("MinimumItemLevel") .HasColumnType("smallint"); b.Property<int>("NpcPriceDivisor") .HasColumnType("integer"); b.Property<byte>("Reference") .HasColumnType("smallint"); b.Property<Guid?>("SimpleCraftingSettingsId") .HasColumnType("uuid"); b.Property<int>("SuccessResult") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("SimpleCraftingSettingsId"); b.ToTable("ItemCraftingRequiredItem", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemCraftingRequiredItemItemDefinition", b => { b.Property<Guid>("ItemCraftingRequiredItemId") .HasColumnType("uuid"); b.Property<Guid>("ItemDefinitionId") .HasColumnType("uuid"); b.HasKey("ItemCraftingRequiredItemId", "ItemDefinitionId"); b.HasIndex("ItemDefinitionId"); b.ToTable("ItemCraftingRequiredItemItemDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemCraftingRequiredItemItemOptionType", b => { b.Property<Guid>("ItemCraftingRequiredItemId") .HasColumnType("uuid"); b.Property<Guid>("ItemOptionTypeId") .HasColumnType("uuid"); b.HasKey("ItemCraftingRequiredItemId", "ItemOptionTypeId"); b.HasIndex("ItemOptionTypeId"); b.ToTable("ItemCraftingRequiredItemItemOptionType", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemCraftingResultItem", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<byte>("AddLevel") .HasColumnType("smallint"); b.Property<byte?>("Durability") .HasColumnType("smallint"); b.Property<Guid?>("ItemDefinitionId") .HasColumnType("uuid"); b.Property<byte>("RandomMaximumLevel") .HasColumnType("smallint"); b.Property<byte>("RandomMinimumLevel") .HasColumnType("smallint"); b.Property<byte>("Reference") .HasColumnType("smallint"); b.Property<Guid?>("SimpleCraftingSettingsId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("ItemDefinitionId"); b.HasIndex("SimpleCraftingSettingsId"); b.ToTable("ItemCraftingResultItem", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinition", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<string>("ConsumeHandlerClass") .HasColumnType("text"); b.Property<byte>("DropLevel") .HasColumnType("smallint"); b.Property<bool>("DropsFromMonsters") .HasColumnType("boolean"); b.Property<byte>("Durability") .HasColumnType("smallint"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.Property<byte>("Group") .HasColumnType("smallint"); b.Property<byte>("Height") .HasColumnType("smallint"); b.Property<bool>("IsAmmunition") .HasColumnType("boolean"); b.Property<bool>("IsBoundToCharacter") .HasColumnType("boolean"); b.Property<Guid?>("ItemSlotId") .HasColumnType("uuid"); b.Property<byte>("MaximumItemLevel") .HasColumnType("smallint"); b.Property<int>("MaximumSockets") .HasColumnType("integer"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.Property<short>("Number") .HasColumnType("smallint"); b.Property<Guid?>("SkillId") .HasColumnType("uuid"); b.Property<int>("Value") .HasColumnType("integer"); b.Property<byte>("Width") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("GameConfigurationId"); b.HasIndex("ItemSlotId"); b.HasIndex("SkillId"); b.ToTable("ItemDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinitionCharacterClass", b => { b.Property<Guid>("ItemDefinitionId") .HasColumnType("uuid"); b.Property<Guid>("CharacterClassId") .HasColumnType("uuid"); b.HasKey("ItemDefinitionId", "CharacterClassId"); b.HasIndex("CharacterClassId"); b.ToTable("ItemDefinitionCharacterClass", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinitionItemOptionDefinition", b => { b.Property<Guid>("ItemDefinitionId") .HasColumnType("uuid"); b.Property<Guid>("ItemOptionDefinitionId") .HasColumnType("uuid"); b.HasKey("ItemDefinitionId", "ItemOptionDefinitionId"); b.HasIndex("ItemOptionDefinitionId"); b.ToTable("ItemDefinitionItemOptionDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinitionItemSetGroup", b => { b.Property<Guid>("ItemDefinitionId") .HasColumnType("uuid"); b.Property<Guid>("ItemSetGroupId") .HasColumnType("uuid"); b.HasKey("ItemDefinitionId", "ItemSetGroupId"); b.HasIndex("ItemSetGroupId"); b.ToTable("ItemDefinitionItemSetGroup", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemItemSetGroup", b => { b.Property<Guid>("ItemId") .HasColumnType("uuid"); b.Property<Guid>("ItemSetGroupId") .HasColumnType("uuid"); b.HasKey("ItemId", "ItemSetGroupId"); b.HasIndex("ItemSetGroupId"); b.ToTable("ItemItemSetGroup", "data"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOfItemSet", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("BonusOptionId") .HasColumnType("uuid"); b.Property<Guid?>("ItemDefinitionId") .HasColumnType("uuid"); b.Property<Guid?>("ItemSetGroupId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("BonusOptionId"); b.HasIndex("ItemDefinitionId"); b.HasIndex("ItemSetGroupId"); b.ToTable("ItemOfItemSet", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionCombinationBonus", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<bool>("AppliesMultipleTimes") .HasColumnType("boolean"); b.Property<Guid?>("BonusId") .HasColumnType("uuid"); b.Property<string>("Description") .IsRequired() .HasColumnType("text"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.Property<int>("Number") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("BonusId"); b.HasIndex("GameConfigurationId"); b.ToTable("ItemOptionCombinationBonus", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionDefinition", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<float>("AddChance") .HasColumnType("real"); b.Property<bool>("AddsRandomly") .HasColumnType("boolean"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.Property<int>("MaximumOptionsPerItem") .HasColumnType("integer"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("GameConfigurationId"); b.ToTable("ItemOptionDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionLink", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<int>("Index") .HasColumnType("integer"); b.Property<Guid?>("ItemId") .HasColumnType("uuid"); b.Property<Guid?>("ItemOptionId") .HasColumnType("uuid"); b.Property<int>("Level") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("ItemId"); b.HasIndex("ItemOptionId"); b.ToTable("ItemOptionLink", "data"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionOfLevel", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("IncreasableItemOptionId") .HasColumnType("uuid"); b.Property<int>("Level") .HasColumnType("integer"); b.Property<Guid?>("PowerUpDefinitionId") .HasColumnType("uuid"); b.Property<int>("RequiredItemLevel") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("IncreasableItemOptionId"); b.HasIndex("PowerUpDefinitionId"); b.ToTable("ItemOptionOfLevel", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionType", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<string>("Description") .IsRequired() .HasColumnType("text"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.Property<bool>("IsVisible") .HasColumnType("boolean"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("GameConfigurationId"); b.ToTable("ItemOptionType", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemSetGroup", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<bool>("AlwaysApplies") .HasColumnType("boolean"); b.Property<int>("AncientSetDiscriminator") .HasColumnType("integer"); b.Property<bool>("CountDistinct") .HasColumnType("boolean"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.Property<int>("MinimumItemCount") .HasColumnType("integer"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.Property<int>("SetLevel") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("GameConfigurationId"); b.ToTable("ItemSetGroup", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemSlotType", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<string>("Description") .IsRequired() .HasColumnType("text"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.Property<string>("RawItemSlots") .HasColumnType("text") .HasColumnName("ItemSlots"); b.HasKey("Id"); b.HasIndex("GameConfigurationId"); b.ToTable("ItemSlotType", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemStorage", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<int>("Money") .HasColumnType("integer"); b.HasKey("Id"); b.ToTable("ItemStorage", "data"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.JewelMix", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.Property<Guid?>("MixedJewelId") .HasColumnType("uuid"); b.Property<byte>("Number") .HasColumnType("smallint"); b.Property<Guid?>("SingleJewelId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("GameConfigurationId"); b.HasIndex("MixedJewelId"); b.HasIndex("SingleJewelId"); b.ToTable("JewelMix", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.LetterBody", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<byte>("Animation") .HasColumnType("smallint"); b.Property<Guid?>("HeaderId") .HasColumnType("uuid"); b.Property<string>("Message") .IsRequired() .HasColumnType("text"); b.Property<byte>("Rotation") .HasColumnType("smallint"); b.Property<Guid?>("SenderAppearanceId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("HeaderId"); b.HasIndex("SenderAppearanceId"); b.ToTable("LetterBody", "data"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.LetterHeader", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<DateTime>("LetterDate") .HasColumnType("timestamp without time zone"); b.Property<bool>("ReadFlag") .HasColumnType("boolean"); b.Property<Guid>("ReceiverId") .HasColumnType("uuid"); b.Property<string>("SenderName") .HasColumnType("text"); b.Property<string>("Subject") .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("ReceiverId"); b.ToTable("LetterHeader", "data"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.LevelBonus", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<float>("AdditionalValue") .HasColumnType("real"); b.Property<Guid?>("ItemBasePowerUpDefinitionId") .HasColumnType("uuid"); b.Property<int>("Level") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("ItemBasePowerUpDefinitionId"); b.ToTable("LevelBonus", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MagicEffectDefinition", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.Property<bool>("InformObservers") .HasColumnType("boolean"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.Property<short>("Number") .HasColumnType("smallint"); b.Property<Guid?>("PowerUpDefinitionId") .HasColumnType("uuid"); b.Property<bool>("SendDuration") .HasColumnType("boolean"); b.Property<bool>("StopByDeath") .HasColumnType("boolean"); b.Property<byte>("SubType") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("GameConfigurationId"); b.HasIndex("PowerUpDefinitionId"); b.ToTable("MagicEffectDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MasterSkillDefinition", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<int>("Aggregation") .HasColumnType("integer"); b.Property<string>("DisplayValueFormula") .IsRequired() .HasColumnType("text"); b.Property<byte>("MaximumLevel") .HasColumnType("smallint"); b.Property<byte>("MinimumLevel") .HasColumnType("smallint"); b.Property<byte>("Rank") .HasColumnType("smallint"); b.Property<Guid?>("ReplacedSkillId") .HasColumnType("uuid"); b.Property<Guid?>("RootId") .HasColumnType("uuid"); b.Property<Guid?>("TargetAttributeId") .HasColumnType("uuid"); b.Property<string>("ValueFormula") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("ReplacedSkillId"); b.HasIndex("RootId"); b.HasIndex("TargetAttributeId"); b.ToTable("MasterSkillDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MasterSkillDefinitionSkill", b => { b.Property<Guid>("MasterSkillDefinitionId") .HasColumnType("uuid"); b.Property<Guid>("SkillId") .HasColumnType("uuid"); b.HasKey("MasterSkillDefinitionId", "SkillId"); b.HasIndex("SkillId"); b.ToTable("MasterSkillDefinitionSkill", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MasterSkillRoot", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("GameConfigurationId"); b.ToTable("MasterSkillRoot", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MonsterAttribute", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("AttributeDefinitionId") .HasColumnType("uuid"); b.Property<Guid?>("MonsterDefinitionId") .HasColumnType("uuid"); b.Property<float>("Value") .HasColumnType("real"); b.HasKey("Id"); b.HasIndex("AttributeDefinitionId"); b.HasIndex("MonsterDefinitionId"); b.ToTable("MonsterAttribute", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MonsterDefinition", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<TimeSpan>("AttackDelay") .HasColumnType("interval"); b.Property<byte>("AttackRange") .HasColumnType("smallint"); b.Property<Guid?>("AttackSkillId") .HasColumnType("uuid"); b.Property<byte>("Attribute") .HasColumnType("smallint"); b.Property<string>("Designation") .IsRequired() .HasColumnType("text"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.Property<string>("IntelligenceTypeName") .HasColumnType("text"); b.Property<Guid?>("MerchantStoreId") .HasColumnType("uuid"); b.Property<TimeSpan>("MoveDelay") .HasColumnType("interval"); b.Property<byte>("MoveRange") .HasColumnType("smallint"); b.Property<int>("NpcWindow") .HasColumnType("integer"); b.Property<short>("Number") .HasColumnType("smallint"); b.Property<int>("NumberOfMaximumItemDrops") .HasColumnType("integer"); b.Property<int>("ObjectKind") .HasColumnType("integer"); b.Property<TimeSpan>("RespawnDelay") .HasColumnType("interval"); b.Property<short>("ViewRange") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("AttackSkillId"); b.HasIndex("GameConfigurationId"); b.HasIndex("MerchantStoreId"); b.ToTable("MonsterDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MonsterDefinitionDropItemGroup", b => { b.Property<Guid>("MonsterDefinitionId") .HasColumnType("uuid"); b.Property<Guid>("DropItemGroupId") .HasColumnType("uuid"); b.HasKey("MonsterDefinitionId", "DropItemGroupId"); b.HasIndex("DropItemGroupId"); b.ToTable("MonsterDefinitionDropItemGroup", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MonsterSpawnArea", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<int>("Direction") .HasColumnType("integer"); b.Property<Guid?>("GameMapId") .HasColumnType("uuid"); b.Property<Guid?>("MonsterDefinitionId") .HasColumnType("uuid"); b.Property<short>("Quantity") .HasColumnType("smallint"); b.Property<int>("SpawnTrigger") .HasColumnType("integer"); b.Property<byte>("X1") .HasColumnType("smallint"); b.Property<byte>("X2") .HasColumnType("smallint"); b.Property<byte>("Y1") .HasColumnType("smallint"); b.Property<byte>("Y2") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("GameMapId"); b.HasIndex("MonsterDefinitionId"); b.ToTable("MonsterSpawnArea", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.PlugInConfiguration", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<string>("CustomConfiguration") .HasColumnType("text"); b.Property<string>("CustomPlugInSource") .HasColumnType("text"); b.Property<string>("ExternalAssemblyName") .HasColumnType("text"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.Property<bool>("IsActive") .HasColumnType("boolean"); b.Property<Guid>("TypeId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("GameConfigurationId"); b.ToTable("PlugInConfiguration", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.PowerUpDefinition", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("BoostId") .HasColumnType("uuid"); b.Property<Guid?>("TargetAttributeId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("BoostId"); b.HasIndex("TargetAttributeId"); b.ToTable("PowerUpDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.PowerUpDefinitionValue", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<int>("AggregateType") .HasColumnType("integer"); b.Property<Guid?>("ParentAsBoostId") .HasColumnType("uuid"); b.Property<Guid?>("ParentAsDurationId") .HasColumnType("uuid"); b.Property<float>("Value") .HasColumnType("real"); b.HasKey("Id"); b.ToTable("PowerUpDefinitionValue", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.PowerUpDefinitionWithDuration", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("BoostId") .HasColumnType("uuid"); b.Property<Guid?>("DurationId") .HasColumnType("uuid"); b.Property<Guid?>("TargetAttributeId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("BoostId") .IsUnique(); b.HasIndex("DurationId") .IsUnique(); b.HasIndex("TargetAttributeId"); b.ToTable("PowerUpDefinitionWithDuration", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.QuestDefinition", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<short>("Group") .HasColumnType("smallint"); b.Property<int>("MaximumCharacterLevel") .HasColumnType("integer"); b.Property<int>("MinimumCharacterLevel") .HasColumnType("integer"); b.Property<Guid?>("MonsterDefinitionId") .HasColumnType("uuid"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.Property<short>("Number") .HasColumnType("smallint"); b.Property<Guid?>("QualifiedCharacterId") .HasColumnType("uuid"); b.Property<Guid?>("QuestGiverId") .HasColumnType("uuid"); b.Property<short>("RefuseNumber") .HasColumnType("smallint"); b.Property<bool>("Repeatable") .HasColumnType("boolean"); b.Property<int>("RequiredStartMoney") .HasColumnType("integer"); b.Property<bool>("RequiresClientAction") .HasColumnType("boolean"); b.Property<short>("StartingNumber") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("MonsterDefinitionId"); b.HasIndex("QualifiedCharacterId"); b.HasIndex("QuestGiverId"); b.ToTable("QuestDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.QuestItemRequirement", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("DropItemGroupId") .HasColumnType("uuid"); b.Property<Guid?>("ItemId") .HasColumnType("uuid"); b.Property<int>("MinimumNumber") .HasColumnType("integer"); b.Property<Guid?>("QuestDefinitionId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("DropItemGroupId"); b.HasIndex("ItemId"); b.HasIndex("QuestDefinitionId"); b.ToTable("QuestItemRequirement", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.QuestMonsterKillRequirement", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<int>("MinimumNumber") .HasColumnType("integer"); b.Property<Guid?>("MonsterId") .HasColumnType("uuid"); b.Property<Guid?>("QuestDefinitionId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("MonsterId"); b.HasIndex("QuestDefinitionId"); b.ToTable("QuestMonsterKillRequirement", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.QuestMonsterKillRequirementState", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("CharacterQuestStateId") .HasColumnType("uuid"); b.Property<int>("KillCount") .HasColumnType("integer"); b.Property<Guid?>("RequirementId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("CharacterQuestStateId"); b.HasIndex("RequirementId"); b.ToTable("QuestMonsterKillRequirementState", "data"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.QuestReward", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("AttributeRewardId") .HasColumnType("uuid"); b.Property<Guid?>("ItemRewardId") .HasColumnType("uuid"); b.Property<Guid?>("QuestDefinitionId") .HasColumnType("uuid"); b.Property<int>("RewardType") .HasColumnType("integer"); b.Property<int>("Value") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("AttributeRewardId"); b.HasIndex("ItemRewardId"); b.HasIndex("QuestDefinitionId"); b.ToTable("QuestReward", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.SimpleCraftingSettings", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<byte>("MaximumSuccessPercent") .HasColumnType("smallint"); b.Property<int>("Money") .HasColumnType("integer"); b.Property<int>("MoneyPerFinalSuccessPercentage") .HasColumnType("integer"); b.Property<bool>("MultipleAllowed") .HasColumnType("boolean"); b.Property<byte>("ResultItemExcellentOptionChance") .HasColumnType("smallint"); b.Property<byte>("ResultItemLuckOptionChance") .HasColumnType("smallint"); b.Property<byte>("ResultItemMaxExcOptionCount") .HasColumnType("smallint"); b.Property<int>("ResultItemSelect") .HasColumnType("integer"); b.Property<byte>("ResultItemSkillChance") .HasColumnType("smallint"); b.Property<byte>("SuccessPercent") .HasColumnType("smallint"); b.Property<int>("SuccessPercentageAdditionForAncientItem") .HasColumnType("integer"); b.Property<int>("SuccessPercentageAdditionForExcellentItem") .HasColumnType("integer"); b.Property<int>("SuccessPercentageAdditionForLuck") .HasColumnType("integer"); b.Property<int>("SuccessPercentageAdditionForSocketItem") .HasColumnType("integer"); b.HasKey("Id"); b.ToTable("SimpleCraftingSettings", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.Skill", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<int>("AttackDamage") .HasColumnType("integer"); b.Property<int>("DamageType") .HasColumnType("integer"); b.Property<Guid?>("ElementalModifierTargetId") .HasColumnType("uuid"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.Property<short>("ImplicitTargetRange") .HasColumnType("smallint"); b.Property<Guid?>("MagicEffectDefId") .HasColumnType("uuid"); b.Property<Guid?>("MasterDefinitionId") .HasColumnType("uuid"); b.Property<bool>("MovesTarget") .HasColumnType("boolean"); b.Property<bool>("MovesToTarget") .HasColumnType("boolean"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.Property<short>("Number") .HasColumnType("smallint"); b.Property<short>("Range") .HasColumnType("smallint"); b.Property<int>("SkillType") .HasColumnType("integer"); b.Property<int>("Target") .HasColumnType("integer"); b.Property<int>("TargetRestriction") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("ElementalModifierTargetId"); b.HasIndex("GameConfigurationId"); b.HasIndex("MagicEffectDefId"); b.HasIndex("MasterDefinitionId"); b.ToTable("Skill", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.SkillCharacterClass", b => { b.Property<Guid>("SkillId") .HasColumnType("uuid"); b.Property<Guid>("CharacterClassId") .HasColumnType("uuid"); b.HasKey("SkillId", "CharacterClassId"); b.HasIndex("CharacterClassId"); b.ToTable("SkillCharacterClass", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.SkillEntry", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("CharacterId") .HasColumnType("uuid"); b.Property<int>("Level") .HasColumnType("integer"); b.Property<Guid?>("SkillId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("CharacterId"); b.HasIndex("SkillId"); b.ToTable("SkillEntry", "data"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.StatAttribute", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("CharacterId") .HasColumnType("uuid"); b.Property<Guid?>("DefinitionId") .HasColumnType("uuid"); b.Property<float>("Value") .HasColumnType("real"); b.HasKey("Id"); b.HasIndex("CharacterId"); b.HasIndex("DefinitionId"); b.ToTable("StatAttribute", "data"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.StatAttributeDefinition", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<Guid?>("AttributeId") .HasColumnType("uuid"); b.Property<float>("BaseValue") .HasColumnType("real"); b.Property<Guid?>("CharacterClassId") .HasColumnType("uuid"); b.Property<bool>("IncreasableByPlayer") .HasColumnType("boolean"); b.HasKey("Id"); b.HasIndex("AttributeId"); b.HasIndex("CharacterClassId"); b.ToTable("StatAttributeDefinition", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.WarpInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<int>("Costs") .HasColumnType("integer"); b.Property<Guid?>("GameConfigurationId") .HasColumnType("uuid"); b.Property<Guid?>("GateId") .HasColumnType("uuid"); b.Property<int>("Index") .HasColumnType("integer"); b.Property<int>("LevelRequirement") .HasColumnType("integer"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("GameConfigurationId"); b.HasIndex("GateId"); b.ToTable("WarpInfo", "config"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.Account", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemStorage", "RawVault") .WithMany() .HasForeignKey("VaultId"); b.Navigation("RawVault"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.AccountCharacterClass", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Account", "Account") .WithMany("JoinedUnlockedCharacterClasses") .HasForeignKey("AccountId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterClass", "CharacterClass") .WithMany() .HasForeignKey("CharacterClassId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Account"); b.Navigation("CharacterClass"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.AppearanceData", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterClass", "RawCharacterClass") .WithMany() .HasForeignKey("CharacterClassId"); b.Navigation("RawCharacterClass"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeDefinition", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", null) .WithMany("RawAttributes") .HasForeignKey("GameConfigurationId"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeRelationship", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterClass", null) .WithMany("RawAttributeCombinations") .HasForeignKey("CharacterClassId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeDefinition", "RawInputAttribute") .WithMany() .HasForeignKey("InputAttributeId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.PowerUpDefinitionValue", null) .WithMany("RawRelatedValues") .HasForeignKey("PowerUpDefinitionValueId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeDefinition", "RawTargetAttribute") .WithMany() .HasForeignKey("TargetAttributeId"); b.Navigation("RawInputAttribute"); b.Navigation("RawTargetAttribute"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeRequirement", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeDefinition", "RawAttribute") .WithMany() .HasForeignKey("AttributeId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameMapDefinition", null) .WithMany("RawMapRequirements") .HasForeignKey("GameMapDefinitionId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinition", null) .WithMany("RawRequirements") .HasForeignKey("ItemDefinitionId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Skill", null) .WithMany("RawConsumeRequirements") .HasForeignKey("SkillId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Skill", null) .WithMany("RawRequirements") .HasForeignKey("SkillId1"); b.Navigation("RawAttribute"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.Character", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Account", null) .WithMany("RawCharacters") .HasForeignKey("AccountId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterClass", "RawCharacterClass") .WithMany() .HasForeignKey("CharacterClassId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameMapDefinition", "RawCurrentMap") .WithMany() .HasForeignKey("CurrentMapId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemStorage", "RawInventory") .WithMany() .HasForeignKey("InventoryId"); b.Navigation("RawCharacterClass"); b.Navigation("RawCurrentMap"); b.Navigation("RawInventory"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterClass", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", null) .WithMany("RawCharacterClasses") .HasForeignKey("GameConfigurationId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameMapDefinition", "RawHomeMap") .WithMany() .HasForeignKey("HomeMapId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterClass", "RawNextGenerationClass") .WithMany() .HasForeignKey("NextGenerationClassId"); b.Navigation("RawHomeMap"); b.Navigation("RawNextGenerationClass"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterDropItemGroup", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Character", "Character") .WithMany("JoinedDropItemGroups") .HasForeignKey("CharacterId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.DropItemGroup", "DropItemGroup") .WithMany() .HasForeignKey("DropItemGroupId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Character"); b.Navigation("DropItemGroup"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterQuestState", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.QuestDefinition", "RawActiveQuest") .WithMany() .HasForeignKey("ActiveQuestId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Character", null) .WithMany("RawQuestStates") .HasForeignKey("CharacterId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.QuestDefinition", "RawLastFinishedQuest") .WithMany() .HasForeignKey("LastFinishedQuestId"); b.Navigation("RawActiveQuest"); b.Navigation("RawLastFinishedQuest"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ChatServerEndpoint", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ChatServerDefinition", null) .WithMany("RawEndpoints") .HasForeignKey("ChatServerDefinitionId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameClientDefinition", "RawClient") .WithMany() .HasForeignKey("ClientId"); b.Navigation("RawClient"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.CombinationBonusRequirement", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionCombinationBonus", null) .WithMany("RawRequirements") .HasForeignKey("ItemOptionCombinationBonusId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionType", "RawOptionType") .WithMany() .HasForeignKey("OptionTypeId"); b.Navigation("RawOptionType"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ConnectServerDefinition", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameClientDefinition", "RawClient") .WithMany() .HasForeignKey("ClientId"); b.Navigation("RawClient"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ConstValueAttribute", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterClass", "CharacterClass") .WithMany("RawBaseAttributeValues") .HasForeignKey("CharacterClassId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeDefinition", "RawDefinition") .WithMany() .HasForeignKey("DefinitionId"); b.Navigation("CharacterClass"); b.Navigation("RawDefinition"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.DropItemGroup", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", null) .WithMany("RawDropItemGroups") .HasForeignKey("GameConfigurationId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.MonsterDefinition", "RawMonster") .WithMany() .HasForeignKey("MonsterId"); b.Navigation("RawMonster"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.DropItemGroupItemDefinition", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.DropItemGroup", "DropItemGroup") .WithMany("JoinedPossibleItems") .HasForeignKey("DropItemGroupId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinition", "ItemDefinition") .WithMany() .HasForeignKey("ItemDefinitionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("DropItemGroup"); b.Navigation("ItemDefinition"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.EnterGate", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameMapDefinition", null) .WithMany("RawEnterGates") .HasForeignKey("GameMapDefinitionId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ExitGate", "RawTargetGate") .WithMany() .HasForeignKey("TargetGateId"); b.Navigation("RawTargetGate"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ExitGate", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameMapDefinition", "RawMap") .WithMany("RawExitGates") .HasForeignKey("MapId"); b.Navigation("RawMap"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GameMapDefinition", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", null) .WithMany("RawMaps") .HasForeignKey("GameConfigurationId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameMapDefinition", "RawSafezoneMap") .WithMany() .HasForeignKey("SafezoneMapId"); b.Navigation("RawSafezoneMap"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GameMapDefinitionDropItemGroup", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.DropItemGroup", "DropItemGroup") .WithMany() .HasForeignKey("DropItemGroupId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameMapDefinition", "GameMapDefinition") .WithMany("JoinedDropItemGroups") .HasForeignKey("GameMapDefinitionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("DropItemGroup"); b.Navigation("GameMapDefinition"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GameServerConfigurationGameMapDefinition", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameMapDefinition", "GameMapDefinition") .WithMany() .HasForeignKey("GameMapDefinitionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameServerConfiguration", "GameServerConfiguration") .WithMany("JoinedMaps") .HasForeignKey("GameServerConfigurationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("GameMapDefinition"); b.Navigation("GameServerConfiguration"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GameServerDefinition", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", "RawGameConfiguration") .WithMany() .HasForeignKey("GameConfigurationId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameServerConfiguration", "RawServerConfiguration") .WithMany() .HasForeignKey("ServerConfigurationId"); b.Navigation("RawGameConfiguration"); b.Navigation("RawServerConfiguration"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GameServerEndpoint", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameClientDefinition", "RawClient") .WithMany() .HasForeignKey("ClientId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameServerDefinition", null) .WithMany("RawEndpoints") .HasForeignKey("GameServerDefinitionId"); b.Navigation("RawClient"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.Guild", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Guild", "RawAllianceGuild") .WithMany() .HasForeignKey("AllianceGuildId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Guild", "RawHostility") .WithMany() .HasForeignKey("HostilityId"); b.Navigation("RawAllianceGuild"); b.Navigation("RawHostility"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GuildMember", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Guild", null) .WithMany("RawMembers") .HasForeignKey("GuildId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Character", "Character") .WithMany() .HasForeignKey("Id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Character"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.IncreasableItemOption", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionDefinition", null) .WithMany("RawPossibleOptions") .HasForeignKey("ItemOptionDefinitionId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemSetGroup", null) .WithMany("RawOptions") .HasForeignKey("ItemSetGroupId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionType", "RawOptionType") .WithMany() .HasForeignKey("OptionTypeId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.PowerUpDefinition", "RawPowerUpDefinition") .WithMany() .HasForeignKey("PowerUpDefinitionId"); b.Navigation("RawOptionType"); b.Navigation("RawPowerUpDefinition"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.Item", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinition", "RawDefinition") .WithMany() .HasForeignKey("DefinitionId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemStorage", "RawItemStorage") .WithMany("RawItems") .HasForeignKey("ItemStorageId"); b.Navigation("RawDefinition"); b.Navigation("RawItemStorage"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemAppearance", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.AppearanceData", null) .WithMany("RawEquippedItems") .HasForeignKey("AppearanceDataId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinition", "RawDefinition") .WithMany() .HasForeignKey("DefinitionId"); b.Navigation("RawDefinition"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemAppearanceItemOptionType", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemAppearance", "ItemAppearance") .WithMany("JoinedVisibleOptions") .HasForeignKey("ItemAppearanceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionType", "ItemOptionType") .WithMany() .HasForeignKey("ItemOptionTypeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("ItemAppearance"); b.Navigation("ItemOptionType"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemBasePowerUpDefinition", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinition", null) .WithMany("RawBasePowerUpAttributes") .HasForeignKey("ItemDefinitionId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeDefinition", "RawTargetAttribute") .WithMany() .HasForeignKey("TargetAttributeId"); b.Navigation("RawTargetAttribute"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemCrafting", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.MonsterDefinition", null) .WithMany("RawItemCraftings") .HasForeignKey("MonsterDefinitionId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.SimpleCraftingSettings", "RawSimpleCraftingSettings") .WithMany() .HasForeignKey("SimpleCraftingSettingsId"); b.Navigation("RawSimpleCraftingSettings"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemCraftingRequiredItem", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.SimpleCraftingSettings", null) .WithMany("RawRequiredItems") .HasForeignKey("SimpleCraftingSettingsId"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemCraftingRequiredItemItemDefinition", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemCraftingRequiredItem", "ItemCraftingRequiredItem") .WithMany("JoinedPossibleItems") .HasForeignKey("ItemCraftingRequiredItemId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinition", "ItemDefinition") .WithMany() .HasForeignKey("ItemDefinitionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("ItemCraftingRequiredItem"); b.Navigation("ItemDefinition"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemCraftingRequiredItemItemOptionType", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemCraftingRequiredItem", "ItemCraftingRequiredItem") .WithMany("JoinedRequiredItemOptions") .HasForeignKey("ItemCraftingRequiredItemId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionType", "ItemOptionType") .WithMany() .HasForeignKey("ItemOptionTypeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("ItemCraftingRequiredItem"); b.Navigation("ItemOptionType"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemCraftingResultItem", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinition", "RawItemDefinition") .WithMany() .HasForeignKey("ItemDefinitionId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.SimpleCraftingSettings", null) .WithMany("RawResultItems") .HasForeignKey("SimpleCraftingSettingsId"); b.Navigation("RawItemDefinition"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinition", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", null) .WithMany("RawItems") .HasForeignKey("GameConfigurationId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemSlotType", "RawItemSlot") .WithMany() .HasForeignKey("ItemSlotId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Skill", "RawSkill") .WithMany() .HasForeignKey("SkillId"); b.Navigation("RawItemSlot"); b.Navigation("RawSkill"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinitionCharacterClass", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterClass", "CharacterClass") .WithMany() .HasForeignKey("CharacterClassId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinition", "ItemDefinition") .WithMany("JoinedQualifiedCharacters") .HasForeignKey("ItemDefinitionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("CharacterClass"); b.Navigation("ItemDefinition"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinitionItemOptionDefinition", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinition", "ItemDefinition") .WithMany("JoinedPossibleItemOptions") .HasForeignKey("ItemDefinitionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionDefinition", "ItemOptionDefinition") .WithMany() .HasForeignKey("ItemOptionDefinitionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("ItemDefinition"); b.Navigation("ItemOptionDefinition"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinitionItemSetGroup", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinition", "ItemDefinition") .WithMany("JoinedPossibleItemSetGroups") .HasForeignKey("ItemDefinitionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemSetGroup", "ItemSetGroup") .WithMany() .HasForeignKey("ItemSetGroupId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("ItemDefinition"); b.Navigation("ItemSetGroup"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemItemSetGroup", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Item", "Item") .WithMany("JoinedItemSetGroups") .HasForeignKey("ItemId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemSetGroup", "ItemSetGroup") .WithMany() .HasForeignKey("ItemSetGroupId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Item"); b.Navigation("ItemSetGroup"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOfItemSet", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.IncreasableItemOption", "RawBonusOption") .WithMany() .HasForeignKey("BonusOptionId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinition", "RawItemDefinition") .WithMany() .HasForeignKey("ItemDefinitionId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemSetGroup", null) .WithMany("RawItems") .HasForeignKey("ItemSetGroupId"); b.Navigation("RawBonusOption"); b.Navigation("RawItemDefinition"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionCombinationBonus", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.PowerUpDefinition", "RawBonus") .WithMany() .HasForeignKey("BonusId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", null) .WithMany("RawItemOptionCombinationBonuses") .HasForeignKey("GameConfigurationId"); b.Navigation("RawBonus"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionDefinition", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", null) .WithMany("RawItemOptions") .HasForeignKey("GameConfigurationId"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionLink", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Item", null) .WithMany("RawItemOptions") .HasForeignKey("ItemId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.IncreasableItemOption", "RawItemOption") .WithMany() .HasForeignKey("ItemOptionId"); b.Navigation("RawItemOption"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionOfLevel", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.IncreasableItemOption", null) .WithMany("RawLevelDependentOptions") .HasForeignKey("IncreasableItemOptionId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.PowerUpDefinition", "RawPowerUpDefinition") .WithMany() .HasForeignKey("PowerUpDefinitionId"); b.Navigation("RawPowerUpDefinition"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionType", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", null) .WithMany("RawItemOptionTypes") .HasForeignKey("GameConfigurationId"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemSetGroup", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", null) .WithMany("RawItemSetGroups") .HasForeignKey("GameConfigurationId"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemSlotType", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", null) .WithMany("RawItemSlotTypes") .HasForeignKey("GameConfigurationId"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.JewelMix", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", null) .WithMany("RawJewelMixes") .HasForeignKey("GameConfigurationId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinition", "RawMixedJewel") .WithMany() .HasForeignKey("MixedJewelId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinition", "RawSingleJewel") .WithMany() .HasForeignKey("SingleJewelId"); b.Navigation("RawMixedJewel"); b.Navigation("RawSingleJewel"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.LetterBody", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.LetterHeader", "RawHeader") .WithMany() .HasForeignKey("HeaderId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.AppearanceData", "RawSenderAppearance") .WithMany() .HasForeignKey("SenderAppearanceId"); b.Navigation("RawHeader"); b.Navigation("RawSenderAppearance"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.LetterHeader", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Character", "Receiver") .WithMany("RawLetters") .HasForeignKey("ReceiverId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Receiver"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.LevelBonus", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemBasePowerUpDefinition", null) .WithMany("RawBonusPerLevel") .HasForeignKey("ItemBasePowerUpDefinitionId"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MagicEffectDefinition", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", null) .WithMany("RawMagicEffects") .HasForeignKey("GameConfigurationId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.PowerUpDefinitionWithDuration", "RawPowerUpDefinition") .WithMany() .HasForeignKey("PowerUpDefinitionId"); b.Navigation("RawPowerUpDefinition"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MasterSkillDefinition", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Skill", "RawReplacedSkill") .WithMany() .HasForeignKey("ReplacedSkillId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.MasterSkillRoot", "RawRoot") .WithMany() .HasForeignKey("RootId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeDefinition", "RawTargetAttribute") .WithMany() .HasForeignKey("TargetAttributeId"); b.Navigation("RawReplacedSkill"); b.Navigation("RawRoot"); b.Navigation("RawTargetAttribute"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MasterSkillDefinitionSkill", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.MasterSkillDefinition", "MasterSkillDefinition") .WithMany("JoinedRequiredMasterSkills") .HasForeignKey("MasterSkillDefinitionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Skill", "Skill") .WithMany() .HasForeignKey("SkillId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("MasterSkillDefinition"); b.Navigation("Skill"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MasterSkillRoot", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", null) .WithMany("RawMasterSkillRoots") .HasForeignKey("GameConfigurationId"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MonsterAttribute", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeDefinition", "RawAttributeDefinition") .WithMany() .HasForeignKey("AttributeDefinitionId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.MonsterDefinition", null) .WithMany("RawAttributes") .HasForeignKey("MonsterDefinitionId"); b.Navigation("RawAttributeDefinition"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MonsterDefinition", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Skill", "RawAttackSkill") .WithMany() .HasForeignKey("AttackSkillId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", null) .WithMany("RawMonsters") .HasForeignKey("GameConfigurationId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemStorage", "RawMerchantStore") .WithMany() .HasForeignKey("MerchantStoreId"); b.Navigation("RawAttackSkill"); b.Navigation("RawMerchantStore"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MonsterDefinitionDropItemGroup", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.DropItemGroup", "DropItemGroup") .WithMany() .HasForeignKey("DropItemGroupId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.MonsterDefinition", "MonsterDefinition") .WithMany("JoinedDropItemGroups") .HasForeignKey("MonsterDefinitionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("DropItemGroup"); b.Navigation("MonsterDefinition"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MonsterSpawnArea", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameMapDefinition", "RawGameMap") .WithMany("RawMonsterSpawns") .HasForeignKey("GameMapId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.MonsterDefinition", "RawMonsterDefinition") .WithMany() .HasForeignKey("MonsterDefinitionId"); b.Navigation("RawGameMap"); b.Navigation("RawMonsterDefinition"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.PlugInConfiguration", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", null) .WithMany("RawPlugInConfigurations") .HasForeignKey("GameConfigurationId"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.PowerUpDefinition", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.PowerUpDefinitionValue", "RawBoost") .WithMany() .HasForeignKey("BoostId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeDefinition", "RawTargetAttribute") .WithMany() .HasForeignKey("TargetAttributeId"); b.Navigation("RawBoost"); b.Navigation("RawTargetAttribute"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.PowerUpDefinitionWithDuration", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.PowerUpDefinitionValue", "RawBoost") .WithOne("ParentAsBoost") .HasForeignKey("MUnique.OpenMU.Persistence.EntityFramework.Model.PowerUpDefinitionWithDuration", "BoostId") .HasConstraintName("PowerUpDefinitionWithDuration_Boost") .OnDelete(DeleteBehavior.Cascade); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.PowerUpDefinitionValue", "RawDuration") .WithOne("ParentAsDuration") .HasForeignKey("MUnique.OpenMU.Persistence.EntityFramework.Model.PowerUpDefinitionWithDuration", "DurationId") .HasConstraintName("PowerUpDefinitionWithDuration_Duration") .OnDelete(DeleteBehavior.Cascade); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeDefinition", "RawTargetAttribute") .WithMany() .HasForeignKey("TargetAttributeId"); b.Navigation("RawBoost"); b.Navigation("RawDuration"); b.Navigation("RawTargetAttribute"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.QuestDefinition", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.MonsterDefinition", null) .WithMany("RawQuests") .HasForeignKey("MonsterDefinitionId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterClass", "RawQualifiedCharacter") .WithMany() .HasForeignKey("QualifiedCharacterId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.MonsterDefinition", "RawQuestGiver") .WithMany() .HasForeignKey("QuestGiverId"); b.Navigation("RawQualifiedCharacter"); b.Navigation("RawQuestGiver"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.QuestItemRequirement", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.DropItemGroup", "RawDropItemGroup") .WithMany() .HasForeignKey("DropItemGroupId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinition", "RawItem") .WithMany() .HasForeignKey("ItemId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.QuestDefinition", null) .WithMany("RawRequiredItems") .HasForeignKey("QuestDefinitionId"); b.Navigation("RawDropItemGroup"); b.Navigation("RawItem"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.QuestMonsterKillRequirement", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.MonsterDefinition", "RawMonster") .WithMany() .HasForeignKey("MonsterId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.QuestDefinition", null) .WithMany("RawRequiredMonsterKills") .HasForeignKey("QuestDefinitionId"); b.Navigation("RawMonster"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.QuestMonsterKillRequirementState", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterQuestState", null) .WithMany("RawRequirementStates") .HasForeignKey("CharacterQuestStateId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.QuestMonsterKillRequirement", "RawRequirement") .WithMany() .HasForeignKey("RequirementId"); b.Navigation("RawRequirement"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.QuestReward", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeDefinition", "RawAttributeReward") .WithMany() .HasForeignKey("AttributeRewardId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Item", "RawItemReward") .WithMany() .HasForeignKey("ItemRewardId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.QuestDefinition", null) .WithMany("RawRewards") .HasForeignKey("QuestDefinitionId"); b.Navigation("RawAttributeReward"); b.Navigation("RawItemReward"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.Skill", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeDefinition", "RawElementalModifierTarget") .WithMany() .HasForeignKey("ElementalModifierTargetId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", null) .WithMany("RawSkills") .HasForeignKey("GameConfigurationId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.MagicEffectDefinition", "RawMagicEffectDef") .WithMany() .HasForeignKey("MagicEffectDefId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.MasterSkillDefinition", "RawMasterDefinition") .WithMany() .HasForeignKey("MasterDefinitionId"); b.Navigation("RawElementalModifierTarget"); b.Navigation("RawMagicEffectDef"); b.Navigation("RawMasterDefinition"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.SkillCharacterClass", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterClass", "CharacterClass") .WithMany() .HasForeignKey("CharacterClassId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Skill", "Skill") .WithMany("JoinedQualifiedCharacters") .HasForeignKey("SkillId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("CharacterClass"); b.Navigation("Skill"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.SkillEntry", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Character", null) .WithMany("RawLearnedSkills") .HasForeignKey("CharacterId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Skill", "RawSkill") .WithMany() .HasForeignKey("SkillId"); b.Navigation("RawSkill"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.StatAttribute", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.Character", null) .WithMany("RawAttributes") .HasForeignKey("CharacterId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeDefinition", "RawDefinition") .WithMany() .HasForeignKey("DefinitionId"); b.Navigation("RawDefinition"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.StatAttributeDefinition", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.AttributeDefinition", "RawAttribute") .WithMany() .HasForeignKey("AttributeId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterClass", null) .WithMany("RawStatAttributes") .HasForeignKey("CharacterClassId"); b.Navigation("RawAttribute"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.WarpInfo", b => { b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", null) .WithMany("RawWarpList") .HasForeignKey("GameConfigurationId"); b.HasOne("MUnique.OpenMU.Persistence.EntityFramework.Model.ExitGate", "RawGate") .WithMany() .HasForeignKey("GateId"); b.Navigation("RawGate"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.Account", b => { b.Navigation("JoinedUnlockedCharacterClasses"); b.Navigation("RawCharacters"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.AppearanceData", b => { b.Navigation("RawEquippedItems"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.Character", b => { b.Navigation("JoinedDropItemGroups"); b.Navigation("RawAttributes"); b.Navigation("RawLearnedSkills"); b.Navigation("RawLetters"); b.Navigation("RawQuestStates"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterClass", b => { b.Navigation("RawAttributeCombinations"); b.Navigation("RawBaseAttributeValues"); b.Navigation("RawStatAttributes"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.CharacterQuestState", b => { b.Navigation("RawRequirementStates"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ChatServerDefinition", b => { b.Navigation("RawEndpoints"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.DropItemGroup", b => { b.Navigation("JoinedPossibleItems"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GameConfiguration", b => { b.Navigation("RawAttributes"); b.Navigation("RawCharacterClasses"); b.Navigation("RawDropItemGroups"); b.Navigation("RawItemOptionCombinationBonuses"); b.Navigation("RawItemOptions"); b.Navigation("RawItemOptionTypes"); b.Navigation("RawItems"); b.Navigation("RawItemSetGroups"); b.Navigation("RawItemSlotTypes"); b.Navigation("RawJewelMixes"); b.Navigation("RawMagicEffects"); b.Navigation("RawMaps"); b.Navigation("RawMasterSkillRoots"); b.Navigation("RawMonsters"); b.Navigation("RawPlugInConfigurations"); b.Navigation("RawSkills"); b.Navigation("RawWarpList"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GameMapDefinition", b => { b.Navigation("JoinedDropItemGroups"); b.Navigation("RawEnterGates"); b.Navigation("RawExitGates"); b.Navigation("RawMapRequirements"); b.Navigation("RawMonsterSpawns"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GameServerConfiguration", b => { b.Navigation("JoinedMaps"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.GameServerDefinition", b => { b.Navigation("RawEndpoints"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.Guild", b => { b.Navigation("RawMembers"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.IncreasableItemOption", b => { b.Navigation("RawLevelDependentOptions"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.Item", b => { b.Navigation("JoinedItemSetGroups"); b.Navigation("RawItemOptions"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemAppearance", b => { b.Navigation("JoinedVisibleOptions"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemBasePowerUpDefinition", b => { b.Navigation("RawBonusPerLevel"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemCraftingRequiredItem", b => { b.Navigation("JoinedPossibleItems"); b.Navigation("JoinedRequiredItemOptions"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemDefinition", b => { b.Navigation("JoinedPossibleItemOptions"); b.Navigation("JoinedPossibleItemSetGroups"); b.Navigation("JoinedQualifiedCharacters"); b.Navigation("RawBasePowerUpAttributes"); b.Navigation("RawRequirements"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionCombinationBonus", b => { b.Navigation("RawRequirements"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemOptionDefinition", b => { b.Navigation("RawPossibleOptions"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemSetGroup", b => { b.Navigation("RawItems"); b.Navigation("RawOptions"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.ItemStorage", b => { b.Navigation("RawItems"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MasterSkillDefinition", b => { b.Navigation("JoinedRequiredMasterSkills"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.MonsterDefinition", b => { b.Navigation("JoinedDropItemGroups"); b.Navigation("RawAttributes"); b.Navigation("RawItemCraftings"); b.Navigation("RawQuests"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.PowerUpDefinitionValue", b => { b.Navigation("ParentAsBoost"); b.Navigation("ParentAsDuration"); b.Navigation("RawRelatedValues"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.QuestDefinition", b => { b.Navigation("RawRequiredItems"); b.Navigation("RawRequiredMonsterKills"); b.Navigation("RawRewards"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.SimpleCraftingSettings", b => { b.Navigation("RawRequiredItems"); b.Navigation("RawResultItems"); }); modelBuilder.Entity("MUnique.OpenMU.Persistence.EntityFramework.Model.Skill", b => { b.Navigation("JoinedQualifiedCharacters"); b.Navigation("RawConsumeRequirements"); b.Navigation("RawRequirements"); }); #pragma warning restore 612, 618 } } }
38.306138
134
0.482437
[ "MIT" ]
cristian-eriomenco/OpenMU
src/Persistence/EntityFramework/Migrations/00000000000000_Initial.designer.cs
149,779
C#
namespace Usain.Samples.Advanced.AzureQueue.Common { using System; using Azure.Storage.Queues; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; // Azure StorageConnectionString is now internal .. // we don't have access to Azure SDK internal validation logic (eg. StorageConnectionString.Parse) // This class just serves as a fast fail check when validating options // rather than waiting for a AzureQueueClient instance initialization (late in the pipeline) // Please don't use that in production public class AzureQueueConnectionStringValidator : IAzureQueueConnectionStringValidator { private const string ErrorMessage = "Azure Queue connection string is not valid. Check your configuration"; private readonly ILogger _logger; public AzureQueueConnectionStringValidator( ILogger<AzureQueueConnectionStringValidator> logger) => _logger = logger; public ValidateOptionsResult Validate( string connectionString, string queueName) { try { new QueueClient( connectionString, queueName); } catch (Exception ex) { _logger.LogError( ex, ErrorMessage); return ValidateOptionsResult.Fail(ErrorMessage); } return ValidateOptionsResult.Success; } } }
33.586957
102
0.620712
[ "MIT" ]
Ciaanh/Usain
samples/02.advanced.azurequeue/Usain.Samples.Advanced.AzureQueue.Common/AzureQueueConnectionStringValidator.cs
1,545
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Blog.Mingor.NET { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
32.196721
109
0.601833
[ "Apache-2.0" ]
FeynmanLoo/Blog.Mingor.NET
src/Startup.cs
1,966
C#
namespace GeminiLab.Core2.Stream { public interface ISeekableStream : IStream { long Seek(long offset, SeekOrigin origin); long Length { get; set; } long Position { get; set; } } }
26.625
50
0.629108
[ "BSD-3-Clause" ]
GeminiLab/GeminiLab.Core2
src/GeminiLab.Core2.Stream/ISeekableStream.cs
213
C#
using Android.Content; using Android.Views; using Android.Widget; namespace Microsoft.Maui.Controls.Handlers.Compatibility { internal class ConditionalFocusLayout : LinearLayout, global::Android.Views.View.IOnTouchListener { public ConditionalFocusLayout(System.IntPtr p, global::Android.Runtime.JniHandleOwnership o) : base(p, o) { // Added default constructor to prevent crash when accessing selected row in ListViewAdapter.Dispose } public ConditionalFocusLayout(Context context) : base(context) { SetOnTouchListener(this); } public bool OnTouch(global::Android.Views.View v, MotionEvent e) { bool allowFocus = v is EditText; DescendantFocusability = allowFocus ? DescendantFocusability.AfterDescendants : DescendantFocusability.BlockDescendants; return false; } internal void ApplyTouchListenersToSpecialCells(Cell item) { DescendantFocusability = DescendantFocusability.BlockDescendants; global::Android.Views.View aView = GetChildAt(0); (aView as EntryCellView)?.EditText.SetOnTouchListener(this); var viewCell = item as ViewCell; if (viewCell?.View == null) return; var renderer = viewCell.View.ToPlatform(item.Handler.MauiContext); GetEditText(renderer)?.SetOnTouchListener(this); foreach (Element descendant in viewCell.View.Descendants()) { var element = descendant as VisualElement; if (element == null) continue; renderer = element.ToPlatform(item.Handler.MauiContext); GetEditText(renderer)?.SetOnTouchListener(this); } } internal EditText GetEditText(global::Android.Views.View v) { if (v is EditText editText) return editText; if (v is ViewGroup vg) return vg.GetFirstChildOfType<EditText>(); return null; } } }
28.354839
123
0.749147
[ "MIT" ]
10088/maui
src/Controls/src/Core/Compatibility/Handlers/ListView/Android/ConditionalFocusLayout.cs
1,758
C#
using System; using System.Collections.Generic; using System.Xml.Serialization; using log4net; using Ramone; using WebRequest = Ramone.Request; namespace OpenWeatherMap.ZimmerBot.AddOn { public class OpenWeatherMapAPI { protected static ILog Logger = LogManager.GetLogger(typeof(OpenWeatherMapAPI)); protected IService OWMService { get; private set; } public OpenWeatherMapAPI() { string baseUrl = OpenWeatherMapAppSettings.BaseUrl; OWMService = RamoneConfiguration.NewService(new Uri(baseUrl)); } public ISession NewSession() { ISession session = OWMService.NewSession(); return session; } public Current GetWeather(string input) { ISession session = NewSession(); WebRequest request = session.Bind("weather", new { q = input, appid = OpenWeatherMapAppSettings.Key.Value, units = "metric", lang = "da", mode = "xml" }); Logger.Debug("GET weather online"); using (var response = request.AcceptXml().Get<Current>()) { return response.Body; } } public Forecast GetForecast(string input, int hours) { ISession session = NewSession(); Logger.Debug("GET forecast online"); WebRequest request = session.Bind("forecast", new { q = input, appid = OpenWeatherMapAppSettings.Key.Value, units = "metric", lang = "da", mode = "xml", cnt = (hours-1)/3 + 1 // One item for every 3 hours }); using (var response = request.AcceptXml().Get<Forecast>()) { return response.Body; } } [XmlRoot("current")] public class Current { [XmlElement("city")] public CurrentCity City { get; set; } [XmlElement("temperature")] public ForecastTemperature Temperature { get; set; } [XmlElement("wind")] public CurrentWind Wind { get; set; } [XmlElement("clouds")] public CurrentClouds Clouds { get; set; } [XmlElement("precipitation")] public CurrentPrecipitation Precipitation { get; set; } [XmlElement("weather")] public CurrentWeather Weather { get; set; } } public class CurrentCity { [XmlElement("sun")] public ForecastSun Sun { get; set; } } public class CurrentWind { [XmlElement("speed")] public CurrentWindSpeed Speed { get; set; } [XmlElement("direction")] public CurrentWindDirection Direction { get; set; } } public class CurrentWindSpeed { [XmlAttribute("value")] public decimal MetersPerSecond { get; set; } [XmlAttribute("name")] public string Name { get; set; } } public class CurrentWindDirection { [XmlAttribute("value")] public string Value { get; set; } [XmlAttribute("code")] public string Code { get; set; } [XmlAttribute("name")] public string Name { get; set; } } public class CurrentClouds { [XmlAttribute("value")] public decimal Value { get; set; } [XmlAttribute("name")] public string Name { get; set; } } public class CurrentWeather { [XmlAttribute("number")] public decimal Number { get; set; } [XmlAttribute("value")] public string Value { get; set; } } public class CurrentPrecipitation { [XmlAttribute("unit")] public string Unit { get; set; } [XmlAttribute("value")] public decimal Value { get; set; } [XmlAttribute("mode")] public string Mode { get; set; } } [XmlRoot("weatherdata")] public class Forecast { [XmlElement("sun")] public ForecastSun Sun { get; set; } [XmlArray("forecast")] [XmlArrayItem("time")] public List<ForecastItem> List { get; set; } } public class ForecastSun { [XmlAttribute("rise")] public DateTime Rise { get; set; } [XmlAttribute("set")] public DateTime Set { get; set; } } public class ForecastItem { [XmlAttribute("from")] public DateTime From { get; set; } [XmlAttribute("to")] public DateTime To { get; set; } [XmlElement("symbol")] public ForecastSymbol Symbol { get; set; } [XmlElement("windDirection")] public ForecastWindDirection WindDirection { get; set; } [XmlElement("windSpeed")] public ForecastWindSpeed WindSpeed { get; set; } [XmlElement("temperature")] public ForecastTemperature Temperature { get; set; } [XmlElement("clouds")] public ForecastClouds Clouds { get; set; } [XmlElement("precipation")] public ForecastPrecipation Precipation { get; set; } } public class ForecastSymbol { [XmlAttribute("number")] public string Number { get; set; } [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("var")] public string Var { get; set; } } public class ForecastWindDirection { [XmlAttribute("deg")] public string Deg { get; set; } [XmlAttribute("code")] public string Code { get; set; } [XmlAttribute("name")] public string Name { get; set; } } public class ForecastWindSpeed { [XmlAttribute("mps")] public decimal MetersPerSecond { get; set; } [XmlAttribute("name")] public string Name { get; set; } } public class ForecastTemperature { [XmlAttribute("value")] public decimal Value { get; set; } [XmlAttribute("min")] public decimal Min { get; set; } [XmlAttribute("max")] public decimal Max { get; set; } } public class ForecastClouds { [XmlAttribute("value")] public string Value { get; set; } [XmlAttribute("all")] public decimal all { get; set; } } public class ForecastPrecipation { [XmlAttribute("value")] public decimal Value { get; set; } [XmlAttribute("type")] public string type { get; set; } } } }
22.284722
84
0.565441
[ "MIT" ]
JornWildt/ZimmerBot
OpenWeatherMap.ZimmerBot.AddOn/OpenWeatherMapAPI.cs
6,420
C#
using NUnit.Framework; namespace Samples.Specifications { public class Summator { public int Sum(int a, int b) { return a + b; } } [TestFixture] public class Summator_Should { [Test] public void DoSomething_WhenSomething() { } } }
14.347826
47
0.521212
[ "MIT" ]
BlokhinaElizaveta/ShporaTesting
Samples/Specifications/Summator.cs
330
C#
using BookingSeatPlan.Properties; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Drawing.Printing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace BookingSeatPlan { public partial class SeatPlan : Form { public bool Change { get; set; } List<Course> courses; List<Booked> bookings; string courseName; int[] coursesIndex; static string[] textToPrintHeder, textToPrintDate, textToPrintCost, seatToPrint; public SeatPlan(List<Course> courses, string courseName) { InitializeComponent(); // init data Change = false; bookings = new List<Booked>(); this.courses = courses; this.courseName = courseName; // start seting ChoiseCourses(); InitView(); } // build view private void InitView() { lblCourseName.Text = courseName; int counter = 0; int index; // loop for courses with same name for (int nr = 0; nr < coursesIndex.Length; nr++) { index = coursesIndex[nr]; // loop of seat for (int seat = 0; seat < 12; seat++) { TextBox box = new TextBox(); box.Location = new Point(seat * 22, nr * 25); box.TextAlign = HorizontalAlignment.Center; box.Size = new Size(20, 20); box.Tag = counter; box.Click += Box_Click; BookedBox(box, (courses[index].Seat[seat] == 'B'), seat); pnlView.Controls.Add(box); counter++; } // add date and cost label Label date = new Label(); date.Location = new Point(265, nr * 25); date.Text = courses[index].Date; date.TextAlign = ContentAlignment.MiddleCenter; pnlView.Controls.Add(date); Label cost = new Label(); cost.Location = new Point(335, nr * 25); cost.TextAlign = ContentAlignment.MiddleCenter; cost.Text = courses[index].Cost; pnlView.Controls.Add(cost); } } // create array with indexes of courses private void ChoiseCourses() { int counter = 0; // count number of matched courses foreach (Course course in courses) { if (course.Name == courseName) { counter++; } } coursesIndex = new int[counter]; // store indexes counter = 0; foreach (Course course in courses) { if (course.Name == courseName) { coursesIndex[counter++] = courses.IndexOf(course); } } SortCourses(); } // when click on seat... private void Box_Click(object sender, EventArgs e) { //Debug.WriteLine((sender as TextBox).Tag.ToString()); TextBox box = sender as TextBox; int nr = int.Parse(box.Tag.ToString()); int row = nr / 12; int seat = nr % 12; // Change = true; Booked booked = new Booked(); booked.IndexCourse = coursesIndex[row]; booked.SeatNumber = seat; if (box.Text == "B") { // change view BookedBox(box, false, seat); // change model char[] seats = courses[coursesIndex[row]].Seat.ToCharArray(); seats[seat] = 'F'; courses[coursesIndex[row]].Seat = new string(seats); booked.Occupied = false; } else { // change view BookedBox(box, true, seat); // change model char[] seats = courses[coursesIndex[row]].Seat.ToCharArray(); seats[seat] = 'B'; courses[coursesIndex[row]].Seat = new string(seats); booked.Occupied = true; } //Debug.WriteLine(courses[coursesIndex[row]].Seat); //Debug.WriteLine(booked); // add to list of booked place if (!bookings.Contains(booked) && booked.Occupied) { bookings.Add(booked); Debug.WriteLine("bookeds size = " + bookings.Count.ToString()); } } // change view of seat private void BookedBox(TextBox box, bool booked, int seat) { if (booked) { box.Text = "B"; box.BackColor = Color.LightGreen; } else { box.Text = (seat + 1).ToString(); box.BackColor = Color.LightGray; } } // sort array by date of courses private void SortCourses() { Array.Sort(coursesIndex, delegate (int x, int y) { return (DateTime.Parse(courses[x].Date)).CompareTo(DateTime.Parse(courses[y].Date)); } ); } private void btnPrint_Click(object sender, EventArgs e) { string s = ""; textToPrintHeder = new string[bookings.Count]; textToPrintDate = new string[bookings.Count]; textToPrintCost = new string[bookings.Count]; seatToPrint = new string[bookings.Count]; int index = 0; foreach (Booked booked in bookings) { textToPrintHeder[index] = "BOOKING NUMBER:\t" + (index + 1).ToString() + "\t"; textToPrintHeder[index] += courses[booked.IndexCourse].Name; textToPrintDate[index] = courses[booked.IndexCourse].Date; textToPrintCost[index] = courses[booked.IndexCourse].Cost; seatToPrint[index] = courses[booked.IndexCourse].Seat; index++; } // print to printer PrintDialog printDlg = new PrintDialog(); PrintDocument printDoc = new PrintDocument(); printDoc.DocumentName = "Print Holidays"; printDlg.Document = printDoc; printDlg.AllowSelection = true; printDlg.AllowSomePages = true; //Call ShowDialog if (printDlg.ShowDialog() == DialogResult.OK) { printDoc.PrintPage += new PrintPageEventHandler(pd_PrintPage); printDoc.Print(); } } private static void pd_PrintPage(object sender, PrintPageEventArgs ev) { Font font = new Font("Consolas", 10); Font fontBold = new Font("Consolas", 10, FontStyle.Bold); Font fontHeder = new Font("Consolas", 15, FontStyle.Bold); string line = "-------------------------------------------------------------------------------------"; Image chair = Resources.chair; Image user = Resources.user; //ev.Graphics.DrawPie(new Pen(Brushes.Red, 7), new RectangleF(new PointF(20, 10), new Size(100, 80)), 30, 320); //ev.Graphics.DrawEllipse(new Pen(Brushes.Blue, 2), new RectangleF(new PointF(80, 25), new Size(10, 10))); for (int i = 0; i < textToPrintHeder.Length; i++) { ev.Graphics.DrawString(textToPrintHeder[i], fontHeder, Brushes.Black, ev.MarginBounds.Left + 10, i * 100); ev.Graphics.DrawString("Date:", fontBold, Brushes.Black, ev.MarginBounds.Left , i * 100 + 35); ev.Graphics.DrawString(textToPrintDate[i], font, Brushes.Black, ev.MarginBounds.Left + 60, i * 100 + 35); ev.Graphics.DrawString("Cost:", fontBold, Brushes.Black, ev.MarginBounds.Left, i * 100 + 60); ev.Graphics.DrawString(textToPrintCost[i], font, Brushes.Black, ev.MarginBounds.Left + 60, i * 100 + 60); ev.Graphics.DrawString(line, font, Brushes.Black, ev.MarginBounds.Left, i * 100 + 80); char[] seat = seatToPrint[i].ToCharArray(); for (int j = 0; j < 12; j++) ev.Graphics.DrawImage(((seat[j] == 'B') ? user: chair), 250 + j * 47, i * 100 + 25); } //ev.Graphics.DrawString(textToPrint, font, Brushes.Black, ev.MarginBounds.Left, 0, new StringFormat()); //ev.Graphics.DrawString(textToPrintHeder, fontBold, Brushes.Black, ev.MarginBounds.Left, 0, new StringFormat()); //ev.Graphics.DrawString(textToPrintTitle, fontHeder, Brushes.Black, ev.MarginBounds.Left, 0, new StringFormat()); } } }
37.628099
126
0.511311
[ "MIT" ]
BogdanPasterak/BookingSeatPlan
BookingSeatPlan/SeatPlan.cs
9,108
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using System.Diagnostics; namespace IdentityDeveloperTemplates.AzureADB2C.Authz.WebApp.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public class ErrorModel : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); private readonly ILogger<ErrorModel> _logger; public ErrorModel(ILogger<ErrorModel> logger) { _logger = logger; } public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
26.928571
88
0.676393
[ "MIT" ]
Daniel-Krzyczkowski/IdentityDeveloperTemplates
src/app-templates/IdentityDeveloperTemplates.AzureADB2C.Authz.WebApp/Pages/Error.cshtml.cs
754
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace IdxSistemas.Models { [Table("RELATORIOS")] public class Relatorios : BaseModel { public string Codigo { get; set; } public string Nome { get; set; } public string Descricao { get; set; } public string Modulo { get; set; } public string Link { get; set; } public string Executar { get; set; } } }
20.708333
51
0.637827
[ "Unlicense" ]
IDX-Sistemas/S4-Varejo-Backend
Models/Models/Relatorios.cs
499
C#
using System; using System.IO; using GitVersion; using GitVersionCore.Tests.Helpers; using LibGit2Sharp; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using NUnit.Framework; namespace GitVersionCore.Tests { [TestFixture] public class GitVersionTaskDirectoryTests : TestBase { private string gitDirectory; private string workDirectory; [SetUp] public void SetUp() { workDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); gitDirectory = Repository.Init(workDirectory).TrimEnd(Path.DirectorySeparatorChar); Assert.NotNull(gitDirectory); } [TearDown] public void Cleanup() { Directory.Delete(workDirectory, true); } [Test] public void FindsGitDirectory() { try { var options = Options.Create(new Arguments { TargetPath = workDirectory, NoFetch = true }); var sp = ConfigureServices(services => { services.AddSingleton(options); }); var gitVersionCalculator = sp.GetService<IGitVersionTool>(); gitVersionCalculator.CalculateVersionVariables(); } catch (Exception ex) { // `RepositoryNotFoundException` means that it couldn't find the .git directory, // any other exception means that the .git was found but there was some other issue that this test doesn't care about. Assert.IsNotAssignableFrom<RepositoryNotFoundException>(ex); } } [Test] public void FindsGitDirectoryInParent() { var childDir = Path.Combine(workDirectory, "child"); Directory.CreateDirectory(childDir); try { var options = Options.Create(new Arguments { TargetPath = childDir, NoFetch = true }); var sp = ConfigureServices(services => { services.AddSingleton(options); }); var gitVersionCalculator = sp.GetService<IGitVersionTool>(); gitVersionCalculator.CalculateVersionVariables(); } catch (Exception ex) { // TODO I think this test is wrong.. It throws a different exception // `RepositoryNotFoundException` means that it couldn't find the .git directory, // any other exception means that the .git was found but there was some other issue that this test doesn't care about. Assert.IsNotAssignableFrom<RepositoryNotFoundException>(ex); } } } }
32.252874
134
0.583749
[ "MIT" ]
rainersigwald/GitVersion
src/GitVersionCore.Tests/Core/GitVersionToolDirectoryTests.cs
2,806
C#
using System.Collections.Generic; using UnityEngine; namespace Unity.MLAgents.Sensors { internal class SensorShapeValidator { List<ObservationSpec> m_SensorShapes; /// <summary> /// Check that the List Sensors are the same shape as the previous ones. /// If this is the first List of Sensors being checked, its Sensor sizes will be saved. /// </summary> public void ValidateSensors(List<ISensor> sensors) { if (m_SensorShapes == null) { m_SensorShapes = new List<ObservationSpec>(sensors.Count); // First agent, save the sensor sizes foreach (var sensor in sensors) { m_SensorShapes.Add(sensor.GetObservationSpec()); } } else { // Check for compatibility with the other Agents' Sensors if (m_SensorShapes.Count != sensors.Count) { Debug.AssertFormat( m_SensorShapes.Count == sensors.Count, "Number of Sensors must match. {0} != {1}", m_SensorShapes.Count, sensors.Count ); } for (var i = 0; i < Mathf.Min(m_SensorShapes.Count, sensors.Count); i++) { var cachedSpec = m_SensorShapes[i]; var sensorSpec = sensors[i].GetObservationSpec(); if (cachedSpec.Shape != sensorSpec.Shape) { Debug.AssertFormat( cachedSpec.Shape == sensorSpec.Shape, "Sensor shapes must match. {0} != {1}", cachedSpec.Shape, sensorSpec.Shape ); } } } } } }
35.482143
95
0.460996
[ "Apache-2.0" ]
315930399/ml-agents
com.unity.ml-agents/Runtime/Sensors/SensorShapeValidator.cs
1,987
C#
using System.IO; namespace AzureFunctions.Extensions.Swashbuckle { public interface ISwashBuckleClient { Stream GetSwaggerDocument(string host, string documentName = "v1"); Stream GetSwaggerUi(string swaggerUrl); string RoutePrefix { get; } } }
20.357143
75
0.694737
[ "MIT" ]
LockTar/azure-functions-extensions-swashbuckle
src/AzureFunctions.Extensions.Swashbuckle/AzureFunctions.Extensions.Swashbuckle/ISwashBuckleClient.cs
287
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Linq; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace PipeClient { class Program { static void Main(string[] Args) { Application.Run(new MainSimpleClient()); } } }
19.125
52
0.71024
[ "MIT" ]
pingkunga/VB6_DOTNET_NAMEPIPE_Example
NetPipe/PipeClient/Program.cs
459
C#
using Easter.Models.Dyes.Contracts; using System; using System.Collections.Generic; using System.Text; namespace Easter.Models.Dyes { public class Dye : IDye { private int power; public Dye(int power) { this.Power = power; } public int Power { get { return this.power; } private set { if (value<0) { value = 0; } this.power = value; } } public bool IsFinished() { if (this.power == 0) { return true; } return false; } public void Use() { this.power -= 10; if (this.power < 0) { this.power = 0; } } } }
17.679245
36
0.366062
[ "MIT" ]
DaniHristov/SoftUni
C#-OOP/Easter-Exam/Easter/Models/Dyes/Dye.cs
939
C#
using Abp.Application.Services.Dto; using Abp.AutoMapper; using BrandChallenge.MultiTenancy; namespace BrandChallenge.Sessions.Dto { [AutoMapFrom(typeof(Tenant))] public class TenantLoginInfoDto : EntityDto { public string TenancyName { get; set; } public string Name { get; set; } } }
21.4
47
0.700935
[ "MIT" ]
afaqch1/BrandChallengeBoilerPlate
aspnet-core/src/BrandChallenge.Application/Sessions/Dto/TenantLoginInfoDto.cs
323
C#
/*! \cond PRIVATE */ using UnityEngine; using Random = UnityEngine.Random; // ReSharper disable once CheckNamespace namespace DarkTonic.MasterAudio { /// <summary> /// This class is only activated when you need code to execute in an Update method, such as "follow" code. /// </summary> // ReSharper disable once CheckNamespace [AudioScriptOrder(-15)] public class SoundGroupVariationUpdater : MonoBehaviour { private const float TimeEarlyToScheduleNextClip = .1f; private const float FakeNegativeFloatValue = -10f; private Transform _objectToFollow; private GameObject _objectToFollowGo; private bool _isFollowing; private SoundGroupVariation _variation; private float _priorityLastUpdated = FakeNegativeFloatValue; private bool _useClipAgePriority; private WaitForSoundFinishMode _waitMode = WaitForSoundFinishMode.None; private AudioSource _varAudio; private MasterAudioGroup _parentGrp; private Transform _trans; private int _frameNum = -1; private bool _inited = false; // fade in out vars private float _fadeOutStartTime = -5; private bool _fadeInOutWillFadeOut; private bool _hasFadeInOutSetMaxVolume; private float _fadeInOutInFactor; private float _fadeInOutOutFactor; // fade out early vars private int _fadeOutEarlyTotalFrames; private float _fadeOutEarlyFrameVolChange; private int _fadeOutEarlyFrameNumber; private float _fadeOutEarlyOrigVol; // gradual fade vars private float _fadeToTargetFrameVolChange; private int _fadeToTargetFrameNumber; private float _fadeToTargetOrigVol; private int _fadeToTargetTotalFrames; private float _fadeToTargetVolume; private bool _fadeOutStarted; private float _lastFrameClipTime = -1f; private bool _isPlayingBackward; private int _pitchGlideToTargetTotalFrames; private float _pitchGlideToTargetFramePitchChange; private int _pitchGlideToTargetFrameNumber; private float _glideToTargetPitch; private float _glideToTargetOrigPitch; private System.Action _glideToPitchCompletionCallback; private bool _hasStartedNextInChain; private bool _isWaitingForQueuedOcclusionRay; private int _framesPlayed = 0; private float? _clipStartPosition; private float? _clipEndPosition; private double? _clipSchedEndTime; private bool _hasScheduledNextClip; private bool _hasScheduledEndLinkedGroups; private int _lastFrameClipPosition = -1; private int _timesLooped = 0; private bool _isPaused; private double _pauseTime; private static int _maCachedFromFrame = -1; private static MasterAudio _maThisFrame; private static Transform _listenerThisFrame; private enum WaitForSoundFinishMode { None, Play, WaitForEnd, StopOrRepeat } #region Public methods public void GlidePitch(float targetPitch, float glideTime, System.Action completionCallback = null) { GrpVariation.curPitchMode = SoundGroupVariation.PitchMode.Gliding; var pitchDiff = targetPitch - VarAudio.pitch; _pitchGlideToTargetTotalFrames = (int)(glideTime / AudioUtil.FrameTime); _pitchGlideToTargetFramePitchChange = pitchDiff / _pitchGlideToTargetTotalFrames; _pitchGlideToTargetFrameNumber = 0; _glideToTargetPitch = targetPitch; _glideToTargetOrigPitch = VarAudio.pitch; _glideToPitchCompletionCallback = completionCallback; } public void FadeOverTimeToVolume(float targetVolume, float fadeTime) { GrpVariation.curFadeMode = SoundGroupVariation.FadeMode.GradualFade; var volDiff = targetVolume - VarAudio.volume; var currentClipTime = VarAudio.time; var currentClipLength = ClipEndPosition; if (!VarAudio.loop && VarAudio.clip != null && fadeTime + currentClipTime > currentClipLength) { // if too long, fade out faster fadeTime = currentClipLength - currentClipTime; } _fadeToTargetTotalFrames = (int)(fadeTime / AudioUtil.FrameTime); _fadeToTargetFrameVolChange = volDiff / _fadeToTargetTotalFrames; _fadeToTargetFrameNumber = 0; _fadeToTargetOrigVol = VarAudio.volume; _fadeToTargetVolume = targetVolume; } public void FadeOutEarly(float fadeTime) { GrpVariation.curFadeMode = SoundGroupVariation.FadeMode.FadeOutEarly; // cancel the FadeInOut loop, if it's going. if (!VarAudio.loop && VarAudio.clip != null && VarAudio.time + fadeTime > ClipEndPosition) { // if too long, fade out faster fadeTime = ClipEndPosition - VarAudio.time; } var frameTime = AudioUtil.FrameTime; if (frameTime == 0) { frameTime = AudioUtil.FixedDeltaTime; } _fadeOutEarlyTotalFrames = (int)(fadeTime / frameTime); _fadeOutEarlyFrameVolChange = -VarAudio.volume / _fadeOutEarlyTotalFrames; _fadeOutEarlyFrameNumber = 0; _fadeOutEarlyOrigVol = VarAudio.volume; } // Called by Master Audio, do not call. public void Initialize() { if (_inited) { return; } _lastFrameClipPosition = -1; _timesLooped = 0; _isPaused = false; _pauseTime = -1; _clipStartPosition = null; _clipEndPosition = null; _clipSchedEndTime = null; _hasScheduledNextClip = false; _hasScheduledEndLinkedGroups = false; _inited = true; } public void FadeInOut() { GrpVariation.curFadeMode = SoundGroupVariation.FadeMode.FadeInOut; // wait to set this so it stops the previous one if it's still going. _fadeOutStartTime = ClipEndPosition - GrpVariation.fadeOutTime; if (GrpVariation.fadeInTime > 0f) { VarAudio.volume = 0f; // start at zero volume _fadeInOutInFactor = GrpVariation.fadeMaxVolume / GrpVariation.fadeInTime; } else { _fadeInOutInFactor = 0f; } _fadeInOutWillFadeOut = GrpVariation.fadeOutTime > 0f && !VarAudio.loop; if (_fadeInOutWillFadeOut) { _fadeInOutOutFactor = GrpVariation.fadeMaxVolume / (ClipEndPosition - _fadeOutStartTime); } else { _fadeInOutOutFactor = 0f; } } public void FollowObject(bool follow, Transform objToFollow, bool clipAgePriority) { _isFollowing = follow; if (objToFollow != null) { _objectToFollow = objToFollow; _objectToFollowGo = objToFollow.gameObject; } _useClipAgePriority = clipAgePriority; UpdateCachedObjects(); UpdateAudioLocationAndPriority(false); // in case we're not following, it should get one update. } public void WaitForSoundFinish() { if (MasterAudio.IsWarming) { PlaySoundAndWait(); return; } _waitMode = WaitForSoundFinishMode.Play; } public void StopPitchGliding() { GrpVariation.curPitchMode = SoundGroupVariation.PitchMode.None; if (_glideToPitchCompletionCallback != null) { _glideToPitchCompletionCallback(); _glideToPitchCompletionCallback = null; } DisableIfFinished(); } public void StopFading() { GrpVariation.curFadeMode = SoundGroupVariation.FadeMode.None; DisableIfFinished(); } public void StopWaitingForFinish() { _waitMode = WaitForSoundFinishMode.None; GrpVariation.curDetectEndMode = SoundGroupVariation.DetectEndMode.None; DisableIfFinished(); } public void StopFollowing() { _isFollowing = false; _useClipAgePriority = false; _objectToFollow = null; _objectToFollowGo = null; DisableIfFinished(); } #endregion #region Helper methods private void DisableIfFinished() { if (_isFollowing || GrpVariation.curDetectEndMode == SoundGroupVariation.DetectEndMode.DetectEnd || GrpVariation.curFadeMode != SoundGroupVariation.FadeMode.None) { return; } if (GrpVariation.curPitchMode != SoundGroupVariation.PitchMode.None) { return; } enabled = false; } private void UpdateAudioLocationAndPriority(bool rePrioritize) { // update location, only if following. if (_isFollowing && _objectToFollow != null) { Trans.position = _objectToFollow.position; } // re-set priority, still used by non-following (audio clip age priority) if (!_maThisFrame.prioritizeOnDistance || !rePrioritize || ParentGroup.alwaysHighestPriority) { return; } if (Time.realtimeSinceStartup - _priorityLastUpdated <= MasterAudio.ReprioritizeTime) { return; } AudioPrioritizer.Set3DPriority(GrpVariation, _useClipAgePriority); _priorityLastUpdated = AudioUtil.Time; } private void ResetToNonOcclusionSetting() { var lp = GrpVariation.LowPassFilter; if (lp != null) { lp.cutoffFrequency = AudioUtil.DefaultMinOcclusionCutoffFrequency; } } private void UpdateOcclusion() { var hasOcclusionOn = GrpVariation.UsesOcclusion; if (!hasOcclusionOn) { MasterAudio.StopTrackingOcclusionForSource(GrpVariation.GameObj); ResetToNonOcclusionSetting(); return; } if (_listenerThisFrame == null) { // cannot occlude without something to raycast at. return; } if (IsOcclusionMeasuringPaused) { return; // wait until processed } MasterAudio.AddToQueuedOcclusionRays(this); _isWaitingForQueuedOcclusionRay = true; } private void DoneWithOcclusion() { _isWaitingForQueuedOcclusionRay = false; MasterAudio.RemoveFromOcclusionFrequencyTransitioning(GrpVariation); } /// <summary> /// This method is called in a batch from ListenerFollower /// </summary> /// <returns></returns> public bool RayCastForOcclusion() { DoneWithOcclusion(); var raycastOrigin = Trans.position; var offset = RayCastOriginOffset; if (offset > 0) { raycastOrigin = Vector3.MoveTowards(raycastOrigin, _listenerThisFrame.position, offset); } var direction = _listenerThisFrame.position - raycastOrigin; var distanceToListener = direction.magnitude; if (distanceToListener > VarAudio.maxDistance) { // out of hearing range, no reason to calculate occlusion. MasterAudio.AddToOcclusionOutOfRangeSources(GrpVariation.GameObj); ResetToNonOcclusionSetting(); return false; } MasterAudio.AddToOcclusionInRangeSources(GrpVariation.GameObj); var is2DRaycast = _maThisFrame.occlusionRaycastMode == MasterAudio.RaycastMode.Physics2D; if (GrpVariation.LowPassFilter == null) { // in case Occlusion got turned on during runtime. var newFilter = GrpVariation.gameObject.AddComponent<AudioLowPassFilter>(); GrpVariation.LowPassFilter = newFilter; } #if UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5_0 || UNITY_5_1 // no option for this if (is2DRaycast) { } #else var oldQueriesStart = Physics2D.queriesStartInColliders; if (is2DRaycast) { Physics2D.queriesStartInColliders = _maThisFrame.occlusionIncludeStartRaycast2DCollider; } var oldRaycastsHitTriggers = true; // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression if (is2DRaycast) { oldRaycastsHitTriggers = Physics2D.queriesHitTriggers; Physics2D.queriesHitTriggers = _maThisFrame.occlusionRaycastsHitTriggers; } else { oldRaycastsHitTriggers = Physics.queriesHitTriggers; Physics.queriesHitTriggers = _maThisFrame.occlusionRaycastsHitTriggers; } #endif var hitPoint = Vector3.zero; float? hitDistance = null; var isHit = false; if (_maThisFrame.occlusionUseLayerMask) { switch (_maThisFrame.occlusionRaycastMode) { case MasterAudio.RaycastMode.Physics3D: RaycastHit hitObject; if (Physics.Raycast(raycastOrigin, direction, out hitObject, distanceToListener, _maThisFrame.occlusionLayerMask.value)) { isHit = true; hitPoint = hitObject.point; hitDistance = hitObject.distance; } break; case MasterAudio.RaycastMode.Physics2D: var castHit2D = Physics2D.Raycast(raycastOrigin, direction, distanceToListener, _maThisFrame.occlusionLayerMask.value); if (castHit2D.transform != null) { isHit = true; hitPoint = castHit2D.point; hitDistance = castHit2D.distance; } break; } } else { switch (_maThisFrame.occlusionRaycastMode) { case MasterAudio.RaycastMode.Physics3D: RaycastHit hitObject; if (Physics.Raycast(raycastOrigin, direction, out hitObject, distanceToListener)) { isHit = true; hitPoint = hitObject.point; hitDistance = hitObject.distance; } break; case MasterAudio.RaycastMode.Physics2D: var castHit2D = Physics2D.Raycast(raycastOrigin, direction, distanceToListener); if (castHit2D.transform != null) { isHit = true; hitPoint = castHit2D.point; hitDistance = castHit2D.distance; } break; } } #if UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5_0 || UNITY_5_1 #else if (is2DRaycast) { Physics2D.queriesStartInColliders = oldQueriesStart; Physics2D.queriesHitTriggers = oldRaycastsHitTriggers; } else { Physics.queriesHitTriggers = oldRaycastsHitTriggers; } #endif if (_maThisFrame.occlusionShowRaycasts) { var endPoint = isHit ? hitPoint : _listenerThisFrame.position; var lineColor = isHit ? Color.red : Color.green; Debug.DrawLine(raycastOrigin, endPoint, lineColor, .1f); } if (!isHit) { // ReSharper disable once PossibleNullReferenceException MasterAudio.RemoveFromBlockedOcclusionSources(GrpVariation.GameObj); ResetToNonOcclusionSetting(); return true; } MasterAudio.AddToBlockedOcclusionSources(GrpVariation.GameObj); var ratioToEdgeOfSound = hitDistance.Value / VarAudio.maxDistance; var filterFrequency = AudioUtil.GetOcclusionCutoffFrequencyByDistanceRatio(ratioToEdgeOfSound, this); var fadeTime = _maThisFrame.occlusionFreqChangeSeconds; if (fadeTime <= MasterAudio.InnerLoopCheckInterval) { // fast, just do it instantly. // ReSharper disable once PossibleNullReferenceException GrpVariation.LowPassFilter.cutoffFrequency = filterFrequency; return true; } MasterAudio.GradualOcclusionFreqChange(GrpVariation, fadeTime, filterFrequency); return true; } private void PlaySoundAndWait() { if (VarAudio.clip == null) { // in case the warming sound is an "internet file" return; } double startTime = AudioSettings.dspTime; if (GrpVariation.PlaySoundParm.TimeToSchedulePlay.HasValue) { startTime = GrpVariation.PlaySoundParm.TimeToSchedulePlay.Value; } var delayTime = 0f; if (GrpVariation.useIntroSilence && GrpVariation.introSilenceMax > 0f) { var rndSilence = Random.Range(GrpVariation.introSilenceMin, GrpVariation.introSilenceMax); delayTime += rndSilence; } delayTime += GrpVariation.PlaySoundParm.DelaySoundTime; if (delayTime > 0f) { startTime += delayTime; } VarAudio.PlayScheduled(startTime); AudioUtil.ClipPlayed(VarAudio.clip, GrpVariation.GameObj); if (GrpVariation.useRandomStartTime) { VarAudio.time = ClipStartPosition; if (!VarAudio.loop) { // don't stop it if it's going to loop. var playableLength = AudioUtil.AdjustAudioClipDurationForPitch(ClipEndPosition - ClipStartPosition, VarAudio); _clipSchedEndTime = startTime + playableLength; VarAudio.SetScheduledEndTime(_clipSchedEndTime.Value); } } GrpVariation.LastTimePlayed = AudioUtil.Time; DuckIfNotSilent(); _isPlayingBackward = GrpVariation.OriginalPitch < 0; _lastFrameClipTime = _isPlayingBackward ? ClipEndPosition + 1 : -1f; _waitMode = WaitForSoundFinishMode.WaitForEnd; } private void DuckIfNotSilent() { bool isSilent = false; if (GrpVariation.PlaySoundParm.VolumePercentage <= 0) { isSilent = true; } else if (GrpVariation.ParentGroup.groupMasterVolume <= 0) { isSilent = true; } else if (GrpVariation.VarAudio.mute) { // other group soloed isSilent = true; } else if (MasterAudio.MixerMuted) { isSilent = true; } else if (GrpVariation.ParentGroup.isMuted) { isSilent = true; } else { var bus = GrpVariation.ParentGroup.BusForGroup; if (bus != null && bus.isMuted) { isSilent = true; } } // sound play worked! Duck music if a ducking sound and sound is not silent. if (!isSilent) { MasterAudio.DuckSoundGroup(ParentGroup.GameObjectName, VarAudio); } } private void StopOrChain() { //Debug.Log("stop or chain: " + name); var playSnd = GrpVariation.PlaySoundParm; var wasPlaying = playSnd.IsPlaying; var usingChainLoop = wasPlaying && playSnd.IsChainLoop; if (!VarAudio.loop || usingChainLoop) { GrpVariation.Stop(); } if (!usingChainLoop) { return; } StopWaitingForFinish(); MaybeChain(); } public void Pause() { _isPaused = true; _pauseTime = AudioSettings.dspTime; } public void Unpause() { _isPaused = false; if (_clipSchedEndTime.HasValue) { var timePaused = AudioSettings.dspTime - _pauseTime; _clipSchedEndTime += timePaused; VarAudio.SetScheduledEndTime(_clipSchedEndTime.Value); } } public void MaybeChain() { if (_hasStartedNextInChain) { return; } _hasStartedNextInChain = true; var playSnd = GrpVariation.PlaySoundParm; var clipsRemaining = MasterAudio.RemainingClipsInGroup(ParentGroup.GameObjectName); var totalClips = MasterAudio.VoicesForGroup(ParentGroup.GameObjectName); if (clipsRemaining == totalClips) { ParentGroup.FireLastVariationFinishedPlay(); } // check if loop count is over. if (ParentGroup.chainLoopMode == MasterAudioGroup.ChainedLoopLoopMode.NumberOfLoops && ParentGroup.ChainLoopCount >= ParentGroup.chainLoopNumLoops) { // done looping return; } var rndDelay = playSnd.DelaySoundTime; if (ParentGroup.chainLoopDelayMin > 0f || ParentGroup.chainLoopDelayMax > 0f) { rndDelay = Random.Range(ParentGroup.chainLoopDelayMin, ParentGroup.chainLoopDelayMax); } // cannot use "AndForget" methods! Chain loop needs to check the status. if (playSnd.AttachToSource || playSnd.SourceTrans != null) { if (playSnd.AttachToSource) { MasterAudio.PlaySound3DFollowTransform(playSnd.SoundType, playSnd.SourceTrans, playSnd.VolumePercentage, playSnd.Pitch, rndDelay, null, _clipSchedEndTime, true); } else { MasterAudio.PlaySound3DAtTransform(playSnd.SoundType, playSnd.SourceTrans, playSnd.VolumePercentage, playSnd.Pitch, rndDelay, null, _clipSchedEndTime, true); } } else { MasterAudio.PlaySound(playSnd.SoundType, playSnd.VolumePercentage, playSnd.Pitch, rndDelay, null, _clipSchedEndTime, true); } } private void UpdatePitch() { switch (GrpVariation.curPitchMode) { case SoundGroupVariation.PitchMode.None: return; case SoundGroupVariation.PitchMode.Gliding: if (!VarAudio.isPlaying) { break; } _pitchGlideToTargetFrameNumber++; if (_pitchGlideToTargetFrameNumber >= _pitchGlideToTargetTotalFrames) { VarAudio.pitch = _glideToTargetPitch; StopPitchGliding(); } else { VarAudio.pitch = (_pitchGlideToTargetFrameNumber * _pitchGlideToTargetFramePitchChange) + _glideToTargetOrigPitch; } break; } } private void PerformFading() { switch (GrpVariation.curFadeMode) { case SoundGroupVariation.FadeMode.None: break; case SoundGroupVariation.FadeMode.FadeInOut: if (!VarAudio.isPlaying) { break; } var clipTime = VarAudio.time; if (GrpVariation.fadeInTime > 0f && clipTime < GrpVariation.fadeInTime) { // fade in! VarAudio.volume = clipTime * _fadeInOutInFactor; } else if (clipTime >= GrpVariation.fadeInTime && !_hasFadeInOutSetMaxVolume) { VarAudio.volume = GrpVariation.fadeMaxVolume; _hasFadeInOutSetMaxVolume = true; if (!_fadeInOutWillFadeOut) { StopFading(); } } else if (_fadeInOutWillFadeOut && clipTime >= _fadeOutStartTime) { // fade out! if (GrpVariation.PlaySoundParm.IsChainLoop && !_fadeOutStarted) { MaybeChain(); _fadeOutStarted = true; } VarAudio.volume = (ClipEndPosition - clipTime) * _fadeInOutOutFactor; } break; case SoundGroupVariation.FadeMode.FadeOutEarly: if (!VarAudio.isPlaying) { break; } _fadeOutEarlyFrameNumber++; VarAudio.volume = (_fadeOutEarlyFrameNumber * _fadeOutEarlyFrameVolChange) + _fadeOutEarlyOrigVol; if (_fadeOutEarlyFrameNumber >= _fadeOutEarlyTotalFrames) { GrpVariation.curFadeMode = SoundGroupVariation.FadeMode.None; GrpVariation.Stop(); } break; case SoundGroupVariation.FadeMode.GradualFade: if (!VarAudio.isPlaying) { break; } _fadeToTargetFrameNumber++; if (_fadeToTargetFrameNumber >= _fadeToTargetTotalFrames) { VarAudio.volume = _fadeToTargetVolume; StopFading(); } else { VarAudio.volume = (_fadeToTargetFrameNumber * _fadeToTargetFrameVolChange) + _fadeToTargetOrigVol; } break; } } #endregion #region MonoBehavior events // ReSharper disable once UnusedMember.Local private void OnEnable() { _inited = false; // values to be reset every time a sound plays. _fadeInOutWillFadeOut = false; _hasFadeInOutSetMaxVolume = false; _fadeOutStarted = false; _hasStartedNextInChain = false; _framesPlayed = 0; _clipStartPosition = null; _clipEndPosition = null; DoneWithOcclusion(); MasterAudio.RegisterUpdaterForUpdates(this); } // ReSharper disable once UnusedMember.Local private void OnDisable() { if (MasterAudio.AppIsShuttingDown) { return; // do nothing } _framesPlayed = 0; DoneWithOcclusion(); MasterAudio.UnregisterUpdaterForUpdates(this); } public void UpdateCachedObjects() { _frameNum = AudioUtil.FrameCount; // ReSharper disable once InvertIf if (_maCachedFromFrame >= _frameNum) { return; // same frame. Use cached objects } // new frame. Update cached objects and frame counters; _maCachedFromFrame = _frameNum; _maThisFrame = MasterAudio.Instance; _listenerThisFrame = MasterAudio.ListenerTrans; } /// <summary> /// This method will be called by MasterAudio.cs either during LateUpdate (default) or FixedUpdate, however you've configured it in Advanced Settings. /// </summary> public void ManualUpdate() { UpdateCachedObjects(); _framesPlayed++; if (VarAudio.loop) { if (VarAudio.timeSamples < _lastFrameClipPosition) { _timesLooped++; if (VarAudio.loop && GrpVariation.useCustomLooping && _timesLooped >= GrpVariation.MaxLoops) { GrpVariation.Stop(); } else { GrpVariation.SoundLoopStarted(_timesLooped); } } _lastFrameClipPosition = VarAudio.timeSamples; } if (_isFollowing) { // check for despawned caller and act if so. if (ParentGroup.targetDespawnedBehavior != MasterAudioGroup.TargetDespawnedBehavior.None) { if (_objectToFollowGo == null || !DTMonoHelper.IsActive(_objectToFollowGo)) { switch (ParentGroup.targetDespawnedBehavior) { case MasterAudioGroup.TargetDespawnedBehavior.Stop: GrpVariation.Stop(); break; case MasterAudioGroup.TargetDespawnedBehavior.FadeOut: GrpVariation.FadeOutNow(ParentGroup.despawnFadeTime); break; } StopFollowing(); } } } // fade in out / out early etc. PerformFading(); // priority UpdateAudioLocationAndPriority(true); // occlusion UpdateOcclusion(); // pitch UpdatePitch(); switch (_waitMode) { case WaitForSoundFinishMode.None: break; case WaitForSoundFinishMode.Play: PlaySoundAndWait(); break; case WaitForSoundFinishMode.WaitForEnd: if (_isPaused) { break; } if (_clipSchedEndTime.HasValue) { if (AudioSettings.dspTime + TimeEarlyToScheduleNextClip >= _clipSchedEndTime.Value) { if (GrpVariation.PlaySoundParm.IsChainLoop && !_hasScheduledNextClip) { MaybeChain(); _hasScheduledNextClip = true; } if (HasEndLinkedGroups && !_hasScheduledEndLinkedGroups) { GrpVariation.PlayEndLinkedGroups(_clipSchedEndTime.Value); _hasScheduledEndLinkedGroups = true; } } } var willChangeModes = false; if (_isPlayingBackward) { if (VarAudio.time > _lastFrameClipTime) { willChangeModes = true; } } else { if (VarAudio.time < _lastFrameClipTime) { willChangeModes = true; } } _lastFrameClipTime = VarAudio.time; if (willChangeModes) { _waitMode = WaitForSoundFinishMode.StopOrRepeat; } break; case WaitForSoundFinishMode.StopOrRepeat: StopOrChain(); break; } } #endregion #region Properties public float ClipStartPosition { get { if (_clipStartPosition.HasValue) { return _clipStartPosition.Value; } if (GrpVariation.useRandomStartTime) { _clipStartPosition = Random.Range(GrpVariation.randomStartMinPercent, GrpVariation.randomStartMaxPercent) * 0.01f * VarAudio.clip.length; } else { _clipStartPosition = 0f; } return _clipStartPosition.Value; } } public float ClipEndPosition { get { if (_clipEndPosition.HasValue) { return _clipEndPosition.Value; } if (GrpVariation.useRandomStartTime) { _clipEndPosition = GrpVariation.randomEndPercent * 0.01f * VarAudio.clip.length; } else { _clipEndPosition = VarAudio.clip.length; } return _clipEndPosition.Value; } } public int FramesPlayed { get { return _framesPlayed; } } public MasterAudio MAThisFrame { get { return _maThisFrame; } } public float MaxOcclusionFreq { get { // ReSharper disable once InvertIf if (GrpVariation.UsesOcclusion && ParentGroup.willOcclusionOverrideFrequencies) { return ParentGroup.occlusionMaxCutoffFreq; } return _maThisFrame.occlusionMaxCutoffFreq; } } public float MinOcclusionFreq { get { // ReSharper disable once InvertIf if (GrpVariation.UsesOcclusion && ParentGroup.willOcclusionOverrideFrequencies) { return ParentGroup.occlusionMinCutoffFreq; } return _maThisFrame.occlusionMinCutoffFreq; } } private Transform Trans { get { if (_trans != null) { return _trans; } _trans = GrpVariation.Trans; return _trans; } } private AudioSource VarAudio { get { if (_varAudio != null) { return _varAudio; } _varAudio = GrpVariation.VarAudio; return _varAudio; } } private MasterAudioGroup ParentGroup { get { if (_parentGrp != null) { return _parentGrp; } _parentGrp = GrpVariation.ParentGroup; return _parentGrp; } } private SoundGroupVariation GrpVariation { get { if (_variation != null) { return _variation; } _variation = GetComponent<SoundGroupVariation>(); return _variation; } } private float RayCastOriginOffset { get { // ReSharper disable once InvertIf if (GrpVariation.UsesOcclusion && ParentGroup.willOcclusionOverrideRaycastOffset) { return ParentGroup.occlusionRayCastOffset; } return _maThisFrame.occlusionRayCastOffset; } } private bool IsOcclusionMeasuringPaused { get { return _isWaitingForQueuedOcclusionRay || MasterAudio.IsOcclusionFreqencyTransitioning(GrpVariation); } } private bool HasEndLinkedGroups { get { if (GrpVariation.ParentGroup.endLinkedGroups.Count > 0) { return true; } return false; } } #endregion } } /*! \endcond */
37.520619
162
0.538398
[ "MIT" ]
alpdogan1/GGJ19_Roof
Assets/Plugins/DarkTonic/MasterAudio/Scripts/Settings/SoundGroupVariationUpdater.cs
36,395
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text; using System.Xml; using System.Xml.Linq; using System.Runtime.Serialization.Json; using System.Net.Http; using System.Net.Http.Headers; namespace YammerOGApp { public partial class _Default : Page { public const string ClientId = "HyJWY8MJpOBV5lGMMQQRQ"; public const string RedirectUri = "http://localhost:19356/"; public const string ClientSecret = "5xFzSmZ5lTW0kim5bizpbybOqhxiGJkDkVucGXYf8"; protected async void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { string accessToken = null; try { accessToken = GetFromCache("AccessToken").ToString(); } catch { accessToken = null; } if (accessToken == null) { string code = Request.QueryString["code"]; if (code == null) { Response.Redirect( String.Format("https://www.yammer.com/dialog/oauth?client_id={0}&redirect_uri={1}", ClientId, RedirectUri), false); } else { string requestUri = String.Format( "https://www.yammer.com/oauth2/access_token.json?client_id={0}&client_secret={1}&code={2}", ClientId, ClientSecret, code); HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUri); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.SendAsync(request); XElement root = Json2Xml(await response.Content.ReadAsStringAsync()); accessToken = root.Descendants("token").First().Value; SaveInCache("AccessToken", accessToken); } } } } private static XElement Json2Xml(string json) { using (XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader( Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max)) { return XElement.Load(reader); } } public static void SaveInCache(string name, object value) { System.Web.HttpContext.Current.Session[name] = value; } public static object GetFromCache(string name) { return System.Web.HttpContext.Current.Session[name]; } public static void RemoveFromCache(string name) { System.Web.HttpContext.Current.Session.Remove(name); } protected async void createActivity_Click(object sender, EventArgs e) { string accessToken = GetFromCache("AccessToken").ToString(); string requestUri = "https://www.yammer.com/api/v1/activity.json"; HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); ActivityEnvelope envelope = new ActivityEnvelope(); envelope.Activity.Actor.Name = actorName.Text; envelope.Activity.Actor.Email = actorEmail.Text; envelope.Activity.Action = "create"; envelope.Activity.Message = activityMessage.Text; envelope.Activity.OG_Object.Title = objectTitle.Text; envelope.Activity.OG_Object.Url = objectUrl.Text; string json = envelope.GetJSON(); StringContent requestContent = new StringContent(json); request.Content = requestContent; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpResponseMessage response = await client.SendAsync(request); XElement root = Json2Xml(await response.Content.ReadAsStringAsync()); } } }
37.300813
119
0.576286
[ "MIT" ]
OfficeDev/TrainingContent-Archive
O3653/O3653-5 Deep Dive into Office 365 APIs for Yammer Services/Completed Projects/Exercise 03/YammerOGApp/YammerOGApp/Default.aspx.cs
4,590
C#
using System.IO; using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class SSRCustomData : ICameraStorageCustomData { public SSRCustomData(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
21.133333
100
0.728707
[ "MIT" ]
Eingin/CP77Tools
CP77.CR2W/Types/cp77/SSRCustomData.cs
303
C#