content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Linq.Expressions; using HotChocolate.Language; namespace HotChocolate.Data.Filters.Expressions { public class QueryableStringNotEndsWithHandler : QueryableStringOperationHandler { public QueryableStringNotEndsWithHandler() { CanBeNull = false; } protected override int Operation => DefaultOperations.NotEndsWith; public override Expression HandleOperation( QueryableFilterContext context, IFilterOperationField field, IValueNode value, object parsedValue) { Expression property = context.GetInstance(); return FilterExpressionBuilder.Not( FilterExpressionBuilder.EndsWith(property, parsedValue)); } } }
28.142857
84
0.663706
[ "MIT" ]
GraemeF/hotchocolate
src/HotChocolate/Data/src/Data/Filters/Expressions/Handlers/String/QueryableStringNotEndsWithHandler.cs
788
C#
using FluentValidation.Results; using System; using System.Collections.Generic; using System.Linq; namespace Order.Application.Exceptions { public class ValidationException : ApplicationException { public ValidationException() : base("One or more validation failures have occured.") { Errors = new Dictionary<string, string[]>(); } public ValidationException(IEnumerable<ValidationFailure> failures) : this() { Errors = failures .GroupBy(i => i.PropertyName, i => i.ErrorMessage) .ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray()); foreach (var failure in failures) Errors.Add(failure.PropertyName, new string[] { failure.ErrorMessage }); } public Dictionary<string, string[]> Errors { get; } } }
31.821429
104
0.639731
[ "MIT" ]
mehmetkaradeniz/ms
src/Services/Order/Order.Application/Exceptions/ValidationException.cs
893
C#
using System; using PdfSharp.Drawing; using PdfSharp.Drawing.Layout; namespace PdfSharp.Pdf.Signatures { internal class DefaultAppearanceHandler : ISignatureAppearanceHandler { public string Location { get; set; } public string Reason { get; set; } public string Signer { get; set; } public void DrawAppearance(XGraphics gfx, XRect rect) { var backColor = XColor.Empty; var defaultText = string.Format("Signed by: {0}\nLocation: {1}\nReason: {2}\nDate: {3}", Signer, Location, Reason, DateTime.Now); XFont font = new XFont("Verdana", 7, XFontStyle.Regular); XTextFormatter txtFormat = new XTextFormatter(gfx); var currentPosition = new XPoint(0, 0); txtFormat.DrawString(defaultText, font, new XSolidBrush(XColor.FromKnownColor(XKnownColor.Black)), new XRect(currentPosition.X, currentPosition.Y, rect.Width - currentPosition.X, rect.Height), XStringFormats.TopLeft); } } }
34.757576
153
0.590235
[ "MIT" ]
brunoserrano/PDFsharp
src/PdfSharp/Pdf.Signatures/DefaultAppearanceHandler.cs
1,149
C#
namespace DawtNetProject.Migrations { using System; using System.Data.Entity.Migrations; public partial class Initial : DbMigration { public override void Up() { CreateTable( "dbo.Articles", c => new { Id = c.Int(nullable: false), ProtectFromEditing = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Versions", t => t.Id) .Index(t => t.Id); CreateTable( "dbo.Comments", c => new { Id = c.Int(nullable: false, identity: true), Content = c.String(nullable: false), LastEdit = c.DateTime(nullable: false), article_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Articles", t => t.article_Id) .Index(t => t.article_Id); CreateTable( "dbo.Versions", c => new { Id = c.Int(nullable: false, identity: true), Title = c.String(nullable: false), ContentPath = c.String(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Domains", c => new { Id = c.Int(nullable: false, identity: true), Title = c.String(nullable: false), Description = c.String(nullable: false), LastEdit = c.DateTime(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.DomainArticles", c => new { Domain_Id = c.Int(nullable: false), Article_Id = c.Int(nullable: false), }) .PrimaryKey(t => new { t.Domain_Id, t.Article_Id }) .ForeignKey("dbo.Domains", t => t.Domain_Id, cascadeDelete: true) .ForeignKey("dbo.Articles", t => t.Article_Id, cascadeDelete: true) .Index(t => t.Domain_Id) .Index(t => t.Article_Id); } public override void Down() { DropForeignKey("dbo.DomainArticles", "Article_Id", "dbo.Articles"); DropForeignKey("dbo.DomainArticles", "Domain_Id", "dbo.Domains"); DropForeignKey("dbo.Articles", "Id", "dbo.Versions"); DropForeignKey("dbo.Comments", "article_Id", "dbo.Articles"); DropIndex("dbo.DomainArticles", new[] { "Article_Id" }); DropIndex("dbo.DomainArticles", new[] { "Domain_Id" }); DropIndex("dbo.Comments", new[] { "article_Id" }); DropIndex("dbo.Articles", new[] { "Id" }); DropTable("dbo.DomainArticles"); DropTable("dbo.Domains"); DropTable("dbo.Versions"); DropTable("dbo.Comments"); DropTable("dbo.Articles"); } } }
38.068182
83
0.428955
[ "MIT" ]
IHorvalds/DawtNetProj
Migrations/202011282036595_Initial.cs
3,352
C#
using System; using System.Collections.Generic; using System.Text; namespace PlayersAndMonsters { public class Wizard : Hero { public Wizard(string username, int level) : base(username, level) { } } }
16
73
0.641667
[ "MIT" ]
Anzzhhela98/CSharp-Advanced
C# OOP/01.Inheritance/Inheritance - Exercises/PlayersAndMonsters/Wizard.cs
242
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V6301 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="UKCT_MT140301UK03.PertinentInformation3", Namespace="urn:hl7-org:v3")] public partial class UKCT_MT140301UK03PertinentInformation3 { private BL seperatableIndField; private UKCT_MT140301UK03AdditionalInstructions pertinentAdditionalInstructionsField; private string typeField; private string typeCodeField; private bool contextConductionIndField; private string[] typeIDField; private string[] realmCodeField; private string nullFlavorField; private static System.Xml.Serialization.XmlSerializer serializer; public UKCT_MT140301UK03PertinentInformation3() { this.typeField = "ActRelationship"; this.typeCodeField = "PERT"; this.contextConductionIndField = true; } public BL seperatableInd { get { return this.seperatableIndField; } set { this.seperatableIndField = value; } } public UKCT_MT140301UK03AdditionalInstructions pertinentAdditionalInstructions { get { return this.pertinentAdditionalInstructionsField; } set { this.pertinentAdditionalInstructionsField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string type { get { return this.typeField; } set { this.typeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string typeCode { get { return this.typeCodeField; } set { this.typeCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public bool contextConductionInd { get { return this.contextConductionIndField; } set { this.contextConductionIndField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string[] typeID { get { return this.typeIDField; } set { this.typeIDField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string[] realmCode { get { return this.realmCodeField; } set { this.realmCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string nullFlavor { get { return this.nullFlavorField; } set { this.nullFlavorField = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(UKCT_MT140301UK03PertinentInformation3)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current UKCT_MT140301UK03PertinentInformation3 object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an UKCT_MT140301UK03PertinentInformation3 object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output UKCT_MT140301UK03PertinentInformation3 object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out UKCT_MT140301UK03PertinentInformation3 obj, out System.Exception exception) { exception = null; obj = default(UKCT_MT140301UK03PertinentInformation3); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out UKCT_MT140301UK03PertinentInformation3 obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static UKCT_MT140301UK03PertinentInformation3 Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((UKCT_MT140301UK03PertinentInformation3)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current UKCT_MT140301UK03PertinentInformation3 object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an UKCT_MT140301UK03PertinentInformation3 object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output UKCT_MT140301UK03PertinentInformation3 object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out UKCT_MT140301UK03PertinentInformation3 obj, out System.Exception exception) { exception = null; obj = default(UKCT_MT140301UK03PertinentInformation3); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out UKCT_MT140301UK03PertinentInformation3 obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static UKCT_MT140301UK03PertinentInformation3 LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this UKCT_MT140301UK03PertinentInformation3 object /// </summary> public virtual UKCT_MT140301UK03PertinentInformation3 Clone() { return ((UKCT_MT140301UK03PertinentInformation3)(this.MemberwiseClone())); } #endregion } }
41.297578
1,358
0.580729
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V6301/Generated/UKCT_MT140301UK03PertinentInformation3.cs
11,935
C#
namespace WebChemistry.Framework.Core { using WebChemistry.Framework.Math; using System; using WebChemistry.Framework.Core.Pdb; /// <summary> /// A representation of the Mol2 atom record. /// </summary> public sealed class Mol2Atom : Atom { /// <summary> /// Mol 2 atom type. /// </summary> public string AtomType { get; private set; } /// <summary> /// Atom name. /// </summary> public string Name { get; private set; } /// <summary> /// Partail Charge [double] /// </summary> public double PartialCharge { get; private set; } /// <summary> /// Residue identifier. /// </summary> public PdbResidueIdentifier ResidueIdentifier { get; private set; } /// <summary> /// residue name. /// </summary> public string ResidueName { get; private set; } /// <summary> /// Clone the atom. /// </summary> /// <returns></returns> public override IAtom Clone() { var ret = new Mol2Atom(this.Id, this.ElementSymbol, this.AtomType, this.Name, this.InvariantPosition) { Position = new Vector3D(this.Position.X, this.Position.Y, this.Position.Z) }; //ret.CopyPropertiesFrom(this); ret.ResidueIdentifier = this.ResidueIdentifier; ret.PartialCharge = this.PartialCharge; ret.ResidueName = this.ResidueName; return ret; } /// <summary> /// Clone the atom with alternate properties. /// </summary> /// <returns></returns> public static IAtom CloneWith( IAtom atom, int? id = null, ElementSymbol? elementSymbol = null, string atomType = null, string name = null, PdbResidueIdentifier? residueIdentifier = null, string residueName = null, double? partialCharge = null) { var molAtom = atom as Mol2Atom; if (molAtom == null) throw new ArgumentException("'atom' must be a Mol2Atom."); var ret = new Mol2Atom(id.DefaultIfNull(atom.Id), elementSymbol.DefaultIfNull(atom.ElementSymbol), atomType ?? molAtom.AtomType, name ?? molAtom.Name, atom.InvariantPosition) { Position = new Vector3D(atom.Position.X, atom.Position.Y, atom.Position.Z) }; ret.ResidueIdentifier = residueIdentifier.HasValue ? residueIdentifier.Value : molAtom.ResidueIdentifier; ret.PartialCharge = partialCharge.HasValue ? partialCharge.Value : molAtom.PartialCharge; ret.ResidueName = residueName ?? molAtom.ResidueName; return ret; } /// <summary> /// Create a new instance of the atom. /// </summary> /// <param name="id"></param> /// <param name="name"></param> /// <param name="elementSymbol"></param> /// <param name="partialCharge"></param> private Mol2Atom(int id, ElementSymbol elementSymbol, string atomType, string name, Vector3D invariantPosition) : base(id, elementSymbol, invariantPosition) { this.AtomType = atomType; this.Name = name; } /// <summary> /// Creates an instance of a Mol2 atom. /// </summary> /// <param name="id"></param> /// <param name="elementSymbol"></param> /// <param name="partialCharge"></param> /// <returns></returns> public static IAtom Create(int id, ElementSymbol elementSymbol, string atomType, string name, PdbResidueIdentifier? residueIdenfier = null, string residueName = "UNK", double partialCharge = 0.0, Vector3D position = new Vector3D()) { var ret = new Mol2Atom(id, elementSymbol, atomType, name, new Vector3D(position.X, position.Y, position.Z)) { Position = position }; ret.PartialCharge = partialCharge; ret.ResidueName = residueName; ret.ResidueIdentifier = residueIdenfier.HasValue ? residueIdenfier.Value : new PdbResidueIdentifier(1, "A", ' '); return ret; } } }
36.739837
193
0.543704
[ "MIT" ]
dsehnal/PatternQuery
src/WebChemistry.Framework.Core/Structure/Mol2/Mol2Atom.cs
4,521
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Globalization; using System.IO; using System.Linq; using Microsoft.VisualStudio.TestPlatform.Client.RequestHelper; using Microsoft.VisualStudio.TestPlatform.CommandLine.Internal; using Microsoft.VisualStudio.TestPlatform.CommandLine.TestPlatformHelpers; using Microsoft.VisualStudio.TestPlatform.Common; using Microsoft.VisualStudio.TestPlatform.Common.Filtering; using Microsoft.VisualStudio.TestPlatform.Common.Interfaces; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; using Microsoft.VisualStudio.TestPlatform.Utilities; using CommandLineResources = Microsoft.VisualStudio.TestPlatform.CommandLine.Resources.Resources; #nullable disable namespace Microsoft.VisualStudio.TestPlatform.CommandLine.Processors; /// <summary> /// Argument Executor for the "--ListFullyQualifiedTests|/ListFullyQualifiedTests" command line argument. /// </summary> internal class ListFullyQualifiedTestsArgumentProcessor : IArgumentProcessor { /// <summary> /// The name of the command line argument that the ListFullyQualifiedTestsArgumentProcessor handles. /// </summary> public const string CommandName = "/ListFullyQualifiedTests"; private Lazy<IArgumentProcessorCapabilities> _metadata; private Lazy<IArgumentExecutor> _executor; /// <summary> /// Gets the metadata. /// </summary> public Lazy<IArgumentProcessorCapabilities> Metadata => _metadata ??= new Lazy<IArgumentProcessorCapabilities>(() => new ListFullyQualifiedTestsArgumentProcessorCapabilities()); /// <summary> /// Gets or sets the executor. /// </summary> public Lazy<IArgumentExecutor> Executor { get => _executor ??= new Lazy<IArgumentExecutor>(() => new ListFullyQualifiedTestsArgumentExecutor( CommandLineOptions.Instance, RunSettingsManager.Instance, TestRequestManager.Instance)); set => _executor = value; } } internal class ListFullyQualifiedTestsArgumentProcessorCapabilities : BaseArgumentProcessorCapabilities { public override string CommandName => ListFullyQualifiedTestsArgumentProcessor.CommandName; public override bool AllowMultiple => false; public override bool IsAction => true; public override ArgumentProcessorPriority Priority => ArgumentProcessorPriority.Normal; } /// <summary> /// Argument Executor for the "/ListTests" command line argument. /// </summary> internal class ListFullyQualifiedTestsArgumentExecutor : IArgumentExecutor { /// <summary> /// Used for getting sources. /// </summary> private readonly CommandLineOptions _commandLineOptions; /// <summary> /// Used for getting tests. /// </summary> private readonly ITestRequestManager _testRequestManager; /// <summary> /// Used for sending output. /// </summary> internal IOutput Output; /// <summary> /// RunSettingsManager to get currently active run settings. /// </summary> private readonly IRunSettingsProvider _runSettingsManager; /// <summary> /// Registers for discovery events during discovery /// </summary> private readonly ITestDiscoveryEventsRegistrar _discoveryEventsRegistrar; /// <summary> /// Test case filter instance /// </summary> private readonly TestCaseFilter _testCasefilter; /// <summary> /// List to store the discovered tests /// </summary> private readonly List<string> _discoveredTests = new(); /// <summary> /// Default constructor. /// </summary> /// <param name="options"> /// The options. /// </param> public ListFullyQualifiedTestsArgumentExecutor( CommandLineOptions options, IRunSettingsProvider runSettingsProvider, ITestRequestManager testRequestManager) : this(options, runSettingsProvider, testRequestManager, ConsoleOutput.Instance) { } /// <summary> /// Default constructor. /// </summary> /// <param name="options"> /// The options. /// </param> internal ListFullyQualifiedTestsArgumentExecutor( CommandLineOptions options, IRunSettingsProvider runSettingsProvider, ITestRequestManager testRequestManager, IOutput output) { Contract.Requires(options != null); _commandLineOptions = options; Output = output; _testRequestManager = testRequestManager; _runSettingsManager = runSettingsProvider; _testCasefilter = new TestCaseFilter(); _discoveryEventsRegistrar = new DiscoveryEventsRegistrar(output, _testCasefilter, _discoveredTests, _commandLineOptions); } #region IArgumentExecutor /// <summary> /// Initializes with the argument that was provided with the command. /// </summary> /// <param name="argument">Argument that was provided with the command.</param> public void Initialize(string argument) { if (!string.IsNullOrWhiteSpace(argument)) { _commandLineOptions.AddSource(argument); } } /// <summary> /// Lists out the available discoverers. /// </summary> public ArgumentProcessorResult Execute() { Contract.Assert(Output != null); Contract.Assert(_commandLineOptions != null); Contract.Assert(!string.IsNullOrWhiteSpace(_runSettingsManager?.ActiveRunSettings?.SettingsXml)); if (!_commandLineOptions.Sources.Any()) { throw new CommandLineException(string.Format(CultureInfo.CurrentUICulture, CommandLineResources.MissingTestSourceFile)); } if (!string.IsNullOrEmpty(EqtTrace.LogFile)) { Output.Information(false, CommandLineResources.VstestDiagLogOutputPath, EqtTrace.LogFile); } var runSettings = _runSettingsManager.ActiveRunSettings.SettingsXml; _testRequestManager.DiscoverTests( new DiscoveryRequestPayload { Sources = _commandLineOptions.Sources, RunSettings = runSettings }, _discoveryEventsRegistrar, Constants.DefaultProtocolConfig); if (string.IsNullOrEmpty(_commandLineOptions.ListTestsTargetPath)) { // This string does not need to go to Resources. Reason - only internal consumption throw new CommandLineException("Target Path should be specified for listing FQDN tests!"); } File.WriteAllLines(_commandLineOptions.ListTestsTargetPath, _discoveredTests); return ArgumentProcessorResult.Success; } #endregion private class DiscoveryEventsRegistrar : ITestDiscoveryEventsRegistrar { private readonly IOutput _output; private readonly TestCaseFilter _testCasefilter; private readonly List<string> _discoveredTests; private readonly CommandLineOptions _options; public DiscoveryEventsRegistrar(IOutput output, TestCaseFilter filter, List<string> discoveredTests, CommandLineOptions cmdOptions) { _output = output; _testCasefilter = filter; _discoveredTests = discoveredTests; _options = cmdOptions; } public void LogWarning(string message) { ConsoleLogger.RaiseTestRunWarning(message); } public void RegisterDiscoveryEvents(IDiscoveryRequest discoveryRequest) { discoveryRequest.OnDiscoveredTests += DiscoveryRequest_OnDiscoveredTests; } public void UnregisterDiscoveryEvents(IDiscoveryRequest discoveryRequest) { discoveryRequest.OnDiscoveredTests -= DiscoveryRequest_OnDiscoveredTests; } private void DiscoveryRequest_OnDiscoveredTests(Object sender, DiscoveredTestsEventArgs args) { if (args == null) { throw new TestPlatformException("DiscoveredTestsEventArgs cannot be null."); } // Initializing the test case filter here because the filter value is read late. _testCasefilter.Initialize(_options.TestCaseFilterValue); var discoveredTests = args.DiscoveredTestCases.ToList(); var filteredTests = _testCasefilter.FilterTests(discoveredTests).ToList(); // remove any duplicate tests filteredTests = filteredTests.Select(test => test.FullyQualifiedName) .Distinct() .Select(fqdn => filteredTests.First(test => test.FullyQualifiedName == fqdn)) .ToList(); _discoveredTests.AddRange(filteredTests.Select(test => test.FullyQualifiedName)); } } private class TestCaseFilter { private static TestCaseFilterExpression s_filterExpression; private const string TestCategory = "TestCategory"; private const string Category = "Category"; private const string Traits = "Traits"; public TestCaseFilter() { } public void Initialize(string filterString) { ValidateFilter(filterString); } /// <summary> /// Filter tests /// </summary> public IEnumerable<TestCase> FilterTests(IEnumerable<TestCase> testCases) { EqtTrace.Verbose("TestCaseFilter.FilterTests : Test Filtering invoked."); List<TestCase> filteredList; try { filteredList = GetFilteredTestCases(testCases); } catch (Exception ex) { EqtTrace.Error("TestCaseFilter.FilterTests : Exception during filtering : {0}", ex.ToString()); throw; } return filteredList; } private static void ValidateFilter(string filterString) { if (string.IsNullOrEmpty(filterString)) { s_filterExpression = null; return; } var filterWrapper = new FilterExpressionWrapper(filterString); if (filterWrapper.ParseError != null) { var fe = new FormatException(string.Format("Invalid Test Case Filter: {0}", filterString)); EqtTrace.Error("TestCaseFilter.ValidateFilter : Filtering failed with exception : " + fe.Message); throw fe; } s_filterExpression = new TestCaseFilterExpression(filterWrapper); } /// <summary> /// get list of test cases that satisfy the filter criteria /// </summary> private static List<TestCase> GetFilteredTestCases(IEnumerable<TestCase> testCases) { var filteredList = new List<TestCase>(); if (s_filterExpression == null) { filteredList = testCases.ToList(); return filteredList; } foreach (var testCase in testCases) { var traitDictionary = GetTestPropertiesInTraitDictionary(testCase);// Dictionary with trait key to value mapping traitDictionary = GetTraitsInTraitDictionary(traitDictionary, testCase.Traits); // Skip test if not fitting filter criteria. if (!s_filterExpression.MatchTestCase(testCase, p => PropertyValueProvider(p, traitDictionary))) { continue; } filteredList.Add(testCase); } return filteredList; } /// <summary> /// fetch the test properties on this test method as traits and populate a trait dictionary /// </summary> private static Dictionary<string, List<string>> GetTestPropertiesInTraitDictionary(TestCase testCase) { var traitDictionary = new Dictionary<string, List<string>>(); foreach (var testProperty in testCase.Properties) { string testPropertyKey = testProperty.Label; if (testPropertyKey.Equals(Traits)) { // skip the "Traits" property. traits to be set separately continue; } var testPropertyValue = testCase.GetPropertyValue(testProperty); if (testPropertyKey.Equals(TestCategory)) { if (testPropertyValue is string[] testPropertyValueArray) { var testPropertyValueList = new List<string>(testPropertyValueArray); traitDictionary.Add(testPropertyKey, testPropertyValueList); continue; } } //always return value as a list of string if (testPropertyValue != null) { var multiValue = new List<string> { testPropertyValue.ToString() }; traitDictionary.Add(testPropertyKey, multiValue); } } return traitDictionary; } /// <summary> /// fetch the traits on this test method and populate a trait dictionary /// </summary> private static Dictionary<string, List<string>> GetTraitsInTraitDictionary(Dictionary<string, List<string>> traitDictionary, TraitCollection traits) { foreach (var trait in traits) { var newTraitValueList = new List<string> { trait.Value }; if (!traitDictionary.TryGetValue(trait.Name, out List<string> currentTraitValue)) { // if the current trait's key is not already present, add the current trait key-value pair traitDictionary.Add(trait.Name, newTraitValueList); } else { if (null == currentTraitValue) { // if the current trait's value is null, replace the previous value with the current value traitDictionary[trait.Name] = newTraitValueList; } else { // if the current trait's key is already present and is not null, append current value to the previous value list List<string> traitValueList = currentTraitValue; traitValueList.Add(trait.Value); } } } //This is hack for NUnit, XUnit to understand test category -> This method is called only for NUnit/XUnit if (!traitDictionary.ContainsKey(TestCategory) && traitDictionary.ContainsKey(Category)) { traitDictionary.TryGetValue(Category, out var categoryValue); traitDictionary.Add(TestCategory, categoryValue); } return traitDictionary; } /// <summary> /// Provides value for property name 'propertyName' as used in filter. /// </summary> private static string[] PropertyValueProvider(string propertyName, Dictionary<string, List<string>> traitDictionary) { traitDictionary.TryGetValue(propertyName, out List<string> propertyValueList); if (propertyValueList != null) { var propertyValueArray = propertyValueList.ToArray(); return propertyValueArray; } return null; } } }
36.098398
156
0.634992
[ "MIT" ]
Evangelink/vstest
src/vstest.console/Processors/ListFullyQualifiedTestsArgumentProcessor.cs
15,775
C#
namespace MassTransit.GrpcTransport.Tests { using System; using System.Threading.Tasks; using Courier.Contracts; using NUnit.Framework; using TestFramework; using Testing; public record DemoArguments(Guid Id); public record DemoEvent(Guid Id); public class DemoActivityTests : InMemoryActivityTestFixture { protected override void SetupActivities(BusTestHarness testHarness) { AddActivityContext<DemoActivity, DemoArguments>(() => new DemoActivity()); } [Test] public async Task Demo_should_not_fail_to_serialize() { var activity = GetActivityContext<DemoActivity>(); Task<ConsumeContext<RoutingSlipCompleted>> completed = InMemoryTestHarness.SubscribeHandler<RoutingSlipCompleted>(); Task<ConsumeContext<RoutingSlipActivityCompleted>> activityCompleted = InMemoryTestHarness.SubscribeHandler<RoutingSlipActivityCompleted>(); var trackingNumber = NewId.NextGuid(); var builder = new RoutingSlipBuilder(trackingNumber); builder.AddSubscription(InMemoryTestHarness.BusAddress, RoutingSlipEvents.All); builder.AddActivity(activity.Name, activity.ExecuteUri, new DemoArguments(Guid.NewGuid())); await InMemoryTestHarness.Bus.Execute(builder.Build()); await completed; ConsumeContext<RoutingSlipActivityCompleted> context = await activityCompleted!; Assert.True(await InMemoryTestHarness.Published.Any<DemoEvent>()); Assert.AreEqual(trackingNumber, context.Message.TrackingNumber); } } public class DemoActivity : IExecuteActivity<DemoArguments> { public async Task<ExecutionResult> Execute(ExecuteContext<DemoArguments> context) { await Task.Delay(500); await context.Publish(new DemoEvent(context.Arguments.Id)).ConfigureAwait(false); return context.Completed(); } } }
33.081967
152
0.688801
[ "ECL-2.0", "Apache-2.0" ]
AlexanderMeier/MassTransit
tests/MassTransit.GrpcTransport.Tests/RoutingSlipDictionary_Specs.cs
2,018
C#
using System; using System.Collections.Generic; using System.Text; namespace DayVsNight.Themes { class ThemeMessage { public const string ThemeChanged = "ThemeChanged"; } }
16.333333
59
0.704082
[ "MIT" ]
DaraOladapo/DayVsNight
src/DayVsNight/DayVsNight/DayVsNight/Themes/ThemeMessage.cs
198
C#
namespace NoLockScreenHelper2 { partial class SettingsForm { /// <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(SettingsForm)); this.buttonPortableMaker = new System.Windows.Forms.Button(); this.checkBoxActivateOnStartup = new System.Windows.Forms.CheckBox(); this.checkBoxRunOnLogOn = new System.Windows.Forms.CheckBox(); this.checkBoxHideIfMinimalized = new System.Windows.Forms.CheckBox(); this.checkBoxStartMinimized = new System.Windows.Forms.CheckBox(); this.checkBoxEnableNotificationBubbles = new System.Windows.Forms.CheckBox(); this.buttonAdd = new System.Windows.Forms.Button(); this.buttonRemove = new System.Windows.Forms.Button(); this.objectListView1 = new BrightIdeasSoftware.DataListView(); this.olvColumnName = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn())); this.olvColumnNetworkName = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn())); this.olvColumnIPAddress = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn())); this.olvColumnGateway = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn())); this.tabControlMain = new System.Windows.Forms.TabControl(); this.tabPageBehavior = new System.Windows.Forms.TabPage(); this.tabPageNetworks = new System.Windows.Forms.TabPage(); this.splitContainerNetworks = new System.Windows.Forms.SplitContainer(); this.tabPageOther = new System.Windows.Forms.TabPage(); this.groupBoxLanguage = new System.Windows.Forms.GroupBox(); this.groupBoxPortability = new System.Windows.Forms.GroupBox(); this.tabPageTimer = new System.Windows.Forms.TabPage(); this.groupBoxTimerEnds = new System.Windows.Forms.GroupBox(); this.radioButtonTimerEndsStop = new System.Windows.Forms.RadioButton(); this.radioButtonTimerEndsAuto = new System.Windows.Forms.RadioButton(); this.groupBoxTimer = new System.Windows.Forms.GroupBox(); this.dataListView1 = new BrightIdeasSoftware.DataListView(); this.olvColumnTimerTimeSpan = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn())); this.comboBoxLanguage = new System.Windows.Forms.ComboBox(); ((System.ComponentModel.ISupportInitialize)(this.objectListView1)).BeginInit(); this.tabControlMain.SuspendLayout(); this.tabPageBehavior.SuspendLayout(); this.tabPageNetworks.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainerNetworks)).BeginInit(); this.splitContainerNetworks.Panel1.SuspendLayout(); this.splitContainerNetworks.Panel2.SuspendLayout(); this.splitContainerNetworks.SuspendLayout(); this.tabPageOther.SuspendLayout(); this.groupBoxLanguage.SuspendLayout(); this.groupBoxPortability.SuspendLayout(); this.tabPageTimer.SuspendLayout(); this.groupBoxTimerEnds.SuspendLayout(); this.groupBoxTimer.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataListView1)).BeginInit(); this.SuspendLayout(); // // buttonPortableMaker // this.buttonPortableMaker.Location = new System.Drawing.Point(6, 19); this.buttonPortableMaker.Name = "buttonPortableMaker"; this.buttonPortableMaker.Size = new System.Drawing.Size(124, 30); this.buttonPortableMaker.TabIndex = 0; this.buttonPortableMaker.Text = "Udělat přenositelné"; this.buttonPortableMaker.UseVisualStyleBackColor = true; this.buttonPortableMaker.Click += new System.EventHandler(this.buttonPortableMaker_Click); // // checkBoxActivateOnStartup // this.checkBoxActivateOnStartup.AutoSize = true; this.checkBoxActivateOnStartup.Location = new System.Drawing.Point(6, 6); this.checkBoxActivateOnStartup.Name = "checkBoxActivateOnStartup"; this.checkBoxActivateOnStartup.Size = new System.Drawing.Size(130, 17); this.checkBoxActivateOnStartup.TabIndex = 1; this.checkBoxActivateOnStartup.Text = "Aktivovat po spuštění"; this.checkBoxActivateOnStartup.UseVisualStyleBackColor = true; // // checkBoxRunOnLogOn // this.checkBoxRunOnLogOn.AutoSize = true; this.checkBoxRunOnLogOn.Location = new System.Drawing.Point(6, 23); this.checkBoxRunOnLogOn.Name = "checkBoxRunOnLogOn"; this.checkBoxRunOnLogOn.Size = new System.Drawing.Size(123, 17); this.checkBoxRunOnLogOn.TabIndex = 2; this.checkBoxRunOnLogOn.Text = "Spustit po přihlášení"; this.checkBoxRunOnLogOn.UseVisualStyleBackColor = true; // // checkBoxHideIfMinimalized // this.checkBoxHideIfMinimalized.AutoSize = true; this.checkBoxHideIfMinimalized.Location = new System.Drawing.Point(6, 78); this.checkBoxHideIfMinimalized.Name = "checkBoxHideIfMinimalized"; this.checkBoxHideIfMinimalized.Size = new System.Drawing.Size(139, 17); this.checkBoxHideIfMinimalized.TabIndex = 11; this.checkBoxHideIfMinimalized.Text = "Schovat při minimalizaci"; this.checkBoxHideIfMinimalized.UseVisualStyleBackColor = true; // // checkBoxStartMinimized // this.checkBoxStartMinimized.AutoSize = true; this.checkBoxStartMinimized.Location = new System.Drawing.Point(6, 59); this.checkBoxStartMinimized.Name = "checkBoxStartMinimized"; this.checkBoxStartMinimized.Size = new System.Drawing.Size(132, 17); this.checkBoxStartMinimized.TabIndex = 10; this.checkBoxStartMinimized.Text = "Spustit minimalizovaně"; this.checkBoxStartMinimized.UseVisualStyleBackColor = true; // // checkBoxEnableNotificationBubbles // this.checkBoxEnableNotificationBubbles.AutoSize = true; this.checkBoxEnableNotificationBubbles.Location = new System.Drawing.Point(6, 41); this.checkBoxEnableNotificationBubbles.Name = "checkBoxEnableNotificationBubbles"; this.checkBoxEnableNotificationBubbles.Size = new System.Drawing.Size(147, 17); this.checkBoxEnableNotificationBubbles.TabIndex = 9; this.checkBoxEnableNotificationBubbles.Text = "Povolit informační bubliny"; this.checkBoxEnableNotificationBubbles.UseVisualStyleBackColor = true; // // buttonAdd // this.buttonAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonAdd.Location = new System.Drawing.Point(4, 10); this.buttonAdd.Name = "buttonAdd"; this.buttonAdd.Size = new System.Drawing.Size(75, 23); this.buttonAdd.TabIndex = 6; this.buttonAdd.Text = "Přidat"; this.buttonAdd.UseVisualStyleBackColor = true; this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click); // // buttonRemove // this.buttonRemove.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonRemove.Location = new System.Drawing.Point(85, 10); this.buttonRemove.Name = "buttonRemove"; this.buttonRemove.Size = new System.Drawing.Size(75, 23); this.buttonRemove.TabIndex = 7; this.buttonRemove.Text = "Odebrat"; this.buttonRemove.UseVisualStyleBackColor = true; this.buttonRemove.Click += new System.EventHandler(this.buttonRemove_Click); // // objectListView1 // this.objectListView1.AllColumns.Add(this.olvColumnName); this.objectListView1.AllColumns.Add(this.olvColumnNetworkName); this.objectListView1.AllColumns.Add(this.olvColumnIPAddress); this.objectListView1.AllColumns.Add(this.olvColumnGateway); this.objectListView1.CellEditUseWholeCell = false; this.objectListView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.olvColumnName, this.olvColumnNetworkName, this.olvColumnIPAddress, this.olvColumnGateway}); this.objectListView1.Cursor = System.Windows.Forms.Cursors.Default; this.objectListView1.DataSource = null; this.objectListView1.Dock = System.Windows.Forms.DockStyle.Fill; this.objectListView1.HideSelection = false; this.objectListView1.Location = new System.Drawing.Point(0, 0); this.objectListView1.Name = "objectListView1"; this.objectListView1.Size = new System.Drawing.Size(396, 242); this.objectListView1.TabIndex = 8; this.objectListView1.UseCompatibleStateImageBehavior = false; this.objectListView1.View = System.Windows.Forms.View.Details; // // olvColumnName // this.olvColumnName.AspectName = "Name"; this.olvColumnName.Text = "Název"; this.olvColumnName.Width = 92; // // olvColumnNetworkName // this.olvColumnNetworkName.AspectName = "NetworkName"; this.olvColumnNetworkName.Text = "Název sítě"; this.olvColumnNetworkName.Width = 98; // // olvColumnIPAddress // this.olvColumnIPAddress.AspectName = "IPAddress"; this.olvColumnIPAddress.Text = "IP Adresa"; this.olvColumnIPAddress.Width = 100; // // olvColumnGateway // this.olvColumnGateway.AspectName = "Gateway"; this.olvColumnGateway.Text = "IP Brány"; this.olvColumnGateway.Width = 100; // // tabControlMain // this.tabControlMain.Controls.Add(this.tabPageBehavior); this.tabControlMain.Controls.Add(this.tabPageNetworks); this.tabControlMain.Controls.Add(this.tabPageOther); this.tabControlMain.Controls.Add(this.tabPageTimer); this.tabControlMain.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControlMain.Location = new System.Drawing.Point(0, 0); this.tabControlMain.Name = "tabControlMain"; this.tabControlMain.SelectedIndex = 0; this.tabControlMain.Size = new System.Drawing.Size(410, 314); this.tabControlMain.TabIndex = 9; // // tabPageBehavior // this.tabPageBehavior.Controls.Add(this.checkBoxHideIfMinimalized); this.tabPageBehavior.Controls.Add(this.checkBoxStartMinimized); this.tabPageBehavior.Controls.Add(this.checkBoxActivateOnStartup); this.tabPageBehavior.Controls.Add(this.checkBoxEnableNotificationBubbles); this.tabPageBehavior.Controls.Add(this.checkBoxRunOnLogOn); this.tabPageBehavior.Location = new System.Drawing.Point(4, 22); this.tabPageBehavior.Name = "tabPageBehavior"; this.tabPageBehavior.Padding = new System.Windows.Forms.Padding(3); this.tabPageBehavior.Size = new System.Drawing.Size(402, 288); this.tabPageBehavior.TabIndex = 0; this.tabPageBehavior.Text = "Chování"; this.tabPageBehavior.UseVisualStyleBackColor = true; // // tabPageNetworks // this.tabPageNetworks.Controls.Add(this.splitContainerNetworks); this.tabPageNetworks.Location = new System.Drawing.Point(4, 22); this.tabPageNetworks.Name = "tabPageNetworks"; this.tabPageNetworks.Padding = new System.Windows.Forms.Padding(3); this.tabPageNetworks.Size = new System.Drawing.Size(402, 288); this.tabPageNetworks.TabIndex = 1; this.tabPageNetworks.Text = "Sítě"; this.tabPageNetworks.UseVisualStyleBackColor = true; // // splitContainerNetworks // this.splitContainerNetworks.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainerNetworks.FixedPanel = System.Windows.Forms.FixedPanel.Panel2; this.splitContainerNetworks.IsSplitterFixed = true; this.splitContainerNetworks.Location = new System.Drawing.Point(3, 3); this.splitContainerNetworks.Name = "splitContainerNetworks"; this.splitContainerNetworks.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainerNetworks.Panel1 // this.splitContainerNetworks.Panel1.Controls.Add(this.objectListView1); // // splitContainerNetworks.Panel2 // this.splitContainerNetworks.Panel2.Controls.Add(this.buttonRemove); this.splitContainerNetworks.Panel2.Controls.Add(this.buttonAdd); this.splitContainerNetworks.Size = new System.Drawing.Size(396, 282); this.splitContainerNetworks.SplitterDistance = 242; this.splitContainerNetworks.SplitterWidth = 1; this.splitContainerNetworks.TabIndex = 10; this.splitContainerNetworks.TabStop = false; // // tabPageOther // this.tabPageOther.Controls.Add(this.groupBoxLanguage); this.tabPageOther.Controls.Add(this.groupBoxPortability); this.tabPageOther.Location = new System.Drawing.Point(4, 22); this.tabPageOther.Name = "tabPageOther"; this.tabPageOther.Padding = new System.Windows.Forms.Padding(3); this.tabPageOther.Size = new System.Drawing.Size(402, 288); this.tabPageOther.TabIndex = 2; this.tabPageOther.Text = "Ostatní"; this.tabPageOther.UseVisualStyleBackColor = true; // // groupBoxLanguage // this.groupBoxLanguage.Controls.Add(this.comboBoxLanguage); this.groupBoxLanguage.Location = new System.Drawing.Point(163, 6); this.groupBoxLanguage.Name = "groupBoxLanguage"; this.groupBoxLanguage.Size = new System.Drawing.Size(153, 70); this.groupBoxLanguage.TabIndex = 2; this.groupBoxLanguage.TabStop = false; this.groupBoxLanguage.Text = "Jazyk"; // // groupBoxPortability // this.groupBoxPortability.Controls.Add(this.buttonPortableMaker); this.groupBoxPortability.Location = new System.Drawing.Point(8, 6); this.groupBoxPortability.Name = "groupBoxPortability"; this.groupBoxPortability.Size = new System.Drawing.Size(149, 70); this.groupBoxPortability.TabIndex = 1; this.groupBoxPortability.TabStop = false; this.groupBoxPortability.Text = "Portability"; // // tabPageTimer // this.tabPageTimer.Controls.Add(this.groupBoxTimerEnds); this.tabPageTimer.Controls.Add(this.groupBoxTimer); this.tabPageTimer.Location = new System.Drawing.Point(4, 22); this.tabPageTimer.Name = "tabPageTimer"; this.tabPageTimer.Padding = new System.Windows.Forms.Padding(3); this.tabPageTimer.Size = new System.Drawing.Size(402, 288); this.tabPageTimer.TabIndex = 3; this.tabPageTimer.Text = "Časovač"; this.tabPageTimer.UseVisualStyleBackColor = true; // // groupBoxTimerEnds // this.groupBoxTimerEnds.Controls.Add(this.radioButtonTimerEndsStop); this.groupBoxTimerEnds.Controls.Add(this.radioButtonTimerEndsAuto); this.groupBoxTimerEnds.Location = new System.Drawing.Point(8, 6); this.groupBoxTimerEnds.Name = "groupBoxTimerEnds"; this.groupBoxTimerEnds.Size = new System.Drawing.Size(386, 82); this.groupBoxTimerEnds.TabIndex = 13; this.groupBoxTimerEnds.TabStop = false; this.groupBoxTimerEnds.Text = "When timer ends"; // // radioButtonTimerEndsStop // this.radioButtonTimerEndsStop.AutoSize = true; this.radioButtonTimerEndsStop.Location = new System.Drawing.Point(7, 44); this.radioButtonTimerEndsStop.Name = "radioButtonTimerEndsStop"; this.radioButtonTimerEndsStop.Size = new System.Drawing.Size(108, 17); this.radioButtonTimerEndsStop.TabIndex = 1; this.radioButtonTimerEndsStop.TabStop = true; this.radioButtonTimerEndsStop.Text = "přepnout na Stop"; this.radioButtonTimerEndsStop.UseVisualStyleBackColor = true; // // radioButtonTimerEndsAuto // this.radioButtonTimerEndsAuto.AutoSize = true; this.radioButtonTimerEndsAuto.Location = new System.Drawing.Point(7, 20); this.radioButtonTimerEndsAuto.Name = "radioButtonTimerEndsAuto"; this.radioButtonTimerEndsAuto.Size = new System.Drawing.Size(108, 17); this.radioButtonTimerEndsAuto.TabIndex = 0; this.radioButtonTimerEndsAuto.TabStop = true; this.radioButtonTimerEndsAuto.Text = "přeonout na Auto"; this.radioButtonTimerEndsAuto.UseVisualStyleBackColor = true; // // groupBoxTimer // this.groupBoxTimer.Controls.Add(this.dataListView1); this.groupBoxTimer.Location = new System.Drawing.Point(8, 94); this.groupBoxTimer.Name = "groupBoxTimer"; this.groupBoxTimer.Size = new System.Drawing.Size(386, 188); this.groupBoxTimer.TabIndex = 4; this.groupBoxTimer.TabStop = false; this.groupBoxTimer.Text = "Časovač"; // // dataListView1 // this.dataListView1.AllColumns.Add(this.olvColumnTimerTimeSpan); this.dataListView1.CellEditUseWholeCell = false; this.dataListView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.olvColumnTimerTimeSpan}); this.dataListView1.Cursor = System.Windows.Forms.Cursors.Default; this.dataListView1.DataSource = null; this.dataListView1.Dock = System.Windows.Forms.DockStyle.Fill; this.dataListView1.HideSelection = false; this.dataListView1.Location = new System.Drawing.Point(3, 16); this.dataListView1.Name = "dataListView1"; this.dataListView1.Size = new System.Drawing.Size(380, 169); this.dataListView1.TabIndex = 0; this.dataListView1.UseCompatibleStateImageBehavior = false; this.dataListView1.View = System.Windows.Forms.View.Details; // // olvColumnTimerTimeSpan // this.olvColumnTimerTimeSpan.AspectName = "TimeSpan"; this.olvColumnTimerTimeSpan.IsEditable = false; this.olvColumnTimerTimeSpan.Text = "Čas"; this.olvColumnTimerTimeSpan.Width = 344; // // comboBoxLanguage // this.comboBoxLanguage.FormattingEnabled = true; this.comboBoxLanguage.Location = new System.Drawing.Point(6, 25); this.comboBoxLanguage.Name = "comboBoxLanguage"; this.comboBoxLanguage.Size = new System.Drawing.Size(141, 21); this.comboBoxLanguage.TabIndex = 0; // // SettingsForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Window; this.ClientSize = new System.Drawing.Size(410, 314); this.Controls.Add(this.tabControlMain); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "SettingsForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Nastavení"; ((System.ComponentModel.ISupportInitialize)(this.objectListView1)).EndInit(); this.tabControlMain.ResumeLayout(false); this.tabPageBehavior.ResumeLayout(false); this.tabPageBehavior.PerformLayout(); this.tabPageNetworks.ResumeLayout(false); this.splitContainerNetworks.Panel1.ResumeLayout(false); this.splitContainerNetworks.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainerNetworks)).EndInit(); this.splitContainerNetworks.ResumeLayout(false); this.tabPageOther.ResumeLayout(false); this.groupBoxLanguage.ResumeLayout(false); this.groupBoxPortability.ResumeLayout(false); this.tabPageTimer.ResumeLayout(false); this.groupBoxTimerEnds.ResumeLayout(false); this.groupBoxTimerEnds.PerformLayout(); this.groupBoxTimer.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataListView1)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button buttonPortableMaker; private System.Windows.Forms.CheckBox checkBoxActivateOnStartup; private System.Windows.Forms.CheckBox checkBoxRunOnLogOn; private System.Windows.Forms.Button buttonAdd; private System.Windows.Forms.Button buttonRemove; private BrightIdeasSoftware.DataListView objectListView1; private BrightIdeasSoftware.OLVColumn olvColumnName; private BrightIdeasSoftware.OLVColumn olvColumnNetworkName; private BrightIdeasSoftware.OLVColumn olvColumnIPAddress; private BrightIdeasSoftware.OLVColumn olvColumnGateway; private System.Windows.Forms.CheckBox checkBoxEnableNotificationBubbles; private System.Windows.Forms.CheckBox checkBoxHideIfMinimalized; private System.Windows.Forms.CheckBox checkBoxStartMinimized; private System.Windows.Forms.TabControl tabControlMain; private System.Windows.Forms.TabPage tabPageBehavior; private System.Windows.Forms.TabPage tabPageNetworks; private System.Windows.Forms.TabPage tabPageOther; private System.Windows.Forms.SplitContainer splitContainerNetworks; private System.Windows.Forms.GroupBox groupBoxPortability; private System.Windows.Forms.TabPage tabPageTimer; private System.Windows.Forms.GroupBox groupBoxTimerEnds; private System.Windows.Forms.RadioButton radioButtonTimerEndsStop; private System.Windows.Forms.RadioButton radioButtonTimerEndsAuto; private System.Windows.Forms.GroupBox groupBoxTimer; private BrightIdeasSoftware.DataListView dataListView1; private BrightIdeasSoftware.OLVColumn olvColumnTimerTimeSpan; private System.Windows.Forms.GroupBox groupBoxLanguage; private System.Windows.Forms.ComboBox comboBoxLanguage; } }
55.008889
162
0.648622
[ "MIT" ]
lordrak007/NLSH
NoLockScreenHelper2/SettingsForm.Designer.cs
24,789
C#
using Models.DB; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using System.Collections.Generic; using System.Threading.Tasks; namespace API.Controllers { [Route("api/[controller]")] //[Authorize] [ApiController] public class TcontrollersController : Controller { private RailML_3_1Context db = new RailML_3_1Context(); // GET api/values/5 [HttpGet("{id}")] public async Task<string> Get(int id) { //IList<Tcontroller> lTcontrollers = await db.Tcontroller.GetAllCompanyTcontrollers(id); //return JsonConvert.SerializeObject(lTcontrollers.ToArray()); return ""; } // POST api/values [HttpPost] public async Task<string> Post([FromBody]Tcontroller tcontroller) { //Create db.Tcontroller.Add(tcontroller); await db.SaveChangesAsync(); return JsonConvert.SerializeObject(tcontroller); } // PUT api/values/5 [HttpPut("{id}")] public async Task Put(int id, [FromBody]Tcontroller tcontroller) { //Update db.Tcontroller.Update(tcontroller); await db.SaveChangesAsync(); } // DELETE api/values/5 [HttpDelete("{id}")] public async Task<string> DeleteAsync([FromBody]Tcontroller tcontroller) { db.Tcontroller.Remove(tcontroller); await db.SaveChangesAsync(); return JsonConvert.SerializeObject("Ok"); } } }
25.648148
93
0.701083
[ "Apache-2.0" ]
LightosLimited/RailML
v3.1/API/Controllers/TcontrollerController.cs
1,385
C#
// ------------------------------------------------------------------------ // Copyright 2021 The Dapr Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------ namespace Microsoft.AspNetCore.Builder { using System; using Dapr.Actors; using Dapr.Actors.Runtime; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; /// <summary> /// Contains extension methods for using Dapr Actors with endpoint routing. /// </summary> public static class ActorsEndpointRouteBuilderExtensions { /// <summary> /// Maps endpoints for Dapr Actors into the <see cref="IEndpointRouteBuilder" />. /// </summary> /// <param name="endpoints">The <see cref="IEndpointRouteBuilder" />.</param> /// <returns> /// An <see cref="IEndpointConventionBuilder" /> that can be used to configure the endpoints. /// </returns> public static IEndpointConventionBuilder MapActorsHandlers(this IEndpointRouteBuilder endpoints) { if (endpoints.ServiceProvider.GetService<ActorRuntime>() is null) { throw new InvalidOperationException( "The ActorRuntime service is not registered with the dependency injection container. " + "Call AddActors() inside ConfigureServices() to register the actor runtime and actor types."); } var builders = new[] { MapDaprConfigEndpoint(endpoints), MapActorDeactivationEndpoint(endpoints), MapActorMethodEndpoint(endpoints), MapReminderEndpoint(endpoints), MapTimerEndpoint(endpoints), MapActorHealthChecks(endpoints), }; return new CompositeEndpointConventionBuilder(builders); } private static IEndpointConventionBuilder MapDaprConfigEndpoint(this IEndpointRouteBuilder endpoints) { var runtime = endpoints.ServiceProvider.GetRequiredService<ActorRuntime>(); return endpoints.MapGet("dapr/config", async context => { context.Response.ContentType = "application/json"; await runtime.SerializeSettingsAndRegisteredTypes(context.Response.BodyWriter); await context.Response.BodyWriter.FlushAsync(); }).WithDisplayName(b => "Dapr Actors Config"); } private static IEndpointConventionBuilder MapActorDeactivationEndpoint(this IEndpointRouteBuilder endpoints) { var runtime = endpoints.ServiceProvider.GetRequiredService<ActorRuntime>(); return endpoints.MapDelete("actors/{actorTypeName}/{actorId}", async context => { var routeValues = context.Request.RouteValues; var actorTypeName = (string)routeValues["actorTypeName"]; var actorId = (string)routeValues["actorId"]; await runtime.DeactivateAsync(actorTypeName, actorId); }).WithDisplayName(b => "Dapr Actors Deactivation"); } private static IEndpointConventionBuilder MapActorMethodEndpoint(this IEndpointRouteBuilder endpoints) { var runtime = endpoints.ServiceProvider.GetRequiredService<ActorRuntime>(); return endpoints.MapPut("actors/{actorTypeName}/{actorId}/method/{methodName}", async context => { var routeValues = context.Request.RouteValues; var actorTypeName = (string)routeValues["actorTypeName"]; var actorId = (string)routeValues["actorId"]; var methodName = (string)routeValues["methodName"]; if (context.Request.Headers.ContainsKey(Constants.ReentrancyRequestHeaderName)) { var daprReentrancyHeader = context.Request.Headers[Constants.ReentrancyRequestHeaderName]; ActorReentrancyContextAccessor.ReentrancyContext = daprReentrancyHeader; } // If Header is present, call is made using Remoting, use Remoting dispatcher. if (context.Request.Headers.ContainsKey(Constants.RequestHeaderName)) { var daprActorheader = context.Request.Headers[Constants.RequestHeaderName]; try { var (header, body) = await runtime.DispatchWithRemotingAsync(actorTypeName, actorId, methodName, daprActorheader, context.Request.Body); // Item 1 is header , Item 2 is body if (header != string.Empty) { // exception case context.Response.Headers.Add(Constants.ErrorResponseHeaderName, header); // add error header } await context.Response.Body.WriteAsync(body, 0, body.Length); // add response message body } finally { ActorReentrancyContextAccessor.ReentrancyContext = null; } } else { try { await runtime.DispatchWithoutRemotingAsync(actorTypeName, actorId, methodName, context.Request.Body, context.Response.Body); } finally { ActorReentrancyContextAccessor.ReentrancyContext = null; } } }).WithDisplayName(b => "Dapr Actors Invoke"); } private static IEndpointConventionBuilder MapReminderEndpoint(this IEndpointRouteBuilder endpoints) { var runtime = endpoints.ServiceProvider.GetRequiredService<ActorRuntime>(); return endpoints.MapPut("actors/{actorTypeName}/{actorId}/method/remind/{reminderName}", async context => { var routeValues = context.Request.RouteValues; var actorTypeName = (string)routeValues["actorTypeName"]; var actorId = (string)routeValues["actorId"]; var reminderName = (string)routeValues["reminderName"]; // read dueTime, period and data from Request Body. await runtime.FireReminderAsync(actorTypeName, actorId, reminderName, context.Request.Body); }).WithDisplayName(b => "Dapr Actors Reminder"); } private static IEndpointConventionBuilder MapTimerEndpoint(this IEndpointRouteBuilder endpoints) { var runtime = endpoints.ServiceProvider.GetRequiredService<ActorRuntime>(); return endpoints.MapPut("actors/{actorTypeName}/{actorId}/method/timer/{timerName}", async context => { var routeValues = context.Request.RouteValues; var actorTypeName = (string)routeValues["actorTypeName"]; var actorId = (string)routeValues["actorId"]; var timerName = (string)routeValues["timerName"]; // read dueTime, period and data from Request Body. await runtime.FireTimerAsync(actorTypeName, actorId, timerName, context.Request.Body); }).WithDisplayName(b => "Dapr Actors Timer"); } private static IEndpointConventionBuilder MapActorHealthChecks(this IEndpointRouteBuilder endpoints) { var builder = endpoints.MapHealthChecks("/healthz"); builder.Add(b => { // Sets the route order so that this is matched with lower priority than an endpoint // configured by default. // // This is necessary because it allows a user defined `/healthz` endpoint to win in the // most common cases, but still fulfills Dapr's contract when the user doesn't have // a health check at `/healthz`. ((RouteEndpointBuilder)b).Order = 100; }); return builder.WithDisplayName(b => "Dapr Actors Health Check"); } private class CompositeEndpointConventionBuilder : IEndpointConventionBuilder { private readonly IEndpointConventionBuilder[] inner; public CompositeEndpointConventionBuilder(IEndpointConventionBuilder[] inner) { this.inner = inner; } public void Add(Action<EndpointBuilder> convention) { for (var i = 0; i < inner.Length; i++) { inner[i].Add(convention); } } } } }
47.080402
160
0.5943
[ "Apache-2.0" ]
ChrisProlls/dotnet-sdk
src/Dapr.Actors.AspNetCore/ActorsEndpointRouteBuilderExtensions.cs
9,369
C#
// This is an independent project of an individual developer. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com namespace ExtraGACUtil.Interfaces { interface IProjectsRepository { } }
26.5
96
0.716981
[ "MIT" ]
Rombique/ExtraGACUtil
Interfaces/IProjectsRepository.cs
267
C#
using System.Drawing; using SciChart.Charting3D.Common.Math; using SciChart.Charting3D.Model; using SciChart.Charting3D.Model.DataSeries.Xyz; using SciChart.Charting3D.Modifiers; using SciChart.Charting3D.Visuals; using SciChart.Charting3D.Visuals.Axes; using SciChart.Charting3D.Visuals.Camera; using SciChart.Charting3D.Visuals.PointMarkers; using SciChart.Charting3D.Visuals.RenderableSeries.Scatter; using SciChart.Data.Model; using Xamarin.Examples.Demo.Data; using Xamarin.Examples.Demo; using Xamarin.Examples.Demo.Droid.Fragments.Base; namespace Xamarin.Examples.Demo.Droid.Fragments.Examples3D { [Example3DDefinition("Simple Point Cloud 3D Chart", description: "Create a simple Point Cloud 3D Chart", icon: ExampleIcon.Scatter3D)] class CreatePointCloud3DChartFragment : ExampleBaseFragment { public SciChartSurface3D Surface => View.FindViewById<SciChartSurface3D>(Resource.Id.chart3d); public override int ExampleLayoutId => Resource.Layout.Example_Single_3D_Chart_Fragment; protected override void InitExample() { var dataManager = DataManager.Instance; var dataSeries3D = new XyzDataSeries3D<double, double, double>(); for (int i = 0; i < 10000; i++) { double x = dataManager.GetGaussianRandomNumber(5, 1.5); double y = dataManager.GetGaussianRandomNumber(5, 1.5); double z = dataManager.GetGaussianRandomNumber(5, 1.5); dataSeries3D.Append(x, y, z); } var pointMarker3D = new EllipsePointMarker3D() { FillColor = Color.FromArgb(0x77, 0xAD, 0xFF, 0x2F), Size = 5f }; var renderableSeries3D = new ScatterRenderableSeries3D() { PointMarker = pointMarker3D, DataSeries = dataSeries3D }; using (Surface.SuspendUpdates()) { Surface.XAxis = new NumericAxis3D() { GrowBy = new DoubleRange(0.1, 0.1) }; Surface.YAxis = new NumericAxis3D() { GrowBy = new DoubleRange(0.1, 0.1) }; Surface.ZAxis = new NumericAxis3D() { GrowBy = new DoubleRange(0.1, 0.1) }; Surface.Camera = new Camera3D() { Position = new Vector3(-350, 100, -350), Target = new Vector3(0, 50, 0) }; Surface.RenderableSeries.Add(renderableSeries3D); Surface.ChartModifiers = new ChartModifier3DCollection { new PinchZoomModifier3D(), new OrbitModifier3D(), new ZoomExtentsModifier3D() }; } } } }
38.173333
139
0.596228
[ "MIT" ]
ABTSoftware/SciChart.Xamarin.Examples
src/Xamarin.Examples.Demo.Droid/Fragments/Examples3D/CreatePointCloud3DChartFragment.cs
2,865
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Web.Models { public class BankAccountsModel { public string Status { get; set; } public List<BankAccountModel> BankAccounts { get; set; } } }
18.666667
64
0.692857
[ "MIT" ]
guvenbank/guvenbank.web
Web/Web/Models/BankAccountsModel.cs
282
C#
using System.Collections.ObjectModel; namespace FriendOrganizer.Model { public class FriendMeetings { public int FriendId { get; set; } public Friend Friend { get; set; } public int MeetingId { get; set; } public Meeting Meeting { get; set; } } }
22.538462
44
0.627986
[ "MIT" ]
pancholopez/EnterpriseWpf
FriendOrganizer/FriendOrganizer.Model/FriendMeetings.cs
295
C#
using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Z80.Kernel.Z80Assembler; namespace Z80.Kernel.Test.AssemblerInstructionTests { [TestClass] public class EquInstructionTests { [TestMethod] public void EquIsWorkingWithByte() { var assembler = new Z80Assembler.Z80Assembler(new List<string> { "ORG $3000", "SZAM EQU $FA" }); bool successBuildProgram = assembler.BuildProgram(); Assert.AreEqual(successBuildProgram, true); Assert.AreEqual(assembler.AssembledProgram.SymbolTable.Count == 2, true); Assert.AreEqual(assembler.AssembledProgram.SymbolTable["SZAM"].Type == SymbolType.Constant, true); Assert.AreEqual(assembler.AssembledProgram.SymbolTable["SZAM"].Value == 0xFA, true); } [TestMethod] public void EquIsWorkingWithAnotherSymbol() { var assembler = new Z80Assembler.Z80Assembler(new List<string> { "ORG $3000", "ELSO = $FA", "SZAM EQU ELSO" }); bool successBuildProgram = assembler.BuildProgram(); Assert.AreEqual(successBuildProgram, true); Assert.AreEqual(assembler.AssembledProgram.SymbolTable.Count == 3, true); Assert.AreEqual(assembler.AssembledProgram.SymbolTable["ELSO"].Type == SymbolType.Constant, true); Assert.AreEqual(assembler.AssembledProgram.SymbolTable["ELSO"].Value == 0xFA, true); Assert.AreEqual(assembler.AssembledProgram.SymbolTable["SZAM"].Type == SymbolType.Constant, true); Assert.AreEqual(assembler.AssembledProgram.SymbolTable["SZAM"].Value == 0xFA, true); } [TestMethod] public void EquIsWorkingWithByteAndWithEqualSymbol() { var assembler = new Z80Assembler.Z80Assembler(new List<string> { "ORG $3000", "SZAM = $FA" }); bool successBuildProgram = assembler.BuildProgram(); Assert.AreEqual(successBuildProgram, true); Assert.AreEqual(assembler.AssembledProgram.SymbolTable.Count == 2, true); Assert.AreEqual(assembler.AssembledProgram.SymbolTable["SZAM"].Type == SymbolType.Constant, true); Assert.AreEqual(assembler.AssembledProgram.SymbolTable["SZAM"].Value == 0xFA, true); } [TestMethod] public void EquIsWorkingCharacter() { var assembler = new Z80Assembler.Z80Assembler(new List<string> { "ORG $3000", "BETU EQU 'A'" }); bool successBuildProgram = assembler.BuildProgram(); Assert.AreEqual(successBuildProgram, true); Assert.AreEqual(assembler.AssembledProgram.SymbolTable.Count == 2, true); Assert.AreEqual(assembler.AssembledProgram.SymbolTable["BETU"].Type == SymbolType.Constant, true); Assert.AreEqual(assembler.AssembledProgram.SymbolTable["BETU"].Value == 0x41, true); } [TestMethod] public void EquIsWorkingWithWord() { var assembler = new Z80Assembler.Z80Assembler(new List<string> { "ORG $3000", "VIDEO EQU $FA66" }); bool successBuildProgram = assembler.BuildProgram(); Assert.AreEqual(successBuildProgram, true); Assert.AreEqual(assembler.AssembledProgram.SymbolTable.Count == 2, true); Assert.AreEqual(assembler.AssembledProgram.SymbolTable["VIDEO"].Type == SymbolType.Constant, true); Assert.AreEqual(assembler.AssembledProgram.SymbolTable["VIDEO"].Value == 0xFA66, true); } [TestMethod] public void EquDoesNotWorkWithLiteral() { var assembler = new Z80Assembler.Z80Assembler(new List<string> { "ORG $3000", "VIDEO EQU 'Literal'" }); bool successBuildProgram = assembler.BuildProgram(); Assert.AreEqual(successBuildProgram, false); Assert.AreEqual(assembler.AssembledProgram.SymbolTable.Count == 2, true); Assert.AreEqual(assembler.StatusMessage.StartsWith(@"Az EQU utasítás nem támogatja a megadott operandust"), true); } [TestMethod] public void EquWithReqursiveSymbolDoesNotWork() { var assembler = new Z80Assembler.Z80Assembler(new List<string> { "ORG $3000", "VIDEO EQU (VIDEO+12*sqrt(25))" }); bool successBuildProgram = assembler.BuildProgram(); Assert.AreEqual(successBuildProgram, false); Assert.AreEqual(assembler.AssembledProgram.SymbolTable.Count == 2, true); Assert.AreEqual(assembler.StatusMessage.StartsWith(@"Az EQU utasításban rekurzív szimbólum hivatkozás található"), true); } } }
54.635294
133
0.664298
[ "MIT" ]
konzolcowboy/TVCStudio
Z80.Kernel.Test/AssemblerInstructionTests/EquInstructionTests.cs
4,656
C#
using Entia.Core; using Entia.Experimental.Serialization; using Entia.Injectables; using Entia.Messages; using Entia.Modules; using Entia.Queryables; using Entia.Systems; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using Entia.Json; using Entia.Core.Documentation; using System.Runtime.CompilerServices; using System.Diagnostics; //[TypeDiagnostic("Poulah '{type}'", WithAnyFilters = Filters.Types, HaveNoneFilters = Filters.Class)] [TypeDiagnostic("Type '{type}' must implement 'ISwanson'", WithAnyFilters = Filters.Class, HaveAllImplementations = new[] { typeof(ISwanson) })] [TypeDiagnostic("Type '{type}' must have attribute 'Attribz'", WithAnyFilters = Filters.Class, HaveAllAttributes = new[] { typeof(Attribz) })] [TypeDiagnostic("Type '{type}' must be public.", WithAnyFilters = Filters.Class, HaveAllFilters = Filters.Public)] interface IKarl { } interface ISwanson { } class Attribz : Attribute { } class Karl : IKarl { } namespace Entia.Experiment { [Serializable] public struct Position : IComponent { public float X, Y, Z; } [Serializable] public struct Velocity : IComponent { public float X, Y, Z; } [Serializable] public struct Lifetime : IComponent { public float Remaining; } public struct Targetable : IComponent { } public struct Targeter : IComponent { public Entity? Current; public float Distance; } [Serializable] public struct Mass : IComponent { public float Value; } public struct Impure : IComponent { public Dictionary<int, List<DateTime>> Dates; } public struct IsDead : IComponent { } public struct IsInvincible : IComponent { } public struct Time : IResource { public float Current; public float Delta; } public struct Seed : IResource { public float Value; } public struct OnMove : IMessage { public Entity Entity; } public static class Program { static class Default<T> { static readonly T[] _array = new T[1]; public static ref T Value => ref _array[0]; } struct Jango : IRun, IInitialize, IDispose { double _value; public Jango(int value) { _value = value; } public void Initialize() => Console.WriteLine(nameof(Initialize)); public void Run() { for (var i = 0; i < 1_000_000; i++) _value += Math.Sqrt(i); } public void Dispose() => Console.WriteLine(nameof(Dispose)); } public static class Systems { public struct A : IRun { public Components<Position> P; public void Run() => throw new NotImplementedException(); } public struct B : IRun { public Emitter<OnMove> M; public Components<Position>.Read P; public void Run() => throw new NotImplementedException(); } public struct C : IRun { public Components<Position>.Read P; public Components<Velocity> V; public void Run() => throw new NotImplementedException(); } public struct D : IRun { public Components<Position>.Read P; public Components<Velocity>.Read V; public void Run() => throw new NotImplementedException(); } public struct E : IRun { public Components<Lifetime> L; public Components<Targetable>.Read T; public void Run() => throw new NotImplementedException(); } public struct F : IRun { public Components<Lifetime> L; public Components<Targetable> T; public void Run() => throw new NotImplementedException(); } public struct G : IRun { public Emitter<OnMove> M; public void Run() => throw new NotImplementedException(); } public struct H : IRun { public Emitter<OnMove> M; public void Run() => throw new NotImplementedException(); } public struct I : IRun { public Components<Position>.Read P; public Components<Lifetime>.Read L; public void Run() => throw new NotImplementedException(); } public struct J : IRun { public Reaction<OnMove> M; public Components<Position>.Read P; public void Run() => throw new NotImplementedException(); } public struct K : IRun { public Components<Targetable>.Read T; public void Run() => throw new NotImplementedException(); } } static void TypeMap() { var (super, sub) = (false, false); var map = new TypeMap<IEnumerable, string>(); map.Set<List<int>>("Poulah"); map.Set<List<string>>("Viarge"); map.Set<IList>("Jango"); var value1 = map.Get(typeof(List<>), out var success1, super, sub); var value2 = map.Get(typeof(IList), out var success2, super, sub); var value3 = map.Get(typeof(List<>), out var success3, super, sub); var value4 = map.Get<IList>(out var success4, super, sub); var value5 = map.Get(typeof(List<string>), out var success5, super, sub); var value6 = map.Get(typeof(IList<string>), out var success6, super, sub); var value7 = map.Get<IList<string>>(out var success7, super, sub); map.Remove<List<int>>(super, sub); var value8 = map.Get(typeof(IList), out var success8, super, sub); var value9 = map.Get<IList>(out var success9, super, sub); } public unsafe struct QueryC : Queryables.IQueryable { public Velocity* P2; public Position* P1; public Velocity* P3; public byte A1, A2, A3; public Position* P4; public ushort B1, B2; public Velocity* P5; public uint C1, C2, C3; public Position* P6; public Entity Entity; public Any<Read<Position>, Write<Velocity>> Any; public bool D1, D2, D3; public Velocity* P7; public Position* P8; } [Serializable] public class Cyclic { public Cyclic This; public Cyclic() { This = this; } } public struct BlittableA { public int A, B; } public struct NonBlittableA { public int A; public string B; } static void Serializer() { var world = new World(); byte[] bytes; bool success; var type = typeof(Program); success = world.Serialize(type, type.GetType(), out bytes); success = world.Deserialize(bytes, out type); var array = new int[] { 1, 2, 3, 4 }; success = world.Serialize(array, out bytes); success = world.Deserialize(bytes, out array); var cycle = new Cyclic(); cycle.This = cycle; success = world.Serialize(cycle, out bytes); success = world.Deserialize(bytes, out cycle); success = world.Serialize(null, typeof(object), out bytes); success = world.Deserialize(bytes, out object @null); var function = new Func<int>(() => 321); success = world.Serialize(function, out bytes); success = world.Deserialize(bytes, out function); var value = function(); var action = new Action(() => value += 1); success = world.Serialize(action, out bytes, default, action.Target); success = world.Deserialize(bytes, out action, default, action.Target); action(); var reaction = new Entia.Modules.Message.Reaction<OnCreate>(); success = world.Serialize(reaction, out bytes); success = world.Deserialize(bytes, out reaction); var emitter = new Entia.Modules.Message.Emitter<OnCreate>(); success = world.Serialize(emitter, out bytes); success = world.Deserialize(bytes, out emitter); var entities = world.Entities(); for (int i = 0; i < 100; i++) entities.Create(); success = world.Serialize(entities, out bytes); success = world.Deserialize(bytes, out entities); success = world.Serialize(world, out bytes); success = world.Deserialize(bytes, out world); success = world.Serialize(new NonBlittableA { A = 1, B = "Boba" }, out bytes); success = world.Deserialize(bytes, out BlittableA ba); success = world.Serialize(new BlittableA { A = 1, B = 2 }, out bytes); success = world.Deserialize(bytes, out NonBlittableA nba); } static void CompareSerializers() { const int size = 10; var value = new Dictionary<object, object>(); value[1] = "2"; value["3"] = 4; value[DateTime.Now] = TimeSpan.MaxValue; value[TimeSpan.MinValue] = DateTime.UtcNow; value[new object()] = value; value[new Position[size]] = new Velocity[size]; value[new List<Mass>(new Mass[size])] = new List<Lifetime>(new Lifetime[size]); var cyclic = new Cyclic(); cyclic.This = new Cyclic { This = new Cyclic { This = cyclic } }; value[cyclic] = cyclic.This; value[new string[] { "Boba", "Fett", "Jango" }] = new byte[512]; var values = new Dictionary<Position, Velocity>(); for (int i = 0; i < size; i++) values[new Position { X = i }] = new Velocity { Y = 1 }; value[(1, "2", byte.MaxValue, short.MinValue)] = (values, new List<Position>(new Position[size]), new List<Velocity>(new Velocity[size])); CompareSerializers(value); } static void CompareSerializers<T>(T value) { var world1 = new World(); var world2 = new World(); world2.Container.Add(new Experimental.Serializers.BlittableObject<Position>()); world2.Container.Add(new Experimental.Serializers.BlittableArray<Position>()); world2.Container.Add(new Experimental.Serializers.BlittableObject<Velocity>()); world2.Container.Add(new Experimental.Serializers.BlittableArray<Velocity>()); world2.Container.Add(new Experimental.Serializers.BlittableObject<Mass>()); world2.Container.Add(new Experimental.Serializers.BlittableArray<Mass>()); world2.Container.Add(new Experimental.Serializers.BlittableObject<Lifetime>()); world2.Container.Add(new Experimental.Serializers.BlittableArray<Lifetime>()); world1.Serialize(value, out var bytes1, Options.Blittable); world1.Serialize(value, out var bytes2); world2.Serialize(value, out var bytes3); byte[] bytes4; var binary = new BinaryFormatter(); using (var stream = new MemoryStream()) { binary.Serialize(stream, value); bytes4 = stream.ToArray(); } void BlittableSerialize() => world1.Serialize(value, out var a, Options.Blittable); void BlittableDeserialize() => world1.Deserialize(bytes1, out T a, Options.Blittable); void NoneSerialize() => world1.Serialize(value, out var a); void NoneDeserialize() => world1.Deserialize(bytes2, out T a); void ManualSerialize() => world2.Serialize(value, out var a); void ManualDeserialize() => world2.Deserialize(bytes3, out T a); void BinarySerialize() { using (var stream = new MemoryStream()) { binary.Serialize(stream, value); stream.ToArray(); } } void BinaryDeserialize() { using (var stream = new MemoryStream(bytes4)) binary.Deserialize(stream); } while (true) { Test.Measure(BlittableSerialize, new Action[] { NoneSerialize, ManualSerialize, BinarySerialize }, 1000); Test.Measure(BlittableDeserialize, new Action[] { NoneDeserialize, ManualDeserialize, BinaryDeserialize }, 1000); Console.WriteLine(); } } static void TestFamilies() { var world = new World(); var entities = world.Entities(); var families = world.Families(); var parent = entities.Create(); var middle = entities.Create(); var child = entities.Create(); var success1 = families.Adopt(parent, middle); var success2 = families.Adopt(middle, child); var success3 = families.Adopt(child, parent); var family = families.Family(parent).ToArray(); var descendants = families.Descendants(parent).ToArray(); var ancestors = families.Ancestors(child).ToArray(); } unsafe static void Main() { // LockTests.Test(); // SuperDuperUnsafe(); // VeryUnsafe(); // TestFamilies(); // Serializer(); // TypeMapTest.Benchmark(); // CompareSerializers(); V4.Test.Do(); // - Iterates once. Babylon2.Run((in Time time) => { }); // Generated names in 'Inject<T>' and 'Query<T>' will use tuple names if any are provided, otherwise // type names will be used. If conflict arise, generated name will try to specify the type by adding // type argument names // Babylon2.Inject((Inject<(Time, OnAdd<Position>)> inject) => // Babylon2.Run((Query<Position> query) => // { // // while (inject.OnAdd(out var message)) // // { // // ref var time = ref inject.Time; // // query.Has(entity); // // query.TryGet(message.Entity, out var item); // // } // })); Babylon2.Run(( in Time time, Query<(Entity, Position)> query0, Query<(Entity, Position, Velocity)> query1, Query<(Entity, Position, Velocity, Mass?)> query2) => { foreach (var item1 in query1) { item1.Position.X++; foreach (var item2 in query2) { ref var mass = ref item2.Mass(out var hasMass); if (hasMass) { } } } } //, Filter.Not<IsInvincible>() ); // - Iterates on each entity. // - May run on any thread if analyzed as safe. Babylon2.Run( // Filtering with entity? (in Time time, V4.Entity<(Targetable, Not<IsInvincible>)> entity, ref Position a, in Velocity b) => { a.X += b.X * time.Delta; } // Filter.Not<IsInvincible>() // Additional filtering. ); // - Iterates on each chunks. // - May run on any thread if analyzed as safe. // - Allows for SIMD operations. Babylon2.Run((in Time time, Span<V4.Entity<Not<IsInvincible>>> entity, Span<Position> a, Span<Velocity> b) => { }); // Probably a bad idea to give direct access to arrays?... Babylon2.Run((in Time time, V4.Entity<Not<IsInvincible>> entity, Position[] a, Velocity[] b) => { }); // - Iterates on each message received. // - Will skip frames where no message has been emitted. Babylon2.Run( (in Time time, in OnAdd<Position> onAdd, Components<Position> positions) => { } //, Filter.Not<IsInvincible>() ); // - Iterates on each entity for each message received. Babylon2.Run( (in Time time, in OnAdd<Position> onAdd, Entity entity, ref Position a, in Velocity b) => { } //, Filter.Not<IsInvincible>() ); // Babylon2.Run(default(Action)); // Babylon2.Run(default(Func<int>)); // Babylon2.RunAction(() => { }); // Babylon2.RunFunc(() => 123); // Babylon2.RunPhase(default); } public readonly struct BobaData : ISystem { public readonly AllEntities Entities; public readonly AllComponents Components; public readonly Components<Position> Positions; public readonly Components<IsDead> IsDead; public readonly Emitter<OnMove> OnMove; public readonly Receiver<OnMove> OnMove2; [None(typeof(IsDead))] public readonly Group<Read<Velocity>> Group; public readonly FettData Fett; public readonly Reaction<OnMove> OnMove3; public void Run() { } } public readonly struct FettData : ISystem { public readonly AllEntities Entities; public readonly AllComponents Components; public readonly Components<Position> Positions; public readonly Components<IsDead> IsDead; public readonly Emitter<OnMove> OnMove; public readonly Receiver<OnMove> OnMove2; [None(typeof(IsDead))] public readonly Group<Write<Position>> Group; public void Run() => throw new NotImplementedException(); } } public struct Inject<T> { } public struct Query<T> { } public struct Not<T> { } public sealed class Chunk { public int Count; } public static class QueryExtensions { public ref struct Enumerator0 { public Item0 Current => _item; Item0 _item; int _index; int _count; readonly (Chunk chunk, (Entity[], Position[], Velocity[], Mass[]) stores)[] _chunks; public Enumerator0(int index, (Chunk, (Entity[], Position[], Velocity[], Mass[]))[] chunks) { _item = default; _index = -1; _count = 0; _chunks = chunks; } public bool MoveNext() { while (true) { if (++_item.Index < _count) return true; else if (++_index < _chunks.Length) { ref var chunk = ref _chunks[_index]; _item = new Item0(chunk.stores); _count = chunk.chunk.Count; } else return false; } } } public ref struct Item0 { public Entity Entity => _store0[Index]; public ref Position Position => ref _store1[Index]; public ref Velocity Velocity => ref _store2[Index]; public ref Mass Mass(out bool has) => ref (has = _has3) ? ref _store3[Index] : ref Dummy<Mass>.Value; public bool TryMass(out Mass mass) { mass = Mass(out var has); return has; } internal int Index; readonly Entity[] _store0; readonly Position[] _store1; readonly Velocity[] _store2; readonly Mass[] _store3; readonly bool _has3; internal Item0(in (Entity[], Position[], Velocity[], Mass[]) stores) { Index = -1; (_store0, _store1, _store2, _store3) = stores; _has3 = _store3 is not null; } } public ref struct Enumerator1 { public Item1 Current => throw null; public bool MoveNext() => throw null; } public ref struct Item1 { public Entity Entity => _entities[Index]; public ref Position Position => ref _store0[Index]; public ref Velocity Velocity => ref _store1[Index]; internal int Index; readonly Entity[] _entities; readonly Position[] _store0; readonly Velocity[] _store1; public Item1(int index, Entity[] entities, Position[] store0, Velocity[] store1) { Index = index; _entities = entities; _store0 = store0; _store1 = store1; } } public static Enumerator0 GetEnumerator(this Query<(Entity, Position, Velocity, Mass?)> query) => throw null; public static Enumerator1 GetEnumerator(this Query<(Entity, Position, Velocity)> query) => throw null; } }
40.269663
150
0.542597
[ "MIT" ]
Magicolo/Entia
Entia.Experiment/Program.cs
21,506
C#
////******************************************************************** // <copyright file="FindAllCallCompletedEventArgs.cs" company="Intuit"> /******************************************************************************* * Copyright 2016 Intuit * * 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. *******************************************************************************/ // <summary>This file contains SdkException.</summary> // <summary>This file contains logic for REST request handler.</summary> ////******************************************************************** namespace Intuit.Ipp.Core { using System; using System.Collections.Generic; using Intuit.Ipp.Data; using Intuit.Ipp.Exception; /// <summary> /// Event argument is class used to communicate after FindAll operation completed. /// </summary> public partial class FindAllCallCompletedEventArgs : EventArgs { /// <summary> /// Initializes a new instance of the FindAllCallCompletedEventArgs class. /// </summary> public FindAllCallCompletedEventArgs() { this.Entities = new List<IEntity>(); } /// <summary> /// Gets or sets Entities from the result. /// </summary> public IList<IEntity> Entities { get; set; } /// <summary> /// Gets or sets Ids Exception. /// </summary> public IdsException Error { get; set; } } }
33.622951
86
0.540712
[ "Apache-2.0" ]
ANSIOS-X9SAN-iOS-XR/QuickBooks-V3-DotNET-SDK
IPPDotNetDevKitCSV3/Code/Intuit.Ipp.Core/RestCalls/EventArgs/FindAllCallCompletedEventArgs.cs
2,053
C#
using System; namespace Alex.GuiDebugger.Models { public class ElementTreeItemProperty { public Guid ElementId { get; } public string Name { get; } public Type Type { get; } public object Value { get; set; } public ElementTreeItemProperty() { } public ElementTreeItemProperty(Guid elementId, string name, Type type, object value) : this() { ElementId = elementId; Name = name; Type = type; Value = value; } } }
19.2
101
0.527778
[ "MPL-2.0" ]
TheBlackPlague/Alex
src/Tools/GuiDebugger/Alex.GuiDebugger/Models/ElementTreeItemProperty.cs
578
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using CryptoExchange.Net.Interfaces; using CryptoExchange.Net.Objects; using Kucoin.Net.Objects; using Kucoin.Net.Objects.Spot; namespace Kucoin.Net.Interfaces { /// <summary> /// Interface for the Kucoin client /// </summary> public interface IKucoinClientSpot : IRestClient { /// <summary> /// Set the API key and secret /// </summary> /// <param name="apiKey">The api key</param> /// <param name="apiSecret">The api secret</param> /// <param name="apiPass">The api passphrase</param> void SetApiCredentials(string apiKey, string apiSecret, string apiPass); /// <summary> /// Gets the server time /// </summary> /// <returns>The time of the server</returns> Task<WebCallResult<DateTime>> GetServerTimeAsync(CancellationToken ct = default); /// <summary> /// Gets a list of symbols supported by the server /// </summary> /// <param name="market">Only get symbols for a specific market, for example 'ALTS'</param> /// <param name="ct">Cancellation token</param> /// <returns>List of symbols</returns> Task<WebCallResult<IEnumerable<KucoinSymbol>>> GetSymbolsAsync(string? market = null, CancellationToken ct = default); /// <summary> /// Gets ticker info of a symbol /// </summary> /// <param name="symbol">The symbol to get info for</param> /// <param name="ct">Cancellation token</param> /// <returns>Ticker info</returns> Task<WebCallResult<KucoinTick>> GetTickerAsync(string symbol, CancellationToken ct = default); /// <summary> /// Gets the ticker for all trading pairs /// </summary> /// <param name="ct">Cancellation token</param> /// <returns>List of tickers</returns> Task<WebCallResult<KucoinTicks>> GetTickersAsync(CancellationToken ct = default); /// <summary> /// Gets the 24 hour stats of a symbol /// </summary> /// <param name="symbol">The symbol to get stats for</param> /// <param name="ct">Cancellation token</param> /// <returns>24 hour stats</returns> Task<WebCallResult<Kucoin24HourStat>> Get24HourStatsAsync(string symbol, CancellationToken ct = default); /// <summary> /// Gets a list of supported markets /// </summary> /// <param name="ct">Cancellation token</param> /// <returns>List of markets</returns> Task<WebCallResult<IEnumerable<string>>> GetMarketsAsync(CancellationToken ct = default); /// <summary> /// Get a partial aggregated order book for a symbol. Orders for the same price are combined and amount results are limited. /// </summary> /// <param name="symbol">The symbol to get order book for</param> /// <param name="limit">The limit of results (20 / 100)</param> /// <param name="ct">Cancellation token</param> /// <returns>Partial aggregated order book</returns> Task<WebCallResult<KucoinOrderBook>> GetAggregatedPartialOrderBookAsync(string symbol, int limit, CancellationToken ct = default); /// <summary> /// Get a full aggregated order book for a symbol. Orders for the same price are combined. /// </summary> /// <param name="symbol">The symbol to get order book for</param> /// <param name="ct">Cancellation token</param> /// <returns>Full aggregated order book</returns> Task<WebCallResult<KucoinOrderBook>> GetAggregatedFullOrderBookAsync(string symbol, CancellationToken ct = default); /// <summary> /// Get a full order book for a symbol /// </summary> /// <param name="symbol">The symbol to get order book for</param> /// <param name="ct">Cancellation token</param> /// <returns>Full order book</returns> Task<WebCallResult<KucoinFullOrderBook>> GetOrderBookAsync(string symbol, CancellationToken ct = default); /// <summary> /// Gets the recent trade history for a symbol /// </summary> /// <param name="symbol">The symbol to get trade history for</param> /// <param name="ct">Cancellation token</param> /// <returns>List of trades for the symbol</returns> Task<WebCallResult<IEnumerable<KucoinTrade>>> GetTradeHistoryAsync(string symbol, CancellationToken ct = default); /// <summary> /// Get kline data for a symbol /// </summary> /// <param name="symbol">The symbol to get klines for</param> /// <param name="interval">The interval of a kline</param> /// <param name="startTime">The start time of the data</param> /// <param name="endTime">The end time of the data</param> /// <param name="ct">Cancellation token</param> /// <returns>List of klines</returns> Task<WebCallResult<IEnumerable<KucoinKline>>> GetKlinesAsync(string symbol, KucoinKlineInterval interval, DateTime? startTime = null, DateTime? endTime = null, CancellationToken ct = default); /// <summary> /// Gets a list of supported currencies /// </summary> /// <returns>List of currencies</returns> Task<WebCallResult<IEnumerable<KucoinCurrency>>> GetCurrenciesAsync(CancellationToken ct = default); /// <summary> /// Get info on a specific currency /// </summary> /// <param name="currency">The currency to get</param> /// <param name="ct">Cancellation token</param> /// <returns>Currency info</returns> Task<WebCallResult<KucoinCurrency>> GetCurrencyAsync(string currency, CancellationToken ct = default); /// <summary> /// Gets a list of prices for all /// </summary> /// <param name="fiatBase">The three letter code of the fiat to convert to. Defaults to USD</param> /// <param name="currencies">The currencies to get price for. Defaults to all</param> /// <param name="ct">Cancellation token</param> /// <returns>List of prices</returns> Task<WebCallResult<Dictionary<string, decimal>>> GetFiatPricesAsync(string? fiatBase = null, IEnumerable<string>? currencies = null, CancellationToken ct = default); /// <summary> /// Gets a list of sub users /// </summary> /// <param name="ct">Cancellation token</param> /// <returns>List of sub users</returns> Task<WebCallResult<IEnumerable<KucoinSubUser>>> GetUserInfoAsync(CancellationToken ct = default); /// <summary> /// Gets a list of accounts /// </summary> /// <param name="currency">Get the accounts for a specific currency</param> /// <param name="accountType">Filter on type of account</param> /// <param name="ct">Cancellation token</param> /// <returns>List of accounts</returns> Task<WebCallResult<IEnumerable<KucoinAccount>>> GetAccountsAsync(string? currency = null, KucoinAccountType? accountType = null, CancellationToken ct = default); /// <summary> /// Get a specific account /// </summary> /// <param name="accountId">The id of the account to get</param> /// <param name="ct">Cancellation token</param> /// <returns>Account info</returns> Task<WebCallResult<KucoinAccountSingle>> GetAccountAsync(string accountId, CancellationToken ct = default); /// <summary> /// Create a new account /// </summary> /// <param name="type">The type of the account</param> /// <param name="currency">The currency of the account</param> /// <param name="ct">Cancellation token</param> /// <returns>The id of the account</returns> Task<WebCallResult<KucoinNewAccount>> CreateAccountAsync(KucoinAccountType type, string currency, CancellationToken ct = default); /// <summary> /// Get the basic user fees /// </summary> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<KucoinUserFee>> GetBasicUserFeeAsync(CancellationToken ct = default); /// <summary> /// Get the trading fees for symbols /// </summary> /// <param name="symbol">The symbol to retrieve fees for</param> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<KucoinTradeFee[]>> GetSymbolTradingFeesAsync(string symbol, CancellationToken ct = default); /// <summary> /// Get the trading fees for symbols /// </summary> /// <param name="symbols">The symbols to retrieve fees for</param> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<KucoinTradeFee[]>> GetSymbolTradingFeesAsync(IEnumerable<string> symbols, CancellationToken ct = default); /// <summary> /// Gets a list of account activity /// </summary> /// <param name="accountId">The account id to get the activities for</param> /// <param name="startTime">Filter by start time</param> /// <param name="endTime">Filter by end time</param> /// <param name="currentPage">The page to retrieve</param> /// <param name="pageSize">The amount of results per page</param> /// <param name="ct">Cancellation token</param> /// <returns>Info on account activity</returns> [Obsolete("Prefers GetAccountLedgersAsync")] Task<WebCallResult<KucoinPaginated<KucoinAccountActivity>>> GetAccountLedgerAsync(string accountId, DateTime? startTime = null, DateTime? endTime = null, int? currentPage = null, int? pageSize = null, CancellationToken ct = default); /// <summary> /// Gets a list of account activity /// </summary> /// <param name="currency">The currency to retrieve activity or null</param> /// <param name="startTime">Filter by start time</param> /// <param name="direction">Side</param> /// <param name="bizType">Business type</param> /// <param name="endTime">Filter by end time</param> /// <param name="currentPage">The page to retrieve</param> /// <param name="pageSize">The amount of results per page</param> /// <param name="ct">Cancellation token</param> /// <returns>Info on account activity</returns> Task<WebCallResult<KucoinPaginated<KucoinAccountActivity>>> GetAccountLedgersAsync(string? currency = null, KucoinAccountDirection? direction = null, KucoinBizType? bizType = null, DateTime? startTime = null, DateTime? endTime = null, int? currentPage = null, int? pageSize = null, CancellationToken ct = default); /// <summary> /// Gets a transferable balance of a specified account. /// </summary> /// <param name="currency">Get the accounts for a specific currency</param> /// <param name="accountType">Filter on type of account</param> /// <param name="ct">Cancellation token</param> /// <returns>Info on transferable account balance</returns> Task<WebCallResult<KucoinTransferableAccount>> GetTransferableAsync(string currency, KucoinAccountType accountType, CancellationToken ct = default); /// <summary> /// Transfers assets between the accounts of a user. /// </summary> /// <param name="currency">Get the accounts for a specific currency</param> /// <param name="from">The type of the account</param> /// <param name="to">The type of the account</param> /// <param name="quantity">The quantity to transfer</param> /// <param name="clientOrderId">Client order id</param> /// <param name="ct">Cancellation token</param> /// <returns>The order ID of a funds transfer</returns> Task<WebCallResult<KucoinInnerTransfer>> InnerTransferAsync(string currency, KucoinAccountType from, KucoinAccountType to, decimal quantity, string? clientOrderId = null, CancellationToken ct = default); /// <summary> /// Gets hold information /// </summary> /// <param name="accountId">The account to get info for</param> /// <param name="currentPage">The page to retrieve</param> /// <param name="pageSize">The amount of results per page</param> /// <param name="ct">Cancellation token</param> /// <returns>Info on current holds</returns> Task<WebCallResult<KucoinPaginated<KucoinHold>>> GetHoldsAsync(string accountId, int? currentPage = null, int? pageSize = null, CancellationToken ct = default); /// <summary> /// Gets a list of deposits /// </summary> /// <param name="currency">Filter list by currency</param> /// <param name="startTime">Filter list by start time</param> /// <param name="endTime">Filter list by end time</param> /// <param name="status">Filter list by deposit status</param> /// <param name="currentPage">The page to retrieve</param> /// <param name="pageSize">The amount of results per page</param> /// <param name="ct">Cancellation token</param> /// <returns>List of deposits</returns> Task<WebCallResult<KucoinPaginated<KucoinDeposit>>> GetDepositsAsync(string? currency = null, DateTime? startTime = null, DateTime? endTime = null, KucoinDepositStatus? status = null, int? currentPage = null, int? pageSize = null, CancellationToken ct = default); /// <summary> /// Gets a list of historical deposits /// </summary> /// <param name="currency">Filter list by currency</param> /// <param name="startTime">Filter list by start time</param> /// <param name="endTime">Filter list by end time</param> /// <param name="status">Filter list by deposit status</param> /// <param name="currentPage">The page to retrieve</param> /// <param name="pageSize">The amount of results per page</param> /// <param name="ct">Cancellation token</param> /// <returns>List of historical deposits</returns> Task<WebCallResult<KucoinPaginated<KucoinHistoricalDeposit>>> GetHistoricalDepositsAsync(string? currency = null, DateTime? startTime = null, DateTime? endTime = null, KucoinDepositStatus? status = null, int? currentPage = null, int? pageSize = null, CancellationToken ct = default); /// <summary> /// Gets the deposit address for a currency /// </summary> /// <param name="currency">The currency to get the address for</param> /// <param name="chain">The chain to get the address for</param> /// <param name="ct">Cancellation token</param> /// <returns>The deposit address for the currency</returns> Task<WebCallResult<KucoinDepositAddress>> GetDepositAddressAsync(string currency, string? chain = null, CancellationToken ct = default); /// <summary> /// Gets the deposit addresses for a currency /// </summary> /// <param name="currency">The currency to get the address for</param> /// <param name="ct">Cancellation token</param> /// <returns>The deposit address for the currency</returns> Task<WebCallResult<IEnumerable<KucoinDepositAddress>>> GetDepositAddressesAsync(string currency, CancellationToken ct = default); /// <summary> /// Creates a new deposit address for a currency /// </summary> /// <param name="currency">The currency to create the address for</param> /// <param name="chain">The currency to create the address for</param> /// <param name="ct">Cancellation token</param> /// <returns>The address that was created</returns> Task<WebCallResult<KucoinDepositAddress>> CreateDepositAddressAsync(string currency, string? chain = null, CancellationToken ct = default); /// <summary> /// Gets a list of withdrawals /// </summary> /// <param name="currency">Filter list by currency</param> /// <param name="startTime">Filter list by start time</param> /// <param name="endTime">Filter list by end time</param> /// <param name="status">Filter list by deposit status</param> /// <param name="currentPage">The page to retrieve</param> /// <param name="pageSize">The amount of results per page</param> /// <param name="ct">Cancellation token</param> /// <returns>List of withdrawals</returns> Task<WebCallResult<KucoinPaginated<KucoinWithdrawal>>> GetWithdrawalsAsync(string? currency = null, DateTime? startTime = null, DateTime? endTime = null, KucoinWithdrawalStatus? status = null, int? currentPage = null, int? pageSize = null, CancellationToken ct = default); /// <summary> /// Gets a list of historical withdrawals /// </summary> /// <param name="currency">Filter list by currency</param> /// <param name="startTime">Filter list by start time</param> /// <param name="endTime">Filter list by end time</param> /// <param name="status">Filter list by deposit status</param> /// <param name="currentPage">The page to retrieve</param> /// <param name="pageSize">The amount of results per page</param> /// <param name="ct">Cancellation token</param> /// <returns>List of historical withdrawals</returns> Task<WebCallResult<KucoinPaginated<KucoinHistoricalWithdrawal>>> GetHistoricalWithdrawalsAsync(string? currency = null, DateTime? startTime = null, DateTime? endTime = null, KucoinWithdrawalStatus? status = null, int? currentPage = null, int? pageSize = null, CancellationToken ct = default); /// <summary> /// Get the withdrawal quota for a currency /// </summary> /// <param name="currency">The currency to get the quota for</param> /// <param name="ct">Cancellation token</param> /// <returns>Quota info</returns> Task<WebCallResult<KucoinWithdrawalQuota>> GetWithdrawalQuotasAsync(string currency, CancellationToken ct = default); /// <summary> /// Withdraw a currency to an address /// </summary> /// <param name="currency">The currency to withdraw</param> /// <param name="toAddress">The address to withdraw to</param> /// <param name="quantity">The quantity to withdraw</param> /// <param name="memo">The note that is left on the withdrawal address. When you withdraw from KuCoin to other platforms, you need to fill in memo(tag). If you don't fill in memo(tag), your withdrawal may not be available.</param> /// <param name="isInner">Internal withdrawal or not. Default false.</param> /// <param name="remark">Remark for the withdrawal</param> /// <param name="chain">The chain name of currency, e.g. The available value for USDT are OMNI, ERC20, TRC20, default is OMNI. This only apply for multi-chain currency, and there is no need for single chain currency.</param> /// <param name="ct">Cancellation token</param> /// <returns>Id of the withdrawal</returns> Task<WebCallResult<KucoinNewWithdrawal>> WithdrawAsync(string currency, string toAddress, decimal quantity, string? memo = null, bool isInner = false, string? remark = null, string? chain = null, CancellationToken ct = default); /// <summary> /// Cancel a withdrawal /// </summary> /// <param name="withdrawalId">The id of the withdrawal to cancel</param> /// <param name="ct">Cancellation token</param> /// <returns>Null</returns> Task<WebCallResult<object>> CancelWithdrawalAsync(string withdrawalId, CancellationToken ct = default); /// <summary> /// Places an order /// </summary> /// <param name="symbol">The symbol the order is for</param> /// <param name="side">The side of the order</param> /// <param name="type">The type of the order</param> /// <param name="price">The price of the order. Only valid for limit orders.</param> /// <param name="quantity">The quantity of the order</param> /// <param name="funds">The funds to use for the order. Only valid for market orders. If used, quantity needs to be empty</param> /// <param name="timeInForce">The time the order is in force</param> /// <param name="cancelAfter">Cancel after a time</param> /// <param name="postOnly">Order is post only</param> /// <param name="hidden">Order is hidden</param> /// <param name="iceBerg">Order is an iceberg order</param> /// <param name="visibleIceBergSize">The maximum visible size of an iceberg order</param> /// <param name="remark">Remark on the order</param> /// <param name="selfTradePrevention">Self trade prevention setting</param> /// <param name="clientOrderId">Client order id</param> /// <param name="ct">Cancellation token</param> /// <returns>The id of the new order</returns> Task<WebCallResult<KucoinNewOrder>> PlaceOrderAsync( string symbol, string clientOrderId, KucoinOrderSide side, KucoinNewOrderType type, decimal? price = null, decimal? quantity = null, decimal? funds = null, KucoinTimeInForce? timeInForce = null, TimeSpan? cancelAfter = null, bool? postOnly = null, bool? hidden = null, bool? iceBerg = null, decimal? visibleIceBergSize = null, string? remark = null, KucoinSelfTradePrevention? selfTradePrevention = null, CancellationToken ct = default); /// <summary> /// Places a margin order /// </summary> /// <param name="clientOrderId">Client order id</param> /// <param name="side">The side((buy or sell) of the order</param> /// <param name="symbol">The symbol the order is for</param> /// <param name="type">The type of the order</param> /// <param name="remark">Remark on the order</param> /// <param name="selfTradePrevention">Self trade prevention setting</param> /// <param name="marginMode">The type of trading, including 'cross' and 'isolated'</param> /// <param name="autoBorrow">Auto-borrow to place order.</param> /// <param name="price">The price of the order. Only valid for limit orders.</param> /// <param name="quantity">amount of base currency to buy or sell of the order</param> /// <param name="timeInForce">The time the order is in force</param> /// <param name="cancelAfter">Cancel after a time</param> /// <param name="postOnly">Order is post only</param> /// <param name="hidden">Order is hidden</param> /// <param name="iceBerg">Order is an iceberg order</param> /// <param name="visibleIceBergSize">The maximum visible size of an iceberg order</param> /// <param name="funds">The funds to use for the order. Only valid for market orders. If used, quantity needs to be empty</param> /// <param name="ct">Cancellation token</param> /// <returns>The id of the new order</returns> Task<WebCallResult<KucoinNewOrder>> PlaceMarginOrderAsync( string symbol, KucoinOrderSide side, KucoinNewOrderType type, decimal? price = null, decimal? quantity = null, decimal? funds = null, KucoinTimeInForce? timeInForce = null, TimeSpan? cancelAfter = null, bool? postOnly = null, bool? hidden = null, bool? iceBerg = null, decimal? visibleIceBergSize = null, string? remark = null, KucoinMarginMode? marginMode = null, bool? autoBorrow = null, KucoinSelfTradePrevention? selfTradePrevention = null, string? clientOrderId = null, CancellationToken ct = default); /// <summary> /// Cancel an order /// </summary> /// <param name="orderId">The id of the order to cancel</param> /// <param name="ct">Cancellation token</param> /// <returns>List of cancelled orders</returns> Task<WebCallResult<KucoinCancelledOrders>> CancelOrderAsync(string orderId, CancellationToken ct = default); /// <summary> /// Cancel an order /// </summary> /// <param name="clientOrderId">The client order id of the order to cancel</param> /// <param name="ct">Cancellation token</param> /// <returns>List of cancelled orders</returns> Task<WebCallResult<KucoinCancelledOrder>> CancelOrderByClientOrderIdAsync(string clientOrderId, CancellationToken ct = default); /// <summary> /// Cancel all open orders /// </summary> /// <param name="symbol">Only cancel orders for this symbol</param> /// <param name="ct">Cancellation token</param> /// <returns>List of cancelled orders</returns> Task<WebCallResult<KucoinCancelledOrders>> CancelAllOrdersAsync(string? symbol = null, CancellationToken ct = default); /// <summary> /// Gets a list of orders /// </summary> /// <param name="symbol">Filter list by symbol</param> /// <param name="type">Filter list by order type</param> /// <param name="side">Filter list by order side</param> /// <param name="startTime">Filter list by start time</param> /// <param name="endTime">Filter list by end time</param> /// <param name="status">Filter list by order status. Defaults to done</param> /// <param name="currentPage">The page to retrieve</param> /// <param name="pageSize">The amount of results per page</param> /// <param name="ct">Cancellation token</param> /// <returns>List of orders</returns> Task<WebCallResult<KucoinPaginated<KucoinOrder>>> GetOrdersAsync(string? symbol = null, KucoinOrderSide? side = null, KucoinOrderType? type = null, DateTime? startTime = null, DateTime? endTime = null, KucoinOrderStatus? status = null, int? currentPage = null, int? pageSize = null, CancellationToken ct = default); /// <summary> /// Gets a list of max 1000 orders in the last 24 hours /// </summary> /// <param name="ct">Cancellation token</param> /// <returns>List of orders</returns> Task<WebCallResult<IEnumerable<KucoinOrder>>> GetRecentOrdersAsync(CancellationToken ct = default); /// <summary> /// Get info on a specific order /// </summary> /// <param name="clientOrderId">The client order id of the order</param> /// <param name="ct">Cancellation token</param> /// <returns>Order info</returns> Task<WebCallResult<KucoinOrder>> GetOrderByClientOrderIdAsync(string clientOrderId, CancellationToken ct = default); /// <summary> /// Get info on a specific order /// </summary> /// <param name="orderId">The id of the order</param> /// <param name="ct">Cancellation token</param> /// <returns>Order info</returns> Task<WebCallResult<KucoinOrder>> GetOrderAsync(string orderId, CancellationToken ct = default); /// <summary> /// Gets a list of historical orders /// </summary> /// <param name="symbol">Filter list by symbol</param> /// <param name="side">Filter list by order side</param> /// <param name="startTime">Filter list by start time</param> /// <param name="endTime">Filter list by end time</param> /// <param name="currentPage">The page to retrieve</param> /// <param name="pageSize">The amount of results per page</param> /// <param name="ct">Cancellation token</param> /// <returns>List of historical orders</returns> Task<WebCallResult<KucoinPaginated<KucoinHistoricalOrder>>> GetHistoricalOrdersAsync(string? symbol = null, KucoinOrderSide? side = null, DateTime? startTime = null, DateTime? endTime = null, int? currentPage = null, int? pageSize = null, CancellationToken ct = default); /// <summary> /// Gets a list of fills /// </summary> /// <param name="symbol">Filter list by symbol</param> /// <param name="type">Filter list by order type</param> /// <param name="side">Filter list by order side</param> /// <param name="startTime">Filter list by start time</param> /// <param name="endTime">Filter list by end time</param> /// <param name="orderId">Filter list by order id</param> /// <param name="currentPage">The page to retrieve</param> /// <param name="pageSize">The amount of results per page</param> /// <param name="ct">Cancellation token</param> /// <returns>List of fills</returns> Task<WebCallResult<KucoinPaginated<KucoinFill>>> GetUserTradesAsync(string? symbol = null, KucoinOrderSide? side = null, KucoinOrderType? type = null, DateTime? startTime = null, DateTime? endTime = null, string? orderId = null, int? currentPage = null, int? pageSize = null, CancellationToken ct = default); /// <summary> /// Gets a list of max 1000 fills in the last 24 hours /// </summary> /// <param name="ct">Cancellation token</param> /// <returns>List of fills</returns> Task<WebCallResult<IEnumerable<KucoinFill>>> GetRecentUserTradesAsync(CancellationToken ct = default); /// <summary> /// Place a new stop order /// </summary> /// <param name="symbol">The symbol the order is for</param> /// <param name="orderSide">The side of the order</param> /// <param name="orderType">The type of the order</param> /// <param name="price">The price of the order. Only valid for limit orders.</param> /// <param name="quantity">The quantity of the order</param> /// <param name="quoteQuantity">The funds to use for the order. Only valid for market orders. If used, quantity needs to be empty</param> /// <param name="timeInForce">The time the order is in force</param> /// <param name="cancelAfter">Cancel after a time</param> /// <param name="postOnly">Order is post only</param> /// <param name="hidden">Order is hidden</param> /// <param name="iceberg">Order is an iceberg order</param> /// <param name="visibleSize">The maximum visible size of an iceberg order</param> /// <param name="remark">Remark on the order</param> /// <param name="selfTradePrevention">Self trade prevention setting</param> /// <param name="clientOrderId">Client order id</param> /// <param name="stopCondition">Stop price condition</param> /// <param name="stopPrice">Price to trigger the order placement</param> /// <param name="tradeType">Trade type</param> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<KucoinNewOrder>> PlaceStopOrderAsync( string symbol, string clientOrderId, KucoinOrderSide orderSide, KucoinNewOrderType orderType, KucoinStopCondition stopCondition, decimal stopPrice, string? remark = null, KucoinSelfTradePrevention? selfTradePrevention = null, KucoinTradeType? tradeType = null, decimal? price = null, decimal? quantity = null, KucoinTimeInForce? timeInForce = null, DateTime? cancelAfter = null, bool? postOnly = null, bool? hidden = null, bool? iceberg = null, decimal? visibleSize = null, decimal? quoteQuantity = null, CancellationToken ct = default); /// <summary> /// Cancel a stop order by order id /// </summary> /// <param name="orderId">Order id</param> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<KucoinCancelledOrders>> CancelStopOrderAsync(string orderId, CancellationToken ct = default); /// <summary> /// Cancel a stop order by client order id /// </summary> /// <param name="clientOrderId">The client order id</param> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<KucoinCancelledOrder>> CancelStopOrderByClientOrderIdAsync(string clientOrderId, CancellationToken ct = default); /// <summary> /// Cancel all stop orders fitting the provided parameters /// </summary> /// <param name="symbol">Symbol to cancel orders on</param> /// <param name="orderIds">Order ids of the orders to cancel</param> /// <param name="tradeType">Trade type</param> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<KucoinCancelledOrders>> CancelStopOrdersAsync(string? symbol = null, IEnumerable<string>? orderIds = null, KucoinTradeType? tradeType = null, CancellationToken ct = default); /// <summary> /// Get a list of stop orders fitting the provided parameters /// </summary> /// <param name="activeOrders">True to return active orders, false for completed orders</param> /// <param name="symbol">Symbol of the orders</param> /// <param name="side">Side of the orders</param> /// <param name="type">Type of the orders</param> /// <param name="tradeType">Trade type</param> /// <param name="startTime">Filter list by start time</param> /// <param name="endTime">Filter list by end time</param> /// <param name="orderIds">Filter list by order ids</param> /// <param name="currentPage">The page to retrieve</param> /// <param name="pageSize">The amount of results per page</param> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<KucoinPaginated<KucoinOrder>>> GetStopOrdersAsync(bool? activeOrders = null, string? symbol = null, KucoinOrderSide? side = null, KucoinOrderType? type = null, KucoinTradeType? tradeType = null, DateTime? startTime = null, DateTime? endTime = null, IEnumerable<string>? orderIds = null, int? currentPage = null, int? pageSize = null, CancellationToken ct = default); /// <summary> /// Get a stop order by id /// </summary> /// <param name="orderId">Order id</param> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<KucoinOrder>> GetStopOrderAsync(string orderId, CancellationToken ct = default); /// <summary> /// Get a stop order by client order id /// </summary> /// <param name="clientOrderId">The client order id</param> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<IEnumerable<KucoinOrder>>> GetStopOrderByClientOrderIdAsync(string clientOrderId, CancellationToken ct = default); } }
55.159938
323
0.631957
[ "MIT" ]
agent-rat/Kucoin.Net
Kucoin.Net/Interfaces/IKucoinClientSpot.cs
35,523
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using ContractTools.WebApp.Base; using ContractTools.WebApp.Model; using ZyGames.Framework.Common; using ZyGames.Framework.Common.Log; namespace ContractTools.WebApp { public partial class ContractEdit : BasePage { protected int SlnID { get { if (string.IsNullOrEmpty(Request.QueryString["slnID"])) { return 0; } return Convert.ToInt32(Request.Params["slnID"]); } } protected int VerID { get { if (string.IsNullOrEmpty(Request["VerID"])) { return 0; } return Convert.ToInt32(Request["VerID"]); } } protected int ContractID { get { if (string.IsNullOrEmpty(Request.QueryString["ID"])) { return 0; } return Convert.ToInt32(Request.QueryString["ID"]); } } protected bool IsModify { get { return Request["modify"].ToBool(); } } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { try { int slnId = SlnID; var agreementList = DbDataLoader.GetAgreement(slnId); ddlAgreement.DataSource = agreementList; ddlAgreement.DataTextField = "Title"; ddlAgreement.DataValueField = "AgreementID"; ddlAgreement.DataBind(); if (ddlAgreement.Items.Count == 0) { ddlAgreement.Items.Add(new ListItem("选择类别", "0")); } var versiontList = DbDataLoader.GetVersion(slnId); versiontList.Insert(0, new VersionMode() { ID = 0, SlnID = slnId, Title = "选择版本" }); ddVersion.DataSource = versiontList; ddVersion.DataTextField = "Title"; ddVersion.DataValueField = "ID"; ddVersion.DataBind(); if (IsModify) { ContractModel model = DbDataLoader.GetContract(slnId, ContractID, 0); if (model != null) { txtID.Text = model.ID.ToString(); txtDescption.Text = model.Descption; ddlAgreement.SelectedValue = model.AgreementID.ToString(); ddVersion.SelectedValue = model.VerID.ToString(); btnDelete.Visible = true; } } else { btnDelete.Visible = false; ddVersion.SelectedValue = VerID.ToString(); } } catch (Exception) { } } } protected void butSubmit_Click(object sender, EventArgs e) { try { ContractModel model = new ContractModel(); model.ID = Convert.ToInt32((string)txtID.Text.Trim()); model.Descption = txtDescption.Text.Trim(); model.ParentID = 1; model.SlnID = SlnID; model.VerID = Convert.ToInt32(ddVersion.Text.Trim()); model.AgreementID = ddlAgreement.SelectedValue.ToInt(); if (IsModify) { DbDataLoader.Update(model); } else { DbDataLoader.Add(model); } } catch (Exception ex) { Page.RegisterStartupScript("", "<script language=javascript>alert('添加失败,填写重复!')</script>"); } } protected void btnDelete_Click(object sender, EventArgs e) { try { var contractModel = new ContractModel() { ID = txtID.Text.ToInt(), SlnID = SlnID }; if (DbDataLoader.Delete(contractModel)) { Response.Write("<script language=javascript>alert('删除成功!')</script>"); Response.Redirect("Default.aspx?edit=true"); } else { Response.Write("<script language=javascript>alert('删除失败!')</script>"); } } catch (Exception ex) { TraceLog.WriteError("delete contract error:{0}",ex); } } } }
33.089744
108
0.431616
[ "Unlicense" ]
seem-sky/Scut
Source/Tools/ContractTools/src/ContractTools.WebApp/ContractEdit.aspx.cs
5,218
C#
using System; using System.Collections.Generic; using System.Text; namespace Model { public enum Color { White, Black } }
10.076923
33
0.717557
[ "MIT" ]
Bobby-Read/ReallyGoodChess
Model/Color.cs
133
C#
using System.Collections.Generic; namespace Edison.Core.Common.Models { public class ResponseActionPlanModel { public string Name { get; set; } public string Description { get; set; } public string Color { get; set; } public string Icon { get; set; } public double PrimaryRadius { get; set; } public double SecondaryRadius { get; set; } public bool AcceptSafeStatus { get; set; } public IEnumerable<ResponseActionModel> OpenActions { get; set; } public IEnumerable<ResponseActionModel> CloseActions { get; set; } } }
33.5
74
0.651741
[ "MIT" ]
Mahesh1998/ProjectEdison
Edison.Core/Edison.Core.Common/Models/Response/ResponseActionPlanModel.cs
605
C#
using System; namespace NModbus { /// <summary> /// Represents a serial resource. /// Implementor - http://en.wikipedia.org/wiki/Bridge_Pattern /// </summary> public interface IStreamResource : IDisposable { /// <summary> /// Indicates that no timeout should occur. /// </summary> int InfiniteTimeout { get; } /// <summary> /// Gets or sets the number of milliseconds before a timeout occurs when a read operation does not finish. /// </summary> int ReadTimeout { get; set; } /// <summary> /// Gets or sets the number of milliseconds before a timeout occurs when a write operation does not finish. /// </summary> int WriteTimeout { get; set; } /// <summary> /// Purges the receive buffer. /// </summary> void DiscardInBuffer(); /// <summary> /// Reads a number of bytes from the input buffer and writes those bytes into a byte array at the specified offset. /// </summary> /// <param name="buffer">The byte array to write the input to.</param> /// <param name="offset">The offset in the buffer array to begin writing.</param> /// <param name="count">The number of bytes to read.</param> /// <returns>The number of bytes read.</returns> int Read(byte[] buffer, int offset, int count); /// <summary> /// Writes a specified number of bytes to the port from an output buffer, starting at the specified offset. /// </summary> /// <param name="buffer">The byte array that contains the data to write to the port.</param> /// <param name="offset">The offset in the buffer array to begin writing.</param> /// <param name="count">The number of bytes to write.</param> void Write(byte[] buffer, int offset, int count); } }
40.306122
128
0.576203
[ "MIT" ]
vantyaevserega/NModbus
NModbus.Interfaces/IStreamResource.cs
1,977
C#
using DreamWallHub.Core.ViewModels; using DreamWallHub.Infrastructure.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DreamWallHub.Core.Contracts { public interface IProjectService { Task<IEnumerable<AllProjectViewModel>> GetProjects(); Task<ProjectEditViewModel> GetProjectForEdit(string id); Task<bool> UpdateProject(ProjectEditViewModel model); Task<Project> GetProjectById(string id); Task<bool> CreateProject(ProjectCreateViewModel model); } }
24.625
64
0.754653
[ "MIT" ]
StrikeITBG/DreamWallHub
DreamWallHub/DreamWallHub.Core/Contracts/IProjectService.cs
593
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("ArgsDemo")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("ArgsDemo")] [assembly: System.Reflection.AssemblyTitleAttribute("ArgsDemo")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
40.652174
80
0.64385
[ "MIT" ]
BoomlabsInc/BCSF
2022-S1/W6/ArgsDemo/obj/Debug/net6.0/ArgsDemo.AssemblyInfo.cs
935
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Trapezoid_Area { class Program { static void Main(string[] args) { var b1 = double.Parse(Console.ReadLine()); var b2 = double.Parse(Console.ReadLine()); var h = double.Parse(Console.ReadLine()); var area = (b1 + b2) * h / 2; Console.WriteLine("Trapezoid Area = " + area); } } }
23.818182
59
0.557252
[ "MIT" ]
Menkachev/SoftUni-C-Sharp-Basics-Fundamentals
Programing Basics - October 2016/01. Simple Calculations - October 22, 2016/05. Trapezoid Area/Program.cs
526
C#
using System; using GitIssue.Fields; using GitIssue.Issues; namespace GitIssue.Formatters { /// <summary> /// A simple formatter for showing the issue on a single line /// </summary> public class DelegateFormatter : IIssueFormatter, IFieldFormatter { private readonly Func<IField, string?> fieldFormatter = f => f.ToString(); private readonly Func<IReadOnlyIssue, string?> issueFormatter = i => i.ToString(); /// <summary> /// Initializes a new instance of the <see cref="DelegateFormatter" /> class /// </summary> public DelegateFormatter() { } /// <summary> /// Initializes a new instance of the <see cref="DelegateFormatter" /> class /// </summary> public DelegateFormatter(Func<IReadOnlyIssue, string> issueFormatter) { this.issueFormatter = issueFormatter; } /// <summary> /// Initializes a new instance of the <see cref="DelegateFormatter" /> class /// </summary> public DelegateFormatter(Func<IField, string> fieldFormatter) { this.fieldFormatter = fieldFormatter; } /// <summary> /// Initializes a new instance of the <see cref="DelegateFormatter" /> class /// </summary> public DelegateFormatter(Func<IReadOnlyIssue, string> issueFormatter, Func<IField, string> fieldFormatter) { this.issueFormatter = issueFormatter; this.fieldFormatter = fieldFormatter; } /// <summary> /// Gets the default formatter /// </summary> public static DelegateFormatter Default => new DelegateFormatter(); /// <inheritdoc /> public string? Format(IField field) { return fieldFormatter?.Invoke(field); } /// <inheritdoc /> public string? Format(IReadOnlyIssue issue) { return issueFormatter?.Invoke(issue); } } }
31.765625
114
0.587309
[ "MIT" ]
lennoncork/GitIssue
src/GitIssue/Formatters/DelegateFormatter.cs
2,035
C#
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // 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.Collections; using System.Collections.Generic; using NUnit.Framework.Internal; using NUnit.TestUtilities.Collections; namespace NUnit.Framework.Constraints { [TestFixture] public class CollectionSubsetConstraintTests : ConstraintTestBase { [SetUp] public void SetUp() { theConstraint = new CollectionSubsetConstraint(new int[] { 1, 2, 3, 4, 5 }); stringRepresentation = "<subsetof System.Int32[]>"; expectedDescription = "subset of < 1, 2, 3, 4, 5 >"; } static object[] SuccessData = new object[] { new int[] { 1, 3, 5 }, new int[] { 1, 2, 3, 4, 5 } }; static object[] FailureData = new object[] { new object[] { new int[] { 1, 3, 7 }, "< 1, 3, 7 >" }, new object[] { new int[] { 1, 2, 2, 2, 5 }, "< 1, 2, 2, 2, 5 >" } }; [Test] [TestCaseSource(typeof(IgnoreCaseDataProvider), "TestCases")] public void HonorsIgnoreCase( IEnumerable expected, IEnumerable actual ) { var constraint = new CollectionSubsetConstraint( expected ).IgnoreCase; var constraintResult = constraint.ApplyTo( actual ); if ( !constraintResult.IsSuccess ) { MessageWriter writer = new TextMessageWriter(); constraintResult.WriteMessageTo( writer ); Assert.Fail( writer.ToString() ); } } public class IgnoreCaseDataProvider { public static IEnumerable TestCases { get { yield return new TestCaseData(new SimpleObjectCollection("w", "x", "y", "z"), new SimpleObjectCollection("z", "Y", "X")); yield return new TestCaseData(new[] {'A', 'B', 'C', 'D', 'E'}, new object[] {'a', 'b', 'c'}); yield return new TestCaseData(new[] {"a", "b", "c", "d", "e"}, new object[] {"A", "C", "B"}); yield return new TestCaseData(new Dictionary<int, string> {{1, "a"}, {2, "b"}}, new Dictionary<int, string> {{1, "A"}}); yield return new TestCaseData(new Dictionary<int, char> {{1, 'A'}, {2, 'B'}}, new Dictionary<int, char> {{1, 'a'}}); yield return new TestCaseData(new Dictionary<string, int> {{ "b", 2 }, { "a", 1 } }, new Dictionary<string, int> {{"b", 2}}); yield return new TestCaseData(new Dictionary<char, int> {{'A', 1 }, {'B', 2}}, new Dictionary<char, int> {{'a', 1}}); #if !PORTABLE && !NETSTANDARD1_6 yield return new TestCaseData(new Hashtable {{1, "a"}, {2, "b"}}, new Hashtable {{1, "A"}}); yield return new TestCaseData(new Hashtable {{1, 'A'}, {2, 'B'}}, new Hashtable {{2, 'b'}}); yield return new TestCaseData(new Hashtable {{"b", 2}, {"a", 1}}, new Hashtable {{"A", 1}}); yield return new TestCaseData(new Hashtable {{'A', 1}, {'B', 2}}, new Hashtable {{'a', 1}}); #endif } } } [Test] public void IsSubsetHonorsUsingWhenCollectionsAreOfDifferentTypes() { ICollection set = new SimpleObjectCollection("1", "2", "3", "4", "5"); ICollection subset = new SimpleObjectCollection(2, 3); Assert.That(subset, Is.SubsetOf(set).Using<int, string>((i, s) => i.ToString() == s)); } } }
49.494737
145
0.572097
[ "MIT" ]
jnm2/nunit
src/NUnitFramework/tests/Constraints/CollectionSubsetConstraintTests.cs
4,704
C#
using System; using System.Collections.Generic; namespace AltUI.Collections { public class ObservableListModified<T> : EventArgs { public IEnumerable<T> Items { get; private set; } public ObservableListModified(IEnumerable<T> items) { Items = items; } } }
19.6875
59
0.631746
[ "MIT" ]
kran27/AltUI
AltUI/Collections/ObservableListModified.cs
317
C#
using System.Linq.Expressions; namespace ExpressionTreeParsing.Domain { public class ParsedNewExpression : ParsedExpression { public ParsedNewExpression( ParsedConstructorInfo constructor) : base() { this.Constructor = constructor; } public ParsedConstructorInfo Constructor { get; } public override ExpressionType NodeType => ExpressionType.New; } }
23.315789
70
0.65237
[ "MIT" ]
Rightpoint/ExpressionTreeParsing
ExpressionTreeParsing.Domain/ParsedNewExpression.cs
445
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // 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("Xamarin_Android")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Xamarin_Android")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
34.419355
84
0.743205
[ "MIT" ]
dhindrik/TDswe16
Lab - Xamarin.Android/solution/Xamarin_Android/Properties/AssemblyInfo.cs
1,070
C#
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data.OleDb; using System.Web.UI.HtmlControls; using Nitobi.Components.Grid; using Nitobi.Components.Model; namespace GridCSharpSamples.Basic.Paging { /// <summary> /// Summary description for index. /// </summary> public partial class index : System.Web.UI.Page { static OleDbConnection dbConn; protected void Page_Load(object sender, System.EventArgs e) { PagingGrid.DataSources.PrimaryData.DatasourceStructure.Keys.Add("ContactID"); LocalPagingGrid.DataSourceId = "LocalData"; LocalPagingGrid.DataBind(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); //this.PagingGrid.GetData += new Nitobi.Grid.GetEventHandler(this.PagingGrid_GetData); //this.PagingGrid.SaveData += new Nitobi.Grid.SaveEventHandler(this.PagingGrid_SaveData); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.PagingGrid.GetData += new Nitobi.Grid.GetEventHandler(this.PagingGrid_GetData); this.PagingGrid.SaveData += new Nitobi.Grid.SaveEventHandler(this.PagingGrid_SaveData); } #endregion private void PagingGrid_GetData(object sender, Nitobi.Components.Grid.GetEventArgs e) { OleDbDataAdapter dAdapter; string serverPath=""; serverPath=Server.MapPath(serverPath); dbConn=new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; data source=" + serverPath + @"\data\contactsflatfile3k.mdb" ); dbConn.Open(); OleDbCommand cmd = new OleDbCommand("select count(*) from tblContacts3k", dbConn); int count = (int)cmd.ExecuteScalar(); if (count > e.NumRowsRequested + e.StartingRecordIndex) { count = e.NumRowsRequested + e.StartingRecordIndex; } int numRows = count - e.StartingRecordIndex; string query=""; if (PagingGrid.RowsPerPage ==0) PagingGrid.RowsPerPage=20; string sortField = "ContactID"; SortOrder sortOrder = SortOrder.Asc; if (e!=null && e.Sort != null && e.Sort.SortField != null) { sortField = e.Sort.SortField; sortOrder = e.Sort.SortOrder; } string ReverseDirection; if (sortOrder == SortOrder.Asc) ReverseDirection = SortOrder.Desc.ToString(); else ReverseDirection = SortOrder.Asc.ToString(); string tableName; //if (e.DataSourceId == DataSources.PrimaryDataSourceId) //{ // The reason for this overly complicated SQL query is due to the fact that MDB does not support proper paging. // Using a server such as Oracle or MySql would eliminate the complexity of this query, and most of the // preceeding code. query = "SELECT * FROM (SELECT TOP " + numRows + " * FROM (SELECT TOP " + count + " * FROM tblContacts3k ORDER BY " + sortField + " " + sortOrder + ") ORDER BY " + sortField + " " + ReverseDirection + ") ORDER BY " + sortField + " " + sortOrder; tableName = "tblContacts3k"; /*} else { query = "SELECT * FROM tblProductCategories"; if (e.SearchString != "") { query += " WHERE ProductCategoryName LIKE '" + e.SearchString + "%'"; } tableName = "tblProductCategories"; }*/ // Fill the tables from the dataset with the data from the database. DataSet ds = new DataSet(); ds.Tables.Add(tableName); dAdapter=new OleDbDataAdapter(query,dbConn); dAdapter.Fill(ds.Tables[tableName]); dbConn.Close(); e.DataSource = ds; } private void PagingGrid_SaveData(object sender, Nitobi.Components.Grid.GridSaveEventArgs e) { OleDbDataAdapter dAdapter = new OleDbDataAdapter(); string serverPath=""; serverPath=Server.MapPath(serverPath); dbConn=new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; data source=" + serverPath + @"\data\contactsflatfile3k.mdb" ); dAdapter.SelectCommand = new OleDbCommand("SELECT * FROM tblContacts3k", dbConn); // The following line required for updates and inserts. new OleDbCommandBuilder(dAdapter); DataSet ds = new DataSet(); ds.Tables.Add("tblContacts3k"); dAdapter.TableMappings.Add("Table","tblContacts3k"); dbConn.Open(); dAdapter.Fill(ds.Tables["tblContacts3k"]); ds.Tables["tblContacts3k"].PrimaryKey = new DataColumn[] {ds.Tables["tblContacts3k"].Columns["ContactID"]}; // Ensure that we capture the key assigned by the db in order to send it back to the grid. dAdapter.RowUpdated += new OleDbRowUpdatedEventHandler(RowUpdated); Hashtable ht = new Hashtable(); int MDB_WORKAROUND=0, i=0; foreach (Row row in PagingGrid.DataSources.PrimaryData.Rows) { UpdateAction xac = row.EditAction; switch(xac) { case(UpdateAction.INSERT): { DataRow r = ds.Tables["tblContacts3k"].NewRow(); // The first field is an auto-increment field. r[0]=MDB_WORKAROUND--; // Keep the row so that we can update the key later. ht[i] = r; for (int j=1;j<row.Count;j++) { if (!ds.Tables["tblContacts3k"].Columns[j].AutoIncrement) { r[j] = row[j]; } } ds.Tables["tblContacts3k"].Rows.Add(r); break; } case(UpdateAction.DELETE): { DataRow r = ds.Tables["tblContacts3k"].Rows.Find(row[0]); r.Delete(); break; } case(UpdateAction.UPDATE): { DataRow r = ds.Tables["tblContacts3k"].Rows.Find(row[0]); for (int j=0;j<row.Count;j++) { r[j] = row[j]; } break; } } i++; } dAdapter.Update(ds.Tables["tblContacts3k"]); // Update the rows that were inserted with the keys that were returned // by the db. Rows rs = PagingGrid.DataSources.PrimaryData.Rows; foreach (int key in ht.Keys) { string s = ((DataRow)ht[key])[0].ToString(); rs[key][0] = s; } dbConn.Close(); } protected static void RowUpdated(object sender, OleDbRowUpdatedEventArgs args) { OleDbCommand idCMD = new OleDbCommand("SELECT @@IDENTITY", dbConn); if (args.StatementType == StatementType.Insert) { int newID; newID = (int)idCMD.ExecuteScalar(); args.Row["ContactID"] = newID; } } } }
31.712195
250
0.678511
[ "MIT" ]
stevengill/completeui
server/samples/server/grid/dotnet/csharp2.0/Basic/Paging/index.aspx.cs
6,501
C#
using System.Reflection; namespace TechTalk.SpecFlow.Bindings.Reflection { public class RuntimeBindingParameter : IBindingParameter { private readonly ParameterInfo parameterInfo; public IBindingType Type { get { return new RuntimeBindingType(parameterInfo.ParameterType); } } public string ParameterName { get { return parameterInfo.Name; } } public RuntimeBindingParameter(ParameterInfo parameterInfo) { this.parameterInfo = parameterInfo; } public override string ToString() { return $"{ParameterName}: {Type}"; } protected bool Equals(RuntimeBindingParameter other) { return Equals(parameterInfo, other.parameterInfo); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((RuntimeBindingParameter) obj); } public override int GetHashCode() { return (parameterInfo != null ? parameterInfo.GetHashCode() : 0); } } }
27.234043
79
0.594531
[ "BSD-3-Clause", "Apache-2.0", "MIT" ]
Jedarc/SpecFlow
TechTalk.SpecFlow/Bindings/Reflection/RuntimeBindingParameter.cs
1,280
C#
using System.Diagnostics; using Clean.Architecture.Web.ViewModels; using Microsoft.AspNetCore.Mvc; namespace Clean.Architecture.Web.Controllers; /// <summary> /// A sample MVC controller that uses views. /// Razor Pages provides a better way to manage view-based content, since the behavior, viewmodel, and view are all in one place, /// rather than spread between 3 different folders in your Web project. Look in /Pages to see examples. /// See: https://ardalis.com/aspnet-core-razor-pages-%E2%80%93-worth-checking-out/ /// </summary> public class HomeController : Controller { public IActionResult Index() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() => View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); }
37.304348
129
0.749417
[ "MIT" ]
Allann/CleanArchitecture-1
src/Clean.Architecture.Web/Controllers/HomeController.cs
860
C#
namespace LinFx.Extensions.Auditing { /// <summary> /// This interface can be implemented to add standard auditing properties to a class. /// </summary> public interface IAuditedObject : ICreationAuditedObject, IModificationAuditedObject { } /// <summary> /// Extends <see cref="IAuditedObject"/> to add user navigation properties. /// </summary> /// <typeparam name="TUser">Type of the user</typeparam> public interface IAuditedObject<TUser> : IAuditedObject, ICreationAuditedObject<TUser>, IModificationAuditedObject<TUser> { } }
34.352941
125
0.69863
[ "MIT" ]
ailuozhu/LinFx
src/LinFx/Extensions/Auditing/IAuditedObject.cs
584
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 28.03.2019. // // <param>.ExtractMonth() // using System; using System.Linq; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.DataTypes.Extensions; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Funcs.NullableDateTime.SET001.EXT.ExtractMonth{ //////////////////////////////////////////////////////////////////////////////// //using using T_DATA=System.Nullable<System.DateTime>; //////////////////////////////////////////////////////////////////////////////// //class TestSet___param public static class TestSet___param { private const string c_NameOf__TABLE="TEST_MODIFY_ROW"; private const string c_NameOf__COL_DATA="COL_TIMESTAMP"; private const string c_NameOf__COL_INTEGER="COL_INTEGER"; //----------------------------------------------------------------------- private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA)] public T_DATA DATA { get; set; } [Column(c_NameOf__COL_INTEGER)] public System.Int32? COL_INTEGER { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test___01___ByEF() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA c_data=new System.DateTime(2018,10,9); System.Int64? testID=Helper__InsertRow(db,c_data); System.DateTime? vv_src=c_data; var recs=db.testTable.Where(r => vv_src.ExtractMonth()==10 && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_data, r.DATA); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE ").N("t","TEST_ID").T(" = ").P_ID("__testID_0")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test___01___ByEF //----------------------------------------------------------------------- [Test] public static void Test___02___ByEF() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA c_data=new System.DateTime(2018,10,9); System.Int64? testID=Helper__InsertRow(db,c_data); System.DateTime? vv_src=c_data; var recs=db.testTable.Where(r => vv_src.ExtractMonth()+1==11 && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_data, r.DATA); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE ").N("t","TEST_ID").T(" = ").P_ID("__testID_0")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test___02___ByEF //----------------------------------------------------------------------- [Test] public static void Test___03___ByEF() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA c_data=new System.DateTime(2018,10,9); System.Int64? testID=Helper__InsertRow(db,c_data); System.DateTime? vv_src=c_data; var recs=db.testTable.Where(r => vv_src.ExtractMonth()+r.COL_INTEGER==null && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_data, r.DATA); }//foreach r var sqlt =new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N("t",c_NameOf__COL_INTEGER).IS_NULL().T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_1").T(")"); db.CheckTextOfLastExecutedCommand (sqlt); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test___03___ByEF //----------------------------------------------------------------------- [Test] public static void Test___04___ByEF() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA c_data=new System.DateTime(2018,10,9); System.Int64? testID=Helper__InsertRow(db,c_data,-2); System.DateTime? vv_src=c_data; var recs=db.testTable.Where(r => vv_src.ExtractMonth()+r.COL_INTEGER==8 && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_data, r.DATA); }//foreach r var sqlt =new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE ((").P_I4("__Exec_0").T(" + ").N("t",c_NameOf__COL_INTEGER).T(") = 8) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_1").T(")"); db.CheckTextOfLastExecutedCommand (sqlt); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test___04___ByEF //----------------------------------------------------------------------- [Test] public static void Test___05___ByDBMS() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA c_data=new System.DateTime(2018,10,9); System.Int64? testID=Helper__InsertRow(db,c_data,-2); System.DateTime? vv_src=c_data; var recs=db.testTable.Where(r => vv_src.ExtractMonth()==8-r.COL_INTEGER && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_data, r.DATA); }//foreach r var sqlt =new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").P_I4("__Exec_0").T(" = (8 - ").N("t",c_NameOf__COL_INTEGER).T(")) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_1").T(")"); db.CheckTextOfLastExecutedCommand (sqlt); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test___05___ByDBMS //----------------------------------------------------------------------- [Test] public static void Test___06___ByDBMS() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA c_data=new System.DateTime(2018,10,9); System.Int64? testID=Helper__InsertRow(db,c_data); System.DateTime? vv_src=c_data; var recs=db.testTable.Where(r => vv_src.ExtractMonth()!=8-r.COL_INTEGER && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_data, r.DATA); }//foreach r var sqlt =new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE ((").P_I4("__Exec_0").T(" <> (8 - ").N("t",c_NameOf__COL_INTEGER).T(")) OR (").N("t",c_NameOf__COL_INTEGER).IS_NULL().T(")) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_1").T(")"); db.CheckTextOfLastExecutedCommand (sqlt); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test___06___ByDBMS //----------------------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA valueOfData) { var newRecord=new MyContext.TEST_RECORD(); newRecord.DATA=valueOfData; db.testTable.Add(newRecord); db.SaveChanges(); var sqlt =new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_INTEGER).T(", ").N(c_NameOf__COL_DATA).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";"); db.CheckTextOfLastExecutedCommand (sqlt); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow //----------------------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA valueOfData, System.Int32 valueOfColInteger) { var newRecord=new MyContext.TEST_RECORD(); newRecord.DATA=valueOfData; newRecord.COL_INTEGER=valueOfColInteger; db.testTable.Add(newRecord); db.SaveChanges(); var sqlt =new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_INTEGER).T(", ").N(c_NameOf__COL_DATA).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";"); db.CheckTextOfLastExecutedCommand (sqlt); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet___param //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Funcs.NullableDateTime.SET001.EXT.ExtractMonth
24.979757
202
0.546272
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Funcs/NullableDateTime/SET001/EXT/ExtractMonth/TestSet___param.cs
12,342
C#
using System.IO; using Kralizek.Assembla.Connector.Files; using Kralizek.Assembla.Connector.Files.Content; using NUnit.Framework; using Shouldly; namespace Tests.Connector.Files { [TestFixture] public class FileContentTests { private const string FileName = "fileName.txt"; [Test, CustomAutoData] public void FromString_returns_StringFileContent(string fileContent) { var content = FileContent.FromString(fileContent, fileName: FileName); content.FileName.ShouldBe(FileName); content.ShouldBeOfType<StringFileContent>(); } [Test, CustomAutoData] public void FromByteArray_returns_ByteArrayFileContent(byte[] byteArray) { var content = FileContent.FromByteArray(byteArray, FileName); content.FileName.ShouldBe(FileName); content.ShouldBeOfType<ByteArrayFileContent>(); } [Test, CustomAutoData] public void FromStream_returns_StreamFileContent(Stream stream) { var content = FileContent.FromStream(stream, FileName); content.FileName.ShouldBe(FileName); content.ShouldBeOfType<StreamFileContent>(); } [Test, CustomAutoData] public void FromObjectAsJson_returns_StringFileContent(string text) { var obj = new {text}; var content = FileContent.FromObjectAsJson(obj, fileName: FileName); content.FileName.ShouldBe(FileName); content.ShouldBeOfType<StringFileContent>(); } } }
30.557692
82
0.658905
[ "MIT" ]
Kralizek/Assembla.Connector
tests/Tests.Assembla.Connector/Connector/Files/FileContentTests.cs
1,591
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using System.Runtime.CompilerServices; using HarmonyLib; using UnityEngine; using System.Collections; namespace NoBlockDetach { public static class IngressPoint { public static bool Debug = true; private static void DebugPrint(String prefix, String contents) { if (NoBlockDetach.IngressPoint.Debug) { Console.WriteLine(prefix + contents); } } private static FieldInfo m_DetachCallback = typeof(BlockManager).GetField("m_DetachCallback", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); private static FieldInfo tank = typeof(BlockManager).GetField("tank", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); private static FieldInfo allBlocks = typeof(BlockManager).GetField("allBlocks", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); private static FieldInfo m_RemoveBlockRecursionCounter = typeof(BlockManager).GetField("m_RemoveBlockRecursionCounter", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); private static FieldInfo blockTable = typeof(BlockManager).GetField("blockTable", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); private static FieldInfo m_APbitfield = typeof(BlockManager).GetField("m_APbitfield", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); private static FieldInfo rootBlock = typeof(BlockManager).GetField("rootBlock", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); private static FieldInfo _blockCentreBounds = typeof(BlockManager).GetField("_blockCentreBounds", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); private static FieldInfo m_BlockTableCentre = typeof(BlockManager).GetField("m_BlockTableCentre", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); private static FieldInfo changed = typeof(BlockManager).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault(field => field.CustomAttributes.Any(attr => attr.AttributeType == typeof(CompilerGeneratedAttribute)) && (field.DeclaringType == typeof(BlockManager).GetProperty("changed").DeclaringType) && field.FieldType.IsAssignableFrom(typeof(BlockManager).GetProperty("changed").PropertyType) && field.Name.StartsWith("<" + typeof(BlockManager).GetProperty("changed").Name + ">") ); private static FieldInfo BlockHash = typeof(BlockManager).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault(field => field.CustomAttributes.Any(attr => attr.AttributeType == typeof(CompilerGeneratedAttribute)) && (field.DeclaringType == typeof(BlockManager).GetProperty("BlockHash").DeclaringType) && field.FieldType.IsAssignableFrom(typeof(BlockManager).GetProperty("BlockHash").PropertyType) && field.Name.StartsWith("<" + typeof(BlockManager).GetProperty("BlockHash").Name + ">") ); private static FieldInfo s_LastRemovedBlocks = typeof(BlockManager).GetField("s_LastRemovedBlocks", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); private static FieldInfo s_ActiveMgr = typeof(BlockManager).GetField("s_ActiveMgr", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); private static Bounds k_InvalidBounds = (Bounds) typeof(BlockManager).GetField("k_InvalidBounds", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).GetValue(null); private static void FixupBlockRefs(BlockManager __instance) { int num = 0; List<TankBlock> blockList = (List<TankBlock>)IngressPoint.allBlocks.GetValue(__instance); for (int i = 0; i < blockList.Count; i++) { if (blockList[i].tank == (Tank)IngressPoint.tank.GetValue(__instance)) { if (i != num) { blockList[num] = blockList[i]; } num++; } } if (num != blockList.Count) { blockList.RemoveRange(num, blockList.Count - num); } // PatchBlockManager.m_allBlocks.SetValue(__instance, blockList); } private static void RemoveAllBlocks(BlockManager __instance, BlockManager.RemoveAllAction option) { Tank tank = (Tank)IngressPoint.tank.GetValue(__instance); if (tank.rbody.isKinematic) { tank.rbody.isKinematic = false; } IngressPoint.m_RemoveBlockRecursionCounter.SetValue(__instance, 1); List<TankBlock> allBlocks = (List<TankBlock>)IngressPoint.allBlocks.GetValue(__instance); Action<Tank, TankBlock> DetachCallback = (Action<Tank, TankBlock>)IngressPoint.m_DetachCallback.GetValue(__instance); foreach (TankBlock tankBlock in allBlocks) { bool flag = option != BlockManager.RemoveAllAction.Recycle; tankBlock.OnDetach(tank, flag, flag); tank.NotifyBlock(tankBlock, false); tankBlock.RemoveLinks(null, true); if (DetachCallback != null) { DetachCallback(tank, tankBlock); } switch (option) { case BlockManager.RemoveAllAction.ApplyPhysicsKick: tankBlock.trans.parent = null; tankBlock.trans.Recycle(true); break; case BlockManager.RemoveAllAction.Recycle: tankBlock.trans.Recycle(true); break; case BlockManager.RemoveAllAction.HandOff: tankBlock.trans.parent = null; tankBlock.trans.Recycle(true); break; default: d.LogError("BlockManager.RemoveAllBlocks - No remove action found for " + option); break; } } IngressPoint.m_RemoveBlockRecursionCounter.SetValue(__instance, 0); allBlocks.Clear(); TankBlock[,,] l_blockTable = (TankBlock[,,])IngressPoint.blockTable.GetValue(__instance); byte[,,] l_m_APbitfield = (byte[,,])IngressPoint.m_APbitfield.GetValue(__instance); Array.Clear(l_blockTable, 0, l_blockTable.Length); Array.Clear(l_m_APbitfield, 0, l_m_APbitfield.Length); IngressPoint.changed.SetValue(__instance, false); IngressPoint.rootBlock.SetValue(__instance, null); IngressPoint._blockCentreBounds.SetValue(__instance, IngressPoint.k_InvalidBounds); } private static void HostRemoveAllBlocks(BlockManager __instance, BlockManager.RemoveAllAction option) { d.Assert(ManNetwork.IsHost, "Can't call HostRemoveAllBlocks on client"); Tank tank = (Tank)IngressPoint.tank.GetValue(__instance); if (ManNetwork.IsNetworked && tank.netTech != null) { RemoveAllBlocksMessage message = new RemoveAllBlocksMessage { m_Action = option }; Singleton.Manager<ManNetwork>.inst.SendToAllExceptClient(-1, TTMsgType.RemoveAllBlocksFromTech, message, tank.netTech.netId, true); IngressPoint.RemoveAllBlocks(__instance, option); return; } IngressPoint.RemoveAllBlocks(__instance, option); } private static void AddLastRemovedBlock(BlockManager __instance, TankBlock removed) { List<TankBlock> lastRemovedBlocks = (List<TankBlock>) IngressPoint.s_LastRemovedBlocks.GetValue(null); BlockManager activeMgr = (BlockManager) IngressPoint.s_ActiveMgr.GetValue(null); if (activeMgr != __instance) { lastRemovedBlocks.Clear(); IngressPoint.s_ActiveMgr.SetValue(null, __instance); } lastRemovedBlocks.Add(removed); } // Handles destroying everything when tech cab is sniped [HarmonyPatch(typeof(BlockManager))] [HarmonyPatch("FixupAfterRemovingBlocks")] public static class PatchBlockManagerFixup { public static bool Prefix(ref BlockManager __instance, ref bool allowHeadlessTech, ref bool removeTechIfEmpty) { Tank tank = (Tank)IngressPoint.tank.GetValue(__instance); IngressPoint.FixupBlockRefs(__instance); if (!allowHeadlessTech && !tank.control.HasController && !tank.IsAnchored) { IngressPoint.HostRemoveAllBlocks(__instance, BlockManager.RemoveAllAction.ApplyPhysicsKick); } if (__instance.blockCount == 0) { d.Assert(tank.blockman.blockCount == 0); tank.EnableGravity = false; } return false; } } /* Don't change DetachSingleBlock, because it's used in DetachBlockAndRestructure * Make the change in Detach, which holds both */ [HarmonyPatch(typeof(BlockManager))] [HarmonyPatch("DetachSingleBlock")] public static class PatchDetachSingleBlock { public static void Postfix(ref BlockManager __instance, ref TankBlock block, ref bool isPropogating, ref bool rootTransfer) { ManDamage.DamageInfo damageInfo = new ManDamage.DamageInfo(float.PositiveInfinity, ManDamage.DamageType.Standard, (Component) null, (Tank) null, block.transform.position, default(Vector3), 0.0f, 0.0f); block.visible.damageable.TryToDamage(damageInfo, true); return; } } /* [HarmonyPatch(typeof(BlockManager))] [HarmonyPatch("Detach")] public static class PatchDetach { public static void Postfix(ref ModuleDamage __instance, ref TankBlock block, ref bool allowHeadlessTech, ref bool rootTransfer, ref bool propogate, ref Action<Tank, TankBlock> detachCallback) { if (!propogate) { block.trans.parent = null; block.trans.Recycle(true); } return; } } [HarmonyPatch(typeof(BlockManager))] [HarmonyPatch("DetachBlockAndRestructure")] public static class PatchDetachRecurseBlock { public static void Postfix(ref ModuleDamage __instance, ref TankBlock block, ref bool rootTransfer, ref bool allowHeadlessTech, ref TechSplitNamer techSplitNamer) { block.trans.parent = null; block.trans.Recycle(true); return; } } */ // patch fragility [HarmonyPatch(typeof(ModuleDamage))] [HarmonyPatch("OnSpawn")] public static class PatchDamageFragility { public static void Postfix(ref ModuleDamage __instance) { __instance.m_DamageDetachFragility = 0.0f; return; } } public static void Main() { Console.WriteLine("WALALALA"); new Harmony("flsoz.ttmm.noblockdetach.mod").PatchAll(Assembly.GetExecutingAssembly()); } } }
49.475207
217
0.623737
[ "MIT" ]
FLSoz/NoBlockDetach
IngressPoint.cs
11,975
C#
using CyberCAT.Core.Classes.Mapping; namespace CyberCAT.Core.Classes.DumpedClasses { [RealName("IWorldWidgetComponent")] public class IWorldWidgetComponent : WidgetBaseComponent { [RealName("isEnabled")] public bool IsEnabled { get; set; } [RealName("glitchValue")] public float GlitchValue { get; set; } [RealName("meshTargetBinding")] public Handle<WorlduiMeshTargetBinding> MeshTargetBinding { get; set; } [RealName("tintColor")] public Color TintColor { get; set; } [RealName("screenAreaMultiplier")] public float ScreenAreaMultiplier { get; set; } } }
28.75
79
0.627536
[ "MIT" ]
Deweh/CyberCAT
CyberCAT.Core/Classes/DumpedClasses/IWorldWidgetComponent.cs
690
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 NeoWeb.Data; namespace NeoWeb.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20181204062844_BlogTag")] partial class BlogTag { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.4-rtm-31024") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("NeoWeb.Models.ApplicationUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("NeoWeb.Models.Blog", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Content") .IsRequired(); b.Property<DateTime>("CreateTime"); b.Property<DateTime>("EditTime"); b.Property<bool>("IsShow"); b.Property<string>("Lang"); b.Property<int>("ReadCount"); b.Property<string>("Summary"); b.Property<string>("Tags"); b.Property<string>("Title") .IsRequired(); b.Property<string>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("Blogs"); }); modelBuilder.Entity("NeoWeb.Models.Candidate", b => { b.Property<string>("PublicKey") .ValueGeneratedOnAdd(); b.Property<string>("Email") .IsRequired(); b.Property<string>("Logo"); b.Property<string>("Organization") .IsRequired() .HasMaxLength(50); b.Property<string>("SocialAccount") .HasMaxLength(200); b.Property<string>("Summary") .HasMaxLength(500); b.Property<string>("Website") .IsRequired() .HasMaxLength(50); b.HasKey("PublicKey"); b.ToTable("Candidates"); }); modelBuilder.Entity("NeoWeb.Models.Careers", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Description") .IsRequired(); b.Property<bool>("IsShow"); b.Property<string>("Title") .IsRequired(); b.Property<int>("Type"); b.HasKey("Id"); b.ToTable("Careers"); }); modelBuilder.Entity("NeoWeb.Models.Country", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Code"); b.Property<string>("Code2"); b.Property<bool>("IsShow"); b.Property<string>("Name"); b.Property<string>("ZhName"); b.HasKey("Id"); b.ToTable("Countries"); }); modelBuilder.Entity("NeoWeb.Models.Event", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Address") .IsRequired(); b.Property<string>("City") .IsRequired(); b.Property<int?>("CountryId"); b.Property<string>("Cover"); b.Property<string>("Details"); b.Property<DateTime>("EndTime"); b.Property<bool>("IsFree"); b.Property<string>("Name") .IsRequired(); b.Property<string>("Organizers") .IsRequired(); b.Property<DateTime>("StartTime"); b.Property<string>("ThirdPartyLink"); b.Property<int>("Type"); b.HasKey("Id"); b.HasIndex("CountryId"); b.ToTable("Events"); }); modelBuilder.Entity("NeoWeb.Models.News", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Link") .IsRequired(); b.Property<DateTime>("Time"); b.Property<string>("Title") .IsRequired(); b.HasKey("Id"); b.ToTable("News"); }); modelBuilder.Entity("NeoWeb.Models.Subscription", b => { b.Property<string>("Email") .ValueGeneratedOnAdd(); b.Property<bool>("IsSubscription"); b.Property<DateTime>("SubscriptionTime"); b.HasKey("Email"); b.ToTable("Subscription"); }); modelBuilder.Entity("NeoWeb.Models.TestCoin", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Company") .IsRequired(); b.Property<string>("Email") .IsRequired(); b.Property<string>("GasCount") .IsRequired(); b.Property<string>("Name") .IsRequired(); b.Property<string>("NeoCount") .IsRequired(); b.Property<string>("Phone"); b.Property<string>("PubKey") .IsRequired(); b.Property<string>("QQ"); b.Property<string>("Reason") .IsRequired() .HasMaxLength(300); b.Property<string>("Remark"); b.Property<DateTime>("Time"); b.HasKey("Id"); b.ToTable("TestCoins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("NeoWeb.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("NeoWeb.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("NeoWeb.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("NeoWeb.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("NeoWeb.Models.Blog", b => { b.HasOne("NeoWeb.Models.ApplicationUser", "User") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("NeoWeb.Models.Event", b => { b.HasOne("NeoWeb.Models.Country", "Country") .WithMany() .HasForeignKey("CountryId"); }); #pragma warning restore 612, 618 } } }
32.673077
125
0.450592
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
EdgeDLT/neo.org
NeoWeb/Data/Migrations/20181204062844_BlogTag.Designer.cs
15,293
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer { internal abstract class AbstractRequestHandlerProvider { private readonly ImmutableDictionary<string, Lazy<IRequestHandler, IRequestHandlerMetadata>> _requestHandlers; public AbstractRequestHandlerProvider(IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers, string? languageName = null) { _requestHandlers = CreateMethodToHandlerMap(requestHandlers.Where(rh => rh.Metadata.LanguageName == languageName)); } private static ImmutableDictionary<string, Lazy<IRequestHandler, IRequestHandlerMetadata>> CreateMethodToHandlerMap(IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers) { var requestHandlerDictionary = ImmutableDictionary.CreateBuilder<string, Lazy<IRequestHandler, IRequestHandlerMetadata>>(); foreach (var lazyHandler in requestHandlers) { requestHandlerDictionary.Add(lazyHandler.Metadata.MethodName, lazyHandler); } return requestHandlerDictionary.ToImmutable(); } public Task<ResponseType> ExecuteRequestAsync<RequestType, ResponseType>(RequestExecutionQueue queue, string methodName, RequestType request, LSP.ClientCapabilities clientCapabilities, string? clientName, CancellationToken cancellationToken) where RequestType : class { Contract.ThrowIfNull(request); Contract.ThrowIfTrue(string.IsNullOrEmpty(methodName), "Invalid method name"); var handlerEntry = _requestHandlers[methodName]; Contract.ThrowIfNull(handlerEntry, string.Format("Request handler entry not found for method {0}", methodName)); var mutatesSolutionState = handlerEntry.Metadata.MutatesSolutionState; var handler = (IRequestHandler<RequestType, ResponseType>?)handlerEntry.Value; Contract.ThrowIfNull(handler, string.Format("Request handler not found for method {0}", methodName)); return ExecuteRequestAsync(queue, request, clientCapabilities, clientName, methodName, mutatesSolutionState, handler, cancellationToken); } protected virtual Task<ResponseType> ExecuteRequestAsync<RequestType, ResponseType>(RequestExecutionQueue queue, RequestType request, ClientCapabilities clientCapabilities, string? clientName, string methodName, bool mutatesSolutionState, IRequestHandler<RequestType, ResponseType> handler, CancellationToken cancellationToken) where RequestType : class { return queue.ExecuteAsync(mutatesSolutionState, handler, request, clientCapabilities, clientName, methodName, cancellationToken); } } }
53.901639
361
0.759732
[ "MIT" ]
Cosifne/roslyn
src/Features/LanguageServer/Protocol/AbstractRequestHandlerProvider.cs
3,290
C#
// This file is part of SharpNEAT; Copyright Colin D. Green. // See LICENSE.txt for details. using SharpNeat.Graphs; using SharpNeat.Neat.Genome; namespace SharpNeat.Neat.DistanceMetrics.Double; // TODO: Performance tuning target. E.g. use Math.Fma(), vectorisation, or use single-precision floats for some of the calcs. /// <summary> /// Manhattan distance metric. /// /// The Manhattan distance is simply the sum total of all of the distances in each dimension. /// Also known as the taxicab distance, rectilinear distance, L1 distance or L1 norm. /// /// Use the default constructor for classical Manhattan Distance. /// Optionally the constructor can be provided with a two coefficients and a constant that can be used to modify/distort /// distance measures. These are: /// /// matchDistanceCoeff: When comparing two positions in the same dimension the distance between those two position is /// multiplied by this coefficient. /// /// mismatchDistanceCoeff, mismatchDistanceConstant: When comparing two coordinates where one describes a position in a given /// dimension and the other does not then the second coordinate is assumed to be at position zero in that dimension. However, /// the resulting distance is multiplied by this coefficient and mismatchDistanceConstant is added, therefore allowing matches and /// mismatches to be weighted differently, e.g. more emphasis can be placed on mismatches (and therefore network topology). /// If mismatchDistanceCoeff is zero and mismatchDistanceConstant is non-zero then the distance of mismatches is a fixed value. /// /// The two coefficients and constant allow the following schemes: /// /// 1) Classical Manhattan distance. /// 2) Topology only distance metric (ignore connections weights). /// 3) Equivalent of genome distance in Original NEAT (O-NEAT). This is actually a mix of (1) and (2). /// </summary> public sealed class ManhattanDistanceMetric : IDistanceMetric<double> { #region Instance Fields // A coefficient to applied to the distance obtained from two coordinates that both // describe a position in a given dimension. readonly double _matchDistanceCoeff; // A coefficient applied to the distance obtained from two coordinates where only one of the coordinates describes // a position in a given dimension. The other point is taken to be at position zero in that dimension. readonly double _mismatchDistanceCoeff; // A constant that is added to the distance where only one of the coordinates describes a position in a given // dimension. This adds extra emphasis to distance when comparing coordinates that exist in different dimensions. readonly double _mismatchDistanceConstant; #endregion #region Constructors /// <summary> /// Constructs using default weightings for comparisons on matching and mismatching dimensions. /// Classical Manhattan Distance. /// </summary> public ManhattanDistanceMetric() : this(1.0, 1.0, 0.0) { } /// <summary> /// Constructs using the provided weightings for comparisons on matching and mismatching dimensions. /// </summary> /// <param name="matchDistanceCoeff">A coefficient to applied to the distance obtained from two coordinates that both /// describe a position in a given dimension.</param> /// <param name="mismatchDistanceCoeff">A coefficient applied to the distance obtained from two coordinates where only one of the coordinates describes /// a position in a given dimension. The other point is taken to be at position zero in that dimension.</param> /// <param name="mismatchDistanceConstant">A constant that is added to the distance where only one of the coordinates describes a position in a given dimension. /// This adds extra emphasis to distance when comparing coordinates that exist in different dimensions.</param> public ManhattanDistanceMetric( double matchDistanceCoeff, double mismatchDistanceCoeff, double mismatchDistanceConstant) { _matchDistanceCoeff = matchDistanceCoeff; _mismatchDistanceCoeff = mismatchDistanceCoeff; _mismatchDistanceConstant = mismatchDistanceConstant; } #endregion #region IDistanceMetric Members /// <summary> /// Calculates the distance between two positions. /// </summary> /// <param name="p1">Position one.</param> /// <param name="p2">Position two.</param> /// <returns>The distance between <paramref name="p1"/> and <paramref name="p2"/>.</returns> public double CalcDistance(ConnectionGenes<double> p1, ConnectionGenes<double> p2) { DirectedConnection[] connArr1 = p1._connArr; DirectedConnection[] connArr2 = p2._connArr; double[] weightArr1 = p1._weightArr; double[] weightArr2 = p2._weightArr; // Store these heavily used values locally. int length1 = connArr1.Length; int length2 = connArr2.Length; // Test for special cases. if(length1 == 0 && length2 == 0) { // Both arrays are empty. No disparities, therefore the distance is zero. return 0.0; } double distance = 0.0; if(length1 == 0) { // All p2 genes are mismatches. for(int i=0; i < length2; i++) distance += Math.Abs(weightArr2[i]); return (_mismatchDistanceConstant * length2) + (distance * _mismatchDistanceCoeff); } if(length2 == 0) { // All p1 elements are mismatches. for(int i=0; i < length1; i++) distance += Math.Abs(weightArr1[i]); return (_mismatchDistanceConstant * length1) + (distance * _mismatchDistanceCoeff); } // Both arrays contain elements. int arr1Idx = 0; int arr2Idx = 0; DirectedConnection conn1 = connArr1[arr1Idx]; DirectedConnection conn2 = connArr2[arr2Idx]; double weight1 = weightArr1[arr1Idx]; double weight2 = weightArr2[arr2Idx]; for(;;) { if(conn1 < conn2) { // p2 doesn't specify a value in this dimension therefore we take its position to be 0. distance += _mismatchDistanceConstant + (Math.Abs(weight1) * _mismatchDistanceCoeff); // Move to the next element in p1. arr1Idx++; } else if(conn1 == conn2) { // Matching elements. distance += Math.Abs(weight1 - weight2) * _matchDistanceCoeff; // Move to the next element in both arrays. arr1Idx++; arr2Idx++; } else // conn2 > conn1 { // p1 doesn't specify a value in this dimension therefore we take its position to be 0. distance += _mismatchDistanceConstant + (Math.Abs(weight2) * _mismatchDistanceCoeff); // Move to the next element in p2. arr2Idx++; } // Check if we have exhausted one or both of the arrays. if(arr1Idx == length1) { // All remaining p2 elements are mismatches. for(int i = arr2Idx; i < length2; i++) distance += _mismatchDistanceConstant + (Math.Abs(weightArr2[i]) * _mismatchDistanceCoeff); return distance; } if(arr2Idx == length2) { // All remaining p1 elements are mismatches. for(int i = arr1Idx; i < connArr1.Length; i++) distance += _mismatchDistanceConstant + (Math.Abs(weightArr1[i]) * _mismatchDistanceCoeff); return distance; } conn1 = connArr1[arr1Idx]; conn2 = connArr2[arr2Idx]; weight1 = weightArr1[arr1Idx]; weight2 = weightArr2[arr2Idx]; } } /// <summary> /// Tests if the distance between two positions is less than some threshold. /// </summary> /// <param name="p1">Position one.</param> /// <param name="p2">Position two.</param> /// <param name="threshold">Distance threshold.</param> /// <returns> /// True if the distance between <paramref name="p1"/> and <paramref name="p2"/> is less than /// <paramref name="threshold"/>. /// </returns> public bool TestDistance(ConnectionGenes<double> p1, ConnectionGenes<double> p2, double threshold) { DirectedConnection[] connArr1 = p1._connArr; DirectedConnection[] connArr2 = p2._connArr; double[] weightArr1 = p1._weightArr; double[] weightArr2 = p2._weightArr; // Store these heavily used values locally. int length1 = connArr1.Length; int length2 = connArr2.Length; // Test for special case. if(length1 == 0 && length2 == 0) { // Both arrays are empty. No disparities, therefore the distance is zero. return threshold > 0.0; } double distance = 0.0; if(length1 == 0) { // All p2 elements are mismatches. // p1 doesn't specify a value in these dimensions therefore we take its position to be 0 in all of them. for(int i=0; i < length2; i++) distance += Math.Abs(weightArr2[i]); distance = (_mismatchDistanceConstant * length2) + (distance * _mismatchDistanceCoeff); return distance < threshold; } if(length2 == 0) { // All p1 elements are mismatches. // p2 doesn't specify a value in these dimensions therefore we take its position to be 0 in all of them. for(int i=0; i < length1; i++) distance += Math.Abs(weightArr1[i]); distance = (_mismatchDistanceConstant * length1) + (distance * _mismatchDistanceCoeff); return distance < threshold; } // Both arrays contain elements. Compare the contents starting from the ends where the greatest discrepancies // between coordinates are expected to occur. In the general case this should result in less element comparisons // before the threshold is passed and we exit the method. int arr1Idx = length1 - 1; int arr2Idx = length2 - 1; DirectedConnection conn1 = connArr1[arr1Idx]; DirectedConnection conn2 = connArr2[arr2Idx]; double weight1 = weightArr1[arr1Idx]; double weight2 = weightArr2[arr2Idx]; for(;;) { if(conn1 > conn2) { // p2 doesn't specify a value in this dimension therefore we take its position to be 0. distance += _mismatchDistanceConstant + (Math.Abs(weight1) * _mismatchDistanceCoeff); // Move to the next element in p1. arr1Idx--; } else if(conn1 == conn2) { // Matching elements. distance += Math.Abs(weight1 - weight2) * _matchDistanceCoeff; // Move to the next element in both arrays. arr1Idx--; arr2Idx--; } else // conn2 > conn1 { // p1 doesn't specify a value in this dimension therefore we take its position to be 0. distance += _mismatchDistanceConstant + (Math.Abs(weight2) * _mismatchDistanceCoeff); // Move to the next element in p12 arr2Idx--; } // Test the threshold. if(distance >= threshold) return false; // Check if we have exhausted one or both of the arrays. if(arr1Idx < 0) { // Any remaining p2 elements are mismatches. for(int i = arr2Idx; i > -1; i--) distance += _mismatchDistanceConstant + (Math.Abs(weightArr2[i]) * _mismatchDistanceCoeff); return distance < threshold; } if(arr2Idx < 0) { // All remaining p1 elements are mismatches. for(int i = arr1Idx; i > -1; i--) distance += _mismatchDistanceConstant + (Math.Abs(weightArr1[i]) * _mismatchDistanceCoeff); return distance < threshold; } conn1 = connArr1[arr1Idx]; conn2 = connArr2[arr2Idx]; weight1 = weightArr1[arr1Idx]; weight2 = weightArr2[arr2Idx]; } } // TODO: Determine mathematically correct centroid. This method calculates the Euclidean distance centroid and // is an approximation of the true centroid in L1 space (Manhattan distance). // Note. In practice this is possibly a near optimal centroid for all but small clusters. /// <summary> /// Calculates the centroid for a set of points. /// </summary> /// <param name="pointList">The set of points.</param> /// <returns>A new instance of <see cref="ConnectionGenes{T}"/>.</returns> public ConnectionGenes<double> CalculateCentroid(IList<ConnectionGenes<double>> pointList) { return DistanceMetricUtils.CalculateEuclideanCentroid(pointList); } #endregion }
41.067901
164
0.622501
[ "MIT" ]
karuzzo/sharpneat-refactor
src/SharpNeat/Neat/DistanceMetrics/Double/ManhattanDistanceMetric.cs
13,308
C#
// ****************************************************************** // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THE CODE 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 CODE OR THE USE OR OTHER DEALINGS IN THE CODE. // ****************************************************************** using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Text; using System.Threading; using System.Threading.Tasks; using Windows.Devices.Bluetooth.GenericAttributeProfile; namespace UnityUWPBTLEPlugin { /// <summary> /// Wrapper around <see cref="GattDeviceService"/> to make it easier to use /// </summary> public sealed class GattDeviceServiceWrapper { /// <summary> /// Source for <see cref="Characteristics"/> /// </summary> private ObservableCollection<GattCharacteristicsWrapper> _characteristics = new ObservableCollection<GattCharacteristicsWrapper>(); /// <summary> /// Source for <see cref="Name"/> /// </summary> private string _name; /// <summary> /// Source for <see cref="Service"/> /// </summary> private GattDeviceService _service; /// <summary> /// Source for <see cref="UUID"/> /// </summary> private string _uuid; /// <summary> /// Initializes a new instance of the <see cref="GattDeviceServiceWrapper" /> class. /// </summary> /// <param name="service">The service this class wraps</param> public GattDeviceServiceWrapper(GattDeviceService service) { Service = service; Name = GattUuidsService.ConvertUuidToName(service.Uuid); UUID = Service.Uuid.ToString(); GetAllCharacteristics(); } /// <summary> /// Gets or sets the service this class wraps /// </summary> public GattDeviceService Service { get { return _service; } set { if (_service != value) { _service = value; } } } /// <summary> /// Gets or sets all the characteristics of this service /// </summary> public IList<GattCharacteristicsWrapper> Characteristics { get { return _characteristics; } } /// <summary> /// Gets or sets the name of this service /// </summary> public string Name { get { return _name; } set { if (_name != value) { _name = value; } } } /// <summary> /// Gets or sets the UUID of this service /// </summary> public string UUID { get { return _uuid; } set { if (_uuid != value) { _uuid = value; } } } /// <summary> /// Gets all the characteristics of this service /// </summary> private async void GetAllCharacteristics() { var sb = new StringBuilder(); sb.Append("GattDeviceServiceWrapper::getAllCharacteristics: "); sb.Append(Name); try { var tokenSource = new CancellationTokenSource(5000); var t = Task.Run( () => Service.GetCharacteristicsAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.Uncached), tokenSource.Token); GattCharacteristicsResult result = null; result = await t.Result; if (result.Status == GattCommunicationStatus.Success) { sb.Append(" - getAllCharacteristics found "); sb.Append(result.Characteristics.Count); sb.Append(" characteristics"); //Debug.WriteLine(sb); foreach (GattCharacteristic gattchar in result.Characteristics) { _characteristics.Add(new GattCharacteristicsWrapper(gattchar, this)); } } else if (result.Status == GattCommunicationStatus.Unreachable) { sb.Append(" - getAllCharacteristics failed with Unreachable"); //Debug.WriteLine(sb.ToString()); } else if (result.Status == GattCommunicationStatus.ProtocolError) { sb.Append(" - getAllCharacteristics failed with Unreachable"); //Debug.WriteLine(sb.ToString()); } } catch (AggregateException ae) { foreach (var ex in ae.InnerExceptions) { if (ex is TaskCanceledException) { Debug.WriteLine("Getting characteristics took too long."); Name += " - Timed out getting some characteristics"; return; } } } catch (UnauthorizedAccessException) { // Bug 9145823:GetCharacteristicsAsync throw System.UnauthorizedAccessException when querying GenericAccess Service Characteristics Name += " - Unauthorized Access"; } catch (Exception ex) { Debug.WriteLine("getAllCharacteristics: Exception - {0}" + ex.Message); throw; } } } }
33.648649
147
0.510843
[ "MIT" ]
Bhaskers-Blu-Org2/UnityUWPBTLEPlugin
UnityUWPBTLEPlugin/BluethoothLEHelper/GattDeviceServiceWrapper.cs
6,231
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type WorkbookTableSortRequest. /// </summary> public partial class WorkbookTableSortRequest : BaseRequest, IWorkbookTableSortRequest { /// <summary> /// Constructs a new WorkbookTableSortRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public WorkbookTableSortRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified WorkbookTableSort using POST. /// </summary> /// <param name="workbookTableSortToCreate">The WorkbookTableSort to create.</param> /// <returns>The created WorkbookTableSort.</returns> public System.Threading.Tasks.Task<WorkbookTableSort> CreateAsync(WorkbookTableSort workbookTableSortToCreate) { return this.CreateAsync(workbookTableSortToCreate, CancellationToken.None); } /// <summary> /// Creates the specified WorkbookTableSort using POST. /// </summary> /// <param name="workbookTableSortToCreate">The WorkbookTableSort to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WorkbookTableSort.</returns> public async System.Threading.Tasks.Task<WorkbookTableSort> CreateAsync(WorkbookTableSort workbookTableSortToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<WorkbookTableSort>(workbookTableSortToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified WorkbookTableSort. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified WorkbookTableSort. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<WorkbookTableSort>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified WorkbookTableSort. /// </summary> /// <returns>The WorkbookTableSort.</returns> public System.Threading.Tasks.Task<WorkbookTableSort> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified WorkbookTableSort. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The WorkbookTableSort.</returns> public async System.Threading.Tasks.Task<WorkbookTableSort> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<WorkbookTableSort>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified WorkbookTableSort using PATCH. /// </summary> /// <param name="workbookTableSortToUpdate">The WorkbookTableSort to update.</param> /// <returns>The updated WorkbookTableSort.</returns> public System.Threading.Tasks.Task<WorkbookTableSort> UpdateAsync(WorkbookTableSort workbookTableSortToUpdate) { return this.UpdateAsync(workbookTableSortToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified WorkbookTableSort using PATCH. /// </summary> /// <param name="workbookTableSortToUpdate">The WorkbookTableSort to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated WorkbookTableSort.</returns> public async System.Threading.Tasks.Task<WorkbookTableSort> UpdateAsync(WorkbookTableSort workbookTableSortToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<WorkbookTableSort>(workbookTableSortToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookTableSortRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookTableSortRequest Expand(Expression<Func<WorkbookTableSort, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookTableSortRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IWorkbookTableSortRequest Select(Expression<Func<WorkbookTableSort, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="workbookTableSortToInitialize">The <see cref="WorkbookTableSort"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(WorkbookTableSort workbookTableSortToInitialize) { } } }
43.143541
161
0.618609
[ "MIT" ]
AzureMentor/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/WorkbookTableSortRequest.cs
9,017
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ConcatenateDocuments")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConcatenateDocuments")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("03afef3e-ef50-41d0-98be-61e487bc9204")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.189189
84
0.748054
[ "MIT" ]
Contasimple-Engineering/PDFsharp-samples
samples/wpf/ConcatenateDocuments/Properties/AssemblyInfo.cs
1,416
C#
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\shared\d3dkmddi.h(560,9) using System; using System.Runtime.InteropServices; namespace DirectN { [StructLayout(LayoutKind.Sequential)] public partial struct _D3DKM_TRANSPARENTBLTFLAGS__union_0__struct_0 { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public byte[] __bits; public uint HonorAlpha { get => InteropRuntime.GetUInt32(__bits, 0, 1); set { if (__bits == null) __bits = new byte[1]; InteropRuntime.SetUInt32(value, __bits, 0, 1); } } } }
41.125
178
0.724924
[ "MIT" ]
riQQ/DirectN
DirectN/DirectN/Generated/_D3DKM_TRANSPARENTBLTFLAGS__union_0__struct_0.cs
660
C#
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Application.Common.Interfaces; using Application.Common.Models; using Domain.Event; using MediatR; using Microsoft.Extensions.Logging; namespace Application.Cities.EventHandler { public class CityCreatedEventHandler : INotificationHandler<DomainEventNotification<CityCreatedEvent>> { private readonly ILogger<CityActivatedEventHandler> _logger; private readonly IEmailService _emailService; public CityCreatedEventHandler(ILogger<CityActivatedEventHandler> logger, IEmailService emailService) { _logger = logger; _emailService = emailService; } public async Task Handle(DomainEventNotification<CityCreatedEvent> notification, CancellationToken cancellationToken) { var domainEvent = notification.DomainEvent; _logger.LogInformation("CleanArchitecture Domain Event: {DomainEvent}", domainEvent.GetType().Name); if (domainEvent.City != null) { await _emailService.SendAsync(new EmailRequest { Subject = domainEvent.City.Name + " is created.", Body = "City is created successfully.", FromDisplayName = "Clean Architecture", FromMail = "test@test.com", ToMail = new List<string> { "to@test.com" } }); } } } }
35.186047
125
0.64772
[ "MIT" ]
digaomatias/CleanArchitecture
src/Common/Application/Cities/EventHandler/CityCreatedEventHandler.cs
1,515
C#
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Miru.Fabrication; using Miru.Foundation.Hosting; using Miru.Testing; using Miru.Testing.Userfy; using Supportreon.Domain; using Supportreon.Tests.Features.Donations; namespace Supportreon.Tests.Config { public class TestsConfig : ITestConfig { public virtual void ConfigureTestServices(IServiceCollection services) { services .AddFeatureTesting() .AddSqliteDatabaseCleaner() .AddFabrication<SupportreonFabricator>(); // Mock your services that talk with external apps // services.Mock<IService>(); } public void ConfigureRun(TestRunConfig run) { // This run configurations only works for tests that inherits MiruTest // It includes FeatureTest, PageTest, and all other Miru's types of tests run.BeforeSuite(_ => { _.MigrateDatabase(); }); run.BeforeCase(_ => { _.Logout(); _.ClearFabricator(); _.ClearDatabase(); _.ClearQueue(); }); run.BeforeCase<AuthorizationTest>(_ => { _.Logout(); }); run.BeforeCase<IRequiresAuthenticatedUser>(_ => { _.MakeSavingLogin(_.Fab().Make<User>()); }); } public virtual IHostBuilder GetHostBuilder() { return MiruHost.CreateMiruHost<Startup>(); } } }
27.836066
85
0.539458
[ "MIT" ]
joaofx/Supportreon
tests/Supportreon.Tests/Config/TestConfig.cs
1,698
C#
using System; using System.Collections.Generic; using System.Text; namespace Lab8_CS { class FirstTask { public delegate int LineOperator(string str, char ch); public static int FirstChar(string str, char ch) => str.IndexOf(ch); public int firstChar(string str, char ch) => str.IndexOf(ch); } }
23.785714
76
0.675676
[ "Apache-2.0" ]
AshBringer47/KPI_OOP
Lab8/Lab8_CS/FirstTask.cs
335
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; namespace Aop.Api.Domain { /// <summary> /// DeviceRelationData Data Structure. /// </summary> [Serializable] public class DeviceRelationData : AopObject { /// <summary> /// 生效计划id列表 /// </summary> [XmlArray("plan_id_list")] [XmlArrayItem("number")] public List<long> PlanIdList { get; set; } /// <summary> /// 设备sn /// </summary> [XmlElement("sn")] public string Sn { get; set; } } }
22.555556
51
0.530378
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Domain/DeviceRelationData.cs
625
C#
using System.Collections.Generic; using System.Xml.Serialization; using Alipay.AopSdk.Core.Domain; namespace Alipay.AopSdk.Core.Response { /// <summary> /// AlipayUserTradeSearchResponse. /// </summary> public class AlipayUserTradeSearchResponse : AopResponse { /// <summary> /// 总页数 /// </summary> [XmlElement("total_pages")] public string TotalPages { get; set; } /// <summary> /// 总记录数 /// </summary> [XmlElement("total_results")] public string TotalResults { get; set; } /// <summary> /// 交易记录列表 /// </summary> [XmlArray("trade_records")] [XmlArrayItem("trade_record")] public List<TradeRecord> TradeRecords { get; set; } } }
24.53125
60
0.574522
[ "MIT" ]
leixf2005/Alipay.AopSdk.Core
Alipay.AopSdk.Core/Response/AlipayUserTradeSearchResponse.cs
811
C#
using System; namespace _01._Smallest_of_three { class Program { static int SmallestOfThree(int firstNum, int secondNum, int thirdNum) { return Math.Min(firstNum, Math.Min(secondNum, thirdNum)); } static void Main(string[] args) { int first = int.Parse(Console.ReadLine()); int second = int.Parse(Console.ReadLine()); int third = int.Parse(Console.ReadLine()); Console.WriteLine(SmallestOfThree(first, second, third)); } } }
27.35
77
0.586837
[ "MIT" ]
DeyanDanailov/SoftUniCSharpFundamentals
repos/01. Smallest of three/Program.cs
549
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.AzureNative.Maps.Outputs { [OutputType] public sealed class CreatorPropertiesResponse { /// <summary> /// The state of the resource provisioning, terminal states: Succeeded, Failed, Canceled /// </summary> public readonly string? ProvisioningState; [OutputConstructor] private CreatorPropertiesResponse(string? provisioningState) { ProvisioningState = provisioningState; } } }
28.107143
96
0.687421
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Maps/Outputs/CreatorPropertiesResponse.cs
787
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Lclb.Cllb.Interfaces.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Microsoft.Dynamics.CRM.duplicaterecord /// </summary> public partial class MicrosoftDynamicsCRMduplicaterecord { /// <summary> /// Initializes a new instance of the /// MicrosoftDynamicsCRMduplicaterecord class. /// </summary> public MicrosoftDynamicsCRMduplicaterecord() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// MicrosoftDynamicsCRMduplicaterecord class. /// </summary> public MicrosoftDynamicsCRMduplicaterecord(string owninguser = default(string), string _duplicateruleidValue = default(string), System.DateTimeOffset? createdon = default(System.DateTimeOffset?), string _owneridValue = default(string), string owningbusinessunit = default(string), string _asyncoperationidValue = default(string), string _baserecordidValue = default(string), string duplicateid = default(string), string _duplicaterecordidValue = default(string), MicrosoftDynamicsCRMknowledgearticle duplicaterecordidKnowledgearticle = default(MicrosoftDynamicsCRMknowledgearticle), MicrosoftDynamicsCRMknowledgearticle baserecordidKnowledgearticle = default(MicrosoftDynamicsCRMknowledgearticle), MicrosoftDynamicsCRMentitlement duplicaterecordidEntitlement = default(MicrosoftDynamicsCRMentitlement), MicrosoftDynamicsCRMentitlement baserecordidEntitlement = default(MicrosoftDynamicsCRMentitlement), MicrosoftDynamicsCRMentitlementchannel duplicaterecordidEntitlementchannel = default(MicrosoftDynamicsCRMentitlementchannel), MicrosoftDynamicsCRMentitlementchannel baserecordidEntitlementchannel = default(MicrosoftDynamicsCRMentitlementchannel), MicrosoftDynamicsCRMentitlementtemplate duplicaterecordidEntitlementtemplate = default(MicrosoftDynamicsCRMentitlementtemplate), MicrosoftDynamicsCRMentitlementtemplate baserecordidEntitlementtemplate = default(MicrosoftDynamicsCRMentitlementtemplate), MicrosoftDynamicsCRMbookableresource duplicaterecordidBookableresource = default(MicrosoftDynamicsCRMbookableresource), MicrosoftDynamicsCRMbookableresource baserecordidBookableresource = default(MicrosoftDynamicsCRMbookableresource), MicrosoftDynamicsCRMbookableresourcebooking duplicaterecordidBookableresourcebooking = default(MicrosoftDynamicsCRMbookableresourcebooking), MicrosoftDynamicsCRMbookableresourcebooking baserecordidBookableresourcebooking = default(MicrosoftDynamicsCRMbookableresourcebooking), MicrosoftDynamicsCRMbookableresourcebookingheader duplicaterecordidBookableresourcebookingheader = default(MicrosoftDynamicsCRMbookableresourcebookingheader), MicrosoftDynamicsCRMbookableresourcebookingheader baserecordidBookableresourcebookingheader = default(MicrosoftDynamicsCRMbookableresourcebookingheader), MicrosoftDynamicsCRMbookableresourcecategory duplicaterecordidBookableresourcecategory = default(MicrosoftDynamicsCRMbookableresourcecategory), MicrosoftDynamicsCRMbookableresourcecategory baserecordidBookableresourcecategory = default(MicrosoftDynamicsCRMbookableresourcecategory), MicrosoftDynamicsCRMbookableresourcecategoryassn duplicaterecordidBookableresourcecategoryassn = default(MicrosoftDynamicsCRMbookableresourcecategoryassn), MicrosoftDynamicsCRMbookableresourcecategoryassn baserecordidBookableresourcecategoryassn = default(MicrosoftDynamicsCRMbookableresourcecategoryassn), MicrosoftDynamicsCRMbookableresourcecharacteristic duplicaterecordidBookableresourcecharacteristic = default(MicrosoftDynamicsCRMbookableresourcecharacteristic), MicrosoftDynamicsCRMbookableresourcecharacteristic baserecordidBookableresourcecharacteristic = default(MicrosoftDynamicsCRMbookableresourcecharacteristic), MicrosoftDynamicsCRMbookableresourcegroup duplicaterecordidBookableresourcegroup = default(MicrosoftDynamicsCRMbookableresourcegroup), MicrosoftDynamicsCRMbookableresourcegroup baserecordidBookableresourcegroup = default(MicrosoftDynamicsCRMbookableresourcegroup), MicrosoftDynamicsCRMbookingstatus duplicaterecordidBookingstatus = default(MicrosoftDynamicsCRMbookingstatus), MicrosoftDynamicsCRMbookingstatus baserecordidBookingstatus = default(MicrosoftDynamicsCRMbookingstatus), MicrosoftDynamicsCRMcharacteristic duplicaterecordidCharacteristic = default(MicrosoftDynamicsCRMcharacteristic), MicrosoftDynamicsCRMcharacteristic baserecordidCharacteristic = default(MicrosoftDynamicsCRMcharacteristic), MicrosoftDynamicsCRMratingmodel duplicaterecordidRatingmodel = default(MicrosoftDynamicsCRMratingmodel), MicrosoftDynamicsCRMratingmodel baserecordidRatingmodel = default(MicrosoftDynamicsCRMratingmodel), MicrosoftDynamicsCRMratingvalue duplicaterecordidRatingvalue = default(MicrosoftDynamicsCRMratingvalue), MicrosoftDynamicsCRMratingvalue baserecordidRatingvalue = default(MicrosoftDynamicsCRMratingvalue), MicrosoftDynamicsCRMknowledgebaserecord duplicaterecordidKnowledgebaserecord = default(MicrosoftDynamicsCRMknowledgebaserecord), MicrosoftDynamicsCRMknowledgebaserecord baserecordidKnowledgebaserecord = default(MicrosoftDynamicsCRMknowledgebaserecord), MicrosoftDynamicsCRMmsdynPostalbum duplicaterecordidMsdynPostalbum = default(MicrosoftDynamicsCRMmsdynPostalbum), MicrosoftDynamicsCRMmsdynPostalbum baserecordidMsdynPostalbum = default(MicrosoftDynamicsCRMmsdynPostalbum), MicrosoftDynamicsCRMadoxioAlias duplicaterecordidAdoxioAlias = default(MicrosoftDynamicsCRMadoxioAlias), MicrosoftDynamicsCRMadoxioAlias baserecordidAdoxioAlias = default(MicrosoftDynamicsCRMadoxioAlias), MicrosoftDynamicsCRMadoxioApplication duplicaterecordidAdoxioApplication = default(MicrosoftDynamicsCRMadoxioApplication), MicrosoftDynamicsCRMadoxioApplication baserecordidAdoxioApplication = default(MicrosoftDynamicsCRMadoxioApplication), MicrosoftDynamicsCRMadoxioApplicationinvoicehistory duplicaterecordidAdoxioApplicationinvoicehistory = default(MicrosoftDynamicsCRMadoxioApplicationinvoicehistory), MicrosoftDynamicsCRMadoxioApplicationinvoicehistory baserecordidAdoxioApplicationinvoicehistory = default(MicrosoftDynamicsCRMadoxioApplicationinvoicehistory), MicrosoftDynamicsCRMadoxioApplicationtermsconditionslimitation duplicaterecordidAdoxioApplicationtermsconditionslimitation = default(MicrosoftDynamicsCRMadoxioApplicationtermsconditionslimitation), MicrosoftDynamicsCRMadoxioApplicationtermsconditionslimitation baserecordidAdoxioApplicationtermsconditionslimitation = default(MicrosoftDynamicsCRMadoxioApplicationtermsconditionslimitation), MicrosoftDynamicsCRMadoxioArea duplicaterecordidAdoxioArea = default(MicrosoftDynamicsCRMadoxioArea), MicrosoftDynamicsCRMadoxioArea baserecordidAdoxioArea = default(MicrosoftDynamicsCRMadoxioArea), MicrosoftDynamicsCRMadoxioBusinessaccount duplicaterecordidAdoxioBusinessaccount = default(MicrosoftDynamicsCRMadoxioBusinessaccount), MicrosoftDynamicsCRMadoxioBusinessaccount baserecordidAdoxioBusinessaccount = default(MicrosoftDynamicsCRMadoxioBusinessaccount), MicrosoftDynamicsCRMadoxioCitydistrict duplicaterecordidAdoxioCitydistrict = default(MicrosoftDynamicsCRMadoxioCitydistrict), MicrosoftDynamicsCRMadoxioCitydistrict baserecordidAdoxioCitydistrict = default(MicrosoftDynamicsCRMadoxioCitydistrict), MicrosoftDynamicsCRMadoxioComplaint duplicaterecordidAdoxioComplaint = default(MicrosoftDynamicsCRMadoxioComplaint), MicrosoftDynamicsCRMadoxioComplaint baserecordidAdoxioComplaint = default(MicrosoftDynamicsCRMadoxioComplaint), MicrosoftDynamicsCRMadoxioContravention duplicaterecordidAdoxioContravention = default(MicrosoftDynamicsCRMadoxioContravention), MicrosoftDynamicsCRMadoxioContravention baserecordidAdoxioContravention = default(MicrosoftDynamicsCRMadoxioContravention), MicrosoftDynamicsCRMadoxioCorporatehistorysummary duplicaterecordidAdoxioCorporatehistorysummary = default(MicrosoftDynamicsCRMadoxioCorporatehistorysummary), MicrosoftDynamicsCRMadoxioCorporatehistorysummary baserecordidAdoxioCorporatehistorysummary = default(MicrosoftDynamicsCRMadoxioCorporatehistorysummary), MicrosoftDynamicsCRMadoxioEstablishment duplicaterecordidAdoxioEstablishment = default(MicrosoftDynamicsCRMadoxioEstablishment), MicrosoftDynamicsCRMadoxioEstablishment baserecordidAdoxioEstablishment = default(MicrosoftDynamicsCRMadoxioEstablishment), MicrosoftDynamicsCRMadoxioFundingsource duplicaterecordidAdoxioFundingsource = default(MicrosoftDynamicsCRMadoxioFundingsource), MicrosoftDynamicsCRMadoxioFundingsource baserecordidAdoxioFundingsource = default(MicrosoftDynamicsCRMadoxioFundingsource), MicrosoftDynamicsCRMadoxioInterest duplicaterecordidAdoxioInterest = default(MicrosoftDynamicsCRMadoxioInterest), MicrosoftDynamicsCRMadoxioInterest baserecordidAdoxioInterest = default(MicrosoftDynamicsCRMadoxioInterest), MicrosoftDynamicsCRMadoxioInvestigation duplicaterecordidAdoxioInvestigation = default(MicrosoftDynamicsCRMadoxioInvestigation), MicrosoftDynamicsCRMadoxioInvestigation baserecordidAdoxioInvestigation = default(MicrosoftDynamicsCRMadoxioInvestigation), MicrosoftDynamicsCRMadoxioLegalentity duplicaterecordidAdoxioLegalentity = default(MicrosoftDynamicsCRMadoxioLegalentity), MicrosoftDynamicsCRMadoxioLegalentity baserecordidAdoxioLegalentity = default(MicrosoftDynamicsCRMadoxioLegalentity), MicrosoftDynamicsCRMadoxioLicences duplicaterecordidAdoxioLicences = default(MicrosoftDynamicsCRMadoxioLicences), MicrosoftDynamicsCRMadoxioLicences baserecordidAdoxioLicences = default(MicrosoftDynamicsCRMadoxioLicences), MicrosoftDynamicsCRMadoxioLicencetype duplicaterecordidAdoxioLicencetype = default(MicrosoftDynamicsCRMadoxioLicencetype), MicrosoftDynamicsCRMadoxioLicencetype baserecordidAdoxioLicencetype = default(MicrosoftDynamicsCRMadoxioLicencetype), MicrosoftDynamicsCRMadoxioLoan duplicaterecordidAdoxioLoan = default(MicrosoftDynamicsCRMadoxioLoan), MicrosoftDynamicsCRMadoxioLoan baserecordidAdoxioLoan = default(MicrosoftDynamicsCRMadoxioLoan), MicrosoftDynamicsCRMadoxioLocalgovindigenousnation duplicaterecordidAdoxioLocalgovindigenousnation = default(MicrosoftDynamicsCRMadoxioLocalgovindigenousnation), MicrosoftDynamicsCRMadoxioLocalgovindigenousnation baserecordidAdoxioLocalgovindigenousnation = default(MicrosoftDynamicsCRMadoxioLocalgovindigenousnation), MicrosoftDynamicsCRMadoxioPersonalhistorysummary duplicaterecordidAdoxioPersonalhistorysummary = default(MicrosoftDynamicsCRMadoxioPersonalhistorysummary), MicrosoftDynamicsCRMadoxioPersonalhistorysummary baserecordidAdoxioPersonalhistorysummary = default(MicrosoftDynamicsCRMadoxioPersonalhistorysummary), MicrosoftDynamicsCRMadoxioPolicejurisdiction duplicaterecordidAdoxioPolicejurisdiction = default(MicrosoftDynamicsCRMadoxioPolicejurisdiction), MicrosoftDynamicsCRMadoxioPolicejurisdiction baserecordidAdoxioPolicejurisdiction = default(MicrosoftDynamicsCRMadoxioPolicejurisdiction), MicrosoftDynamicsCRMadoxioPolicydocument duplicaterecordidAdoxioPolicydocument = default(MicrosoftDynamicsCRMadoxioPolicydocument), MicrosoftDynamicsCRMadoxioPolicydocument baserecordidAdoxioPolicydocument = default(MicrosoftDynamicsCRMadoxioPolicydocument), MicrosoftDynamicsCRMadoxioPostalcode duplicaterecordidAdoxioPostalcode = default(MicrosoftDynamicsCRMadoxioPostalcode), MicrosoftDynamicsCRMadoxioPostalcode baserecordidAdoxioPostalcode = default(MicrosoftDynamicsCRMadoxioPostalcode), MicrosoftDynamicsCRMadoxioRegion duplicaterecordidAdoxioRegion = default(MicrosoftDynamicsCRMadoxioRegion), MicrosoftDynamicsCRMadoxioRegion baserecordidAdoxioRegion = default(MicrosoftDynamicsCRMadoxioRegion), MicrosoftDynamicsCRMadoxioSetting duplicaterecordidAdoxioSetting = default(MicrosoftDynamicsCRMadoxioSetting), MicrosoftDynamicsCRMadoxioSetting baserecordidAdoxioSetting = default(MicrosoftDynamicsCRMadoxioSetting), MicrosoftDynamicsCRMadoxioTaxandaccounting duplicaterecordidAdoxioTaxandaccounting = default(MicrosoftDynamicsCRMadoxioTaxandaccounting), MicrosoftDynamicsCRMadoxioTaxandaccounting baserecordidAdoxioTaxandaccounting = default(MicrosoftDynamicsCRMadoxioTaxandaccounting), MicrosoftDynamicsCRMadoxioTermsconditionslimitationspreset duplicaterecordidAdoxioTermsconditionslimitationspreset = default(MicrosoftDynamicsCRMadoxioTermsconditionslimitationspreset), MicrosoftDynamicsCRMadoxioTermsconditionslimitationspreset baserecordidAdoxioTermsconditionslimitationspreset = default(MicrosoftDynamicsCRMadoxioTermsconditionslimitationspreset), MicrosoftDynamicsCRMadoxioTerritory duplicaterecordidAdoxioTerritory = default(MicrosoftDynamicsCRMadoxioTerritory), MicrosoftDynamicsCRMadoxioTerritory baserecordidAdoxioTerritory = default(MicrosoftDynamicsCRMadoxioTerritory), MicrosoftDynamicsCRMadoxioTiedhouseassociation duplicaterecordidAdoxioTiedhouseassociation = default(MicrosoftDynamicsCRMadoxioTiedhouseassociation), MicrosoftDynamicsCRMadoxioTiedhouseassociation baserecordidAdoxioTiedhouseassociation = default(MicrosoftDynamicsCRMadoxioTiedhouseassociation), MicrosoftDynamicsCRMadoxioTiedhouseconnection duplicaterecordidAdoxioTiedhouseconnection = default(MicrosoftDynamicsCRMadoxioTiedhouseconnection), MicrosoftDynamicsCRMadoxioTiedhouseconnection baserecordidAdoxioTiedhouseconnection = default(MicrosoftDynamicsCRMadoxioTiedhouseconnection), MicrosoftDynamicsCRMadoxioWorker duplicaterecordidAdoxioWorker = default(MicrosoftDynamicsCRMadoxioWorker), MicrosoftDynamicsCRMadoxioWorker baserecordidAdoxioWorker = default(MicrosoftDynamicsCRMadoxioWorker), MicrosoftDynamicsCRMadoxioDocument duplicaterecordidAdoxioDocument = default(MicrosoftDynamicsCRMadoxioDocument), MicrosoftDynamicsCRMadoxioDocument baserecordidAdoxioDocument = default(MicrosoftDynamicsCRMadoxioDocument), MicrosoftDynamicsCRMadoxioDocumentadmin duplicaterecordidAdoxioDocumentadmin = default(MicrosoftDynamicsCRMadoxioDocumentadmin), MicrosoftDynamicsCRMadoxioDocumentadmin baserecordidAdoxioDocumentadmin = default(MicrosoftDynamicsCRMadoxioDocumentadmin), MicrosoftDynamicsCRMadoxioContraventionadmin duplicaterecordidAdoxioContraventionadmin = default(MicrosoftDynamicsCRMadoxioContraventionadmin), MicrosoftDynamicsCRMadoxioContraventionadmin baserecordidAdoxioContraventionadmin = default(MicrosoftDynamicsCRMadoxioContraventionadmin), MicrosoftDynamicsCRMadoxioCompliancemeeting duplicaterecordidAdoxioCompliancemeeting = default(MicrosoftDynamicsCRMadoxioCompliancemeeting), MicrosoftDynamicsCRMadoxioCompliancemeeting baserecordidAdoxioCompliancemeeting = default(MicrosoftDynamicsCRMadoxioCompliancemeeting), MicrosoftDynamicsCRMadoxioInvestigationactivity duplicaterecordidAdoxioInvestigationactivity = default(MicrosoftDynamicsCRMadoxioInvestigationactivity), MicrosoftDynamicsCRMadoxioInvestigationactivity baserecordidAdoxioInvestigationactivity = default(MicrosoftDynamicsCRMadoxioInvestigationactivity), MicrosoftDynamicsCRMadoxioComplianceinvestigation duplicaterecordidAdoxioComplianceinvestigation = default(MicrosoftDynamicsCRMadoxioComplianceinvestigation), MicrosoftDynamicsCRMadoxioComplianceinvestigation baserecordidAdoxioComplianceinvestigation = default(MicrosoftDynamicsCRMadoxioComplianceinvestigation), MicrosoftDynamicsCRMadoxioFiainvestigationlog duplicaterecordidAdoxioFiainvestigationlog = default(MicrosoftDynamicsCRMadoxioFiainvestigationlog), MicrosoftDynamicsCRMadoxioFiainvestigationlog baserecordidAdoxioFiainvestigationlog = default(MicrosoftDynamicsCRMadoxioFiainvestigationlog), MicrosoftDynamicsCRMadoxioApplicationtype duplicaterecordidAdoxioApplicationtype = default(MicrosoftDynamicsCRMadoxioApplicationtype), MicrosoftDynamicsCRMadoxioApplicationtype baserecordidAdoxioApplicationtype = default(MicrosoftDynamicsCRMadoxioApplicationtype), MicrosoftDynamicsCRMadoxioApplicationtypecontent duplicaterecordidAdoxioApplicationtypecontent = default(MicrosoftDynamicsCRMadoxioApplicationtypecontent), MicrosoftDynamicsCRMadoxioApplicationtypecontent baserecordidAdoxioApplicationtypecontent = default(MicrosoftDynamicsCRMadoxioApplicationtypecontent), MicrosoftDynamicsCRMadoxioInspectionreactivationhistory duplicaterecordidAdoxioInspectionreactivationhistory = default(MicrosoftDynamicsCRMadoxioInspectionreactivationhistory), MicrosoftDynamicsCRMadoxioInspectionreactivationhistory baserecordidAdoxioInspectionreactivationhistory = default(MicrosoftDynamicsCRMadoxioInspectionreactivationhistory), MicrosoftDynamicsCRMadoxioEstablishmentwatchword duplicaterecordidAdoxioEstablishmentwatchword = default(MicrosoftDynamicsCRMadoxioEstablishmentwatchword), MicrosoftDynamicsCRMadoxioEstablishmentwatchword baserecordidAdoxioEstablishmentwatchword = default(MicrosoftDynamicsCRMadoxioEstablishmentwatchword), MicrosoftDynamicsCRMadoxioRelatedparty duplicaterecordidAdoxioRelatedparty = default(MicrosoftDynamicsCRMadoxioRelatedparty), MicrosoftDynamicsCRMadoxioRelatedparty baserecordidAdoxioRelatedparty = default(MicrosoftDynamicsCRMadoxioRelatedparty), MicrosoftDynamicsCRMadoxioWitness duplicaterecordidAdoxioWitness = default(MicrosoftDynamicsCRMadoxioWitness), MicrosoftDynamicsCRMadoxioWitness baserecordidAdoxioWitness = default(MicrosoftDynamicsCRMadoxioWitness), MicrosoftDynamicsCRMadoxioCannabismonthlyreport duplicaterecordidAdoxioCannabismonthlyreport = default(MicrosoftDynamicsCRMadoxioCannabismonthlyreport), MicrosoftDynamicsCRMadoxioCannabismonthlyreport baserecordidAdoxioCannabismonthlyreport = default(MicrosoftDynamicsCRMadoxioCannabismonthlyreport), MicrosoftDynamicsCRMadoxioCannabisproductadmin duplicaterecordidAdoxioCannabisproductadmin = default(MicrosoftDynamicsCRMadoxioCannabisproductadmin), MicrosoftDynamicsCRMadoxioCannabisproductadmin baserecordidAdoxioCannabisproductadmin = default(MicrosoftDynamicsCRMadoxioCannabisproductadmin), MicrosoftDynamicsCRMadoxioCannabisinventoryreport duplicaterecordidAdoxioCannabisinventoryreport = default(MicrosoftDynamicsCRMadoxioCannabisinventoryreport), MicrosoftDynamicsCRMadoxioCannabisinventoryreport baserecordidAdoxioCannabisinventoryreport = default(MicrosoftDynamicsCRMadoxioCannabisinventoryreport), MicrosoftDynamicsCRMadoxioInvestigationreactivationhistory duplicaterecordidAdoxioInvestigationreactivationhistory = default(MicrosoftDynamicsCRMadoxioInvestigationreactivationhistory), MicrosoftDynamicsCRMadoxioInvestigationreactivationhistory baserecordidAdoxioInvestigationreactivationhistory = default(MicrosoftDynamicsCRMadoxioInvestigationreactivationhistory), MicrosoftDynamicsCRMadoxioAuditlogrequest duplicaterecordidAdoxioAuditlogrequest = default(MicrosoftDynamicsCRMadoxioAuditlogrequest), MicrosoftDynamicsCRMadoxioAuditlogrequest baserecordidAdoxioAuditlogrequest = default(MicrosoftDynamicsCRMadoxioAuditlogrequest), MicrosoftDynamicsCRMadoxioExhibit duplicaterecordidAdoxioExhibit = default(MicrosoftDynamicsCRMadoxioExhibit), MicrosoftDynamicsCRMadoxioExhibit baserecordidAdoxioExhibit = default(MicrosoftDynamicsCRMadoxioExhibit), MicrosoftDynamicsCRMadoxioFormelementuploadfield duplicaterecordidAdoxioFormelementuploadfield = default(MicrosoftDynamicsCRMadoxioFormelementuploadfield), MicrosoftDynamicsCRMadoxioFormelementuploadfield baserecordidAdoxioFormelementuploadfield = default(MicrosoftDynamicsCRMadoxioFormelementuploadfield), MicrosoftDynamicsCRMmsdynRelationshipinsightsunifiedconfig duplicaterecordidMsdynRelationshipinsightsunifiedconfig = default(MicrosoftDynamicsCRMmsdynRelationshipinsightsunifiedconfig), MicrosoftDynamicsCRMmsdynRelationshipinsightsunifiedconfig baserecordidMsdynRelationshipinsightsunifiedconfig = default(MicrosoftDynamicsCRMmsdynRelationshipinsightsunifiedconfig), MicrosoftDynamicsCRMmsdynSiconfig duplicaterecordidMsdynSiconfig = default(MicrosoftDynamicsCRMmsdynSiconfig), MicrosoftDynamicsCRMmsdynSiconfig baserecordidMsdynSiconfig = default(MicrosoftDynamicsCRMmsdynSiconfig), MicrosoftDynamicsCRMadminsettingsentity duplicaterecordidAdminsettingsentity = default(MicrosoftDynamicsCRMadminsettingsentity), MicrosoftDynamicsCRMadminsettingsentity baserecordidAdminsettingsentity = default(MicrosoftDynamicsCRMadminsettingsentity), MicrosoftDynamicsCRMadoxioEvent duplicaterecordidAdoxioEvent = default(MicrosoftDynamicsCRMadoxioEvent), MicrosoftDynamicsCRMadoxioEvent baserecordidAdoxioEvent = default(MicrosoftDynamicsCRMadoxioEvent), MicrosoftDynamicsCRMadoxioEventschedule duplicaterecordidAdoxioEventschedule = default(MicrosoftDynamicsCRMadoxioEventschedule), MicrosoftDynamicsCRMadoxioEventschedule baserecordidAdoxioEventschedule = default(MicrosoftDynamicsCRMadoxioEventschedule), MicrosoftDynamicsCRMadoxioFederalreportexport duplicaterecordidAdoxioFederalreportexport = default(MicrosoftDynamicsCRMadoxioFederalreportexport), MicrosoftDynamicsCRMadoxioFederalreportexport baserecordidAdoxioFederalreportexport = default(MicrosoftDynamicsCRMadoxioFederalreportexport), MicrosoftDynamicsCRMadoxioLdborder duplicaterecordidAdoxioLdborder = default(MicrosoftDynamicsCRMadoxioLdborder), MicrosoftDynamicsCRMadoxioLdborder baserecordidAdoxioLdborder = default(MicrosoftDynamicsCRMadoxioLdborder), MicrosoftDynamicsCRMadoxioApplicationtypefeeschedule duplicaterecordidAdoxioApplicationtypefeeschedule = default(MicrosoftDynamicsCRMadoxioApplicationtypefeeschedule), MicrosoftDynamicsCRMadoxioApplicationtypefeeschedule baserecordidAdoxioApplicationtypefeeschedule = default(MicrosoftDynamicsCRMadoxioApplicationtypefeeschedule), MicrosoftDynamicsCRMadoxioEndorsement duplicaterecordidAdoxioEndorsement = default(MicrosoftDynamicsCRMadoxioEndorsement), MicrosoftDynamicsCRMadoxioEndorsement baserecordidAdoxioEndorsement = default(MicrosoftDynamicsCRMadoxioEndorsement), MicrosoftDynamicsCRMadoxioLicenceldbordertotalhistory duplicaterecordidAdoxioLicenceldbordertotalhistory = default(MicrosoftDynamicsCRMadoxioLicenceldbordertotalhistory), MicrosoftDynamicsCRMadoxioLicenceldbordertotalhistory baserecordidAdoxioLicenceldbordertotalhistory = default(MicrosoftDynamicsCRMadoxioLicenceldbordertotalhistory), MicrosoftDynamicsCRMadoxioRmreview duplicaterecordidAdoxioRmreview = default(MicrosoftDynamicsCRMadoxioRmreview), MicrosoftDynamicsCRMadoxioRmreview baserecordidAdoxioRmreview = default(MicrosoftDynamicsCRMadoxioRmreview), MicrosoftDynamicsCRMadoxioEnforcementaction duplicaterecordidAdoxioEnforcementaction = default(MicrosoftDynamicsCRMadoxioEnforcementaction), MicrosoftDynamicsCRMadoxioEnforcementaction baserecordidAdoxioEnforcementaction = default(MicrosoftDynamicsCRMadoxioEnforcementaction), MicrosoftDynamicsCRMadoxioServicearea duplicaterecordidAdoxioServicearea = default(MicrosoftDynamicsCRMadoxioServicearea), MicrosoftDynamicsCRMadoxioServicearea baserecordidAdoxioServicearea = default(MicrosoftDynamicsCRMadoxioServicearea), MicrosoftDynamicsCRMadoxioAnnualvolume duplicaterecordidAdoxioAnnualvolume = default(MicrosoftDynamicsCRMadoxioAnnualvolume), MicrosoftDynamicsCRMadoxioAnnualvolume baserecordidAdoxioAnnualvolume = default(MicrosoftDynamicsCRMadoxioAnnualvolume), MicrosoftDynamicsCRMadoxioHoursofservice duplicaterecordidAdoxioHoursofservice = default(MicrosoftDynamicsCRMadoxioHoursofservice), MicrosoftDynamicsCRMadoxioHoursofservice baserecordidAdoxioHoursofservice = default(MicrosoftDynamicsCRMadoxioHoursofservice), MicrosoftDynamicsCRMadoxioPmuarea duplicaterecordidAdoxioPmuarea = default(MicrosoftDynamicsCRMadoxioPmuarea), MicrosoftDynamicsCRMadoxioPmuarea baserecordidAdoxioPmuarea = default(MicrosoftDynamicsCRMadoxioPmuarea), MicrosoftDynamicsCRMadoxioInspectorreport duplicaterecordidAdoxioInspectorreport = default(MicrosoftDynamicsCRMadoxioInspectorreport), MicrosoftDynamicsCRMadoxioInspectorreport baserecordidAdoxioInspectorreport = default(MicrosoftDynamicsCRMadoxioInspectorreport), MicrosoftDynamicsCRMadoxioOffsitestorage duplicaterecordidAdoxioOffsitestorage = default(MicrosoftDynamicsCRMadoxioOffsitestorage), MicrosoftDynamicsCRMadoxioOffsitestorage baserecordidAdoxioOffsitestorage = default(MicrosoftDynamicsCRMadoxioOffsitestorage), MicrosoftDynamicsCRMgoalrollupquery baserecordidGoalrollupquery = default(MicrosoftDynamicsCRMgoalrollupquery), MicrosoftDynamicsCRMpublisher duplicaterecordidPublisher = default(MicrosoftDynamicsCRMpublisher), MicrosoftDynamicsCRMtransactioncurrency baserecordidTransactioncurrency = default(MicrosoftDynamicsCRMtransactioncurrency), MicrosoftDynamicsCRMcampaign baserecordidCampaign = default(MicrosoftDynamicsCRMcampaign), MicrosoftDynamicsCRMlead baserecordidLead = default(MicrosoftDynamicsCRMlead), MicrosoftDynamicsCRMrecurringappointmentmaster baserecordidRecurringappointmentmaster = default(MicrosoftDynamicsCRMrecurringappointmentmaster), MicrosoftDynamicsCRMgoal duplicaterecordidGoal = default(MicrosoftDynamicsCRMgoal), MicrosoftDynamicsCRMtransactioncurrency duplicaterecordidTransactioncurrency = default(MicrosoftDynamicsCRMtransactioncurrency), MicrosoftDynamicsCRMcompetitor baserecordidCompetitor = default(MicrosoftDynamicsCRMcompetitor), MicrosoftDynamicsCRMequipment baserecordidEquipment = default(MicrosoftDynamicsCRMequipment), MicrosoftDynamicsCRMtask baserecordidTask = default(MicrosoftDynamicsCRMtask), MicrosoftDynamicsCRMrecurringappointmentmaster duplicaterecordidRecurringappointmentmaster = default(MicrosoftDynamicsCRMrecurringappointmentmaster), MicrosoftDynamicsCRMasyncoperation asyncoperationid = default(MicrosoftDynamicsCRMasyncoperation), MicrosoftDynamicsCRMtask duplicaterecordidTask = default(MicrosoftDynamicsCRMtask), MicrosoftDynamicsCRMequipment duplicaterecordidEquipment = default(MicrosoftDynamicsCRMequipment), MicrosoftDynamicsCRMemail baserecordidEmail = default(MicrosoftDynamicsCRMemail), MicrosoftDynamicsCRMsocialprofile baserecordidSocialprofile = default(MicrosoftDynamicsCRMsocialprofile), MicrosoftDynamicsCRMteam baserecordidTeam = default(MicrosoftDynamicsCRMteam), MicrosoftDynamicsCRMsystemuser baserecordidSystemuser = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMaccount baserecordidAccount = default(MicrosoftDynamicsCRMaccount), MicrosoftDynamicsCRMappointment baserecordidAppointment = default(MicrosoftDynamicsCRMappointment), MicrosoftDynamicsCRMopportunity baserecordidOpportunity = default(MicrosoftDynamicsCRMopportunity), MicrosoftDynamicsCRMcampaign duplicaterecordidCampaign = default(MicrosoftDynamicsCRMcampaign), MicrosoftDynamicsCRMsharepointdocumentlocation baserecordidSharepointdocumentlocation = default(MicrosoftDynamicsCRMsharepointdocumentlocation), MicrosoftDynamicsCRMfax duplicaterecordidFax = default(MicrosoftDynamicsCRMfax), MicrosoftDynamicsCRMterritory duplicaterecordidTerritory = default(MicrosoftDynamicsCRMterritory), MicrosoftDynamicsCRMlist baserecordidList = default(MicrosoftDynamicsCRMlist), MicrosoftDynamicsCRMpublisher baserecordidPublisher = default(MicrosoftDynamicsCRMpublisher), MicrosoftDynamicsCRMsharepointsite duplicaterecordidSharepointsite = default(MicrosoftDynamicsCRMsharepointsite), MicrosoftDynamicsCRMkbarticle duplicaterecordidKbarticle = default(MicrosoftDynamicsCRMkbarticle), MicrosoftDynamicsCRMteam duplicaterecordidTeam = default(MicrosoftDynamicsCRMteam), MicrosoftDynamicsCRMappointment duplicaterecordidAppointment = default(MicrosoftDynamicsCRMappointment), MicrosoftDynamicsCRMcontract baserecordidContract = default(MicrosoftDynamicsCRMcontract), MicrosoftDynamicsCRMincident duplicaterecordidIncident = default(MicrosoftDynamicsCRMincident), MicrosoftDynamicsCRMopportunity duplicaterecordidOpportunity = default(MicrosoftDynamicsCRMopportunity), MicrosoftDynamicsCRMquote duplicaterecordidQuote = default(MicrosoftDynamicsCRMquote), MicrosoftDynamicsCRMphonecall duplicaterecordidPhonecall = default(MicrosoftDynamicsCRMphonecall), MicrosoftDynamicsCRMresourcegroup baserecordidResourcegroup = default(MicrosoftDynamicsCRMresourcegroup), MicrosoftDynamicsCRMterritory baserecordidTerritory = default(MicrosoftDynamicsCRMterritory), MicrosoftDynamicsCRMgoalrollupquery duplicaterecordidGoalrollupquery = default(MicrosoftDynamicsCRMgoalrollupquery), MicrosoftDynamicsCRMsharepointsite baserecordidSharepointsite = default(MicrosoftDynamicsCRMsharepointsite), MicrosoftDynamicsCRMphonecall baserecordidPhonecall = default(MicrosoftDynamicsCRMphonecall), MicrosoftDynamicsCRMcontact duplicaterecordidContact = default(MicrosoftDynamicsCRMcontact), MicrosoftDynamicsCRMcampaignresponse duplicaterecordidCampaignresponse = default(MicrosoftDynamicsCRMcampaignresponse), MicrosoftDynamicsCRMkbarticle baserecordidKbarticle = default(MicrosoftDynamicsCRMkbarticle), MicrosoftDynamicsCRMservice baserecordidService = default(MicrosoftDynamicsCRMservice), MicrosoftDynamicsCRMemail duplicaterecordidEmail = default(MicrosoftDynamicsCRMemail), MicrosoftDynamicsCRMcompetitor duplicaterecordidCompetitor = default(MicrosoftDynamicsCRMcompetitor), MicrosoftDynamicsCRMletter baserecordidLetter = default(MicrosoftDynamicsCRMletter), MicrosoftDynamicsCRMsocialactivity baserecordidSocialactivity = default(MicrosoftDynamicsCRMsocialactivity), MicrosoftDynamicsCRMsystemuser duplicaterecordidSystemuser = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMlead duplicaterecordidLead = default(MicrosoftDynamicsCRMlead), MicrosoftDynamicsCRMsocialactivity duplicaterecordidSocialactivity = default(MicrosoftDynamicsCRMsocialactivity), MicrosoftDynamicsCRMsharepointdocumentlocation duplicaterecordidSharepointdocumentlocation = default(MicrosoftDynamicsCRMsharepointdocumentlocation), MicrosoftDynamicsCRMsocialprofile duplicaterecordidSocialprofile = default(MicrosoftDynamicsCRMsocialprofile), MicrosoftDynamicsCRMgoal baserecordidGoal = default(MicrosoftDynamicsCRMgoal), MicrosoftDynamicsCRMaccount duplicaterecordidAccount = default(MicrosoftDynamicsCRMaccount), MicrosoftDynamicsCRMlist duplicaterecordidList = default(MicrosoftDynamicsCRMlist), MicrosoftDynamicsCRMresourcegroup duplicaterecordidResourcegroup = default(MicrosoftDynamicsCRMresourcegroup), MicrosoftDynamicsCRMcampaignresponse baserecordidCampaignresponse = default(MicrosoftDynamicsCRMcampaignresponse), MicrosoftDynamicsCRMcontract duplicaterecordidContract = default(MicrosoftDynamicsCRMcontract), MicrosoftDynamicsCRMservice duplicaterecordidService = default(MicrosoftDynamicsCRMservice), MicrosoftDynamicsCRMfax baserecordidFax = default(MicrosoftDynamicsCRMfax), MicrosoftDynamicsCRMqueue duplicaterecordidQueue = default(MicrosoftDynamicsCRMqueue), MicrosoftDynamicsCRMduplicaterule duplicateruleid = default(MicrosoftDynamicsCRMduplicaterule), MicrosoftDynamicsCRMcontact baserecordidContact = default(MicrosoftDynamicsCRMcontact), MicrosoftDynamicsCRMincident baserecordidIncident = default(MicrosoftDynamicsCRMincident), MicrosoftDynamicsCRMemailserverprofile duplicaterecordidEmailserverprofile = default(MicrosoftDynamicsCRMemailserverprofile), MicrosoftDynamicsCRMqueue baserecordidQueue = default(MicrosoftDynamicsCRMqueue), MicrosoftDynamicsCRMemailserverprofile baserecordidEmailserverprofile = default(MicrosoftDynamicsCRMemailserverprofile), MicrosoftDynamicsCRMletter duplicaterecordidLetter = default(MicrosoftDynamicsCRMletter), MicrosoftDynamicsCRMquote baserecordidQuote = default(MicrosoftDynamicsCRMquote)) { Owninguser = owninguser; this._duplicateruleidValue = _duplicateruleidValue; Createdon = createdon; this._owneridValue = _owneridValue; Owningbusinessunit = owningbusinessunit; this._asyncoperationidValue = _asyncoperationidValue; this._baserecordidValue = _baserecordidValue; Duplicateid = duplicateid; this._duplicaterecordidValue = _duplicaterecordidValue; DuplicaterecordidKnowledgearticle = duplicaterecordidKnowledgearticle; BaserecordidKnowledgearticle = baserecordidKnowledgearticle; DuplicaterecordidEntitlement = duplicaterecordidEntitlement; BaserecordidEntitlement = baserecordidEntitlement; DuplicaterecordidEntitlementchannel = duplicaterecordidEntitlementchannel; BaserecordidEntitlementchannel = baserecordidEntitlementchannel; DuplicaterecordidEntitlementtemplate = duplicaterecordidEntitlementtemplate; BaserecordidEntitlementtemplate = baserecordidEntitlementtemplate; DuplicaterecordidBookableresource = duplicaterecordidBookableresource; BaserecordidBookableresource = baserecordidBookableresource; DuplicaterecordidBookableresourcebooking = duplicaterecordidBookableresourcebooking; BaserecordidBookableresourcebooking = baserecordidBookableresourcebooking; DuplicaterecordidBookableresourcebookingheader = duplicaterecordidBookableresourcebookingheader; BaserecordidBookableresourcebookingheader = baserecordidBookableresourcebookingheader; DuplicaterecordidBookableresourcecategory = duplicaterecordidBookableresourcecategory; BaserecordidBookableresourcecategory = baserecordidBookableresourcecategory; DuplicaterecordidBookableresourcecategoryassn = duplicaterecordidBookableresourcecategoryassn; BaserecordidBookableresourcecategoryassn = baserecordidBookableresourcecategoryassn; DuplicaterecordidBookableresourcecharacteristic = duplicaterecordidBookableresourcecharacteristic; BaserecordidBookableresourcecharacteristic = baserecordidBookableresourcecharacteristic; DuplicaterecordidBookableresourcegroup = duplicaterecordidBookableresourcegroup; BaserecordidBookableresourcegroup = baserecordidBookableresourcegroup; DuplicaterecordidBookingstatus = duplicaterecordidBookingstatus; BaserecordidBookingstatus = baserecordidBookingstatus; DuplicaterecordidCharacteristic = duplicaterecordidCharacteristic; BaserecordidCharacteristic = baserecordidCharacteristic; DuplicaterecordidRatingmodel = duplicaterecordidRatingmodel; BaserecordidRatingmodel = baserecordidRatingmodel; DuplicaterecordidRatingvalue = duplicaterecordidRatingvalue; BaserecordidRatingvalue = baserecordidRatingvalue; DuplicaterecordidKnowledgebaserecord = duplicaterecordidKnowledgebaserecord; BaserecordidKnowledgebaserecord = baserecordidKnowledgebaserecord; DuplicaterecordidMsdynPostalbum = duplicaterecordidMsdynPostalbum; BaserecordidMsdynPostalbum = baserecordidMsdynPostalbum; DuplicaterecordidAdoxioAlias = duplicaterecordidAdoxioAlias; BaserecordidAdoxioAlias = baserecordidAdoxioAlias; DuplicaterecordidAdoxioApplication = duplicaterecordidAdoxioApplication; BaserecordidAdoxioApplication = baserecordidAdoxioApplication; DuplicaterecordidAdoxioApplicationinvoicehistory = duplicaterecordidAdoxioApplicationinvoicehistory; BaserecordidAdoxioApplicationinvoicehistory = baserecordidAdoxioApplicationinvoicehistory; DuplicaterecordidAdoxioApplicationtermsconditionslimitation = duplicaterecordidAdoxioApplicationtermsconditionslimitation; BaserecordidAdoxioApplicationtermsconditionslimitation = baserecordidAdoxioApplicationtermsconditionslimitation; DuplicaterecordidAdoxioArea = duplicaterecordidAdoxioArea; BaserecordidAdoxioArea = baserecordidAdoxioArea; DuplicaterecordidAdoxioBusinessaccount = duplicaterecordidAdoxioBusinessaccount; BaserecordidAdoxioBusinessaccount = baserecordidAdoxioBusinessaccount; DuplicaterecordidAdoxioCitydistrict = duplicaterecordidAdoxioCitydistrict; BaserecordidAdoxioCitydistrict = baserecordidAdoxioCitydistrict; DuplicaterecordidAdoxioComplaint = duplicaterecordidAdoxioComplaint; BaserecordidAdoxioComplaint = baserecordidAdoxioComplaint; DuplicaterecordidAdoxioContravention = duplicaterecordidAdoxioContravention; BaserecordidAdoxioContravention = baserecordidAdoxioContravention; DuplicaterecordidAdoxioCorporatehistorysummary = duplicaterecordidAdoxioCorporatehistorysummary; BaserecordidAdoxioCorporatehistorysummary = baserecordidAdoxioCorporatehistorysummary; DuplicaterecordidAdoxioEstablishment = duplicaterecordidAdoxioEstablishment; BaserecordidAdoxioEstablishment = baserecordidAdoxioEstablishment; DuplicaterecordidAdoxioFundingsource = duplicaterecordidAdoxioFundingsource; BaserecordidAdoxioFundingsource = baserecordidAdoxioFundingsource; DuplicaterecordidAdoxioInterest = duplicaterecordidAdoxioInterest; BaserecordidAdoxioInterest = baserecordidAdoxioInterest; DuplicaterecordidAdoxioInvestigation = duplicaterecordidAdoxioInvestigation; BaserecordidAdoxioInvestigation = baserecordidAdoxioInvestigation; DuplicaterecordidAdoxioLegalentity = duplicaterecordidAdoxioLegalentity; BaserecordidAdoxioLegalentity = baserecordidAdoxioLegalentity; DuplicaterecordidAdoxioLicences = duplicaterecordidAdoxioLicences; BaserecordidAdoxioLicences = baserecordidAdoxioLicences; DuplicaterecordidAdoxioLicencetype = duplicaterecordidAdoxioLicencetype; BaserecordidAdoxioLicencetype = baserecordidAdoxioLicencetype; DuplicaterecordidAdoxioLoan = duplicaterecordidAdoxioLoan; BaserecordidAdoxioLoan = baserecordidAdoxioLoan; DuplicaterecordidAdoxioLocalgovindigenousnation = duplicaterecordidAdoxioLocalgovindigenousnation; BaserecordidAdoxioLocalgovindigenousnation = baserecordidAdoxioLocalgovindigenousnation; DuplicaterecordidAdoxioPersonalhistorysummary = duplicaterecordidAdoxioPersonalhistorysummary; BaserecordidAdoxioPersonalhistorysummary = baserecordidAdoxioPersonalhistorysummary; DuplicaterecordidAdoxioPolicejurisdiction = duplicaterecordidAdoxioPolicejurisdiction; BaserecordidAdoxioPolicejurisdiction = baserecordidAdoxioPolicejurisdiction; DuplicaterecordidAdoxioPolicydocument = duplicaterecordidAdoxioPolicydocument; BaserecordidAdoxioPolicydocument = baserecordidAdoxioPolicydocument; DuplicaterecordidAdoxioPostalcode = duplicaterecordidAdoxioPostalcode; BaserecordidAdoxioPostalcode = baserecordidAdoxioPostalcode; DuplicaterecordidAdoxioRegion = duplicaterecordidAdoxioRegion; BaserecordidAdoxioRegion = baserecordidAdoxioRegion; DuplicaterecordidAdoxioSetting = duplicaterecordidAdoxioSetting; BaserecordidAdoxioSetting = baserecordidAdoxioSetting; DuplicaterecordidAdoxioTaxandaccounting = duplicaterecordidAdoxioTaxandaccounting; BaserecordidAdoxioTaxandaccounting = baserecordidAdoxioTaxandaccounting; DuplicaterecordidAdoxioTermsconditionslimitationspreset = duplicaterecordidAdoxioTermsconditionslimitationspreset; BaserecordidAdoxioTermsconditionslimitationspreset = baserecordidAdoxioTermsconditionslimitationspreset; DuplicaterecordidAdoxioTerritory = duplicaterecordidAdoxioTerritory; BaserecordidAdoxioTerritory = baserecordidAdoxioTerritory; DuplicaterecordidAdoxioTiedhouseassociation = duplicaterecordidAdoxioTiedhouseassociation; BaserecordidAdoxioTiedhouseassociation = baserecordidAdoxioTiedhouseassociation; DuplicaterecordidAdoxioTiedhouseconnection = duplicaterecordidAdoxioTiedhouseconnection; BaserecordidAdoxioTiedhouseconnection = baserecordidAdoxioTiedhouseconnection; DuplicaterecordidAdoxioWorker = duplicaterecordidAdoxioWorker; BaserecordidAdoxioWorker = baserecordidAdoxioWorker; DuplicaterecordidAdoxioDocument = duplicaterecordidAdoxioDocument; BaserecordidAdoxioDocument = baserecordidAdoxioDocument; DuplicaterecordidAdoxioDocumentadmin = duplicaterecordidAdoxioDocumentadmin; BaserecordidAdoxioDocumentadmin = baserecordidAdoxioDocumentadmin; DuplicaterecordidAdoxioContraventionadmin = duplicaterecordidAdoxioContraventionadmin; BaserecordidAdoxioContraventionadmin = baserecordidAdoxioContraventionadmin; DuplicaterecordidAdoxioCompliancemeeting = duplicaterecordidAdoxioCompliancemeeting; BaserecordidAdoxioCompliancemeeting = baserecordidAdoxioCompliancemeeting; DuplicaterecordidAdoxioInvestigationactivity = duplicaterecordidAdoxioInvestigationactivity; BaserecordidAdoxioInvestigationactivity = baserecordidAdoxioInvestigationactivity; DuplicaterecordidAdoxioComplianceinvestigation = duplicaterecordidAdoxioComplianceinvestigation; BaserecordidAdoxioComplianceinvestigation = baserecordidAdoxioComplianceinvestigation; DuplicaterecordidAdoxioFiainvestigationlog = duplicaterecordidAdoxioFiainvestigationlog; BaserecordidAdoxioFiainvestigationlog = baserecordidAdoxioFiainvestigationlog; DuplicaterecordidAdoxioApplicationtype = duplicaterecordidAdoxioApplicationtype; BaserecordidAdoxioApplicationtype = baserecordidAdoxioApplicationtype; DuplicaterecordidAdoxioApplicationtypecontent = duplicaterecordidAdoxioApplicationtypecontent; BaserecordidAdoxioApplicationtypecontent = baserecordidAdoxioApplicationtypecontent; DuplicaterecordidAdoxioInspectionreactivationhistory = duplicaterecordidAdoxioInspectionreactivationhistory; BaserecordidAdoxioInspectionreactivationhistory = baserecordidAdoxioInspectionreactivationhistory; DuplicaterecordidAdoxioEstablishmentwatchword = duplicaterecordidAdoxioEstablishmentwatchword; BaserecordidAdoxioEstablishmentwatchword = baserecordidAdoxioEstablishmentwatchword; DuplicaterecordidAdoxioRelatedparty = duplicaterecordidAdoxioRelatedparty; BaserecordidAdoxioRelatedparty = baserecordidAdoxioRelatedparty; DuplicaterecordidAdoxioWitness = duplicaterecordidAdoxioWitness; BaserecordidAdoxioWitness = baserecordidAdoxioWitness; DuplicaterecordidAdoxioCannabismonthlyreport = duplicaterecordidAdoxioCannabismonthlyreport; BaserecordidAdoxioCannabismonthlyreport = baserecordidAdoxioCannabismonthlyreport; DuplicaterecordidAdoxioCannabisproductadmin = duplicaterecordidAdoxioCannabisproductadmin; BaserecordidAdoxioCannabisproductadmin = baserecordidAdoxioCannabisproductadmin; DuplicaterecordidAdoxioCannabisinventoryreport = duplicaterecordidAdoxioCannabisinventoryreport; BaserecordidAdoxioCannabisinventoryreport = baserecordidAdoxioCannabisinventoryreport; DuplicaterecordidAdoxioInvestigationreactivationhistory = duplicaterecordidAdoxioInvestigationreactivationhistory; BaserecordidAdoxioInvestigationreactivationhistory = baserecordidAdoxioInvestigationreactivationhistory; DuplicaterecordidAdoxioAuditlogrequest = duplicaterecordidAdoxioAuditlogrequest; BaserecordidAdoxioAuditlogrequest = baserecordidAdoxioAuditlogrequest; DuplicaterecordidAdoxioExhibit = duplicaterecordidAdoxioExhibit; BaserecordidAdoxioExhibit = baserecordidAdoxioExhibit; DuplicaterecordidAdoxioFormelementuploadfield = duplicaterecordidAdoxioFormelementuploadfield; BaserecordidAdoxioFormelementuploadfield = baserecordidAdoxioFormelementuploadfield; DuplicaterecordidMsdynRelationshipinsightsunifiedconfig = duplicaterecordidMsdynRelationshipinsightsunifiedconfig; BaserecordidMsdynRelationshipinsightsunifiedconfig = baserecordidMsdynRelationshipinsightsunifiedconfig; DuplicaterecordidMsdynSiconfig = duplicaterecordidMsdynSiconfig; BaserecordidMsdynSiconfig = baserecordidMsdynSiconfig; DuplicaterecordidAdminsettingsentity = duplicaterecordidAdminsettingsentity; BaserecordidAdminsettingsentity = baserecordidAdminsettingsentity; DuplicaterecordidAdoxioEvent = duplicaterecordidAdoxioEvent; BaserecordidAdoxioEvent = baserecordidAdoxioEvent; DuplicaterecordidAdoxioEventschedule = duplicaterecordidAdoxioEventschedule; BaserecordidAdoxioEventschedule = baserecordidAdoxioEventschedule; DuplicaterecordidAdoxioFederalreportexport = duplicaterecordidAdoxioFederalreportexport; BaserecordidAdoxioFederalreportexport = baserecordidAdoxioFederalreportexport; DuplicaterecordidAdoxioLdborder = duplicaterecordidAdoxioLdborder; BaserecordidAdoxioLdborder = baserecordidAdoxioLdborder; DuplicaterecordidAdoxioApplicationtypefeeschedule = duplicaterecordidAdoxioApplicationtypefeeschedule; BaserecordidAdoxioApplicationtypefeeschedule = baserecordidAdoxioApplicationtypefeeschedule; DuplicaterecordidAdoxioEndorsement = duplicaterecordidAdoxioEndorsement; BaserecordidAdoxioEndorsement = baserecordidAdoxioEndorsement; DuplicaterecordidAdoxioLicenceldbordertotalhistory = duplicaterecordidAdoxioLicenceldbordertotalhistory; BaserecordidAdoxioLicenceldbordertotalhistory = baserecordidAdoxioLicenceldbordertotalhistory; DuplicaterecordidAdoxioRmreview = duplicaterecordidAdoxioRmreview; BaserecordidAdoxioRmreview = baserecordidAdoxioRmreview; DuplicaterecordidAdoxioEnforcementaction = duplicaterecordidAdoxioEnforcementaction; BaserecordidAdoxioEnforcementaction = baserecordidAdoxioEnforcementaction; DuplicaterecordidAdoxioServicearea = duplicaterecordidAdoxioServicearea; BaserecordidAdoxioServicearea = baserecordidAdoxioServicearea; DuplicaterecordidAdoxioAnnualvolume = duplicaterecordidAdoxioAnnualvolume; BaserecordidAdoxioAnnualvolume = baserecordidAdoxioAnnualvolume; DuplicaterecordidAdoxioHoursofservice = duplicaterecordidAdoxioHoursofservice; BaserecordidAdoxioHoursofservice = baserecordidAdoxioHoursofservice; DuplicaterecordidAdoxioPmuarea = duplicaterecordidAdoxioPmuarea; BaserecordidAdoxioPmuarea = baserecordidAdoxioPmuarea; DuplicaterecordidAdoxioInspectorreport = duplicaterecordidAdoxioInspectorreport; BaserecordidAdoxioInspectorreport = baserecordidAdoxioInspectorreport; DuplicaterecordidAdoxioOffsitestorage = duplicaterecordidAdoxioOffsitestorage; BaserecordidAdoxioOffsitestorage = baserecordidAdoxioOffsitestorage; BaserecordidGoalrollupquery = baserecordidGoalrollupquery; DuplicaterecordidPublisher = duplicaterecordidPublisher; BaserecordidTransactioncurrency = baserecordidTransactioncurrency; BaserecordidCampaign = baserecordidCampaign; BaserecordidLead = baserecordidLead; BaserecordidRecurringappointmentmaster = baserecordidRecurringappointmentmaster; DuplicaterecordidGoal = duplicaterecordidGoal; DuplicaterecordidTransactioncurrency = duplicaterecordidTransactioncurrency; BaserecordidCompetitor = baserecordidCompetitor; BaserecordidEquipment = baserecordidEquipment; BaserecordidTask = baserecordidTask; DuplicaterecordidRecurringappointmentmaster = duplicaterecordidRecurringappointmentmaster; Asyncoperationid = asyncoperationid; DuplicaterecordidTask = duplicaterecordidTask; DuplicaterecordidEquipment = duplicaterecordidEquipment; BaserecordidEmail = baserecordidEmail; BaserecordidSocialprofile = baserecordidSocialprofile; BaserecordidTeam = baserecordidTeam; BaserecordidSystemuser = baserecordidSystemuser; BaserecordidAccount = baserecordidAccount; BaserecordidAppointment = baserecordidAppointment; BaserecordidOpportunity = baserecordidOpportunity; DuplicaterecordidCampaign = duplicaterecordidCampaign; BaserecordidSharepointdocumentlocation = baserecordidSharepointdocumentlocation; DuplicaterecordidFax = duplicaterecordidFax; DuplicaterecordidTerritory = duplicaterecordidTerritory; BaserecordidList = baserecordidList; BaserecordidPublisher = baserecordidPublisher; DuplicaterecordidSharepointsite = duplicaterecordidSharepointsite; DuplicaterecordidKbarticle = duplicaterecordidKbarticle; DuplicaterecordidTeam = duplicaterecordidTeam; DuplicaterecordidAppointment = duplicaterecordidAppointment; BaserecordidContract = baserecordidContract; DuplicaterecordidIncident = duplicaterecordidIncident; DuplicaterecordidOpportunity = duplicaterecordidOpportunity; DuplicaterecordidQuote = duplicaterecordidQuote; DuplicaterecordidPhonecall = duplicaterecordidPhonecall; BaserecordidResourcegroup = baserecordidResourcegroup; BaserecordidTerritory = baserecordidTerritory; DuplicaterecordidGoalrollupquery = duplicaterecordidGoalrollupquery; BaserecordidSharepointsite = baserecordidSharepointsite; BaserecordidPhonecall = baserecordidPhonecall; DuplicaterecordidContact = duplicaterecordidContact; DuplicaterecordidCampaignresponse = duplicaterecordidCampaignresponse; BaserecordidKbarticle = baserecordidKbarticle; BaserecordidService = baserecordidService; DuplicaterecordidEmail = duplicaterecordidEmail; DuplicaterecordidCompetitor = duplicaterecordidCompetitor; BaserecordidLetter = baserecordidLetter; BaserecordidSocialactivity = baserecordidSocialactivity; DuplicaterecordidSystemuser = duplicaterecordidSystemuser; DuplicaterecordidLead = duplicaterecordidLead; DuplicaterecordidSocialactivity = duplicaterecordidSocialactivity; DuplicaterecordidSharepointdocumentlocation = duplicaterecordidSharepointdocumentlocation; DuplicaterecordidSocialprofile = duplicaterecordidSocialprofile; BaserecordidGoal = baserecordidGoal; DuplicaterecordidAccount = duplicaterecordidAccount; DuplicaterecordidList = duplicaterecordidList; DuplicaterecordidResourcegroup = duplicaterecordidResourcegroup; BaserecordidCampaignresponse = baserecordidCampaignresponse; DuplicaterecordidContract = duplicaterecordidContract; DuplicaterecordidService = duplicaterecordidService; BaserecordidFax = baserecordidFax; DuplicaterecordidQueue = duplicaterecordidQueue; Duplicateruleid = duplicateruleid; BaserecordidContact = baserecordidContact; BaserecordidIncident = baserecordidIncident; DuplicaterecordidEmailserverprofile = duplicaterecordidEmailserverprofile; BaserecordidQueue = baserecordidQueue; BaserecordidEmailserverprofile = baserecordidEmailserverprofile; DuplicaterecordidLetter = duplicaterecordidLetter; BaserecordidQuote = baserecordidQuote; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "owninguser")] public string Owninguser { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_duplicateruleid_value")] public string _duplicateruleidValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdon")] public System.DateTimeOffset? Createdon { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_ownerid_value")] public string _owneridValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "owningbusinessunit")] public string Owningbusinessunit { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_asyncoperationid_value")] public string _asyncoperationidValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_baserecordid_value")] public string _baserecordidValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicateid")] public string Duplicateid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_duplicaterecordid_value")] public string _duplicaterecordidValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_knowledgearticle")] public MicrosoftDynamicsCRMknowledgearticle DuplicaterecordidKnowledgearticle { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_knowledgearticle")] public MicrosoftDynamicsCRMknowledgearticle BaserecordidKnowledgearticle { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_entitlement")] public MicrosoftDynamicsCRMentitlement DuplicaterecordidEntitlement { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_entitlement")] public MicrosoftDynamicsCRMentitlement BaserecordidEntitlement { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_entitlementchannel")] public MicrosoftDynamicsCRMentitlementchannel DuplicaterecordidEntitlementchannel { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_entitlementchannel")] public MicrosoftDynamicsCRMentitlementchannel BaserecordidEntitlementchannel { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_entitlementtemplate")] public MicrosoftDynamicsCRMentitlementtemplate DuplicaterecordidEntitlementtemplate { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_entitlementtemplate")] public MicrosoftDynamicsCRMentitlementtemplate BaserecordidEntitlementtemplate { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_bookableresource")] public MicrosoftDynamicsCRMbookableresource DuplicaterecordidBookableresource { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_bookableresource")] public MicrosoftDynamicsCRMbookableresource BaserecordidBookableresource { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_bookableresourcebooking")] public MicrosoftDynamicsCRMbookableresourcebooking DuplicaterecordidBookableresourcebooking { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_bookableresourcebooking")] public MicrosoftDynamicsCRMbookableresourcebooking BaserecordidBookableresourcebooking { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_bookableresourcebookingheader")] public MicrosoftDynamicsCRMbookableresourcebookingheader DuplicaterecordidBookableresourcebookingheader { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_bookableresourcebookingheader")] public MicrosoftDynamicsCRMbookableresourcebookingheader BaserecordidBookableresourcebookingheader { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_bookableresourcecategory")] public MicrosoftDynamicsCRMbookableresourcecategory DuplicaterecordidBookableresourcecategory { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_bookableresourcecategory")] public MicrosoftDynamicsCRMbookableresourcecategory BaserecordidBookableresourcecategory { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_bookableresourcecategoryassn")] public MicrosoftDynamicsCRMbookableresourcecategoryassn DuplicaterecordidBookableresourcecategoryassn { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_bookableresourcecategoryassn")] public MicrosoftDynamicsCRMbookableresourcecategoryassn BaserecordidBookableresourcecategoryassn { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_bookableresourcecharacteristic")] public MicrosoftDynamicsCRMbookableresourcecharacteristic DuplicaterecordidBookableresourcecharacteristic { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_bookableresourcecharacteristic")] public MicrosoftDynamicsCRMbookableresourcecharacteristic BaserecordidBookableresourcecharacteristic { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_bookableresourcegroup")] public MicrosoftDynamicsCRMbookableresourcegroup DuplicaterecordidBookableresourcegroup { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_bookableresourcegroup")] public MicrosoftDynamicsCRMbookableresourcegroup BaserecordidBookableresourcegroup { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_bookingstatus")] public MicrosoftDynamicsCRMbookingstatus DuplicaterecordidBookingstatus { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_bookingstatus")] public MicrosoftDynamicsCRMbookingstatus BaserecordidBookingstatus { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_characteristic")] public MicrosoftDynamicsCRMcharacteristic DuplicaterecordidCharacteristic { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_characteristic")] public MicrosoftDynamicsCRMcharacteristic BaserecordidCharacteristic { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_ratingmodel")] public MicrosoftDynamicsCRMratingmodel DuplicaterecordidRatingmodel { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_ratingmodel")] public MicrosoftDynamicsCRMratingmodel BaserecordidRatingmodel { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_ratingvalue")] public MicrosoftDynamicsCRMratingvalue DuplicaterecordidRatingvalue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_ratingvalue")] public MicrosoftDynamicsCRMratingvalue BaserecordidRatingvalue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_knowledgebaserecord")] public MicrosoftDynamicsCRMknowledgebaserecord DuplicaterecordidKnowledgebaserecord { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_knowledgebaserecord")] public MicrosoftDynamicsCRMknowledgebaserecord BaserecordidKnowledgebaserecord { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_msdyn_postalbum")] public MicrosoftDynamicsCRMmsdynPostalbum DuplicaterecordidMsdynPostalbum { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_msdyn_postalbum")] public MicrosoftDynamicsCRMmsdynPostalbum BaserecordidMsdynPostalbum { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_alias")] public MicrosoftDynamicsCRMadoxioAlias DuplicaterecordidAdoxioAlias { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_alias")] public MicrosoftDynamicsCRMadoxioAlias BaserecordidAdoxioAlias { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_application")] public MicrosoftDynamicsCRMadoxioApplication DuplicaterecordidAdoxioApplication { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_application")] public MicrosoftDynamicsCRMadoxioApplication BaserecordidAdoxioApplication { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_applicationinvoicehistory")] public MicrosoftDynamicsCRMadoxioApplicationinvoicehistory DuplicaterecordidAdoxioApplicationinvoicehistory { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_applicationinvoicehistory")] public MicrosoftDynamicsCRMadoxioApplicationinvoicehistory BaserecordidAdoxioApplicationinvoicehistory { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_applicationtermsconditionslimitation")] public MicrosoftDynamicsCRMadoxioApplicationtermsconditionslimitation DuplicaterecordidAdoxioApplicationtermsconditionslimitation { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_applicationtermsconditionslimitation")] public MicrosoftDynamicsCRMadoxioApplicationtermsconditionslimitation BaserecordidAdoxioApplicationtermsconditionslimitation { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_area")] public MicrosoftDynamicsCRMadoxioArea DuplicaterecordidAdoxioArea { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_area")] public MicrosoftDynamicsCRMadoxioArea BaserecordidAdoxioArea { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_businessaccount")] public MicrosoftDynamicsCRMadoxioBusinessaccount DuplicaterecordidAdoxioBusinessaccount { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_businessaccount")] public MicrosoftDynamicsCRMadoxioBusinessaccount BaserecordidAdoxioBusinessaccount { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_citydistrict")] public MicrosoftDynamicsCRMadoxioCitydistrict DuplicaterecordidAdoxioCitydistrict { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_citydistrict")] public MicrosoftDynamicsCRMadoxioCitydistrict BaserecordidAdoxioCitydistrict { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_complaint")] public MicrosoftDynamicsCRMadoxioComplaint DuplicaterecordidAdoxioComplaint { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_complaint")] public MicrosoftDynamicsCRMadoxioComplaint BaserecordidAdoxioComplaint { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_contravention")] public MicrosoftDynamicsCRMadoxioContravention DuplicaterecordidAdoxioContravention { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_contravention")] public MicrosoftDynamicsCRMadoxioContravention BaserecordidAdoxioContravention { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_corporatehistorysummary")] public MicrosoftDynamicsCRMadoxioCorporatehistorysummary DuplicaterecordidAdoxioCorporatehistorysummary { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_corporatehistorysummary")] public MicrosoftDynamicsCRMadoxioCorporatehistorysummary BaserecordidAdoxioCorporatehistorysummary { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_establishment")] public MicrosoftDynamicsCRMadoxioEstablishment DuplicaterecordidAdoxioEstablishment { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_establishment")] public MicrosoftDynamicsCRMadoxioEstablishment BaserecordidAdoxioEstablishment { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_fundingsource")] public MicrosoftDynamicsCRMadoxioFundingsource DuplicaterecordidAdoxioFundingsource { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_fundingsource")] public MicrosoftDynamicsCRMadoxioFundingsource BaserecordidAdoxioFundingsource { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_interest")] public MicrosoftDynamicsCRMadoxioInterest DuplicaterecordidAdoxioInterest { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_interest")] public MicrosoftDynamicsCRMadoxioInterest BaserecordidAdoxioInterest { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_investigation")] public MicrosoftDynamicsCRMadoxioInvestigation DuplicaterecordidAdoxioInvestigation { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_investigation")] public MicrosoftDynamicsCRMadoxioInvestigation BaserecordidAdoxioInvestigation { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_legalentity")] public MicrosoftDynamicsCRMadoxioLegalentity DuplicaterecordidAdoxioLegalentity { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_legalentity")] public MicrosoftDynamicsCRMadoxioLegalentity BaserecordidAdoxioLegalentity { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_licences")] public MicrosoftDynamicsCRMadoxioLicences DuplicaterecordidAdoxioLicences { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_licences")] public MicrosoftDynamicsCRMadoxioLicences BaserecordidAdoxioLicences { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_licencetype")] public MicrosoftDynamicsCRMadoxioLicencetype DuplicaterecordidAdoxioLicencetype { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_licencetype")] public MicrosoftDynamicsCRMadoxioLicencetype BaserecordidAdoxioLicencetype { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_loan")] public MicrosoftDynamicsCRMadoxioLoan DuplicaterecordidAdoxioLoan { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_loan")] public MicrosoftDynamicsCRMadoxioLoan BaserecordidAdoxioLoan { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_localgovindigenousnation")] public MicrosoftDynamicsCRMadoxioLocalgovindigenousnation DuplicaterecordidAdoxioLocalgovindigenousnation { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_localgovindigenousnation")] public MicrosoftDynamicsCRMadoxioLocalgovindigenousnation BaserecordidAdoxioLocalgovindigenousnation { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_personalhistorysummary")] public MicrosoftDynamicsCRMadoxioPersonalhistorysummary DuplicaterecordidAdoxioPersonalhistorysummary { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_personalhistorysummary")] public MicrosoftDynamicsCRMadoxioPersonalhistorysummary BaserecordidAdoxioPersonalhistorysummary { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_policejurisdiction")] public MicrosoftDynamicsCRMadoxioPolicejurisdiction DuplicaterecordidAdoxioPolicejurisdiction { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_policejurisdiction")] public MicrosoftDynamicsCRMadoxioPolicejurisdiction BaserecordidAdoxioPolicejurisdiction { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_policydocument")] public MicrosoftDynamicsCRMadoxioPolicydocument DuplicaterecordidAdoxioPolicydocument { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_policydocument")] public MicrosoftDynamicsCRMadoxioPolicydocument BaserecordidAdoxioPolicydocument { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_postalcode")] public MicrosoftDynamicsCRMadoxioPostalcode DuplicaterecordidAdoxioPostalcode { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_postalcode")] public MicrosoftDynamicsCRMadoxioPostalcode BaserecordidAdoxioPostalcode { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_region")] public MicrosoftDynamicsCRMadoxioRegion DuplicaterecordidAdoxioRegion { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_region")] public MicrosoftDynamicsCRMadoxioRegion BaserecordidAdoxioRegion { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_setting")] public MicrosoftDynamicsCRMadoxioSetting DuplicaterecordidAdoxioSetting { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_setting")] public MicrosoftDynamicsCRMadoxioSetting BaserecordidAdoxioSetting { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_taxandaccounting")] public MicrosoftDynamicsCRMadoxioTaxandaccounting DuplicaterecordidAdoxioTaxandaccounting { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_taxandaccounting")] public MicrosoftDynamicsCRMadoxioTaxandaccounting BaserecordidAdoxioTaxandaccounting { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_termsconditionslimitationspreset")] public MicrosoftDynamicsCRMadoxioTermsconditionslimitationspreset DuplicaterecordidAdoxioTermsconditionslimitationspreset { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_termsconditionslimitationspreset")] public MicrosoftDynamicsCRMadoxioTermsconditionslimitationspreset BaserecordidAdoxioTermsconditionslimitationspreset { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_territory")] public MicrosoftDynamicsCRMadoxioTerritory DuplicaterecordidAdoxioTerritory { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_territory")] public MicrosoftDynamicsCRMadoxioTerritory BaserecordidAdoxioTerritory { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_tiedhouseassociation")] public MicrosoftDynamicsCRMadoxioTiedhouseassociation DuplicaterecordidAdoxioTiedhouseassociation { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_tiedhouseassociation")] public MicrosoftDynamicsCRMadoxioTiedhouseassociation BaserecordidAdoxioTiedhouseassociation { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_tiedhouseconnection")] public MicrosoftDynamicsCRMadoxioTiedhouseconnection DuplicaterecordidAdoxioTiedhouseconnection { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_tiedhouseconnection")] public MicrosoftDynamicsCRMadoxioTiedhouseconnection BaserecordidAdoxioTiedhouseconnection { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_worker")] public MicrosoftDynamicsCRMadoxioWorker DuplicaterecordidAdoxioWorker { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_worker")] public MicrosoftDynamicsCRMadoxioWorker BaserecordidAdoxioWorker { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_document")] public MicrosoftDynamicsCRMadoxioDocument DuplicaterecordidAdoxioDocument { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_document")] public MicrosoftDynamicsCRMadoxioDocument BaserecordidAdoxioDocument { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_documentadmin")] public MicrosoftDynamicsCRMadoxioDocumentadmin DuplicaterecordidAdoxioDocumentadmin { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_documentadmin")] public MicrosoftDynamicsCRMadoxioDocumentadmin BaserecordidAdoxioDocumentadmin { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_contraventionadmin")] public MicrosoftDynamicsCRMadoxioContraventionadmin DuplicaterecordidAdoxioContraventionadmin { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_contraventionadmin")] public MicrosoftDynamicsCRMadoxioContraventionadmin BaserecordidAdoxioContraventionadmin { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_compliancemeeting")] public MicrosoftDynamicsCRMadoxioCompliancemeeting DuplicaterecordidAdoxioCompliancemeeting { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_compliancemeeting")] public MicrosoftDynamicsCRMadoxioCompliancemeeting BaserecordidAdoxioCompliancemeeting { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_investigationactivity")] public MicrosoftDynamicsCRMadoxioInvestigationactivity DuplicaterecordidAdoxioInvestigationactivity { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_investigationactivity")] public MicrosoftDynamicsCRMadoxioInvestigationactivity BaserecordidAdoxioInvestigationactivity { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_complianceinvestigation")] public MicrosoftDynamicsCRMadoxioComplianceinvestigation DuplicaterecordidAdoxioComplianceinvestigation { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_complianceinvestigation")] public MicrosoftDynamicsCRMadoxioComplianceinvestigation BaserecordidAdoxioComplianceinvestigation { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_fiainvestigationlog")] public MicrosoftDynamicsCRMadoxioFiainvestigationlog DuplicaterecordidAdoxioFiainvestigationlog { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_fiainvestigationlog")] public MicrosoftDynamicsCRMadoxioFiainvestigationlog BaserecordidAdoxioFiainvestigationlog { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_applicationtype")] public MicrosoftDynamicsCRMadoxioApplicationtype DuplicaterecordidAdoxioApplicationtype { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_applicationtype")] public MicrosoftDynamicsCRMadoxioApplicationtype BaserecordidAdoxioApplicationtype { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_applicationtypecontent")] public MicrosoftDynamicsCRMadoxioApplicationtypecontent DuplicaterecordidAdoxioApplicationtypecontent { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_applicationtypecontent")] public MicrosoftDynamicsCRMadoxioApplicationtypecontent BaserecordidAdoxioApplicationtypecontent { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_inspectionreactivationhistory")] public MicrosoftDynamicsCRMadoxioInspectionreactivationhistory DuplicaterecordidAdoxioInspectionreactivationhistory { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_inspectionreactivationhistory")] public MicrosoftDynamicsCRMadoxioInspectionreactivationhistory BaserecordidAdoxioInspectionreactivationhistory { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_establishmentwatchword")] public MicrosoftDynamicsCRMadoxioEstablishmentwatchword DuplicaterecordidAdoxioEstablishmentwatchword { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_establishmentwatchword")] public MicrosoftDynamicsCRMadoxioEstablishmentwatchword BaserecordidAdoxioEstablishmentwatchword { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_relatedparty")] public MicrosoftDynamicsCRMadoxioRelatedparty DuplicaterecordidAdoxioRelatedparty { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_relatedparty")] public MicrosoftDynamicsCRMadoxioRelatedparty BaserecordidAdoxioRelatedparty { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_witness")] public MicrosoftDynamicsCRMadoxioWitness DuplicaterecordidAdoxioWitness { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_witness")] public MicrosoftDynamicsCRMadoxioWitness BaserecordidAdoxioWitness { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_cannabismonthlyreport")] public MicrosoftDynamicsCRMadoxioCannabismonthlyreport DuplicaterecordidAdoxioCannabismonthlyreport { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_cannabismonthlyreport")] public MicrosoftDynamicsCRMadoxioCannabismonthlyreport BaserecordidAdoxioCannabismonthlyreport { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_cannabisproductadmin")] public MicrosoftDynamicsCRMadoxioCannabisproductadmin DuplicaterecordidAdoxioCannabisproductadmin { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_cannabisproductadmin")] public MicrosoftDynamicsCRMadoxioCannabisproductadmin BaserecordidAdoxioCannabisproductadmin { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_cannabisinventoryreport")] public MicrosoftDynamicsCRMadoxioCannabisinventoryreport DuplicaterecordidAdoxioCannabisinventoryreport { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_cannabisinventoryreport")] public MicrosoftDynamicsCRMadoxioCannabisinventoryreport BaserecordidAdoxioCannabisinventoryreport { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_investigationreactivationhistory")] public MicrosoftDynamicsCRMadoxioInvestigationreactivationhistory DuplicaterecordidAdoxioInvestigationreactivationhistory { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_investigationreactivationhistory")] public MicrosoftDynamicsCRMadoxioInvestigationreactivationhistory BaserecordidAdoxioInvestigationreactivationhistory { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_auditlogrequest")] public MicrosoftDynamicsCRMadoxioAuditlogrequest DuplicaterecordidAdoxioAuditlogrequest { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_auditlogrequest")] public MicrosoftDynamicsCRMadoxioAuditlogrequest BaserecordidAdoxioAuditlogrequest { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_exhibit")] public MicrosoftDynamicsCRMadoxioExhibit DuplicaterecordidAdoxioExhibit { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_exhibit")] public MicrosoftDynamicsCRMadoxioExhibit BaserecordidAdoxioExhibit { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_formelementuploadfield")] public MicrosoftDynamicsCRMadoxioFormelementuploadfield DuplicaterecordidAdoxioFormelementuploadfield { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_formelementuploadfield")] public MicrosoftDynamicsCRMadoxioFormelementuploadfield BaserecordidAdoxioFormelementuploadfield { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_msdyn_relationshipinsightsunifiedconfig")] public MicrosoftDynamicsCRMmsdynRelationshipinsightsunifiedconfig DuplicaterecordidMsdynRelationshipinsightsunifiedconfig { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_msdyn_relationshipinsightsunifiedconfig")] public MicrosoftDynamicsCRMmsdynRelationshipinsightsunifiedconfig BaserecordidMsdynRelationshipinsightsunifiedconfig { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_msdyn_siconfig")] public MicrosoftDynamicsCRMmsdynSiconfig DuplicaterecordidMsdynSiconfig { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_msdyn_siconfig")] public MicrosoftDynamicsCRMmsdynSiconfig BaserecordidMsdynSiconfig { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adminsettingsentity")] public MicrosoftDynamicsCRMadminsettingsentity DuplicaterecordidAdminsettingsentity { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adminsettingsentity")] public MicrosoftDynamicsCRMadminsettingsentity BaserecordidAdminsettingsentity { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_event")] public MicrosoftDynamicsCRMadoxioEvent DuplicaterecordidAdoxioEvent { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_event")] public MicrosoftDynamicsCRMadoxioEvent BaserecordidAdoxioEvent { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_eventschedule")] public MicrosoftDynamicsCRMadoxioEventschedule DuplicaterecordidAdoxioEventschedule { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_eventschedule")] public MicrosoftDynamicsCRMadoxioEventschedule BaserecordidAdoxioEventschedule { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_federalreportexport")] public MicrosoftDynamicsCRMadoxioFederalreportexport DuplicaterecordidAdoxioFederalreportexport { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_federalreportexport")] public MicrosoftDynamicsCRMadoxioFederalreportexport BaserecordidAdoxioFederalreportexport { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_ldborder")] public MicrosoftDynamicsCRMadoxioLdborder DuplicaterecordidAdoxioLdborder { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_ldborder")] public MicrosoftDynamicsCRMadoxioLdborder BaserecordidAdoxioLdborder { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_applicationtypefeeschedule")] public MicrosoftDynamicsCRMadoxioApplicationtypefeeschedule DuplicaterecordidAdoxioApplicationtypefeeschedule { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_applicationtypefeeschedule")] public MicrosoftDynamicsCRMadoxioApplicationtypefeeschedule BaserecordidAdoxioApplicationtypefeeschedule { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_endorsement")] public MicrosoftDynamicsCRMadoxioEndorsement DuplicaterecordidAdoxioEndorsement { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_endorsement")] public MicrosoftDynamicsCRMadoxioEndorsement BaserecordidAdoxioEndorsement { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_licenceldbordertotalhistory")] public MicrosoftDynamicsCRMadoxioLicenceldbordertotalhistory DuplicaterecordidAdoxioLicenceldbordertotalhistory { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_licenceldbordertotalhistory")] public MicrosoftDynamicsCRMadoxioLicenceldbordertotalhistory BaserecordidAdoxioLicenceldbordertotalhistory { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_rmreview")] public MicrosoftDynamicsCRMadoxioRmreview DuplicaterecordidAdoxioRmreview { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_rmreview")] public MicrosoftDynamicsCRMadoxioRmreview BaserecordidAdoxioRmreview { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_enforcementaction")] public MicrosoftDynamicsCRMadoxioEnforcementaction DuplicaterecordidAdoxioEnforcementaction { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_enforcementaction")] public MicrosoftDynamicsCRMadoxioEnforcementaction BaserecordidAdoxioEnforcementaction { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_servicearea")] public MicrosoftDynamicsCRMadoxioServicearea DuplicaterecordidAdoxioServicearea { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_servicearea")] public MicrosoftDynamicsCRMadoxioServicearea BaserecordidAdoxioServicearea { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_annualvolume")] public MicrosoftDynamicsCRMadoxioAnnualvolume DuplicaterecordidAdoxioAnnualvolume { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_annualvolume")] public MicrosoftDynamicsCRMadoxioAnnualvolume BaserecordidAdoxioAnnualvolume { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_hoursofservice")] public MicrosoftDynamicsCRMadoxioHoursofservice DuplicaterecordidAdoxioHoursofservice { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_hoursofservice")] public MicrosoftDynamicsCRMadoxioHoursofservice BaserecordidAdoxioHoursofservice { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_pmuarea")] public MicrosoftDynamicsCRMadoxioPmuarea DuplicaterecordidAdoxioPmuarea { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_pmuarea")] public MicrosoftDynamicsCRMadoxioPmuarea BaserecordidAdoxioPmuarea { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_inspectorreport")] public MicrosoftDynamicsCRMadoxioInspectorreport DuplicaterecordidAdoxioInspectorreport { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_inspectorreport")] public MicrosoftDynamicsCRMadoxioInspectorreport BaserecordidAdoxioInspectorreport { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_adoxio_offsitestorage")] public MicrosoftDynamicsCRMadoxioOffsitestorage DuplicaterecordidAdoxioOffsitestorage { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_adoxio_offsitestorage")] public MicrosoftDynamicsCRMadoxioOffsitestorage BaserecordidAdoxioOffsitestorage { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_goalrollupquery")] public MicrosoftDynamicsCRMgoalrollupquery BaserecordidGoalrollupquery { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_publisher")] public MicrosoftDynamicsCRMpublisher DuplicaterecordidPublisher { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_transactioncurrency")] public MicrosoftDynamicsCRMtransactioncurrency BaserecordidTransactioncurrency { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_campaign")] public MicrosoftDynamicsCRMcampaign BaserecordidCampaign { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_lead")] public MicrosoftDynamicsCRMlead BaserecordidLead { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_recurringappointmentmaster")] public MicrosoftDynamicsCRMrecurringappointmentmaster BaserecordidRecurringappointmentmaster { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_goal")] public MicrosoftDynamicsCRMgoal DuplicaterecordidGoal { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_transactioncurrency")] public MicrosoftDynamicsCRMtransactioncurrency DuplicaterecordidTransactioncurrency { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_competitor")] public MicrosoftDynamicsCRMcompetitor BaserecordidCompetitor { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_equipment")] public MicrosoftDynamicsCRMequipment BaserecordidEquipment { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_task")] public MicrosoftDynamicsCRMtask BaserecordidTask { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_recurringappointmentmaster")] public MicrosoftDynamicsCRMrecurringappointmentmaster DuplicaterecordidRecurringappointmentmaster { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "asyncoperationid")] public MicrosoftDynamicsCRMasyncoperation Asyncoperationid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_task")] public MicrosoftDynamicsCRMtask DuplicaterecordidTask { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_equipment")] public MicrosoftDynamicsCRMequipment DuplicaterecordidEquipment { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_email")] public MicrosoftDynamicsCRMemail BaserecordidEmail { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_socialprofile")] public MicrosoftDynamicsCRMsocialprofile BaserecordidSocialprofile { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_team")] public MicrosoftDynamicsCRMteam BaserecordidTeam { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_systemuser")] public MicrosoftDynamicsCRMsystemuser BaserecordidSystemuser { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_account")] public MicrosoftDynamicsCRMaccount BaserecordidAccount { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_appointment")] public MicrosoftDynamicsCRMappointment BaserecordidAppointment { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_opportunity")] public MicrosoftDynamicsCRMopportunity BaserecordidOpportunity { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_campaign")] public MicrosoftDynamicsCRMcampaign DuplicaterecordidCampaign { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_sharepointdocumentlocation")] public MicrosoftDynamicsCRMsharepointdocumentlocation BaserecordidSharepointdocumentlocation { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_fax")] public MicrosoftDynamicsCRMfax DuplicaterecordidFax { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_territory")] public MicrosoftDynamicsCRMterritory DuplicaterecordidTerritory { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_list")] public MicrosoftDynamicsCRMlist BaserecordidList { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_publisher")] public MicrosoftDynamicsCRMpublisher BaserecordidPublisher { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_sharepointsite")] public MicrosoftDynamicsCRMsharepointsite DuplicaterecordidSharepointsite { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_kbarticle")] public MicrosoftDynamicsCRMkbarticle DuplicaterecordidKbarticle { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_team")] public MicrosoftDynamicsCRMteam DuplicaterecordidTeam { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_appointment")] public MicrosoftDynamicsCRMappointment DuplicaterecordidAppointment { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_contract")] public MicrosoftDynamicsCRMcontract BaserecordidContract { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_incident")] public MicrosoftDynamicsCRMincident DuplicaterecordidIncident { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_opportunity")] public MicrosoftDynamicsCRMopportunity DuplicaterecordidOpportunity { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_quote")] public MicrosoftDynamicsCRMquote DuplicaterecordidQuote { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_phonecall")] public MicrosoftDynamicsCRMphonecall DuplicaterecordidPhonecall { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_resourcegroup")] public MicrosoftDynamicsCRMresourcegroup BaserecordidResourcegroup { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_territory")] public MicrosoftDynamicsCRMterritory BaserecordidTerritory { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_goalrollupquery")] public MicrosoftDynamicsCRMgoalrollupquery DuplicaterecordidGoalrollupquery { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_sharepointsite")] public MicrosoftDynamicsCRMsharepointsite BaserecordidSharepointsite { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_phonecall")] public MicrosoftDynamicsCRMphonecall BaserecordidPhonecall { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_contact")] public MicrosoftDynamicsCRMcontact DuplicaterecordidContact { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_campaignresponse")] public MicrosoftDynamicsCRMcampaignresponse DuplicaterecordidCampaignresponse { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_kbarticle")] public MicrosoftDynamicsCRMkbarticle BaserecordidKbarticle { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_service")] public MicrosoftDynamicsCRMservice BaserecordidService { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_email")] public MicrosoftDynamicsCRMemail DuplicaterecordidEmail { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_competitor")] public MicrosoftDynamicsCRMcompetitor DuplicaterecordidCompetitor { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_letter")] public MicrosoftDynamicsCRMletter BaserecordidLetter { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_socialactivity")] public MicrosoftDynamicsCRMsocialactivity BaserecordidSocialactivity { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_systemuser")] public MicrosoftDynamicsCRMsystemuser DuplicaterecordidSystemuser { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_lead")] public MicrosoftDynamicsCRMlead DuplicaterecordidLead { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_socialactivity")] public MicrosoftDynamicsCRMsocialactivity DuplicaterecordidSocialactivity { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_sharepointdocumentlocation")] public MicrosoftDynamicsCRMsharepointdocumentlocation DuplicaterecordidSharepointdocumentlocation { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_socialprofile")] public MicrosoftDynamicsCRMsocialprofile DuplicaterecordidSocialprofile { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_goal")] public MicrosoftDynamicsCRMgoal BaserecordidGoal { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_account")] public MicrosoftDynamicsCRMaccount DuplicaterecordidAccount { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_list")] public MicrosoftDynamicsCRMlist DuplicaterecordidList { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_resourcegroup")] public MicrosoftDynamicsCRMresourcegroup DuplicaterecordidResourcegroup { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_campaignresponse")] public MicrosoftDynamicsCRMcampaignresponse BaserecordidCampaignresponse { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_contract")] public MicrosoftDynamicsCRMcontract DuplicaterecordidContract { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_service")] public MicrosoftDynamicsCRMservice DuplicaterecordidService { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_fax")] public MicrosoftDynamicsCRMfax BaserecordidFax { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_queue")] public MicrosoftDynamicsCRMqueue DuplicaterecordidQueue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicateruleid")] public MicrosoftDynamicsCRMduplicaterule Duplicateruleid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_contact")] public MicrosoftDynamicsCRMcontact BaserecordidContact { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_incident")] public MicrosoftDynamicsCRMincident BaserecordidIncident { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_emailserverprofile")] public MicrosoftDynamicsCRMemailserverprofile DuplicaterecordidEmailserverprofile { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_queue")] public MicrosoftDynamicsCRMqueue BaserecordidQueue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_emailserverprofile")] public MicrosoftDynamicsCRMemailserverprofile BaserecordidEmailserverprofile { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "duplicaterecordid_letter")] public MicrosoftDynamicsCRMletter DuplicaterecordidLetter { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "baserecordid_quote")] public MicrosoftDynamicsCRMquote BaserecordidQuote { get; set; } } }
68.822436
30,342
0.774429
[ "Apache-2.0" ]
brianorwhatever/jag-lcrb-carla-public
cllc-interfaces/Dynamics-Autorest/Models/MicrosoftDynamicsCRMduplicaterecord.cs
107,363
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Kureshark.Model.Network { [Flags] public enum IpV4Dscp : byte { /// <summary> /// Default /// </summary> Default=0x00, /// <summary> /// Expedited Forwarding /// </summary> EF=0x2e, #region Class Selector //CSn=n*8 /// <summary> /// Class Selector 1 /// </summary> CS1=8, /// <summary> /// Class Selector 2 /// </summary> CS2=16, /// <summary> /// Class Selector 3 /// </summary> CS3=24, /// <summary> /// Class Selector 4 /// </summary> CS4=32, /// <summary> /// Class Selector 5 /// </summary> CS5=40, /// <summary> /// Class Selector 6 /// </summary> CS6=48, /// <summary> /// Class Selector 7 /// </summary> CS7=56, #endregion #region Assured Forwarding /// <summary> /// Class 1, Low Drop /// </summary> AF11=10, /// <summary> /// Class 1, Med Drop /// </summary> AF12=12, /// <summary> /// Class 1, High Drop /// </summary> AF13=14, /// <summary> /// Class 2, Low Drop /// </summary> AF21 = 18, /// <summary> /// Class 2, Med Drop /// </summary> AF22 = 20, /// <summary> /// Class 2, High Drop /// </summary> AF23 = 22, /// <summary> /// Class 3, Low Drop /// </summary> AF31 = 26, /// <summary> /// Class 3, Med Drop /// </summary> AF32 = 28, /// <summary> /// Class 3, High Drop /// </summary> AF33 = 30, /// <summary> /// Class 4, Low Drop /// </summary> AF41 = 34, /// <summary> /// Class 4, Med Drop /// </summary> AF42 = 36, /// <summary> /// Class 4, High Drop /// </summary> AF43 = 38, #endregion } }
21.970588
34
0.398483
[ "MIT" ]
KureFM/Kureshark
Kureshark.Model/Network/IpV4/IpV4Dscp.cs
2,243
C#
using Javeriana.Convenios.Api.Models; using Javeriana.Convenios.Api.Repository; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace Javeriana.Convenios.Api.Interfaces { public interface IPaisRepository : IRepositoryBase<Pais> { public IEnumerable<Pais> FindByCondition(int codigo); } }
24.625
61
0.781726
[ "Apache-2.0" ]
jacking1008/toures-balon
services/Convenios/ConveniosAPI/Convenios/ConveniosAPI/Interfaces/IPaisRepository.cs
396
C#
// // System.Runtime.InteropServices.ComTypes.IBindCtx.cs // // Author: // Andreas Nahr (ClassDevelopment@A-SoftTech.com) // Kazuki Oikawa (kazuki@panicode.com) // // // Copyright (C) 2004 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.Runtime.InteropServices.ComTypes { [ComImport] [Guid ("0000000e-0000-0000-c000-000000000046")] [InterfaceType (ComInterfaceType.InterfaceIsIUnknown)] public interface IBindCtx { void RegisterObjectBound ([MarshalAs(UnmanagedType.Interface)] object punk); void RevokeObjectBound ([MarshalAs(UnmanagedType.Interface)] object punk); void ReleaseBoundObjects (); void SetBindOptions ([In] ref BIND_OPTS pbindopts); void GetBindOptions (ref BIND_OPTS pbindopts); void GetRunningObjectTable (out IRunningObjectTable pprot); void RegisterObjectParam ([MarshalAs (UnmanagedType.LPWStr)] string pszKey, [MarshalAs (UnmanagedType.Interface)] object punk); void GetObjectParam ([MarshalAs (UnmanagedType.LPWStr)] string pszKey, [MarshalAs (UnmanagedType.Interface)] out object ppunk); void EnumObjectParam (out IEnumString ppenum); [PreserveSig] int RevokeObjectParam ([MarshalAs(UnmanagedType.LPWStr)] string pszKey); } }
43.113208
129
0.768053
[ "Apache-2.0" ]
121468615/mono
mcs/class/corlib/System.Runtime.InteropServices.ComTypes/IBindCtx.cs
2,285
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestClassLibrary; namespace TestClassLibraryTest { [TestClass] public class IndexerStubsTest { [TestMethod] public void TestIndexerGet() { var stub = new StubIGenericContainer<int>(); stub.Item_Get(index => { switch (index) { case 0: return 13; case 1: return 5; default: throw new IndexOutOfRangeException(); } }); IGenericContainer<int> container = stub; Assert.AreEqual(13, container[0]); Assert.AreEqual(5, container[1]); } [TestMethod] public void TestIndexerSet() { var stub = new StubIGenericContainer<int>(); int res = -1; stub.Item_Set((index, value) => { if (index != 0) throw new IndexOutOfRangeException(); res = value; }); IGenericContainer<int> container = stub; container[0] = 13; Assert.AreEqual(13, res); } [TestMethod] public void TestThatMultipleIndexerDontConflict() { var stub = new StubIGenericContainer<int>(); stub.Item_Get(index => 12).Item_Get((key, i) => 3); IGenericContainer<int> container = stub; Assert.AreEqual(12, container[0]); Assert.AreEqual(3, container["foo", 0]); } } }
27.098361
69
0.486388
[ "MIT" ]
Bhaskers-Blu-Org2/SimpleStubs
test/TestClassLibraryTest/IndexerStubsTest.cs
1,655
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Expression.cs" company="Hukano"> // Copyright (c) Hukano. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Sundew.Quantities.Representations.Expressions; using Sundew.Quantities.Representations.Expressions.Visitors; /// <summary> /// Base class for implementing expressions. /// </summary> public abstract class Expression { /// <summary> /// Creates an <see cref="MultiplicationExpression"/> with the specified lhs and rhs. /// </summary> /// <param name="lhs">The LHS <see cref="Expression"/>.</param> /// <param name="rhs">The RHS <see cref="Expression"/>.</param> /// <returns>An <see cref="MultiplicationExpression"/>.</returns> public static MultiplicationExpression operator *(Expression lhs, Expression rhs) { return new MultiplicationExpression(lhs, rhs); } /// <summary> /// Creates an <see cref="DivisionExpression"/> with the specified lhs and rhs. /// </summary> /// <param name="lhs">The LHS <see cref="Expression"/>.</param> /// <param name="rhs">The RHS <see cref="Expression"/>.</param> /// <returns>An <see cref="DivisionExpression"/>.</returns> public static DivisionExpression operator /(Expression lhs, Expression rhs) { return new DivisionExpression(lhs, rhs); } /// <summary> /// Visits the specified expression visitor. /// </summary> /// <typeparam name="TImmutableParameter">The type of the parameter1.</typeparam> /// <typeparam name="TMutableParameter">The type of the parameter2.</typeparam> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="expressionVisitor">The expression visitor.</param> /// <param name="parameter1">The parameter1.</param> /// <param name="parameter2">The parameter2.</param> public abstract void Visit<TImmutableParameter, TMutableParameter, TResult>( IExpressionVisitor<TImmutableParameter, TMutableParameter, TResult> expressionVisitor, TImmutableParameter parameter1, TMutableParameter parameter2); /// <summary> /// Returns a <see cref="string" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="string" /> that represents this instance. /// </returns> public override string ToString() { return DefaultVisitors.NotationVisitor.Visit(this); } }
43.253968
119
0.617982
[ "MIT" ]
hugener/Sundew.Quantities
Source/Sundew.Quantities/Representations/Expressions/Expression.cs
2,725
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; using UnityEngine.Assertions; using UnityEngine.Rendering; namespace UnityEditor.Rendering { /// <summary> /// This attributes tells a <see cref="VolumeComponentEditor"/> class which type of /// <see cref="VolumeComponent"/> it's an editor for. /// When you make a custom editor for a component, you need put this attribute on the editor /// class. /// </summary> /// <seealso cref="VolumeComponentEditor"/> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public sealed class VolumeComponentEditorAttribute : Attribute { /// <summary> /// A type derived from <see cref="VolumeComponent"/>. /// </summary> public readonly Type componentType; /// <summary> /// Creates a new <see cref="VolumeComponentEditorAttribute"/> instance. /// </summary> /// <param name="componentType">A type derived from <see cref="VolumeComponent"/></param> public VolumeComponentEditorAttribute(Type componentType) { this.componentType = componentType; } } /// <summary> /// A custom editor class that draws a <see cref="VolumeComponent"/> in the Inspector. If you do not /// provide a custom editor for a <see cref="VolumeComponent"/>, Unity uses the default one. /// You must use a <see cref="VolumeComponentEditorAttribute"/> to let the editor know which /// component this drawer is for. /// </summary> /// <example> /// Below is an example of a custom <see cref="VolumeComponent"/>: /// <code> /// using UnityEngine.Rendering; /// /// [Serializable, VolumeComponentMenu("Custom/Example Component")] /// public class ExampleComponent : VolumeComponent /// { /// public ClampedFloatParameter intensity = new ClampedFloatParameter(0f, 0f, 1f); /// } /// </code> /// And its associated editor: /// <code> /// using UnityEditor.Rendering; /// /// [VolumeComponentEditor(typeof(ExampleComponent))] /// class ExampleComponentEditor : VolumeComponentEditor /// { /// SerializedDataParameter m_Intensity; /// /// public override void OnEnable() /// { /// var o = new PropertyFetcher&lt;ExampleComponent&gt;(serializedObject); /// m_Intensity = Unpack(o.Find(x => x.intensity)); /// } /// /// public override void OnInspectorGUI() /// { /// PropertyField(m_Intensity); /// } /// } /// </code> /// </example> /// <seealso cref="VolumeComponentEditorAttribute"/> public class VolumeComponentEditor { /// <summary> /// Specifies the <see cref="VolumeComponent"/> this editor is drawing. /// </summary> public VolumeComponent target { get; private set; } /// <summary> /// A <c>SerializedObject</c> representing the object being inspected. /// </summary> public SerializedObject serializedObject { get; private set; } /// <summary> /// The copy of the serialized property of the <see cref="VolumeComponent"/> being /// inspected. Unity uses this to track whether the editor is collapsed in the Inspector or not. /// </summary> public SerializedProperty baseProperty { get; internal set; } /// <summary> /// The serialized property of <see cref="VolumeComponent.active"/> for the component being /// inspected. /// </summary> public SerializedProperty activeProperty { get; internal set; } SerializedProperty m_AdvancedMode; /// <summary> /// Override this property if your editor makes use of the "More Options" feature. /// </summary> public virtual bool hasAdvancedMode => false; /// <summary> /// Checks if the editor currently has the "More Options" feature toggled on. /// </summary> public bool isInAdvancedMode { get => m_AdvancedMode != null && m_AdvancedMode.boolValue; internal set { if (m_AdvancedMode != null) { m_AdvancedMode.boolValue = value; serializedObject.ApplyModifiedProperties(); } } } /// <summary> /// A reference to the parent editor in the Inspector. /// </summary> protected Editor m_Inspector; List<(GUIContent displayName, int displayOrder, SerializedDataParameter param)> m_Parameters; static Dictionary<Type, VolumeParameterDrawer> s_ParameterDrawers; static VolumeComponentEditor() { s_ParameterDrawers = new Dictionary<Type, VolumeParameterDrawer>(); ReloadDecoratorTypes(); } [Callbacks.DidReloadScripts] static void OnEditorReload() { ReloadDecoratorTypes(); } static void ReloadDecoratorTypes() { s_ParameterDrawers.Clear(); // Look for all the valid parameter drawers var types = CoreUtils.GetAllTypesDerivedFrom<VolumeParameterDrawer>() .Where( t => t.IsDefined(typeof(VolumeParameterDrawerAttribute), false) && !t.IsAbstract ); // Store them foreach (var type in types) { var attr = (VolumeParameterDrawerAttribute)type.GetCustomAttributes(typeof(VolumeParameterDrawerAttribute), false)[0]; var decorator = (VolumeParameterDrawer)Activator.CreateInstance(type); s_ParameterDrawers.Add(attr.parameterType, decorator); } } /// <summary> /// Triggers an Inspector repaint event. /// </summary> public void Repaint() { m_Inspector.Repaint(); } internal void Init(VolumeComponent target, Editor inspector) { this.target = target; m_Inspector = inspector; serializedObject = new SerializedObject(target); activeProperty = serializedObject.FindProperty("active"); m_AdvancedMode = serializedObject.FindProperty("m_AdvancedMode"); OnEnable(); } class ParameterSorter : Comparer<(GUIContent displayName, int displayOrder, SerializedDataParameter param)> { public override int Compare((GUIContent displayName, int displayOrder, SerializedDataParameter param) x, (GUIContent displayName, int displayOrder, SerializedDataParameter param) y) { if (x.displayOrder < y.displayOrder) return -1; else if (x.displayOrder == y.displayOrder) return 0; else return 1; } } /// <summary> /// Unity calls this method when the object loads. /// </summary> /// <remarks> /// You can safely override this method and not call <c>base.OnEnable()</c> unless you want /// Unity to display all the properties from the <see cref="VolumeComponent"/> automatically. /// </remarks> public virtual void OnEnable() { m_Parameters = new List<(GUIContent, int, SerializedDataParameter)>(); // Grab all valid serializable field on the VolumeComponent // TODO: Should only be done when needed / on demand as this can potentially be wasted CPU when a custom editor is in use var fields = target.GetType() .GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) .Where(t => t.FieldType.IsSubclassOf(typeof(VolumeParameter))) .Where(t => (t.IsPublic && t.GetCustomAttributes(typeof(NonSerializedAttribute), false).Length == 0) || (t.GetCustomAttributes(typeof(SerializeField), false).Length > 0) ) .Where(t => t.GetCustomAttributes(typeof(HideInInspector), false).Length == 0) .ToList(); // Prepare all serialized objects for this editor foreach (var field in fields) { var property = serializedObject.FindProperty(field.Name); var name = ""; var order = 0; var attr = (DisplayInfoAttribute[])field.GetCustomAttributes(typeof(DisplayInfoAttribute), true); if (attr.Length != 0) { name = attr[0].name; order = attr[0].order; } var parameter = new SerializedDataParameter(property); m_Parameters.Add((new GUIContent(name), order, parameter)); } m_Parameters.Sort(new ParameterSorter()); } /// <summary> /// Unity calls this method when the object goes out of scope. /// </summary> public virtual void OnDisable() { } internal void OnInternalInspectorGUI() { serializedObject.Update(); TopRowFields(); OnInspectorGUI(); EditorGUILayout.Space(); serializedObject.ApplyModifiedProperties(); } /// <summary> /// Unity calls this method everytime it re-draws the Inspector. /// </summary> /// <remarks> /// You can safely override this method and not call <c>base.OnInspectorGUI()</c> unless you /// want Unity to display all the properties from the <see cref="VolumeComponent"/> /// automatically. /// </remarks> public virtual void OnInspectorGUI() { // Display every field as-is foreach (var parameter in m_Parameters) { if (parameter.displayName.text != "") PropertyField(parameter.param, parameter.displayName); else PropertyField(parameter.param); } } /// <summary> /// Sets the label for the component header. Override this method to provide /// a custom label. If you don't, Unity automatically inferres one from the class name. /// </summary> /// <returns>A label to display in the component header.</returns> public virtual string GetDisplayTitle() { return target.displayName == "" ? ObjectNames.NicifyVariableName(target.GetType().Name) : target.displayName; } void TopRowFields() { using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Button(EditorGUIUtility.TrTextContent("All", "Toggle all overrides on. To maximize performances you should only toggle overrides that you actually need."), CoreEditorStyles.miniLabelButton, GUILayout.Width(17f), GUILayout.ExpandWidth(false))) SetAllOverridesTo(true); if (GUILayout.Button(EditorGUIUtility.TrTextContent("None", "Toggle all overrides off."), CoreEditorStyles.miniLabelButton, GUILayout.Width(32f), GUILayout.ExpandWidth(false))) SetAllOverridesTo(false); } } internal void SetAllOverridesTo(bool state) { Undo.RecordObject(target, "Toggle All"); target.SetAllOverridesTo(state); serializedObject.Update(); } /// <summary> /// Generates and auto-populates a <see cref="SerializedDataParameter"/> from a serialized /// <see cref="VolumeParameter{T}"/>. /// </summary> /// <param name="property">A serialized property holding a <see cref="VolumeParameter{T}"/> /// </param> /// <returns></returns> protected SerializedDataParameter Unpack(SerializedProperty property) { Assert.IsNotNull(property); return new SerializedDataParameter(property); } /// <summary> /// Draws a given <see cref="SerializedDataParameter"/> in the editor. /// </summary> /// <param name="property">The property to draw in the editor</param> protected void PropertyField(SerializedDataParameter property) { var title = EditorGUIUtility.TrTextContent(property.displayName); PropertyField(property, title); } /// <summary> /// Draws a given <see cref="SerializedDataParameter"/> in the editor using a custom label /// and tooltip. /// </summary> /// <param name="property">The property to draw in the editor.</param> /// <param name="title">A custom label and/or tooltip.</param> protected void PropertyField(SerializedDataParameter property, GUIContent title) { // Handle unity built-in decorators (Space, Header, Tooltip etc) foreach (var attr in property.attributes) { if (attr is PropertyAttribute) { if (attr is SpaceAttribute) { EditorGUILayout.GetControlRect(false, (attr as SpaceAttribute).height); } else if (attr is HeaderAttribute) { var rect = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight); rect.y += 0f; rect = EditorGUI.IndentedRect(rect); EditorGUI.LabelField(rect, (attr as HeaderAttribute).header, EditorStyles.miniLabel); } else if (attr is TooltipAttribute) { if (string.IsNullOrEmpty(title.tooltip)) title.tooltip = (attr as TooltipAttribute).tooltip; } } } // Custom parameter drawer VolumeParameterDrawer drawer; s_ParameterDrawers.TryGetValue(property.referenceType, out drawer); bool invalidProp = false; if (drawer != null && !drawer.IsAutoProperty()) { if (drawer.OnGUI(property, title)) return; invalidProp = true; } // ObjectParameter<T> is a special case if (VolumeParameter.IsObjectParameter(property.referenceType)) { bool expanded = property.value.isExpanded; expanded = EditorGUILayout.Foldout(expanded, title, true); if (expanded) { EditorGUI.indentLevel++; // Not the fastest way to do it but that'll do just fine for now var it = property.value.Copy(); var end = it.GetEndProperty(); bool first = true; while (it.Next(first) && !SerializedProperty.EqualContents(it, end)) { PropertyField(Unpack(it)); first = false; } EditorGUI.indentLevel--; } property.value.isExpanded = expanded; return; } using (new EditorGUILayout.HorizontalScope()) { // Override checkbox DrawOverrideCheckbox(property); // Property using (new EditorGUI.DisabledScope(!property.overrideState.boolValue)) { if (drawer != null && !invalidProp) { if (drawer.OnGUI(property, title)) return; } // Default unity field EditorGUILayout.PropertyField(property.value, title); } } } /// <summary> /// Draws the override checkbox used by a property in the editor. /// </summary> /// <param name="property">The property to draw the override checkbox for</param> protected void DrawOverrideCheckbox(SerializedDataParameter property) { var overrideRect = GUILayoutUtility.GetRect(17f, 17f, GUILayout.ExpandWidth(false)); overrideRect.yMin += 4f; property.overrideState.boolValue = GUI.Toggle(overrideRect, property.overrideState.boolValue, EditorGUIUtility.TrTextContent("", "Override this setting for this volume."), CoreEditorStyles.smallTickbox); } } }
38.967593
272
0.56677
[ "MIT" ]
thelebaron/bendfoldjam
Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentEditor.cs
16,834
C#
using System; using System.IO; using System.Windows.Forms; using VanBurenExplorer.Properties; using VanBurenExplorerLib; using VanBurenExplorerLib.Helpers; using VanBurenExplorerLib.Views; namespace VanBurenExplorer { public partial class MainForm : Form, IMainView { private readonly MainViewPresenter _presenter; public MainForm() { InitializeComponent(); _presenter = new MainViewPresenter(this); } private void Exit_Click(object sender, EventArgs e) { Close(); } private void About_Click(object sender, EventArgs e) { var aboutBox = new AboutBox(); aboutBox.ShowDialog(); } private void Directory_Click(object sender, EventArgs e) { var result = folderBrowserDialog1.ShowDialog(); if (!result.Equals(DialogResult.OK)) return; ClearControls(); ChangeDirectory(folderBrowserDialog1.SelectedPath); } private void GetDirectories(DirectoryInfo[] subDirs, TreeNode nodeToAddTo) { foreach (var subDir in subDirs) { try { var aNode = new TreeNode(subDir.Name, 0, 0) { Tag = subDir, ImageKey = Resources.TreeNodeImageKey }; var subSubDirs = subDir.GetDirectories(); if (subSubDirs.Length != 0) { GetDirectories(subSubDirs, aNode); } nodeToAddTo.Nodes.Add(aNode); } catch (UnauthorizedAccessException) { // ok, so we are not allowed to dig into that directory. Move on... } } } private void TreeView_AfterSelect(object sender, TreeViewEventArgs e) { using (new WaitCursor()) { if (!e.Node.IsSelected) return; var newSelected = e.Node; listView.Items.Clear(); var nodeDirInfo = (DirectoryInfo) newSelected.Tag; ListViewItem.ListViewSubItem[] subItems; foreach (var dir in nodeDirInfo.GetDirectories()) { var item = new ListViewItem(dir.Name, 0); subItems = new[] { new ListViewItem.ListViewSubItem(item, dir.LastAccessTime.ToString("g")), new ListViewItem.ListViewSubItem(item, Resources.DirectoryListViewType) }; item.SubItems.AddRange(subItems); listView.Items.Add(item); } foreach (var file in nodeDirInfo.GetFiles()) { var item = new ListViewItem(file.Name, 1) {Tag = file}; subItems = new[] { new ListViewItem.ListViewSubItem(item, file.LastAccessTime.ToString("g")), new ListViewItem.ListViewSubItem(item, FileHelper.GetFileTypeDescription(file.Name)), new ListViewItem.ListViewSubItem(item, FileHelper.GetFormattedSize(file.Length)) }; item.SubItems.AddRange(subItems); listView.Items.Add(item); } directoryTextBox.Text = nodeDirInfo.FullName; listView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); } } private void ListView_SelectedIndexChanged(object sender, EventArgs e) { using (new WaitCursor()) { // get currently selected file var item = listView.FocusedItem; // check if we have the full details for the file (folders won't have this) var file = (FileInfo) item?.Tag; // if this a folder just return if (file == null) return; // process it for viewing _presenter.LoadFile(file); } } private void MainForm_Load(object sender, EventArgs e) { using (new WaitCursor()) { _presenter.Init(); } } /// <summary> /// The tree view load is done here after the form is displayed so the user /// is at least looking at something in case we have a big folder to process /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainForm_Shown(object sender, EventArgs e) { // let the user know we're about to do this toolStripStatusLabel1.Text = Resources.StatusLoadingText; // start the program off by asking where to start looking for files Directory_Click(this, e); // once we're ready let the user know toolStripStatusLabel1.Text = Resources.StatusReadyText; } public void SetControl(Control control) { splitContainer1.Panel1.Controls.Clear(); splitContainer1.Panel1.Controls.Add(control); } public void SetStatusText(string text) { toolStripStatusLabel1.Text = text; } public void ChangeDirectory(string path) { using (new WaitCursor()) { var info = new DirectoryInfo(path); if (!info.Exists) return; var rootNode = new TreeNode(info.Name) { Tag = info }; GetDirectories(info.GetDirectories(), rootNode); treeView.Nodes.Add(rootNode); rootNode.Expand(); treeView.SelectedNode = rootNode; _presenter.LoadCatalog(path); } } private void ClearControls() { treeView.Nodes.Clear(); listView.Items.Clear(); splitContainer1.Panel1.Controls.Clear(); } } }
35.782353
120
0.532632
[ "MIT" ]
bsimser/Van-Buren-Explorer
VanBurenExplorer/MainForm.cs
6,085
C#
using System.Windows; namespace LucaHome.Dialogs { public enum DialogAction { NULL, CONFIRM, CANCEL }; public partial class SetDialog : Window { private const string TAG = "SetDialog"; private DialogAction _setDialogAction = DialogAction.NULL; public SetDialog(string title, string description, string confirmButtonText, string cancelButtonText) { InitializeComponent(); Title.Text = title; Description.Text = description; ConfirmButton.Content = confirmButtonText; CancelButton.Content = cancelButtonText; } public SetDialog(string title, string description) : this(title, description, "Confirm", "Cancel") { } public DialogAction SetDialogAction { get { return _setDialogAction; } } private void ConfirmButton_Click(object sender, RoutedEventArgs routedEventArgs) { _setDialogAction = DialogAction.CONFIRM; Close(); } private void CancelButton_Click(object sender, RoutedEventArgs routedEventArgs) { _setDialogAction = DialogAction.CANCEL; Close(); } } }
26.5
109
0.605346
[ "MIT" ]
FriedrichWilhelmNietzsche/LucaHome-WPFApplication
LucaHome/Dialogs/SetDialog.xaml.cs
1,274
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudfront-2014-11-06.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.CloudFront.Model { ///<summary> /// CloudFront exception /// </summary> public class NoSuchOriginException : AmazonCloudFrontException { /// <summary> /// Constructs a new NoSuchOriginException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public NoSuchOriginException(string message) : base(message) {} public NoSuchOriginException(string message, Exception innerException) : base(message, innerException) {} public NoSuchOriginException(Exception innerException) : base(innerException) {} public NoSuchOriginException(string message, Exception innerException, ErrorType errorType, string errorCode, string RequestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, RequestId, statusCode) {} public NoSuchOriginException(string message, ErrorType errorType, string errorCode, string RequestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, RequestId, statusCode) {} } }
37.886792
163
0.680777
[ "Apache-2.0" ]
samritchie/aws-sdk-net
AWSSDK_DotNet35/Amazon.CloudFront/Model/NoSuchOriginException.cs
2,008
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; using ReqIFSharp; namespace ReqIF_Editor { public class SpecObjectsViewModel { public SpecObjectsViewModel(ReqIFContent content) { foreach (SpecObject specObject in content.SpecObjects) { SpecobjectViewModel specobjectViewModel = new SpecobjectViewModel() { Identifier = specObject.Identifier, AlternativeId = specObject.AlternativeId, Description = specObject.Description, LastChange = specObject.LastChange, LongName = specObject.LongName, Type = specObject.Type, SpecType = specObject.SpecType }; foreach (AttributeDefinition attributeDefinition in content.SpecTypes.Single(x => x == specObject.SpecType).SpecAttributes) { AttributeValue attributeValue = specObject.Values.Where(x => x.AttributeDefinition == attributeDefinition).FirstOrDefault(); specobjectViewModel.Values.Add(new AttributeValueViewModel() { AttributeValue = attributeValue, AttributeDefinition = attributeDefinition }); } this.SpecObjects.Add(specobjectViewModel); } } private readonly ObservableCollection<SpecobjectViewModel> specObjects = new ObservableCollection<SpecobjectViewModel>(); /// <summary> /// Gets the <see cref="SpecobjectViewModel"/> /// </summary> public ObservableCollection<SpecobjectViewModel> SpecObjects { get { return this.specObjects; } } } public class SpecobjectViewModel : SpecObject { private ObservableCollection<AttributeValueViewModel> values = new ObservableCollection<AttributeValueViewModel>(); public new ObservableCollection<AttributeValueViewModel> Values { get { return this.values; } } } public class AttributeValueViewModel : INotifyPropertyChanged { private AttributeDefinition _attributeDefinition; private AttributeValue _attributeValue; private bool _added; private bool _removed; private bool _changed; public AttributeDefinition AttributeDefinition { get { return _attributeDefinition; } set { _attributeDefinition = value; } } public AttributeValue AttributeValue { get { return _attributeValue; } set { _attributeValue = value; NotifyPropertyChanged(); } } public bool added { get { return _added; } set { _added = value; NotifyPropertyChanged(); } } public bool removed { get { return _removed; } set { _removed = value; NotifyPropertyChanged(); } } public bool changed { get { return _changed; } set { _changed = value; NotifyPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
33.078261
161
0.606467
[ "Apache-2.0" ]
LBRNZ/ReqIF_Editor
Tools/SpecObjectsViewModel.cs
3,806
C#
using System; using System.Collections.Generic; namespace binarysearchtree { // https://stackoverflow.com/a/36496436/1051256 public static class BTreePrinter { class NodeInfo { public BinarySearchTree Node; public string Text; public int StartPos; public int Size { get { return Text.Length; } } public int EndPos { get { return StartPos + Size; } set { StartPos = value - Size; } } public NodeInfo Parent, Left, Right; } public static void Print(this BinarySearchTree root, int topMargin = 2, int leftMargin = 2) { if (root == null) return; int rootTop = Console.CursorTop + topMargin; var last = new List<NodeInfo>(); var next = root; for (int level = 0; next != null; level++) { var item = new NodeInfo { Node = next, Text = next.Value.ToString(" 0 ") }; if (level < last.Count) { item.StartPos = last[level].EndPos + 1; last[level] = item; } else { item.StartPos = leftMargin; last.Add(item); } if (level > 0) { item.Parent = last[level - 1]; if (next == item.Parent.Node.Left) { item.Parent.Left = item; item.EndPos = Math.Max(item.EndPos, item.Parent.StartPos); } else { item.Parent.Right = item; item.StartPos = Math.Max(item.StartPos, item.Parent.EndPos); } } next = next.Left ?? next.Right; for (; next == null; item = item.Parent) { Print(item, rootTop + 2 * level); if (--level < 0) break; if (item == item.Parent.Left) { item.Parent.StartPos = item.EndPos; next = item.Parent.Node.Right; } else { if (item.Parent.Left == null) item.Parent.EndPos = item.StartPos; else item.Parent.StartPos += (item.StartPos - item.Parent.EndPos) / 2; } } } Console.SetCursorPosition(0, rootTop + 2 * last.Count - 1); } private static void Print(NodeInfo item, int top) { SwapColors(); Print(item.Text, top, item.StartPos); SwapColors(); if (item.Left != null) PrintLink(top + 1, "┌", "┘", item.Left.StartPos + item.Left.Size / 2, item.StartPos); if (item.Right != null) PrintLink(top + 1, "└", "┐", item.EndPos - 1, item.Right.StartPos + item.Right.Size / 2); } private static void PrintLink(int top, string start, string end, int startPos, int endPos) { Print(start, top, startPos); Print("─", top, startPos + 1, endPos); Print(end, top, endPos); } private static void Print(string s, int top, int left, int right = -1) { Console.SetCursorPosition(left, top); if (right < 0) right = left + s.Length; while (Console.CursorLeft < right) Console.Write(s); } private static void SwapColors() { var color = Console.ForegroundColor; Console.ForegroundColor = Console.BackgroundColor; Console.BackgroundColor = color; } } }
36.476636
105
0.450679
[ "MIT" ]
macromania/algorithms-data-structures
data-structures/binarysearchtree/TreePrinter.cs
3,913
C#
using Light.Domain.Bus.EventHandler; using Light.Domain.Bus.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Light.Event.Contracts { public interface IAuditVersionedEventHandler : IEventHandler<VersionedEvent> { } }
21.266667
80
0.789969
[ "MIT" ]
delexw/net-lightBoilerplate
Domain/Light.Event/Contracts/IAuditVersionedEventHandler.cs
321
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: MethodRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The type WorkbookFunctionsMatchRequest. /// </summary> public partial class WorkbookFunctionsMatchRequest : BaseRequest, IWorkbookFunctionsMatchRequest { /// <summary> /// Constructs a new WorkbookFunctionsMatchRequest. /// </summary> public WorkbookFunctionsMatchRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.RequestBody = new WorkbookFunctionsMatchRequestBody(); } /// <summary> /// Gets the request body. /// </summary> public WorkbookFunctionsMatchRequestBody RequestBody { get; private set; } /// <summary> /// Issues the POST request. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await for async call.</returns> public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync( CancellationToken cancellationToken = default) { this.Method = HttpMethods.POST; return this.SendAsync<WorkbookFunctionResult>(this.RequestBody, cancellationToken); } /// <summary> /// Issues the POST request and returns a <see cref="GraphResponse"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse"/> object of the request</returns> public System.Threading.Tasks.Task<GraphResponse<WorkbookFunctionResult>> PostResponseAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.POST; return this.SendAsyncWithGraphResponse<WorkbookFunctionResult>(this.RequestBody, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsMatchRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsMatchRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } } }
38.988764
153
0.60317
[ "MIT" ]
Aliases/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/WorkbookFunctionsMatchRequest.cs
3,470
C#
namespace PersonInfo { public interface IIdentifiable { string Id { get; } } }
11.666667
34
0.552381
[ "MIT" ]
teodortenchev/C-Sharp-Advanced-Coursework
C# OOP Basics/InterfacesAndAbstraction/P2_MultipleImplementation/IIdentifiable.cs
107
C#
using System; namespace WeifenLuo.WinFormsUI.Docking { public class DockContentEventArgs : EventArgs { private IDockContent m_content; public DockContentEventArgs(IDockContent content) { m_content = content; } public IDockContent Content { get { return m_content; } } } }
14.9
51
0.731544
[ "MIT" ]
3-Delta/Unity-UI
Tools/AI/Behaviac/External/DockPanel/WinFormsUI/Docking/DockContentEventArgs.cs
298
C#
#region --- License --- /* 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. */ #endregion using System; using System.Runtime.InteropServices; using System.Xml.Serialization; namespace OpenTK { /// <summary>Represents a 4D vector using four double-precision floating-point numbers.</summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector4d : IEquatable<Vector4d> { #region Fields /// <summary> /// The X component of the Vector4d. /// </summary> public double X; /// <summary> /// The Y component of the Vector4d. /// </summary> public double Y; /// <summary> /// The Z component of the Vector4d. /// </summary> public double Z; /// <summary> /// The W component of the Vector4d. /// </summary> public double W; /// <summary> /// Defines a unit-length Vector4d that points towards the X-axis. /// </summary> public static Vector4d UnitX = new Vector4d(1, 0, 0, 0); /// <summary> /// Defines a unit-length Vector4d that points towards the Y-axis. /// </summary> public static Vector4d UnitY = new Vector4d(0, 1, 0, 0); /// <summary> /// Defines a unit-length Vector4d that points towards the Z-axis. /// </summary> public static Vector4d UnitZ = new Vector4d(0, 0, 1, 0); /// <summary> /// Defines a unit-length Vector4d that points towards the W-axis. /// </summary> public static Vector4d UnitW = new Vector4d(0, 0, 0, 1); /// <summary> /// Defines a zero-length Vector4d. /// </summary> public static Vector4d Zero = new Vector4d(0, 0, 0, 0); /// <summary> /// Defines an instance with all components set to 1. /// </summary> public static readonly Vector4d One = new Vector4d(1, 1, 1, 1); /// <summary> /// Defines the size of the Vector4d struct in bytes. /// </summary> public static readonly int SizeInBytes = Marshal.SizeOf(new Vector4d()); #endregion #region Constructors /// <summary> /// Constructs a new instance. /// </summary> /// <param name="value">The value that will initialize this instance.</param> public Vector4d(double value) { X = value; Y = value; Z = value; W = value; } /// <summary> /// Constructs a new Vector4d. /// </summary> /// <param name="x">The x component of the Vector4d.</param> /// <param name="y">The y component of the Vector4d.</param> /// <param name="z">The z component of the Vector4d.</param> /// <param name="w">The w component of the Vector4d.</param> public Vector4d(double x, double y, double z, double w) { X = x; Y = y; Z = z; W = w; } /// <summary> /// Constructs a new Vector4d from the given Vector2d. /// </summary> /// <param name="v">The Vector2d to copy components from.</param> public Vector4d(Vector2d v) { X = v.X; Y = v.Y; Z = 0.0f; W = 0.0f; } /// <summary> /// Constructs a new Vector4d from the given Vector3d. /// The w component is initialized to 0. /// </summary> /// <param name="v">The Vector3d to copy components from.</param> /// <remarks><seealso cref="Vector4d(Vector3d, double)"/></remarks> public Vector4d(Vector3d v) { X = v.X; Y = v.Y; Z = v.Z; W = 0.0f; } /// <summary> /// Constructs a new Vector4d from the specified Vector3d and w component. /// </summary> /// <param name="v">The Vector3d to copy components from.</param> /// <param name="w">The w component of the new Vector4.</param> public Vector4d(Vector3d v, double w) { X = v.X; Y = v.Y; Z = v.Z; W = w; } /// <summary> /// Constructs a new Vector4d from the given Vector4d. /// </summary> /// <param name="v">The Vector4d to copy components from.</param> public Vector4d(Vector4d v) { X = v.X; Y = v.Y; Z = v.Z; W = v.W; } #endregion #region Public Members #region Instance #region public void Add() /// <summary>Add the Vector passed as parameter to this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [Obsolete("Use static Add() method instead.")] public void Add(Vector4d right) { this.X += right.X; this.Y += right.Y; this.Z += right.Z; this.W += right.W; } /// <summary>Add the Vector passed as parameter to this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [CLSCompliant(false)] [Obsolete("Use static Add() method instead.")] public void Add(ref Vector4d right) { this.X += right.X; this.Y += right.Y; this.Z += right.Z; this.W += right.W; } #endregion public void Add() #region public void Sub() /// <summary>Subtract the Vector passed as parameter from this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [Obsolete("Use static Subtract() method instead.")] public void Sub(Vector4d right) { this.X -= right.X; this.Y -= right.Y; this.Z -= right.Z; this.W -= right.W; } /// <summary>Subtract the Vector passed as parameter from this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [CLSCompliant(false)] [Obsolete("Use static Subtract() method instead.")] public void Sub(ref Vector4d right) { this.X -= right.X; this.Y -= right.Y; this.Z -= right.Z; this.W -= right.W; } #endregion public void Sub() #region public void Mult() /// <summary>Multiply this instance by a scalar.</summary> /// <param name="f">Scalar operand.</param> [Obsolete("Use static Multiply() method instead.")] public void Mult(double f) { this.X *= f; this.Y *= f; this.Z *= f; this.W *= f; } #endregion public void Mult() #region public void Div() /// <summary>Divide this instance by a scalar.</summary> /// <param name="f">Scalar operand.</param> [Obsolete("Use static Divide() method instead.")] public void Div(double f) { double mult = 1.0 / f; this.X *= mult; this.Y *= mult; this.Z *= mult; this.W *= mult; } #endregion public void Div() #region public double Length /// <summary> /// Gets the length (magnitude) of the vector. /// </summary> /// <see cref="LengthFast"/> /// <seealso cref="LengthSquared"/> public double Length { get { return System.Math.Sqrt(X * X + Y * Y + Z * Z + W * W); } } #endregion #region public double LengthFast /// <summary> /// Gets an approximation of the vector length (magnitude). /// </summary> /// <remarks> /// This property uses an approximation of the square root function to calculate vector magnitude, with /// an upper error bound of 0.001. /// </remarks> /// <see cref="Length"/> /// <seealso cref="LengthSquared"/> public double LengthFast { get { return 1.0 / MathHelper.InverseSqrtFast(X * X + Y * Y + Z * Z + W * W); } } #endregion #region public double LengthSquared /// <summary> /// Gets the square of the vector length (magnitude). /// </summary> /// <remarks> /// This property avoids the costly square root operation required by the Length property. This makes it more suitable /// for comparisons. /// </remarks> /// <see cref="Length"/> public double LengthSquared { get { return X * X + Y * Y + Z * Z + W * W; } } #endregion #region public void Normalize() /// <summary> /// Scales the Vector4d to unit length. /// </summary> public void Normalize() { double scale = 1.0 / this.Length; X *= scale; Y *= scale; Z *= scale; W *= scale; } #endregion #region public void NormalizeFast() /// <summary> /// Scales the Vector4d to approximately unit length. /// </summary> public void NormalizeFast() { double scale = MathHelper.InverseSqrtFast(X * X + Y * Y + Z * Z + W * W); X *= scale; Y *= scale; Z *= scale; W *= scale; } #endregion #region public void Scale() /// <summary> /// Scales the current Vector4d by the given amounts. /// </summary> /// <param name="sx">The scale of the X component.</param> /// <param name="sy">The scale of the Y component.</param> /// <param name="sz">The scale of the Z component.</param> /// <param name="sw">The scale of the Z component.</param> [Obsolete("Use static Multiply() method instead.")] public void Scale(double sx, double sy, double sz, double sw) { this.X = X * sx; this.Y = Y * sy; this.Z = Z * sz; this.W = W * sw; } /// <summary>Scales this instance by the given parameter.</summary> /// <param name="scale">The scaling of the individual components.</param> [Obsolete("Use static Multiply() method instead.")] public void Scale(Vector4d scale) { this.X *= scale.X; this.Y *= scale.Y; this.Z *= scale.Z; this.W *= scale.W; } /// <summary>Scales this instance by the given parameter.</summary> /// <param name="scale">The scaling of the individual components.</param> [CLSCompliant(false)] [Obsolete("Use static Multiply() method instead.")] public void Scale(ref Vector4d scale) { this.X *= scale.X; this.Y *= scale.Y; this.Z *= scale.Z; this.W *= scale.W; } #endregion public void Scale() #endregion #region Static #region Obsolete #region Sub /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>Result of subtraction</returns> [Obsolete("Use static Subtract() method instead.")] public static Vector4d Sub(Vector4d a, Vector4d b) { a.X -= b.X; a.Y -= b.Y; a.Z -= b.Z; a.W -= b.W; return a; } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> [Obsolete("Use static Subtract() method instead.")] public static void Sub(ref Vector4d a, ref Vector4d b, out Vector4d result) { result.X = a.X - b.X; result.Y = a.Y - b.Y; result.Z = a.Z - b.Z; result.W = a.W - b.W; } #endregion #region Mult /// <summary> /// Multiply a vector and a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="f">Scalar operand</param> /// <returns>Result of the multiplication</returns> [Obsolete("Use static Multiply() method instead.")] public static Vector4d Mult(Vector4d a, double f) { a.X *= f; a.Y *= f; a.Z *= f; a.W *= f; return a; } /// <summary> /// Multiply a vector and a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="f">Scalar operand</param> /// <param name="result">Result of the multiplication</param> [Obsolete("Use static Multiply() method instead.")] public static void Mult(ref Vector4d a, double f, out Vector4d result) { result.X = a.X * f; result.Y = a.Y * f; result.Z = a.Z * f; result.W = a.W * f; } #endregion #region Div /// <summary> /// Divide a vector by a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="f">Scalar operand</param> /// <returns>Result of the division</returns> [Obsolete("Use static Divide() method instead.")] public static Vector4d Div(Vector4d a, double f) { double mult = 1.0 / f; a.X *= mult; a.Y *= mult; a.Z *= mult; a.W *= mult; return a; } /// <summary> /// Divide a vector by a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="f">Scalar operand</param> /// <param name="result">Result of the division</param> [Obsolete("Use static Divide() method instead.")] public static void Div(ref Vector4d a, double f, out Vector4d result) { double mult = 1.0 / f; result.X = a.X * mult; result.Y = a.Y * mult; result.Z = a.Z * mult; result.W = a.W * mult; } #endregion #endregion #region Add /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <returns>Result of operation.</returns> public static Vector4d Add(Vector4d a, Vector4d b) { Add(ref a, ref b, out a); return a; } /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <param name="result">Result of operation.</param> public static void Add(ref Vector4d a, ref Vector4d b, out Vector4d result) { result = new Vector4d(a.X + b.X, a.Y + b.Y, a.Z + b.Z, a.W + b.W); } #endregion #region Subtract /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>Result of subtraction</returns> public static Vector4d Subtract(Vector4d a, Vector4d b) { Subtract(ref a, ref b, out a); return a; } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> public static void Subtract(ref Vector4d a, ref Vector4d b, out Vector4d result) { result = new Vector4d(a.X - b.X, a.Y - b.Y, a.Z - b.Z, a.W - b.W); } #endregion #region Multiply /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector4d Multiply(Vector4d vector, double scale) { Multiply(ref vector, scale, out vector); return vector; } /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector4d vector, double scale, out Vector4d result) { result = new Vector4d(vector.X * scale, vector.Y * scale, vector.Z * scale, vector.W * scale); } /// <summary> /// Multiplies a vector by the components a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector4d Multiply(Vector4d vector, Vector4d scale) { Multiply(ref vector, ref scale, out vector); return vector; } /// <summary> /// Multiplies a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector4d vector, ref Vector4d scale, out Vector4d result) { result = new Vector4d(vector.X * scale.X, vector.Y * scale.Y, vector.Z * scale.Z, vector.W * scale.W); } #endregion #region Divide /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector4d Divide(Vector4d vector, double scale) { Divide(ref vector, scale, out vector); return vector; } /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector4d vector, double scale, out Vector4d result) { Multiply(ref vector, 1 / scale, out result); } /// <summary> /// Divides a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector4d Divide(Vector4d vector, Vector4d scale) { Divide(ref vector, ref scale, out vector); return vector; } /// <summary> /// Divide a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector4d vector, ref Vector4d scale, out Vector4d result) { result = new Vector4d(vector.X / scale.X, vector.Y / scale.Y, vector.Z / scale.Z, vector.W / scale.W); } #endregion #region Min /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise minimum</returns> public static Vector4d Min(Vector4d a, Vector4d b) { a.X = a.X < b.X ? a.X : b.X; a.Y = a.Y < b.Y ? a.Y : b.Y; a.Z = a.Z < b.Z ? a.Z : b.Z; a.W = a.W < b.W ? a.W : b.W; return a; } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise minimum</param> public static void Min(ref Vector4d a, ref Vector4d b, out Vector4d result) { result.X = a.X < b.X ? a.X : b.X; result.Y = a.Y < b.Y ? a.Y : b.Y; result.Z = a.Z < b.Z ? a.Z : b.Z; result.W = a.W < b.W ? a.W : b.W; } #endregion #region Max /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise maximum</returns> public static Vector4d Max(Vector4d a, Vector4d b) { a.X = a.X > b.X ? a.X : b.X; a.Y = a.Y > b.Y ? a.Y : b.Y; a.Z = a.Z > b.Z ? a.Z : b.Z; a.W = a.W > b.W ? a.W : b.W; return a; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise maximum</param> public static void Max(ref Vector4d a, ref Vector4d b, out Vector4d result) { result.X = a.X > b.X ? a.X : b.X; result.Y = a.Y > b.Y ? a.Y : b.Y; result.Z = a.Z > b.Z ? a.Z : b.Z; result.W = a.W > b.W ? a.W : b.W; } #endregion #region Clamp /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <returns>The clamped vector</returns> public static Vector4d Clamp(Vector4d vec, Vector4d min, Vector4d max) { vec.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; vec.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; vec.Z = vec.X < min.Z ? min.Z : vec.Z > max.Z ? max.Z : vec.Z; vec.W = vec.Y < min.W ? min.W : vec.W > max.W ? max.W : vec.W; return vec; } /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <param name="result">The clamped vector</param> public static void Clamp(ref Vector4d vec, ref Vector4d min, ref Vector4d max, out Vector4d result) { result.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; result.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; result.Z = vec.X < min.Z ? min.Z : vec.Z > max.Z ? max.Z : vec.Z; result.W = vec.Y < min.W ? min.W : vec.W > max.W ? max.W : vec.W; } #endregion #region Normalize /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector4d Normalize(Vector4d vec) { double scale = 1.0 / vec.Length; vec.X *= scale; vec.Y *= scale; vec.Z *= scale; vec.W *= scale; return vec; } /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void Normalize(ref Vector4d vec, out Vector4d result) { double scale = 1.0 / vec.Length; result.X = vec.X * scale; result.Y = vec.Y * scale; result.Z = vec.Z * scale; result.W = vec.W * scale; } #endregion #region NormalizeFast /// <summary> /// Scale a vector to approximately unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector4d NormalizeFast(Vector4d vec) { double scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y + vec.Z * vec.Z + vec.W * vec.W); vec.X *= scale; vec.Y *= scale; vec.Z *= scale; vec.W *= scale; return vec; } /// <summary> /// Scale a vector to approximately unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void NormalizeFast(ref Vector4d vec, out Vector4d result) { double scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y + vec.Z * vec.Z + vec.W * vec.W); result.X = vec.X * scale; result.Y = vec.Y * scale; result.Z = vec.Z * scale; result.W = vec.W * scale; } #endregion #region Dot /// <summary> /// Calculate the dot product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The dot product of the two inputs</returns> public static double Dot(Vector4d left, Vector4d right) { return left.X * right.X + left.Y * right.Y + left.Z * right.Z + left.W * right.W; } /// <summary> /// Calculate the dot product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <param name="result">The dot product of the two inputs</param> public static void Dot(ref Vector4d left, ref Vector4d right, out double result) { result = left.X * right.X + left.Y * right.Y + left.Z * right.Z + left.W * right.W; } #endregion #region Lerp /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns> public static Vector4d Lerp(Vector4d a, Vector4d b, double blend) { a.X = blend * (b.X - a.X) + a.X; a.Y = blend * (b.Y - a.Y) + a.Y; a.Z = blend * (b.Z - a.Z) + a.Z; a.W = blend * (b.W - a.W) + a.W; return a; } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param> public static void Lerp(ref Vector4d a, ref Vector4d b, double blend, out Vector4d result) { result.X = blend * (b.X - a.X) + a.X; result.Y = blend * (b.Y - a.Y) + a.Y; result.Z = blend * (b.Z - a.Z) + a.Z; result.W = blend * (b.W - a.W) + a.W; } #endregion #region Barycentric /// <summary> /// Interpolate 3 Vectors using Barycentric coordinates /// </summary> /// <param name="a">First input Vector</param> /// <param name="b">Second input Vector</param> /// <param name="c">Third input Vector</param> /// <param name="u">First Barycentric Coordinate</param> /// <param name="v">Second Barycentric Coordinate</param> /// <returns>a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</returns> public static Vector4d BaryCentric(Vector4d a, Vector4d b, Vector4d c, double u, double v) { return a + u * (b - a) + v * (c - a); } /// <summary>Interpolate 3 Vectors using Barycentric coordinates</summary> /// <param name="a">First input Vector.</param> /// <param name="b">Second input Vector.</param> /// <param name="c">Third input Vector.</param> /// <param name="u">First Barycentric Coordinate.</param> /// <param name="v">Second Barycentric Coordinate.</param> /// <param name="result">Output Vector. a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</param> public static void BaryCentric(ref Vector4d a, ref Vector4d b, ref Vector4d c, double u, double v, out Vector4d result) { result = a; // copy Vector4d temp = b; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, u, out temp); Add(ref result, ref temp, out result); temp = c; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, v, out temp); Add(ref result, ref temp, out result); } #endregion #region Transform /// <summary>Transform a Vector by the given Matrix</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed vector</returns> public static Vector4d Transform(Vector4d vec, Matrix4d mat) { Vector4d result; Transform(ref vec, ref mat, out result); return result; } /// <summary>Transform a Vector by the given Matrix</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed vector</param> public static void Transform(ref Vector4d vec, ref Matrix4d mat, out Vector4d result) { result = new Vector4d( vec.X * mat.Row0.X + vec.Y * mat.Row1.X + vec.Z * mat.Row2.X + vec.W * mat.Row3.X, vec.X * mat.Row0.Y + vec.Y * mat.Row1.Y + vec.Z * mat.Row2.Y + vec.W * mat.Row3.Y, vec.X * mat.Row0.Z + vec.Y * mat.Row1.Z + vec.Z * mat.Row2.Z + vec.W * mat.Row3.Z, vec.X * mat.Row0.W + vec.Y * mat.Row1.W + vec.Z * mat.Row2.W + vec.W * mat.Row3.W); } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <returns>The result of the operation.</returns> public static Vector4d Transform(Vector4d vec, Quaterniond quat) { Vector4d result; Transform(ref vec, ref quat, out result); return result; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <param name="result">The result of the operation.</param> public static void Transform(ref Vector4d vec, ref Quaterniond quat, out Vector4d result) { Quaterniond v = new Quaterniond(vec.X, vec.Y, vec.Z, vec.W), i, t; Quaterniond.Invert(ref quat, out i); Quaterniond.Multiply(ref quat, ref v, out t); Quaterniond.Multiply(ref t, ref i, out v); result = new Vector4d(v.X, v.Y, v.Z, v.W); } #endregion #endregion #region Swizzle /// <summary> /// Gets or sets an OpenTK.Vector2d with the X and Y components of this instance. /// </summary> [XmlIgnore] public Vector2d Xy { get { return new Vector2d(X, Y); } set { X = value.X; Y = value.Y; } } /// <summary> /// Gets or sets an OpenTK.Vector3d with the X, Y and Z components of this instance. /// </summary> [XmlIgnore] public Vector3d Xyz { get { return new Vector3d(X, Y, Z); } set { X = value.X; Y = value.Y; Z = value.Z; } } #endregion #region Operators /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Vector4d operator +(Vector4d left, Vector4d right) { left.X += right.X; left.Y += right.Y; left.Z += right.Z; left.W += right.W; return left; } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Vector4d operator -(Vector4d left, Vector4d right) { left.X -= right.X; left.Y -= right.Y; left.Z -= right.Z; left.W -= right.W; return left; } /// <summary> /// Negates an instance. /// </summary> /// <param name="vec">The instance.</param> /// <returns>The result of the calculation.</returns> public static Vector4d operator -(Vector4d vec) { vec.X = -vec.X; vec.Y = -vec.Y; vec.Z = -vec.Z; vec.W = -vec.W; return vec; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector4d operator *(Vector4d vec, double scale) { vec.X *= scale; vec.Y *= scale; vec.Z *= scale; vec.W *= scale; return vec; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="scale">The scalar.</param> /// <param name="vec">The instance.</param> /// <returns>The result of the calculation.</returns> public static Vector4d operator *(double scale, Vector4d vec) { vec.X *= scale; vec.Y *= scale; vec.Z *= scale; vec.W *= scale; return vec; } /// <summary> /// Divides an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector4d operator /(Vector4d vec, double scale) { double mult = 1 / scale; vec.X *= mult; vec.Y *= mult; vec.Z *= mult; vec.W *= mult; return vec; } /// <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 ==(Vector4d left, Vector4d 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 equa lright; false otherwise.</returns> public static bool operator !=(Vector4d left, Vector4d right) { return !left.Equals(right); } /// <summary> /// Returns a pointer to the first element of the specified instance. /// </summary> /// <param name="v">The instance.</param> /// <returns>A pointer to the first element of v.</returns> [CLSCompliant(false)] unsafe public static explicit operator double*(Vector4d v) { return &v.X; } /// <summary> /// Returns a pointer to the first element of the specified instance. /// </summary> /// <param name="v">The instance.</param> /// <returns>A pointer to the first element of v.</returns> public static explicit operator IntPtr(Vector4d v) { unsafe { return (IntPtr)(&v.X); } } /// <summary>Converts OpenTK.Vector4 to OpenTK.Vector4d.</summary> /// <param name="v4">The Vector4 to convert.</param> /// <returns>The resulting Vector4d.</returns> public static explicit operator Vector4d(Vector4 v4) { return new Vector4d(v4.X, v4.Y, v4.Z, v4.W); } /// <summary>Converts OpenTK.Vector4d to OpenTK.Vector4.</summary> /// <param name="v4d">The Vector4d to convert.</param> /// <returns>The resulting Vector4.</returns> public static explicit operator Vector4(Vector4d v4d) { return new Vector4((float)v4d.X, (float)v4d.Y, (float)v4d.Z, (float)v4d.W); } #endregion #region Overrides #region public override string ToString() /// <summary> /// Returns a System.String that represents the current Vector4d. /// </summary> /// <returns></returns> public override string ToString() { return String.Format("({0}, {1}, {2}, {3})", X, Y, Z, W); } #endregion #region public override int GetHashCode() /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode() ^ W.GetHashCode(); } #endregion #region public override bool Equals(object obj) /// <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 Vector4d)) return false; return this.Equals((Vector4d)obj); } #endregion #endregion #endregion #region IEquatable<Vector4d> Members /// <summary>Indicates whether the current vector is equal to another vector.</summary> /// <param name="other">A vector to compare with this vector.</param> /// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns> public bool Equals(Vector4d other) { return X == other.X && Y == other.Y && Z == other.Z && W == other.W; } #endregion } }
35.108766
146
0.509109
[ "MIT" ]
tksuoran/renderstack_net
technologies/opentk/Source/OpenTK/Math/Vector4d.cs
43,254
C#
using System; using System.Collections.Generic; using System.Windows; using Caliburn.Micro; using Paint101.Desktop.ViewModels; namespace Paint101.Desktop { /// <summary> /// Caliburn bootstrapper for application /// </summary> public class AppBootstrapper : BootstrapperBase { private SimpleContainer _container; public AppBootstrapper() { Initialize(); } protected override void Configure() { NlogHelper.Configure(); _container = new SimpleContainer(); _container.Singleton<IWindowManager, WindowManager>(); _container.PerRequest<ShellViewModel>(); } protected override void OnStartup(object sender, StartupEventArgs e) { DisplayRootViewFor<ShellViewModel>(); } protected override object GetInstance(Type service, string key) { return _container.GetInstance(service, key); } protected override IEnumerable<object> GetAllInstances(Type service) { return _container.GetAllInstances(service); } protected override void BuildUp(object instance) { _container.BuildUp(instance); } } }
23.218182
76
0.616288
[ "MIT" ]
kinpa200296/Paint101
Paint101/Paint101.Desktop/AppBootstrapper.cs
1,279
C#
// Copyright 2017-2020 Elringus (Artyom Sovetnikov). All Rights Reserved. using System; using UnityEngine; namespace Naninovel { /// <summary> /// Allows detecting touch swipes by sampling user input. /// </summary> [Serializable] public class InputSwipeTrigger { [Tooltip("Swipe of which direction should be registered.")] public InputSwipeDirection Direction = default; [Tooltip("How much fingers (touches) should be active to register the swipe."), Range(1, 5)] public int FingerCount = 1; [Tooltip("Minimum required swipe speed to activate the trigger, in screen factor per second.")] public float MinimumSpeed = 2f; /// <summary> /// Returns whether the swipe is currently registered. /// </summary> public bool Sample () { #if ENABLE_LEGACY_INPUT_MANAGER if (Input.touchCount != FingerCount) return false; for (int i = 0; i < Input.touchCount; i++) { var touch = Input.GetTouch(i); var speed = new Vector2(touch.deltaPosition.x / Screen.width, touch.deltaPosition.y / Screen.height) / touch.deltaTime; if (Mathf.Abs(touch.deltaPosition.x) > Mathf.Abs(touch.deltaPosition.y)) { if (Direction == InputSwipeDirection.Left && speed.x <= -MinimumSpeed) return true; if (Direction == InputSwipeDirection.Right && speed.x >= MinimumSpeed) return true; } else { if (Direction == InputSwipeDirection.Up && speed.y >= MinimumSpeed) return true; if (Direction == InputSwipeDirection.Down && speed.y <= -MinimumSpeed) return true; } } #endif return false; } } }
39.285714
136
0.561558
[ "MIT" ]
286studio/Sim286
AVG/Assets/Naninovel/Runtime/Input/InputSwipeTrigger.cs
1,927
C#
using System; using System.Linq; using System.Linq.Expressions; namespace NPoco.FluentMappings { public class Map<T> : IMap { private readonly TypeDefinition _petaPocoTypeDefinition; public Map() : this(new TypeDefinition(typeof(T))) { } public Map(TypeDefinition petaPocoTypeDefinition) { _petaPocoTypeDefinition = petaPocoTypeDefinition; } public void UseMap<TMap>() where TMap : IMap { Activator.CreateInstance(typeof (TMap), _petaPocoTypeDefinition); var keys = _petaPocoTypeDefinition.ColumnConfiguration.Select(x => x.Key).ToList(); var fieldsAndPropertiesForClasses = ReflectionUtils.GetFieldsAndPropertiesForClasses(typeof(T)); foreach (var key in keys.Where(key => fieldsAndPropertiesForClasses.All(x => x.Name != key))) { _petaPocoTypeDefinition.ColumnConfiguration.Remove(key); } } public Map<T> TableName(string tableName) { _petaPocoTypeDefinition.TableName = tableName; return this; } public Map<T> Columns(Action<ColumnConfigurationBuilder<T>> columnConfiguration) { return Columns(columnConfiguration, null); } public Map<T> Columns(Action<ColumnConfigurationBuilder<T>> columnConfiguration, bool? explicitColumns) { _petaPocoTypeDefinition.ExplicitColumns = explicitColumns; columnConfiguration(new ColumnConfigurationBuilder<T>(_petaPocoTypeDefinition.ColumnConfiguration)); return this; } public Map<T> PrimaryKey(Expression<Func<T, object>> column, string sequenceName) { var propertyInfo = PropertyHelper<T>.GetProperty(column); return PrimaryKey(propertyInfo.Name, sequenceName); } public Map<T> PrimaryKey(Expression<Func<T, object>> column) { _petaPocoTypeDefinition.AutoIncrement = true; return PrimaryKey(column, null); } public Map<T> PrimaryKey(Expression<Func<T, object>> column, bool autoIncrement) { var propertyInfo = PropertyHelper<T>.GetProperty(column); return PrimaryKey(propertyInfo.Name, autoIncrement); } public Map<T> CompositePrimaryKey(params Expression<Func<T, object>>[] columns) { var columnNames = new string[columns.Length]; for (int i = 0; i < columns.Length; i++) { columnNames[i] = PropertyHelper<T>.GetProperty(columns[i]).Name; } _petaPocoTypeDefinition.PrimaryKey = string.Join(",", columnNames); return this; } public Map<T> PrimaryKey(string primaryKeyColumn, bool autoIncrement) { _petaPocoTypeDefinition.PrimaryKey = primaryKeyColumn; _petaPocoTypeDefinition.AutoIncrement = autoIncrement; return this; } public Map<T> PrimaryKey(string primaryKeyColumn, string sequenceName) { _petaPocoTypeDefinition.PrimaryKey = primaryKeyColumn; _petaPocoTypeDefinition.SequenceName = sequenceName; return this; } public Map<T> PrimaryKey(string primaryKeyColumn) { return PrimaryKey(primaryKeyColumn, null); } TypeDefinition IMap.TypeDefinition { get { return _petaPocoTypeDefinition; } } } }
33.819048
112
0.621233
[ "Apache-2.0" ]
asterd/NPoco.iSeries
NPoco/FluentMappings/Map.cs
3,551
C#
namespace Trifolia.DB { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("role")] public partial class Role { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Role() { AppSecurables = new HashSet<RoleAppSecurable>(); Restrictions = new HashSet<RoleRestriction>(); Users = new HashSet<UserRole>(); } [Column("id")] public int Id { get; set; } [Column("name")] [StringLength(50)] public string Name { get; set; } [Column("isDefault")] public bool IsDefault { get; set; } [Column("isAdmin")] public bool IsAdmin { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<RoleAppSecurable> AppSecurables { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<RoleRestriction> Restrictions { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<UserRole> Users { get; set; } } }
35.44186
128
0.671916
[ "Apache-2.0" ]
lantanagroup/trifolia
Trifolia.DB/Model/role.cs
1,524
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// VMwareCbt specific update migration item input. /// </summary> [Newtonsoft.Json.JsonObject("VMwareCbt")] public partial class VMwareCbtUpdateMigrationItemInput : UpdateMigrationItemProviderSpecificInput { /// <summary> /// Initializes a new instance of the VMwareCbtUpdateMigrationItemInput /// class. /// </summary> public VMwareCbtUpdateMigrationItemInput() { CustomInit(); } /// <summary> /// Initializes a new instance of the VMwareCbtUpdateMigrationItemInput /// class. /// </summary> /// <param name="targetVmName">The target VM name.</param> /// <param name="targetVmSize">The target VM size.</param> /// <param name="targetResourceGroupId">The target resource group ARM /// Id.</param> /// <param name="targetAvailabilitySetId">The target availability set /// ARM Id.</param> /// <param name="targetAvailabilityZone">The target availability /// zone.</param> /// <param name="targetProximityPlacementGroupId">The target proximity /// placement group ARM Id.</param> /// <param name="targetBootDiagnosticsStorageAccountId">The target boot /// diagnostics storage account ARM Id.</param> /// <param name="targetNetworkId">The target network ARM Id.</param> /// <param name="vmNics">The list of NIC details.</param> /// <param name="vmDisks">The list of disk update properties.</param> /// <param name="licenseType">The license type. Possible values /// include: 'NotSpecified', 'NoLicenseType', 'WindowsServer'</param> /// <param name="sqlServerLicenseType">The SQL Server license type. /// Possible values include: 'NotSpecified', 'NoLicenseType', 'PAYG', /// 'AHUB'</param> /// <param name="performAutoResync">A value indicating whether auto /// resync is to be done.</param> /// <param name="targetVmTags">The target VM tags.</param> /// <param name="targetDiskTags">The tags for the target disks.</param> /// <param name="targetNicTags">The tags for the target NICs.</param> public VMwareCbtUpdateMigrationItemInput(string targetVmName = default(string), string targetVmSize = default(string), string targetResourceGroupId = default(string), string targetAvailabilitySetId = default(string), string targetAvailabilityZone = default(string), string targetProximityPlacementGroupId = default(string), string targetBootDiagnosticsStorageAccountId = default(string), string targetNetworkId = default(string), IList<VMwareCbtNicInput> vmNics = default(IList<VMwareCbtNicInput>), IList<VMwareCbtUpdateDiskInput> vmDisks = default(IList<VMwareCbtUpdateDiskInput>), string licenseType = default(string), string sqlServerLicenseType = default(string), string performAutoResync = default(string), IDictionary<string, string> targetVmTags = default(IDictionary<string, string>), IDictionary<string, string> targetDiskTags = default(IDictionary<string, string>), IDictionary<string, string> targetNicTags = default(IDictionary<string, string>)) { TargetVmName = targetVmName; TargetVmSize = targetVmSize; TargetResourceGroupId = targetResourceGroupId; TargetAvailabilitySetId = targetAvailabilitySetId; TargetAvailabilityZone = targetAvailabilityZone; TargetProximityPlacementGroupId = targetProximityPlacementGroupId; TargetBootDiagnosticsStorageAccountId = targetBootDiagnosticsStorageAccountId; TargetNetworkId = targetNetworkId; VmNics = vmNics; VmDisks = vmDisks; LicenseType = licenseType; SqlServerLicenseType = sqlServerLicenseType; PerformAutoResync = performAutoResync; TargetVmTags = targetVmTags; TargetDiskTags = targetDiskTags; TargetNicTags = targetNicTags; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the target VM name. /// </summary> [JsonProperty(PropertyName = "targetVmName")] public string TargetVmName { get; set; } /// <summary> /// Gets or sets the target VM size. /// </summary> [JsonProperty(PropertyName = "targetVmSize")] public string TargetVmSize { get; set; } /// <summary> /// Gets or sets the target resource group ARM Id. /// </summary> [JsonProperty(PropertyName = "targetResourceGroupId")] public string TargetResourceGroupId { get; set; } /// <summary> /// Gets or sets the target availability set ARM Id. /// </summary> [JsonProperty(PropertyName = "targetAvailabilitySetId")] public string TargetAvailabilitySetId { get; set; } /// <summary> /// Gets or sets the target availability zone. /// </summary> [JsonProperty(PropertyName = "targetAvailabilityZone")] public string TargetAvailabilityZone { get; set; } /// <summary> /// Gets or sets the target proximity placement group ARM Id. /// </summary> [JsonProperty(PropertyName = "targetProximityPlacementGroupId")] public string TargetProximityPlacementGroupId { get; set; } /// <summary> /// Gets or sets the target boot diagnostics storage account ARM Id. /// </summary> [JsonProperty(PropertyName = "targetBootDiagnosticsStorageAccountId")] public string TargetBootDiagnosticsStorageAccountId { get; set; } /// <summary> /// Gets or sets the target network ARM Id. /// </summary> [JsonProperty(PropertyName = "targetNetworkId")] public string TargetNetworkId { get; set; } /// <summary> /// Gets or sets the list of NIC details. /// </summary> [JsonProperty(PropertyName = "vmNics")] public IList<VMwareCbtNicInput> VmNics { get; set; } /// <summary> /// Gets or sets the list of disk update properties. /// </summary> [JsonProperty(PropertyName = "vmDisks")] public IList<VMwareCbtUpdateDiskInput> VmDisks { get; set; } /// <summary> /// Gets or sets the license type. Possible values include: /// 'NotSpecified', 'NoLicenseType', 'WindowsServer' /// </summary> [JsonProperty(PropertyName = "licenseType")] public string LicenseType { get; set; } /// <summary> /// Gets or sets the SQL Server license type. Possible values include: /// 'NotSpecified', 'NoLicenseType', 'PAYG', 'AHUB' /// </summary> [JsonProperty(PropertyName = "sqlServerLicenseType")] public string SqlServerLicenseType { get; set; } /// <summary> /// Gets or sets a value indicating whether auto resync is to be done. /// </summary> [JsonProperty(PropertyName = "performAutoResync")] public string PerformAutoResync { get; set; } /// <summary> /// Gets or sets the target VM tags. /// </summary> [JsonProperty(PropertyName = "targetVmTags")] public IDictionary<string, string> TargetVmTags { get; set; } /// <summary> /// Gets or sets the tags for the target disks. /// </summary> [JsonProperty(PropertyName = "targetDiskTags")] public IDictionary<string, string> TargetDiskTags { get; set; } /// <summary> /// Gets or sets the tags for the target NICs. /// </summary> [JsonProperty(PropertyName = "targetNicTags")] public IDictionary<string, string> TargetNicTags { get; set; } } }
45.303191
965
0.643067
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/recoveryservices-siterecovery/Microsoft.Azure.Management.RecoveryServices.SiteRecovery/src/Generated/Models/VMwareCbtUpdateMigrationItemInput.cs
8,517
C#
//From https://github.com/LogosBible/Logos.Utility/blob/master/src/Logos.Utility/GuidUtility.cs#L16 //Modified by removing the built in guids this class had. using System; using System.Security.Cryptography; using System.Text; namespace Logos.Utility { /// <summary> /// Helper methods for working with <see cref="Guid"/>. /// </summary> /// <example> /// Guid guid = GuidUtility.Create(GuidUtility.DnsNamespace, "code.logos.com"); /// </example> public static class GuidUtility { /// <summary> /// Creates a name-based UUID using the algorithm from RFC 4122 §4.3. /// </summary> /// <param name="namespaceId">The ID of the namespace.</param> /// <param name="name">The name (within that namespace).</param> /// <returns>A UUID derived from the namespace and name.</returns> /// <remarks>See <a href="http://code.logos.com/blog/2011/04/generating_a_deterministic_guid.html">Generating a deterministic GUID</a>.</remarks> public static Guid Create(Guid namespaceId, string name) { return Create(namespaceId, name, 5); } /// <summary> /// Creates a name-based UUID using the algorithm from RFC 4122 §4.3. /// </summary> /// <param name="namespaceId">The ID of the namespace.</param> /// <param name="name">The name (within that namespace).</param> /// <param name="version">The version number of the UUID to create; this value must be either /// 3 (for MD5 hashing) or 5 (for SHA-1 hashing).</param> /// <returns>A UUID derived from the namespace and name.</returns> /// <remarks>See <a href="http://code.logos.com/blog/2011/04/generating_a_deterministic_guid.html">Generating a deterministic GUID</a>.</remarks> public static Guid Create(Guid namespaceId, string name, int version) { if (name == null) throw new ArgumentNullException("name"); if (version != 3 && version != 5) throw new ArgumentOutOfRangeException("version", "version must be either 3 or 5."); // convert the name to a sequence of octets (as defined by the standard or conventions of its namespace) (step 3) // ASSUME: UTF-8 encoding is always appropriate byte[] nameBytes = Encoding.UTF8.GetBytes(name); // convert the namespace UUID to network order (step 3) byte[] namespaceBytes = namespaceId.ToByteArray(); SwapByteOrder(namespaceBytes); // comput the hash of the name space ID concatenated with the name (step 4) byte[] hash; using (HashAlgorithm algorithm = version == 3 ? (HashAlgorithm)MD5.Create() : SHA1.Create()) { algorithm.TransformBlock(namespaceBytes, 0, namespaceBytes.Length, null, 0); algorithm.TransformFinalBlock(nameBytes, 0, nameBytes.Length); hash = algorithm.Hash; } // most bytes from the hash are copied straight to the bytes of the new GUID (steps 5-7, 9, 11-12) byte[] newGuid = new byte[16]; Array.Copy(hash, 0, newGuid, 0, 16); // set the four most significant bits (bits 12 through 15) of the time_hi_and_version field to the appropriate 4-bit version number from Section 4.1.3 (step 8) newGuid[6] = (byte)((newGuid[6] & 0x0F) | (version << 4)); // set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively (step 10) newGuid[8] = (byte)((newGuid[8] & 0x3F) | 0x80); // convert the resulting UUID to local byte order (step 13) SwapByteOrder(newGuid); return new Guid(newGuid); } // Converts a GUID (expressed as a byte array) to/from network order (MSB-first). internal static void SwapByteOrder(byte[] guid) { SwapBytes(guid, 0, 3); SwapBytes(guid, 1, 2); SwapBytes(guid, 4, 5); SwapBytes(guid, 6, 7); } private static void SwapBytes(byte[] guid, int left, int right) { byte temp = guid[left]; guid[left] = guid[right]; guid[right] = temp; } } }
46.06383
171
0.605312
[ "MIT" ]
threax/Threax.IdServer
Threax.IdServer/Services/GuidServices/GuidUtility.cs
4,334
C#
using SharpPulsar.Extension; using SharpPulsar.Interfaces.ISchema; using SharpPulsar.Shared; using System; /// <summary> /// 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> namespace SharpPulsar.Schemas { /// <summary> /// A schema for `java.util.Date` or `java.sql.Date`. /// </summary> public class DateSchema : AbstractSchema<DateTime> { private static readonly DateSchema _instance; private static readonly ISchemaInfo _schemaInfo; static DateSchema() { var info = new SchemaInfo { Name = "Date", Type = SchemaType.DATE, Schema = new byte[0] }; _schemaInfo = info; _instance = new DateSchema(); } public static DateSchema Of() { return _instance; } public override byte[] Encode(DateTime message) { long date = message.ConvertToMsTimestamp().LongToBigEndian(); return BitConverter.GetBytes(date); } public override DateTime Decode(byte[] bytes) { var decode = BitConverter.ToInt64(bytes, 0).LongFromBigEndian(); return decode.ConvertToDateTime(); } public override ISchemaInfo SchemaInfo { get { return _schemaInfo; } } } }
26.364865
67
0.695541
[ "Apache-2.0" ]
eaba/SharpPulsar
SharpPulsar/Schemas/DateSchema.cs
1,953
C#
using System; using System.Diagnostics; using System.Net; using System.Text; using System.Threading; using System.Web; using System.Windows; using System.Xml; namespace ScriptPlayer.Shared { public class VlcTimeSource : TimeSource, IDisposable { private VlcConnectionSettings _connectionSettings; public event EventHandler<string> FileOpened; private readonly Thread _clientLoop; private readonly ManualTimeSource _timeSource; private bool _running = true; private VlcStatus _previousStatus; public VlcTimeSource(ISampleClock clock, VlcConnectionSettings connectionSettings) { _connectionSettings = connectionSettings; _previousStatus = new VlcStatus{IsValid = false}; _timeSource = new ManualTimeSource(clock, TimeSpan.FromMilliseconds(200)); _timeSource.DurationChanged += TimeSourceOnDurationChanged; _timeSource.IsPlayingChanged += TimeSourceOnIsPlayingChanged; _timeSource.ProgressChanged += TimeSourceOnProgressChanged; _timeSource.PlaybackRateChanged += TimeSourceOnPlaybackRateChanged; _clientLoop = new Thread(ClientLoop); _clientLoop.Start(); } private void TimeSourceOnPlaybackRateChanged(object sender, double d) { OnPlaybackRateChanged(d); } public void UpdateConnectionSettings(VlcConnectionSettings connectionSettings) { _connectionSettings = connectionSettings; } private void TimeSourceOnProgressChanged(object sender, TimeSpan progress) { Progress = progress; } private void TimeSourceOnDurationChanged(object sender, TimeSpan duration) { Duration = duration; } private void TimeSourceOnIsPlayingChanged(object sender, bool isPlaying) { IsPlaying = isPlaying; } private void ClientLoop() { while (_running) { try { while (_running) { string status = Request("status.xml"); if (string.IsNullOrWhiteSpace(status)) { SetConnected(false); } else { InterpretStatus(status); SetConnected(true); } } } catch (ThreadAbortException) { return; } catch (ThreadInterruptedException) { return; } catch (Exception e) { Debug.WriteLine(e.Message); } finally { SetConnected(false); } } } private void SetConnected(bool isConnected) { if (CheckAccess()) IsConnected = isConnected; else Dispatcher.Invoke(() => { SetConnected(isConnected); }); } private void InterpretStatus(string statusXml) { if (!_timeSource.CheckAccess()) { _timeSource.Dispatcher.Invoke(() => InterpretStatus(statusXml)); return; } try { VlcStatus newStatus = new VlcStatus(statusXml); if (newStatus.IsValid) { if (!_previousStatus.IsValid || _previousStatus.Filename != newStatus.Filename) { FindFullFilename(newStatus.Filename); } if (!_previousStatus.IsValid || _previousStatus.PlaybackState != newStatus.PlaybackState) { if (newStatus.PlaybackState == VlcPlaybackState.Playing) _timeSource.Play(); else _timeSource.Pause(); } if (!_previousStatus.IsValid || _previousStatus.Duration != newStatus.Duration) { _timeSource.SetDuration(newStatus.Duration); } if (!_previousStatus.IsValid || _previousStatus.Progress != newStatus.Progress) { _timeSource.SetPosition(newStatus.Progress); } } _previousStatus = newStatus; } catch (Exception exception) { Debug.WriteLine("Couldn't interpret VLC Status: " + exception.Message); } } private void FindFullFilename(string newStatusFilename) { string playlist = Request("playlist.xml"); if (String.IsNullOrWhiteSpace(playlist)) return; string filename = FindFileByName(playlist, newStatusFilename); if(!String.IsNullOrWhiteSpace(filename)) OnFileOpened(filename); } public string Request(string filename) { try { var client = new WebClient(); string userName = ""; string password = _connectionSettings.Password; string baseUrl = $"http://{_connectionSettings.IpAndPort}"; //string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + password)); string credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(userName + ":" + password)); client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}"; return client.DownloadString(new Uri($"{baseUrl}/requests/{filename}")); } catch { return null; } } private string FindFileByName(string playlist, string newStatusFilename) { XmlDocument document = new XmlDocument(); document.LoadXml(playlist); XmlNodeList nodes = document.SelectNodes("//leaf"); if (nodes == null) return null; string encodedFilename = null; foreach (XmlNode node in nodes) { if (node.Attributes == null) continue; if (node.Attributes["name"]?.InnerText != newStatusFilename) continue; encodedFilename = node.Attributes["uri"]?.InnerText; break; } if (string.IsNullOrWhiteSpace(encodedFilename)) return null; if (encodedFilename.StartsWith("file:///")) encodedFilename = encodedFilename.Substring("file:///".Length); encodedFilename = HttpUtility.UrlDecode(encodedFilename); return encodedFilename; } public override void Play() { Request("status.xml?command=pl_forceresume"); } public override void Pause() { Request("status.xml?command=pl_forcepause"); } public override void SetPosition(TimeSpan position) { Request("status.xml?command=seek&val=" + (int) position.TotalSeconds); } public void SetDuration(TimeSpan duration) { _timeSource.SetDuration(duration); } protected virtual void OnFileOpened(string e) { FileOpened?.Invoke(this, e); } public void Dispose() { _running = false; _clientLoop?.Interrupt(); _clientLoop?.Abort(); } public override double PlaybackRate { get => _timeSource.PlaybackRate; set => _timeSource.PlaybackRate = value; } public override bool CanPlayPause => true; public override bool CanSeek => true; public override bool CanOpenMedia => false; } }
31.150943
114
0.522108
[ "BSD-3-Clause" ]
hotcoconuts/ScriptPlayer
ScriptPlayer/ScriptPlayer.Shared/TimeSource/VlcTimeSource.cs
8,257
C#
// <copyright file="AirSpeed.cs" company="Mark Lauter"> // Copyright (c) Mark Lauter. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> using System; namespace Tello.State { internal sealed class AirSpeed : IAirSpeed { public AirSpeed(IAirSpeed airspeed) { if (airspeed == null) { throw new ArgumentNullException(nameof(airspeed)); } this.AccelerationX = airspeed.AccelerationX; this.AccelerationY = airspeed.AccelerationY; this.AccelerationZ = airspeed.AccelerationZ; this.SpeedX = airspeed.SpeedX; this.SpeedY = airspeed.SpeedY; this.SpeedZ = airspeed.SpeedZ; this.Timestamp = airspeed.Timestamp; } public AirSpeed(ITelloState state) { if (state == null) { throw new ArgumentNullException(nameof(state)); } this.AccelerationX = state.AccelerationX; this.AccelerationY = state.AccelerationY; this.AccelerationZ = state.AccelerationZ; this.SpeedX = state.SpeedX; this.SpeedY = state.SpeedY; this.SpeedZ = state.SpeedZ; this.Timestamp = state.Timestamp; } public int SpeedX { get; } public int SpeedY { get; } public int SpeedZ { get; } public double AccelerationX { get; } public double AccelerationY { get; } public double AccelerationZ { get; } public DateTime Timestamp { get; } public override string ToString() { return $"X: {this.SpeedX} cm/s, Y: {this.SpeedY} cm/s, Z: {this.SpeedZ} cm/s, AX: {this.AccelerationX} cm/s/s, , AY: {this.AccelerationY} cm/s/s, , AZ: {this.AccelerationZ} cm/s/s"; } } }
30.203125
193
0.580445
[ "MIT" ]
marklauter/TelloAPI
src/Tello/State/AirSpeed.cs
1,935
C#
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; namespace MOE.Common.Models { [DataContract] public class VersionAction { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] [DataMember] public int ID { get; set; } [DataMember] public string Description { get; set; } } }
23.722222
57
0.679157
[ "Apache-2.0" ]
AndreRSanchez/ATSPM
MOE.Common/Models/VersionAction.cs
429
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V3109</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V3109 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="PORX_MT024003UK06.SuppliedMaterial", Namespace="urn:hl7-org:v3")] [System.Xml.Serialization.XmlRootAttribute("PORX_MT024003UK06.SuppliedMaterial", Namespace="urn:hl7-org:v3")] public partial class PORX_MT024003UK06SuppliedMaterial { private CE codeField; private string typeField; private string classCodeField; private string determinerCodeField; private string[] typeIDField; private string[] realmCodeField; private string nullFlavorField; private static System.Xml.Serialization.XmlSerializer serializer; public PORX_MT024003UK06SuppliedMaterial() { this.typeField = "ManufacturedMaterial"; this.classCodeField = "MMAT"; this.determinerCodeField = "INSTANCE"; } public CE code { get { return this.codeField; } set { this.codeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string type { get { return this.typeField; } set { this.typeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string classCode { get { return this.classCodeField; } set { this.classCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string determinerCode { get { return this.determinerCodeField; } set { this.determinerCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string[] typeID { get { return this.typeIDField; } set { this.typeIDField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string[] realmCode { get { return this.realmCodeField; } set { this.realmCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string nullFlavor { get { return this.nullFlavorField; } set { this.nullFlavorField = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(PORX_MT024003UK06SuppliedMaterial)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current PORX_MT024003UK06SuppliedMaterial object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an PORX_MT024003UK06SuppliedMaterial object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output PORX_MT024003UK06SuppliedMaterial object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out PORX_MT024003UK06SuppliedMaterial obj, out System.Exception exception) { exception = null; obj = default(PORX_MT024003UK06SuppliedMaterial); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out PORX_MT024003UK06SuppliedMaterial obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static PORX_MT024003UK06SuppliedMaterial Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((PORX_MT024003UK06SuppliedMaterial)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current PORX_MT024003UK06SuppliedMaterial object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an PORX_MT024003UK06SuppliedMaterial object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output PORX_MT024003UK06SuppliedMaterial object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out PORX_MT024003UK06SuppliedMaterial obj, out System.Exception exception) { exception = null; obj = default(PORX_MT024003UK06SuppliedMaterial); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out PORX_MT024003UK06SuppliedMaterial obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static PORX_MT024003UK06SuppliedMaterial LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this PORX_MT024003UK06SuppliedMaterial object /// </summary> public virtual PORX_MT024003UK06SuppliedMaterial Clone() { return ((PORX_MT024003UK06SuppliedMaterial)(this.MemberwiseClone())); } #endregion } }
41.150538
1,358
0.575298
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V3109/Generated/PORX_MT024003UK06SuppliedMaterial.cs
11,481
C#
using System; using System.Collections.Generic; using System.Linq; using System.Drawing; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.CoreVideo; using MonoMac.OpenGL; namespace GLFullScreen { public partial class MyOpenGLView : MonoMac.AppKit.NSView { NSOpenGLContext openGLContext; NSOpenGLPixelFormat pixelFormat; MainWindowController controller; CVDisplayLink displayLink; NSObject notificationProxy; [Export("initWithFrame:")] public MyOpenGLView (RectangleF frame) : this(frame, null) { } public MyOpenGLView (RectangleF frame, NSOpenGLContext context) : base(frame) { var attribs = new object [] { NSOpenGLPixelFormatAttribute.Accelerated, NSOpenGLPixelFormatAttribute.NoRecovery, NSOpenGLPixelFormatAttribute.DoubleBuffer, NSOpenGLPixelFormatAttribute.ColorSize, 24, NSOpenGLPixelFormatAttribute.DepthSize, 16 }; pixelFormat = new NSOpenGLPixelFormat (attribs); if (pixelFormat == null) Console.WriteLine ("No OpenGL pixel format"); // NSOpenGLView does not handle context sharing, so we draw to a custom NSView instead openGLContext = new NSOpenGLContext (pixelFormat, context); openGLContext.MakeCurrentContext (); // Synchronize buffer swaps with vertical refresh rate openGLContext.SwapInterval = true; SetupDisplayLink(); // Look for changes in view size // Note, -reshape will not be called automatically on size changes because NSView does not export it to override notificationProxy = NSNotificationCenter.DefaultCenter.AddObserver (NSView.NSViewGlobalFrameDidChangeNotification, HandleReshape); } public override void DrawRect (RectangleF dirtyRect) { // Ignore if the display link is still running if (!displayLink.IsRunning && controller != null) DrawView (); } public override bool AcceptsFirstResponder () { // We want this view to be able to receive key events return true; } public override void LockFocus () { base.LockFocus (); if (openGLContext.View != this) openGLContext.View = this; } public override void KeyDown (NSEvent theEvent) { controller.KeyDown (theEvent); } public override void MouseDown (NSEvent theEvent) { controller.MouseDown (theEvent); } private void DrawView () { // This method will be called on both the main thread (through -drawRect:) and a secondary thread (through the display link rendering loop) // Also, when resizing the view, -reshape is called on the main thread, but we may be drawing on a secondary thread // Add a mutex around to avoid the threads accessing the context simultaneously openGLContext.CGLContext.Lock (); // Make sure we draw to the right context openGLContext.MakeCurrentContext (); // Delegate to the scene object for rendering controller.Scene.render (); openGLContext.FlushBuffer (); openGLContext.CGLContext.Unlock (); } private void SetupDisplayLink () { // Create a display link capable of being used with all active displays displayLink = new CVDisplayLink (); // Set the renderer output callback function displayLink.SetOutputCallback (MyDisplayLinkOutputCallback); // Set the display link for the current renderer CGLContext cglContext = openGLContext.CGLContext; CGLPixelFormat cglPixelFormat = PixelFormat.CGLPixelFormat; displayLink.SetCurrentDisplay (cglContext, cglPixelFormat); } public CVReturn MyDisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut) { CVReturn result = GetFrameForTime (inOutputTime); return result; } private CVReturn GetFrameForTime (CVTimeStamp outputTime) { // There is no autorelease pool when this method is called because it will be called from a background thread // It's important to create one or you will leak objects using (NSAutoreleasePool pool = new NSAutoreleasePool ()) { // Update the animation double current = DateTime.Now.TimeOfDay.TotalMilliseconds; controller.Scene.advanceTimeBy ((float)(current - controller.RenderTime)); controller.RenderTime = (float)current; DrawView (); } return CVReturn.Success; } public NSOpenGLContext OpenGLContext { get { return openGLContext; } } public NSOpenGLPixelFormat PixelFormat { get { return pixelFormat; } } public MainWindowController MainController { set { controller = value; } } public void UpdateView () { // This method will be called on the main thread when resizing, but we may be drawing on a secondary thread through the display link // Add a mutex around to avoid the threads accessing the context simultaneously openGLContext.CGLContext.Lock (); // Delegate to the scene object to update for a change in the view size controller.Scene.setViewportRect (Bounds); openGLContext.Update (); openGLContext.CGLContext.Unlock (); } private void HandleReshape (NSNotification note) { UpdateView (); } public void StartAnimation () { if (displayLink != null && !displayLink.IsRunning) displayLink.Start (); } public void StopAnimation () { if (displayLink != null && displayLink.IsRunning) displayLink.Stop (); } // Clean up the notifications public void DeAllocate() { displayLink.Stop(); displayLink.SetOutputCallback(null); NSNotificationCenter.DefaultCenter.RemoveObserver(notificationProxy); } } }
27.845771
177
0.727711
[ "MIT" ]
Devolutions/monomac
samples/GLFullScreen/MyOpenGLView.cs
5,597
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using Microsoft.PowerFx.Core.Errors; using Microsoft.PowerFx.Core.Lexer.Tokens; using Microsoft.PowerFx.Core.Syntax.Nodes; using Microsoft.PowerFx.Core.Syntax.SourceInformation; using Microsoft.PowerFx.Core.Utils; namespace Microsoft.PowerFx.Core.Parser { internal class ParseResult { internal TexlNode Root { get; } internal List<TexlError> Errors { get; } internal bool HasError { get; } internal List<CommentToken> Comments { get; } internal SourceList Before { get; } internal SourceList After { get; } public ParseResult(TexlNode root, List<TexlError> errors, bool hasError, List<CommentToken> comments, SourceList before, SourceList after) { Contracts.AssertValue(root); Contracts.AssertValue(comments); // You can have an empty error list and still have a semi-silent error, but if you have an error in your list there must have been an error. Contracts.Assert(errors != null ? hasError : true); Root = root; Errors = errors; HasError = hasError; Comments = comments; Before = before; After = after; } } }
31.785714
152
0.654682
[ "MIT" ]
ivanradicek/Power-Fx
src/libraries/Microsoft.PowerFx.Core/Parser/ParseResult.cs
1,337
C#
using System.Runtime.Serialization; namespace Structurizr { /// <summary> /// A definition of an element style. /// </summary> [DataContract] public sealed class ElementStyle { /// <summary> /// The tag to which this element style applies. /// </summary> [DataMember(Name="tag", EmitDefaultValue=false)] public string Tag { get; set; } /// <summary> /// The width of the element, in pixels. /// </summary> [DataMember(Name="width", EmitDefaultValue=false)] public int? Width { get; set; } /// <summary> /// The height of the element, in pixels. /// </summary> [DataMember(Name="height", EmitDefaultValue=false)] public int? Height { get; set; } /// <summary> /// The background colour of the element, as a HTML RGB hex string (e.g. /// </summary> [DataMember(Name="background", EmitDefaultValue=false)] public string Background { get; set; } /// <summary> /// The foreground (text) colour of the element, as a HTML RGB hex string (e.g. /// </summary> [DataMember(Name="color", EmitDefaultValue=false)] public string Color { get; set; } /// <summary> /// The standard font size used to render text, in pixels. /// </summary> /// <value>The standard font size used to render text, in pixels.</value> [DataMember(Name="fontSize", EmitDefaultValue=false)] public int? FontSize { get; set; } /// <summary> /// The shape used to render the element. /// </summary> [DataMember(Name="shape", EmitDefaultValue=false)] public Shape Shape { get; set; } /// <summary> /// The border to use when rendering the element. /// </summary> [DataMember(Name="border", EmitDefaultValue=false)] public Border Border { get; set; } private int? _opacity; /// <summary> /// The opacity of the line/text; 0 to 100. /// </summary> [DataMember(Name = "opacity", EmitDefaultValue = false)] public int? Opacity { get { return _opacity; } set { if (value != null) { if (value < 0) { _opacity = 0; } else if (value > 100) { _opacity = 100; } else { _opacity = value; } } } } internal ElementStyle() { } public ElementStyle(string tag) { this.Tag = tag; } } }
28.693069
87
0.477916
[ "Apache-2.0" ]
kurattila/dotnet
Structurizr.Core/View/ElementStyle.cs
2,898
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ResetButton : MonoBehaviour { public Image playImage; public Sprite playSprite; public void Start() { this.gameObject.SetActive(false); } public void Reset() { AudioManager.playSounds = false; this.gameObject.SetActive(false); playImage.sprite = playSprite; GridManager.instance.Reset(); LinkedListNode<Cell> selectedNode = CellFunctions.generatedCellList.First; { Cell cell; while (selectedNode != null) { cell = selectedNode.Value; selectedNode = selectedNode.Next; cell.Delete(true); } } CellFunctions.generatedCellList.Clear(); foreach (Cell cell in CellFunctions.cellList) { cell.Delete(false); } foreach (Cell cell in CellFunctions.cellList) { cell.gameObject.SetActive(true); cell.Setup(cell.spawnPosition, (Direction_e)cell.spawnRotation, false); cell.suppresed = false; } AudioManager.playSounds = true; GridManager.enemyCount = GridManager.initialEnemyCount; } }
25.153846
83
0.600917
[ "Apache-2.0" ]
Dead-Doctor/Cell-Machine-Mystic-Mod
src/Assets/Scripts/UI/Level Scene/ResetButton.cs
1,310
C#
#pragma checksum "..\..\..\..\..\HUD\Assets\UserControls\ItemBar.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "033309168ED0AC0FCC68E44BB33CEAF8D05A0E6377E78BE5B0B0CA08FD6A8C22" //------------------------------------------------------------------------------ // <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.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace HUD { /// <summary> /// ItemBar /// </summary> public partial class ItemBar : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector { #line 19 "..\..\..\..\..\HUD\Assets\UserControls\ItemBar.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Grid LayoutRoot; #line default #line hidden private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/HUD;component/hud/assets/usercontrols/itembar.xaml", System.UriKind.Relative); #line 1 "..\..\..\..\..\HUD\Assets\UserControls\ItemBar.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.LayoutRoot = ((System.Windows.Controls.Grid)(target)); return; } this._contentLoaded = true; } } }
40.629213
180
0.636892
[ "MIT" ]
CodingJinxx/polypoly
UserInterface/HUD/obj/Debug/HUD/Assets/UserControls/ItemBar.g.cs
3,618
C#
using System; using System.Collections.Generic; using System.Text; namespace DP.B.Strategy.Real { interface IMovable { void Move(); } }
13.166667
33
0.658228
[ "MIT" ]
Mihu89/DesignPatterns
DP/DP/B/Strategy/Real/IMovable.cs
160
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated (once) by \generate-code.bat, but will not be // regenerated when it already exists. The purpose of creating this file is to make // it easier to remember to implement all the unit conversion test cases. // // Whenever a new unit is added to this quantity and \generate-code.bat is run, // the base test class will get a new abstract property and cause a compile error // in this derived class, reminding the developer to implement the test case // for the new unit. // // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. // Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // </auto-generated> //------------------------------------------------------------------------------ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet // // 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 Xunit; namespace UnitsNet.Tests.CustomCode { public class SpecificVolumeTests : SpecificVolumeTestsBase { protected override double CubicMetersPerKilogramInOneCubicMeterPerKilogram => 1; protected override double CubicFeetPerPoundInOneCubicMeterPerKilogram => 16.01846353; [Fact] public static void SpecificVolumeTimesMassEqualsVolume() { Volume volume = SpecificVolume.FromCubicMetersPerKilogram(5) * Mass.FromKilograms(10); Assert.Equal(volume, Volume.FromCubicMeters(50)); } [Fact] public static void ConstantOverSpecificVolumeEqualsDensity() { Density density = 5 / SpecificVolume.FromCubicMetersPerKilogram(20); Assert.Equal(density, Density.FromKilogramsPerCubicMeter(0.25)); } } }
47.358209
104
0.69335
[ "MIT" ]
AlexejLiebenthal/UnitsNet
UnitsNet.Tests/CustomCode/SpecificVolumeTests.cs
3,175
C#
using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.IO; using System.Collections; using System.Reflection; using System.Threading; using System.Diagnostics; using DigitalPlatform; // Stop类 using DigitalPlatform.rms.Client; using DigitalPlatform.Xml; using DigitalPlatform.IO; using DigitalPlatform.Text; using DigitalPlatform.Script; using DigitalPlatform.MarcDom; using DigitalPlatform.Marc; using DigitalPlatform.Message; using DigitalPlatform.rms.Client.rmsws_localhost; using DigitalPlatform.LibraryServer.Common; using DigitalPlatform.Core; namespace DigitalPlatform.LibraryServer { /// <summary> /// 本部分是和日志恢复相关的代码 /// </summary> public partial class LibraryApplication { // Borrow() API 恢复动作 /* 日志记录格式如下 <root> <operation>borrow</operation> 操作类型 <action>borrow</action> 动作 borrow/renew <readerBarcode>R0000002</readerBarcode> 读者证条码号 <itemBarcode>0000001</itemBarcode> 册条码号 <borrowDate>Fri, 08 Dec 2006 04:17:31 GMT</borrowDate> 借阅日期 <borrowPeriod>30day</borrowPeriod> 借阅期限 <no>0</no> 续借次数。0为首次普通借阅,1开始为续借 <operator>test</operator> 操作者 <operTime>Fri, 08 Dec 2006 04:17:31 GMT</operTime> 操作时间 <confirmItemRecPath>...</confirmItemRecPath> 辅助判断用的册记录路径 <readerRecord recPath='...'>...</readerRecord> 最新读者记录 <itemRecord recPath='...'>...</itemRecord> 最新册记录 </root> * */ // parameters: // level 恢复级别。注意 Snapshot 级别非常危险,弄不好会破坏以前的读者记录,要慎用 // bForce 是否为容错状态。在容错状态下,如果遇到重复的册条码号,就算做第一条。 public int RecoverBorrow( RmsChannelCollection Channels, RecoverLevel level, XmlDocument domLog, bool bForce, out string strError) { strError = ""; long lRet = 0; int nRet = 0; // bool bMissing = false; // 是否缺失快照信息? RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } DO_SNAPSHOT: // 快照恢复 if (level == RecoverLevel.Snapshot) { string strReaderXml = DomUtil.GetElementText(domLog.DocumentElement, "readerRecord", out XmlNode node); if (node == null) { strError = "日志记录中缺 <readerRecord> 元素"; return -1; } // 2017/1/12 bool bClipping = DomUtil.GetBooleanParam(node, "clipping", false); if (bClipping == true) { strError = "日志记录中 <readerRecord> 元素为 clipping 状态,无法进行快照恢复"; return -1; } string strReaderRecPath = DomUtil.GetAttr(node, "recPath"); string strItemXml = DomUtil.GetElementText(domLog.DocumentElement, "itemRecord", out node); if (node == null) { strError = "日志记录中缺 <itemRecord> 元素"; return -1; } string strItemRecPath = DomUtil.GetAttr(node, "recPath"); byte[] timestamp = null; // 写读者记录 lRet = channel.DoSaveTextRes(strReaderRecPath, strReaderXml, false, "content,ignorechecktimestamp", timestamp, out byte[] output_timestamp, out string strOutputPath, out strError); if (lRet == -1) { strError = "写入读者记录 '" + strReaderRecPath + "' 时发生错误: " + strError; return -1; } // 写册记录 lRet = channel.DoSaveTextRes(strItemRecPath, strItemXml, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入册记录 '" + strItemRecPath + "' 时发生错误: " + strError; return -1; } return 0; } // 逻辑恢复或者混合恢复 if (level == RecoverLevel.Logic || level == RecoverLevel.LogicAndSnapshot) { string strRecoverComment = ""; string strReaderBarcode = DomUtil.GetElementText(domLog.DocumentElement, "readerBarcode"); if (String.IsNullOrEmpty(strReaderBarcode) == true) { strError = "<readerBarcode>元素值为空"; goto ERROR1; } // 读入读者记录 nRet = this.GetReaderRecXml( // Channels, channel, strReaderBarcode, out string strReaderXml, out string strOutputReaderRecPath, out byte[] reader_timestamp, out strError); if (nRet == 0) { strError = "读者证条码号 '" + strReaderBarcode + "' 不存在"; goto ERROR1; } if (nRet == -1) { strError = "读入证条码号为 '" + strReaderBarcode + "' 的读者记录时发生错误: " + strError; goto ERROR1; } // 获得读者库的馆代码 // return: // -1 出错 // 0 成功 nRet = GetLibraryCode( strOutputReaderRecPath, out string strLibraryCode, out strError); if (nRet == -1) goto ERROR1; nRet = LibraryApplication.LoadToDom(strReaderXml, out XmlDocument readerdom, out strError); if (nRet == -1) { strError = "装载读者记录进入XML DOM时发生错误: " + strError; goto ERROR1; } // 读入册记录 string strConfirmItemRecPath = DomUtil.GetElementText(domLog.DocumentElement, "confirmItemRecPath"); string strItemBarcode = DomUtil.GetElementText(domLog.DocumentElement, "itemBarcode"); if (String.IsNullOrEmpty(strItemBarcode) == true) { strError = "<strItemBarcode>元素值为空"; goto ERROR1; } string strItemXml = ""; string strOutputItemRecPath = ""; byte[] item_timestamp = null; // 如果已经有确定的册记录路径 if (String.IsNullOrEmpty(strConfirmItemRecPath) == false) { lRet = channel.GetRes(strConfirmItemRecPath, out strItemXml, out string strMetaData, out item_timestamp, out strOutputItemRecPath, out strError); if (lRet == -1) { strError = "根据strConfirmItemRecPath '" + strConfirmItemRecPath + "' 获得册记录失败: " + strError; goto ERROR1; } // 需要检查记录中的<barcode>元素值是否匹配册条码号 // TODO: 如果记录路径所表达的记录不存在,或者其<barcode>元素值和要求的册条码号不匹配,那么都要改用逻辑方法,也就是利用册条码号来获得记录。 // 当然,这种情况下,非常要紧的是确保数据库的素质很好,本身没有重条码号的情况出现。 } else { // 从册条码号获得册记录 // 获得册记录 // return: // -1 error // 0 not found // 1 命中1条 // >1 命中多于1条 nRet = this.GetItemRecXml( // Channels, channel, strItemBarcode, out strItemXml, 100, out List<string> aPath, out item_timestamp, out strError); if (nRet == 0) { strError = "册条码号 '" + strItemBarcode + "' 不存在"; goto ERROR1; } if (nRet == -1) { strError = "读入册条码号为 '" + strItemBarcode + "' 的册记录时发生错误: " + strError; goto ERROR1; } if (aPath.Count > 1) { if (bForce == true) { // 容错! strOutputItemRecPath = aPath[0]; strRecoverComment += "册条码号 " + strItemBarcode + " 有 " + aPath.Count.ToString() + " 条重复记录,因受容错要求所迫,权且采用其中第一个记录 " + strOutputItemRecPath + " 来进行借阅操作。"; } else { strError = "册条码号为 '" + strItemBarcode + "' 的册记录有 " + aPath.Count.ToString() + " 条,但此时comfirmItemRecPath却为空"; goto ERROR1; } } else { Debug.Assert(nRet == 1, ""); Debug.Assert(aPath.Count == 1, ""); if (nRet == 1) { strOutputItemRecPath = aPath[0]; } } } nRet = LibraryApplication.LoadToDom(strItemXml, out XmlDocument itemdom, out strError); if (nRet == -1) { strError = "装载册记录进入XML DOM时发生错误: " + strError; goto ERROR1; } // 修改读者记录 // 修改册记录 // TODO: 容错情况下如果遇到册条码号是重复的,要写入额外的日志。 nRet = BorrowChangeReaderAndItemRecord( // Channels, channel, strItemBarcode, strReaderBarcode, domLog, strRecoverComment, strLibraryCode, ref readerdom, ref itemdom, out strError); if (nRet == -1) goto ERROR1; // 写回读者、册记录 // 写回读者记录 lRet = channel.DoSaveTextRes(strOutputReaderRecPath, readerdom.OuterXml, false, "content,ignorechecktimestamp", reader_timestamp, out byte[] output_timestamp, out string strOutputPath, out strError); if (lRet == -1) goto ERROR1; // 写回册记录 lRet = channel.DoSaveTextRes(strOutputItemRecPath, itemdom.OuterXml, false, "content,ignorechecktimestamp", item_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; } // 容错恢复 if (level == RecoverLevel.Robust) { string strRecoverComment = ""; string strReaderBarcode = DomUtil.GetElementText(domLog.DocumentElement, "readerBarcode"); if (String.IsNullOrEmpty(strReaderBarcode) == true) { strError = "<readerBarcode>元素值为空"; return -1; } // 读入读者记录 nRet = this.GetReaderRecXml( // Channels, channel, strReaderBarcode, out string strReaderXml, out string strOutputReaderRecPath, out byte[] reader_timestamp, out strError); if (nRet == 0) { strError = "读者证条码号 '" + strReaderBarcode + "' 不存在"; // TODO: 记入信息文件 // 从日志记录中获得读者记录 strReaderXml = DomUtil.GetElementText(domLog.DocumentElement, "readerRecord", out XmlNode node); if (node == null) { strError = "日志记录中缺<readerRecord>元素"; return -1; } string strReaderRecPath = DomUtil.GetAttr(node, "recPath"); if (String.IsNullOrEmpty(strReaderRecPath) == true) { strError = "日志记录中<readerRecord>元素缺recPath属性"; return -1; } // 新增一条读者记录 strOutputReaderRecPath = ResPath.GetDbName(strReaderRecPath) + "/?"; reader_timestamp = null; } else { if (nRet == -1) { strError = "读入证条码号为 '" + strReaderBarcode + "' 的读者记录时发生错误: " + strError; return -1; } } string strLibraryCode = ""; // 获得读者库的馆代码 // return: // -1 出错 // 0 成功 nRet = GetLibraryCode( strOutputReaderRecPath, out strLibraryCode, out strError); if (nRet == -1) goto ERROR1; XmlDocument readerdom = null; nRet = LibraryApplication.LoadToDom(strReaderXml, out readerdom, out strError); if (nRet == -1) { strError = "装载读者记录进入XML DOM时发生错误: " + strError; return -1; } // 读入册记录 string strConfirmItemRecPath = DomUtil.GetElementText(domLog.DocumentElement, "confirmItemRecPath"); string strItemBarcode = DomUtil.GetElementText(domLog.DocumentElement, "itemBarcode"); if (String.IsNullOrEmpty(strItemBarcode) == true) { strError = "<strItemBarcode>元素值为空"; return -1; } string strOutputItemRecPath = ""; // 从册条码号获得册记录 // 获得册记录 // return: // -1 error // 0 not found // 1 命中1条 // >1 命中多于1条 nRet = this.GetItemRecXml( // Channels, channel, strItemBarcode, out string strItemXml, 100, out List<string> aPath, out byte[] item_timestamp, out strError); if (nRet == 0) { strError = "册条码号 '" + strItemBarcode + "' 不存在"; // TODO: 记入信息文件 XmlNode node = null; strItemXml = DomUtil.GetElementText(domLog.DocumentElement, "itemRecord", out node); if (node == null) { strError = "日志记录中缺<itemRecord>元素"; return -1; } string strItemRecPath = DomUtil.GetAttr(node, "recPath"); if (String.IsNullOrEmpty(strItemRecPath) == true) { strError = "日志记录中<itemRecord>元素缺recPath属性"; return -1; } // 新增一条册记录 strOutputItemRecPath = ResPath.GetDbName(strItemRecPath) + "/?"; item_timestamp = null; } else { if (nRet == -1) { strError = "读入册条码号为 '" + strItemBarcode + "' 的册记录时发生错误: " + strError; return -1; } Debug.Assert(aPath != null, ""); bool bNeedReload = false; if (aPath.Count > 1) { // 建议根据strConfirmItemRecPath来进行挑选 if (String.IsNullOrEmpty(strConfirmItemRecPath) == true) { // 容错! strOutputItemRecPath = aPath[0]; strRecoverComment += "册条码号 " + strItemBarcode + " 有 " + aPath.Count.ToString() + " 条重复记录,因受容错要求所迫,权且采用其中第一个记录 " + strOutputItemRecPath + " 来进行借阅操作。"; // 是否需要重新装载? bNeedReload = false; // 所取得的第一个路径,其记录已经装载 } else { ///// nRet = aPath.IndexOf(strConfirmItemRecPath); if (nRet != -1) { strOutputItemRecPath = aPath[nRet]; strRecoverComment += "册条码号 " + strItemBarcode + " 有 " + aPath.Count.ToString() + " 条重复记录,经过找到strConfirmItemRecPath=[" + strConfirmItemRecPath + "]" + "来进行借阅操作。"; // 是否需要重新装载? if (nRet != 0) bNeedReload = true; // 第一个以外的路径才需要装载 } else { // 容错 strOutputItemRecPath = aPath[0]; strRecoverComment += "册条码号 " + strItemBarcode + " 有 " + aPath.Count.ToString() + " 条重复记录,在其中无法找到strConfirmItemRecPath=[" + strConfirmItemRecPath + "]的记录" + "因受容错要求所迫,权且采用其中第一个记录 " + strOutputItemRecPath + " 来进行借阅操作。"; // 是否需要重新装载? bNeedReload = false; // 所取得的第一个路径,其记录已经装载 /* strError = "册条码号 " + strItemBarcode + " 有 " + aPath.Count.ToString() + " 条重复记录,在其中无法找到strConfirmItemRecPath=[" + strConfirmItemRecPath + "]的记录"; return -1; * */ } } } // if (aPath.Count > 1) else { Debug.Assert(nRet == 1, ""); Debug.Assert(aPath.Count == 1, ""); if (nRet == 1) { strOutputItemRecPath = aPath[0]; // 是否需要重新装载? bNeedReload = false; // 所取得的第一个路径,其记录已经装载 } } // 重新装载 if (bNeedReload == true) { lRet = channel.GetRes(strOutputItemRecPath, out strItemXml, out string strMetaData, out item_timestamp, out strOutputItemRecPath, out strError); if (lRet == -1) { strError = "根据strOutputItemRecPath '" + strOutputItemRecPath + "' 重新获得册记录失败: " + strError; return -1; } // 需要检查记录中的<barcode>元素值是否匹配册条码号 } } //// nRet = LibraryApplication.LoadToDom(strItemXml, out XmlDocument itemdom, out strError); if (nRet == -1) { strError = "装载册记录进入XML DOM时发生错误: " + strError; goto ERROR1; } // 修改读者记录 // 修改册记录 nRet = BorrowChangeReaderAndItemRecord( // Channels, channel, strItemBarcode, strReaderBarcode, domLog, strRecoverComment, strLibraryCode, ref readerdom, ref itemdom, out strError); if (nRet == -1) goto ERROR1; // 写回读者、册记录 // 写回读者记录 lRet = channel.DoSaveTextRes(strOutputReaderRecPath, readerdom.OuterXml, false, "content,ignorechecktimestamp", reader_timestamp, out byte[] output_timestamp, out string strOutputPath, out strError); if (lRet == -1) goto ERROR1; // 写回册记录 lRet = channel.DoSaveTextRes(strOutputItemRecPath, itemdom.OuterXml, false, "content,ignorechecktimestamp", item_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; } return 0; ERROR1: if (level == RecoverLevel.LogicAndSnapshot) { WriteErrorLog($"RecoverBorrow() 用 LogicAndSnapShot 方式恢复遇到报错 {strError},后面自动改用 SnapShot 方式尝试 ..."); level = RecoverLevel.Snapshot; goto DO_SNAPSHOT; } return -1; } #region RecoverBorrow()下级函数 // 获得借阅期限 // parameters: // strLibraryCode 读者记录所从属的恶读者库的馆代码 // return: // -1 出错 // 0 没有获得参数 // 1 获得了参数 int GetBorrowPeriod( string strLibraryCode, XmlDocument readerdom, XmlDocument itemdom, int nNo, out string strPeriod, out string strError ) { strPeriod = ""; strError = ""; int nRet = 0; // 从想要借阅的册信息中,找到图书类型 string strBookType = DomUtil.GetElementText(itemdom.DocumentElement, "bookType"); // 从读者信息中, 找到读者类型 string strReaderType = DomUtil.GetElementText(readerdom.DocumentElement, "readerType"); string strBorrowPeriodList = ""; MatchResult matchresult; nRet = this.GetLoanParam( //null, strLibraryCode, strReaderType, strBookType, "借期", out strBorrowPeriodList, out matchresult, out strError); if (nRet == -1) { strError = "获得借期失败。获得 馆代码 '" + strLibraryCode + "' 中 读者类型 '" + strReaderType + "' 针对图书类型 '" + strBookType + "' 的 借期 参数时发生错误: " + strError; return 0; } if (nRet < 4) // nRet == 0 { strError = "获得借期失败。馆代码 '" + strLibraryCode + "' 中 读者类型 '" + strReaderType + "' 针对图书类型 '" + strBookType + "' 的 借期 参数无法获得: " + strError; return 0; } // 按照逗号分列值,需要根据序号取出某个参数 string[] aPeriod = strBorrowPeriodList.Split(new char[] { ',' }); if (aPeriod.Length == 0) { strError = "获得借期失败。馆代码 '" + strLibraryCode + "' 中 读者类型 '" + strReaderType + "' 针对图书类型 '" + strBookType + "' 的 借期 参数 '" + strBorrowPeriodList + "'格式错误"; return 0; } string strThisBorrowPeriod = ""; string strLastBorrowPeriod = ""; if (nNo > 0) { if (nNo >= aPeriod.Length) { if (aPeriod.Length == 1) strError = "续借失败。馆代码 '" + strLibraryCode + "' 中 读者类型 '" + strReaderType + "' 针对图书类型 '" + strBookType + "' 的 借期 参数值 '" + strBorrowPeriodList + "' 规定,不能续借。(所定义的一个期限,是指第一次借阅的期限)"; else strError = "续借失败。馆代码 '" + strLibraryCode + "' 中 读者类型 '" + strReaderType + "' 针对图书类型 '" + strBookType + "' 的 借期 参数值 '" + strBorrowPeriodList + "' 规定,只能续借 " + Convert.ToString(aPeriod.Length - 1) + " 次。"; return -1; } strThisBorrowPeriod = aPeriod[nNo].Trim(); strLastBorrowPeriod = aPeriod[nNo - 1].Trim(); if (String.IsNullOrEmpty(strThisBorrowPeriod) == true) { strError = "续借失败。馆代码 '" + strLibraryCode + "' 中 读者类型 '" + strReaderType + "' 针对图书类型 '" + strBookType + "' 的 借期 参数 '" + strBorrowPeriodList + "' 格式错误:第 " + Convert.ToString(nNo) + "个部分为空。"; return -1; } } else { strThisBorrowPeriod = aPeriod[0].Trim(); if (String.IsNullOrEmpty(strThisBorrowPeriod) == true) { strError = "借阅失败。馆代码 '" + strLibraryCode + "' 中 读者类型 '" + strReaderType + "' 针对图书类型 '" + strBookType + "' 的 借期 参数 '" + strBorrowPeriodList + "' 格式错误:第一部分为空。"; return -1; } } // 检查strBorrowPeriod是否合法 { nRet = LibraryApplication.ParsePeriodUnit( strThisBorrowPeriod, out long lPeriodValue, out string strPeriodUnit, out strError); if (nRet == -1) { strError = "借阅失败。馆代码 '" + strLibraryCode + "' 中 读者类型 '" + strReaderType + "' 针对图书类型 '" + strBookType + "' 的 借期 参数 '" + strBorrowPeriodList + "' 格式错误:'" + strThisBorrowPeriod + "' 格式错误: " + strError; return -1; } } strPeriod = strThisBorrowPeriod; return 1; } // 去除读者记录侧的借阅信息链条 // return: // -1 出错 // 0 没有必要修复 // 1 修复成功 int RemoveReaderSideLink( // RmsChannelCollection Channels, RmsChannel channel, string strReaderBarcode, string strItemBarcode, out string strRemovedInfo, out string strError) { strError = ""; strRemovedInfo = ""; int nRedoCount = 0; // 因为时间戳冲突, 重试的次数 REDO_REPAIR: // 读入读者记录 string strReaderXml = ""; string strOutputReaderRecPath = ""; byte[] reader_timestamp = null; int nRet = this.GetReaderRecXml( // Channels, channel, strReaderBarcode, out strReaderXml, out strOutputReaderRecPath, out reader_timestamp, out strError); if (nRet == 0) { strError = "读者证条码号 '" + strReaderBarcode + "' 不存在"; return 0; } if (nRet == -1) { strError = "读入读者记录时发生错误: " + strError; return -1; } XmlDocument readerdom = null; nRet = LibraryApplication.LoadToDom(strReaderXml, out readerdom, out strError); if (nRet == -1) { strError = "装载读者记录进入XML DOM时发生错误: " + strError; return -1; } // 校验读者证条码号参数是否和XML记录中完全一致 string strTempBarcode = DomUtil.GetElementText(readerdom.DocumentElement, "barcode"); if (strReaderBarcode != strTempBarcode) { strError = "修复操作被拒绝。因读者证条码号参数 '" + strReaderBarcode + "' 和读者记录中<barcode>元素内的读者证条码号值 '" + strTempBarcode + "' 不一致。"; return -1; } XmlNode nodeBorrow = readerdom.DocumentElement.SelectSingleNode("borrows/borrow[@barcode='" + strItemBarcode + "']"); if (nodeBorrow == null) { strError = "在读者记录 '" + strReaderBarcode + "' 中没有找到关于册条码号 '" + strItemBarcode + "' 的链"; return 0; } strRemovedInfo = nodeBorrow.OuterXml; // 移除读者记录侧的链 nodeBorrow.ParentNode.RemoveChild(nodeBorrow); #if NO RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } #endif byte[] output_timestamp = null; string strOutputPath = ""; // 写回读者记录 long lRet = channel.DoSaveTextRes(strOutputReaderRecPath, readerdom.OuterXml, false, "content", // ,ignorechecktimestamp reader_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { nRedoCount++; if (nRedoCount > 10) { strError = "写回读者记录 '" + strOutputReaderRecPath + "' 的时候,遇到时间戳冲突,并因此重试10次,仍失败..."; return -1; } goto REDO_REPAIR; } return -1; } return 1; } public delegate void delegate_writeLog(string text); // 借阅操作,修改读者和册记录 // parameters: // strItemBarcodeParam 册条码号。可以使用 @refID: 前缀 // strLibraryCode 读者记录所从属的恶读者库的馆代码 int BorrowChangeReaderAndItemRecord( // RmsChannelCollection Channels, RmsChannel channel, string strItemBarcodeParam, string strReaderBarcode, XmlDocument domLog, string strRecoverComment, string strLibraryCode, ref XmlDocument readerdom, ref XmlDocument itemdom, out string strError) { strError = ""; int nRet = 0; string strOperator = DomUtil.GetElementText(domLog.DocumentElement, "operator"); // *** 修改读者记录 string strNo = DomUtil.GetElementText(domLog.DocumentElement, "no"); if (String.IsNullOrEmpty(strNo) == true) { strError = "日志记录中缺<no>元素"; return -1; } int nNo = 0; try { nNo = Convert.ToInt32(strNo); } catch (Exception /*ex*/) { strError = "<no>元素值 '" + strNo + "' 应该为纯数字"; return -1; } XmlElement nodeBorrow = null; // 既然日志记录中记载的是 @refID: 的形态,那读者记录中 borrows 里面势必记载的也是这个形态 nodeBorrow = readerdom.DocumentElement.SelectSingleNode("borrows/borrow[@barcode='" + strItemBarcodeParam + "']") as XmlElement; #if NOOOOOOOOOOOOOOOOOO if (nNo >= 1) { // 看看是否已经有先前已经借阅的册 // nodeBorrow = readerdom.DocumentElement.SelectSingleNode("borrows/borrow[@barcode='" + strItemBarcode + "']"); if (nodeBorrow == null) { strError = "该读者未曾借阅过册 '" + strItemBarcode + "',因此无法续借。"; return -1; } /* // 获得上次的序号,加以检验 int nLastNo = 0; string strLastNo = DomUtil.GetAttr(nodeBorrow, "no"); if (String.IsNullOrEmpty(strLastNo) == true) nLastNo = 0; else { try { nLastNo = Convert.ToInt32(strLastNo); } catch { strError = "读者记录中XML片断 " + nodeBorrow.OuterXml + "其中no属性值'" + strLastNo + "' 格式错误"; return -1; } } if (nLastNo != nNo - 1) { strError = "读者记录中已经存在的上次借次编号 '" + nLastNo.ToString() + "' 不是正好比本次的借次编号 '" + nNo.ToString() + "' 小1"; return -1; } * */ } else { if (nodeBorrow != null) { // 2008/1/30 changed ,容错 // strError = "该读者已经借阅了册 '" + strItemBarcode + "',不能重复借。"; // return -1; // } else { // 检查<borrows>元素是否存在 XmlNode root = readerdom.DocumentElement.SelectSingleNode("borrows"); if (root == null) { root = readerdom.CreateElement("borrows"); root = readerdom.DocumentElement.AppendChild(root); } // 加入借阅册信息 nodeBorrow = readerdom.CreateElement("borrow"); nodeBorrow = root.AppendChild(nodeBorrow); } } #endif // 2008/2/1 changed 为了提高容错能力,续借操作时不去追究以前是否借阅过 if (nodeBorrow != null) { // 2008/1/30 changed ,容错 // strError = "该读者已经借阅了册 '" + strItemBarcode + "',不能重复借。"; // return -1; // } else { // 检查<borrows>元素是否存在 XmlNode root = readerdom.DocumentElement.SelectSingleNode("borrows"); if (root == null) { root = readerdom.CreateElement("borrows"); root = readerdom.DocumentElement.AppendChild(root); } // 加入借阅册信息 nodeBorrow = readerdom.CreateElement("borrow"); nodeBorrow = root.AppendChild(nodeBorrow) as XmlElement; } // // barcode DomUtil.SetAttr(nodeBorrow, "barcode", strItemBarcodeParam); string strRenewComment = ""; string strBorrowDate = DomUtil.GetElementText(domLog.DocumentElement, "borrowDate"); if (nNo >= 1) { // 保存前一次借阅的信息 strRenewComment = DomUtil.GetAttr(nodeBorrow, "renewComment"); if (strRenewComment != "") strRenewComment += "; "; strRenewComment += "no=" + Convert.ToString(nNo - 1) + ", "; strRenewComment += "borrowDate=" + DomUtil.GetAttr(nodeBorrow, "borrowDate") + ", "; strRenewComment += "borrowPeriod=" + DomUtil.GetAttr(nodeBorrow, "borrowPeriod") + ", "; strRenewComment += "returnDate=" + strBorrowDate + ", "; strRenewComment += "operator=" + DomUtil.GetAttr(nodeBorrow, "operator"); } // borrowDate DomUtil.SetAttr(nodeBorrow, "borrowDate", strBorrowDate); // no DomUtil.SetAttr(nodeBorrow, "no", Convert.ToString(nNo)); // borrowPeriod string strBorrowPeriod = DomUtil.GetElementText(domLog.DocumentElement, "borrowPeriod"); if (String.IsNullOrEmpty(strBorrowPeriod) == true) { // 获得借阅期限 // return: // -1 出错 // 0 没有获得参数 // 1 获得了参数 nRet = GetBorrowPeriod( strLibraryCode, readerdom, itemdom, nNo, out strBorrowPeriod, out strError); if (nRet == -1) return -1; if (nRet == 0) { strBorrowPeriod = DomUtil.GetElementText(domLog.DocumentElement, "defaultBorrowPeriod"); if (String.IsNullOrEmpty(strBorrowPeriod) == true) strBorrowPeriod = "60day"; } } DomUtil.SetAttr(nodeBorrow, "borrowPeriod", strBorrowPeriod); // returningDate LibraryServerUtil.SetAttribute(domLog, "returningDate", nodeBorrow); // renewComment { if (string.IsNullOrEmpty(strRenewComment) == false) DomUtil.SetAttr(nodeBorrow, "renewComment", strRenewComment); } // operator #if NO DomUtil.SetAttr(nodeBorrow, "operator", strOperator); #endif LibraryServerUtil.SetAttribute(domLog, "operator", nodeBorrow); // recoverComment if (String.IsNullOrEmpty(strRecoverComment) == false) DomUtil.SetAttr(nodeBorrow, "recoverComment", strItemBarcodeParam); // type LibraryServerUtil.SetAttribute(domLog, "type", nodeBorrow); // price LibraryServerUtil.SetAttribute(domLog, "price", nodeBorrow); // *** 检查册记录以前是否存在在借的痕迹,如果存在的话,(如果指向当前读者倒是无妨了反正后面即将要覆盖) 需要事先消除相关的另一个读者记录的痕迹,也就是说相当于把相关的册给进行还书操作 string strBorrower0 = DomUtil.GetElementInnerText(itemdom.DocumentElement, "borrower"); if (string.IsNullOrEmpty(strBorrower0) == false && strBorrower0 != strReaderBarcode) { // 去除读者记录侧的借阅信息链条 // return: // -1 出错 // 0 没有必要修复 // 1 修复成功 nRet = RemoveReaderSideLink( // Channels, channel, strBorrower0, strItemBarcodeParam, out string strRemovedInfo, out strError); if (nRet == -1) { this.WriteErrorLog("册条码号为 '" + strItemBarcodeParam + "' 的册记录,在进行借书操作(拟被读者 '" + strReaderBarcode + "' 借阅)以前,发现它被另一读者 '" + strBorrower0 + "' 持有,软件尝试自动修正(删除)此读者记录的半侧借阅信息链。不过,在去除读者记录册借阅链时发生错误: " + strError); // writeLog?.Invoke($"册条码号为 '{strItemBarcodeParam}' 的册记录,在进行借书操作(拟被读者 '{strReaderBarcode}' 借阅)以前,发现它被另一读者 '{strBorrower0}' 持有,软件尝试自动修正(删除)此读者记录的半侧借阅信息链。不过,在去除读者记录册借阅链时发生错误: {strError}"); } else { this.WriteErrorLog("册条码号为 '" + strItemBarcodeParam + "' 的册记录,在进行借书操作(拟被读者 '" + strReaderBarcode + "' 借阅)以前,发现它被另一读者 '" + strBorrower0 + "' 持有,软件已经自动修正(删除)了此读者记录的半侧借阅信息链。被移走的片断 XML 信息为 '" + strRemovedInfo + "'"); // writeLog?.Invoke($"册条码号为 '{strItemBarcodeParam}' 的册记录,在进行借书操作(拟被读者 '{strReaderBarcode}' 借阅)以前,发现它被另一读者 '{strBorrower0}' 持有,软件已经自动修正(删除)了此读者记录的半侧借阅信息链。被移走的片断 XML 信息为 '{strRemovedInfo}'"); } } // *** 修改册记录 DomUtil.SetElementText(itemdom.DocumentElement, "borrower", strReaderBarcode); DomUtil.SetElementText(itemdom.DocumentElement, "borrowDate", strBorrowDate); DomUtil.SetElementText(itemdom.DocumentElement, "no", Convert.ToString(nNo)); DomUtil.SetElementText(itemdom.DocumentElement, "borrowPeriod", strBorrowPeriod); DomUtil.SetElementText(itemdom.DocumentElement, "renewComment", strRenewComment); DomUtil.SetElementText(itemdom.DocumentElement, "operator", strOperator); // recoverComment if (String.IsNullOrEmpty(strRecoverComment) == false) { DomUtil.SetElementText(itemdom.DocumentElement, "recoverComment", strRecoverComment); } return 0; } #endregion // Return() API 恢复动作 /* 日志记录格式 <root> <operation>return</operation> 操作类型 <action>return</action> 动作。有 return/lost/inventory/read/boxing 几种。恢复动作目前仅恢复 return 和 lost 两种,其余会忽略 <itemBarcode>0000001</itemBarcode> 册条码号 <readerBarcode>R0000002</readerBarcode> 读者证条码号 <operator>test</operator> 操作者 <operTime>Fri, 08 Dec 2006 04:17:45 GMT</operTime> 操作时间 <overdues>...</overdues> 超期信息 通常内容为一个字符串,为一个<overdue>元素XML文本片断 <confirmItemRecPath>...</confirmItemRecPath> 辅助判断用的册记录路径 <readerRecord recPath='...'>...</readerRecord> 最新读者记录 <itemRecord recPath='...'>...</itemRecord> 最新册记录 * 2016/7/22 新增加 * borrowDate * borrowPeriod * denyPeriod * returningDate * borrowOperator </root> * * */ // parameters: // bForce 是否为容错状态。在容错状态下,如果遇到重复的册条码号,就算做第一条。 public int RecoverReturn( RmsChannelCollection Channels, RecoverLevel level, XmlDocument domLog, bool bForce, out string strError) { strError = ""; long lRet = 0; int nRet = 0; RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } DO_SNAPSHOT: // 快照恢复 if (level == RecoverLevel.Snapshot) { string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); if (strAction != "return" && strAction != "lost") { // 忽略其余动作 return 0; } string strReaderXml = DomUtil.GetElementText(domLog.DocumentElement, "readerRecord", out XmlNode node); if (node == null) { strError = "日志记录中缺<readerRecord>元素"; return -1; } // 2017/1/12 bool bClipping = DomUtil.GetBooleanParam(node, "clipping", false); if (bClipping == true) { strError = "日志记录中<readerRecord>元素为 clipping 状态,无法进行快照恢复"; return -1; } string strReaderRecPath = DomUtil.GetAttr(node, "recPath"); string strItemXml = DomUtil.GetElementText(domLog.DocumentElement, "itemRecord", out node); if (node == null) { strError = "日志记录中缺<itemRecord>元素"; return -1; } string strItemRecPath = DomUtil.GetAttr(node, "recPath"); byte[] timestamp = null; // 写读者记录 lRet = channel.DoSaveTextRes(strReaderRecPath, strReaderXml, false, "content,ignorechecktimestamp", timestamp, out byte[] output_timestamp, out string strOutputPath, out strError); if (lRet == -1) { strError = "写入读者记录 '" + strReaderRecPath + "' 时发生错误: " + strError; return -1; } // 写册记录 lRet = channel.DoSaveTextRes(strItemRecPath, strItemXml, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入读者记录 '" + strReaderRecPath + "' 时发生错误: " + strError; return -1; } return 0; } // 逻辑恢复或者混合恢复 if (level == RecoverLevel.Logic || level == RecoverLevel.LogicAndSnapshot) { string strRecoverComment = ""; string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); if (strAction != "return" && strAction != "lost") { // 忽略其余动作 return 0; } string strReaderBarcode = DomUtil.GetElementText(domLog.DocumentElement, "readerBarcode"); // 读入册记录 string strConfirmItemRecPath = DomUtil.GetElementText(domLog.DocumentElement, "confirmItemRecPath"); string strItemBarcode = DomUtil.GetElementText(domLog.DocumentElement, "itemBarcode"); if (String.IsNullOrEmpty(strItemBarcode) == true) { strError = "<strItemBarcode>元素值为空"; goto ERROR1; } string strItemXml = ""; string strOutputItemRecPath = ""; byte[] item_timestamp = null; // 如果已经有确定的册记录路径 if (String.IsNullOrEmpty(strConfirmItemRecPath) == false) { string strMetaData = ""; lRet = channel.GetRes(strConfirmItemRecPath, out strItemXml, out strMetaData, out item_timestamp, out strOutputItemRecPath, out strError); if (lRet == -1) { strError = "根据strConfirmItemRecPath '" + strConfirmItemRecPath + "' 获得册记录失败: " + strError; goto ERROR1; } // 需要检查记录中的<barcode>元素值是否匹配册条码号 } else { // 从册条码号获得册记录 // 获得册记录 // return: // -1 error // 0 not found // 1 命中1条 // >1 命中多于1条 nRet = this.GetItemRecXml( // Channels, channel, strItemBarcode, out strItemXml, 100, out List<string> aPath, out item_timestamp, out strError); if (nRet == 0) { strError = "册条码号 '" + strItemBarcode + "' 不存在"; goto ERROR1; } if (nRet == -1) { strError = "读入册条码号为 '" + strItemBarcode + "' 的册记录时发生错误: " + strError; goto ERROR1; } if (aPath.Count > 1) { if (string.IsNullOrEmpty(strReaderBarcode) == true) { // 发生重条码号的时候,又没有读者证条码号辅助判断 if (bForce == false) { strError = "册条码号为 '" + strItemBarcode + "' 的册记录有 " + aPath.Count.ToString() + " 条,但此时日志记录中没有提供读者证条码号辅助判断,无法进行还书操作。"; goto ERROR1; } // TODO: 那就至少看看这些册中,哪些表明被人借阅着?如果正巧只有一个人借过,那就...。 strRecoverComment += "册条码号 " + strItemBarcode + "有 " + aPath.Count.ToString() + " 条重复记录,而且没有读者证条码号进行辅助选择。"; } /* strError = "册条码号为 '" + strItemBarcode + "' 的册记录有 " + aPath.Count.ToString() + " 条,但此时comfirmItemRecPath却为空"; goto ERROR1; * */ // bItemBarcodeDup = true; // 此时已经需要设置状态。虽然后面可以进一步识别出真正的册记录 /* // 构造strDupBarcodeList string[] pathlist = new string[aPath.Count]; aPath.CopyTo(pathlist); strDupBarcodeList = String.Join(",", pathlist); * */ // 从若干重复条码号的册记录中,选出其中符合当前读者证条码号的 // return: // -1 出错 // 其他 选出的数量 nRet = FindItem( channel, strReaderBarcode, aPath, true, // 优化 out List<string> aFoundPath, out List<string> aItemXml, out List<byte[]> aTimestamp, out strError); if (nRet == -1) { strError = "选择重复条码号的册记录时发生错误: " + strError; goto ERROR1; } if (nRet == 0) { strError = "册条码号 '" + strItemBarcode + "' 检索出的 " + aPath.Count + " 条记录中,没有任何一条其<borrower>元素表明了被读者 '" + strReaderBarcode + "' 借阅。"; goto ERROR1; } if (nRet > 1) { if (bForce == true) { // 容错情况下,选择第一个册条码号 strOutputItemRecPath = aFoundPath[0]; item_timestamp = aTimestamp[0]; strItemXml = aItemXml[0]; // TODO: 不过,应当在记录中记载注释,表示这是容错处理方式 if (string.IsNullOrEmpty(strReaderBarcode) == true) { strRecoverComment += "经过筛选,仍然有 " + aFoundPath.Count.ToString() + " 条册记录含有借阅者信息(无论什么读者证条码号),那么就只好选择其中第一个册记录 " + strOutputItemRecPath + " 进行还书操作。"; } else { strRecoverComment += "经过筛选,仍然有 " + aFoundPath.Count.ToString() + " 条册记录含有借阅者 '" + strReaderBarcode + "' 信息,那么就只好选择其中第一个册记录 " + strOutputItemRecPath + " 进行还书操作。"; } } else { strError = "册条码号为 '" + strItemBarcode + "' 并且<borrower>元素表明为读者 '" + strReaderBarcode + "' 借阅的册记录有 " + aFoundPath.Count.ToString() + " 条,无法进行还书操作。"; /* aDupPath = new string[aFoundPath.Count]; aFoundPath.CopyTo(aDupPath); * */ goto ERROR1; } } Debug.Assert(nRet == 1, ""); strOutputItemRecPath = aFoundPath[0]; item_timestamp = aTimestamp[0]; strItemXml = aItemXml[0]; } else { Debug.Assert(nRet == 1, ""); Debug.Assert(aPath.Count == 1, ""); if (nRet == 1) { strOutputItemRecPath = aPath[0]; } } } XmlDocument itemdom = null; nRet = LibraryApplication.LoadToDom(strItemXml, out itemdom, out strError); if (nRet == -1) { strError = "装载册记录进入XML DOM时发生错误: " + strError; goto ERROR1; } /// if (String.IsNullOrEmpty(strReaderBarcode) == true) { if (bForce == true) { // 容错的情况下,从册记录中获得借者证条码号 strReaderBarcode = DomUtil.GetElementText(itemdom.DocumentElement, "borrower"); if (String.IsNullOrEmpty(strReaderBarcode) == true) { strError = "在不知道读者证条码号的情况下,册记录中的<borrower>元素值为空。无法进行还书操作。"; goto ERROR1; } } else { strError = "日志记录中<readerBarcode>元素值为空"; goto ERROR1; } } // 读入读者记录 nRet = this.GetReaderRecXml( // Channels, channel, strReaderBarcode, out string strReaderXml, out string strOutputReaderRecPath, out byte[] reader_timestamp, out strError); if (nRet == 0) { strError = "读者证条码号 '" + strReaderBarcode + "' 不存在"; goto ERROR1; } if (nRet == -1) { strError = "读入证条码号为 '" + strReaderBarcode + "' 的读者记录时发生错误: " + strError; goto ERROR1; } nRet = LibraryApplication.LoadToDom(strReaderXml, out XmlDocument readerdom, out strError); if (nRet == -1) { strError = "装载读者记录进入XML DOM时发生错误: " + strError; goto ERROR1; } // 修改读者记录 // 修改册记录 nRet = ReturnChangeReaderAndItemRecord( // Channels, channel, strAction, strItemBarcode, strReaderBarcode, domLog, strRecoverComment, ref readerdom, ref itemdom, out strError); if (nRet == -1) goto ERROR1; // 写回读者、册记录 byte[] output_timestamp = null; string strOutputPath = ""; // 写回读者记录 lRet = channel.DoSaveTextRes(strOutputReaderRecPath, readerdom.OuterXml, false, "content,ignorechecktimestamp", reader_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; // 写回册记录 lRet = channel.DoSaveTextRes(strOutputItemRecPath, itemdom.OuterXml, false, "content,ignorechecktimestamp", item_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; } // 容错恢复 if (level == RecoverLevel.Robust) { string strRecoverComment = ""; string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); if (strAction != "return" && strAction != "lost") { // 忽略其余动作 return 0; } string strReaderBarcode = DomUtil.GetElementText(domLog.DocumentElement, "readerBarcode"); // 读入册记录 string strConfirmItemRecPath = DomUtil.GetElementText(domLog.DocumentElement, "confirmItemRecPath"); string strItemBarcode = DomUtil.GetElementText(domLog.DocumentElement, "itemBarcode"); if (String.IsNullOrEmpty(strItemBarcode) == true) { strError = "<strItemBarcode>元素值为空"; goto ERROR1; } string strOutputItemRecPath = ""; // 从册条码号获得册记录 bool bDupItemBarcode = false; // 册条码号是否发生了重复 // 获得册记录 // return: // -1 error // 0 not found // 1 命中1条 // >1 命中多于1条 nRet = this.GetItemRecXml( // Channels, channel, strItemBarcode, out string strItemXml, 100, out List<string> aPath, out byte[] item_timestamp, out strError); if (nRet == 0) { strError = "册条码号 '" + strItemBarcode + "' 不存在"; // TODO: 记入信息文件 strItemXml = DomUtil.GetElementText(domLog.DocumentElement, "itemRecord", out XmlNode node); if (node == null) { strError = "日志记录中缺<itemRecord>元素"; return -1; } string strItemRecPath = DomUtil.GetAttr(node, "recPath"); if (String.IsNullOrEmpty(strItemRecPath) == true) { strError = "日志记录中<itemRecord>元素缺recPath属性"; return -1; } // 新增一条册记录 strOutputItemRecPath = ResPath.GetDbName(strItemRecPath) + "/?"; item_timestamp = null; } else { if (nRet == -1) { strError = "读入册条码号为 '" + strItemBarcode + "' 的册记录时发生错误: " + strError; return -1; } if (aPath.Count > 1) { bDupItemBarcode = true; if (string.IsNullOrEmpty(strReaderBarcode) == true) { // 发生重条码号的时候,又没有读者证条码号辅助判断 if (bForce == false) { strError = "册条码号为 '" + strItemBarcode + "' 的册记录有 " + aPath.Count.ToString() + " 条,但此时日志记录中没有提供读者证条码号辅助判断,无法进行还书操作。"; return -1; } // TODO: 那就至少看看这些册中,哪些表明被人借阅着?如果正巧只有一个人借过,那就...。 strRecoverComment += "册条码号 " + strItemBarcode + " 有 " + aPath.Count.ToString() + " 条重复记录,而且没有读者证条码号进行辅助选择。"; } // 从若干重复条码号的册记录中,选出其中符合当前读者证条码号的 // return: // -1 出错 // 其他 选出的数量 nRet = FindItem( channel, strReaderBarcode, aPath, true, // 优化 out List<string> aFoundPath, out List<string> aItemXml, out List<byte[]> aTimestamp, out strError); if (nRet == -1) { strError = "选择重复条码号的册记录时发生错误: " + strError; return -1; } if (nRet == 0) { if (bDupItemBarcode == false) { // 没有重复册条码号的情况下才作 // 需要把根据“所借册条码号”清除读者记录中借阅信息的动作提前进行? 这样遇到特殊情况范围时,至少读者记录中的信息是被清除了的,这是容错的需要 string strError_1 = ""; nRet = ReturnAllReader( // Channels, channel, strItemBarcode, "", out strError_1); if (nRet == -1) { // 故意不报,继续处理 } } strError = "册条码号 '" + strItemBarcode + "' 检索出的 " + aPath.Count + " 条记录中,没有任何一条其<borrower>元素表明了被读者 '" + strReaderBarcode + "' 借阅。"; return -1; } if (nRet > 1) { if (bForce == true) { // 容错情况下,选择第一个册条码号 strOutputItemRecPath = aFoundPath[0]; item_timestamp = aTimestamp[0]; strItemXml = aItemXml[0]; // TODO: 不过,应当在记录中记载注释,表示这是容错处理方式 if (string.IsNullOrEmpty(strReaderBarcode) == true) { strRecoverComment += "经过筛选,仍然有 " + aFoundPath.Count.ToString() + " 条册记录含有借阅者信息(无论什么读者证条码号),那么就只好选择其中第一个册记录 " + strOutputItemRecPath + " 进行还书操作。"; } else { strRecoverComment += "经过筛选,仍然有 " + aFoundPath.Count.ToString() + " 条册记录含有借阅者 '" + strReaderBarcode + "' 信息,那么就只好选择其中第一个册记录 " + strOutputItemRecPath + " 进行还书操作。"; } } else { strError = "册条码号为 '" + strItemBarcode + "' 并且<borrower>元素表明为读者 '" + strReaderBarcode + "' 借阅的册记录有 " + aFoundPath.Count.ToString() + " 条,无法进行还书操作。"; return -1; } } Debug.Assert(nRet == 1, ""); strOutputItemRecPath = aFoundPath[0]; item_timestamp = aTimestamp[0]; strItemXml = aItemXml[0]; } else { Debug.Assert(nRet == 1, ""); Debug.Assert(aPath.Count == 1, ""); if (nRet == 1) { strOutputItemRecPath = aPath[0]; } } } //// XmlDocument itemdom = null; nRet = LibraryApplication.LoadToDom(strItemXml, out itemdom, out strError); if (nRet == -1) { strError = "装载册记录进入XML DOM时发生错误: " + strError; goto ERROR1; } /// if (String.IsNullOrEmpty(strReaderBarcode) == true) { if (bForce == true) { // 容错的情况下,从册记录中获得借者证条码号 strReaderBarcode = DomUtil.GetElementText(itemdom.DocumentElement, "borrower"); if (String.IsNullOrEmpty(strReaderBarcode) == true) { strError = "在不知道读者证条码号的情况下,册记录中的<borrower>元素值为空。无法进行还书操作。"; return -1; } } else { strError = "日志记录中<readerBarcode>元素值为空"; return -1; } } // 读入读者记录 nRet = this.GetReaderRecXml( // Channels, channel, strReaderBarcode, out string strReaderXml, out string strOutputReaderRecPath, out byte[] reader_timestamp, out strError); if (nRet == 0) { strError = "读者证条码号 '" + strReaderBarcode + "' 不存在"; // TODO: 记入信息文件 // 从日志记录中获得读者记录 strReaderXml = DomUtil.GetElementText(domLog.DocumentElement, "readerRecord", out XmlNode node); if (node == null) { strError = "日志记录中缺<readerRecord>元素"; return -1; } string strReaderRecPath = DomUtil.GetAttr(node, "recPath"); if (String.IsNullOrEmpty(strReaderRecPath) == true) { strError = "日志记录中<readerRecord>元素缺recPath属性"; return -1; } // 新增一条读者记录 strOutputReaderRecPath = ResPath.GetDbName(strReaderRecPath) + "/?"; reader_timestamp = null; } else { if (nRet == -1) { strError = "读入证条码号为 '" + strReaderBarcode + "' 的读者记录时发生错误: " + strError; return -1; } } nRet = LibraryApplication.LoadToDom(strReaderXml, out XmlDocument readerdom, out strError); if (nRet == -1) { strError = "装载读者记录进入XML DOM时发生错误: " + strError; return -1; } // 修改读者记录 // 修改册记录 nRet = ReturnChangeReaderAndItemRecord( // Channels, channel, strAction, strItemBarcode, strReaderBarcode, domLog, strRecoverComment, ref readerdom, ref itemdom, out strError); if (nRet == -1) return -1; // 在容错(并且没有重复册条码号的情况下)的情况下,需要利用读者库的“所借册条码号”检索途径,把除了当前关注的读者记录以外的潜在相关读者记录调出, // 把它们中的相关<borrows/borrow>抹除,以免造成多头的借阅信息。 if (bDupItemBarcode == false) { nRet = ReturnAllReader( // Channels, channel, strItemBarcode, strOutputReaderRecPath, out strError); if (nRet == -1) { // 故意不报,继续处理 } } // 写回读者、册记录 // 写回读者记录 lRet = channel.DoSaveTextRes(strOutputReaderRecPath, readerdom.OuterXml, false, "content,ignorechecktimestamp", reader_timestamp, out byte[] output_timestamp, out string strOutputPath, out strError); if (lRet == -1) return -1; // 写回册记录 lRet = channel.DoSaveTextRes(strOutputItemRecPath, itemdom.OuterXml, false, "content,ignorechecktimestamp", item_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) return -1; } return 0; ERROR1: if (level == RecoverLevel.LogicAndSnapshot) { WriteErrorLog($"RecoverReturn() 用 LogicAndSnapShot 方式恢复遇到报错 {strError},后面自动改用 SnapShot 方式尝试 ..."); level = RecoverLevel.Snapshot; goto DO_SNAPSHOT; } return -1; } #region RecoverReturn()下级函数 // 根据 所借册条码号,清除若干读者记录中的借阅信息 int ReturnAllReader( // RmsChannelCollection Channels, RmsChannel channel, string strItemBarcode, string strExcludeReaderRecPath, out string strError) { strError = ""; // TODO: 关注读者库 “所借册条码号” 检索途径是否存在。必须存在才行 List<string> aReaderPath = null; string strTempReaderXml = ""; byte[] temp_timestamp = null; // 获得读者记录 // return: // -1 error // 0 not found // 1 命中1条 // >1 命中多于1条 int nRet = this.GetReaderRecXml( // Channels, channel, strItemBarcode, out strTempReaderXml, 100, out aReaderPath, out temp_timestamp, out strError); if (nRet == -1) { strError = "检索册条码号为 '" + strItemBarcode + "' 的一条或者多条册记录时发生错误: " + strError; return -1; } if (aReaderPath != null) { // 去除已经被作为当前记录的那条 while (aReaderPath.Count > 0) { nRet = aReaderPath.IndexOf(strExcludeReaderRecPath); if (nRet != -1) aReaderPath.Remove(strExcludeReaderRecPath); else break; } if (aReaderPath.Count >= 1) { #if NO RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } #endif // 从若干读者记录中,清除特定的所借事项。相当于针对读者记录执行了还书操作 // parameters: // strBorrowItemBarcode 要清除的册记录条码号 // aPath 读者记录路径集合 // return: // -1 出错 // 0 成功 nRet = ClearBorrowItem( channel, strItemBarcode, aReaderPath, out strError); if (nRet == -1) { strError = "ClearBorrowItem() error: " + strError; return -1; } } } return 0; } // 从若干读者记录中,清除特定的所借事项。相当于针对读者记录执行了还书操作 // parameters: // strBorrowItemBarcode 要清除的册记录条码号 // aPath 读者记录路径集合 // return: // -1 出错 // 0 成功 static int ClearBorrowItem( RmsChannel channel, string strBorrowItemBarcode, List<string> reader_paths, out string strError) { strError = ""; for (int i = 0; i < reader_paths.Count; i++) { string strXml = ""; string strMetaData = ""; string strOutputPath = ""; byte[] timestamp = null; string strPath = reader_paths[i]; long lRet = channel.GetRes(strPath, out strXml, out strMetaData, out timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; // 装入DOM XmlDocument dom = new XmlDocument(); try { dom.LoadXml(strXml); } catch (Exception ex) { strError = "记录 '" + strPath + "' XML装入DOM出错: " + ex.Message; goto ERROR1; } bool bChanged = false; XmlNodeList nodes = dom.DocumentElement.SelectNodes("//borrows/borrow[@barcode='" + strBorrowItemBarcode + "']"); for (int j = 0; j < nodes.Count; j++) { XmlNode node = nodes[j]; if (node.ParentNode != null) { node.ParentNode.RemoveChild(node); bChanged = true; } } if (bChanged == true) { // 写读者记录 byte[] output_timestamp = null; lRet = channel.DoSaveTextRes(strPath, dom.OuterXml, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入读者记录 '" + strPath + "' 时发生错误: " + strError; return -1; } } } return 0; ERROR1: return -1; } // 还书操作,修改读者和册记录 // parameters: // strItemBarcodeParam 册条码号。可以使用 @refID: 前缀 int ReturnChangeReaderAndItemRecord( // RmsChannelCollection Channels, RmsChannel channel, string strAction, string strItemBarcodeParam, string strReaderBarcode, XmlDocument domLog, string strRecoverComment, ref XmlDocument readerdom, ref XmlDocument itemdom, out string strError) { strError = ""; int nRet = 0; // 2017/10/24 if (strAction != "return" && strAction != "lost") { strError = "ReturnChangeReaderAndItemRecord() 只能处理 strAction 为 'return' 和 'lost' 的情况,不能处理 '" + strAction + "'"; return -1; } string strReturnOperator = DomUtil.GetElementText(domLog.DocumentElement, "operator"); string strOperTime = DomUtil.GetElementText(domLog.DocumentElement, "operTime"); // *** 修改读者记录 string strDeletedBorrowFrag = ""; XmlNode dup_reader_history = null; // 既然日志记录中记载的是 @refID: 的形态,那读者记录中 borrows 里面势必记载的也是这个形态 XmlNode nodeBorrow = readerdom.DocumentElement.SelectSingleNode( "borrows/borrow[@barcode='" + strItemBarcodeParam + "']"); if (nodeBorrow != null) { if (String.IsNullOrEmpty(strRecoverComment) == false) { string strText = strRecoverComment; string strOldRecoverComment = DomUtil.GetAttr(nodeBorrow, "recoverComment"); if (String.IsNullOrEmpty(strOldRecoverComment) == false) strText = "(借阅时原注: " + strOldRecoverComment + ") " + strRecoverComment; DomUtil.SetAttr(nodeBorrow, "recoverComment", strText); } strDeletedBorrowFrag = nodeBorrow.OuterXml; nodeBorrow.ParentNode.RemoveChild(nodeBorrow); // 获得几个查重需要的参数 XmlDocument temp = new XmlDocument(); temp.LoadXml(strDeletedBorrowFrag); string strItemBarcode = temp.DocumentElement.GetAttribute("barcode"); string strBorrowDate = temp.DocumentElement.GetAttribute("borrowDate"); string strBorrowPeriod = temp.DocumentElement.GetAttribute("borrowPeriod"); dup_reader_history = readerdom.DocumentElement.SelectSingleNode("borrowHistory/borrow[@barcode='" + strItemBarcode + "' and @borrowDate='" + strBorrowDate + "' and @borrowPeriod='" + strBorrowPeriod + "']"); } // 加入到读者记录借阅历史字段中 if (string.IsNullOrEmpty(strDeletedBorrowFrag) == false && dup_reader_history == null) { // 看看根下面是否有 borrowHistory 元素 XmlNode root = readerdom.DocumentElement.SelectSingleNode("borrowHistory"); if (root == null) { root = readerdom.CreateElement("borrowHistory"); readerdom.DocumentElement.AppendChild(root); } XmlDocumentFragment fragment = readerdom.CreateDocumentFragment(); fragment.InnerXml = strDeletedBorrowFrag; // 插入到最前面 XmlNode temp = DomUtil.InsertFirstChild(root, fragment); // 2007/6/19 if (temp != null) { // returnDate 加入还书时间 DomUtil.SetAttr(temp, "returnDate", strOperTime); // borrowOperator string strBorrowOperator = DomUtil.GetAttr(temp, "operator"); // 把原来的operator属性值复制到borrowOperator属性中 DomUtil.SetAttr(temp, "borrowOperator", strBorrowOperator); // operator 此时需要表示还书操作者了 DomUtil.SetAttr(temp, "operator", strReturnOperator); } // 如果超过100个,则删除多余的 while (root.ChildNodes.Count > 100) root.RemoveChild(root.ChildNodes[root.ChildNodes.Count - 1]); // 2007/6/19 // 增量借阅量属性值 string strBorrowCount = DomUtil.GetAttr(root, "count"); if (String.IsNullOrEmpty(strBorrowCount) == true) strBorrowCount = "1"; else { long lCount = 1; try { lCount = Convert.ToInt64(strBorrowCount); } catch { } lCount++; strBorrowCount = lCount.ToString(); } DomUtil.SetAttr(root, "count", strBorrowCount); } // 增添超期信息 string strOverdueString = DomUtil.GetElementText(domLog.DocumentElement, "overdues"); if (String.IsNullOrEmpty(strOverdueString) == false) { XmlDocumentFragment fragment = readerdom.CreateDocumentFragment(); fragment.InnerXml = strOverdueString; List<string> existing_ids = new List<string>(); // 看看根下面是否有overdues元素 XmlNode root = readerdom.DocumentElement.SelectSingleNode("overdues"); if (root == null) { root = readerdom.CreateElement("overdues"); readerdom.DocumentElement.AppendChild(root); } else { // 记载以前已经存在的 id XmlNodeList nodes = root.SelectNodes("overdue"); foreach (XmlElement node in nodes) { string strID = node.GetAttribute("id"); if (string.IsNullOrEmpty(strID) == false) existing_ids.Add(strID); } } // root.AppendChild(fragment); { // 一个一个加入,丢掉重复 id 属性值得 overdue 元素 XmlNodeList nodes = fragment.SelectNodes("overdue"); foreach (XmlElement node in nodes) { string strID = node.GetAttribute("id"); if (existing_ids.IndexOf(strID) != -1) continue; root.AppendChild(node); } } } // *** 检查册记录操作前在借的读者,是否指向另外一个读者。如果是这样,则需要事先消除相关的另一个读者记录的痕迹,也就是说相当于把相关的册给进行还书操作 string strBorrower0 = DomUtil.GetElementInnerText(itemdom.DocumentElement, "borrower"); if (string.IsNullOrEmpty(strBorrower0) == false && strBorrower0 != strReaderBarcode) { string strRemovedInfo = ""; // 去除读者记录侧的借阅信息链条 // return: // -1 出错 // 0 没有必要修复 // 1 修复成功 nRet = RemoveReaderSideLink( // Channels, channel, strBorrower0, strItemBarcodeParam, out strRemovedInfo, out strError); if (nRet == -1) { this.WriteErrorLog("册条码号为 '" + strItemBarcodeParam + "' 的册记录,在进行还书操作(拟被读者 '" + strReaderBarcode + "' 借阅)以前,发现它被另一读者 '" + strBorrower0 + "' 持有,软件尝试自动修正(删除)此读者记录的半侧借阅信息链。不过,在去除读者记录册借阅链时发生错误: " + strError); } else { this.WriteErrorLog("册条码号为 '" + strItemBarcodeParam + "' 的册记录,在进行还书操作(拟被读者 '" + strReaderBarcode + "' 借阅)以前,发现它被另一读者 '" + strBorrower0 + "' 持有,软件已经自动修正(删除)了此读者记录的半侧借阅信息链。被移走的片断 XML 信息为 '" + strRemovedInfo + "'"); } } // *** 修改册记录 XmlElement nodeHistoryBorrower = null; string strBorrower = DomUtil.GetElementText(itemdom.DocumentElement, "borrower"); XmlNode dup_item_history = null; // 看看相同借者、借阅日期、换回日期的 BorrowHistory/borrower 元素是否已经存在 { string strBorrowDate = DomUtil.GetElementText(itemdom.DocumentElement, "borrowDate"); dup_item_history = itemdom.DocumentElement.SelectSingleNode("borrowHistory/borrower[@barcode='" + strBorrower + "' and @borrowDate='" + strBorrowDate + "' and @returnDate='" + strOperTime + "']"); } if (dup_item_history != null) { // 历史信息节点已经存在,就不必加入了 // 清空相关元素 DomUtil.DeleteElement(itemdom.DocumentElement, "borrower"); DomUtil.DeleteElement(itemdom.DocumentElement, "borrowDate"); DomUtil.DeleteElement(itemdom.DocumentElement, "returningDate"); DomUtil.DeleteElement(itemdom.DocumentElement, "borrowPeriod"); DomUtil.DeleteElement(itemdom.DocumentElement, "operator"); DomUtil.DeleteElement(itemdom.DocumentElement, "no"); DomUtil.DeleteElement(itemdom.DocumentElement, "renewComment"); } else { // 加入历史信息节点 // TODO: 也可从 domLog 中取得信息,创建 borrowHistory 下级事项。但要防范重复加入的情况 // 这里判断册记录中 borrower 元素是否为空的做法,具有可以避免重复加入 borrowHistory 下级事项的优点 if (string.IsNullOrEmpty(strBorrower) == false) { // 加入到借阅历史字段中 { // 看看根下面是否有borrowHistory元素 XmlNode root = itemdom.DocumentElement.SelectSingleNode("borrowHistory"); if (root == null) { root = itemdom.CreateElement("borrowHistory"); itemdom.DocumentElement.AppendChild(root); } nodeHistoryBorrower = itemdom.CreateElement("borrower"); // 插入到最前面 nodeHistoryBorrower = DomUtil.InsertFirstChild(root, nodeHistoryBorrower) as XmlElement; // 2015/1/12 增加等号左边的部分 // 如果超过100个,则删除多余的 while (root.ChildNodes.Count > 100) root.RemoveChild(root.ChildNodes[root.ChildNodes.Count - 1]); } #if NO DomUtil.SetAttr(nodeOldBorrower, "barcode", DomUtil.GetElementText(itemdom.DocumentElement, "borrower")); DomUtil.SetElementText(itemdom.DocumentElement, "borrower", ""); #endif LibraryServerUtil.SetAttribute(ref itemdom, "borrower", nodeHistoryBorrower, "barcode", true); #if NO DomUtil.SetAttr(nodeOldBorrower, "borrowDate", DomUtil.GetElementText(itemdom.DocumentElement, "borrowDate")); DomUtil.SetElementText(itemdom.DocumentElement, "borrowDate", ""); #endif LibraryServerUtil.SetAttribute(ref itemdom, "borrowDate", nodeHistoryBorrower, "borrowDate", true); #if NO DomUtil.SetAttr(nodeOldBorrower, "returningDate", DomUtil.GetElementText(itemdom.DocumentElement, "returningDate")); DomUtil.SetElementText(itemdom.DocumentElement, "returningDate", ""); #endif LibraryServerUtil.SetAttribute(ref itemdom, "returningDate", nodeHistoryBorrower, "returningDate", true); #if NO DomUtil.SetAttr(nodeOldBorrower, "borrowPeriod", DomUtil.GetElementText(itemdom.DocumentElement, "borrowPeriod")); DomUtil.SetElementText(itemdom.DocumentElement, "borrowPeriod", ""); #endif LibraryServerUtil.SetAttribute(ref itemdom, "borrowPeriod", nodeHistoryBorrower, "borrowPeriod", true); // borrowOperator #if NO DomUtil.SetAttr(nodeOldBorrower, "borrowOperator", DomUtil.GetElementText(itemdom.DocumentElement, "operator")); DomUtil.SetElementText(itemdom.DocumentElement, "operator", ""); #endif LibraryServerUtil.SetAttribute(ref itemdom, "operator", nodeHistoryBorrower, "borrowOperator", true); // operator 本次还书的操作者 DomUtil.SetAttr(nodeHistoryBorrower, "operator", strReturnOperator); DomUtil.SetAttr(nodeHistoryBorrower, "returnDate", strOperTime); // TODO: 0 需要省略 #if NO DomUtil.SetAttr(nodeOldBorrower, "no", DomUtil.GetElementText(itemdom.DocumentElement, "no")); DomUtil.DeleteElement(itemdom.DocumentElement, "no"); #endif LibraryServerUtil.SetAttribute(ref itemdom, "no", nodeHistoryBorrower, "no", true); // renewComment #if NO { string strTemp = DomUtil.GetElementText(itemdom.DocumentElement, "renewComment"); if (string.IsNullOrEmpty(strTemp) == true) strTemp = null; DomUtil.SetAttr(nodeOldBorrower, "renewComment", strTemp); DomUtil.DeleteElement(itemdom.DocumentElement, "renewComment"); } #endif LibraryServerUtil.SetAttribute(ref itemdom, "renewComment", nodeHistoryBorrower, "renewComment", true); { string strText = strRecoverComment; string strOldRecoverComment = DomUtil.GetElementText(itemdom.DocumentElement, "recoverComment"); if (String.IsNullOrEmpty(strOldRecoverComment) == false) strText = "(借阅时原注: " + strOldRecoverComment + ") " + strRecoverComment; if (String.IsNullOrEmpty(strText) == false) { DomUtil.SetAttr(nodeHistoryBorrower, "recoverComment", strText); } } } if (strAction == "lost") { // 修改册记录的<state> string strState = DomUtil.GetElementText(itemdom.DocumentElement, "state"); if (nodeHistoryBorrower != null) { DomUtil.SetAttr(nodeHistoryBorrower, "state", strState); } if (String.IsNullOrEmpty(strState) == false) strState += ","; strState += "丢失"; DomUtil.SetElementText(itemdom.DocumentElement, "state", strState); // 将日志记录中的<lostComment>内容追加写入册记录的<comment>中 string strLostComment = DomUtil.GetElementText(domLog.DocumentElement, "lostComment"); if (strLostComment != "") { string strComment = DomUtil.GetElementText(itemdom.DocumentElement, "comment"); if (nodeHistoryBorrower != null) { DomUtil.SetAttr(nodeHistoryBorrower, "comment", strComment); } if (String.IsNullOrEmpty(strComment) == false) strComment += "\r\n"; strComment += strLostComment; DomUtil.SetElementText(itemdom.DocumentElement, "comment", strComment); } } } return 0; } #endregion // SetEntities() API 恢复动作 /* 日志记录格式 <root> <operation>setEntity</operation> 操作类型 <action>new</action> 具体动作。有new change delete 3种。2019/7/30 增加 transfer,transfer 行为和 change 相似 <style>...</style> 风格。有force nocheckdup noeventlog 3种 <record recPath='中文图书实体/3'><root><parent>2</parent><barcode>0000003</barcode><state>状态2</state><location>阅览室</location><price></price><bookType>教学参考</bookType><registerNo></registerNo><comment>test</comment><mergeComment></mergeComment><batchNo>111</batchNo><borrower></borrower><borrowDate></borrowDate><borrowPeriod></borrowPeriod></root></record> 记录体 <oldRecord recPath='中文图书实体/3'>...</oldRecord> 被覆盖或者删除的记录 动作为change和delete时具备此元素 <operator>test</operator> 操作者 <operTime>Fri, 08 Dec 2006 08:41:46 GMT</operTime> 操作时间 </root> 注:1) 当<action>为delete时,没有<record>元素。为new时,没有<oldRecord>元素。 2) <record>中的内容, 涉及到流通的<borrower><borrowDate><borrowPeriod>等, 在日志恢复阶段, 都应当无效, 这几个内容应当从当前位置库中记录获取, 和<record>中其他内容合并后, 再写入数据库 3) 一次SetEntities()API调用, 可能创建多条日志记录。 * */ // TODO: 要兑现style中force nocheckdup功能 public int RecoverSetEntity( RmsChannelCollection Channels, RecoverLevel level, XmlDocument domLog, out string strError) { strError = ""; long lRet = 0; int nRet = 0; RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } bool bReuse = false; // 是否能够不顾 RecoverLevel 状态而重用部分代码 DO_SNAPSHOT: string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); // 快照恢复 if (level == RecoverLevel.Snapshot || bReuse == true) { byte[] timestamp = null; byte[] output_timestamp = null; string strOutputPath = ""; if (strAction == "new" || strAction == "change" || strAction == "transfer" || strAction == "setuid" || strAction == "move") { XmlNode node = null; string strRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out node); if (node == null) { strError = "日志记录中缺<record>元素"; return -1; } string strNewRecPath = DomUtil.GetAttr(node, "recPath"); // string strOldRecord = ""; string strOldRecPath = ""; if (strAction == "move") { strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } strOldRecPath = DomUtil.GetAttr(node, "recPath"); } // 写册记录 lRet = channel.DoSaveTextRes(strNewRecPath, strRecord, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入册记录 '" + strNewRecPath + "' 时发生错误: " + strError; return -1; } if (strAction == "move") { // 删除册记录 int nRedoCount = 0; REDO_DELETE: lRet = channel.DoDeleteRes(strOldRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) return 0; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoCount < 10) { timestamp = output_timestamp; nRedoCount++; goto REDO_DELETE; } } strError = "删除册记录 '" + strOldRecPath + "' 时发生错误: " + strError; return -1; } } } else if (strAction == "delete") { string strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out XmlNode node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } string strRecPath = DomUtil.GetAttr(node, "recPath"); int nRedoCount = 0; REDO: // 删除册记录 lRet = channel.DoDeleteRes(strRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) return 0; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoCount < 10) { timestamp = output_timestamp; nRedoCount++; goto REDO; } } strError = "删除册记录 '" + strRecPath + "' 时发生错误: " + strError; return -1; } } else { strError = "无法识别的<action>内容 '" + strAction + "'"; return -1; } return 0; } bool bForce = false; // bool bNoCheckDup = false; string strStyle = DomUtil.GetElementText(domLog.DocumentElement, "style"); if (StringUtil.IsInList("force", strStyle) == true) bForce = true; //if (StringUtil.IsInList("nocheckdup", strStyle) == true) // bNoCheckDup = true; // 逻辑恢复或者混合恢复 if (level == RecoverLevel.Logic || level == RecoverLevel.LogicAndSnapshot) { // 和数据库中已有记录合并,然后保存 if (strAction == "new" || strAction == "change" || strAction == "transfer" || strAction == "setuid" || strAction == "move") { string strRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out XmlNode node); if (node == null) { strError = "日志记录中缺<record>元素"; return -1; } string strNewRecPath = DomUtil.GetAttr(node, "recPath"); // string strOldRecord = ""; string strOldRecPath = ""; if (strAction == "move") { strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } strOldRecPath = DomUtil.GetAttr(node, "recPath"); } // 读出数据库中原有的记录 string strExistXml = ""; string strMetaData = ""; byte[] exist_timestamp = null; string strOutputPath = ""; if ((strAction == "change" || strAction == "transfer" || strAction == "setuid" || strAction == "move") && bForce == false) // 2008/10/6 { string strSourceRecPath = ""; if (strAction == "change" || strAction == "transfer" || strAction == "setuid") strSourceRecPath = strNewRecPath; if (strAction == "move") strSourceRecPath = strOldRecPath; lRet = channel.GetRes(strSourceRecPath, out strExistXml, out strMetaData, out exist_timestamp, out strOutputPath, out strError); if (lRet == -1) { // 容错 if (channel.ErrorCode == ChannelErrorCode.NotFound && level == RecoverLevel.LogicAndSnapshot) { // 如果记录不存在, 则构造一条空的记录 // bExist = false; strExistXml = "<root />"; exist_timestamp = null; } else { strError = "在读入原有记录 '" + strNewRecPath + "' 时失败: " + strError; goto ERROR1; } } } // // 把两个记录装入DOM XmlDocument domExist = new XmlDocument(); XmlDocument domNew = new XmlDocument(); try { // 防范空记录 if (String.IsNullOrEmpty(strExistXml) == true) strExistXml = "<root />"; domExist.LoadXml(strExistXml); } catch (Exception ex) { strError = "strExistXml装载进入DOM时发生错误: " + ex.Message; goto ERROR1; } try { domNew.LoadXml(strRecord); } catch (Exception ex) { strError = "strRecord装载进入DOM时发生错误: " + ex.Message; goto ERROR1; } // 合并新旧记录 string strNewXml = ""; if (bForce == false) { // 2020/10/12 string[] elements = null; if (strAction == "transfer") elements = transfer_entity_element_names; else if (strAction == "setuid") elements = setuid_entity_element_names; nRet = MergeTwoEntityXml(domExist, domNew, elements, // strAction == "transfer" ? transfer_entity_element_names : null, false, out strNewXml, out strError); if (nRet == -1) goto ERROR1; } else { strNewXml = domNew.OuterXml; } // 保存新记录 byte[] output_timestamp = null; if (strAction == "move") { // 复制源记录到目标位置,然后自动删除源记录 // 但是尚未在目标位置写入最新内容 lRet = channel.DoCopyRecord(strOldRecPath, strNewRecPath, true, // bDeleteSourceRecord out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; exist_timestamp = output_timestamp; // 及时更新时间戳 } lRet = channel.DoSaveTextRes(strNewRecPath, strNewXml, false, // include preamble? "content,ignorechecktimestamp", exist_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; /* if (strAction == "move") { // 删除册记录 int nRedoCount = 0; byte[] timestamp = null; REDO_DELETE: lRet = channel.DoDeleteRes(strOldRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) return 0; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoCount < 10) { timestamp = output_timestamp; nRedoCount++; goto REDO_DELETE; } } strError = "删除册记录 '" + strRecPath + "' 时发生错误: " + strError; return -1; } } * */ } else if (strAction == "delete") { // 和SnapShot方式相同 bReuse = true; goto DO_SNAPSHOT; } else { strError = "无法识别的 <action> 内容 '" + strAction + "'"; return -1; } } // 容错恢复 if (level == RecoverLevel.Robust) { if (strAction == "move") { strError = "暂不支持SetEntity的move恢复操作"; return -1; } // 和数据库中已有记录合并,然后保存 if (strAction == "change" || strAction == "transfer" || strAction == "setuid" || strAction == "new") { string strRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out XmlNode node); if (node == null) { strError = "日志记录中缺<record>元素"; return -1; } // 取得日志记录中声称的新记录路径。不能轻易相信这个路径。 string strNewRecPath = DomUtil.GetAttr(node, "recPath"); // string strOldRecord = ""; string strOldRecPath = ""; string strOldItemBarcode = ""; string strNewItemBarcode = ""; string strExistXml = ""; byte[] exist_timestamp = null; // 日志记录中记载的旧记录体 strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { if (strAction == "change" || strAction == "transfer" || strAction == "setuid") { strError = "日志记录中缺<oldRecord>元素"; return -1; } } // 日志记录中声称的旧记录路径。不能轻易相信这个路径。 if (node != null) strOldRecPath = DomUtil.GetAttr(node, "recPath"); // 从日志记录中记载的旧记录体中,获得旧记录册条码号 if (String.IsNullOrEmpty(strOldRecord) == false) { nRet = GetItemBarcode(strOldRecord, out strOldItemBarcode, out strError); } nRet = GetItemBarcode(strRecord, out strNewItemBarcode, out strError); // TODO: 需要检查新旧记录中,<barcode>是否一致?如果不一致,则需要对新条码号进行查重? if (strAction == "new" && strOldItemBarcode == "") { if (String.IsNullOrEmpty(strNewItemBarcode) == true) { strError = "因为拟新创建的记录内容中没有包含册条码号,所以new操作被放弃"; return -1; } strOldItemBarcode = strNewItemBarcode; } // 如果有旧记录的册条码号,则需要从数据库中提取最新鲜的旧记录 // (如果没有旧记录的册条码号,则依日志记录中的旧记录) if (String.IsNullOrEmpty(strOldItemBarcode) == false) { string strOutputItemRecPath = ""; // 从册条码号获得册记录 // 获得册记录 // return: // -1 error // 0 not found // 1 命中1条 // >1 命中多于1条 nRet = this.GetItemRecXml( // Channels, channel, strOldItemBarcode, out strExistXml, 100, out List<string> aPath, out exist_timestamp, out strError); if (nRet == 0 || nRet == -1) { if (strAction == "change" || strAction == "transfer" || strAction == "setuid") { /* // 从库中没有找到,只好依日志记录中记载的旧记录 strExistXml = strOldRecord; * */ strExistXml = ""; // 需要创建一条新记录。strOldRecPath中的路径似乎也可以用,但是要严格检查这个路径是否已经存在记录 -- 只能在这里位置不存在记录时才能用。既然如此麻烦,那就不如纯粹用一个新位置 strOutputItemRecPath = ResPath.GetDbName(strOldRecPath) + "/?"; } else { Debug.Assert(strAction == "new", ""); strExistXml = ""; strOutputItemRecPath = ResPath.GetDbName(strNewRecPath) + "/?"; } } else { // 找到一条或者多条旧记录 Debug.Assert(aPath != null && aPath.Count >= 1, ""); bool bNeedReload = false; if (aPath.Count == 1) { Debug.Assert(nRet == 1, ""); strOutputItemRecPath = aPath[0]; // 是否需要重新装载? bNeedReload = false; // 所取得的第一个路径,其记录已经装载 } else { // 多条 Debug.Assert(aPath.Count > 1, ""); /// // 建议根据strOldRecPath来进行挑选 if (String.IsNullOrEmpty(strOldRecPath) == true) { // 空,无法挑选 // 容错! strOutputItemRecPath = aPath[0]; // 是否需要重新装载? bNeedReload = false; // 所取得的第一个路径,其记录已经装载 } else { ///// nRet = aPath.IndexOf(strOldRecPath); if (nRet != -1) { // 选中 strOutputItemRecPath = aPath[nRet]; // 是否需要重新装载? if (nRet != 0) bNeedReload = true; // 第一个以外的路径才需要装载 } else { // 没有选中,只好依第一个 // 容错 strOutputItemRecPath = aPath[0]; // 是否需要重新装载? bNeedReload = false; // 所取得的第一个路径,其记录已经装载 } } /// } // 重新装载 if (bNeedReload == true) { lRet = channel.GetRes(strOutputItemRecPath, out strExistXml, out string strMetaData, out exist_timestamp, out strOutputItemRecPath, out strError); if (lRet == -1) { strError = "根据strOutputItemRecPath '" + strOutputItemRecPath + "' 重新获得册记录失败: " + strError; return -1; } // 需要检查记录中的<barcode>元素值是否匹配册条码号 } } // 修正strOldRecPath if (strOutputItemRecPath != "") strOldRecPath = strOutputItemRecPath; else strOldRecPath = ""; // 破坏掉,以免后面被用 strNewRecPath = strOutputItemRecPath; } // end if 如果有旧记录的册条码号 else { // (如果没有旧记录的册条码号,则依日志记录中的旧记录) // 但无法确定旧记录的路径。也就无法确定覆盖位置。因此建议放弃这种特定的“修改操作”。 strError = "因为日志记录中没有记载旧记录条码号,因此无法确定记录位置,因此change操作被放弃"; return -1; } if (strAction == "change" || strAction == "transfer" || strAction == "setuid") { if (strNewItemBarcode != "" && strNewItemBarcode != strOldItemBarcode) { // 新旧记录的条码号不一致,需要对新条码号进行查重 // 获得册记录 // return: // -1 error // 0 not found // 1 命中1条 // >1 命中多于1条 nRet = this.GetItemRecXml( // Channels, channel, strNewItemBarcode, out string strTempXml, 100, out List<string> aPath, out byte[] temp_timestamp, out strError); if (nRet > 0) { // 有重复,取其第一条,作为老记录进行合并,并保存回这条的位置 strNewRecPath = aPath[0]; exist_timestamp = temp_timestamp; strExistXml = strTempXml; } } } // 把两个记录装入DOM XmlDocument domExist = new XmlDocument(); XmlDocument domNew = new XmlDocument(); try { // 防范空记录 if (String.IsNullOrEmpty(strExistXml) == true) strExistXml = "<root />"; domExist.LoadXml(strExistXml); } catch (Exception ex) { strError = "strExistXml装载进入DOM时发生错误: " + ex.Message; goto ERROR1; } try { domNew.LoadXml(strRecord); } catch (Exception ex) { strError = "strRecord装载进入DOM时发生错误: " + ex.Message; goto ERROR1; } // 合并新旧记录 string strNewXml = ""; if (bForce == false) { // 2020/10/12 string[] elements = null; if (strAction == "transfer") elements = transfer_entity_element_names; else if (strAction == "setuid") elements = setuid_entity_element_names; nRet = MergeTwoEntityXml(domExist, domNew, elements, // strAction == "transfer" ? transfer_entity_element_names : null, false, out strNewXml, out strError); if (nRet == -1) goto ERROR1; } else { strNewXml = domNew.OuterXml; } // 保存新记录 byte[] output_timestamp = null; string strOutputPath = ""; if (strAction == "move") { // 复制源记录到目标位置,然后自动删除源记录 // 但是尚未在目标位置写入最新内容 lRet = channel.DoCopyRecord(strOldRecPath, strNewRecPath, true, // bDeleteSourceRecord out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; exist_timestamp = output_timestamp; // 及时更新时间戳 } /* // 测试 { string strRecID = ResPath.GetRecordId(strNewRecPath); if (strRecID != "?") { try { long id = Convert.ToInt64(strRecID); if (id > 150848) { Debug.Assert(false, "id超过尾部"); } } catch { } } } * */ lRet = channel.DoSaveTextRes(strNewRecPath, strNewXml, false, // include preamble? "content,ignorechecktimestamp", exist_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; } else if (strAction == "delete") { string strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out XmlNode node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } string strRecPath = DomUtil.GetAttr(node, "recPath"); nRet = GetItemBarcode(strOldRecord, out string strOldItemBarcode, out strError); if (String.IsNullOrEmpty(strOldItemBarcode) == true) { strError = "因为日志记录中的旧记录中缺乏非空的<barcode>内容,所以无法进行依据条码号定位的删除,delete操作被放弃"; return -1; } string strOutputItemRecPath = ""; // 从册条码号获得册记录 // 获得册记录 // return: // -1 error // 0 not found // 1 命中1条 // >1 命中多于1条 nRet = this.GetItemRecXml( // Channels, channel, strOldItemBarcode, out string strExistXml, 100, out List<string> aPath, out byte[] exist_timestamp, out strError); if (nRet == -1) return -1; if (nRet == 0) { // 本来就不存在 return 0; } if (nRet >= 1) { /// // 找到一条或者多条旧记录 Debug.Assert(aPath != null && aPath.Count >= 1, ""); bool bNeedReload = false; if (aPath.Count == 1) { Debug.Assert(nRet == 1, ""); /* strOutputItemRecPath = aPath[0]; // 是否需要重新装载? bNeedReload = false; // 所取得的第一个路径,其记录已经装载 * */ strError = "册条码号 " + strOldItemBarcode + " 目前仅有唯一一条记录,放弃删除"; return -1; } else { // 多条 Debug.Assert(aPath.Count > 1, ""); /// // 建议根据strRecPath来进行挑选 if (String.IsNullOrEmpty(strRecPath) == true) { strError = "册条码号 '" + strOldItemBarcode + "' 命中 " + aPath.Count.ToString() + " 条记录,而<oldRecord>的recPath参数缺乏,因此无法进行精确删除,delete操作被放弃"; return -1; } else { ///// nRet = aPath.IndexOf(strRecPath); if (nRet != -1) { // 选中 strOutputItemRecPath = aPath[nRet]; // 是否需要重新装载? if (nRet != 0) bNeedReload = true; // 第一个以外的路径才需要装载 } else { strError = "册条码号 '" + strOldItemBarcode + "' 命中 " + aPath.Count.ToString() + " 条记录,虽用了(<oldRecord>元素中属性recPath的)确认路径 '" + strRecPath + "' 也无法确认出其中一条,无法精确删除,因此delete操作被放弃"; return -1; } } } /// // 重新装载 if (bNeedReload == true) { lRet = channel.GetRes(strOutputItemRecPath, out strExistXml, out string strMetaData, out exist_timestamp, out strOutputItemRecPath, out strError); if (lRet == -1) { strError = "根据strOutputItemRecPath '" + strOutputItemRecPath + "' 重新获得册记录失败: " + strError; return -1; } // 需要检查记录中的<barcode>元素值是否匹配册条码号 } } // 把两个记录装入DOM XmlDocument domExist = new XmlDocument(); try { // 防范空记录 if (String.IsNullOrEmpty(strExistXml) == true) strExistXml = "<root />"; domExist.LoadXml(strExistXml); } catch (Exception ex) { strError = "strExistXml装载进入DOM时发生错误: " + ex.Message; return -1; } bool bHasCirculationInfo = IsEntityHasCirculationInfo(domExist, out string strDetail); // 观察已经存在的记录是否有流通信息 if (bHasCirculationInfo == true && bForce == false) { strError = "拟删除的册记录 '" + strOutputItemRecPath + "' 中包含有流通信息(" + strDetail + "),不能删除。"; goto ERROR1; } int nRedoCount = 0; byte[] timestamp = exist_timestamp; byte[] output_timestamp = null; REDO: // 删除册记录 lRet = channel.DoDeleteRes(strOutputItemRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) return 0; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoCount < 10) { timestamp = output_timestamp; nRedoCount++; goto REDO; } } strError = "删除册记录 '" + strRecPath + "' 时发生错误: " + strError; return -1; } } else { strError = "无法识别的<action>内容 '" + strAction + "'"; return -1; } } return 0; ERROR1: if (level == RecoverLevel.LogicAndSnapshot) { WriteErrorLog($"RecoverSetEntity() 用 LogicAndSnapShot 方式恢复遇到报错 {strError},后面自动改用 SnapShot 方式尝试 ..."); level = RecoverLevel.Snapshot; goto DO_SNAPSHOT; } return -1; } // SetOrders() API 恢复动作 /* 日志记录格式 <root> <operation>setOrder</operation> 操作类型 <action>new</action> 具体动作。有new change delete 3种 <style>...</style> 风格。有force nocheckdup noeventlog 3种 <record recPath='中文图书订购/3'><root><parent>2</parent><barcode>0000003</barcode><state>状态2</state><location>阅览室</location><price></price><bookType>教学参考</bookType><registerNo></registerNo><comment>test</comment><mergeComment></mergeComment><batchNo>111</batchNo><borrower></borrower><borrowDate></borrowDate><borrowPeriod></borrowPeriod></root></record> 记录体 <oldRecord recPath='中文图书订购/3'>...</oldRecord> 被覆盖或者删除的记录 动作为change和delete时具备此元素 <operator>test</operator> 操作者 <operTime>Fri, 08 Dec 2006 08:41:46 GMT</operTime> 操作时间 </root> 注:1) 当<action>为delete时,没有<record>元素。为new时,没有<oldRecord>元素。 2) 一次SetOrders()API调用, 可能创建多条日志记录。 * */ // TODO: 要兑现style中force nocheckdup功能 public int RecoverSetOrder( RmsChannelCollection Channels, RecoverLevel level, XmlDocument domLog, out string strError) { strError = ""; long lRet = 0; int nRet = 0; RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } bool bReuse = false; // 是否能够不顾RecoverLevel状态而重用部分代码 DO_SNAPSHOT: string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); // 快照恢复 if (level == RecoverLevel.Snapshot || bReuse == true) { byte[] timestamp = null; byte[] output_timestamp = null; string strOutputPath = ""; if (strAction == "new" || strAction == "change" || strAction == "move") { XmlNode node = null; string strRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out node); if (node == null) { strError = "日志记录中缺<record>元素"; return -1; } string strNewRecPath = DomUtil.GetAttr(node, "recPath"); // string strOldRecord = ""; string strOldRecPath = ""; if (strAction == "move") { strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } strOldRecPath = DomUtil.GetAttr(node, "recPath"); } // 写订购记录 lRet = channel.DoSaveTextRes(strNewRecPath, strRecord, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入订购记录 '" + strNewRecPath + "' 时发生错误: " + strError; return -1; } if (strAction == "move") { // 删除订购记录 int nRedoCount = 0; REDO_DELETE: lRet = channel.DoDeleteRes(strOldRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) return 0; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoCount < 10) { timestamp = output_timestamp; nRedoCount++; goto REDO_DELETE; } } strError = "删除订购记录 '" + strOldRecPath + "' 时发生错误: " + strError; return -1; } } } else if (strAction == "delete") { XmlNode node = null; string strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } string strRecPath = DomUtil.GetAttr(node, "recPath"); int nRedoCount = 0; REDO: // 删除订购记录 lRet = channel.DoDeleteRes(strRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) return 0; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoCount < 10) { timestamp = output_timestamp; nRedoCount++; goto REDO; } } strError = "删除订购记录 '" + strRecPath + "' 时发生错误: " + strError; return -1; } } else { strError = "无法识别的<action>内容 '" + strAction + "'"; return -1; } return 0; } bool bForce = false; // bool bNoCheckDup = false; string strStyle = DomUtil.GetElementText(domLog.DocumentElement, "style"); if (StringUtil.IsInList("force", strStyle) == true) bForce = true; //if (StringUtil.IsInList("nocheckdup", strStyle) == true) // bNoCheckDup = true; // 逻辑恢复或者混合恢复或者容错恢复 if (level == RecoverLevel.Logic || level == RecoverLevel.LogicAndSnapshot || level == RecoverLevel.Robust) // 容错恢复没有单独实现 { // 和数据库中已有记录合并,然后保存 if (strAction == "new" || strAction == "change" || strAction == "move") { XmlNode node = null; string strRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out node); if (node == null) { strError = "日志记录中缺<record>元素"; return -1; } string strNewRecPath = DomUtil.GetAttr(node, "recPath"); // string strOldRecord = ""; string strOldRecPath = ""; if (strAction == "move") { strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } strOldRecPath = DomUtil.GetAttr(node, "recPath"); } // 读出数据库中原有的记录 string strExistXml = ""; string strMetaData = ""; byte[] exist_timestamp = null; string strOutputPath = ""; if ((strAction == "change" || strAction == "move") && bForce == false) { string strSourceRecPath = ""; if (strAction == "change") strSourceRecPath = strNewRecPath; if (strAction == "move") strSourceRecPath = strOldRecPath; lRet = channel.GetRes(strSourceRecPath, out strExistXml, out strMetaData, out exist_timestamp, out strOutputPath, out strError); if (lRet == -1) { // 容错 if (channel.ErrorCode == ChannelErrorCode.NotFound && level == RecoverLevel.LogicAndSnapshot) { // 如果记录不存在, 则构造一条空的记录 // bExist = false; strExistXml = "<root />"; exist_timestamp = null; } else { strError = "在读入原有记录 '" + strNewRecPath + "' 时失败: " + strError; goto ERROR1; } } } // // 把两个记录装入DOM XmlDocument domExist = new XmlDocument(); XmlDocument domNew = new XmlDocument(); try { // 防范空记录 if (String.IsNullOrEmpty(strExistXml) == true) strExistXml = "<root />"; domExist.LoadXml(strExistXml); } catch (Exception ex) { strError = "strExistXml装载进入DOM时发生错误: " + ex.Message; goto ERROR1; } try { domNew.LoadXml(strRecord); } catch (Exception ex) { strError = "strRecord 装载进入 DOM 时发生错误: " + ex.Message; goto ERROR1; } // 合并新旧记录 string strNewXml = ""; if (bForce == false) { // 模拟一个 SessionInfo string strLibraryCode = DomUtil.GetElementText(domLog.DocumentElement, "libraryCode"); string strOperator = DomUtil.GetElementText(domLog.DocumentElement, "operator"); SessionInfo temp_sessioninfo = new SessionInfo(this); temp_sessioninfo.Account = new Account(); temp_sessioninfo.Account.AccountLibraryCode = strLibraryCode; temp_sessioninfo.Account.UserID = strOperator; nRet = this.OrderItemDatabase.MergeTwoItemXml( temp_sessioninfo, domExist, domNew, out strNewXml, out strError); if (nRet == -1) goto ERROR1; } else { strNewXml = domNew.OuterXml; } // 保存新记录 byte[] output_timestamp = null; if (strAction == "move") { // 复制源记录到目标位置,然后自动删除源记录 // 但是尚未在目标位置写入最新内容 lRet = channel.DoCopyRecord(strOldRecPath, strNewRecPath, true, // bDeleteSourceRecord out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; exist_timestamp = output_timestamp; // 及时更新时间戳 } lRet = channel.DoSaveTextRes(strNewRecPath, strNewXml, false, // include preamble? "content,ignorechecktimestamp", exist_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; } else if (strAction == "delete") { // 和SnapShot方式相同 bReuse = true; goto DO_SNAPSHOT; } else { strError = "无法识别的<action>内容 '" + strAction + "'"; return -1; } } return 0; ERROR1: if (level == RecoverLevel.LogicAndSnapshot) { WriteErrorLog($"RecoverSetOrder() 用 LogicAndSnapShot 方式恢复遇到报错 {strError},后面自动改用 SnapShot 方式尝试 ..."); level = RecoverLevel.Snapshot; goto DO_SNAPSHOT; } return -1; } // SetIssues() API 恢复动作 /* 日志记录格式 <root> <operation>setIssue</operation> 操作类型 <action>new</action> 具体动作。有new change delete 3种 <style>...</style> 风格。有force nocheckdup noeventlog 3种 <record recPath='中文期刊期/3'><root><parent>2</parent><barcode>0000003</barcode><state>状态2</state><location>阅览室</location><price></price><bookType>教学参考</bookType><registerNo></registerNo><comment>test</comment><mergeComment></mergeComment><batchNo>111</batchNo><borrower></borrower><borrowDate></borrowDate><borrowPeriod></borrowPeriod></root></record> 记录体 <oldRecord recPath='中文期刊期/3'>...</oldRecord> 被覆盖或者删除的记录 动作为change和delete时具备此元素 <operator>test</operator> 操作者 <operTime>Fri, 08 Dec 2006 08:41:46 GMT</operTime> 操作时间 </root> 注:1) 当<action>为delete时,没有<record>元素。为new时,没有<oldRecord>元素。 2) 一次SetIssues()API调用, 可能创建多条日志记录。 * */ // TODO: 要兑现style中force nocheckdup功能 public int RecoverSetIssue( RmsChannelCollection Channels, RecoverLevel level, XmlDocument domLog, out string strError) { strError = ""; long lRet = 0; int nRet = 0; RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } bool bReuse = false; // 是否能够不顾RecoverLevel状态而重用部分代码 DO_SNAPSHOT: string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); // 快照恢复 if (level == RecoverLevel.Snapshot || bReuse == true) { byte[] timestamp = null; byte[] output_timestamp = null; string strOutputPath = ""; if (strAction == "new" || strAction == "change" || strAction == "move") { XmlNode node = null; string strRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out node); if (node == null) { strError = "日志记录中缺<record>元素"; return -1; } string strNewRecPath = DomUtil.GetAttr(node, "recPath"); // string strOldRecord = ""; string strOldRecPath = ""; if (strAction == "move") { strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } strOldRecPath = DomUtil.GetAttr(node, "recPath"); } // 写期记录 lRet = channel.DoSaveTextRes(strNewRecPath, strRecord, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入期记录 '" + strNewRecPath + "' 时发生错误: " + strError; return -1; } if (strAction == "move") { // 删除期记录 int nRedoCount = 0; REDO_DELETE: lRet = channel.DoDeleteRes(strOldRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) return 0; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoCount < 10) { timestamp = output_timestamp; nRedoCount++; goto REDO_DELETE; } } strError = "删除期记录 '" + strOldRecPath + "' 时发生错误: " + strError; return -1; } } } else if (strAction == "delete") { XmlNode node = null; string strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } string strRecPath = DomUtil.GetAttr(node, "recPath"); int nRedoCount = 0; REDO: // 删除期记录 lRet = channel.DoDeleteRes(strRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) return 0; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoCount < 10) { timestamp = output_timestamp; nRedoCount++; goto REDO; } } strError = "删除期记录 '" + strRecPath + "' 时发生错误: " + strError; return -1; } } else { strError = "无法识别的<action>内容 '" + strAction + "'"; return -1; } return 0; } bool bForce = false; // bool bNoCheckDup = false; string strStyle = DomUtil.GetElementText(domLog.DocumentElement, "style"); if (StringUtil.IsInList("force", strStyle) == true) bForce = true; //if (StringUtil.IsInList("nocheckdup", strStyle) == true) // bNoCheckDup = true; // 逻辑恢复或者混合恢复或者容错恢复 if (level == RecoverLevel.Logic || level == RecoverLevel.LogicAndSnapshot || level == RecoverLevel.Robust) // 容错恢复没有单独实现 { // 和数据库中已有记录合并,然后保存 if (strAction == "new" || strAction == "change" || strAction == "move") { XmlNode node = null; string strRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out node); if (node == null) { strError = "日志记录中缺<record>元素"; return -1; } string strNewRecPath = DomUtil.GetAttr(node, "recPath"); // string strOldRecord = ""; string strOldRecPath = ""; if (strAction == "move") { strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } strOldRecPath = DomUtil.GetAttr(node, "recPath"); } // 读出数据库中原有的记录 string strExistXml = ""; string strMetaData = ""; byte[] exist_timestamp = null; string strOutputPath = ""; if ((strAction == "change" || strAction == "move") && bForce == false) { string strSourceRecPath = ""; if (strAction == "change") strSourceRecPath = strNewRecPath; if (strAction == "move") strSourceRecPath = strOldRecPath; lRet = channel.GetRes(strSourceRecPath, out strExistXml, out strMetaData, out exist_timestamp, out strOutputPath, out strError); if (lRet == -1) { // 容错 if (channel.ErrorCode == ChannelErrorCode.NotFound && level == RecoverLevel.LogicAndSnapshot) { // 如果记录不存在, 则构造一条空的记录 // bExist = false; strExistXml = "<root />"; exist_timestamp = null; } else { strError = "在读入原有记录 '" + strNewRecPath + "' 时失败: " + strError; goto ERROR1; } } } // // 把两个记录装入DOM XmlDocument domExist = new XmlDocument(); XmlDocument domNew = new XmlDocument(); try { // 防范空记录 if (String.IsNullOrEmpty(strExistXml) == true) strExistXml = "<root />"; domExist.LoadXml(strExistXml); } catch (Exception ex) { strError = "strExistXml装载进入DOM时发生错误: " + ex.Message; goto ERROR1; } try { domNew.LoadXml(strRecord); } catch (Exception ex) { strError = "strRecord装载进入DOM时发生错误: " + ex.Message; goto ERROR1; } // 合并新旧记录 string strNewXml = ""; if (bForce == false) { // 模拟一个 SessionInfo string strLibraryCode = DomUtil.GetElementText(domLog.DocumentElement, "libraryCode"); string strOperator = DomUtil.GetElementText(domLog.DocumentElement, "operator"); SessionInfo temp_sessioninfo = new SessionInfo(this); temp_sessioninfo.Account = new Account(); temp_sessioninfo.Account.AccountLibraryCode = strLibraryCode; temp_sessioninfo.Account.UserID = strOperator; nRet = this.IssueItemDatabase.MergeTwoItemXml( temp_sessioninfo, domExist, domNew, out strNewXml, out strError); if (nRet == -1) goto ERROR1; } else { strNewXml = domNew.OuterXml; } // 保存新记录 byte[] output_timestamp = null; if (strAction == "move") { // 复制源记录到目标位置,然后自动删除源记录 // 但是尚未在目标位置写入最新内容 lRet = channel.DoCopyRecord(strOldRecPath, strNewRecPath, true, // bDeleteSourceRecord out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; exist_timestamp = output_timestamp; // 及时更新时间戳 } lRet = channel.DoSaveTextRes(strNewRecPath, strNewXml, false, // include preamble? "content,ignorechecktimestamp", exist_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; } else if (strAction == "delete") { // 和SnapShot方式相同 bReuse = true; goto DO_SNAPSHOT; } else { strError = "无法识别的<action>内容 '" + strAction + "'"; return -1; } } return 0; ERROR1: if (level == RecoverLevel.LogicAndSnapshot) { WriteErrorLog($"RecoverSetIssue() 用 LogicAndSnapShot 方式恢复遇到报错 {strError},后面自动改用 SnapShot 方式尝试 ..."); level = RecoverLevel.Snapshot; goto DO_SNAPSHOT; } return -1; } // SetComments() API 恢复动作 /* 日志记录格式 <root> <operation>setComment</operation> 操作类型 <action>new</action> 具体动作。有new change delete 3种 <style>...</style> 风格。有force nocheckdup noeventlog 3种 <record recPath='中文图书评注/3'>...</record> 记录体 <oldRecord recPath='中文图书评注/3'>...</oldRecord> 被覆盖或者删除的记录 动作为change和delete时具备此元素 <operator>test</operator> 操作者 <operTime>Fri, 08 Dec 2006 08:41:46 GMT</operTime> 操作时间 </root> 注:1) 当<action>为delete时,没有<record>元素。为new时,没有<oldRecord>元素。 2) 一次SetComments()API调用, 可能创建多条日志记录。 * */ // TODO: 要兑现style中force nocheckdup功能 public int RecoverSetComment( RmsChannelCollection Channels, RecoverLevel level, XmlDocument domLog, out string strError) { strError = ""; long lRet = 0; int nRet = 0; RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } bool bReuse = false; // 是否能够不顾RecoverLevel状态而重用部分代码 DO_SNAPSHOT: string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); // 快照恢复 if (level == RecoverLevel.Snapshot || bReuse == true) { byte[] timestamp = null; byte[] output_timestamp = null; string strOutputPath = ""; if (strAction == "new" || strAction == "change" || strAction == "move") { XmlNode node = null; string strRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out node); if (node == null) { strError = "日志记录中缺<record>元素"; return -1; } string strNewRecPath = DomUtil.GetAttr(node, "recPath"); // string strOldRecord = ""; string strOldRecPath = ""; if (strAction == "move") { strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } strOldRecPath = DomUtil.GetAttr(node, "recPath"); } // 写评注记录 lRet = channel.DoSaveTextRes(strNewRecPath, strRecord, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入评注记录 '" + strNewRecPath + "' 时发生错误: " + strError; return -1; } if (strAction == "move") { // 删除评注记录 int nRedoCount = 0; REDO_DELETE: lRet = channel.DoDeleteRes(strOldRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) return 0; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoCount < 10) { timestamp = output_timestamp; nRedoCount++; goto REDO_DELETE; } } strError = "删除评注记录 '" + strOldRecPath + "' 时发生错误: " + strError; return -1; } } } else if (strAction == "delete") { XmlNode node = null; string strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } string strRecPath = DomUtil.GetAttr(node, "recPath"); int nRedoCount = 0; REDO: // 删除评注记录 lRet = channel.DoDeleteRes(strRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) return 0; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoCount < 10) { timestamp = output_timestamp; nRedoCount++; goto REDO; } } strError = "删除评注记录 '" + strRecPath + "' 时发生错误: " + strError; return -1; } } else { strError = "无法识别的<action>内容 '" + strAction + "'"; return -1; } return 0; } bool bForce = false; // bool bNoCheckDup = false; string strStyle = DomUtil.GetElementText(domLog.DocumentElement, "style"); if (StringUtil.IsInList("force", strStyle) == true) bForce = true; //if (StringUtil.IsInList("nocheckdup", strStyle) == true) // bNoCheckDup = true; // 逻辑恢复或者混合恢复或者容错恢复 if (level == RecoverLevel.Logic || level == RecoverLevel.LogicAndSnapshot || level == RecoverLevel.Robust) // 容错恢复没有单独实现 { // 和数据库中已有记录合并,然后保存 if (strAction == "new" || strAction == "change" || strAction == "move") { XmlNode node = null; string strRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out node); if (node == null) { strError = "日志记录中缺<record>元素"; return -1; } string strNewRecPath = DomUtil.GetAttr(node, "recPath"); // string strOldRecord = ""; string strOldRecPath = ""; if (strAction == "move") { strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } strOldRecPath = DomUtil.GetAttr(node, "recPath"); } // 读出数据库中原有的记录 string strExistXml = ""; string strMetaData = ""; byte[] exist_timestamp = null; string strOutputPath = ""; if ((strAction == "change" || strAction == "move") && bForce == false) { string strSourceRecPath = ""; if (strAction == "change") strSourceRecPath = strNewRecPath; if (strAction == "move") strSourceRecPath = strOldRecPath; lRet = channel.GetRes(strSourceRecPath, out strExistXml, out strMetaData, out exist_timestamp, out strOutputPath, out strError); if (lRet == -1) { // 容错 if (channel.ErrorCode == ChannelErrorCode.NotFound && level == RecoverLevel.LogicAndSnapshot) { // 如果记录不存在, 则构造一条空的记录 // bExist = false; strExistXml = "<root />"; exist_timestamp = null; } else { strError = "在读入原有记录 '" + strNewRecPath + "' 时失败: " + strError; goto ERROR1; } } } // // 把两个记录装入DOM XmlDocument domExist = new XmlDocument(); XmlDocument domNew = new XmlDocument(); try { // 防范空记录 if (String.IsNullOrEmpty(strExistXml) == true) strExistXml = "<root />"; domExist.LoadXml(strExistXml); } catch (Exception ex) { strError = "strExistXml装载进入DOM时发生错误: " + ex.Message; goto ERROR1; } try { domNew.LoadXml(strRecord); } catch (Exception ex) { strError = "strRecord装载进入DOM时发生错误: " + ex.Message; goto ERROR1; } // 合并新旧记录 string strNewXml = ""; if (bForce == false) { // 模拟一个 SessionInfo string strLibraryCode = DomUtil.GetElementText(domLog.DocumentElement, "libraryCode"); string strOperator = DomUtil.GetElementText(domLog.DocumentElement, "operator"); SessionInfo temp_sessioninfo = new SessionInfo(this); temp_sessioninfo.Account = new Account(); temp_sessioninfo.Account.AccountLibraryCode = strLibraryCode; temp_sessioninfo.Account.UserID = strOperator; nRet = this.CommentItemDatabase.MergeTwoItemXml( temp_sessioninfo, domExist, domNew, out strNewXml, out strError); if (nRet == -1) goto ERROR1; } else { strNewXml = domNew.OuterXml; } // 保存新记录 byte[] output_timestamp = null; if (strAction == "move") { // 复制源记录到目标位置,然后自动删除源记录 // 但是尚未在目标位置写入最新内容 lRet = channel.DoCopyRecord(strOldRecPath, strNewRecPath, true, // bDeleteSourceRecord out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; exist_timestamp = output_timestamp; // 及时更新时间戳 } lRet = channel.DoSaveTextRes(strNewRecPath, strNewXml, false, // include preamble? "content,ignorechecktimestamp", exist_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; } else if (strAction == "delete") { // 和SnapShot方式相同 bReuse = true; goto DO_SNAPSHOT; } else { strError = "无法识别的<action>内容 '" + strAction + "'"; return -1; } } return 0; ERROR1: if (level == RecoverLevel.LogicAndSnapshot) { WriteErrorLog($"RecoverSetComment() 用 LogicAndSnapShot 方式恢复遇到报错 {strError},后面自动改用 SnapShot 方式尝试 ..."); level = RecoverLevel.Snapshot; goto DO_SNAPSHOT; } return -1; } // 读出实体记录中的<barcode>元素值 static int GetItemBarcode(string strXml, out string strItemBarcode, out string strError) { strItemBarcode = ""; strError = ""; XmlDocument dom = new XmlDocument(); try { dom.LoadXml(strXml); } catch (Exception ex) { strError = "装载XML进入DOM时发生错误: " + ex.Message; return -1; } strItemBarcode = DomUtil.GetElementText(dom.DocumentElement, "barcode"); return 1; } // ChangeReaderPassword() API 恢复动作 /* <root> <operation>changeReaderPassword</operation> <readerBarcode>...</readerBarcode> 读者证条码号 <newPassword>5npAUJ67/y3aOvdC0r+Dj7SeXGE=</newPassword> <operator>test</operator> <operTime>Fri, 08 Dec 2006 09:01:38 GMT</operTime> <readerRecord recPath='...'>...</readerRecord> 最新读者记录 </root> 注: 2019/4/25 以前的代码存在 bug,少写入了 readerBarcode 和 newPassword 元素。但此二元素可以从 readerRecord 里面找出来 * */ public int RecoverChangeReaderPassword( RmsChannelCollection Channels, RecoverLevel level, XmlDocument domLog, out string strError) { strError = ""; // 暂时把Robust当作Logic处理 if (level == RecoverLevel.Robust) level = RecoverLevel.Logic; long lRet = 0; int nRet = 0; RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } DO_SNAPSHOT: // 快照恢复 if (level == RecoverLevel.Snapshot) { string strReaderXml = DomUtil.GetElementText(domLog.DocumentElement, "readerRecord", out XmlNode node); if (node == null) { strError = "日志记录中缺<readerRecord>元素"; return -1; } string strReaderRecPath = DomUtil.GetAttr(node, "recPath"); byte[] timestamp = null; // 写读者记录 lRet = channel.DoSaveTextRes(strReaderRecPath, strReaderXml, false, "content,ignorechecktimestamp", timestamp, out byte[] output_timestamp, out string strOutputPath, out strError); if (lRet == -1) { strError = "写入读者记录 '" + strReaderRecPath + "' 时发生错误: " + strError; return -1; } return 0; } // 逻辑恢复或者混合恢复 if (level == RecoverLevel.Logic || level == RecoverLevel.LogicAndSnapshot) { // 读出原有读者记录,修改密码后存回 string strReaderBarcode = DomUtil.GetElementText(domLog.DocumentElement, "readerBarcode"); if (String.IsNullOrEmpty(strReaderBarcode) == true) { strError = "日志记录中缺乏 <readerBarcode> 元素"; goto ERROR1; } string strNewPassword = DomUtil.GetElementText(domLog.DocumentElement, "newPassword"); if (String.IsNullOrEmpty(strNewPassword) == true) { strError = "日志记录中缺乏 <newPassword> 元素"; goto ERROR1; } // 读入读者记录 nRet = this.GetReaderRecXml( // Channels, channel, strReaderBarcode, out string strReaderXml, out string strOutputReaderRecPath, out byte[] reader_timestamp, out strError); if (nRet == 0) { strError = "读者证条码号 '" + strReaderBarcode + "' 不存在"; goto ERROR1; } if (nRet == -1) { strError = "读入证条码号为 '" + strReaderBarcode + "' 的读者记录时发生错误: " + strError; goto ERROR1; } nRet = LibraryApplication.LoadToDom(strReaderXml, out XmlDocument readerdom, out strError); if (nRet == -1) { strError = "装载读者记录进入XML DOM时发生错误: " + strError; goto ERROR1; } // strNewPassword中本来就是SHA1形态 DomUtil.SetElementText(readerdom.DocumentElement, "password", strNewPassword); // 写回读者记录 lRet = channel.DoSaveTextRes(strOutputReaderRecPath, readerdom.OuterXml, false, "content,ignorechecktimestamp", reader_timestamp, out byte[] output_timestamp, out string strOutputPath, out strError); if (lRet == -1) goto ERROR1; } return 0; ERROR1: if (level == RecoverLevel.LogicAndSnapshot) { WriteErrorLog($"RecoverChangeReaderPassword() 用 LogicAndSnapShot 方式恢复遇到报错 {strError},后面自动改用 SnapShot 方式尝试 ..."); level = RecoverLevel.Snapshot; goto DO_SNAPSHOT; } return -1; } // SetReaderInfo() API 恢复动作 /* <root> <operation>setReaderInfo</operation> 操作类型 <action>...</action> 具体动作。有new change delete move 4种 <record recPath='...'>...</record> 新记录 <oldRecord recPath='...'>...</oldRecord> 被覆盖或者删除的记录 动作为 change 和 delete 时具备此元素 <changedEntityRecord itemBarcode='...' recPath='...' oldBorrower='...' newBorrower='...' /> 若干个元素。表示连带发生修改的册记录 <operator>test</operator> 操作者 <operTime>Fri, 08 Dec 2006 09:01:38 GMT</operTime> 操作时间 </root> 注: new 的时候只有<record>元素,delete的时候只有<oldRecord>元素,change的时候两者都有 * */ public int RecoverSetReaderInfo( RmsChannelCollection Channels, RecoverLevel level_param, XmlDocument domLog, out string strError) { strError = ""; string[] element_names = _reader_element_names; RecoverLevel level = level_param; // 暂时把Robust当作Logic处理 if (level == RecoverLevel.Robust) level = RecoverLevel.Logic; long lRet = 0; int nRet = 0; RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } bool bReuse = false; // 是否能够不顾RecoverLevel状态而重用部分代码 DO_SNAPSHOT: string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); // 快照恢复 if (level == RecoverLevel.Snapshot || bReuse == true) { byte[] timestamp = null; byte[] output_timestamp = null; string strOutputPath = ""; if (strAction == "new" || strAction == "change") { XmlNode node = null; string strRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out node); if (node == null) { strError = "日志记录中缺<record>元素"; return -1; } string strRecPath = DomUtil.GetAttr(node, "recPath"); // 写读者记录 lRet = channel.DoSaveTextRes(strRecPath, strRecord, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入读者记录 '" + strRecPath + "' 时发生错误: " + strError; return -1; } // 2015/9/11 XmlNodeList nodes = domLog.DocumentElement.SelectNodes("changedEntityRecord"); foreach (XmlElement item in nodes) { string strItemBarcode = item.GetAttribute("itemBarcode"); string strItemRecPath = item.GetAttribute("recPath"); string strOldReaderBarcode = item.GetAttribute("oldBorrower"); string strNewReaderBarcode = item.GetAttribute("newBorrower"); // 修改一条册记录,的 borrower 元素内容 // parameters: // -2 保存记录时出错 // -1 一般性错误 // 0 成功 nRet = ChangeBorrower( channel, strItemBarcode, strItemRecPath, strOldReaderBarcode, strNewReaderBarcode, true, out strError); if (nRet == -1 || nRet == -2) { strError = "修改读者记录所关联的在借册记录时出错:" + strError; return -1; } } } else if (strAction == "delete") { XmlNode node = null; string strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } string strRecPath = DomUtil.GetAttr(node, "recPath"); int nRedoCount = 0; REDO: // 删除读者记录 lRet = channel.DoDeleteRes(strRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) return 0; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoCount < 10) { timestamp = output_timestamp; nRedoCount++; goto REDO; } } strError = "删除读者记录 '" + strRecPath + "' 时发生错误: " + strError; return -1; } } else if (strAction == "move") { XmlNode node = null; string strRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out node); if (node == null) { strError = "日志记录中缺<record>元素"; return -1; } string strRecPath = DomUtil.GetAttr(node, "recPath"); if (string.IsNullOrEmpty(strRecPath) == true) { strError = "日志记录中<record>元素内缺recPath属性值"; return -1; } string strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } string strOldRecPath = DomUtil.GetAttr(node, "recPath"); if (string.IsNullOrEmpty(strOldRecPath) == true) { strError = "日志记录中<oldRecord>元素内缺recPath属性值"; return -1; } /* int nRedoCount = 0; REDO: * */ // 移动读者记录 lRet = channel.DoCopyRecord( strOldRecPath, strRecPath, true, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { // 源记录本来就不存在。进行容错处理 if (channel.ErrorCode == ChannelErrorCode.NotFound && level_param == RecoverLevel.Robust) { // 优先用最新的记录内容复原。实在没有才用旧的记录内容 if (string.IsNullOrEmpty(strRecord) == true) strRecord = strOldRecord; if (string.IsNullOrEmpty(strRecord) == false) { // 写读者记录 lRet = channel.DoSaveTextRes(strRecPath, strRecord, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "为容错,写入读者记录 '" + strRecPath + "' 时发生错误: " + strError; return -1; } return 0; } } strError = "移动读者记录 '" + strOldRecPath + "' 到 '" + strRecPath + "' 时发生错误: " + strError; return -1; } // <record>中如果有记录体,则还需要写入一次 // 所以这里需要注意,在创建日志记录的时候,如果没有在CopyRecord()后追加修改过记录,则不要创建<record>记录正文部分,以免引起多余的日志恢复时写入动作 if (string.IsNullOrEmpty(strRecord) == false) { lRet = channel.DoSaveTextRes(strRecPath, strRecord, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入读者记录 '" + strRecPath + "' 时发生错误: " + strError; return -1; } } } return 0; } // 逻辑恢复或者混合恢复 if (level == RecoverLevel.Logic || level == RecoverLevel.LogicAndSnapshot) { // 和数据库中已有记录合并,然后保存 if (strAction == "new" || strAction == "change") { XmlNode node = null; string strRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out node); if (node == null) { strError = "日志记录中缺<record>元素"; return -1; } string strRecPath = DomUtil.GetAttr(node, "recPath"); // 读出数据库中原有的记录 string strExistXml = ""; string strMetaData = ""; byte[] exist_timestamp = null; string strOutputPath = ""; if (strAction == "change") { lRet = channel.GetRes(strRecPath, out strExistXml, out strMetaData, out exist_timestamp, out strOutputPath, out strError); if (lRet == -1) { // 容错 if (channel.ErrorCode == ChannelErrorCode.NotFound && level == RecoverLevel.LogicAndSnapshot) { // 如果记录不存在, 则构造一条空的记录 // bExist = false; strExistXml = "<root />"; exist_timestamp = null; } else { strError = "在读入原有记录 '" + strRecPath + "' 时失败: " + strError; goto ERROR1; } } } // // 把两个记录装入DOM XmlDocument domExist = new XmlDocument(); XmlDocument domNew = new XmlDocument(); try { // 防范空记录 if (String.IsNullOrEmpty(strExistXml) == true) strExistXml = "<root />"; domExist.LoadXml(strExistXml); } catch (Exception ex) { strError = "strExistXml装载进入DOM时发生错误: " + ex.Message; goto ERROR1; } try { domNew.LoadXml(strRecord); } catch (Exception ex) { strError = "strRecord装载进入DOM时发生错误: " + ex.Message; goto ERROR1; } // 合并新旧记录 string strNewXml = ""; nRet = MergeTwoReaderXml( element_names, "change", domExist, domNew, out strNewXml, out strError); if (nRet == -1) goto ERROR1; // 保存新记录 byte[] output_timestamp = null; lRet = channel.DoSaveTextRes(strRecPath, strNewXml, false, // include preamble? "content,ignorechecktimestamp", exist_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { goto ERROR1; } } else if (strAction == "delete") { // 和SnapShot方式相同 bReuse = true; goto DO_SNAPSHOT; } else if (strAction == "move") { // 和SnapShot方式相同 bReuse = true; goto DO_SNAPSHOT; } else { strError = "无法识别的<action>内容 '" + strAction + "'"; return -1; } } return 0; ERROR1: if (level == RecoverLevel.LogicAndSnapshot) { WriteErrorLog($"RecoverSetReaderInfo() 用 LogicAndSnapShot 方式恢复遇到报错 {strError},后面自动改用 SnapShot 方式尝试 ..."); level = RecoverLevel.Snapshot; goto DO_SNAPSHOT; } return -1; } // Amerce() API 恢复动作 /* <root> <operation>amerce</operation> 操作类型 <action>amerce</action> 具体动作。有amerce undo modifyprice <readerBarcode>...</readerBarcode> 读者证条码号 <!-- <idList>...<idList> ID列表,逗号间隔 已废止 --> <amerceItems> <amerceItem id="..." newPrice="..." newComment="..." /> newComment中内容追加或替换原来的注释内容。到底是追加还是覆盖,取决于第一个字符是否为'>'还是'<',前者为追加(这时第一个字符不被当作内容)。如果第一个字符不是这两者之一,则默认为追加 ... </amerceItems> <amerceRecord recPath='...'><root><itemBarcode>0000001</itemBarcode><readerBarcode>R0000002</readerBarcode><state>amerced</state><id>632958375041543888-1</id><over>31day</over><borrowDate>Sat, 07 Oct 2006 09:04:28 GMT</borrowDate><borrowPeriod>30day</borrowPeriod><returnDate>Thu, 07 Dec 2006 09:04:27 GMT</returnDate><returnOperator>test</returnOperator></root></amerceRecord> 在罚款库中创建的新记录。注意<amerceRecord>元素可以重复。<amerceRecord>元素内容里面的<itemBarcode><readerBarcode><id>等具备了足够的信息。 <operator>test</operator> 操作者 <operTime>Fri, 08 Dec 2006 10:09:36 GMT</operTime> 操作时间 * 早期缺乏 oldReaderRecord 元素,无法计算 修改了金额情况下 新旧金额之间的差值 <readerRecord recPath='...'>...</readerRecord> 最新读者记录 </root> <root> <operation>amerce</operation> <action>undo</action> <readerBarcode>...</readerBarcode> 读者证条码号 <!-- <idList>...<idList> ID列表,逗号间隔 已废止 --> <amerceItems> <amerceItem id="..." newPrice="..."/> ... </amerceItems> <amerceRecord recPath='...'><root><itemBarcode>0000001</itemBarcode><readerBarcode>R0000002</readerBarcode><state>amerced</state><id>632958375041543888-1</id><over>31day</over><borrowDate>Sat, 07 Oct 2006 09:04:28 GMT</borrowDate><borrowPeriod>30day</borrowPeriod><returnDate>Thu, 07 Dec 2006 09:04:27 GMT</returnDate><returnOperator>test</returnOperator></root></amerceRecord> Undo所去掉的罚款库记录 <operator>test</operator> <operTime>Fri, 08 Dec 2006 10:12:20 GMT</operTime> <readerRecord recPath='...'>...</readerRecord> 最新读者记录 </root> <root> <operation>amerce</operation> <action>modifyprice</action> <readerBarcode>...</readerBarcode> 读者证条码号 <amerceItems> <amerceItem id="..." newPrice="..." newComment="..."/> newComment中内容追加或替换原来的注释内容。到底是追加还是覆盖,取决于第一个字符是否为'>'还是'<',前者为追加(这时第一个字符不被当作内容)。如果第一个字符不是这两者之一,则默认为追加 ... </amerceItems> <!-- modifyprice操作时不产生<amerceRecord>元素 --> <operator>test</operator> <operTime>Fri, 08 Dec 2006 10:12:20 GMT</operTime> <oldReaderRecord recPath='...'>...</oldReaderRecord> 操作前旧的读者记录。<oldReaderRecord>元素是modifyprice操作时特有的元素 <readerRecord recPath='...'>...</readerRecord> 最新读者记录 </root> 2007/12/18 <root> <operation>amerce</operation> 操作类型 <action>expire</action> 以停代金到期 <readerBarcode>...</readerBarcode> 读者证条码号 <expiredOverdues> 已经到期的若干<overdue>元素 <overdue ... /> ... </expiredOverdues> <operator>test</operator> 操作者 如果为#readersMonitor,表示为后台线程 <operTime>Fri, 08 Dec 2006 10:09:36 GMT</operTime> 操作时间 <readerRecord recPath='...'>...</readerRecord> 最新读者记录 </root> * 2008/6/20 <root> <operation>amerce</operation> <action>modifycomment</action> <readerBarcode>...</readerBarcode> 读者证条码号 <amerceItems> <amerceItem id="..." newComment="..."/> newComment中内容追加或替换原来的注释内容。到底是追加还是覆盖,取决于第一个字符是否为'>'还是'<',前者为追加(这时第一个字符不被当作内容)。如果第一个字符不是这两者之一,则默认为追加 ... </amerceItems> <!-- modifycomment操作时不产生<amerceRecord>元素 --> <operator>test</operator> <operTime>Fri, 08 Dec 2006 10:12:20 GMT</operTime> <oldReaderRecord recPath='...'>...</oldReaderRecord> 操作前旧的读者记录。<oldReaderRecord>元素是modifycomment操作时特有的元素 <readerRecord recPath='...'>...</readerRecord> 最新读者记录 </root> * * * */ public int RecoverAmerce( RmsChannelCollection Channels, RecoverLevel level, XmlDocument domLog, out string strError) { strError = ""; // 暂时把Robust当作Logic处理 if (level == RecoverLevel.Robust) level = RecoverLevel.Logic; long lRet = 0; int nRet = 0; RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } DO_SNAPSHOT: string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); // 快照恢复 if (level == RecoverLevel.Snapshot) { byte[] timestamp = null; byte[] output_timestamp = null; string strOutputPath = ""; if (strAction == "amerce") { XmlNodeList nodes = domLog.DocumentElement.SelectNodes("amerceRecord"); int nErrorCount = 0; for (int i = 0; i < nodes.Count; i++) { XmlNode node = nodes[i]; string strRecord = node.InnerText; string strRecPath = DomUtil.GetAttr(node, "recPath"); // 写违约金记录 string strError0 = ""; lRet = channel.DoSaveTextRes(strRecPath, strRecord, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError0); if (lRet == -1) { // 继续循环 if (strError != "") strError += "\r\n"; strError += "写入违约金记录 '" + strRecPath + "' 时发生错误: " + strError0; nErrorCount++; } } if (nErrorCount > 0) return -1; } else if (strAction == "undo") { XmlNodeList nodes = domLog.DocumentElement.SelectNodes("amerceRecord"); int nErrorCount = 0; for (int i = 0; i < nodes.Count; i++) { XmlNode node = nodes[i]; string strRecPath = DomUtil.GetAttr(node, "recPath"); int nRedoCount = 0; string strError0 = ""; REDO: // 删除违约金记录 lRet = channel.DoDeleteRes(strRecPath, timestamp, out output_timestamp, out strError0); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) continue; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoCount < 10) { timestamp = output_timestamp; nRedoCount++; goto REDO; } } // 继续循环 if (strError != "") strError += "\r\n"; strError += "删除违约金记录 '" + strRecPath + "' 时发生错误: " + strError0; nErrorCount++; } } // end of for if (nErrorCount > 0) return -1; } else if (strAction == "modifyprice") { // 这里什么都不作,只等后面用快照的读者记录来恢复 } else if (strAction == "expire") { // 这里什么都不作,只等后面用快照的读者记录来恢复 } else if (strAction == "modifycomment") { // 这里什么都不作,只等后面用快照的读者记录来恢复 } else if (strAction == "appendcomment") { // 这里什么都不作,只等后面用快照的读者记录来恢复 } else { strError = "未知的<action>类型: " + strAction; return -1; } { XmlNode node = null; // 写入读者记录 string strReaderRecord = DomUtil.GetElementText(domLog.DocumentElement, "readerRecord", out node); string strReaderRecPath = DomUtil.GetAttr(node, "recPath"); // 写读者记录 lRet = channel.DoSaveTextRes(strReaderRecPath, strReaderRecord, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入读者记录 '" + strReaderRecPath + "' 时发生错误: " + strError; return -1; } } return 0; } // 逻辑恢复或者混合恢复 if (level == RecoverLevel.Logic || level == RecoverLevel.LogicAndSnapshot) { string strReaderBarcode = DomUtil.GetElementText(domLog.DocumentElement, "readerBarcode"); if (String.IsNullOrEmpty(strReaderBarcode) == true) { strError = "日志记录中缺乏<readerBarcode>元素"; return -1; } string strLibraryCode = DomUtil.GetElementText(domLog.DocumentElement, "libraryCode"); string strOperator = DomUtil.GetElementText(domLog.DocumentElement, "operator"); string strOperTime = DomUtil.GetElementText(domLog.DocumentElement, "operTime"); /* string strAmerceItemIdList = DomUtil.GetElementText(domLog.DocumentElement, "idList"); if (String.IsNullOrEmpty(strAmerceItemIdList) == true) { strError = "日志记录中缺乏<idList>元素"; return -1; } * */ AmerceItem[] amerce_items = ReadAmerceItemList(domLog); // 读入读者记录 string strReaderXml = ""; string strOutputReaderRecPath = ""; byte[] reader_timestamp = null; nRet = this.GetReaderRecXml( // Channels, channel, strReaderBarcode, out strReaderXml, out strOutputReaderRecPath, out reader_timestamp, out strError); if (nRet == 0) { strError = "读者证条码号 '" + strReaderBarcode + "' 不存在"; goto ERROR1; } if (nRet == -1) { strError = "读入读者记录时发生错误: " + strError; goto ERROR1; } XmlDocument readerdom = null; nRet = LibraryApplication.LoadToDom(strReaderXml, out readerdom, out strError); if (nRet == -1) { strError = "装载读者记录进入XML DOM时发生错误: " + strError; goto ERROR1; } byte[] output_timestamp = null; string strOutputPath = ""; if (strAction == "amerce") { List<string> NotFoundIds = null; List<string> Ids = null; List<string> AmerceRecordXmls = null; // 交违约金:在读者记录中去除所选的<overdue>元素,并且构造一批新记录准备加入违约金库 // return: // -1 error // 0 读者dom没有变化 // 1 读者dom发生了变化 nRet = DoAmerceReaderXml( strLibraryCode, ref readerdom, amerce_items, strOperator, strOperTime, out AmerceRecordXmls, out NotFoundIds, out Ids, out strError); if (nRet == -1) { // 在错误信息后面增补每个id对应的amerce record if (NotFoundIds != null && NotFoundIds.Count > 0) { strError += "。读者证条码号为 " + strReaderBarcode + ",日志记录中相关的AmerceRecord如下:\r\n" + GetAmerceRecordStringByID(domLog, NotFoundIds); } goto ERROR1; } // 如果有精力,可以把AmerceRecordXmls和日志记录中的<amerceRecord>逐个进行核对 // 写入违约金记录 XmlNodeList nodes = domLog.DocumentElement.SelectNodes("amerceRecord"); for (int i = 0; i < nodes.Count; i++) { XmlNode node = nodes[i]; string strRecord = node.InnerText; string strRecPath = DomUtil.GetAttr(node, "recPath"); // 写违约金记录 lRet = channel.DoSaveTextRes(strRecPath, strRecord, false, "content,ignorechecktimestamp", null, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入违约金记录 '" + strRecPath + "' 时发生错误: " + strError; goto ERROR1; } } } if (strAction == "undo") { XmlNodeList nodes = domLog.DocumentElement.SelectNodes("amerceRecord"); // 看看根下面是否有overdues元素 XmlNode root = readerdom.DocumentElement.SelectSingleNode("overdues"); if (root == null) { root = readerdom.CreateElement("overdues"); readerdom.DocumentElement.AppendChild(root); } for (int i = 0; i < nodes.Count; i++) { XmlNode node = nodes[i]; string strRecord = node.InnerText; string strRecPath = DomUtil.GetAttr(node, "recPath"); // 如果有精力,可以把违约金记录中的id和日志记录<amerceItems>中的id对比检查 // 违约金信息加回读者记录 string strTempReaderBarcode = ""; string strOverdueString = ""; // 将违约金记录格式转换为读者记录中的<overdue>元素格式 nRet = ConvertAmerceRecordToOverdueString(strRecord, out strTempReaderBarcode, out strOverdueString, out strError); if (nRet == -1) goto ERROR1; if (strTempReaderBarcode != strReaderBarcode) { strError = "<amerceRecord>中的读者证条码号和日志记录中的<readerBarcode>读者证条码号不一致"; goto ERROR1; } XmlDocumentFragment fragment = readerdom.CreateDocumentFragment(); fragment.InnerXml = strOverdueString; // 2008/11/13 changed XmlNode node_added = root.AppendChild(fragment); Debug.Assert(node_added != null, ""); string strReason = DomUtil.GetAttr(node_added, "reason"); if (strReason == "押金。") { string strPrice = DomUtil.GetAttr(node_added, "price"); if (String.IsNullOrEmpty(strPrice) == false) { // 需要从<foregift>元素中减去这个价格 string strContent = DomUtil.GetElementText(readerdom.DocumentElement, "foregift"); string strNegativePrice = ""; // 将形如"-123.4+10.55-20.3"的价格字符串反转正负号 // parameters: // bSum 是否要顺便汇总? true表示要汇总 nRet = PriceUtil.NegativePrices(strPrice, false, out strNegativePrice, out strError); if (nRet == -1) { strError = "反转价格字符串 '" + strPrice + "时发生错误: " + strError; goto ERROR1; } strContent = PriceUtil.JoinPriceString(strContent, strNegativePrice); DomUtil.SetElementText(readerdom.DocumentElement, "foregift", strContent); // bReaderDomChanged = true; } } // 删除违约金记录 int nRedoCount = 0; byte[] timestamp = null; REDO: // 删除违约金记录 lRet = channel.DoDeleteRes(strRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) continue; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoCount < 10) { timestamp = output_timestamp; nRedoCount++; goto REDO; } } // 是否需要继续循环? strError = "删除违约金记录 '" + strRecPath + "' 时发生错误: " + strError; goto ERROR1; } } } if (strAction == "modifyprice") { nRet = ModifyPrice(ref readerdom, amerce_items, out strError); if (nRet == -1) { strError = "ModifyPrice()时发生错误: " + strError; goto ERROR1; } } // 2008/6/20 if (strAction == "modifycomment") { nRet = ModifyComment( ref readerdom, amerce_items, out strError); if (nRet == -1) { strError = "ModifyComment()时发生错误: " + strError; goto ERROR1; } } if (strAction == "expire") { // 寻找<expiredOverdues/overdue>元素 XmlNodeList nodes = domLog.DocumentElement.SelectNodes("//expiredOverdues/overdue"); for (int i = 0; i < nodes.Count; i++) { XmlNode node = nodes[i]; string strID = DomUtil.GetAttr(node, "id"); if (String.IsNullOrEmpty(strID) == true) continue; // 从读者记录中去掉这个id的<overdue>元素 XmlNode nodeOverdue = readerdom.DocumentElement.SelectSingleNode("overdues/overdue[@id='" + strID + "']"); if (nodeOverdue != null) { if (nodeOverdue.ParentNode != null) nodeOverdue.ParentNode.RemoveChild(nodeOverdue); } } } // 写回读者记录 strReaderXml = readerdom.OuterXml; lRet = channel.DoSaveTextRes(strOutputReaderRecPath, strReaderXml, false, "content,ignorechecktimestamp", reader_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; } return 0; ERROR1: if (level == RecoverLevel.LogicAndSnapshot) { WriteErrorLog($"RecoverAmerce() 用 LogicAndSnapShot 方式恢复遇到报错 {strError},后面自动改用 SnapShot 方式尝试 ..."); level = RecoverLevel.Snapshot; goto DO_SNAPSHOT; } return -1; } // 获得和指定id相关的AmerceRecord static string GetAmerceRecordStringByID(XmlDocument domLog, List<string> NotFoundIds) { string strResult = ""; List<string> records = new List<string>(); List<string> ids = new List<string>(); XmlNodeList nodes = domLog.DocumentElement.SelectNodes("amerceRecord"); for (int i = 0; i < nodes.Count; i++) { string strRecord = nodes[i].InnerText; if (String.IsNullOrEmpty(strRecord) == true) continue; XmlDocument dom = new XmlDocument(); try { dom.LoadXml(strRecord); } catch (Exception ex) { strResult += "XML字符串装入DOM时发生错误: " + ex.Message + "\r\n"; continue; } records.Add(strRecord); string strID = DomUtil.GetElementText(dom.DocumentElement, "id"); ids.Add(strID); } for (int i = 0; i < NotFoundIds.Count; i++) { string strID = NotFoundIds[i]; int index = ids.IndexOf(strID); if (index == -1) { strResult += "id [" + strID + "] 在日志记录中没有找到对应的<amerceRecord>元素\r\n"; continue; } strResult += "id: " + strID + " -- " + records[index] + "\r\n"; } return strResult; } // 获得附件记录 static int GetAttachmentRecord( Stream attachment, int nAttachmentIndex, out byte[] baRecord, out string strError) { baRecord = null; strError = ""; if (attachment == null) { strError = "attachment为空"; return -1; } if (nAttachmentIndex < 0) { strError = "nAttachmentIndex参数值必须>=0"; return -1; } attachment.Seek(0, SeekOrigin.Begin); long lLength = 0; // 找到记录开头 for (int i = 0; i <= nAttachmentIndex; i++) { byte[] length = new byte[8]; int nRet = attachment.Read(length, 0, 8); if (nRet != 8) { strError = "附件格式错误1"; return -1; } lLength = BitConverter.ToInt64(length, 0); if (attachment.Length - attachment.Position < lLength) { strError = "附件格式错误2"; return -1; } if (i == nAttachmentIndex) break; attachment.Seek(lLength, SeekOrigin.Current); } if (lLength >= 1000 * 1024) { strError = "附件记录长度太大,超过1000*1024,无法处理"; return -1; } // 读入记录内容 baRecord = new byte[(int)lLength]; attachment.Read(baRecord, 0, (int)lLength); return 0; } /* <root> <operation>devolveReaderInfo</operation> <sourceReaderBarcode>...</sourceReaderBarcode> 源读者证条码号 <targetReaderBarcode>...</targetReaderBarcode> 目标读者证条码号 <borrows>...</borrows> 移动过去的<borrows>内容,下级为<borrow>元素 <overdues>...</overdues> 移动过去的<overdue>内容,下级为<overdue>元素 <sourceReaderRecord recPath='...'>...</sourceReaderRecord> 最新源读者记录 <targetReaderRecord recPath='...'>...</targetReaderRecord> 最新目标读者记录 <changedEntityRecord recPath='...' attahchmentIndex='.'>...</changedEntityRecord> 所牵连到的发生了修改的实体记录。此元素的文本即是记录体,但注意为不透明的字符串(HtmlEncoding后的记录字符串)。如果存在attachmentIndex属性,则表明实体记录不在此元素文本中,而在日志记录的附件中 <operator>test</operator> <operTime>Fri, 08 Dec 2006 10:12:20 GMT</operTime> </root> * * */ public int RecoverDevolveReaderInfo( RmsChannelCollection Channels, RecoverLevel level, XmlDocument domLog, Stream attachmentLog, out string strError) { strError = ""; // 暂时把Robust当作Logic处理 if (level == RecoverLevel.Robust) level = RecoverLevel.Logic; long lRet = 0; int nRet = 0; RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } DO_SNAPSHOT: // 快照恢复 if (level == RecoverLevel.Snapshot) { /* // 观察是否有<warning>元素 XmlNode nodeWarning = domLog.SelectSingleNode("warning"); if (nodeWarning != null) { // 如果<warning元素存在,表明只能采用逻辑恢复> strError = nodeWarning.InnerText; return -1; } */ // 获源读者记录 XmlNode node = null; string strSourceReaderXml = DomUtil.GetElementText( domLog.DocumentElement, "sourceReaderRecord", out node); if (node == null) { strError = "日志记录中缺<sourceReaderRecord>元素"; return -1; } string strSourceReaderRecPath = DomUtil.GetAttr(node, "recPath"); byte[] timestamp = null; string strOutputPath = ""; byte[] output_timestamp = null; // 写源读者记录 lRet = channel.DoSaveTextRes(strSourceReaderRecPath, strSourceReaderXml, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入源读者记录 '" + strSourceReaderRecPath + "' 时发生错误: " + strError; return -1; } // 获目标读者记录 node = null; string strTargetReaderXml = DomUtil.GetElementText( domLog.DocumentElement, "targetReaderRecord", out node); if (node == null) { strError = "日志记录中缺<targetReaderRecord>元素"; return -1; } string strTargetReaderRecPath = DomUtil.GetAttr(node, "recPath"); // 写目标读者记录 lRet = channel.DoSaveTextRes(strTargetReaderRecPath, strTargetReaderXml, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入目标读者记录 '" + strSourceReaderRecPath + "' 时发生错误: " + strError; return -1; } // 循环,写入相关的若干实体记录 XmlNodeList nodeEntities = domLog.DocumentElement.SelectNodes("changedEntityRecord"); for (int i = 0; i < nodeEntities.Count; i++) { XmlNode nodeEntity = nodeEntities[i]; string strItemRecPath = DomUtil.GetAttr(nodeEntity, "recPath"); string strAttachmentIndex = DomUtil.GetAttr(nodeEntity, "attachmentIndex"); string strItemXml = ""; if (String.IsNullOrEmpty(strAttachmentIndex) == true) { strItemXml = nodeEntity.InnerText; if (String.IsNullOrEmpty(strItemXml) == true) { strError = "<changedEntityRecord>元素缺乏文本内容。"; return -1; } } else { // 实体记录在附件中 int nAttachmentIndex = 0; try { nAttachmentIndex = Convert.ToInt32(strAttachmentIndex); } catch { strError = "<changedEntityRecord>元素的attachmentIndex属性值'" + strAttachmentIndex + "'格式不正确,应当为>=0的纯数字"; return -1; } byte[] baItem = null; nRet = GetAttachmentRecord( attachmentLog, nAttachmentIndex, out baItem, out strError); if (nRet == -1) { strError = "获得 index 为 " + nAttachmentIndex.ToString() + " 的日志附件记录时出错:" + strError; return -1; } strItemXml = Encoding.UTF8.GetString(baItem); } // 写册记录 lRet = channel.DoSaveTextRes(strItemRecPath, strItemXml, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入册记录 '" + strItemRecPath + "' 时发生错误: " + strError; return -1; } } return 0; } // 逻辑恢复或者混合恢复 if (level == RecoverLevel.Logic || level == RecoverLevel.LogicAndSnapshot) { string strOperTimeString = DomUtil.GetElementText(domLog.DocumentElement, "operTime"); string strSourceReaderBarcode = DomUtil.GetElementText(domLog.DocumentElement, "sourceReaderBarcode"); if (String.IsNullOrEmpty(strSourceReaderBarcode) == true) { strError = "<sourceReaderBarcode>元素值为空"; goto ERROR1; } string strTargetReaderBarcode = DomUtil.GetElementText(domLog.DocumentElement, "targetReaderBarcode"); if (String.IsNullOrEmpty(strTargetReaderBarcode) == true) { strError = "<targetReaderBarcode>元素值为空"; goto ERROR1; } // 读入源读者记录 string strSourceReaderXml = ""; string strSourceOutputReaderRecPath = ""; byte[] source_reader_timestamp = null; nRet = this.GetReaderRecXml( // Channels, channel, strSourceReaderBarcode, out strSourceReaderXml, out strSourceOutputReaderRecPath, out source_reader_timestamp, out strError); if (nRet == 0) { strError = "源读者证条码号 '" + strSourceReaderBarcode + "' 不存在"; goto ERROR1; } if (nRet == -1) { strError = "读入证条码号为 '" + strSourceReaderBarcode + "' 的源读者记录时发生错误: " + strError; goto ERROR1; } XmlDocument source_readerdom = null; nRet = LibraryApplication.LoadToDom(strSourceReaderXml, out source_readerdom, out strError); if (nRet == -1) { strError = "装载源读者记录进入XML DOM时发生错误: " + strError; goto ERROR1; } // // 读入目标读者记录 string strTargetReaderXml = ""; string strTargetOutputReaderRecPath = ""; byte[] target_reader_timestamp = null; nRet = this.GetReaderRecXml( // Channels, channel, strTargetReaderBarcode, out strTargetReaderXml, out strTargetOutputReaderRecPath, out target_reader_timestamp, out strError); if (nRet == 0) { strError = "目标读者证条码号 '" + strTargetReaderBarcode + "' 不存在"; goto ERROR1; } if (nRet == -1) { strError = "读入证条码号为 '" + strTargetReaderBarcode + "' 的目标读者记录时发生错误: " + strError; goto ERROR1; } XmlDocument target_readerdom = null; nRet = LibraryApplication.LoadToDom(strTargetReaderXml, out target_readerdom, out strError); if (nRet == -1) { strError = "装载目标读者记录进入XML DOM时发生错误: " + strError; goto ERROR1; } // 移动信息 XmlDocument domTemp = null; { Stream tempstream = null; try { // 移动借阅信息 -- <borrows>元素内容 // return: // -1 error // 0 not found brrowinfo // 1 found and moved nRet = DevolveBorrowInfo( // Channels, channel, strSourceReaderBarcode, strTargetReaderBarcode, strOperTimeString, ref source_readerdom, ref target_readerdom, ref domTemp, "", out tempstream, out strError); if (nRet == -1) goto ERROR1; } finally { if (tempstream != null) tempstream.Close(); } } // 移动超期违约金信息 -- <overdues>元素内容 // return: // -1 error // 0 not found overdueinfo // 1 found and moved nRet = DevolveOverdueInfo( strSourceReaderBarcode, strTargetReaderBarcode, strOperTimeString, ref source_readerdom, ref target_readerdom, ref domTemp, out strError); if (nRet == -1) goto ERROR1; // 写回读者记录 byte[] output_timestamp = null; string strOutputPath = ""; // 写回源读者记录 lRet = channel.DoSaveTextRes(strSourceOutputReaderRecPath, source_readerdom.OuterXml, false, "content,ignorechecktimestamp", source_reader_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; // 写回目标读者记录 lRet = channel.DoSaveTextRes(strTargetOutputReaderRecPath, target_readerdom.OuterXml, false, "content,ignorechecktimestamp", source_reader_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; } return 0; ERROR1: if (level == RecoverLevel.LogicAndSnapshot) { WriteErrorLog($"RecoverDevolveReaderInfo() 用 LogicAndSnapShot 方式恢复遇到报错 {strError},后面自动改用 SnapShot 方式尝试 ..."); level = RecoverLevel.Snapshot; goto DO_SNAPSHOT; } return -1; } // SetBiblioInfo() API 或CopyBiblioInfo() API 的恢复动作 // 函数内,使用return -1;还是goto ERROR1; 要看错误发生的时候,是否还有价值继续探索SnapShot重试。如果是,就用后者。 /* <root> <operation>setBiblioInfo</operation> <action>...</action> 具体动作 有 new/change/delete/onlydeletebiblio/onlydeletesubrecord 和 onlycopybiblio/onlymovebiblio/copy/move <record recPath='中文图书/3'>...</record> 记录体 动作为new/change/ *move* / *copy* 时具有此元素(即delete时没有此元素) <oldRecord recPath='中文图书/3'>...</oldRecord> 被覆盖、删除或者移动的记录 动作为change/ *delete* / *move* / *copy* 时具备此元素 <deletedEntityRecords> 被删除的实体记录(容器)。只有当<action>为delete时才有这个元素。 <record recPath='中文图书实体/100'>...</record> 这个元素可以重复。注意元素内文本内容目前为空。 ... </deletedEntityRecords> <copyEntityRecords> 被复制的实体记录(容器)。只有当<action>为*copy*时才有这个元素。 <record recPath='中文图书实体/100' targetRecPath='中文图书实体/110'>...</record> 这个元素可以重复。注意元素内文本内容目前为空。recPath属性为源记录路径,targetRecPath为目标记录路径 ... </copyEntityRecords> <moveEntityRecords> 被移动的实体记录(容器)。只有当<action>为*move*时才有这个元素。 <record recPath='中文图书实体/100' targetRecPath='中文图书实体/110'>...</record> 这个元素可以重复。注意元素内文本内容目前为空。recPath属性为源记录路径,targetRecPath为目标记录路径 ... </moveEntityRecords> <copyOrderRecords /> <moveOrderRecords /> <copyIssueRecords /> <moveIssueRecords /> <copyCommentRecords /> <moveCommentRecords /> <mergeStyle>...</mergeStyle> reserve_source 或者 reserve_target。缺省为 reserve_source <operator>test</operator> <operTime>Fri, 08 Dec 2006 10:12:20 GMT</operTime> </root> 逻辑恢复delete操作的时候,检索出全部下属的实体记录删除。 快照恢复的时候,可以根据operlogdom直接删除记录了path的那些实体记录 * */ public int RecoverSetBiblioInfo( RmsChannelCollection Channels, RecoverLevel level, XmlDocument domLog, out string strError) { strError = ""; // 暂时把Robust当作Logic处理 if (level == RecoverLevel.Robust) level = RecoverLevel.Logic; long lRet = 0; int nRet = 0; RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } bool bReuse = false; // 是否能够不顾RecoverLevel状态而重用部分代码 DO_SNAPSHOT: string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); // 快照恢复 if (level == RecoverLevel.Snapshot || bReuse == true) { byte[] timestamp = null; byte[] output_timestamp = null; string strOutputPath = ""; if (strAction == "new" || strAction == "change") { XmlNode node = null; string strRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out node); if (node == null) { strError = "日志记录中缺<record>元素"; goto ERROR1; } string strRecPath = DomUtil.GetAttr(node, "recPath"); // 写书目记录 lRet = channel.DoSaveTextRes(strRecPath, strRecord, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入书目记录 '" + strRecPath + "' 时发生错误: " + strError; return -1; } } else if (strAction == "onlymovebiblio" || strAction == "onlycopybiblio" || strAction == "move" || strAction == "copy") { XmlNode node = null; string strTargetRecord = DomUtil.GetElementText(domLog.DocumentElement, "record", out node); if (node == null) { strError = "日志记录中缺<record>元素"; goto ERROR1; } string strTargetRecPath = DomUtil.GetAttr(node, "recPath"); string strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } string strOldRecPath = DomUtil.GetAttr(node, "recPath"); string strMergeStyle = DomUtil.GetElementText(domLog.DocumentElement, "mergeStyle"); bool bSourceExist = true; // 观察源记录是否存在 { string strMetaData = ""; string strXml = ""; byte[] temp_timestamp = null; lRet = channel.GetRes(strOldRecPath, out strXml, out strMetaData, out temp_timestamp, out strOutputPath, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) { bSourceExist = false; } } } if (bSourceExist == true) { string strIdChangeList = ""; // 复制书目记录 lRet = channel.DoCopyRecord(strOldRecPath, strTargetRecPath, strAction == "onlymovebiblio" ? true : false, // bDeleteSourceRecord strMergeStyle, out strIdChangeList, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "DoCopyRecord() error :" + strError; goto ERROR1; } } /* // 写书目记录 lRet = channel.DoSaveTextRes(strRecPath, strRecord, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "复制书目记录 '" + strOldRecPath + "' 到 '" + strTargetRecPath + "' 时发生错误: " + strError; return -1; } * */ if (bSourceExist == false) { if (String.IsNullOrEmpty(strTargetRecord) == true) { if (String.IsNullOrEmpty(strOldRecord) == true) { strError = "源记录 '" + strOldRecPath + "' 不存在,并且<record>元素无文本内容,这时<oldRecord>元素也无文本内容,无法获得要写入的记录内容"; return -1; } strTargetRecord = strOldRecord; } } // 如果有“新记录”内容 if (String.IsNullOrEmpty(strTargetRecord) == false) { // 写书目记录 lRet = channel.DoSaveTextRes(strTargetRecPath, strTargetRecord, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写书目记录 '" + strTargetRecPath + "' 时发生错误: " + strError; return -1; } } // 复制或者移动下级子纪录 if (strAction == "move" || strAction == "copy") { string[] element_names = new string[] { "copyEntityRecords", "moveEntityRecords", "copyOrderRecords", "moveOrderRecords", "copyIssueRecords", "moveIssueRecords", "copyCommentRecords", "moveCommentRecords" }; for (int i = 0; i < element_names.Length; i++) { XmlNode node_subrecords = domLog.DocumentElement.SelectSingleNode( element_names[i]); if (node_subrecords != null) { nRet = CopySubRecords( channel, node_subrecords, strTargetRecPath, out strError); if (nRet == -1) return -1; } } } // 2011/12/12 if (bSourceExist == true && (strAction == "move" || strAction == "onlymovebiblio") ) { int nRedoCount = 0; REDO_DELETE: // 删除源书目记录 lRet = channel.DoDeleteRes(strOldRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) { // 记录本来就不存在 } else if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoCount < 10) { timestamp = output_timestamp; nRedoCount++; goto REDO_DELETE; } } else { strError = "删除书目记录 '" + strOldRecPath + "' 时发生错误: " + strError; return -1; } } } } else if (strAction == "delete" || strAction == "onlydeletebiblio" || strAction == "onlydeletesubrecord") { XmlNode node = null; string strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } string strRecPath = DomUtil.GetAttr(node, "recPath"); if (strAction != "onlydeletesubrecord") { int nRedoCount = 0; REDO: // 删除书目记录 lRet = channel.DoDeleteRes(strRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) goto DO_DELETE_CHILD_ENTITYRECORDS; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoCount < 10) { timestamp = output_timestamp; nRedoCount++; goto REDO; } } strError = "删除书目记录 '" + strRecPath + "' 时发生错误: " + strError; return -1; } } DO_DELETE_CHILD_ENTITYRECORDS: if (strAction == "delete" || strAction == "onlydeletesubrecord") { XmlNodeList nodes = domLog.DocumentElement.SelectNodes("deletedEntityRecords/record"); for (int i = 0; i < nodes.Count; i++) { string strEntityRecPath = DomUtil.GetAttr(nodes[i], "recPath"); /* if (String.IsNullOrEmpty(strEntityRecPath) == true) continue; * */ int nRedoDeleteCount = 0; REDO_DELETE_ENTITY: // 删除实体记录 lRet = channel.DoDeleteRes(strEntityRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) continue; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoDeleteCount < 10) { timestamp = output_timestamp; nRedoDeleteCount++; goto REDO_DELETE_ENTITY; } } strError = "删除实体记录 '" + strEntityRecPath + "' 时发生错误: " + strError; return -1; } } nodes = domLog.DocumentElement.SelectNodes("deletedOrderRecords/record"); for (int i = 0; i < nodes.Count; i++) { string strOrderRecPath = DomUtil.GetAttr(nodes[i], "recPath"); if (String.IsNullOrEmpty(strOrderRecPath) == true) continue; int nRedoDeleteCount = 0; REDO_DELETE_ORDER: // 删除订购记录 lRet = channel.DoDeleteRes(strOrderRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) continue; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoDeleteCount < 10) { timestamp = output_timestamp; nRedoDeleteCount++; goto REDO_DELETE_ORDER; } } strError = "删除订购记录 '" + strOrderRecPath + "' 时发生错误: " + strError; return -1; } } nodes = domLog.DocumentElement.SelectNodes("deletedIssueRecords/record"); for (int i = 0; i < nodes.Count; i++) { string strIssueRecPath = DomUtil.GetAttr(nodes[i], "recPath"); if (String.IsNullOrEmpty(strIssueRecPath) == true) continue; int nRedoDeleteCount = 0; REDO_DELETE_ISSUE: // 删除期记录 lRet = channel.DoDeleteRes(strIssueRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) continue; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoDeleteCount < 10) { timestamp = output_timestamp; nRedoDeleteCount++; goto REDO_DELETE_ISSUE; } } strError = "删除期记录 '" + strIssueRecPath + "' 时发生错误: " + strError; return -1; } } } // end if } return 0; } // 逻辑恢复或者混合恢复 if (level == RecoverLevel.Logic || level == RecoverLevel.LogicAndSnapshot) { // 和数据库中已有记录合并,然后保存 if (strAction == "new" || strAction == "change") { // 和SnapShot方式相同 bReuse = true; goto DO_SNAPSHOT; } else if (strAction == "onlymovebiblio" || strAction == "onlycopybiblio" || strAction == "move" || strAction == "copy") { // 和SnapShot方式相同 bReuse = true; goto DO_SNAPSHOT; } else if (strAction == "delete" || strAction == "onlydeletebiblio" || strAction == "onlydeletesubrecord") { XmlNode node = null; string strOldRecord = DomUtil.GetElementText(domLog.DocumentElement, "oldRecord", out node); if (node == null) { strError = "日志记录中缺<oldRecord>元素"; return -1; } string strRecPath = DomUtil.GetAttr(node, "recPath"); if (strAction != "onlydeletesubrecord") { int nRedoCount = 0; byte[] timestamp = null; byte[] output_timestamp = null; REDO: // 删除书目记录 lRet = channel.DoDeleteRes(strRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) goto DO_DELETE_CHILD_ENTITYRECORDS; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoCount < 10) { timestamp = output_timestamp; nRedoCount++; goto REDO; } } strError = "删除书目记录 '" + strRecPath + "' 时发生错误: " + strError; goto ERROR1; } } DO_DELETE_CHILD_ENTITYRECORDS: if (strAction == "delete" || strAction == "onlydeletesubrecord") { // 删除属于同一书目记录的全部实体记录 // return: // -1 error // 0 没有找到属于书目记录的任何实体记录,因此也就无从删除 // >0 实际删除的实体记录数 nRet = DeleteBiblioChildEntities(channel, strRecPath, null, out strError); if (nRet == -1) { strError = "删除书目记录 '" + strRecPath + "' 下属的实体记录时出错: " + strError; goto ERROR1; } // return: // -1 error // 0 没有找到属于书目记录的任何实体记录,因此也就无从删除 // >0 实际删除的实体记录数 nRet = this.OrderItemDatabase.DeleteBiblioChildItems( // Channels, channel, strRecPath, null, out strError); if (nRet == -1) { strError = "删除书目记录 '" + strRecPath + "' 下属的订购记录时出错: " + strError; goto ERROR1; } // return: // -1 error // 0 没有找到属于书目记录的任何实体记录,因此也就无从删除 // >0 实际删除的实体记录数 nRet = this.IssueItemDatabase.DeleteBiblioChildItems( // Channels, channel, strRecPath, null, out strError); if (nRet == -1) { strError = "删除书目记录 '" + strRecPath + "' 下属的期记录时出错: " + strError; goto ERROR1; } } } else { strError = "无法识别的<action>内容 '" + strAction + "'"; return -1; } } return 0; ERROR1: if (level == RecoverLevel.LogicAndSnapshot) { WriteErrorLog($"RecoverSetBiblioInfo() 用 LogicAndSnapShot 方式恢复遇到报错 {strError},后面自动改用 SnapShot 方式尝试 ..."); level = RecoverLevel.Snapshot; goto DO_SNAPSHOT; } return -1; } // 源记录不存在,应该忽略;目标库不存在,也应该忽略 /* <copyEntityRecords> 被复制的实体记录(容器)。只有当<action>为*copy*时才有这个元素。 <record recPath='中文图书实体/100' targetRecPath='中文图书实体/110'>...</record> 这个元素可以重复。注意元素内文本内容目前为空。recPath属性为源记录路径,targetRecPath为目标记录路径 ... </copyEntityRecords> <moveEntityRecords> 被移动的实体记录(容器)。只有当<action>为*move*时才有这个元素。 <record recPath='中文图书实体/100' targetRecPath='中文图书实体/110'>...</record> 这个元素可以重复。注意元素内文本内容目前为空。recPath属性为源记录路径,targetRecPath为目标记录路径 ... </moveEntityRecords> * */ public int CopySubRecords( RmsChannel channel, XmlNode node, string strTargetBiblioRecPath, out string strError) { strError = ""; string strAction = ""; if (StringUtil.HasHead(node.Name, "copy") == true) strAction = "copy"; else if (StringUtil.HasHead(node.Name, "move") == true) // 2011/12/5 原先有BUG "copy" strAction = "move"; else { strError = "不能识别的元素名 '" + node.Name + "'"; return -1; } XmlNodeList nodes = node.SelectNodes("record"); foreach (XmlNode record_node in nodes) { string strSourceRecPath = DomUtil.GetAttr(record_node, "recPath"); string strTargetRecPath = DomUtil.GetAttr(record_node, "targetRecPath"); string strNewBarcode = DomUtil.GetAttr(record_node, "newBarcode"); string strMetaData = ""; string strXml = ""; byte[] timestamp = null; string strOutputPath = ""; long lRet = channel.GetRes(strSourceRecPath, out strXml, out strMetaData, out timestamp, out strOutputPath, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) continue; // 是否报错? strError = "获取下级记录 '" + strSourceRecPath + "' 时发生错误: " + strError; return -1; // goto CONTINUE; } DeleteEntityInfo entityinfo = new DeleteEntityInfo(); entityinfo.RecPath = strOutputPath; entityinfo.OldTimestamp = timestamp; entityinfo.OldRecord = strXml; List<DeleteEntityInfo> entityinfos = new List<DeleteEntityInfo>(); entityinfos.Add(entityinfo); // TODO: 如果目标数据库已经不存在,要跳过 List<string> target_recpaths = new List<string>(); target_recpaths.Add(strTargetRecPath); List<string> newbarcodes = new List<string>(); newbarcodes.Add(strNewBarcode); // 复制属于同一书目记录的全部实体记录 // parameters: // strAction copy / move // return: // -1 error // >=0 实际复制或者移动的实体记录数 int nRet = CopyBiblioChildRecords(channel, strAction, entityinfos, target_recpaths, strTargetBiblioRecPath, newbarcodes, out strError); if (nRet == -1) return -1; } return 0; } /* hire 创建租金记录 API: Hire() <root> <operation>hire</operation> 操作类型 <action>...</action> 具体动作 有hire hirelate两种 <readerBarcode>R0000002</readerBarcode> 读者证条码号 <operator>test</operator> 操作者 <operTime>Fri, 08 Dec 2006 04:17:45 GMT</operTime> 操作时间 <overdues>...</overdues> 租金信息 通常内容为一个字符串,为一个或多个<overdue>元素XML文本片断 <readerRecord recPath='...'>...</readerRecord> 最新读者记录 </root> * */ public int RecoverHire( RmsChannelCollection Channels, RecoverLevel level, XmlDocument domLog, out string strError) { strError = ""; // 暂时把Robust当作Logic处理 if (level == RecoverLevel.Robust) level = RecoverLevel.Logic; long lRet = 0; int nRet = 0; RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } DO_SNAPSHOT: // 快照恢复 if (level == RecoverLevel.Snapshot) { XmlNode node = null; string strReaderXml = DomUtil.GetElementText(domLog.DocumentElement, "readerRecord", out node); if (node == null) { strError = "日志记录中缺<readerRecord>元素"; return -1; } string strReaderRecPath = DomUtil.GetAttr(node, "recPath"); byte[] timestamp = null; byte[] output_timestamp = null; string strOutputPath = ""; // 写读者记录 lRet = channel.DoSaveTextRes(strReaderRecPath, strReaderXml, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入读者记录 '" + strReaderRecPath + "' 时发生错误: " + strError; return -1; } return 0; } // 逻辑恢复或者混合恢复 if (level == RecoverLevel.Logic || level == RecoverLevel.LogicAndSnapshot) { // string strRecoverComment = ""; string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); string strReaderBarcode = DomUtil.GetElementText(domLog.DocumentElement, "readerBarcode"); /// if (String.IsNullOrEmpty(strReaderBarcode) == true) { strError = "日志记录中<readerBarcode>元素值为空"; goto ERROR1; } string strOperator = DomUtil.GetElementText(domLog.DocumentElement, "operator"); string strOperTime = DomUtil.GetElementText(domLog.DocumentElement, "operTime"); string strOverdues = DomUtil.GetElementText(domLog.DocumentElement, "overdues"); if (String.IsNullOrEmpty(strOverdues) == true) { strError = "日志记录中<overdues>元素值为空"; goto ERROR1; } // 从overdues字符串中分析出id XmlDocument tempdom = new XmlDocument(); tempdom.LoadXml("<root />"); XmlDocumentFragment fragment = tempdom.CreateDocumentFragment(); fragment.InnerXml = strOverdues; tempdom.DocumentElement.AppendChild(fragment); XmlNode tempnode = tempdom.DocumentElement.SelectSingleNode("overdue"); if (tempnode == null) { strError = "<overdues>元素内容有误,缺乏<overdue>元素"; goto ERROR1; } string strID = DomUtil.GetAttr(tempnode, "id"); if (String.IsNullOrEmpty(strID) == true) { strError = "日志记录中<overdues>内容中<overdue>元素中id属性值为空"; goto ERROR1; } // 读入读者记录 string strReaderXml = ""; string strOutputReaderRecPath = ""; byte[] reader_timestamp = null; nRet = this.GetReaderRecXml( // Channels, channel, strReaderBarcode, out strReaderXml, out strOutputReaderRecPath, out reader_timestamp, out strError); if (nRet == 0) { strError = "读者证条码号 '" + strReaderBarcode + "' 不存在"; goto ERROR1; } if (nRet == -1) { strError = "读入证条码号为 '" + strReaderBarcode + "' 的读者记录时发生错误: " + strError; goto ERROR1; } XmlDocument readerdom = null; nRet = LibraryApplication.LoadToDom(strReaderXml, out readerdom, out strError); if (nRet == -1) { strError = "装载读者记录进入XML DOM时发生错误: " + strError; goto ERROR1; } // string strOverdueString = ""; // 根据Hire() API要求,修改readerdom nRet = DoHire(strAction, readerdom, ref strID, strOperator, strOperTime, out strOverdueString, out strError); if (nRet == -1) goto ERROR1; // 写回读者、册记录 byte[] output_timestamp = null; string strOutputPath = ""; // 写回读者记录 lRet = channel.DoSaveTextRes(strOutputReaderRecPath, readerdom.OuterXml, false, "content,ignorechecktimestamp", reader_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; } return 0; ERROR1: if (level == RecoverLevel.LogicAndSnapshot) { WriteErrorLog($"RecoverHire() 用 LogicAndSnapShot 方式恢复遇到报错 {strError},后面自动改用 SnapShot 方式尝试 ..."); level = RecoverLevel.Snapshot; goto DO_SNAPSHOT; } return -1; } /* foregift 创建押金记录 API: Foregift() <root> <operation>foregift</operation> 操作类型 <action>...</action> 具体动作 目前有foregift return (注: return操作时,overdue元素里面的price属性,可以使用宏 %return_foregift_price% 表示当前剩余的押金额) <readerBarcode>R0000002</readerBarcode> 读者证条码号 <operator>test</operator> 操作者 <operTime>Fri, 08 Dec 2006 04:17:45 GMT</operTime> 操作时间 <overdues>...</overdues> 押金信息 通常内容为一个字符串,为一个或多个<overdue>元素XML文本片断 <readerRecord recPath='...'>...</readerRecord> 最新读者记录 </root> * * */ public int RecoverForegift( RmsChannelCollection Channels, RecoverLevel level, XmlDocument domLog, out string strError) { strError = ""; // 暂时把Robust当作Logic处理 if (level == RecoverLevel.Robust) level = RecoverLevel.Logic; long lRet = 0; int nRet = 0; RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } DO_SNAPSHOT: // 快照恢复 if (level == RecoverLevel.Snapshot) { XmlNode node = null; string strReaderXml = DomUtil.GetElementText(domLog.DocumentElement, "readerRecord", out node); if (node == null) { strError = "日志记录中缺<readerRecord>元素"; return -1; } string strReaderRecPath = DomUtil.GetAttr(node, "recPath"); byte[] timestamp = null; byte[] output_timestamp = null; string strOutputPath = ""; // 写读者记录 lRet = channel.DoSaveTextRes(strReaderRecPath, strReaderXml, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入读者记录 '" + strReaderRecPath + "' 时发生错误: " + strError; return -1; } return 0; } // 逻辑恢复或者混合恢复 if (level == RecoverLevel.Logic || level == RecoverLevel.LogicAndSnapshot) { // string strRecoverComment = ""; string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); string strReaderBarcode = DomUtil.GetElementText(domLog.DocumentElement, "readerBarcode"); /// if (String.IsNullOrEmpty(strReaderBarcode) == true) { strError = "日志记录中<readerBarcode>元素值为空"; goto ERROR1; } string strOperator = DomUtil.GetElementText(domLog.DocumentElement, "operator"); string strOperTime = DomUtil.GetElementText(domLog.DocumentElement, "operTime"); string strOverdues = DomUtil.GetElementText(domLog.DocumentElement, "overdues"); if (String.IsNullOrEmpty(strOverdues) == true) { strError = "日志记录中<overdues>元素值为空"; goto ERROR1; } // 从overdues字符串中分析出id XmlDocument tempdom = new XmlDocument(); tempdom.LoadXml("<root />"); XmlDocumentFragment fragment = tempdom.CreateDocumentFragment(); fragment.InnerXml = strOverdues; tempdom.DocumentElement.AppendChild(fragment); XmlNode tempnode = tempdom.DocumentElement.SelectSingleNode("overdue"); if (tempnode == null) { strError = "<overdues>元素内容有误,缺乏<overdue>元素"; goto ERROR1; } string strID = DomUtil.GetAttr(tempnode, "id"); if (String.IsNullOrEmpty(strID) == true) { strError = "日志记录中<overdues>内容中<overdue>元素中id属性值为空"; goto ERROR1; } // 读入读者记录 string strReaderXml = ""; string strOutputReaderRecPath = ""; byte[] reader_timestamp = null; nRet = this.GetReaderRecXml( // Channels, channel, strReaderBarcode, out strReaderXml, out strOutputReaderRecPath, out reader_timestamp, out strError); if (nRet == 0) { strError = "读者证条码号 '" + strReaderBarcode + "' 不存在"; goto ERROR1; } if (nRet == -1) { strError = "读入证条码号为 '" + strReaderBarcode + "' 的读者记录时发生错误: " + strError; goto ERROR1; } XmlDocument readerdom = null; nRet = LibraryApplication.LoadToDom(strReaderXml, out readerdom, out strError); if (nRet == -1) { strError = "装载读者记录进入XML DOM时发生错误: " + strError; goto ERROR1; } // string strOverdueString = ""; // 根据Foregift() API要求,修改readerdom nRet = DoForegift(strAction, readerdom, ref strID, strOperator, strOperTime, out strOverdueString, out strError); if (nRet == -1) goto ERROR1; // 写回读者、册记录 byte[] output_timestamp = null; string strOutputPath = ""; // 写回读者记录 lRet = channel.DoSaveTextRes(strOutputReaderRecPath, readerdom.OuterXml, false, "content,ignorechecktimestamp", reader_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; } return 0; ERROR1: if (level == RecoverLevel.LogicAndSnapshot) { WriteErrorLog($"RecoverForegift() 用 LogicAndSnapShot 方式恢复遇到报错 {strError},后面自动改用 SnapShot 方式尝试 ..."); level = RecoverLevel.Snapshot; goto DO_SNAPSHOT; } return -1; } /* settlement 结算违约金 API: Settlement() <root> <operation>settlement</operation> 操作类型 <action>...</action> 具体动作 有settlement undosettlement delete 3种 <id>1234567-1</id> ID <operator>test</operator> 操作者 <operTime>Fri, 08 Dec 2006 04:17:45 GMT</operTime> 操作时间 <oldAmerceRecord recPath='...'>...</oldAmerceRecord> 旧违约金记录 <amerceRecord recPath='...'>...</amerceRecord> 新违约金记录 delete操作无此元素 </root> * */ public int RecoverSettlement( RmsChannelCollection Channels, RecoverLevel level, XmlDocument domLog, out string strError) { strError = ""; // 暂时把Robust当作Logic处理 if (level == RecoverLevel.Robust) level = RecoverLevel.Logic; long lRet = 0; int nRet = 0; RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } DO_SNAPSHOT: // 快照恢复 if (level == RecoverLevel.Snapshot) { string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); if (strAction == "settlement" || strAction == "undosettlement") { XmlNode node = null; string strAmerceXml = DomUtil.GetElementText(domLog.DocumentElement, "amerceRecord", out node); if (node == null) { strError = "日志记录中缺<amerceRecord>元素"; return -1; } string strAmerceRecPath = DomUtil.GetAttr(node, "recPath"); byte[] timestamp = null; byte[] output_timestamp = null; string strOutputPath = ""; // 写违约金记录 lRet = channel.DoSaveTextRes(strAmerceRecPath, strAmerceXml, false, "content,ignorechecktimestamp", timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "写入违约金记录 '" + strAmerceRecPath + "' 时发生错误: " + strError; return -1; } } else if (strAction == "delete") { XmlNode node = null; string strOldAmerceXml = DomUtil.GetElementText(domLog.DocumentElement, "oldAmerceRecord", out node); if (node == null) { strError = "日志记录中缺<oldAmerceRecord>元素"; return -1; } string strOldAmerceRecPath = DomUtil.GetAttr(node, "recPath"); // 删除违约金记录 int nRedoCount = 0; byte[] timestamp = null; byte[] output_timestamp = null; REDO_DELETE: lRet = channel.DoDeleteRes(strOldAmerceRecPath, timestamp, out output_timestamp, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) return 0; // 记录本来就不存在 if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (nRedoCount < 10) { timestamp = output_timestamp; nRedoCount++; goto REDO_DELETE; } } strError = "删除违约金记录 '" + strOldAmerceRecPath + "' 时发生错误: " + strError; return -1; } } else { strError = "未能识别的action值 '" + strAction + "'"; } return 0; } // 逻辑恢复或者混合恢复 if (level == RecoverLevel.Logic || level == RecoverLevel.LogicAndSnapshot) { string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); string strID = DomUtil.GetElementText(domLog.DocumentElement, "id"); /// if (String.IsNullOrEmpty(strID) == true) { strError = "日志记录中<id>元素值为空"; goto ERROR1; } string strOperator = DomUtil.GetElementText(domLog.DocumentElement, "operator"); string strOperTime = DomUtil.GetElementText(domLog.DocumentElement, "operTime"); // 通过id获得违约金记录的路径 string strText = ""; string strCount = ""; strCount = "<maxCount>100</maxCount>"; strText = "<item><word>" + StringUtil.GetXmlStringSimple(strID) + "</word>" + strCount + "<match>exact</match><relation>=</relation><dataType>string</dataType>" + "</item>"; string strQueryXml = "<target list='" + StringUtil.GetXmlStringSimple(this.AmerceDbName + ":" + "ID") // 2007/9/14 + "'>" + strText + "<lang>zh</lang></target>"; lRet = channel.DoSearch(strQueryXml, "amerced", "", // strOuputStyle out strError); if (lRet == -1) { strError = "检索ID为 '" + strID + "' 的违约金记录出错: " + strError; goto ERROR1; } if (lRet == 0) { strError = "没有找到id为 '" + strID + "' 的违约金记录"; goto ERROR1; } lRet = channel.DoGetSearchResult( "amerced", // strResultSetName 0, 1, "zh", null, // stop out List<string> aPath, out strError); if (lRet == -1) goto ERROR1; if (lRet == 0) { strError = "获取结果集未命中"; goto ERROR1; } if (aPath.Count != 1) { strError = "aPath.Count != 1"; goto ERROR1; } string strAmerceRecPath = aPath[0]; // 结算一个交费记录 // parameters: // bCreateOperLog 是否创建日志 // strOperTime 结算的操作时间 // strOperator 结算的操作者 // return: // -2 致命出错,不宜再继续循环调用本函数 // -1 一般出错,可以继续循环调用本函数 // 0 正常 nRet = SettlementOneRecord( "", // 确保可以执行 false, // 不创建日志 channel, strAction, strAmerceRecPath, strOperTime, strOperator, "", // 表示本机触发 out strError); if (nRet == -1 || nRet == -2) goto ERROR1; } return 0; ERROR1: if (level == RecoverLevel.LogicAndSnapshot) { WriteErrorLog($"RecoverSettlement() 用 LogicAndSnapShot 方式恢复遇到报错 {strError},后面自动改用 SnapShot 方式尝试 ..."); level = RecoverLevel.Snapshot; goto DO_SNAPSHOT; } return -1; } /* <root> <operation>writeRes</operation> <requestResPath>...</requestResPath> 资源路径参数。也就是请求API是的strResPath参数值。可能在路径中的记录ID部分包含问号,表示要追加创建新的记录 <resPath>...</resPath> 资源路径。资源的确定路径。 <ranges>...</ranges> 字节范围 <totalLength>...</totalLength> 总长度。如果为 -1,表示仅修改 metadata <metadata>...</metadata> 此元素的文本即是记录体,但注意为不透明的字符串(HtmlEncoding后的记录字符串)。 <style>...</style> 当 style 中包含 delete 子串时表示要删除这个资源 <operator>test</operator> <operTime>Fri, 08 Dec 2006 10:12:20 GMT</operTime> </root> * 可能会有一个attachment * * */ public int RecoverWriteRes( RmsChannelCollection Channels, RecoverLevel level, XmlDocument domLog, Stream attachmentLog, out string strError) { strError = ""; // 暂时把Robust当作Logic处理 if (level == RecoverLevel.Robust) level = RecoverLevel.Logic; long lRet = 0; // int nRet = 0; RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } bool bReuse = false; // 是否能够不顾RecoverLevel状态而重用部分代码 DO_SNAPSHOT: // 快照恢复 if (level == RecoverLevel.Snapshot || bReuse == true) { string strResPath = DomUtil.GetElementText( domLog.DocumentElement, "resPath"); if (string.IsNullOrEmpty(strResPath) == true) { strError = "日志记录中缺<resPath>元素"; return -1; } string strTotalLength = DomUtil.GetElementText( domLog.DocumentElement, "totalLength"); if (string.IsNullOrEmpty(strTotalLength) == true) { strError = "日志记录中缺<totalLength>元素"; return -1; } long lTotalLength = 0; try { lTotalLength = Convert.ToInt64(strTotalLength); } catch { strError = "lTotalLength值 '" + strTotalLength + "' 格式不正确"; return -1; } string strRanges = DomUtil.GetElementText( domLog.DocumentElement, "ranges"); if (lTotalLength != -1 && string.IsNullOrEmpty(strRanges) == true) { // 2017/10/26 注: 当 totalLength 为 -1 时,表示仅修改 metadata。此时 ranges 为空 // 而当 totalLength 为非 -1 值时,ranges 就不允许为空 strError = "日志记录中缺 <ranges> 元素(当 <totalLength> 元素内容为非 -1 时)"; return -1; } string strMetadata = DomUtil.GetElementText( domLog.DocumentElement, "metadata"); string strStyle = DomUtil.GetElementText( domLog.DocumentElement, "style"); // 读入记录内容 byte[] baRecord = null; if (attachmentLog != null && attachmentLog.Length > 0) { baRecord = new byte[(int)attachmentLog.Length]; attachmentLog.Seek(0, SeekOrigin.Begin); attachmentLog.Read(baRecord, 0, (int)attachmentLog.Length); } strStyle += ",ignorechecktimestamp"; byte[] timestamp = null; string strOutputResPath = ""; byte[] output_timestamp = null; if (StringUtil.IsInList("delete", strStyle) == true) { // 2015/9/3 增加 lRet = channel.DoDeleteRes(strResPath, timestamp, strStyle, out output_timestamp, out strError); } else { lRet = channel.WriteRes(strResPath, strRanges, lTotalLength, baRecord, strMetadata, strStyle, timestamp, out strOutputResPath, out output_timestamp, out strError); } if (lRet == -1) { strError = "WriteRes() '" + strResPath + "' 时发生错误: " + strError; return -1; } return 0; } // 逻辑恢复或者混合恢复 if (level == RecoverLevel.Logic || level == RecoverLevel.LogicAndSnapshot) { // 和SnapShot方式相同 bReuse = true; goto DO_SNAPSHOT; } return 0; #if NO ERROR1: if (level == RecoverLevel.LogicAndSnapshot) { level = RecoverLevel.Snapshot; goto DO_SNAPSHOT; } return -1; #endif } /* <root> <operation>repairBorrowInfo</operation> <action>...</action> 具体动作 有 repairreaderside repairitemside <readerBarcode>...</readerBarcode> <itemBarcode>...</itemBarcode> <confirmItemRecPath>...</confirmItemRecPath> 辅助判断用的册记录路径 <operator>test</operator> <operTime>Fri, 08 Dec 2006 10:12:20 GMT</operTime> </root> * * * */ public int RecoverRepairBorrowInfo( RmsChannelCollection Channels, RecoverLevel level, XmlDocument domLog, Stream attachmentLog, out string strError) { strError = ""; int nRet = 0; // 暂时把Robust当作Logic处理 if (level == RecoverLevel.Robust) level = RecoverLevel.Logic; long lRet = 0; // int nRet = 0; RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } bool bReuse = false; // 是否能够不顾RecoverLevel状态而重用部分代码 DO_SNAPSHOT: // 快照恢复 if (level == RecoverLevel.Snapshot || bReuse == true) { string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); string strReaderBarcode = DomUtil.GetElementText(domLog.DocumentElement, "readerBarcode"); if (String.IsNullOrEmpty(strReaderBarcode) == true) { strError = "<readerBarcode>元素值为空"; goto ERROR1; } // 读入读者记录 string strReaderXml = ""; string strOutputReaderRecPath = ""; byte[] reader_timestamp = null; nRet = this.GetReaderRecXml( // Channels, channel, strReaderBarcode, out strReaderXml, out strOutputReaderRecPath, out reader_timestamp, out strError); if (nRet == 0) { if (strAction == "repairreaderside") { strError = "读者证条码号 '" + strReaderBarcode + "' 不存在"; goto ERROR1; } // 从实体侧恢复的时候,是允许读者记录不存在的 } if (nRet == -1) { strError = "读入证条码号为 '" + strReaderBarcode + "' 的读者记录时发生错误: " + strError; goto ERROR1; } XmlDocument readerdom = null; if (string.IsNullOrEmpty(strReaderXml) == false) { nRet = LibraryApplication.LoadToDom(strReaderXml, out readerdom, out strError); if (nRet == -1) { strError = "装载读者记录进入XML DOM时发生错误: " + strError; goto ERROR1; } } // 校验读者证条码号参数是否和XML记录中完全一致 if (readerdom != null) { string strTempBarcode = DomUtil.GetElementText(readerdom.DocumentElement, "barcode"); if (strReaderBarcode != strTempBarcode) { strError = "修复操作被拒绝。因读者证条码号参数 '" + strReaderBarcode + "' 和读者记录中<barcode>元素内的读者证条码号值 '" + strTempBarcode + "' 不一致。"; goto ERROR1; } } // 读入册记录 string strConfirmItemRecPath = DomUtil.GetElementText(domLog.DocumentElement, "confirmItemRecPath"); string strItemBarcode = DomUtil.GetElementText(domLog.DocumentElement, "itemBarcode"); if (String.IsNullOrEmpty(strItemBarcode) == true) { strError = "<strItemBarcode>元素值为空"; goto ERROR1; } string strItemXml = ""; string strOutputItemRecPath = ""; byte[] item_timestamp = null; // 如果已经有确定的册记录路径 if (String.IsNullOrEmpty(strConfirmItemRecPath) == false) { string strMetaData = ""; lRet = channel.GetRes(strConfirmItemRecPath, out strItemXml, out strMetaData, out item_timestamp, out strOutputItemRecPath, out strError); if (lRet == -1) { strError = "根据strConfirmItemRecPath '" + strConfirmItemRecPath + "' 获得册记录失败: " + strError; goto ERROR1; } // 需要检查记录中的<barcode>元素值是否匹配册条码号 // TODO: 如果记录路径所表达的记录不存在,或者其<barcode>元素值和要求的册条码号不匹配,那么都要改用逻辑方法,也就是利用册条码号来获得记录。 // 当然,这种情况下,非常要紧的是确保数据库的素质很好,本身没有重条码号的情况出现。 } else { // 从册条码号获得册记录 // 获得册记录 // return: // -1 error // 0 not found // 1 命中1条 // >1 命中多于1条 nRet = this.GetItemRecXml( // Channels, channel, strItemBarcode, out strItemXml, 100, out List<string> aPath, out item_timestamp, out strError); if (nRet == 0) { if (strAction == "repairitemside") { strError = "册条码号 '" + strItemBarcode + "' 不存在"; goto ERROR1; } // 从读者侧恢复的时候,册条码号不存在是允许的 goto CONTINUE_REPAIR; } if (nRet == -1) { strError = "读入册条码号为 '" + strItemBarcode + "' 的册记录时发生错误: " + strError; goto ERROR1; } if (aPath.Count > 1) { strError = "册条码号为 '" + strItemBarcode + "' 的册记录有 " + aPath.Count.ToString() + " 条,但此时comfirmItemRecPath却为空"; goto ERROR1; } else { Debug.Assert(nRet == 1, ""); Debug.Assert(aPath.Count == 1, ""); if (nRet == 1) { strOutputItemRecPath = aPath[0]; } } } CONTINUE_REPAIR: XmlDocument itemdom = null; if (string.IsNullOrEmpty(strItemXml) == false) { nRet = LibraryApplication.LoadToDom(strItemXml, out itemdom, out strError); if (nRet == -1) { strError = "装载册记录进入XML DOM时发生错误: " + strError; goto ERROR1; } // 校验册条码号参数是否和XML记录中完全一致 string strTempItemBarcode = DomUtil.GetElementText(itemdom.DocumentElement, "barcode"); if (strItemBarcode != strTempItemBarcode) { strError = "修复操作被拒绝。因册条码号参数 '" + strItemBarcode + "' 和册记录中<barcode>元素内的册条码号值 '" + strTempItemBarcode + "' 不一致。"; goto ERROR1; } } if (strAction == "repairreaderside") { XmlNode nodeBorrow = readerdom.DocumentElement.SelectSingleNode("borrows/borrow[@barcode='" + strItemBarcode + "']"); if (nodeBorrow == null) { strError = "修复操作被拒绝。读者记录 " + strReaderBarcode + " 中并不存在有关册 " + strItemBarcode + " 的借阅信息。"; goto ERROR1; } if (itemdom != null) { // 看看册记录中是否有指回读者记录的链 string strBorrower = DomUtil.GetElementText(itemdom.DocumentElement, "borrower"); if (strBorrower == strReaderBarcode) { strError = "修复操作被拒绝。您所请求要修复的链,本是一条完整正确的链。可直接进行普通还书操作。"; goto ERROR1; } } // 移除读者记录侧的链 nodeBorrow.ParentNode.RemoveChild(nodeBorrow); byte[] output_timestamp = null; string strOutputPath = ""; // 写回读者记录 lRet = channel.DoSaveTextRes(strOutputReaderRecPath, readerdom.OuterXml, false, "content,ignorechecktimestamp", reader_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; } else if (strAction == "repairitemside") { // 看看册记录中是否有指向读者记录的链 string strBorrower = DomUtil.GetElementText(itemdom.DocumentElement, "borrower"); if (String.IsNullOrEmpty(strBorrower) == true) { strError = "修复操作被拒绝。您所请求要修复的册记录中,本来就没有借阅信息,因此谈不上修复。"; goto ERROR1; } if (strBorrower != strReaderBarcode) { strError = "修复操作被拒绝。您所请求要修复的册记录中,并没有指明借阅者是读者 " + strReaderBarcode + "。"; goto ERROR1; } // 看看读者记录中是否有指回链条。 if (readerdom != null) { XmlNode nodeBorrow = readerdom.DocumentElement.SelectSingleNode("borrows/borrow[@barcode='" + strItemBarcode + "']"); if (nodeBorrow != null) { strError = "修复操作被拒绝。您所请求要修复的链,本是一条完整正确的链。可直接进行普通还书操作。"; goto ERROR1; } } // 移除册记录侧的链 DomUtil.SetElementText(itemdom.DocumentElement, "borrower", ""); DomUtil.SetElementText(itemdom.DocumentElement, "borrowDate", ""); DomUtil.SetElementText(itemdom.DocumentElement, "borrowPeriod", ""); byte[] output_timestamp = null; string strOutputPath = ""; // 写回册记录 lRet = channel.DoSaveTextRes(strOutputItemRecPath, itemdom.OuterXml, false, "content,ignorechecktimestamp", item_timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; } else { strError = "不可识别的strAction值 '" + strAction + "'"; goto ERROR1; } return 0; } // 逻辑恢复或者混合恢复 if (level == RecoverLevel.Logic || level == RecoverLevel.LogicAndSnapshot) { // 和SnapShot方式相同 bReuse = true; goto DO_SNAPSHOT; } return 0; ERROR1: if (level == RecoverLevel.LogicAndSnapshot) { WriteErrorLog($"RecoverRepairBorrowInfo() 用 LogicAndSnapShot 方式恢复遇到报错 {strError},后面自动改用 SnapShot 方式尝试 ..."); level = RecoverLevel.Snapshot; goto DO_SNAPSHOT; } return -1; } /* <root> <operation>manageDatabase</operation> <action>createDatabase</action> createDatabase/initializeDatabase/refreshDatabase/deleteDatabase <databases> <database type="biblio" syntax="unimarc" usage="book" role="" inCirculation="true" name="_测试用中文图书" entityDbName="_测试用中文图书实体" orderDbName="_测试用中文图书订购" commentDbName="_测试用中文图书评注" /> </databases> <operator>supervisor</operator> <operTime>Sat, 18 Nov 2017 20:00:05 +0800</operTime> <clientAddress via="net.pipe://localhost/dp2library/xe">localhost</clientAddress> <version>1.06</version> </root> * */ // 2017/10/15 // attachment 附件流对象。注意文件指针在流的尾部 public int RecoverManageDatabase( RmsChannelCollection Channels, RecoverLevel level, XmlDocument domLog, Stream attachmentLog, string strStyle, out string strError) { strError = ""; int nRet = 0; // long lRet = 0; // 暂时把Robust当作Logic处理 if (level == RecoverLevel.Robust) level = RecoverLevel.Logic; RmsChannel channel = Channels.GetChannel(this.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } bool bReuse = false; // 是否能够不顾RecoverLevel状态而重用部分代码 DO_SNAPSHOT: // 快照恢复 if (level == RecoverLevel.Snapshot || bReuse == true) { string strTempFileName = ""; if (attachmentLog != null) { strTempFileName = this.GetTempFileName("db"); using (Stream target = File.Create(strTempFileName)) { attachmentLog.Seek(0, SeekOrigin.Begin); attachmentLog.CopyTo(target); } } string strTempDir = Path.Combine(this.TempDir, "~rcvdb"); PathUtil.CreateDirIfNeed(strTempDir); try { bool bDbNameChanged = false; string strAction = DomUtil.GetElementText(domLog.DocumentElement, "action"); if (strAction == "createDatabase") { nRet = DatabaseUtility.CreateDatabases( null, // stop channel, strTempFileName, strTempDir, out strError); if (nRet == -1) return -1; bDbNameChanged = true; // 更新 library.xml 内容 XmlNodeList nodes = domLog.DocumentElement.SelectNodes("databases/database"); nRet = AppendDatabaseElement(this.LibraryCfgDom, nodes, out strError); if (nRet == -1) return -1; this.Changed = true; } else if (strAction == "changeDatabase") { // 注意处理 attach 和 detach 风格。或者明确报错不予处理 // TODO: 操作日志中没有记载改名以前的数据库名 } else if (strAction == "initializeDatabase") { } else if (strAction == "refreshDatabase") { } else if (strAction == "deleteDatabase") { List<string> dbnames = new List<string>(); XmlNodeList databases = domLog.DocumentElement.SelectNodes("databases/database"); foreach (XmlElement database in databases) { dbnames.Add(database.GetAttribute("name")); } nRet = DeleteDatabases( null, channel, dbnames, strStyle, ref bDbNameChanged, out strError); if (nRet == -1) return -1; } else { strError = "不可识别的strAction值 '" + strAction + "'"; goto ERROR1; } if (this.Changed == true) this.ActivateManagerThread(); if (bDbNameChanged == true) { nRet = InitialKdbs( Channels, out strError); if (nRet == -1) return -1; // 重新初始化虚拟库定义 this.vdbs = null; nRet = this.InitialVdbs(Channels, out strError); if (nRet == -1) return -1; } return 0; } finally { if (string.IsNullOrEmpty(strTempDir) == false) { PathUtil.RemoveReadOnlyAttr(strTempDir); // 避免 .zip 文件中有有只读文件妨碍删除 PathUtil.DeleteDirectory(strTempDir); } if (string.IsNullOrEmpty(strTempFileName) == false) File.Delete(strTempFileName); } } // 逻辑恢复或者混合恢复 if (level == RecoverLevel.Logic || level == RecoverLevel.LogicAndSnapshot) { // 和SnapShot方式相同 bReuse = true; goto DO_SNAPSHOT; } return 0; ERROR1: if (level == RecoverLevel.LogicAndSnapshot) { WriteErrorLog($"RecoverManageDatabase() 用 LogicAndSnapShot 方式恢复遇到报错 {strError},后面自动改用 SnapShot 方式尝试 ..."); level = RecoverLevel.Snapshot; goto DO_SNAPSHOT; } return -1; } int DeleteDatabases( Stop stop, RmsChannel channel, List<string> dbnames, string strStyle, ref bool bDbNameChanged, out string strError) { strError = ""; int nRet = 0; foreach (string dbname in dbnames) { string strDbType = GetDbTypeByDbName(dbname); if (string.IsNullOrEmpty(dbname)) { // TODO: 遇到此种情况,写入错误日志 strError = "数据库 '" + dbname + "' 没有找到类型"; // return -1; continue; } if (strDbType == "biblio") { // 删除一个书目库。 // 根据书目库的库名,在 library.xml 的 itemdbgroup 中找出所有下属库的库名,然后删除它们 // return: // -1 出错 // 0 指定的数据库不存在 // 1 成功删除 nRet = this.DeleteBiblioDatabase( channel, "", dbname, "", ref bDbNameChanged, out strError); if (nRet == -1) return -1; if (StringUtil.IsInList("verify", strStyle)) { if (this.VerifyDatabaseDelete( channel, strDbType, dbname, out strError) == -1) return -1; } continue; } if (/*strDbType == "entity" || strDbType == "order" || strDbType == "issue" || strDbType == "comment"*/ ServerDatabaseUtility.IsBiblioSubType(strDbType)) { nRet = DeleteBiblioChildDatabase(channel, "", // strLibraryCodeList, dbname, "", // strLogFileName, ref bDbNameChanged, out strError); if (nRet == -1) return -1; if (StringUtil.IsInList("verify", strStyle)) { if (this.VerifyDatabaseDelete( channel, strDbType, dbname, out strError) == -1) return -1; } continue; } if (/*strDbType == "arrived" || strDbType == "amerce" || strDbType == "invoice" || strDbType == "pinyin" || strDbType == "gcat" || strDbType == "word" || strDbType == "message"*/ ServerDatabaseUtility.IsSingleDbType(strDbType)) { // 删除一个单独类型的数据库。 // 也会自动修改 library.xml 的相关元素 // parameters: // strLibraryCodeList 当前用户所管辖的分馆代码列表 // bDbNameChanged 如果数据库发生了删除或者修改名字的情况,此参数会被设置为 true。否则其值不会发生改变 // return: // -1 出错 // 0 指定的数据库不存在 // 1 成功删除 nRet = DeleteSingleDatabase(channel, "", // strLibraryCodeList, dbname, "", // strLogFileName, ref bDbNameChanged, out strError); if (nRet == -1) return -1; if (StringUtil.IsInList("verify", strStyle)) { // test // strError = "test 验证发生错误"; // return -1; if (this.VerifyDatabaseDelete(channel, strDbType, dbname, out strError) == -1) return -1; } continue; } if (ServerDatabaseUtility.IsUtilDbName(this.LibraryCfgDom, dbname) == true) { // 删除一个实用库。 // 也会自动修改 library.xml 的相关元素 // parameters: // strLibraryCodeList 当前用户所管辖的分馆代码列表 // bDbNameChanged 如果数据库发生了删除或者修改名字的情况,此参数会被设置为 true。否则其值不会发生改变 // return: // -1 出错 // 0 指定的数据库不存在 // 1 成功删除 nRet = DeleteUtilDatabase(channel, "", // strLibraryCodeList, dbname, "", // strLogFileName, ref bDbNameChanged, out strError); if (nRet == -1) return -1; if (StringUtil.IsInList("verify", strStyle)) { Debug.Assert(string.IsNullOrEmpty(strDbType) == false, ""); if (this.VerifyDatabaseDelete(channel, strDbType, dbname, out strError) == -1) return -1; } continue; } strError = "DeleteDatabases() 遭遇无法识别的数据库名 '" + dbname + "' (数据库类型 '" + strDbType + "')"; return -1; } return 0; } } public enum RecoverLevel { Logic = 0, // 逻辑操作 LogicAndSnapshot = 1, // 逻辑操作,若失败则转用快照恢复 Snapshot = 3, // (完全的)快照 Robust = 4, // 最强壮的容错恢复方式 } }
36.71099
478
0.39737
[ "Apache-2.0" ]
zgren/dp2
DigitalPlatform.LibraryServer/AppLogRecover.cs
338,856
C#
using System; namespace AlexaTVInfoSkill.Areas.HelpPage.ModelDescriptions { /// <summary> /// Describes a type model. /// </summary> public abstract class ModelDescription { public string Documentation { get; set; } public Type ModelType { get; set; } public string Name { get; set; } } }
21.1875
59
0.625369
[ "MIT" ]
kmcoulson/AlexaTvInfoSkill
AlexaTVInfoSkill/Areas/HelpPage/ModelDescriptions/ModelDescription.cs
339
C#
using System; using System.Runtime.InteropServices; namespace DbgEng { [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct _DEBUG_LAST_EVENT_INFO_EXIT_THREAD { public uint ExitCode; } }
16.916667
49
0.788177
[ "Apache-2.0" ]
rdev0/PadAnalyzer
Source/CsDebugScript.DbgEng/DbgEng/_DEBUG_LAST_EVENT_INFO_EXIT_THREAD.cs
203
C#
//------------------------------------------------------------------------------ // 此代码版权(除特别声明或在RRQMCore.XREF命名空间的代码)归作者本人若汝棋茗所有 // 源代码使用协议遵循本仓库的开源协议及附加协议,若本仓库没有设置,则按MIT开源协议授权 // CSDN博客:https://blog.csdn.net/qq_40374647 // 哔哩哔哩视频:https://space.bilibili.com/94253567 // Gitee源代码仓库:https://gitee.com/RRQM_Home // Github源代码仓库:https://github.com/RRQM // 交流QQ群:234762506 // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ using RRQMCore.Dependency; using System; namespace RRQMSocket.RPC.RRQMRPC { /// <summary> /// UdpRPCParser /// </summary> public class UdpRpcParserConfig : UdpSessionConfig { /// <summary> /// 代理令箭,当客户端获取代理文件时需验证令箭, 所需类型<see cref="string"/> /// </summary> public static readonly DependencyProperty ProxyTokenProperty = DependencyProperty.Register("ProxyToken", typeof(string), typeof(UdpRpcParserConfig), null); /// <summary> /// 序列化转换器, 所需类型<see cref="RRQMRPC.SerializationSelector"/> /// </summary> public static readonly DependencyProperty SerializationSelectorProperty = DependencyProperty.Register("SerializationSelector", typeof(SerializationSelector), typeof(UdpRpcParserConfig), new DefaultSerializationSelector()); /// <summary> /// 代理令箭,当客户端获取代理文件时需验证令箭 /// </summary> public string ProxyToken { get { return (string)GetValue(ProxyTokenProperty); } set { SetValue(ProxyTokenProperty, value); } } /// <summary> /// 序列化转换器 /// </summary> public SerializationSelector SerializationSelector { get { return (SerializationSelector)GetValue(SerializationSelectorProperty); } set { SetValue(SerializationSelectorProperty, value); } } } }
37.480769
160
0.573628
[ "Apache-2.0" ]
RRQM/RRQMSocket.RPC
RRQMSocket.RPC/RRQMRPC/Config/UdpRpcParserConfig.cs
2,287
C#
using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; namespace RucheHome.Util { /// <summary> /// プロパティ変更通知をサポートするオブジェクトのコレクションクラス。 /// </summary> /// <typeparam name="TItem"> /// コレクション要素型。 INotifyPropertyChanged インタフェースを実装する必要がある。 /// </typeparam> public class BindableCollection<TItem> : ObservableCollection<TItem> where TItem : INotifyPropertyChanged { /// <summary> /// コンストラクタ。 /// </summary> public BindableCollection() : base() { } /// <summary> /// コンストラクタ。 /// </summary> /// <param name="items">コレクションの初期値となるアイテム列挙。</param> public BindableCollection(IEnumerable<TItem> items) : base(items) { foreach (var item in this) { if (item != null) { item.PropertyChanged += this.OnItemPropertyChanged; } } } /// <summary> /// コレクション要素のプロパティ値が変更された時に呼び出されるイベント。 /// </summary> public event PropertyChangedEventHandler ItemPropertyChanged = null; /// <summary> /// 要素の挿入時に呼び出される。 /// </summary> /// <param name="index">挿入先インデックス。</param> /// <param name="item">挿入する要素。</param> protected override void InsertItem(int index, TItem item) { if (item != null) { item.PropertyChanged += this.OnItemPropertyChanged; } base.InsertItem(index, item); } /// <summary> /// 要素の上書き時に呼び出される。 /// </summary> /// <param name="index">上書き先インデックス。</param> /// <param name="item">上書きする要素。</param> protected override void SetItem(int index, TItem item) { var oldItem = this[index]; if (oldItem != null) { oldItem.PropertyChanged -= this.OnItemPropertyChanged; } if (item != null) { item.PropertyChanged += this.OnItemPropertyChanged; } base.SetItem(index, item); } /// <summary> /// 要素の削除時に呼び出される。 /// </summary> /// <param name="index">削除先インデックス。</param> protected override void RemoveItem(int index) { var oldItem = this[index]; if (oldItem != null) { oldItem.PropertyChanged -= this.OnItemPropertyChanged; } base.RemoveItem(index); } /// <summary> /// 要素のクリア時に呼び出される。 /// </summary> protected override void ClearItems() { foreach (var item in this) { if (item != null) { item.PropertyChanged -= this.OnItemPropertyChanged; } } base.ClearItems(); } /// <summary> /// コレクション要素のプロパティ値が変更された時に呼び出される。 /// </summary> /// <param name="sender">コレクション要素。</param> /// <param name="e">プロパティ値変更イベントパラメータ。</param> protected virtual void OnItemPropertyChanged( object sender, PropertyChangedEventArgs e) => this.ItemPropertyChanged?.Invoke(sender, e); } }
27.950413
76
0.50414
[ "MIT" ]
biss-git/KISS4V
RucheHomeLib/Util/BindableCollection.cs
3,968
C#
#pragma checksum "C:\Users\DRAGON\Downloads\eShop-master\eShop-master\eShop-master\MyShop\MyShopK6\Views\_ViewStart.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "d563719e351c2799e4dee3a31e8cc8c1b76afa2d" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views__ViewStart), @"mvc.1.0.view", @"/Views/_ViewStart.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/_ViewStart.cshtml", typeof(AspNetCore.Views__ViewStart))] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #line 1 "C:\Users\DRAGON\Downloads\eShop-master\eShop-master\eShop-master\MyShop\MyShopK6\Views\_ViewImports.cshtml" using MyShopK6; #line default #line hidden #line 2 "C:\Users\DRAGON\Downloads\eShop-master\eShop-master\eShop-master\MyShop\MyShopK6\Views\_ViewImports.cshtml" using MyShopK6.Models; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"d563719e351c2799e4dee3a31e8cc8c1b76afa2d", @"/Views/_ViewStart.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"e770d053092ef2b99ddd7a06e931c96cc669487a", @"/Views/_ViewImports.cshtml")] public class Views__ViewStart : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #line 1 "C:\Users\DRAGON\Downloads\eShop-master\eShop-master\eShop-master\MyShop\MyShopK6\Views\_ViewStart.cshtml" Layout = "_FrontEnd"; #line default #line hidden } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
54.777778
208
0.757945
[ "Apache-2.0" ]
yennhi2404/k6shoponline
MyShop/MyShopK6/obj/Debug/netcoreapp2.2/Razor/Views/_ViewStart.g.cshtml.cs
2,958
C#
using Domain.Interfaces; using Domain.Entities; namespace Infra.Authentication { public class FakeAuthentication : IToken { public string TokenGenerateClient(Client client) { return "token-implementation-fake"; } public string TokenGenerateOperator(Operator op) { return "token-implementation-fake"; } } }
21.722222
56
0.631714
[ "MIT" ]
Micheler720/Localiza
Tests/Infra/Authentication/FakeAuthentication.cs
391
C#
using RWCustom; using System; using System.Collections.Generic; using UnityEngine; namespace PrimitiveArmory { public class PlayerHooks { public static int swingTime = 10; // Time between regular swings. public static float comboTimeMultiplier = 4f; // Multiplier for how long after a player finishes a combo before they can swing again. private static int postComboCooldown = (int)(swingTime * comboTimeMultiplier); // Time after a successful combo until the player can swing again. public static int maxCombo = 2; // The maximum combo a player can attain. public static float comboCancelMultiplier = 2.5f; public static float maxDrawTime = 35.0f; public struct ClubState { public int swingTimer; public int swingDelay; public int comboCount; public int comboCooldown; public bool firstHit; } public struct BowState { public float drawSpeed; public float drawTime; public int controlLocked; public bool isDrawing; public bool released; public bool useAlternateAim; public float arrowLethality; public Vector2 aimDir; public Vector2 lastAimDir; } public struct GlobalState { public float rangedSkill; public float meleeSkill; public int animTimer; public EquippedArmor headSlot; public EquippedArmor bodySlot; public EquippedArmor accessorySlot; public BackSlot backSlot; } public class EquippedArmor { public Player owner; public Armor armor; public Armor.ArmorSlot slot; public bool increment; public int counter; public float flip; public bool interactionLocked; public AbstractArmorStick abstractStick; public EquippedArmor(Player owner, Armor.ArmorSlot slot) { this.owner = owner; this.slot = slot; } } public class BackSlot { public Player owner; public Weapon backItem; public bool increment; public int counter; public float flip; public bool interactionLocked; public AbstractWeaponOnBackStick abstractStick; public bool HasAWeapon => backItem != null; public BackSlot(Player owner) { this.owner = owner; } public void Update(bool eu) { if (!interactionLocked && increment) { counter++; if (backItem != null && counter > 20) { WeaponToHand(eu); counter = 0; } else if (backItem == null && counter > 20) { for (int i = 0; i < 2; i++) { if (owner.grasps[i] != null && owner.grasps[i].grabbed is Weapon && CanIStashThis(owner.grasps[i].grabbed as Weapon)) { owner.bodyChunks[0].pos += Custom.DirVec(owner.grasps[i].grabbed.firstChunk.pos, owner.bodyChunks[0].pos) * 2f; WeaponToBack(owner.grasps[i].grabbed as Weapon); counter = 0; break; } } } } else { counter = 0; } if (!owner.input[0].pckp) { interactionLocked = false; } increment = false; } public void GraphicsModuleUpdated(bool actuallyViewed, bool eu) { if (backItem == null) { return; } if (backItem.slatedForDeletetion || backItem.grabbedBy.Count > 0) { if (abstractStick != null) { abstractStick.Deactivate(); } backItem = null; return; } Vector2 vector = owner.mainBodyChunk.pos; Vector2 vector2 = owner.bodyChunks[1].pos; if (owner.graphicsModule != null) { vector = Vector2.Lerp((owner.graphicsModule as PlayerGraphics).drawPositions[0, 0], (owner.graphicsModule as PlayerGraphics).head.pos, 0.2f); vector2 = (owner.graphicsModule as PlayerGraphics).drawPositions[1, 0]; } Vector2 vector3 = Custom.DirVec(vector2, vector); if (owner.Consious && owner.bodyMode != Player.BodyModeIndex.ZeroG && owner.room.gravity > 0f) { if (owner.bodyMode == Player.BodyModeIndex.Default && owner.animation == Player.AnimationIndex.None && owner.standing && owner.bodyChunks[1].pos.y < owner.bodyChunks[0].pos.y - 6f) { flip = Custom.LerpAndTick(flip, (float)owner.input[0].x * 0.3f, 0.05f, 0.02f); } else if (owner.bodyMode == Player.BodyModeIndex.Stand && owner.input[0].x != 0) { flip = Custom.LerpAndTick(flip, owner.input[0].x, 0.02f, 0.1f); } else { flip = Custom.LerpAndTick(flip, (float)owner.flipDirection * Mathf.Abs(vector3.x), 0.15f, 355f / (678f * (float)Math.PI)); } if (counter > 12 && !interactionLocked && owner.input[0].x != 0 && owner.standing) { float num = 0f; for (int i = 0; i < owner.grasps.Length; i++) { if (owner.grasps[i] == null) { num = ((i != 0) ? 1f : (-1f)); break; } } backItem.setRotation = Custom.DegToVec(Custom.AimFromOneVectorToAnother(vector2, vector) + Custom.LerpMap(counter, 12f, 20f, 0f, 360f * num)); } else { backItem.setRotation = (vector3 - Custom.PerpendicularVector(vector3) * 0.9f * (1f - Mathf.Abs(flip))).normalized; } backItem.ChangeOverlap(vector3.y < -0.1f && owner.bodyMode != Player.BodyModeIndex.ClimbingOnBeam); } else { flip = Custom.LerpAndTick(flip, 0f, 0.15f, 0.142857149f); backItem.setRotation = vector3 - Custom.PerpendicularVector(vector3) * 0.9f; backItem.ChangeOverlap(newOverlap: false); } backItem.firstChunk.MoveFromOutsideMyUpdate(eu, Vector2.Lerp(vector2, vector, 0.6f) - Custom.PerpendicularVector(vector2, vector) * 7.5f * flip); backItem.firstChunk.vel = owner.mainBodyChunk.vel; backItem.rotationSpeed = 0f; } public void WeaponToHand(bool eu) { if (backItem == null) { return; } for (int i = 0; i < 2; i++) { if (owner.grasps[i] != null && owner.Grabability(owner.grasps[i].grabbed) >= Player.ObjectGrabability.BigOneHand) { return; } } int targetHand = -1; for (int i = 0; i < 2; i++) { if (targetHand != -1) { break; } if (owner.grasps[i] == null) { targetHand = i; } } if (targetHand != -1) { if (owner.graphicsModule != null) { backItem.firstChunk.MoveFromOutsideMyUpdate(eu, (owner.graphicsModule as PlayerGraphics).hands[targetHand].pos); } owner.SlugcatGrab(backItem, targetHand); backItem = null; interactionLocked = true; owner.noPickUpOnRelease = 20; owner.room.PlaySound(SoundID.Slugcat_Pick_Up_Spear, owner.mainBodyChunk); if (abstractStick != null) { abstractStick.Deactivate(); abstractStick = null; } } } public void WeaponToBack(Weapon backItem) { if (this.backItem != null) { return; } for (int i = 0; i < 2; i++) { if (owner.grasps[i] != null && owner.grasps[i].grabbed == backItem) { owner.ReleaseGrasp(i); break; } } this.backItem = backItem; this.backItem.ChangeMode(Weapon.Mode.OnBack); interactionLocked = true; owner.noPickUpOnRelease = 20; owner.room.PlaySound(SoundID.Slugcat_Stash_Spear_On_Back, owner.mainBodyChunk); if (abstractStick != null) { abstractStick.Deactivate(); } abstractStick = new AbstractWeaponOnBackStick(owner.abstractPhysicalObject, this.backItem.abstractPhysicalObject); } public void DropItem() { if (backItem != null) { backItem.firstChunk.vel = owner.mainBodyChunk.vel + Custom.RNV() * 3f * UnityEngine.Random.value; backItem.ChangeMode(Weapon.Mode.Free); backItem = null; if (abstractStick != null) { abstractStick.Deactivate(); abstractStick = null; } } } } public class AbstractArmorStick : AbstractPhysicalObject.AbstractObjectStick { public AbstractPhysicalObject Player { get { return A; } set { A = value; } } public AbstractPhysicalObject Armor { get { return B; } set { B = value; } } public AbstractArmorStick(AbstractPhysicalObject player, AbstractPhysicalObject mask) : base(player, mask) { } public override string SaveToString(int roomIndex) { return roomIndex + "<stkA>gripStk<stkA>" + A.ID.ToString() + "<stkA>" + B.ID.ToString() + "<stkA>" + "2" + "<stkA>" + "1"; } } public class AbstractWeaponOnBackStick : AbstractPhysicalObject.AbstractObjectStick { public AbstractPhysicalObject Player { get { return A; } set { A = value; } } public AbstractPhysicalObject Weapon { get { return B; } set { B = value; } } public AbstractWeaponOnBackStick(AbstractPhysicalObject player, AbstractPhysicalObject weapon) : base(player, weapon) { } public override string SaveToString(int roomIndex) { return roomIndex + "<stkA>wepOnBackStick<stkA>" + A.ID.ToString() + "<stkA>" + B.ID.ToString() + "<stkA>" + "2" + "<stkA>" + "1"; } } public static bool CanPutWeaponToBack(Player player, Weapon weapon) { if (player.spearOnBack != null) { int playerNumber = player.playerState.playerNumber; if (player.spearOnBack.HasASpear) { return false; } switch (weapon) { case Club club: return !globalStats[playerNumber].backSlot.HasAWeapon && (player.grasps[0]?.grabbed is Club || player.grasps[1]?.grabbed is Club) && !player.spearOnBack.HasASpear; case Bow bow: return !globalStats[playerNumber].backSlot.HasAWeapon && (player.grasps[0]?.grabbed is Bow || player.grasps[1]?.grabbed is Bow) && !player.spearOnBack.HasASpear; default: break; } } return false; } public static ClubState[] clubStats; public static GlobalState[] globalStats; public static Player.InputPackage[] playerInput; public static BowState[] bowStats; public static int totalPlayerNum = 4; public static void Patch() { Debug.Log("Patching Player Constructor"); On.Player.ctor += (PlayerPatch); Debug.Log("Patching Player.Grabability"); On.Player.Grabability += GrababilityPatch; Debug.Log("Patching Player.Update"); On.Player.Update += PlayerUpdatePatch; Debug.Log("Patching Player.ThrowObject"); On.Player.ThrowObject += ThrowPatch; Debug.Log("Patching Player.GraphicsModuleUpdated"); On.Player.GraphicsModuleUpdated += GraphicsModulePatch; Debug.Log("Patching Player.Die"); On.Player.Die += DeathPatch; Debug.Log("Patching Player.SpearOnBack.SpearToBack"); On.Player.SpearOnBack.SpearToBack += SpearToBackPatch; Debug.Log("Patching Player.checkInput"); On.Player.checkInput += CheckInputPatch; clubStats = new ClubState[totalPlayerNum]; bowStats = new BowState[totalPlayerNum]; globalStats = new GlobalState[totalPlayerNum]; playerInput = new Player.InputPackage[totalPlayerNum]; } private static void PlayerPatch(On.Player.orig_ctor orig, Player player, AbstractCreature abstractCreature, World world) { orig(player, abstractCreature, world); int playerNumber = player.playerState.playerNumber; if (playerNumber >= totalPlayerNum) { Debug.Log("Extra slugcats detected: " + playerNumber); MoreSlugcat(playerNumber); } clubStats[playerNumber] = new ClubState { swingDelay = 0, swingTimer = 0, comboCount = 0, comboCooldown = 0, firstHit = false }; bowStats[playerNumber] = new BowState { drawTime = 0.0f, aimDir = new Vector2(0, 0), lastAimDir = bowStats[playerNumber].aimDir, controlLocked = 0, isDrawing = false, released = false }; globalStats[playerNumber] = new GlobalState { headSlot = null, bodySlot = null, accessorySlot = null, backSlot = null }; switch (player.slugcatStats.name) { case SlugcatStats.Name.White: globalStats[playerNumber].meleeSkill = 1f; globalStats[playerNumber].rangedSkill = 1f; bowStats[playerNumber].arrowLethality = 1f; break; case SlugcatStats.Name.Red: globalStats[playerNumber].meleeSkill = 1.25f; globalStats[playerNumber].rangedSkill = 0.8f; bowStats[playerNumber].arrowLethality = 1.15f; break; case SlugcatStats.Name.Yellow: globalStats[playerNumber].meleeSkill = 0.75f; globalStats[playerNumber].rangedSkill = 1.45f; bowStats[playerNumber].arrowLethality = 0.85f; break; default: globalStats[playerNumber].meleeSkill = 1f; globalStats[playerNumber].rangedSkill = 1f; bowStats[playerNumber].arrowLethality = 1f; break; } bowStats[playerNumber].drawSpeed = globalStats[playerNumber].rangedSkill * 1f; } private static void PlayerUpdatePatch(On.Player.orig_Update orig, Player player, bool eu) { int playerNumber = player.playerState.playerNumber; bowStats[playerNumber].aimDir = GetAimDir(player).normalized; if (bowStats[playerNumber].aimDir.magnitude > 0.4f) bowStats[playerNumber].lastAimDir = bowStats[playerNumber].aimDir; if (!bowStats[playerNumber].isDrawing && bowStats[playerNumber].released) { PhysicalObject releasedObject = GetOppositeObject(player, 0); if (releasedObject != null && releasedObject.abstractPhysicalObject.type == EnumExt_NewItems.Arrow) { Arrow arrow = releasedObject as Arrow; bowStats[playerNumber].controlLocked = 10; Vector2 launchDir = bowStats[playerNumber].aimDir; Vector2 thrownPos = player.firstChunk.pos + launchDir * 10f + new Vector2(0f, 4f); player.grasps[1].Release(); arrow.Thrown(player, thrownPos, player.mainBodyChunk.pos - launchDir * 10f, new IntVector2(player.ThrowDirection, 0), Mathf.Lerp(1f, 1.5f, player.Adrenaline), eu); foreach (BodyChunk bodyChunk in arrow.bodyChunks) { bodyChunk.pos = player.mainBodyChunk.pos + bowStats[playerNumber].lastAimDir * 10f; bodyChunk.vel = (bowStats[playerNumber].lastAimDir.normalized) * (40f * GetFireStrength(player)); } player.bodyChunks[0].vel -= launchDir * 3f; player.bodyChunks[1].vel -= launchDir * 4.5f; arrow.arrowDamageBonus = (1f * GetFireStrength(player)) * bowStats[playerNumber].arrowLethality; arrow.stillFlyingCounter = Arrow.maxFlyingCount; arrow.rotation = launchDir.normalized; } bowStats[playerNumber].released = false; } orig(player, eu); if (globalStats[playerNumber].backSlot == null) globalStats[playerNumber].backSlot = new BackSlot(player); if (globalStats[playerNumber].headSlot == null) globalStats[playerNumber].headSlot = new EquippedArmor(player, Armor.ArmorSlot.Head); if (globalStats[playerNumber].bodySlot == null) globalStats[playerNumber].bodySlot = new EquippedArmor(player, Armor.ArmorSlot.Body); if (globalStats[playerNumber].accessorySlot == null) globalStats[playerNumber].accessorySlot = new EquippedArmor(player, Armor.ArmorSlot.Accessory); if (player.input[0].pckp && !globalStats[playerNumber].backSlot.interactionLocked && ((CanPutWeaponToBack(player, (player.grasps[0]?.grabbed as Weapon)) || CanPutWeaponToBack(player, (player.grasps[1]?.grabbed as Weapon))) || CanRetrieveWeaponFromBack(player)) && player.CanPutSpearToBack) { globalStats[playerNumber].backSlot.increment = true; } else { globalStats[playerNumber].backSlot.increment = false; } if (player.input[0].pckp && player.grasps[0] != null && player.grasps[0].grabbed is Creature && player.CanEatMeat(player.grasps[0].grabbed as Creature) && (player.grasps[0].grabbed as Creature).Template.meatPoints > 0) { globalStats[playerNumber].backSlot.increment = false; globalStats[playerNumber].backSlot.interactionLocked = true; } else if (player.swallowAndRegurgitateCounter > 90) { globalStats[playerNumber].backSlot.increment = false; globalStats[playerNumber].backSlot.interactionLocked = true; } globalStats[playerNumber].backSlot.Update(eu); if (globalStats[playerNumber].backSlot.HasAWeapon && player.spearOnBack.increment) { player.spearOnBack.increment = false; } for (int i = 0; i < 2; i++) { if (player.grasps[i] == null) continue; PhysicalObject usedObject = player.grasps[i].grabbed; switch (usedObject) { case Club club: Vector2 clubTip = (usedObject.firstChunk.pos + (usedObject as Weapon).rotation * 50f); SharedPhysics.CollisionResult collisionResult = SharedPhysics.TraceProjectileAgainstBodyChunks((usedObject as SharedPhysics.IProjectileTracer), player.room, usedObject.firstChunk.pos, ref clubTip, 10f, player.collisionLayer, player, true); if (collisionResult.obj != null && clubStats[playerNumber].firstHit) { clubStats[playerNumber].firstHit = false; bool arenaHit = false; if (usedObject.abstractPhysicalObject.world.game.IsArenaSession && usedObject.abstractPhysicalObject.world.game.GetArenaGameSession.GameTypeSetup.spearHitScore != 0 && player != null && collisionResult.obj is Creature) { arenaHit = true; if ((collisionResult.obj as Creature).State is HealthState && ((collisionResult.obj as Creature).State as HealthState).health <= 0f) { arenaHit = false; } else if (!((collisionResult.obj as Creature).State is HealthState) && (collisionResult.obj as Creature).State.dead) { arenaHit = false; } } if (collisionResult.obj is Creature) { player.room.socialEventRecognizer.WeaponAttack(usedObject as Club, player, collisionResult.obj as Creature, hit: true); player.room.PlaySound(SoundID.Rock_Hit_Creature, collisionResult.chunk); bool iKilledThis = false; if (((collisionResult.obj as Creature).State as HealthState).health > 0f) { iKilledThis = true; } (collisionResult.obj as Creature).Violence(usedObject.firstChunk, (usedObject as Weapon).rotation * usedObject.firstChunk.mass * 2f, collisionResult.chunk, collisionResult.onAppendagePos, Creature.DamageType.Blunt, globalStats[playerNumber].meleeSkill * 0.6f, 20f); if (((collisionResult.obj as Creature).State as HealthState).health <= 0f && iKilledThis) { player.room.socialEventRecognizer.Killing(player, collisionResult.obj as Creature); } if (arenaHit) { usedObject.abstractPhysicalObject.world.game.GetArenaGameSession.PlayerLandSpear(player, collisionResult.obj as Creature); } } else { player.room.PlaySound(SoundID.Rock_Hit_Wall, collisionResult.chunk); } } break; } } if (clubStats[playerNumber].swingTimer > 0) clubStats[playerNumber].swingTimer--; if (bowStats[playerNumber].controlLocked > 0) bowStats[playerNumber].controlLocked--; if (clubStats[playerNumber].swingDelay > 0) clubStats[playerNumber].swingDelay--; if (clubStats[playerNumber].comboCooldown > 0) { clubStats[playerNumber].comboCooldown--; if (clubStats[playerNumber].comboCooldown == 0) { clubStats[playerNumber].comboCount = 0; } } if (globalStats[playerNumber].animTimer > 0) { globalStats[playerNumber].animTimer--; if (globalStats[playerNumber].animTimer == 0 && clubStats[playerNumber].firstHit) { clubStats[playerNumber].firstHit = false; } } if (bowStats[playerNumber].isDrawing) { bowStats[playerNumber].drawTime = Mathf.Clamp(bowStats[playerNumber].drawTime + bowStats[playerNumber].drawSpeed, 0.0f, maxDrawTime); } else { bowStats[playerNumber].drawTime = Mathf.Clamp(bowStats[playerNumber].drawTime - (bowStats[playerNumber].drawSpeed * 3.0f), 0.0f, maxDrawTime); } } public static void MoreSlugcat(int slugcatNum) { List<ClubState> clubState = new List<ClubState>(); List<BowState> bowState = new List<BowState>(); List<GlobalState> globalState = new List<GlobalState>(); List<Player.InputPackage> inputList = new List<Player.InputPackage>(); for (int i = 0; i < clubStats.Length; i++) { clubState.Add(clubStats[i]); globalState.Add(globalStats[i]); bowState.Add(bowStats[i]); inputList.Add(inputList[i]); } totalPlayerNum = slugcatNum + 1; clubStats = new ClubState[totalPlayerNum]; bowStats = new BowState[totalPlayerNum]; globalStats = new GlobalState[totalPlayerNum]; playerInput = new Player.InputPackage[totalPlayerNum]; for (int j = 0; j < clubStats.Length; j++) { clubStats[j] = clubState[j]; bowStats[j] = bowState[j]; globalStats[j] = globalState[j]; playerInput[j] = inputList[j]; } } #region Backslot Logic public static bool CanIStashThis(Weapon weapon) { switch (weapon) { case Bow bow: case Club club: return true; default: return false; } } public static bool CanRetrieveWeaponFromBack(Player player) { int playerNumber = player.playerState.playerNumber; int activeHand = -1; for (int i = 0; i < 2; i++) { if (player.grasps[i] == null) { activeHand = i; continue; } if (player.grasps[i]?.grabbed is IPlayerEdible || player.grasps[i].grabbed is Spear) { return false; } if (player.Grabability(player.grasps[i].grabbed) >= Player.ObjectGrabability.TwoHands) { return false; } } if (player.spearOnBack != null && player.spearOnBack.HasASpear) { return false; } return globalStats[playerNumber].backSlot.HasAWeapon && activeHand > -1; } private static void SpearToBackPatch(On.Player.SpearOnBack.orig_SpearToBack orig, Player.SpearOnBack spear, Spear spr) { int playerNumber = spear.owner.playerState.playerNumber; if (globalStats[playerNumber].backSlot.backItem is Weapon) return; orig(spear, spr); } #endregion private static void CheckInputPatch(On.Player.orig_checkInput orig, Player player) { int playerNumber = player.playerState.playerNumber; orig(player); if (player.stun == 0 && !player.dead) { PhysicalObject objectChecked; try { objectChecked = player.grasps[0].grabbed; } catch { objectChecked = null; } if ((player.input[playerNumber].thrw && objectChecked != null && objectChecked.abstractPhysicalObject.type == EnumExt_NewItems.Bow) || bowStats[playerNumber].controlLocked > 0) { playerInput[playerNumber] = player.input[0]; player.input[0].x = 0; player.input[0].y = 0; Player.InputPackage[] input = player.input; int x = 0; player.input[x].analogueDir = input[x].analogueDir * 0f; bowStats[playerNumber].isDrawing = true; bowStats[playerNumber].released = true; } else { bowStats[playerNumber].isDrawing = false; } } } private static void DeathPatch(On.Player.orig_Die orig, Player player) { int playerNumber = player.playerState.playerNumber; if (globalStats[playerNumber].backSlot != null && globalStats[playerNumber].backSlot.backItem != null) { globalStats[playerNumber].backSlot.DropItem(); } orig(player); } public static void GraphicsModulePatch(On.Player.orig_GraphicsModuleUpdated orig, Player player, bool actuallyViewed, bool eu) { orig(player, actuallyViewed, eu); int playerNumber = player.playerState.playerNumber; if (globalStats[playerNumber].backSlot != null) globalStats[playerNumber].backSlot.GraphicsModuleUpdated(actuallyViewed, eu); for (int i = 0; i < 2; i++) { if (player.grasps[i] == null) continue; if (actuallyViewed) { Vector2 vector = Custom.DirVec(player.mainBodyChunk.pos, player.grasps[i].grabbed.bodyChunks[0].pos) * ((i != 0) ? 1f : (-1f)); switch (player.grasps[i].grabbed) { case Club club: player.grasps[i].grabbed.firstChunk.vel = (player.graphicsModule as PlayerGraphics).hands[i].vel; player.grasps[i].grabbed.firstChunk.MoveFromOutsideMyUpdate(eu, (player.graphicsModule as PlayerGraphics).hands[i].pos); if (player.animation != Player.AnimationIndex.HangFromBeam) { vector = Custom.PerpendicularVector(vector); } if (player.animation != Player.AnimationIndex.ClimbOnBeam) { vector = Vector3.Slerp(vector, Custom.DegToVec((80f + Mathf.Cos((float)(player.animationFrame + ((!player.leftFoot) ? 3 : 9)) / 12f * 2f * (float)Math.PI) * 4f * (player.graphicsModule as PlayerGraphics).spearDir) * (player.graphicsModule as PlayerGraphics).spearDir), Mathf.Abs((player.graphicsModule as PlayerGraphics).spearDir)); } if (globalStats[playerNumber].animTimer > 0) { float swingProgress = (float)globalStats[playerNumber].animTimer / (float)swingTime; float swingAngle = Mathf.Lerp(110f, -20f, swingProgress * swingProgress); vector = Custom.DegToVec(swingAngle); (player.grasps[i].grabbed as Club).isSwinging = true; if (player.ThrowDirection < 0) { vector = new Vector2(-vector.x, vector.y); } (player.graphicsModule as PlayerGraphics).hands[i].reachingForObject = true; player.grasps[i].grabbed.firstChunk.MoveFromOutsideMyUpdate(eu, player.mainBodyChunk.pos + vector * 25f); (player.graphicsModule as PlayerGraphics).hands[i].absoluteHuntPos = player.grasps[i].grabbed.firstChunk.pos; } else { (player.grasps[i].grabbed as Club).isSwinging = false; } (player.grasps[i].grabbed as Weapon).setRotation = vector; (player.grasps[i].grabbed as Weapon).rotationSpeed = 0f; break; case Bow bow: // player.grasps[i].grabbed.firstChunk.vel = (player.graphicsModule as PlayerGraphics).hands[i].vel; // player.grasps[i].grabbed.firstChunk.MoveFromOutsideMyUpdate(eu, (player.graphicsModule as PlayerGraphics).hands[i].pos); if (player.bodyMode == Player.BodyModeIndex.Crawl) { vector = Custom.DirVec(player.bodyChunks[1].pos, Vector2.Lerp(player.grasps[i].grabbed.bodyChunks[0].pos, player.bodyChunks[0].pos, 0.8f)); } if (player.animation == Player.AnimationIndex.ClimbOnBeam) { vector.y = Mathf.Abs(vector.y); vector = Vector3.Slerp(vector, Custom.DirVec(player.bodyChunks[1].pos, player.bodyChunks[0].pos), 0.75f); } vector = Vector3.Slerp(vector, Custom.DegToVec((35f + Mathf.Cos((float)(player.animationFrame + ((!player.leftFoot) ? 3 : 9)) / 12f * 2f * (float)Math.PI) * 4f * (player.graphicsModule as PlayerGraphics).spearDir) * (player.graphicsModule as PlayerGraphics).spearDir), Mathf.Abs((player.graphicsModule as PlayerGraphics).spearDir)); if (i == 1) { vector = Vector2.Lerp(-vector, vector, Mathf.Abs(player.mainBodyChunk.vel.x) / 4.5f); } if (bowStats[playerNumber].isDrawing) { vector = -bowStats[playerNumber].lastAimDir; (player.graphicsModule as PlayerGraphics).hands[i].reachingForObject = true; player.grasps[i].grabbed.firstChunk.MoveFromOutsideMyUpdate(eu, player.mainBodyChunk.pos + bowStats[playerNumber].lastAimDir * 20f); (player.graphicsModule as PlayerGraphics).LookAtPoint(player.grasps[i].grabbed.firstChunk.pos, 10000.0f); (player.graphicsModule as PlayerGraphics).hands[i].absoluteHuntPos = player.grasps[i].grabbed.firstChunk.pos; } (player.grasps[i].grabbed as Weapon).setRotation = vector; (player.grasps[i].grabbed as Weapon).rotationSpeed = 0f; if (i == 0) { int offGrasp = GetOppositeHand(i); PhysicalObject offObject = GetOppositeObject(player, i); if (offObject != null && offObject.abstractPhysicalObject.type == EnumExt_NewItems.Arrow) { player.grasps[offGrasp].grabbed.firstChunk.MoveFromOutsideMyUpdate(eu, player.grasps[0].grabbed.firstChunk.pos + ((player.grasps[i].grabbed as Weapon).rotation * Mathf.Lerp(-1, 8, (player.grasps[i].grabbed as Bow).drawProgress))); (player.graphicsModule as PlayerGraphics).hands[offGrasp].reachingForObject = true; (player.graphicsModule as PlayerGraphics).hands[offGrasp].absoluteHuntPos = player.grasps[0].grabbed.firstChunk.pos + ((player.grasps[i].grabbed as Weapon).rotation * Mathf.Lerp(10, 20, (player.grasps[i].grabbed as Bow).drawProgress)); (player.grasps[offGrasp].grabbed as Weapon).ChangeOverlap((player.grasps[i].grabbed as Weapon).inFrontOfObjects == 1); (player.grasps[i].grabbed as Bow).drawProgress = Mathf.Pow(bowStats[playerNumber].drawTime / maxDrawTime, 2); (offObject as Weapon).setRotation = -vector; } else if (offObject == null) { (player.graphicsModule as PlayerGraphics).hands[offGrasp].reachingForObject = true; (player.graphicsModule as PlayerGraphics).hands[offGrasp].absoluteHuntPos = player.grasps[0].grabbed.firstChunk.pos + ((player.grasps[i].grabbed as Weapon).rotation * Mathf.Lerp(10, 20, (player.grasps[i].grabbed as Bow).drawProgress)); (player.grasps[i].grabbed as Bow).drawProgress = Mathf.Pow(bowStats[playerNumber].drawTime / maxDrawTime, 2); } } break; case Arrow arrow: if (i == 1) { int offGrasp = GetOppositeHand(i); PhysicalObject offObject = GetOppositeObject(player, i); if (offObject != null && offObject.abstractPhysicalObject.type == EnumExt_NewItems.Bow) { break; } } player.grasps[i].grabbed.firstChunk.vel = (player.graphicsModule as PlayerGraphics).hands[i].vel; player.grasps[i].grabbed.firstChunk.MoveFromOutsideMyUpdate(eu, (player.graphicsModule as PlayerGraphics).hands[i].pos); if (player.bodyMode == Player.BodyModeIndex.Crawl) { vector = Custom.DirVec(player.bodyChunks[1].pos, Vector2.Lerp(player.grasps[i].grabbed.bodyChunks[0].pos, player.bodyChunks[0].pos, 0.8f)); } if (player.animation == Player.AnimationIndex.ClimbOnBeam) { vector.y = Mathf.Abs(vector.y); vector = Vector3.Slerp(vector, Custom.DirVec(player.bodyChunks[1].pos, player.bodyChunks[0].pos), 0.75f); } vector = Vector3.Slerp(vector, Custom.DegToVec((80f + Mathf.Cos((float)(player.animationFrame + ((!player.leftFoot) ? 3 : 9)) / 12f * 2f * (float)Math.PI) * 4f * (player.graphicsModule as PlayerGraphics).spearDir) * (player.graphicsModule as PlayerGraphics).spearDir), Mathf.Abs((player.graphicsModule as PlayerGraphics).spearDir)); (player.grasps[i].grabbed as Weapon).setRotation = vector; (player.grasps[i].grabbed as Weapon).rotationSpeed = 0f; break; case Quiver quiver: player.grasps[i].grabbed.firstChunk.vel = (player.graphicsModule as PlayerGraphics).hands[i].vel; player.grasps[i].grabbed.firstChunk.MoveFromOutsideMyUpdate(eu, (player.graphicsModule as PlayerGraphics).hands[i].pos); if (player.bodyMode == Player.BodyModeIndex.Crawl) { vector = Custom.DirVec(player.bodyChunks[1].pos, Vector2.Lerp(player.grasps[i].grabbed.bodyChunks[0].pos, player.bodyChunks[0].pos, 0.8f)); } if (player.animation == Player.AnimationIndex.ClimbOnBeam) { vector.y = Mathf.Abs(vector.y); vector = Vector3.Slerp(vector, Custom.DirVec(player.bodyChunks[1].pos, player.bodyChunks[0].pos), 0.75f); } vector = Vector3.Slerp(vector, Custom.DegToVec((80f + Mathf.Cos((float)(player.animationFrame + ((!player.leftFoot) ? 3 : 9)) / 12f * 2f * (float)Math.PI) * 4f * (player.graphicsModule as PlayerGraphics).spearDir) * (player.graphicsModule as PlayerGraphics).spearDir), Mathf.Abs((player.graphicsModule as PlayerGraphics).spearDir)); (player.grasps[i].grabbed as Weapon).setRotation = -vector; (player.grasps[i].grabbed as Weapon).rotationSpeed = 0f; break; } } } } private static int GetOppositeHand(int grasp) { return grasp switch { 0 => 1, 1 => 0, _ => -1, }; } private static PhysicalObject GetOppositeObject(Player player, int grasp) { int offGrasp = GetOppositeHand(grasp); PhysicalObject offObject; try { offObject = player.grasps[offGrasp].grabbed; } catch { offObject = null; } return offObject; } private static Player.ObjectGrabability GrababilityPatch(On.Player.orig_Grabability orig, Player player, PhysicalObject obj) { // code that runs before game code switch (obj) { case Club club: case Bow bow: if ((obj as Weapon).mode == Weapon.Mode.OnBack) { return Player.ObjectGrabability.CantGrab; } return Player.ObjectGrabability.BigOneHand; } Player.ObjectGrabability result = orig.Invoke(player, obj); // code that runs after game code return result; } public static void ThrowPatch(On.Player.orig_ThrowObject orig, Player player, int grasp, bool eu) { PhysicalObject thrownObject = player.grasps[grasp].grabbed; AbstractPhysicalObject.AbstractObjectType thrownType = thrownObject.abstractPhysicalObject.type; RWCustom.IntVector2 throwDir = new RWCustom.IntVector2(player.ThrowDirection, 0); int playerNumber = player.playerState.playerNumber; if (thrownType == EnumExt_NewItems.Club) { if (clubStats[playerNumber].swingDelay <= 0 && player.animation != Player.AnimationIndex.Flip && player.animation != Player.AnimationIndex.CrawlTurn && player.animation != Player.AnimationIndex.Roll) { player.room.PlaySound(SoundID.Slugcat_Throw_Spear, player.firstChunk); thrownObject.firstChunk.vel.x = thrownObject.firstChunk.vel.x + (float)throwDir.x * 30f; player.room.AddObject(new ExplosionSpikes(player.room, thrownObject.firstChunk.pos + new Vector2((float)player.rollDirection * -40f, 0f), 6, 5.5f, 4f, 4.5f, 21f, new Color(1f, 1f, 1f, 0.25f))); player.bodyChunks[0].vel += throwDir.ToVector2() * 4f; player.bodyChunks[1].vel -= throwDir.ToVector2() * 3f; // animTimer clubStats[playerNumber].comboCooldown = 30; clubStats[playerNumber].firstHit = true; globalStats[playerNumber].animTimer = swingTime; if (clubStats[playerNumber].comboCount >= maxCombo) { clubStats[playerNumber].swingDelay = postComboCooldown; player.room.AddObject(new ExplosionSpikes(player.room, thrownObject.firstChunk.pos + new Vector2((float)player.rollDirection * -40f, 0f), 15, 25f, 4f, 4.5f, 21f, new Color(1f, 0.5f, 0.75f, 0.5f))); clubStats[playerNumber].comboCount = 0; } else { clubStats[playerNumber].swingDelay = swingTime; clubStats[playerNumber].comboCount++; } } return; } if (thrownType == EnumExt_NewItems.Bow) { int offGrasp = GetOppositeHand(grasp); PhysicalObject offObject = GetOppositeObject(player, grasp); if (offObject != null && !(offObject is Armor) && offObject.abstractPhysicalObject.type != EnumExt_NewItems.Arrow) { orig(player, offGrasp, eu); } return; } if (thrownType == EnumExt_NewItems.Arrow) { orig(player, grasp, eu); thrownObject.firstChunk.vel *= 0.25f; (thrownObject as Weapon).mode = Weapon.Mode.Free; return; } if (thrownType == EnumExt_NewItems.Quiver) { return; } orig(player, grasp, eu); } public static Vector2 GetAimDir(Player player) { int playerNumber = player.playerState.playerNumber; Vector2 result = playerInput[playerNumber].analogueDir; if (result.x != 0f || result.y != 0f) { result = result.normalized; return result; } if (playerInput[playerNumber].ZeroGGamePadIntVec.x != 0 || playerInput[playerNumber].ZeroGGamePadIntVec.y != 0) { return playerInput[playerNumber].IntVec.ToVector2().normalized; } return new Vector2(0f, 0f); } public static float GetFireStrength(Player player) { int playerNumber = player.playerState.playerNumber; float drawProgress = (float)(bowStats[playerNumber].drawTime / maxDrawTime); drawProgress = Mathf.Clamp((float)Math.Round(drawProgress, 3), 0.2f, 1.0f); return drawProgress; } } }
44.392532
364
0.499005
[ "MIT" ]
Penguixia/PrimitiveArmory
PlayerHooks.cs
48,745
C#
using UnityEngine; using System.Collections; namespace Telescopes { public interface IParameterizedCurve { Vector3 StartPosition { get; } Vector3 EndPosition { get; } Vector3 StartTangent { get; } Vector3 EndTangent { get; } void RotateAndOffset(Quaternion rotation, Vector3 center, Vector3 tangent, float radius); } }
20.944444
97
0.668435
[ "MIT" ]
icethrush/telescoping-structures
Assets/Scripts/IParameterizedCurve.cs
379
C#