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
#region "copyright" /* Copyright © 2021 - 2021 George Hilios <ghilios+SERVOCAT@googlemail.com> This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #endregion "copyright" using ASCOM.ghilios.ServoCAT.Astrometry; using ASCOM.ghilios.ServoCAT.Interfaces; namespace ASCOM.ghilios.ServoCAT.Telescope { public class ServoCatStatus { public ServoCatStatus( ICRSCoordinates celestialCoordinates, ICRSCoordinates syncedCelestialCoordinates, TopocentricCoordinates topocentricCoordinates, TopocentricCoordinates syncedTopocentricCoordinates, MotionStatusEnum motionStatus) { this.CelestialCoordinates = celestialCoordinates; this.SyncedCelestialCoordinates = syncedCelestialCoordinates; this.TopocentricCoordinates = topocentricCoordinates; this.SyncedTopocentricCoordinates = syncedTopocentricCoordinates; this.MotionStatus = motionStatus; } public ICRSCoordinates CelestialCoordinates { get; private set; } public ICRSCoordinates SyncedCelestialCoordinates { get; private set; } public TopocentricCoordinates TopocentricCoordinates { get; private set; } public TopocentricCoordinates SyncedTopocentricCoordinates { get; private set; } public MotionStatusEnum MotionStatus { get; set; } } }
41.783784
112
0.716688
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
ghilios/ASCOM.Joko.ServoCAT
ServoCATDriver/Telescope/ServoCatStatus.cs
1,549
C#
using BMEcatSharp.Xml; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Xml.Serialization; namespace OpenTransSharp { /// <summary> /// (Information on the business document)<br/> /// <br/> /// In the element ORDERRESPONSE_INFO administrative information on this order is summarized. /// </summary> public class OrderResponseInformation { /// <summary> /// <inheritdoc cref="OrderResponseInformation"/> /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public OrderResponseInformation() { OrderId = null!; } /// <summary> /// <inheritdoc cref="OrderResponseInformation"/> /// </summary> /// <param name="orderId"></param> /// <param name="date"></param> /// <param name="parties"></param> /// <param name="orderPartiesReference"></param> public OrderResponseInformation(string orderId, DateTime date, IEnumerable<OpenTransParty> parties, OrderPartiesReference orderPartiesReference) { if (string.IsNullOrWhiteSpace(orderId)) { throw new ArgumentException($"'{nameof(orderId)}' cannot be null or whitespace.", nameof(orderId)); } if (parties is null) { throw new ArgumentNullException(nameof(parties)); } OrderId = orderId; Date = date; OrderPartiesReference = orderPartiesReference ?? throw new ArgumentNullException(nameof(orderPartiesReference)); Parties = parties.ToList(); } /// <summary> /// (required) Order number of buyer<br/> /// <br/> /// Unique order number of the buyer. /// </summary> [XmlElement("ORDER_ID")] public string OrderId { get; set; } /// <summary> /// (required) Date of confirmation of order<br/> /// <br/> /// Date of confirmation of order receipt. /// </summary> [XmlElement("ORDERRESPONSE_DATE")] public DateTime Date { get; set; } /// <summary> /// (optional) Date of the order<br/> /// <br/> /// Date of the order. /// </summary> [XmlElement("ORDER_DATE")] public DateTime? OrderDate { get; set; } [EditorBrowsable(EditorBrowsableState.Never)] public bool OrderDateSpecified => OrderDate.HasValue; /// <summary> /// (optional) Alternative order number of the buyer<br/> /// <br/> /// Further buyer order numbers which can be specified by the buyer.<br/> /// Relevant in the case of orders which are passed on again.<br/> /// Here the order number of the original ordering party can be set down. /// </summary> [XmlElement("ALT_CUSTOMER_ORDER_ID")] public List<string>? AlternativeCustomerOrderId { get; set; } = new List<string>(); /// <summary> /// (optional) Supplier order number<br/> /// <br/> /// Unique order number of the supplier. /// </summary> [XmlElement("SUPPLIER_ORDER_ID")] public string? SupplierOrderId { get; set; } /// <summary> /// (optional) Order change sequence<br/> /// <br/> /// The alteration sequence is increased by one with the dispatch of each ORDERCHANGE business document.<br/> /// <br/> /// The numbering begins at 1. /// </summary> [XmlElement("ORDERCHANGE_SEQUENCE_ID")] public int OrderChangeSequenceId { get; set; } /// <summary> /// (optional) Delivery date <br/> /// <br/> /// Date of shipment.<br/> /// <br/> /// The delivery date specifies the date the commissioned goods are accepted by the buyer. If the delivery date deviates from the one specified in the header, the delivery date on item level is valid.<br/> /// <br/> /// To specify exact one date for the shipment, e.g. in the RECEIPTACKNOWLEDGEMENT-document, both sub-elements the DELIVERY_DATE and the DELIVERY_END_DATE should be the equal. /// </summary> [XmlElement("DELIVERY_DATE")] public DeliveryDate? DeliveryDate { get; set; } /// <summary> /// (optional) Language<br/> /// <br/> /// Specification of used languages, especially the default language of all language-dependent information<br/> /// <br/> /// XML-namespace: BMECAT /// </summary> [BMEXmlElement("LANGUAGE")] public List<global::BMEcatSharp.Language>? Languages { get; set; } = new List<global::BMEcatSharp.Language>(); [EditorBrowsable(EditorBrowsableState.Never)] public bool LanguagesSpecified => Languages?.Count > 0; /// <summary> /// (optional) MIME root directory<br/> /// <br/> /// A relative directory can be entered here (and/or a URI), i.e. one to which the relative paths in MIME_SOURCE refer.<br/> /// <br/> /// Max length: 250<br/> /// <br/> /// XML-namespace: BMECAT /// </summary> [BMEXmlElement("MIME_ROOT")] public global::BMEcatSharp.MultiLingualString? MimeRoot { get; set; } /// <summary> /// (required) Parties<br/> /// <br/> /// List of parties that are relevant to this business document. /// </summary> [XmlArray("PARTIES")] [XmlArrayItem("PARTY")] public List<OpenTransParty> Parties { get; set; } = new List<OpenTransParty>(); /// <summary> /// (required) Business partners<br/> /// <br/> /// Reference to the business partners integrated in the process of the document flow. /// </summary> [XmlElement("ORDER_PARTIES_REFERENCE")] public OrderPartiesReference OrderPartiesReference { get; set; } = new OrderPartiesReference(); /// <summary> /// (optional) Document exchange parties<br/> /// <br/> /// Reference to the business partners who take part in the document exchange. /// </summary> [XmlElement("DOCEXCHANGE_PARTIES_REFERENCE")] public DocexchangePartiesReference? DocexchangePartiesReference { get; set; } /// <summary> /// (optional) Currency<br/> /// <br/> /// Provides the currency that is default for all price information in the catalog. If the price of a product has a different currency, or this element is not used, the the currency has to be specified in the PRICE_CURRENCY element for the respective product.<br/> /// <br/> /// Caution:<br/> /// Therefore, the currency must be specified in the catalog header or for each product separately.It is recommended to define a default currency.<br/> /// <br/> /// XML-namespace: BMECAT /// </summary> [BMEXmlElement("CURRENCY")] public string? Currency { get; set; } /// <summary> /// (optional) Additional multimedia information<br/> /// <br/> /// Information about multimedia files. /// </summary> [XmlElement("MIME_INFO")] public OpenTransMimeInfo? MimeInfo { get; set; } /// <summary> /// (optional) Remark<br/> /// <br/> /// Remark related to a business document. /// </summary> [XmlElement("REMARKS")] public List<Remark> Remarks { get; set; } = new List<Remark>(); [EditorBrowsable(EditorBrowsableState.Never)] public bool RemarksSpecified => Remarks?.Count > 0; /// <summary> /// (optional) User-defined extension<br/> /// <br/> /// This element can be used for transferring information in user-defined non-openTRANS-elements; hence it is possible to extend the pre-defined set of openTRANS-elements by user-defined ones. The usage of those elements results in openTRANS business documents, which can only be exchanged between the companies that have agreed on these extensions. The structure of these elements can be very complex, though it must be valid XML.<br/> /// <br/> /// &lt;User Defined Extensions&gt; are defined exclusively as optional fields. Therefore, it is expressly pointed out that if user-defined extensions are used they must be compatible with the target systems and should be clarified on a case-to-case basis.<br/> /// <br/> /// The names of the elements must be clearly distinguishable from the names of other elements contained in the openTRANS standard.For this reason, all element must start with the string "UDX" (Example: &lt;UDX.supplier.elementname&gt;).<br/> /// <br/> /// The definition of user-defined extensions takes place by additional XML DTD or XML-Schema files. /// </summary> [XmlArray("HEADER_UDX")] public List<object>? HeaderUdx { get; set; } = new List<object>(); [EditorBrowsable(EditorBrowsableState.Never)] public bool HeaderUdxSpecified => HeaderUdx?.Count > 0; } }
42.865116
444
0.603082
[ "MPL-2.0" ]
pedropauloreis/OpenTransSharp
OpenTransSharp/Types/OrderResponses/OrderResponseInformation.cs
9,218
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.Serialization; using System.Text.RegularExpressions; using BxlSharp.Parsing; namespace BxlSharp.Parser { public enum Token { NONE, /* XLR tokens */ KW_LAYERDATA, KW_LAYER, KW_NAME, KW_LAYERTYPE, KW_BOARDLAYERTYPE, KW_LAYERORDER, KW_TEXTSTYLES, KW_PADSTACKS, KW_PATTERNS, KW_3DMODELS, KW_SYMBOLS, KW_COMPONENTS, KW_SUPERCOMPONENTS, KW_ATTACHEDFILES, KW_WORKSPACESIZE, KW_COMPONENTINSTANCES, KW_VIAINSTANCES, KW_VIA, KW_NETS, KW_NET, KW_SCHEMATICOMPONENTINSTANCES, KW_SCHEMATICNETS, KW_SCHEMATICDATA, KW_UNITS, KW_SHEET, KW_WORKSPACE, KW_SHEETS, KW_NUMBER, KW_SHOWBORDER, KW_BORDERNAME, KW_SCALEFACTOR, KW_OFFSET, KW_WIRE, KW_PORT, KW_JUNCTION, KW_COPPERPOUR, KW_LAYERS, KW_LAYERNUMBER, KW_LAYERTECHNICALDATA, KW_EOF, /* XLR and BXL common tokens */ KW_PADSTACK_BEGIN, KW_PADSTACK_END, KW_PATTERN_BEGIN, KW_PATTERN_END, KW_SYMBOL_BEGIN, KW_SYMBOL_END, KW_COMPONENT_BEGIN, KW_COMPONENT_END, KW_DATA_BEGIN, KW_DATA_END, KW_COMPPINS_BEGIN, KW_COMPPINS_END, KW_COMPDATA_BEGIN, KW_COMPDATA_END, KW_ATTACHEDSYMBOLS_BEGIN, KW_ATTACHEDSYMBOLS_END, KW_PINMAP_BEGIN, KW_PINMAP_END, KW_TEXTSTYLE, KW_ORIGINPOINT, KW_PICKPOINT, KW_GLUEPOINT, KW_PINSRENAMED, KW_PATTERNNAME, KW_ALTERNATEPATTERN, KW_ORIGINALNAME, KW_EDITED, KW_SOURCELIBRARY, KW_REFDESPREFIX, KW_NUMBEROFPINS, KW_NUMPARTS, KW_COMPOSITION, KW_ALTIEEE, KW_ALTDEMORGAN, KW_PATTERNPINS, KW_REVISIONLEVEL, KW_REVISIONNOTE, KW_SHAPES, KW_PADSHAPE, KW_PAD, KW_DELETEDPAD, KW_POLY, KW_POLYKEEPOUT, KW_LINE, KW_ARC, KW_TEXT, KW_PIN, KW_PINDES, KW_PINNAME, KW_ATTRIBUTE, KW_WIZARD, KW_TEMPLATEDATA, KW_COMPPIN, KW_ATTACHEDSYMBOL, KW_RELATEDFILES, KW_PADNUM, PAREN_L, PAREN_R, COMMA, COLON, SLASH, LIT_DECIMAL, LIT_INTEGER, LIT_BOOLEAN, LIT_STRING, IDENTIFIER, COMMENT, } /// <summary> /// Used to represent a matched token with the proper <seealso cref="Token"/>, /// its <seealso cref="Lexeme"/> and the <seealso cref="Value"/> of the token /// lexeme if appropriate. /// </summary> internal struct TokenMatch { /// <summary> /// This is a placeholder constant value used for tokens are matched /// but that don't need a parameter value. This is needed because the /// token attribute value may be null so we need to be able to tell /// a value of null from no value. /// </summary> private static readonly object NoValue = new object(); /// <summary> /// Used to represent a failed token match. /// </summary> public static readonly TokenMatch Fail = new TokenMatch { IsSuccess = false, Value = NoValue }; public bool IsSuccess { get; private set; } public Token Token { get; private set; } public string Lexeme { get; private set; } public object Value { get; private set; } public bool HasValue => Value != NoValue; public static TokenMatch Success(Token token, string lexeme) => new TokenMatch { Token = token, IsSuccess = true, Lexeme = lexeme, Value = NoValue }; public static TokenMatch Success(Token token, string lexeme, object value) => new TokenMatch { Token = token, IsSuccess = true, Lexeme = lexeme, Value = value }; } /// <summary> /// Structure used to represent the current state of the tokenizer. Having this allows saving the /// tokenizer state and restoring it later. /// </summary> internal readonly struct TokenizerState { public readonly int ParenLevel; public readonly int Position; public readonly int Line; public readonly int Column; public readonly TokenMatch Current; public TokenizerState(int parenLevel, int position, int line, int column, TokenMatch current) { ParenLevel = parenLevel; Position = position; Line = line; Column = column; Current = current; } public TokenizerState With(int? parenLevel = null, int? position = null, int? line = null, int? column = null, TokenMatch? current = null) { return new TokenizerState(parenLevel ?? ParenLevel, position ?? Position, line ?? Line, column ?? Column, current ?? Current); } } /// <summary> /// Tokenizer for the BXL textual representation. /// </summary> public class BxlTokenizer { /// <summary> /// List of the keyword token patterns. It is separated from the general tokens because /// keywords are not reserved and only should be matched in the proper state. /// </summary> private static readonly List<Func<string, int, TokenMatch>> KeywordPatterns = new List<Func<string, int, TokenMatch>>(); /// <summary> /// List of general keyword patterns that can be matched anywhere in the input. /// </summary> private static readonly List<Func<string, int, TokenMatch>> GeneralPatterns = new List<Func<string, int, TokenMatch>>(); static BxlTokenizer() { /* XLR tokens */ KeywordPatterns.Add(KeywordMatcher(Token.KW_LAYERDATA, "LayerData")); KeywordPatterns.Add(KeywordMatcher(Token.KW_LAYER, "Layer")); KeywordPatterns.Add(KeywordMatcher(Token.KW_NAME, "Name")); KeywordPatterns.Add(KeywordMatcher(Token.KW_LAYERTYPE, "LayerType")); KeywordPatterns.Add(KeywordMatcher(Token.KW_BOARDLAYERTYPE, "BoardLayerType")); KeywordPatterns.Add(KeywordMatcher(Token.KW_LAYERORDER, "LayerOrder")); KeywordPatterns.Add(KeywordMatcher(Token.KW_TEXTSTYLES, "TextStyles")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PADSTACKS, "PadStacks")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PATTERNS, "Patterns")); KeywordPatterns.Add(KeywordMatcher(Token.KW_3DMODELS, "3DModels")); KeywordPatterns.Add(KeywordMatcher(Token.KW_SYMBOLS, "Symbols")); KeywordPatterns.Add(KeywordMatcher(Token.KW_COMPONENTS, "Components")); KeywordPatterns.Add(KeywordMatcher(Token.KW_SUPERCOMPONENTS, "SuperComponents")); KeywordPatterns.Add(KeywordMatcher(Token.KW_ATTACHEDFILES, "AttachedFiles")); KeywordPatterns.Add(KeywordMatcher(Token.KW_WORKSPACESIZE, "WorkSpaceSize")); KeywordPatterns.Add(KeywordMatcher(Token.KW_COMPONENTINSTANCES, "ComponentInstances")); KeywordPatterns.Add(KeywordMatcher(Token.KW_VIAINSTANCES, "ViaInstances")); KeywordPatterns.Add(KeywordMatcher(Token.KW_VIA, "Via")); KeywordPatterns.Add(KeywordMatcher(Token.KW_NETS, "Nets")); KeywordPatterns.Add(KeywordMatcher(Token.KW_NET, "Net")); KeywordPatterns.Add(KeywordMatcher(Token.KW_SCHEMATICOMPONENTINSTANCES, "SchematicComponentInstances")); KeywordPatterns.Add(KeywordMatcher(Token.KW_SCHEMATICNETS, "SchematicNets")); KeywordPatterns.Add(KeywordMatcher(Token.KW_SCHEMATICDATA, "SchematicData")); KeywordPatterns.Add(KeywordMatcher(Token.KW_UNITS, "Units")); KeywordPatterns.Add(KeywordMatcher(Token.KW_SHEET, "Sheet")); KeywordPatterns.Add(KeywordMatcher(Token.KW_WORKSPACE, "Workspace")); KeywordPatterns.Add(KeywordMatcher(Token.KW_SHEETS, "Sheets")); KeywordPatterns.Add(KeywordMatcher(Token.KW_NUMBER, "Number")); KeywordPatterns.Add(KeywordMatcher(Token.KW_SHOWBORDER, "ShowBorder")); KeywordPatterns.Add(KeywordMatcher(Token.KW_BORDERNAME, "BorderName")); KeywordPatterns.Add(KeywordMatcher(Token.KW_SCALEFACTOR, "ScaleFactor")); KeywordPatterns.Add(KeywordMatcher(Token.KW_OFFSET, "OffSet")); KeywordPatterns.Add(KeywordMatcher(Token.KW_WIRE, "Wire")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PORT, "Port")); KeywordPatterns.Add(KeywordMatcher(Token.KW_JUNCTION, "Junction")); KeywordPatterns.Add(KeywordMatcher(Token.KW_COPPERPOUR, "Copperpour")); KeywordPatterns.Add(KeywordMatcher(Token.KW_LAYERS, "Layers")); KeywordPatterns.Add(KeywordMatcher(Token.KW_LAYERNUMBER, "LayerNumber")); KeywordPatterns.Add(KeywordMatcher(Token.KW_LAYERTECHNICALDATA, "LayerTechnicalData")); KeywordPatterns.Add(KeywordMatcher(Token.KW_EOF, "End of File")); /* XLR and BXL common tokens */ KeywordPatterns.Add(KeywordMatcher(Token.KW_PADSTACK_BEGIN, "PadStack")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PADSTACK_END, "EndPadStack")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PATTERN_BEGIN, "Pattern")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PATTERN_END, "EndPattern")); KeywordPatterns.Add(KeywordMatcher(Token.KW_SYMBOL_BEGIN, "Symbol")); KeywordPatterns.Add(KeywordMatcher(Token.KW_SYMBOL_END, "EndSymbol")); KeywordPatterns.Add(KeywordMatcher(Token.KW_COMPONENT_BEGIN, "Component")); KeywordPatterns.Add(KeywordMatcher(Token.KW_COMPONENT_END, "EndComponent")); KeywordPatterns.Add(KeywordMatcher(Token.KW_DATA_BEGIN, "Data")); KeywordPatterns.Add(KeywordMatcher(Token.KW_DATA_END, "EndData")); KeywordPatterns.Add(KeywordMatcher(Token.KW_COMPPINS_BEGIN, "CompPins")); KeywordPatterns.Add(KeywordMatcher(Token.KW_COMPPINS_END, "EndCompPins")); KeywordPatterns.Add(KeywordMatcher(Token.KW_COMPDATA_BEGIN, "CompData")); KeywordPatterns.Add(KeywordMatcher(Token.KW_COMPDATA_END, "EndCompData")); KeywordPatterns.Add(KeywordMatcher(Token.KW_ATTACHEDSYMBOLS_BEGIN, "AttachedSymbols")); KeywordPatterns.Add(KeywordMatcher(Token.KW_ATTACHEDSYMBOLS_END, "EndAttachedSymbols")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PINMAP_BEGIN, "PinMap")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PINMAP_END, "EndPinMap")); KeywordPatterns.Add(KeywordMatcher(Token.KW_TEXTSTYLE, "TextStyle")); KeywordPatterns.Add(KeywordMatcher(Token.KW_ORIGINPOINT, "OriginPoint")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PICKPOINT, "PickPoint")); KeywordPatterns.Add(KeywordMatcher(Token.KW_GLUEPOINT, "GluePoint")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PINSRENAMED, "PinsRenamed")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PATTERNNAME, "PatternName")); KeywordPatterns.Add(KeywordMatcher(Token.KW_ALTERNATEPATTERN, "AlternatePattern")); KeywordPatterns.Add(KeywordMatcher(Token.KW_ORIGINALNAME, "OriginalName")); KeywordPatterns.Add(KeywordMatcher(Token.KW_EDITED, "Edited")); KeywordPatterns.Add(KeywordMatcher(Token.KW_SOURCELIBRARY, "SourceLibrary")); KeywordPatterns.Add(KeywordMatcher(Token.KW_REFDESPREFIX, "RefDesPrefix")); KeywordPatterns.Add(KeywordMatcher(Token.KW_NUMBEROFPINS, "NumberofPins")); KeywordPatterns.Add(KeywordMatcher(Token.KW_NUMPARTS, "NumParts")); KeywordPatterns.Add(KeywordMatcher(Token.KW_COMPOSITION, "Composition")); KeywordPatterns.Add(KeywordMatcher(Token.KW_ALTIEEE, "AltIEEE")); KeywordPatterns.Add(KeywordMatcher(Token.KW_ALTDEMORGAN, "AltDeMorgan")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PATTERNPINS, "PatternPins")); KeywordPatterns.Add(KeywordMatcher(Token.KW_REVISIONLEVEL, "Revision Level")); KeywordPatterns.Add(KeywordMatcher(Token.KW_REVISIONNOTE, "Revision Note")); KeywordPatterns.Add(KeywordMatcher(Token.KW_SHAPES, "Shapes")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PADSHAPE, "PadShape")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PAD, "Pad")); KeywordPatterns.Add(KeywordMatcher(Token.KW_DELETEDPAD, "Deletedpad")); KeywordPatterns.Add(KeywordMatcher(Token.KW_POLY, "Poly")); KeywordPatterns.Add(KeywordMatcher(Token.KW_POLYKEEPOUT, "Polykeepout")); KeywordPatterns.Add(KeywordMatcher(Token.KW_LINE, "Line")); KeywordPatterns.Add(KeywordMatcher(Token.KW_ARC, "Arc")); KeywordPatterns.Add(KeywordMatcher(Token.KW_TEXT, "Text")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PIN, "Pin")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PINDES, "PinDes")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PINNAME, "PinName")); KeywordPatterns.Add(KeywordMatcher(Token.KW_ATTRIBUTE, "Attribute")); KeywordPatterns.Add(KeywordMatcher(Token.KW_WIZARD, "Wizard")); KeywordPatterns.Add(KeywordMatcher(Token.KW_TEMPLATEDATA, "Templatedata")); KeywordPatterns.Add(KeywordMatcher(Token.KW_COMPPIN, "CompPin")); KeywordPatterns.Add(KeywordMatcher(Token.KW_ATTACHEDSYMBOL, "AttachedSymbol")); KeywordPatterns.Add(KeywordMatcher(Token.KW_RELATEDFILES, "RelatedFiles")); KeywordPatterns.Add(KeywordMatcher(Token.KW_PADNUM, "PadNum")); GeneralPatterns.Add(PunctuationMatcher(Token.PAREN_L, "(")); GeneralPatterns.Add(PunctuationMatcher(Token.PAREN_R, ")")); GeneralPatterns.Add(PunctuationMatcher(Token.COMMA, ",")); GeneralPatterns.Add(PunctuationMatcher(Token.COLON, ":")); GeneralPatterns.Add(PunctuationMatcher(Token.SLASH, "/")); GeneralPatterns.Add(RegexMatcher(Token.LIT_DECIMAL, @"[-+]?\d*\.\d+(e-\d+)?\b", l => double.Parse(l, CultureInfo.InvariantCulture))); GeneralPatterns.Add(RegexMatcher(Token.LIT_INTEGER, @"[-+]?\d+\b", l => int.Parse(l, CultureInfo.InvariantCulture))); GeneralPatterns.Add(RegexMatcher(Token.LIT_BOOLEAN, @"(True|False)\b", l => l.Equals("True", StringComparison.InvariantCultureIgnoreCase))); GeneralPatterns.Add(RegexMatcher(Token.LIT_STRING, @""""".*?""""", l => l.Substring(2, l.Length - 4))); // some files use doubly quoted strings GeneralPatterns.Add(RegexMatcher(Token.LIT_STRING, @"""(.*?(\d""\s*[\(,]?\s*\d+(\.\d+)?mm)*?)*""", l => l.Substring(1, l.Length - 2))); // this odd regular expression is to allow for regular strings and also strings that contain inches... like "0.180" (4.57mm)" or "8-SOIC (0.154", 3.90mm Width)" //GeneralPatterns.Add(RegexMatcher(Token.LIT_STRING, @""".*?""", l => l.Substring(1, l.Length - 2))); GeneralPatterns.Add(RegexMatcher(Token.IDENTIFIER, @"Open Collector|Open Emitter", l => l)); // special case because those two values are stored with an space GeneralPatterns.Add(RegexMatcher(Token.IDENTIFIER, @"[\w-]+", l => l)); GeneralPatterns.Add(RegexMatcher(Token.COMMENT, @"#.*?\n", l => l.Substring(1))); } private static IEnumerable<Func<string, int, TokenMatch>> GetPatterns(bool includeKeywords) => includeKeywords ? Enumerable.Concat(KeywordPatterns, GeneralPatterns) : GeneralPatterns; /// <summary> /// Creates a matcher that returns when the input matches a <paramref name="lexeme"/> that is surrounded by separators. /// </summary> /// <param name="token">Token this attempts to match.</param> /// <param name="lexeme">Lexeme text to be matched.</param> /// <returns> /// Returns a token match, either indicating the token that was matched with its lexeme and possible value, /// or <seealso cref="TokenMatch.Fail"/> otherwise. /// </returns> private static Func<string, int, TokenMatch> KeywordMatcher(Token token, string lexeme) { var pattern = $"\\G[^(]?(?:{Regex.Escape(lexeme)})\\b"; var re = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); return (input, start) => { return re.IsMatch(input, start > 0 ? start - 1 : start) ? TokenMatch.Success(token, lexeme) : TokenMatch.Fail; }; } /// <summary> /// Creates a matcher that returns when the input matches a punctuation <paramref name="lexeme"/>, escaping the given /// lexeme text if needed. /// </summary> /// <param name="token">Token this attempts to match.</param> /// <param name="lexeme">Lexeme text to be matched.</param> /// <returns> /// Returns a token match, either indicating the token that was matched with its lexeme and possible value, /// or <seealso cref="TokenMatch.Fail"/> otherwise. /// </returns> private static Func<string, int, TokenMatch> PunctuationMatcher(Token token, string lexeme) { var pattern = $"\\G(?:{Regex.Escape(lexeme)})"; var re = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); return (input, start) => { return re.IsMatch(input, start) ? TokenMatch.Success(token, lexeme) : TokenMatch.Fail; }; } /// <summary> /// Creates a matcher that returns when the input matches a regular raw expression <paramref name="pattern"/> /// </summary> /// <param name="token">Token this attempts to match.</param> /// <param name="pattern">Regular expression text to be matched.</param> /// <param name="converter">Function used to convert the matched lexeme into a value.</param> /// <returns> /// Returns a token match, either indicating the token that was matched with its lexeme and possible value, /// or <seealso cref="TokenMatch.Fail"/> otherwise. /// </returns> private static Func<string, int, TokenMatch> RegexMatcher(Token token, string pattern, Func<string, object> converter) { pattern = $"\\G(?:{pattern})"; var re = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); return (input, start) => { var m = re.Match(input, start); return m.Success ? TokenMatch.Success(token, m.Value, converter(m.Value)) : TokenMatch.Fail; }; } /// <summary> /// Input text being tokenized. /// </summary> public string Text { get; } internal TokenizerState State { get; private set; } private int ParenLevel { get => State.ParenLevel; set => State = State.With(parenLevel: value); } /// <summary> /// Current position in the input text. /// </summary> public int Position { get => State.Position; private set => State = State.With(position: value); } /// <summary> /// Current line. Used for error reporting. /// </summary> public int Line { get => State.Line; private set => State = State.With(line: value); } /// <summary> /// Current column. Used for error reporting. /// </summary> public int Column { get => State.Column; private set => State = State.With(column: value); } /// <summary> /// Current token match. /// </summary> internal TokenMatch Current { get => State.Current; private set => State = State.With(current: value); } /// <summary> /// Current token that was last matched. /// </summary> public Token Token => Current.Token; /// <summary> /// The lexeme of the current token match. /// </summary> public string Lexeme => Current.Lexeme; /// <summary> /// The attribute value of the current token match. /// </summary> public object Value => Current.Value; /// <summary> /// Indicates the tokenization has reached the end of the input. /// </summary> public bool IsEof => Position >= Text.Length; public BxlTokenizer(string text) { Text = text; Reset(); } /// <summary> /// Resets the tokenizer so it can start reading the input from the start. /// </summary> public void Reset() { State = new TokenizerState(0, 0, 1, 1, TokenMatch.Fail); Next(); } /// <summary> /// Helper method used for incrementing the current position in the input text. /// <para> /// This has 3 purposes: setting the <seealso cref="ParenLevel"/> to zero on a new line so keywords can /// be matched again, counting <seealso cref="Line"/>s and counting <seealso cref="Column"/>s. /// </para> /// </summary> /// <param name="value">Number of charactes to increment the current position.</param> private void IncPosition(int value = 1) { for (int i = 0; i < value; ++i) { if (Text[Position++] == '\n') { ++Line; Column = 1; ParenLevel = 0; // reset level at new line to cope gracefully with missing closing paranthesis } else { ++Column; } } } /// <summary> /// Increments the input while there is white space in the current position. /// </summary> private void SkipWhiteSpace() { while (!IsEof && char.IsWhiteSpace(Text[Position])) { IncPosition(); } } /// <summary> /// Loops though the patterns trying to find the first one that matches the current input. /// </summary> /// <returns>Returns null if no successful <seealso cref="TokenMatch"/> is found.</returns> private TokenMatch? FindMatchingPattern() { // keywords are NOT reserved, meaning identifiers can have the same name as keywords, // so we need to test for them to only be recognized outside of any parenthesis var includeKeywords = ParenLevel == 0; var patterns = GetPatterns(includeKeywords); foreach (var matcher in patterns) { var tm = matcher(Text, Position); if (tm.IsSuccess) return tm; } return null; } /// <summary> /// Makes the tokenizer skip until a character equal to <paramref name="c"/> is found. /// <para> /// The skipping is achieved by replacing the current token with a <seealso cref="Token.COMMENT"/> /// that contains the skipped input as its lexeme. This is done so the parser /// <seealso cref="BxlParser.SkipUntil(bool, Token[])"/> method can take notice that /// this unusual manipulation has taken place. /// </para> /// </summary> /// <param name="c"></param> internal void SkipUntil(char c) { var dummyLexeme = ""; var pos = Position; while (!IsEof && Text[pos] != c) { dummyLexeme += Text[pos++]; } Current = TokenMatch.Success(Token.COMMENT, dummyLexeme); } /// <summary> /// Fetches the next token available and stores it as the current token. /// </summary> public void Next() { do { IncPosition(Lexeme?.Length ?? 0); SkipWhiteSpace(); if (IsEof) { Current = TokenMatch.Fail; } else { Current = FindMatchingPattern() ?? throw new BxlTokenizerException($"Unrecognized input: {Text.Substring(Position, 10)}"); // keep track of parenthesis level for enabling keyword recognition // only at the zero level if (Current.Token == Token.PAREN_L) { ++ParenLevel; } else if (Current.Token == Token.PAREN_R) { --ParenLevel; } } } while (Current.Token == Token.COMMENT); // ignore comments } } [Serializable] internal class BxlTokenizerException : Exception { public BxlTokenizerException() { } public BxlTokenizerException(string message) : base(message) { } public BxlTokenizerException(string message, Exception innerException) : base(message, innerException) { } protected BxlTokenizerException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
42.620746
309
0.602616
[ "MIT" ]
issus/BxlSharp
BxlSharp/Parsing/BxlTokenizer.cs
26,299
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void LessThanUInt16() { var test = new VectorBinaryOpTest__LessThanUInt16(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBinaryOpTest__LessThanUInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<UInt16> _fld1; public Vector64<UInt16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__LessThanUInt16 testClass) { var result = Vector64.LessThan(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector64<UInt16> _clsVar1; private static Vector64<UInt16> _clsVar2; private Vector64<UInt16> _fld1; private Vector64<UInt16> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__LessThanUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); } public VectorBinaryOpTest__LessThanUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector64.LessThan( Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector64).GetMethod(nameof(Vector64.LessThan), new Type[] { typeof(Vector64<UInt16>), typeof(Vector64<UInt16>) }); if (method is null) { method = typeof(Vector64).GetMethod(nameof(Vector64.LessThan), 1, new Type[] { typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector64.LessThan( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr); var result = Vector64.LessThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__LessThanUInt16(); var result = Vector64.LessThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector64.LessThan(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector64.LessThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector64<UInt16> op1, Vector64<UInt16> op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((left[0] < right[0]) ? ushort.MaxValue : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] < right[i]) ? ushort.MaxValue : 0)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.LessThan)}<UInt16>(Vector64<UInt16>, Vector64<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
43.953623
188
0.603403
[ "MIT" ]
333fred/runtime
src/tests/JIT/HardwareIntrinsics/General/Vector64/LessThan.UInt16.cs
15,164
C#
namespace cwg.web.Generators { public class PE32SignedGenerator : BaseGenerator { public override string Name => "PE32 SIGNED"; public override bool Active => false; protected override string SourceName => "sourcePESIGNED.exe"; protected override string CleanSourceName => "sourcePESIGNED.exe"; protected override string OutputExtension => "exe"; public override bool Packable => true; } }
27.705882
74
0.651805
[ "MIT" ]
jcapellman/cwg
src/cwg.web/Generators/PE32SignedGenerator.cs
473
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V4200</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.V4200 { 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.Xml.Serialization.XmlIncludeAttribute(typeof(RTO_QTY_QTY))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(RTO))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(MO))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(REAL))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(INT))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(PQ))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(TS))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(IVXB_TS))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(SXCM_TS))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(IVL_TS))] [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:hl7-org:v3")] public abstract partial class QTY : ANY { private static System.Xml.Serialization.XmlSerializer serializer; private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(QTY)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current QTY 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 QTY object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output QTY 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 QTY obj, out System.Exception exception) { exception = null; obj = default(QTY); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out QTY obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static QTY Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((QTY)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current QTY 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 QTY object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output QTY 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 QTY obj, out System.Exception exception) { exception = null; obj = default(QTY); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out QTY obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static QTY 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 QTY object /// </summary> public virtual QTY Clone() { return ((QTY)(this.MemberwiseClone())); } #endregion } }
45.336683
1,358
0.58834
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V4200/Generated/QTY.cs
9,022
C#
using System.Reflection; namespace RTWR_RTWLIB { partial class About { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.tableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.labelProductName = new System.Windows.Forms.Label(); this.labelVersion = new System.Windows.Forms.Label(); this.labelCopyright = new System.Windows.Forms.Label(); this.labelCompanyName = new System.Windows.Forms.Label(); this.textBoxDescription = new System.Windows.Forms.TextBox(); this.okButton = new System.Windows.Forms.Button(); this.tableLayoutPanel.SuspendLayout(); this.SuspendLayout(); // // tableLayoutPanel // this.tableLayoutPanel.BackColor = System.Drawing.Color.Transparent; this.tableLayoutPanel.ColumnCount = 2; this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 1.918465F)); this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 98.08154F)); this.tableLayoutPanel.Controls.Add(this.labelProductName, 1, 0); this.tableLayoutPanel.Controls.Add(this.labelVersion, 1, 1); this.tableLayoutPanel.Controls.Add(this.labelCopyright, 1, 2); this.tableLayoutPanel.Controls.Add(this.labelCompanyName, 1, 3); this.tableLayoutPanel.Controls.Add(this.textBoxDescription, 1, 4); this.tableLayoutPanel.Controls.Add(this.okButton, 1, 5); this.tableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel.Location = new System.Drawing.Point(9, 9); this.tableLayoutPanel.Name = "tableLayoutPanel"; this.tableLayoutPanel.RowCount = 6; this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableLayoutPanel.Size = new System.Drawing.Size(242, 265); this.tableLayoutPanel.TabIndex = 0; // // labelProductName // this.labelProductName.Dock = System.Windows.Forms.DockStyle.Fill; this.labelProductName.Location = new System.Drawing.Point(10, 0); this.labelProductName.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0); this.labelProductName.MaximumSize = new System.Drawing.Size(0, 17); this.labelProductName.Name = "labelProductName"; this.labelProductName.Size = new System.Drawing.Size(229, 17); this.labelProductName.TabIndex = 19; this.labelProductName.Text = "Rome Total War Randomiser"; this.labelProductName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // labelVersion // this.labelVersion.Dock = System.Windows.Forms.DockStyle.Fill; this.labelVersion.Location = new System.Drawing.Point(10, 26); this.labelVersion.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0); this.labelVersion.MaximumSize = new System.Drawing.Size(0, 17); this.labelVersion.Name = "labelVersion"; this.labelVersion.Size = new System.Drawing.Size(229, 17); this.labelVersion.TabIndex = 0; this.labelVersion.Text = "-alpha"; this.labelVersion.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // labelCopyright // this.labelCopyright.Dock = System.Windows.Forms.DockStyle.Fill; this.labelCopyright.Location = new System.Drawing.Point(10, 52); this.labelCopyright.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0); this.labelCopyright.MaximumSize = new System.Drawing.Size(0, 17); this.labelCopyright.Name = "labelCopyright"; this.labelCopyright.Size = new System.Drawing.Size(229, 17); this.labelCopyright.TabIndex = 21; this.labelCopyright.Text = "Copyright © SargeantPig 2020"; this.labelCopyright.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // labelCompanyName // this.labelCompanyName.Dock = System.Windows.Forms.DockStyle.Fill; this.labelCompanyName.Location = new System.Drawing.Point(10, 78); this.labelCompanyName.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0); this.labelCompanyName.MaximumSize = new System.Drawing.Size(0, 17); this.labelCompanyName.Name = "labelCompanyName"; this.labelCompanyName.Size = new System.Drawing.Size(229, 17); this.labelCompanyName.TabIndex = 22; this.labelCompanyName.Text = "Anrona"; this.labelCompanyName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // textBoxDescription // this.textBoxDescription.BackColor = System.Drawing.Color.DarkGray; this.textBoxDescription.Dock = System.Windows.Forms.DockStyle.Fill; this.textBoxDescription.Location = new System.Drawing.Point(10, 107); this.textBoxDescription.Margin = new System.Windows.Forms.Padding(6, 3, 3, 3); this.textBoxDescription.Multiline = true; this.textBoxDescription.Name = "textBoxDescription"; this.textBoxDescription.ReadOnly = true; this.textBoxDescription.Size = new System.Drawing.Size(229, 126); this.textBoxDescription.TabIndex = 23; this.textBoxDescription.TabStop = false; this.textBoxDescription.Text = "Randomises Rome Total War for a new interesting experience."; // // okButton // this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.okButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.okButton.Location = new System.Drawing.Point(164, 239); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(75, 23); this.okButton.TabIndex = 24; this.okButton.Text = "&OK"; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // About // this.AcceptButton = this.okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = global::RTWR_RTWLIB.Properties.Resources.marble; this.ClientSize = new System.Drawing.Size(260, 283); this.Controls.Add(this.tableLayoutPanel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "About"; this.Padding = new System.Windows.Forms.Padding(9); this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "About"; this.tableLayoutPanel.ResumeLayout(false); this.tableLayoutPanel.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel; private System.Windows.Forms.Label labelProductName; private System.Windows.Forms.Label labelVersion; private System.Windows.Forms.Label labelCopyright; private System.Windows.Forms.Label labelCompanyName; private System.Windows.Forms.TextBox textBoxDescription; private System.Windows.Forms.Button okButton; } }
53.741379
159
0.640252
[ "MIT" ]
sargeantPig/RTWRandomiser
RTWR_RTWLIB/Forms--/About.Designer.cs
9,354
C#
using System; using System.Collections.Generic; using System.Text; namespace Marmara.Data.Entity { public class CFLData : BaseEntity, IActuator { public string Status { get; set; } public DateTime RunTimeStart { get; set; } public DateTime RunTimeEnd { get; set; } } }
21.928571
50
0.664495
[ "MIT" ]
msensoy/MarmaraUniversityMasterThesis
codes/Common/Marmara.Data/Entity/CFLData.cs
309
C#
using System; using System.Collections.Generic; using System.Text; namespace Common.Interface { /// <summary> /// 序列化接口 /// </summary> public interface ISerialize { /// <summary> /// 序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="input"></param> /// <returns></returns> byte[] Serializes<T>(T input); /// <summary> /// 序列化T为JSON字符串 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="input"></param> /// <returns></returns> string SerializesJson<T>(T input, bool IngoreOptions = false); /// <summary> /// 序列化json字符串为Byte[] /// </summary> /// <param name="jsonStr"></param> /// <returns></returns> byte[] SerializesJsonString(string jsonStr); /// <summary> /// 反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="input"></param> /// <returns></returns> T Deserializes<T>(byte[] input); /// <summary> /// 反序列化JSON字符串为T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="input"></param> /// <returns></returns> T DeserializesJson<T>(string input); /// <summary> /// 反序列化JSON字符串为object /// </summary> /// <param name="type"></param> /// <param name="input"></param> /// <returns></returns> object DeserializesJson(Type type, string input); /// <summary> /// 序列化 /// </summary> /// <param name="type"></param> /// <param name="input"></param> /// <returns></returns> byte[] Serializes(Type type, object input); /// <summary> /// 反序列化 /// </summary> /// <param name="type"></param> /// <param name="input"></param> /// <returns></returns> object Deserializes(Type type, byte[] input); } }
27.890411
70
0.484774
[ "MIT" ]
107295472/DaprHost
Dapr/Common/Interface/ISerialize.cs
2,136
C#
using ABB.Robotics.RobotStudio.Stations; namespace WZcalculator.Interfaces { public interface IZone { /// <summary> /// Returns the zone type associated with this instance. /// </summary> /// <returns></returns> ZoneType GetZoneType(); /// <summary> /// /// </summary> /// <returns>A struct containing the dimensions for this type of temporary graphic.</returns> object GetDimensions(); /// <summary> /// Set the dimensions of the temporary graphic associated with this instance. /// </summary> /// <param name="dimensions">A struct containing the dimensions</param> void SetDimensions(object dimensions); /// <summary> /// Draws a temporary graphic that is aligned to the base frame of the mechanical unit. /// </summary> void DrawZone(RsMechanicalUnit mechanicalUnit); /// <summary> /// Create the zone in RAPID syntax. /// </summary> /// <param name="mechanicalUnit">The robot from which the zone is calculated.</param> string CreateRapidZone(RsMechanicalUnit mechanicalUnit); /// <summary> /// Deletes the temporary graphic associated with this instance. /// </summary> void DeleteZone(); } }
31.952381
101
0.600596
[ "MIT" ]
zaalj03a/WZcalculator
WZcalculator/Interfaces/IZone.cs
1,344
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 Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryDivideTests { #region Test methods [Fact] public static void CheckByteDivideTest() { byte[] array = new byte[] { 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyByteDivide(array[i], array[j]); } } } [Fact] public static void CheckSByteDivideTest() { sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifySByteDivide(array[i], array[j]); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckUShortDivideTest(bool useInterpreter) { ushort[] array = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUShortDivide(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckShortDivideTest(bool useInterpreter) { short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyShortDivide(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckUIntDivideTest(bool useInterpreter) { uint[] array = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUIntDivide(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckIntDivideTest(bool useInterpreter) { int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyIntDivide(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckULongDivideTest(bool useInterpreter) { ulong[] array = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyULongDivide(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckLongDivideTest(bool useInterpreter) { long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyLongDivide(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckFloatDivideTest(bool useInterpreter) { float[] array = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyFloatDivide(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckDoubleDivideTest(bool useInterpreter) { double[] array = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyDoubleDivide(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckDecimalDivideTest(bool useInterpreter) { decimal[] array = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyDecimalDivide(array[i], array[j], useInterpreter); } } } [Fact] public static void CheckCharDivideTest() { char[] array = new char[] { '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyCharDivide(array[i], array[j]); } } } #endregion #region Test verifiers private static void VerifyByteDivide(byte a, byte b) { Expression aExp = Expression.Constant(a, typeof(byte)); Expression bExp = Expression.Constant(b, typeof(byte)); Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp)); } private static void VerifySByteDivide(sbyte a, sbyte b) { Expression aExp = Expression.Constant(a, typeof(sbyte)); Expression bExp = Expression.Constant(b, typeof(sbyte)); Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp)); } private static void VerifyUShortDivide(ushort a, ushort b, bool useInterpreter) { Expression<Func<ushort>> e = Expression.Lambda<Func<ushort>>( Expression.Divide( Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(ushort))), Enumerable.Empty<ParameterExpression>()); Func<ushort> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((ushort)(a / b), f()); } private static void VerifyShortDivide(short a, short b, bool useInterpreter) { Expression<Func<short>> e = Expression.Lambda<Func<short>>( Expression.Divide( Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(short))), Enumerable.Empty<ParameterExpression>()); Func<short> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(unchecked((short)(a / b)), f()); } private static void VerifyUIntDivide(uint a, uint b, bool useInterpreter) { Expression<Func<uint>> e = Expression.Lambda<Func<uint>>( Expression.Divide( Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(uint))), Enumerable.Empty<ParameterExpression>()); Func<uint> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyIntDivide(int a, int b, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Divide( Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (b == -1 && a == int.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyULongDivide(ulong a, ulong b, bool useInterpreter) { Expression<Func<ulong>> e = Expression.Lambda<Func<ulong>>( Expression.Divide( Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(ulong))), Enumerable.Empty<ParameterExpression>()); Func<ulong> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyLongDivide(long a, long b, bool useInterpreter) { Expression<Func<long>> e = Expression.Lambda<Func<long>>( Expression.Divide( Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(long))), Enumerable.Empty<ParameterExpression>()); Func<long> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (b == -1 && a == long.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyFloatDivide(float a, float b, bool useInterpreter) { Expression<Func<float>> e = Expression.Lambda<Func<float>>( Expression.Divide( Expression.Constant(a, typeof(float)), Expression.Constant(b, typeof(float))), Enumerable.Empty<ParameterExpression>()); Func<float> f = e.Compile(useInterpreter); Assert.Equal(a / b, f()); } private static void VerifyDoubleDivide(double a, double b, bool useInterpreter) { Expression<Func<double>> e = Expression.Lambda<Func<double>>( Expression.Divide( Expression.Constant(a, typeof(double)), Expression.Constant(b, typeof(double))), Enumerable.Empty<ParameterExpression>()); Func<double> f = e.Compile(useInterpreter); Assert.Equal(a / b, f()); } private static void VerifyDecimalDivide(decimal a, decimal b, bool useInterpreter) { Expression<Func<decimal>> e = Expression.Lambda<Func<decimal>>( Expression.Divide( Expression.Constant(a, typeof(decimal)), Expression.Constant(b, typeof(decimal))), Enumerable.Empty<ParameterExpression>()); Func<decimal> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyCharDivide(char a, char b) { Expression aExp = Expression.Constant(a, typeof(char)); Expression bExp = Expression.Constant(b, typeof(char)); Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp)); } #endregion [Fact] public static void CannotReduce() { Expression exp = Expression.Divide(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void ThrowsOnLeftNull() { AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.Divide(null, Expression.Constant(""))); } [Fact] public static void ThrowsOnRightNull() { AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.Divide(Expression.Constant(""), null)); } private static class Unreadable<T> { public static T WriteOnly { set { } } } [Fact] public static void ThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); AssertExtensions.Throws<ArgumentException>("left", () => Expression.Divide(value, Expression.Constant(1))); } [Fact] public static void ThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); AssertExtensions.Throws<ArgumentException>("right", () => Expression.Divide(Expression.Constant(1), value)); } [Fact] public static void ToStringTest() { BinaryExpression e = Expression.Divide(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a / b)", e.ToString()); } } }
36.508861
167
0.50267
[ "MIT" ]
06needhamt/runtime
src/libraries/System.Linq.Expressions/tests/BinaryOperators/Arithmetic/BinaryDivideTests.cs
14,421
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 lambda-2015-03-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Lambda.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Model.Internal.MarshallTransformations { /// <summary> /// ListLayerVersions Request Marshaller /// </summary> public class ListLayerVersionsRequestMarshaller : IMarshaller<IRequest, ListLayerVersionsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((ListLayerVersionsRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(ListLayerVersionsRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Lambda"); request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-03-31"; request.HttpMethod = "GET"; string uriResourcePath = "/2018-10-31/layers/{LayerName}/versions"; if (!publicRequest.IsSetLayerName()) throw new AmazonLambdaException("Request object does not have required field LayerName set"); uriResourcePath = uriResourcePath.Replace("{LayerName}", StringUtils.FromStringWithSlashEncoding(publicRequest.LayerName)); if (publicRequest.IsSetCompatibleRuntime()) request.Parameters.Add("CompatibleRuntime", StringUtils.FromString(publicRequest.CompatibleRuntime)); if (publicRequest.IsSetMarker()) request.Parameters.Add("Marker", StringUtils.FromString(publicRequest.Marker)); if (publicRequest.IsSetMaxItems()) request.Parameters.Add("MaxItems", StringUtils.FromInt(publicRequest.MaxItems)); request.ResourcePath = uriResourcePath; request.UseQueryString = true; return request; } private static ListLayerVersionsRequestMarshaller _instance = new ListLayerVersionsRequestMarshaller(); internal static ListLayerVersionsRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ListLayerVersionsRequestMarshaller Instance { get { return _instance; } } } }
37.510204
149
0.656692
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/Lambda/Generated/Model/Internal/MarshallTransformations/ListLayerVersionsRequestMarshaller.cs
3,676
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Threading; using Azure.Storage.Blobs; using Microsoft.Azure.WebJobs.Extensions.Storage.Common.Listeners; using Microsoft.Azure.WebJobs.Extensions.Storage.Common.Timers; namespace Microsoft.Azure.WebJobs.Extensions.Storage.Blobs.Listeners { internal static class BlobNotificationStrategyExtensions { public static TaskSeriesCommandResult Execute(this IBlobListenerStrategy strategy) { if (strategy == null) { throw new ArgumentNullException("strategy"); } return strategy.ExecuteAsync(CancellationToken.None).GetAwaiter().GetResult(); } public static void Register(this IBlobListenerStrategy strategy, BlobServiceClient blobServiceClient, BlobContainerClient container, ITriggerExecutor<BlobTriggerExecutorContext> triggerExecutor) { if (strategy == null) { throw new ArgumentNullException("strategy"); } strategy.RegisterAsync(blobServiceClient, container, triggerExecutor, CancellationToken.None).GetAwaiter().GetResult(); } } }
34.972222
140
0.694202
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/tests/Listeners/BlobNotificationStrategyExtensions.cs
1,261
C#
using Microsoft.AspNetCore.Http; using System; using System.Threading.Tasks; namespace GreenElephantIO.Middleware { public class PublishSubscribeMiddleware { private readonly RequestDelegate _next; public PublishSubscribeMiddleware(RequestDelegate next) { _next = next; } public Task Invoke(HttpContext httpContext) { Console.WriteLine($"invoked! blaaaaaa {httpContext.Request.Path}"); return this._next(httpContext); } } }
22.208333
79
0.651032
[ "MIT" ]
greenelephantio/eventing-webhooks-dotnetcore-middleware
PublishSubscribeMiddleware.cs
535
C#
using DotBPE.Rpc.Protocol; using Peach; using Peach.Messaging; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace DotBPE.Rpc.Server { public class HeartbeatActor : IServiceActor<AmpMessage> { public string Id => "0.0"; public string GroupName { get; } = "default"; public Task ReceiveAsync(ISocketContext<AmpMessage> context, AmpMessage message) { message.InvokeMessageType = InvokeMessageType.Response; return context.SendAsync(message); } } }
23.24
88
0.685026
[ "MIT" ]
dotbpe/dotbpe
src/DotBPE.Rpc/Server/Impl/HeartbeatActor.cs
581
C#
using NuGet; namespace NuSelfUpdate { public interface IExtendedFileSystem : IFileSystem { string AppDirectory { get; } void MoveFile(string sourcePath, string destinationPath); } }
22
66
0.663636
[ "MIT" ]
ShiJess/NuSelfUpdate
src/NuSelfUpdate/IExtendedFileSystem.cs
222
C#
using Entia.Nodes; using Entia.Unity; using static Entia.Unity.Nodes; using static Entia.Nodes.Node; namespace Nodes { public sealed class Main : NodeReference { // This 'Node' represents the execution behavior of systems. // The 'Sequence' node executes its children in order. public override Node Node => Sequence(nameof(Main), // This node holds a few useful Unity-specific library systems. Default, // Any number of systems can be added here. System<Systems.UpdateInput>(), System<Systems.UpdateVelocity>(), System<Systems.UpdatePosition>(), System<Systems.SynchronizeTransform>() ); } }
32.727273
75
0.634722
[ "MIT" ]
outerminds/Entia.Unity
Unity/Assets/Scripts/Example/Main.cs
720
C#
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2012 ServiceStack Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading; using ServiceStack.Text.Common; namespace ServiceStack.Text.Json { internal static class JsonWriter { public static readonly JsWriter<JsonTypeSerializer> Instance = new JsWriter<JsonTypeSerializer>(); private static Dictionary<Type, WriteObjectDelegate> WriteFnCache = new Dictionary<Type, WriteObjectDelegate>(); public static WriteObjectDelegate GetWriteFn(Type type) { try { WriteObjectDelegate writeFn; if (WriteFnCache.TryGetValue(type, out writeFn)) return writeFn; var genericType = typeof(JsonWriter<>).MakeGenericType(type); var mi = genericType.GetMethod("WriteFn", BindingFlags.Public | BindingFlags.Static); var writeFactoryFn = (Func<WriteObjectDelegate>)Delegate.CreateDelegate(typeof(Func<WriteObjectDelegate>), mi); writeFn = writeFactoryFn(); Dictionary<Type, WriteObjectDelegate> snapshot, newCache; do { snapshot = WriteFnCache; newCache = new Dictionary<Type, WriteObjectDelegate>(WriteFnCache); newCache[type] = writeFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref WriteFnCache, newCache, snapshot), snapshot)); return writeFn; } catch (Exception ex) { Tracer.Instance.WriteError(ex); throw; } } private static Dictionary<Type, TypeInfo> JsonTypeInfoCache = new Dictionary<Type, TypeInfo>(); public static TypeInfo GetTypeInfo(Type type) { try { TypeInfo writeFn; if (JsonTypeInfoCache.TryGetValue(type, out writeFn)) return writeFn; var genericType = typeof(JsonWriter<>).MakeGenericType(type); var mi = genericType.GetMethod("GetTypeInfo", BindingFlags.Public | BindingFlags.Static); var writeFactoryFn = (Func<TypeInfo>)Delegate.CreateDelegate(typeof(Func<TypeInfo>), mi); writeFn = writeFactoryFn(); Dictionary<Type, TypeInfo> snapshot, newCache; do { snapshot = JsonTypeInfoCache; newCache = new Dictionary<Type, TypeInfo>(JsonTypeInfoCache); newCache[type] = writeFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref JsonTypeInfoCache, newCache, snapshot), snapshot)); return writeFn; } catch (Exception ex) { Tracer.Instance.WriteError(ex); throw; } } public static void WriteLateBoundObject(TextWriter writer, object value) { if (value == null) { if (JsConfig.IncludeNullValues) { writer.Write(JsonUtils.Null); } return; } var type = value.GetType(); var writeFn = type == typeof(object) ? WriteType<object, JsonTypeSerializer>.WriteEmptyType : GetWriteFn(type); var prevState = JsState.IsWritingDynamic; JsState.IsWritingDynamic = true; writeFn(writer, value); JsState.IsWritingDynamic = prevState; } public static WriteObjectDelegate GetValueTypeToStringMethod(Type type) { return Instance.GetValueTypeToStringMethod(type); } } internal class TypeInfo { internal bool EncodeMapKey; } /// <summary> /// Implement the serializer using a more static approach /// </summary> /// <typeparam name="T"></typeparam> internal static class JsonWriter<T> { internal static TypeInfo TypeInfo; private static readonly WriteObjectDelegate CacheFn; public static WriteObjectDelegate WriteFn() { return CacheFn ?? WriteObject; } public static TypeInfo GetTypeInfo() { return TypeInfo; } static JsonWriter() { TypeInfo = new TypeInfo { EncodeMapKey = typeof(T) == typeof(bool) || typeof(T).IsNumericType() }; CacheFn = typeof(T) == typeof(object) ? JsonWriter.WriteLateBoundObject : JsonWriter.Instance.GetWriteFn<T>(); } public static void WriteObject(TextWriter writer, object value) { CacheFn(writer, value); } } }
26.913043
116
0.68036
[ "BSD-3-Clause" ]
MikaelEliasson/ServiceStack.Text
src/ServiceStack.Text/Json/JsonWriter.Generic.cs
4,333
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using Android.App; using Android.Content; using Android.OS; using Android.Util; using Microsoft.AppCenter; using Microsoft.AppCenter.Test.Functional.Distribute; using Xunit.Runners.ResultChannels; using Xunit.Runners.UI; using Config = Microsoft.AppCenter.Test.Functional.Config; namespace Contoso.Test.Functional.Droid { using Distribute = Microsoft.AppCenter.Distribute.Distribute; [Activity(Label = "xUnit Android Runner", MainLauncher = true, Theme = "@android:style/Theme.Material.Light")] public class MainActivity : RunnerActivity { private const string ResultChannelHost = "10.0.2.2"; protected override void OnCreate(Bundle bundle) { // Clear shared preferences before the test. var prefs = GetSharedPreferences("AppCenter", FileCreationMode.Private); prefs.Edit().Clear(); // Register tests from shared library. AddTestAssembly(typeof(Config).Assembly); // Try to send results to the host via a socket for CI. try { ResultChannel = TrxResultChannel.CreateTcpTrxResultChannel(ResultChannelHost, Config.ResultChannelPort).Result; } catch (Exception e) { Log.Warn("AppCenterTest", $"Could not connect to host for reporting results.\n{e}"); } // start running the test suites as soon as the application is loaded AutoStart = true; #if !DEBUG // crash the application (to ensure it's ended) and return to springboard TerminateAfterExecution = true; #endif Distribute.SetEnabledForDebuggableBuild(true); DistributeUpdateTest.DistributeEvent += ConfigureDataForDistribute; // you cannot add more assemblies once calling base base.OnCreate(bundle); } private void ConfigureDataForDistribute(object sender, DistributeTestType distributeTestType) { var prefs = GetSharedPreferences("AppCenter", FileCreationMode.Private); var prefEditor = prefs.Edit(); switch (distributeTestType) { case DistributeTestType.FreshInstallAsync: prefEditor.PutString("Distribute.request_id", Config.RequestId); break; case DistributeTestType.CheckUpdateAsync: prefEditor.PutString("Distribute.request_id", Config.RequestId); prefEditor.PutString("Distribute.update_token", "token"); prefEditor.PutString("Distribute.distribution_group_id", Config.DistributionGroupId); prefEditor.PutString("Distribute.downloaded_release_hash", "hash"); break; case DistributeTestType.Clear: prefEditor.Remove("Distribute.request_id"); prefEditor.Remove("Distribute.update_token"); prefEditor.Remove("Distribute.distribution_group_id"); prefEditor.Remove("Distribute.downloaded_release_hash"); break; case DistributeTestType.OnResumeActivity: OnResume(); break; } prefEditor.Commit(); } } }
39.988372
127
0.627217
[ "MIT" ]
NATIVE-EARTHLING/appcenter-sdk-dotnet
Tests/Contoso.Test.Functional.Droid/MainActivity.cs
3,441
C#
using Comet.Graphics; using System.Drawing; using System.Windows.Media.Imaging; using Bitmap = Comet.Graphics.Bitmap; namespace Comet.WPF.Graphics { public class WPFBitmap : Bitmap { private BitmapImage _image; public WPFBitmap(BitmapImage image) { _image = image; } public override SizeF Size => new SizeF(_image.PixelWidth, _image.PixelHeight); public override object NativeBitmap => _image; protected override void DisposeNative() { _image = null; } } }
18.148148
81
0.732653
[ "MIT" ]
Clancey/Comet
src/Comet.WPF/Graphics/WPFBitmap.cs
492
C#
using System; namespace AdventOfCode._2015.Day18; [ProblemName("Like a GIF For Your Yard")] internal class Solution : ISolver { private static int size = 0; public object PartOne(string input) { int steps = 100; size = input.Lines().Length; int[,] grid = new int[size + 2, size + 2]; int x = 1; foreach (var line in input.Lines()) { int y = 1; foreach (var c in line) { if (c == '#') grid[x, y] = 1; else if (c == '.') grid[x, y] = 0; else throw new Exception(); y++; } x++; } for (int step = 0; step < steps; step++) { int[,] nextGrid = new int[size + 2, size + 2]; for (int i = 1; i <= size; i++) { for (int j = 1; j <= size; j++) { int n = CountNeighbors(grid, i, j); if (n == 3 || (n == 2 && grid[i, j] == 1)) { nextGrid[i, j] = 1; } } } grid = nextGrid; } int count = 0; for (int i = 1; i <= size; i++) { for (int j = 1; j <= size; j++) { count += grid[i, j]; } } return count; } public object PartTwo(string input) { int steps = 100; size = input.Lines().Length; int[,] grid = new int[size + 2, size + 2]; int x = 1; foreach (var line in input.Lines()) { int y = 1; foreach (var c in line) { if (c == '#') grid[x, y] = 1; else if (c == '.') grid[x, y] = 0; else throw new Exception(); y++; } x++; } for (int step = 0; step < steps; step++) { int[,] nextGrid = new int[size + 2, size + 2]; for (int i = 1; i <= size; i++) { for (int j = 1; j <= size; j++) { // This if statement is only for part B if ((i > 1 && i < size) || (j > 1 && j < size)) { int n = CountNeighbors(grid, i, j); if (n == 3 || (n == 2 && grid[i, j] == 1)) { nextGrid[i, j] = 1; } } else { nextGrid[i, j] = 1; } } } grid = nextGrid; } int count = 0; for (int i = 1; i <= size; i++) { for (int j = 1; j <= size; j++) { count += grid[i, j]; } } return count; } private static int CountNeighbors(int[,] grid, int i, int j) { int sum = -grid[i, j]; for (int x = i - 1; x <= i + 1; x++) { for (int y = j - 1; y <= j + 1; y++) { sum += grid[x, y]; } } return sum; } }
25.129771
67
0.31774
[ "MIT" ]
vinaykapadia/adventofcode
2015/Day18/Solution.cs
3,292
C#
using System; using System.Collections.Generic; using System.Linq; using Amazon; using Amazon.Runtime; using App.Metrics; using App.Metrics.Infrastructure; using App.Metrics.Internal.Infrastructure; using App.Metrics.Reporting.Graphite; using App.Metrics.Reporting.Http; using App.Metrics.Reporting.InfluxDB; using Exceptionless.Core; using Exceptionless.Core.Configuration; using Exceptionless.Core.Extensions; using Exceptionless.Core.Geo; using Exceptionless.Core.Jobs; using Exceptionless.Core.Jobs.Elastic; using Exceptionless.Core.Mail; using Exceptionless.Core.Queues.Models; using Exceptionless.Core.Utility; using Exceptionless.Insulation.Geo; using Exceptionless.Insulation.HealthChecks; using Exceptionless.Insulation.Mail; using Exceptionless.Insulation.Redis; using Foundatio.Caching; using Foundatio.Extensions.Hosting.Startup; using Foundatio.Jobs; using Foundatio.Messaging; using Foundatio.Metrics; using Foundatio.Queues; using Foundatio.Serializer; using Foundatio.Storage; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Serilog.Sinks.Exceptionless; using StackExchange.Redis; using QueueOptions = Exceptionless.Core.Configuration.QueueOptions; namespace Exceptionless.Insulation { public class Bootstrapper { public static void RegisterServices(IServiceCollection services, AppOptions appOptions, bool runMaintenanceTasks) { if (!String.IsNullOrEmpty(appOptions.ExceptionlessApiKey) && !String.IsNullOrEmpty(appOptions.ExceptionlessServerUrl)) { var client = ExceptionlessClient.Default; client.Configuration.ServerUrl = appOptions.ExceptionlessServerUrl; client.Configuration.ApiKey = appOptions.ExceptionlessApiKey; client.Configuration.SetDefaultMinLogLevel(Logging.LogLevel.Warn); client.Configuration.UseLogger(new SelfLogLogger()); client.Configuration.SetVersion(appOptions.Version); if (String.IsNullOrEmpty(appOptions.InternalProjectId)) client.Configuration.Enabled = false; client.Configuration.UseInMemoryStorage(); client.Configuration.UseReferenceIds(); services.ReplaceSingleton<ICoreLastReferenceIdManager, ExceptionlessClientCoreLastReferenceIdManager>(); services.AddSingleton<ExceptionlessClient>(client); } if (!String.IsNullOrEmpty(appOptions.GoogleGeocodingApiKey)) services.ReplaceSingleton<IGeocodeService>(s => new GoogleGeocodeService(appOptions.GoogleGeocodingApiKey)); if (!String.IsNullOrEmpty(appOptions.MaxMindGeoIpKey)) services.ReplaceSingleton<IGeoIpService, MaxMindGeoIpService>(); RegisterCache(services, appOptions.CacheOptions); RegisterMessageBus(services, appOptions.MessageBusOptions); RegisterMetric(services, appOptions.MetricOptions); RegisterQueue(services, appOptions.QueueOptions, runMaintenanceTasks); RegisterStorage(services, appOptions.StorageOptions); var healthCheckBuilder = RegisterHealthChecks(services, appOptions); if (!String.IsNullOrEmpty(appOptions.EmailOptions.SmtpHost)) { services.ReplaceSingleton<IMailSender, MailKitMailSender>(); healthCheckBuilder.Add(new HealthCheckRegistration("Mail", s => s.GetRequiredService<IMailSender>() as MailKitMailSender, null, new[] { "Mail", "MailMessage", "AllJobs" })); } } private static IHealthChecksBuilder RegisterHealthChecks(IServiceCollection services, AppOptions appOptions) { services.AddStartupActionToWaitForHealthChecks("Critical"); return services.AddHealthChecks() .AddCheckForStartupActions("Critical") .AddAutoNamedCheck<ElasticsearchHealthCheck>("Critical") .AddAutoNamedCheck<CacheHealthCheck>("Critical") .AddAutoNamedCheck<StorageHealthCheck>("EventPosts", "AllJobs") .AddAutoNamedCheck<QueueHealthCheck<EventPost>>("EventPosts", "AllJobs") .AddAutoNamedCheck<QueueHealthCheck<EventUserDescription>>("EventUserDescriptions", "AllJobs") .AddAutoNamedCheck<QueueHealthCheck<EventNotification>>("EventNotifications", "AllJobs") .AddAutoNamedCheck<QueueHealthCheck<WebHookNotification>>("WebHooks", "AllJobs") .AddAutoNamedCheck<QueueHealthCheck<MailMessage>>("AllJobs") .AddAutoNamedCheck<QueueHealthCheck<WorkItemData>>("WorkItem", "AllJobs") .AddAutoNamedCheck<CloseInactiveSessionsJob>("AllJobs") .AddAutoNamedCheck<DailySummaryJob>("AllJobs") .AddAutoNamedCheck<DownloadGeoIPDatabaseJob>("AllJobs") .AddAutoNamedCheck<MaintainIndexesJob>("AllJobs") .AddAutoNamedCheck<CleanupDataJob>("AllJobs") .AddAutoNamedCheck<StackStatusJob>("AllJobs") .AddAutoNamedCheck<StackEventCountJob>("AllJobs"); } private static void RegisterCache(IServiceCollection container, CacheOptions options) { if (String.Equals(options.Provider, "redis")) { container.ReplaceSingleton(s => GetRedisConnection(options.Data)); if (!String.IsNullOrEmpty(options.Scope)) container.ReplaceSingleton<ICacheClient>(s => new ScopedCacheClient(CreateRedisCacheClient(s), options.Scope)); else container.ReplaceSingleton<ICacheClient>(CreateRedisCacheClient); container.ReplaceSingleton<IConnectionMapping, RedisConnectionMapping>(); } } private static void RegisterMessageBus(IServiceCollection container, MessageBusOptions options) { if (String.Equals(options.Provider, "redis")) { container.ReplaceSingleton(s => GetRedisConnection(options.Data)); container.ReplaceSingleton<IMessageBus>(s => new RedisMessageBus(new RedisMessageBusOptions { Subscriber = s.GetRequiredService<IConnectionMultiplexer>().GetSubscriber(), Topic = options.Topic, Serializer = s.GetRequiredService<ISerializer>(), LoggerFactory = s.GetRequiredService<ILoggerFactory>() })); } else if (String.Equals(options.Provider, "rabbitmq")) { container.ReplaceSingleton<IMessageBus>(s => new RabbitMQMessageBus(new RabbitMQMessageBusOptions { ConnectionString = options.ConnectionString, Topic = options.Topic, Serializer = s.GetRequiredService<ISerializer>(), LoggerFactory = s.GetRequiredService<ILoggerFactory>() })); } } private static IConnectionMultiplexer GetRedisConnection(Dictionary<string, string> options) { // TODO: Remove this extra config parse step when sentinel bug is fixed var config = ConfigurationOptions.Parse(options.GetString("server")); return ConnectionMultiplexer.Connect(config); } private static void RegisterMetric(IServiceCollection container, MetricOptions options) { if (String.Equals(options.Provider, "statsd")) { container.ReplaceSingleton<IMetricsClient>(s => new StatsDMetricsClient(new StatsDMetricsClientOptions { ServerName = options.Data.GetString("server", "127.0.0.1"), Port = options.Data.GetValueOrDefault("port", 8125), Prefix = "ex", LoggerFactory = s.GetRequiredService<ILoggerFactory>() })); } else { var metrics = BuildAppMetrics(options); if (metrics == null) return; container.ReplaceSingleton(metrics.Clock); container.ReplaceSingleton(metrics.Filter); container.ReplaceSingleton(metrics.DefaultOutputMetricsFormatter); container.ReplaceSingleton(metrics.OutputMetricsFormatters); container.ReplaceSingleton(metrics.DefaultOutputEnvFormatter); container.ReplaceSingleton(metrics.OutputEnvFormatters); container.TryAddSingleton<EnvironmentInfoProvider>(); container.ReplaceSingleton<IMetrics>(metrics); container.ReplaceSingleton(metrics); container.ReplaceSingleton(metrics.Options); container.ReplaceSingleton(metrics.Reporters); container.ReplaceSingleton(metrics.ReportRunner); container.TryAddSingleton<AppMetricsMarkerService, AppMetricsMarkerService>(); container.ReplaceSingleton<IMetricsClient, AppMetricsClient>(); } } private static IMetricsRoot BuildAppMetrics(MetricOptions options) { var metricsBuilder = AppMetrics.CreateDefaultBuilder(); switch (options.Provider) { case "graphite": metricsBuilder.Report.ToGraphite(new MetricsReportingGraphiteOptions { Graphite = { BaseUri = new Uri(options.Data.GetString("server")) } }); break; case "http": metricsBuilder.Report.OverHttp(new MetricsReportingHttpOptions { HttpSettings = { RequestUri = new Uri(options.Data.GetString("server")), UserName = options.Data.GetString("username"), Password = options.Data.GetString("password"), } }); break; case "influxdb": metricsBuilder.Report.ToInfluxDb(new MetricsReportingInfluxDbOptions { InfluxDb = { BaseUri = new Uri(options.Data.GetString("server")), UserName = options.Data.GetString("username"), Password = options.Data.GetString("password"), Database = options.Data.GetString("database", "exceptionless") } }); break; default: return null; } return metricsBuilder.Build(); } private static void RegisterQueue(IServiceCollection container, QueueOptions options, bool runMaintenanceTasks) { if (String.Equals(options.Provider, "azurestorage")) { container.ReplaceSingleton(s => CreateAzureStorageQueue<EventPost>(s, options, retries: 1)); container.ReplaceSingleton(s => CreateAzureStorageQueue<EventUserDescription>(s, options)); container.ReplaceSingleton(s => CreateAzureStorageQueue<EventNotification>(s, options)); container.ReplaceSingleton(s => CreateAzureStorageQueue<WebHookNotification>(s, options)); container.ReplaceSingleton(s => CreateAzureStorageQueue<MailMessage>(s, options)); container.ReplaceSingleton(s => CreateAzureStorageQueue<WorkItemData>(s, options, workItemTimeout: TimeSpan.FromHours(1))); } else if (String.Equals(options.Provider, "redis")) { container.ReplaceSingleton(s => CreateRedisQueue<EventPost>(s, options, runMaintenanceTasks, retries: 1)); container.ReplaceSingleton(s => CreateRedisQueue<EventUserDescription>(s, options, runMaintenanceTasks)); container.ReplaceSingleton(s => CreateRedisQueue<EventNotification>(s, options, runMaintenanceTasks)); container.ReplaceSingleton(s => CreateRedisQueue<WebHookNotification>(s, options, runMaintenanceTasks)); container.ReplaceSingleton(s => CreateRedisQueue<MailMessage>(s, options, runMaintenanceTasks)); container.ReplaceSingleton(s => CreateRedisQueue<WorkItemData>(s, options, runMaintenanceTasks, workItemTimeout: TimeSpan.FromHours(1))); } else if (String.Equals(options.Provider, "sqs")) { container.ReplaceSingleton(s => CreateSQSQueue<EventPost>(s, options, retries: 1)); container.ReplaceSingleton(s => CreateSQSQueue<EventUserDescription>(s, options)); container.ReplaceSingleton(s => CreateSQSQueue<EventNotification>(s, options)); container.ReplaceSingleton(s => CreateSQSQueue<WebHookNotification>(s, options)); container.ReplaceSingleton(s => CreateSQSQueue<MailMessage>(s, options)); container.ReplaceSingleton(s => CreateSQSQueue<WorkItemData>(s, options, workItemTimeout: TimeSpan.FromHours(1))); } } private static void RegisterStorage(IServiceCollection container, StorageOptions options) { if (String.Equals(options.Provider, "aliyun")) { container.ReplaceSingleton<IFileStorage>(s => new AliyunFileStorage(new AliyunFileStorageOptions { ConnectionString = options.ConnectionString, Serializer = s.GetRequiredService<ITextSerializer>(), LoggerFactory = s.GetRequiredService<ILoggerFactory>() })); } else if (String.Equals(options.Provider, "azurestorage")) { container.ReplaceSingleton<IFileStorage>(s => new AzureFileStorage(new AzureFileStorageOptions { ConnectionString = options.ConnectionString, ContainerName = $"{options.ScopePrefix}ex-events", Serializer = s.GetRequiredService<ITextSerializer>(), LoggerFactory = s.GetRequiredService<ILoggerFactory>() })); } else if (String.Equals(options.Provider, "folder")) { string path = options.Data.GetString("path", "|DataDirectory|\\storage"); container.AddSingleton<IFileStorage>(s => new FolderFileStorage(new FolderFileStorageOptions { Folder = PathHelper.ExpandPath(path), Serializer = s.GetRequiredService<ITextSerializer>(), LoggerFactory = s.GetRequiredService<ILoggerFactory>() })); } else if (String.Equals(options.Provider, "minio")) { container.ReplaceSingleton<IFileStorage>(s => new MinioFileStorage(new MinioFileStorageOptions { ConnectionString = options.ConnectionString, Serializer = s.GetRequiredService<ITextSerializer>(), LoggerFactory = s.GetRequiredService<ILoggerFactory>() })); } else if (String.Equals(options.Provider, "s3")) { container.ReplaceSingleton<IFileStorage>(s => new S3FileStorage(new S3FileStorageOptions { ConnectionString = options.ConnectionString, Credentials = GetAWSCredentials(options.Data), Region = GetAWSRegionEndpoint(options.Data), Bucket = $"{options.ScopePrefix}{options.Data.GetString("bucket", "ex-events")}", Serializer = s.GetRequiredService<ITextSerializer>(), LoggerFactory = s.GetRequiredService<ILoggerFactory>() })); } } private static IQueue<T> CreateAzureStorageQueue<T>(IServiceProvider container, QueueOptions options, int retries = 2, TimeSpan? workItemTimeout = null) where T : class { return new AzureStorageQueue<T>(new AzureStorageQueueOptions<T> { ConnectionString = options.ConnectionString, Name = GetQueueName<T>(options).ToLowerInvariant(), Retries = retries, Behaviors = container.GetServices<IQueueBehavior<T>>().ToList(), WorkItemTimeout = workItemTimeout.GetValueOrDefault(TimeSpan.FromMinutes(5.0)), Serializer = container.GetRequiredService<ISerializer>(), LoggerFactory = container.GetRequiredService<ILoggerFactory>() }); } private static IQueue<T> CreateRedisQueue<T>(IServiceProvider container, QueueOptions options, bool runMaintenanceTasks, int retries = 2, TimeSpan? workItemTimeout = null) where T : class { return new RedisQueue<T>(new RedisQueueOptions<T> { ConnectionMultiplexer = container.GetRequiredService<IConnectionMultiplexer>(), Name = GetQueueName<T>(options), Retries = retries, Behaviors = container.GetServices<IQueueBehavior<T>>().ToList(), WorkItemTimeout = workItemTimeout.GetValueOrDefault(TimeSpan.FromMinutes(5.0)), RunMaintenanceTasks = runMaintenanceTasks, Serializer = container.GetRequiredService<ISerializer>(), LoggerFactory = container.GetRequiredService<ILoggerFactory>() }); } private static RedisCacheClient CreateRedisCacheClient(IServiceProvider container) { return new RedisCacheClient(new RedisCacheClientOptions { ConnectionMultiplexer = container.GetRequiredService<IConnectionMultiplexer>(), Serializer = container.GetRequiredService<ISerializer>(), LoggerFactory = container.GetRequiredService<ILoggerFactory>() }); } private static IQueue<T> CreateSQSQueue<T>(IServiceProvider container, QueueOptions options, int retries = 2, TimeSpan? workItemTimeout = null) where T : class { return new SQSQueue<T>(new SQSQueueOptions<T> { Name = GetQueueName<T>(options), Credentials = GetAWSCredentials(options.Data), Region = GetAWSRegionEndpoint(options.Data), CanCreateQueue = false, Retries = retries, Behaviors = container.GetServices<IQueueBehavior<T>>().ToList(), WorkItemTimeout = workItemTimeout.GetValueOrDefault(TimeSpan.FromMinutes(5.0)), Serializer = container.GetRequiredService<ISerializer>(), LoggerFactory = container.GetRequiredService<ILoggerFactory>() }); } private static string GetQueueName<T>(QueueOptions options) { return String.Concat(options.ScopePrefix, typeof(T).Name); } private static RegionEndpoint GetAWSRegionEndpoint(IDictionary<string, string> data) { string region = data.GetString("region"); return RegionEndpoint.GetBySystemName(String.IsNullOrEmpty(region) ? "us-east-1" : region); } private static AWSCredentials GetAWSCredentials(IDictionary<string, string> data) { string accessKey = data.GetString("accesskey"); string secretKey = data.GetString("secretkey"); if (String.IsNullOrEmpty(accessKey) || String.IsNullOrEmpty(secretKey)) return FallbackCredentialsFactory.GetCredentials(); return new BasicAWSCredentials(accessKey, secretKey); } } }
57.008746
197
0.644318
[ "Apache-2.0" ]
aTiKhan/Exceptionless
src/Exceptionless.Insulation/Bootstrapper.cs
19,554
C#
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using Abp.Dependency; using Abp.Linq; namespace Abp.EntityFramework.Linq { public class EfAsyncQueryableExecuter : IAsyncQueryableExecuter, ISingletonDependency { public Task<int> CountAsync<T>(IQueryable<T> queryable) { return queryable.CountAsync(); } [Obsolete("Use System.Linq.Queryable.Count() instead.")] public int Count<T>(IQueryable<T> queryable) { return queryable.Count(); } public Task<List<T>> ToListAsync<T>(IQueryable<T> queryable) { return queryable.ToListAsync(); } [Obsolete("Use System.Linq.Queryable.ToList() instead.")] public List<T> ToList<T>(IQueryable<T> queryable) { return queryable.ToList(); } public Task<T> FirstOrDefaultAsync<T>(IQueryable<T> queryable) { return queryable.FirstOrDefaultAsync(); } [Obsolete("Use System.Linq.Queryable.FirstOrDefault() instead.")] public T FirstOrDefault<T>(IQueryable<T> queryable) { return queryable.FirstOrDefault(); } public Task<bool> AnyAsync<T>(IQueryable<T> queryable) { return queryable.AnyAsync(); } } }
26.865385
89
0.61131
[ "MIT" ]
AnisBOULAID/aspnetboilerplate
src/Abp.EntityFramework/EntityFramework/Linq/EfAsyncQueryableExecuter.cs
1,399
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace MajiroDebugListener.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MajiroDebugListener.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap breakpoints { get { object obj = ResourceManager.GetObject("breakpoints", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap bug { get { object obj = ResourceManager.GetObject("bug", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap pause { get { object obj = ResourceManager.GetObject("pause", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap restart { get { object obj = ResourceManager.GetObject("restart", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap resume { get { object obj = ResourceManager.GetObject("resume", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap run { get { object obj = ResourceManager.GetObject("run", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap settings { get { object obj = ResourceManager.GetObject("settings", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap step_in { get { object obj = ResourceManager.GetObject("step_in", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap step_out { get { object obj = ResourceManager.GetObject("step_out", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap step_over { get { object obj = ResourceManager.GetObject("step_over", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap stop { get { object obj = ResourceManager.GetObject("stop", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap variable { get { object obj = ResourceManager.GetObject("variable", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
39.043478
185
0.556097
[ "MIT" ]
AtomCrafty/MajiroTools
src/MajiroDebugListener/Properties/Resources.Designer.cs
7,186
C#
namespace Altsoft.PDFO { using System; public class MCD_MHBE : Resource { // Methods public MCD_MHBE(PDFDirect direct) : base(direct) { } public static MCD_MHBE Create() { return MCD_MHBE.Create(true); } public static MCD_MHBE Create(bool indirect) { PDFDict dict1 = Library.CreateDict(); if (indirect) { Library.CreateIndirect(dict1); } return new MCD_MHBE(dict1); } public static MCD_MHBE Create(string URL) { MCD_MHBE mcd_mhbe1 = MCD_MHBE.Create(true); mcd_mhbe1.URL = URL; return mcd_mhbe1; } public static MCD_MHBE Create(bool indirect, string URL) { MCD_MHBE mcd_mhbe1 = MCD_MHBE.Create(indirect); mcd_mhbe1.URL = URL; return mcd_mhbe1; } public static Resource Factory(PDFDirect direct) { return new MCD_MHBE(direct); } // Properties public string URL { get { PDFString text1 = (this.Dict["BU"] as PDFString); if (text1 == null) { return null; } return text1.Value; } set { this.Dict["BU"] = Library.CreateString(value); } } } }
22.147059
65
0.462815
[ "MIT" ]
silvath/siscobras
mdlPDF/Xml2PDF/Source/Altsoft/PDFO/MCD_MHBE.cs
1,506
C#
using System; using XK.Common.web; namespace XK.WeiXin.Author { public class AppTicket { public const string AccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}"; /// <summary> /// 获取请求地址 /// </summary> /// <param name="appID"></param> /// <param name="appSecret"></param> /// <returns></returns> public string GetAccessTokenUrl(string appID, string appSecret) { return string.Format(AccessTokenUrl, appID, appSecret); } public string GetAccessTokenUrl() { return string.Format(AccessTokenUrl, AppConfig.Instance.AppID, AppConfig.Instance.AppSecret); } public string GetAccessTokenJson() { string reqUrl = string.Format(GetAccessTokenUrl(AppConfig.Instance.AppID, AppConfig.Instance.AppSecret)); HttpWebHelper httpWebHelper = new HttpWebHelper(reqUrl); string json = httpWebHelper.GetResponseStr(); return json; } public string GetAccessTokenJson(string appID, string appSecret) { string reqUrl = string.Format(GetAccessTokenUrl(appID, appSecret)); HttpWebHelper httpWebHelper = new HttpWebHelper(reqUrl); string json = httpWebHelper.GetResponseStr(); return json; } public AccessToken_Model GetAccessToken() { string jsonAccessToken = GetAccessTokenJson(); AccessToken_Model accessToken = Common.json.JsonHelper<AccessToken_Model>.DeserializeFromStr(jsonAccessToken); return accessToken; } public AccessToken_Model GetAccessToken(string appID, string appSecret) { string jsonAccessToken = GetAccessTokenJson(appID, appSecret); AccessToken_Model accessToken = Common.json.JsonHelper<AccessToken_Model>.DeserializeFromStr(jsonAccessToken); return accessToken; } } }
34.912281
116
0.652764
[ "Apache-2.0" ]
kangwl/xk
XK.WeiXin/Author/AppTicket.cs
2,004
C#
 namespace Homework_26_11_20.Views { partial class SpecialtiesForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.specialtiesGridView = new System.Windows.Forms.DataGridView(); this.IdColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.NameColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.CodeColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.addItemButton = new System.Windows.Forms.Button(); this.deleteItemButton = new System.Windows.Forms.Button(); this.refreshDataButton = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.specialtiesGridView)).BeginInit(); this.SuspendLayout(); // // specialtiesGridView // this.specialtiesGridView.AllowUserToOrderColumns = true; this.specialtiesGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.specialtiesGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.specialtiesGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.IdColumn, this.NameColumn, this.CodeColumn}); this.specialtiesGridView.Location = new System.Drawing.Point(12, 12); this.specialtiesGridView.Name = "specialtiesGridView"; this.specialtiesGridView.RowHeadersWidth = 60; this.specialtiesGridView.Size = new System.Drawing.Size(362, 227); this.specialtiesGridView.TabIndex = 0; // // IdColumn // this.IdColumn.DataPropertyName = "Id"; this.IdColumn.HeaderText = "№"; this.IdColumn.Name = "IdColumn"; this.IdColumn.ReadOnly = true; this.IdColumn.Visible = false; // // NameColumn // this.NameColumn.DataPropertyName = "Name"; this.NameColumn.HeaderText = "Название"; this.NameColumn.Name = "NameColumn"; // // CodeColumn // this.CodeColumn.DataPropertyName = "Code"; this.CodeColumn.HeaderText = "Шифр"; this.CodeColumn.Name = "CodeColumn"; // // addItemButton // this.addItemButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.addItemButton.Location = new System.Drawing.Point(12, 246); this.addItemButton.Name = "addItemButton"; this.addItemButton.Size = new System.Drawing.Size(122, 34); this.addItemButton.TabIndex = 1; this.addItemButton.Text = "Добавить"; this.addItemButton.UseVisualStyleBackColor = true; // // deleteItemButton // this.deleteItemButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.deleteItemButton.Location = new System.Drawing.Point(140, 246); this.deleteItemButton.Name = "deleteItemButton"; this.deleteItemButton.Size = new System.Drawing.Size(122, 34); this.deleteItemButton.TabIndex = 2; this.deleteItemButton.Text = "Удалить"; this.deleteItemButton.UseVisualStyleBackColor = true; // // refreshDataButton // this.refreshDataButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.refreshDataButton.Location = new System.Drawing.Point(287, 245); this.refreshDataButton.Name = "refreshDataButton"; this.refreshDataButton.Size = new System.Drawing.Size(87, 35); this.refreshDataButton.TabIndex = 3; this.refreshDataButton.Text = "Обновить"; this.refreshDataButton.UseVisualStyleBackColor = true; // // SpecialtiesForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(386, 292); this.Controls.Add(this.refreshDataButton); this.Controls.Add(this.deleteItemButton); this.Controls.Add(this.addItemButton); this.Controls.Add(this.specialtiesGridView); this.MinimumSize = new System.Drawing.Size(402, 331); this.Name = "SpecialtiesForm"; this.Text = "Специальности"; ((System.ComponentModel.ISupportInitialize)(this.specialtiesGridView)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.DataGridView specialtiesGridView; private System.Windows.Forms.DataGridViewTextBoxColumn IdColumn; private System.Windows.Forms.DataGridViewTextBoxColumn NameColumn; private System.Windows.Forms.DataGridViewTextBoxColumn CodeColumn; private System.Windows.Forms.Button addItemButton; private System.Windows.Forms.Button deleteItemButton; private System.Windows.Forms.Button refreshDataButton; } }
47.948529
168
0.623831
[ "MIT" ]
12Jekan35/Homework_26_11_20
Homework_26_11_20_project/Views/SpecialtiesForm.Designer.cs
6,573
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Moyasar.Abstraction; using Moyasar.Exceptions; using Newtonsoft.Json; namespace Moyasar.Models { public class StcPaySource : IPaymentSource { [JsonProperty("type")] public string Type { get; } = "stcpay"; [JsonProperty("mobile")] public string Mobile { get; set; } [JsonProperty("branch", NullValueHandling = NullValueHandling.Ignore)] public string Branch { get; set; } [JsonProperty("cashier", NullValueHandling = NullValueHandling.Ignore)] public string Cashier { get; set; } public void Validate() { var errors = new List<FieldError>(); if (String.IsNullOrEmpty(Mobile)) { errors.Add(new FieldError { Field = nameof(Mobile), Error = "Mobile number is required." }); } if (!Regex.IsMatch(Mobile, @"^05[503649187][0-9]{7}$")) { errors.Add(new FieldError { Field = nameof(Mobile), Error = "Number is not a valid Saudi mobile." }); } if (errors.Any()) { throw new ValidationException("stc pay information are incorrect") { FieldErrors = errors }; } } } }
27.333333
82
0.505135
[ "MIT" ]
moyasar/moyasar-dotnet
Moyasar/Models/StcPaySource.cs
1,558
C#
namespace SimpleBackup.Main.Tasks.Backup { partial class BackupForm { /// <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(BackupForm)); this.panel1 = new System.Windows.Forms.Panel(); this.progressBar = new System.Windows.Forms.ProgressBar(); this.buttonCancel = new System.Windows.Forms.Button(); this.processingBackgroundWorker = new System.ComponentModel.BackgroundWorker(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.Controls.Add(this.progressBar); this.panel1.Controls.Add(this.buttonCancel); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Name = "panel1"; this.panel1.Padding = new System.Windows.Forms.Padding(9); this.panel1.Size = new System.Drawing.Size(304, 86); this.panel1.TabIndex = 0; // // progressBar // this.progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.progressBar.Location = new System.Drawing.Point(12, 12); this.progressBar.Name = "progressBar"; this.progressBar.Size = new System.Drawing.Size(280, 23); this.progressBar.Style = System.Windows.Forms.ProgressBarStyle.Marquee; this.progressBar.TabIndex = 1; // // buttonCancel // this.buttonCancel.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Location = new System.Drawing.Point(109, 46); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.Size = new System.Drawing.Size(85, 28); this.buttonCancel.TabIndex = 0; this.buttonCancel.Text = "Cancel"; this.buttonCancel.UseVisualStyleBackColor = true; this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); // // processingBackgroundWorker // this.processingBackgroundWorker.WorkerReportsProgress = true; this.processingBackgroundWorker.WorkerSupportsCancellation = true; this.processingBackgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.processingBackgroundWorker_DoWork); this.processingBackgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.processingBackgroundWorker_RunWorkerCompleted); // // BackupForm // this.AcceptButton = this.buttonCancel; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.CancelButton = this.buttonCancel; this.ClientSize = new System.Drawing.Size(304, 86); this.Controls.Add(this.panel1); this.Font = new System.Drawing.Font("Segoe UI", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "BackupForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Backup folder"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.BackupForm_FormClosing); this.Load += new System.EventHandler(this.BackupForm_Load); this.Shown += new System.EventHandler(this.BackupForm_Shown); this.panel1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.ProgressBar progressBar; private System.ComponentModel.BackgroundWorker processingBackgroundWorker; } }
47.738739
175
0.631062
[ "MIT" ]
UweKeim/SimpleBackup
Source/Main/Tasks/Backup/BackupForm.Designer.cs
5,301
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace Reeduca.Api { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
24.28
76
0.691928
[ "MIT" ]
GemersonDenner/plataforma-reeduca
Reeduca.Api/Program.cs
609
C#
using System.Linq; namespace System.Forest.Services { public class BranchNavigationService : IBranchNavigationService { public void StepDown(ITree tree, int id) { tree.CurrentBranch = tree.CurrentBranch == null ? tree.Branches.Single(b => b.Id == id) : tree.CurrentBranch.Branches.Single(b => b.Id == id); } public void StepUp(ITree tree) { tree.CurrentBranch = tree.CurrentBranch?.PreviousBranch; } } }
27.277778
154
0.623218
[ "MIT" ]
SamB1990/ObjectForest
src/Services/BranchNavigationService.cs
493
C#
namespace Dapper.SimpleSave.Tests.GuidDtos { [Table("dbo.GuidOneToManyReferenceChild")] [ReferenceData] public class GuidOneToManyReferenceChildDto : GuidBaseOneToManyChildDto { } }
29.285714
78
0.741463
[ "MIT" ]
Paymentsense/Dapper.SimpleSave
src/Dapper.SimpleSave.Tests/GuidDtos/GuidOneToManyReferenceChildDto.cs
207
C#
using System; namespace ExistForAll.SimpleSettings { internal interface ISettingsHolder { Type SettingsType { get; } object SettingsImplementation { get; } } }
17.7
41
0.717514
[ "MIT" ]
existall/Settings
src/Core/ExistForAll.SimpleSettings/ISettingsHolder.cs
179
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 ThangNguyen.GlobalTicket.Client.Data; namespace ThangNguyen.GlobalTicket.Client.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20211112003333_AddCardInformationIdentityUser")] partial class AddCardInformationIdentityUser { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.11") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasDatabaseName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("nvarchar(450)"); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(450)"); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(450)"); b.Property<string>("Name") .HasColumnType("nvarchar(450)"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("ThangNguyen.GlobalTicket.Client.Models.ApplicationUser", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("CardHolderName") .HasColumnType("nvarchar(max)"); b.Property<string>("CardNumber") .HasColumnType("nvarchar(max)"); b.Property<int>("CardType") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<string>("Expiration") .HasColumnType("nvarchar(max)"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("NormalizedEmail") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedUserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityNumber") .HasColumnType("nvarchar(max)"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasDatabaseName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasDatabaseName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("ThangNguyen.GlobalTicket.Client.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("ThangNguyen.GlobalTicket.Client.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ThangNguyen.GlobalTicket.Client.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("ThangNguyen.GlobalTicket.Client.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
38.031142
125
0.4773
[ "MIT" ]
thangnguyenofficial/micro-services-synchronous-sample
ThangNguyen.GlobalTicket.Client/Migrations/20211112003333_AddCardInformationIdentityUser.Designer.cs
10,993
C#
using System.Collections.Generic; namespace TriggersTools.Windows.Resources.Menu { /// <summary> /// A template for a menu ex item container. /// </summary> public interface IMenuExTemplateItemContainer : IMenuBaseTemplateItemContainer { /// <summary> /// Gets the list of menu items within this container. /// </summary> new List<IMenuExTemplateItem> MenuItems { get; set; } } }
28.357143
81
0.720403
[ "MIT" ]
trigger-death/TriggersTools.Windows.Resources
src/TriggersTools.Windows.Resources/Menu/IMenuExTemplateItemContainer.cs
399
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public abstract class CollectableBase : MonoBehaviour { protected abstract void Collect(Player player); [SerializeField] float _movementSpeed = 1; protected float MovementSpeed => _movementSpeed; [SerializeField] ParticleSystem _collectParticles; [SerializeField] AudioClip _collectSound; Rigidbody _rb; private void Awake() { _rb = GetComponent<Rigidbody>(); } private void FixedUpdate() { Movement(_rb); } protected virtual void Movement(Rigidbody rb) { // calc rotation Quaternion turnOffset = Quaternion.Euler(0, _movementSpeed, 0); rb.MoveRotation(_rb.rotation * turnOffset); } private void OnTriggerEnter(Collider other) { Player player = other.gameObject.GetComponent<Player>(); if (player != null) { Collect(player); // spawn particles & sfx (disabled object so separate) Feedback(); gameObject.SetActive(false); } } private void Feedback() { // particles if (_collectParticles != null) { _collectParticles = Instantiate(_collectParticles, transform.position, Quaternion.identity); } if (_collectSound != null) { AudioHelper.PlayClip2D(_collectSound, 1f); } } }
21.5
96
0.696899
[ "MIT" ]
gummiez/CaoTyty_4368_P01A
Assets/Scripts/CollectableBase.cs
1,292
C#
using System; namespace Skibitsky.Urx { public interface IScheduler { DateTimeOffset Now { get; } IDisposable Schedule(Action action); IDisposable Schedule(TimeSpan dueTime, Action action); } }
18.461538
62
0.641667
[ "MIT" ]
skibitsky/urx
Runtime/Schedulers/IScheduler.cs
240
C#
using System; using System.Reflection; using System.Windows.Forms; using Microsoft.Win32; using Shadowsocks.Util; namespace Shadowsocks.Controller { static class AutoStartup { // Don't use Application.ExecutablePath private static readonly string ExecutablePath = Assembly.GetEntryAssembly().Location; private static string Key = "Shadowsocks_" + Application.StartupPath.GetHashCode(); public static bool Set(bool enabled) { RegistryKey runKey = null; try { runKey = Utils.OpenRegKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); if ( runKey == null ) { Logging.Error( @"Cannot find HKCU\Software\Microsoft\Windows\CurrentVersion\Run" ); return false; } if (enabled) { runKey.SetValue(Key, ExecutablePath); } else { runKey.DeleteValue(Key); } return true; } catch (Exception e) { Logging.LogUsefulException(e); return false; } finally { if (runKey != null) { try { runKey.Close(); runKey.Dispose(); } catch (Exception e) { Logging.LogUsefulException(e); } } } } public static bool Check() { RegistryKey runKey = null; try { runKey = Utils.OpenRegKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); if (runKey == null) { Logging.Error(@"Cannot find HKCU\Software\Microsoft\Windows\CurrentVersion\Run"); return false; } string[] runList = runKey.GetValueNames(); foreach (string item in runList) { if (item.Equals(Key, StringComparison.OrdinalIgnoreCase)) return true; else if (item.Equals("Shadowsocks", StringComparison.OrdinalIgnoreCase)) // Compatibility with older versions { string value = Convert.ToString(runKey.GetValue(item)); if (ExecutablePath.Equals(value, StringComparison.OrdinalIgnoreCase)) { runKey.DeleteValue(item); runKey.SetValue(Key, ExecutablePath); return true; } } } return false; } catch (Exception e) { Logging.LogUsefulException(e); return false; } finally { if (runKey != null) { try { runKey.Close(); runKey.Dispose(); } catch (Exception e) { Logging.LogUsefulException(e); } } } } } }
33.970297
130
0.426698
[ "Apache-2.0" ]
kanego/Tal-windows
shadowsocks-csharp/Controller/System/AutoStartup.cs
3,433
C#
using AoCHelper; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AoC_2019.IntCode.Instructions { public abstract class BaseInstruction : IInstruction { public const int InstructionPointerValueWhenHalt = -1; public abstract int Length { get; } public abstract Task<InstructionOutput> Run(InstructionInput instructionInput); protected static Task<InstructionOutput> Nothing(int newInstructionPointer) => Task.FromResult(new InstructionOutput() { InstructionPointer = newInstructionPointer }); protected static Task<InstructionOutput> Nothing(long newInstructionPointer) => Nothing((int)newInstructionPointer); protected static int ExtractMemoryAddress(InstructionInput instructionInput, int offset) { long opCode = instructionInput.OpCode; List<ParameterMode> parameterModes = new List<ParameterMode>(); int opCodeLength = opCode.ToString().Length; if (opCodeLength != 1) { IEnumerable<int> parameters = opCode.ToString().Reverse().Select(c => int.Parse(c.ToString())); parameterModes = parameters.Skip(2).Select(n => (ParameterMode)n).ToList(); opCode = int.Parse(opCode.ToString().Substring(opCodeLength - 2)); } ParameterMode parameterMode = offset <= parameterModes.Count ? parameterModes[offset - 1] : default; int memoryAddress = (int)(parameterMode switch { ParameterMode.Position => instructionInput.IntCode[instructionInput.InstructionPointer + offset], ParameterMode.Immediate => instructionInput.InstructionPointer + offset, ParameterMode.Relative => instructionInput.RelativeBase + instructionInput.IntCode[instructionInput.InstructionPointer + offset], _ => throw new SolvingException($"Unknown ParameterMode: {parameterMode}") }); if (memoryAddress >= instructionInput.IntCode.Count) { for (int i = instructionInput.IntCode.Count; i < memoryAddress + 1; ++i) { instructionInput.IntCode.Add(0); } } return memoryAddress; } } }
37.765625
145
0.623086
[ "MIT" ]
eduherminio/AoC2019
AoC_2019/IntCode/Instructions/BaseInstruction.cs
2,419
C#
using FluentBootstrap.ListGroups; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FluentBootstrap.Panels { public interface IPanelCreator<THelper> : IComponentCreator<THelper> where THelper : BootstrapHelper<THelper> { } public class PanelWrapper<THelper> : TagWrapper<THelper>, IPanelSectionCreator<THelper>, IPanelTitleCreator<THelper>, IListGroupCreator<THelper> where THelper : BootstrapHelper<THelper> { } internal interface IPanel : ITag { } public class Panel<THelper> : Tag<THelper, Panel<THelper>, PanelWrapper<THelper>>, IPanel where THelper : BootstrapHelper<THelper> { internal Panel(IComponentCreator<THelper> creator) : base(creator, "div", Css.Panel, Css.PanelDefault) { } } }
25.25
93
0.678768
[ "MIT" ]
jbgriffith/FluentBootstrap
FluentBootstrap/Panels/Panel.cs
912
C#
using System.Threading.Tasks; namespace Cik.MazSite.WebApp.Services { // This class is used by the application to send Email and SMS // when you turn on two-factor authentication in ASP.NET Identity. // For more details see this link http://go.microsoft.com/fwlink/?LinkID=532713 public class AuthMessageSender : IEmailSender, ISmsSender { public Task SendEmailAsync(string email, string subject, string message) { // Plug in your email service here to send an email. return Task.FromResult(0); } public Task SendSmsAsync(string number, string message) { // Plug in your SMS service here to send a text message. return Task.FromResult(0); } } public interface IEmailSender { Task SendEmailAsync(string email, string subject, string message); } public interface ISmsSender { Task SendSmsAsync(string number, string message); } }
31
83
0.653226
[ "MIT" ]
harsharaosk/magazine
src/Services/MessageServices.cs
994
C#
// ReSharper disable once CheckNamespace namespace System.Runtime.CompilerServices { internal static class IsExternalInit { } }
26.4
44
0.795455
[ "MIT" ]
catcat0921/lindexi_gd
LightTextEditorPlus/TextEditorPlus/Utils/Compatibles/IsExternalInit.cs
134
C#
#region License /* Copyright (c) 2015 Betson Roy 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; namespace QueryMaster.GameServer.EventArgs { /// <summary> /// Provides data for PlayerScoreReport event. /// </summary> [Serializable] public class PlayerScoreReportEventArgs : PlayerEventArgs { /// <summary> /// Gets player score. /// </summary> public string Score { get; internal set; } /// <summary> /// Gets the additional data present in the message. /// </summary> public string ExtraInfo { get; internal set; } } }
32.68
65
0.725214
[ "Apache-2.0" ]
TheRealHona/Lambda
src/QueryMaster/GameServer/EventArgs/PlayerScoreReportEventArgs.cs
1,636
C#
using System; using System.Linq; using System.Collections.Generic; namespace Flow.Audio { public class Sound : BaseAudio { public override float this[float t, int channel = 0] => Channels[channel][(int)(t / 50000f)]; public string Path { get; set; } = "output.wav"; public List<float[]> Channels { get; set; } = new List<float[]>(); public override void Save() => SaveAsWave(this.Path); public void SaveAsWave(string path) { if (Channels.Count == 0 || Channels.Count(c => c == null || c.Length == 0) > 0) throw new Exception("One ou more channels of this Sound is empty"); WavCodec codec = new WavCodec(); codec.BitsPerSample = 24; codec.FormatCode = 1; codec.SampleRate = 50000; byte[][] convertedata = new byte[Channels.Count][]; float[] data; int value; int size; for (int i = 0; i < convertedata.Length; i++) { data = Channels[i]; size = (int)(3 * Channels[i].Length); convertedata[i] = new byte[size]; for (int j = 0, k = 0; j < size; j += 3, k++) { if (data[k] > 1f) value = 8388608; else if (data[k] < -1f) value = -8388608; else value = (int)(8388608 * data[k]); if (value < 0) value += 256 * 256 * 256; convertedata[i][j] = (byte)(value % 256); value /= 256; convertedata[i][j + 1] = (byte)(value % 256); convertedata[i][j + 2] = (byte)(value / 256); } } codec.Save(path, convertedata); } public static Sound New(double duration, int channels = 1) { Sound sound = new Sound(); int size = (int)(duration * 50000); while (channels-- > 0) sound.Channels.Add(new float[size]); return sound; } public static Sound operator +(Sound a, Sound b) { for (int c = 0; c < a.Channels.Count; c++) { if (b.Channels.Count == c) break; var datA = a.Channels[c]; var datB = b.Channels[c]; int size = datA.Length < datB.Length ? datA.Length : datB.Length; for (int i = 0; i < size; i++) { datA[i] += datB[i]; } } return a; } public static Sound operator -(Sound a, Sound b) { for (int c = 0; c < a.Channels.Count; c++) { if (b.Channels.Count == c) break; var datA = a.Channels[c]; var datB = b.Channels[c]; int size = datA.Length < datB.Length ? datA.Length : datB.Length; for (int i = 0; i < size; i++) { datA[i] -= datB[i]; } } return a; } public static Sound operator *(Sound a, Sound b) { for (int c = 0; c < a.Channels.Count; c++) { if (b.Channels.Count == c) break; var datA = a.Channels[c]; var datB = b.Channels[c]; int size = datA.Length < datB.Length ? datA.Length : datB.Length; for (int i = 0; i < size; i++) { datA[i] *= datB[i]; } } return a; } public static Sound operator /(Sound a, Sound b) { for (int c = 0; c < a.Channels.Count; c++) { if (b.Channels.Count == c) break; var datA = a.Channels[c]; var datB = b.Channels[c]; int size = datA.Length < datB.Length ? datA.Length : datB.Length; for (int i = 0; i < size; i++) { datA[i] /= datB[i] == 0.0 ? float.Epsilon : datB[i]; } } return a; } } }
35.063492
91
0.405387
[ "MIT" ]
trevisharp/dotflow
Audio/Sound.cs
4,418
C#
using System; using System.Text; using ForgetMeNot.Common; using ForgetMeNot.Messages; namespace ForgetMeNot.Core.Tests { public static class TestHelper { public static ReminderMessage.Schedule BuildMeAScheduleMessage() { return new ReminderMessage.Schedule( Guid.NewGuid(), SystemTime.UtcNow(), "http://delivery/url", "application/json", ReminderMessage.ContentEncodingEnum.utf8, ReminderMessage.TransportEnum.http, Encoding.UTF8.GetBytes("hello world"), 0); } public static ReminderMessage.Schedule BuildMeAScheduleMessage(DateTime dueTime) { return new ReminderMessage.Schedule( Guid.NewGuid(), dueTime, "http://delivery/url", "application/json", ReminderMessage.ContentEncodingEnum.utf8, ReminderMessage.TransportEnum.http, Encoding.UTF8.GetBytes("hello world"), 0); } public static ReminderMessage.Schedule WithRetry(this ReminderMessage.Schedule schedule, int attempts, TimeSpan retryPeriod) { return new ReminderMessage.Schedule( schedule.ReminderId, schedule.DueAt, schedule.DeliveryUrl, schedule.ContentType, schedule.ContentEncoding, schedule.Transport, schedule.Payload, attempts, schedule.DueAt + retryPeriod, schedule.Tag); } public static ReminderMessage.Schedule WithIdentity(this ReminderMessage.Schedule schedule, Guid reminderId) { return new ReminderMessage.Schedule( reminderId, schedule.DueAt, schedule.DeliveryUrl, schedule.ContentType, schedule.ContentEncoding, schedule.Transport, schedule.Payload, schedule.MaxRetries, schedule.DueAt, schedule.Tag); } } }
33.119403
132
0.5516
[ "MIT" ]
rmacdonaldsmith/ForgetMeNot-Akka
src/Core.Tests/TestHelper.cs
2,221
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. // </auto-generated> namespace Microsoft.Azure.Management.Cdn.Fluent.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Rules defining user's geo access within a CDN endpoint. /// </summary> public partial class GeoFilter { /// <summary> /// Initializes a new instance of the GeoFilter class. /// </summary> public GeoFilter() { CustomInit(); } /// <summary> /// Initializes a new instance of the GeoFilter class. /// </summary> /// <param name="relativePath">Relative path applicable to geo filter. /// (e.g. '/mypictures', '/mypicture/kitty.jpg', and etc.)</param> /// <param name="action">Action of the geo filter, i.e. allow or block /// access. Possible values include: 'Block', 'Allow'</param> /// <param name="countryCodes">Two letter country codes defining user /// country access in a geo filter, e.g. AU, MX, US.</param> public GeoFilter(string relativePath, GeoFilterActions action, IList<string> countryCodes) { RelativePath = relativePath; Action = action; CountryCodes = countryCodes; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets relative path applicable to geo filter. (e.g. /// '/mypictures', '/mypicture/kitty.jpg', and etc.) /// </summary> [JsonProperty(PropertyName = "relativePath")] public string RelativePath { get; set; } /// <summary> /// Gets or sets action of the geo filter, i.e. allow or block access. /// Possible values include: 'Block', 'Allow' /// </summary> [JsonProperty(PropertyName = "action")] public GeoFilterActions Action { get; set; } /// <summary> /// Gets or sets two letter country codes defining user country access /// in a geo filter, e.g. AU, MX, US. /// </summary> [JsonProperty(PropertyName = "countryCodes")] public IList<string> CountryCodes { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (RelativePath == null) { throw new ValidationException(ValidationRules.CannotBeNull, "RelativePath"); } if (CountryCodes == null) { throw new ValidationException(ValidationRules.CannotBeNull, "CountryCodes"); } } } }
34.76087
98
0.582864
[ "MIT" ]
AntoineGa/azure-libraries-for-net
src/ResourceManagement/Cdn/Generated/Models/GeoFilter.cs
3,198
C#
using Java.Interop; namespace Square.OkIO { partial class OkBuffer : global::Java.Lang.Object, global::Java.Lang.ICloneable, global::Java.Nio.Channels.IByteChannel, global::Square.OkIO.IBufferedSink, global::Square.OkIO.IBufferedSource { global::Square.OkIO.OkBuffer IBufferedSink.Buffer() { return this; } } }
29.916667
195
0.682451
[ "Apache-2.0" ]
JosueDM94/Xamarin.Square
binding/Square.OkIO/Additions/OkBuffer.cs
359
C#
using UnityEngine; namespace UnityWeld.Binding.Adapters { /// <summary> /// Options for converting a DateTime to a string. /// </summary> [CreateAssetMenu(menuName = "Unity Weld/Adapter options/DateTime to string adapter")] [HelpURL("https://github.com/Real-Serious-Games/Unity-Weld")] public class DateTimeToStringAdapterOptions : AdapterOptions { /// <summary> /// Format passed in to the DateTime.ToString method. /// See this page for details on usage: https://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx /// </summary> public string Format; } }
36.333333
113
0.64526
[ "MIT" ]
MonarchSolutions/Unity-Weld
UnityWeld/Binding/Adapters/DateTimeToStringAdapterOptions.cs
656
C#
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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 Gallio.Model { /// <summary> /// A list of standard test kind names provided by Gallio. /// </summary> /// <remarks> /// <para> /// The test kind has no effect on the semantics of the test runner but it allows tests to /// be classified so that a user interface can provide appropriate icons, descriptions, /// decorations and affordances for registered test kinds. /// </para> /// <para> /// To create your own custom test kinds for your test framework, register a /// <see cref="ITestKind" /> component in your plugin metadata with a unique name. /// </para> /// </remarks> /// <seealso cref="ITestKind"/> /// <seealso cref="TestKindTraits"/> /// <seealso cref="MetadataKeys.TestKind"/> public static class TestKinds { /// <summary> /// The test represents the root of the test tree. /// </summary> public const string Root = "Root"; /// <summary> /// The test represents the tests contained in a single test file. /// </summary> /// <remarks> /// <para> /// A file should have an associated <see cref="MetadataKeys.Framework" /> metadata. /// </para> /// </remarks> public const string File = "File"; /// <summary> /// The test represents the tests contained in a single test assembly. /// </summary> /// <remarks> /// <para> /// An assembly should have an associated <see cref="MetadataKeys.Framework" /> metadata. /// </para> /// </remarks> public const string Assembly = "Assembly"; /// <summary> /// The test represents the tests contained in a single test namespace. /// </summary> public const string Namespace = "Namespace"; /// <summary> /// The test represents a grouping of tests for descriptive purposes. /// </summary> public const string Group = "Group"; /// <summary> /// The test represents a test suite. /// </summary> public const string Suite = "Suite"; /// <summary> /// The test represents a test fixture. /// </summary> public const string Fixture = "Fixture"; /// <summary> /// The test represents a test case. /// </summary> public const string Test = "Test"; /// <summary> /// The test is a placeholder for an unsupported test file or element. /// </summary> public const string Unsupported = "Unsupported"; } }
35.290323
97
0.602377
[ "ECL-2.0", "Apache-2.0" ]
citizenmatt/gallio
src/Gallio/Gallio/Model/TestKinds.cs
3,282
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using static Microsoft.Build.Framework.MessageImportance; namespace MSBuild.CompactJsonResources { public class CompactJsonTask : Task { public ITaskItem[] JsonFiles { get; set; } [Required] public string TempOutputPath { get; set; } public string LogTag { get; set; } [Output] public ITaskItem[] OutputJsonFiles { get; set; } public override bool Execute() { LogMessage($"{nameof(TempOutputPath)}: {TempOutputPath}", High); try { if (JsonFiles?.Length > 0) OutputJsonFiles = ParseAndCopyFiles(JsonFiles)?.ToArray(); else LogMessage($"{nameof(JsonFiles)} is null or empty"); } catch (Exception ex) { Log.LogErrorFromException(ex, true); return false; } return true; } IEnumerable<ITaskItem> ParseAndCopyFiles(ITaskItem[] items) { foreach(var item in items) { LogMessage(item.ToString("Original File"), Low); var json = new JsonFile(item, TempOutputPath); LogMessage($"Temp File Full Path: {json.TempFullPath}"); var outputItem = json.WriteCompactTempFile(); LogMessage(outputItem.ToString("Temp File"), Low); yield return outputItem; } } void LogMessage(string mess, MessageImportance importance = Normal) => Log.LogMessage(importance, $"{LogTag}{mess}"); } }
30.20339
78
0.554994
[ "MIT" ]
dimonovdd/MSBuild.CompactJsonResources
src/CompactJson/CompactJsonTask.cs
1,784
C#
using System.Collections.Generic; namespace Ductus.FluentDocker.Model.Compose { /// <summary> /// Mount host paths or named volumes, specified as sub-options to a service. /// </summary> /// <remarks> /// You can mount a host path as part of a definition for a single service, and there is no need to define it in the top /// level volumes key. But, if you want to reuse a volume across multiple services, then define a named volume in the /// top-level volumes key. Use named volumes with services, swarms, and stack files. Note: The top-level volumes key /// defines a named volume and references it from each service’s volumes list. This replaces volumes_from in earlier /// versions of the Compose file format. See Use volumes and Volume Plugins for general information on volumes. Note: The /// long syntax is new in v3.2 /// </remarks> public sealed class LongServiceVolumeDefinition : IServiceVolumeDefinition { /// <summary> /// the source of the mount, a path on the host for a bind mount, or the name of a volume defined in the top-level /// volumes key. Not applicable for a tmpfs mount. /// </summary> public string Source { get; set; } /// <summary> /// the path in the container where the volume is mounted. /// </summary> public string Target { get; set; } /// <summary> /// The mount type. /// </summary> public VolumeType Type { get; set; } /// <summary> /// flag to set the volume as read-only. /// </summary> public bool IsReadOnly { get; set; } /// <summary> /// Options if any. /// </summary> /// <remarks> /// * bind-> propagation: the propagation mode used for the bind. /// * volume -> nocopy: flag to disable copying of data from a container when a volume is created. /// * tmpfs -> size: the size for the tmpfs mount in bytes. /// </remarks> public IDictionary<string, string> Options { get; set; } = new Dictionary<string, string>(); } }
41.489796
125
0.653222
[ "Apache-2.0" ]
AntoineGa/FluentDocker
Ductus.FluentDocker/Model/Compose/LongServiceVolumeDefinition.cs
2,035
C#
using System; using System.Collections; namespace Org.BouncyCastle.Crypto.Tls { public class CertificateRequest { private ClientCertificateType[] certificateTypes; private IList certificateAuthorities; public CertificateRequest(ClientCertificateType[] certificateTypes, IList certificateAuthorities) { this.certificateTypes = certificateTypes; this.certificateAuthorities = certificateAuthorities; } public ClientCertificateType[] CertificateTypes { get { return certificateTypes; } } /// <returns>A <see cref="IList"/> of X509Name</returns> public IList CertificateAuthorities { get { return certificateAuthorities; } } } }
23.821429
99
0.770615
[ "MIT" ]
SchmooseSA/Schmoose-BouncyCastle
Crypto/crypto/tls/CertificateRequest.cs
667
C#
using IdentityModel.Client; using Microsoft.AspNetCore.SignalR.Client; namespace BlazorBoilerplate.IdentityServer.Test3 { class Program { static string _authority = "http://localhost:53414"; private static async Task Main() { // discover endpoints from metadata var client = new HttpClient(); var disco = await client.GetDiscoveryDocumentAsync(_authority); if (disco.IsError) { Console.WriteLine(disco.Error); return; } // request token var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = disco.TokenEndpoint, ClientId = "clientToDo", ClientSecret = "secret", Scope = "LocalAPI" }); if (tokenResponse.IsError) { Console.WriteLine(tokenResponse.Error); return; } Console.WriteLine(tokenResponse.Json); Console.WriteLine("\n\n"); var connection = new HubConnectionBuilder() .WithUrl(new Uri($"{_authority}/chathub"), options => { options.AccessTokenProvider = () => Task.FromResult(tokenResponse.AccessToken); }) .WithAutomaticReconnect() .Build(); try { connection.On<int, string, string>("ReceiveMessage", (id, username, message) => { Console.WriteLine($"ReceiveMessage: id:{id} username:{username} message:{message}"); }); await connection.StartAsync(); await connection.InvokeAsync("SendMessage", "Ciao!"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); if (connection.State != HubConnectionState.Disconnected) { await connection.StopAsync(); } } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } } }
30.621622
113
0.505737
[ "MIT" ]
IamFlashUser/blazorboilerplate
src/Tests/BlazorBoilerplate.IdentityServer.Test3/Program.cs
2,268
C#
using FuncSharp; using Mews.Fiscalizations.Core.Model; using System; namespace Mews.Fiscalizations.Hungary.Models { public sealed class ExchangeRate { private static readonly int MaxDecimalPlaces = 6; private ExchangeRate(decimal value) { Value = value; } public decimal Value { get; } public static ITry<ExchangeRate, Error> Create(decimal value) { return DecimalValidations.InRange(value, 0, 100_000_000, minIsAllowed: false, maxIsAllowed: false).FlatMap(v => { var validExchangeRate = DecimalValidations.MaxDecimalPlaces(v, MaxDecimalPlaces); return validExchangeRate.Map(r => new ExchangeRate(r)); }); } internal static ITry<ExchangeRate, Error> Rounded(decimal value) { var roundedValue = Decimal.Round(value, MaxDecimalPlaces); return Create(roundedValue); } } }
29.636364
123
0.623722
[ "MIT" ]
MewsSystems/fiscalizations
src/Hungary/Mews.Fiscalizations.Hungary/Models/Types/ExchangeRate.cs
980
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("windowHelp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("windowHelp")] [assembly: AssemblyCopyright("Copyright © Microsoft 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 会使此程序集中的类型 //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] //若要开始生成可本地化的应用程序,请设置 //.csproj 文件中的 <UICulture>CultureYouAreCodingWith</UICulture> //例如,如果您在源文件中使用的是美国英语, //使用的是美国英语,请将 <UICulture> 设置为 en-US。 然后取消 //对以下 NeutralResourceLanguage 特性的注释。 更新 //以下行中的“en-US”以匹配项目文件中的 UICulture 设置。 //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //主题特定资源词典所处位置 //(未在页面中找到资源时使用, //或应用程序资源字典中找到时使用) ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置 //(未在页面中找到资源时使用, //、应用程序或任何主题专用资源字典中找到时使用) )] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号 // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
28.892857
91
0.669345
[ "MIT" ]
linchenrr/kakaTools
windowHelp/windowHelp/Properties/AssemblyInfo.cs
2,277
C#
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Resources; using System.Reflection; namespace Mediachase.Ibn.WebAsp.Pages { public partial class TariffRequests : System.Web.UI.Page { protected ResourceManager LocRM = new ResourceManager("Mediachase.Ibn.WebAsp.App_GlobalResources.Resources.Tariffs", Assembly.GetExecutingAssembly()); protected void Page_Load(object sender, EventArgs e) { pageTemplate.Title = LocRM.GetString("TariffRequests"); } } }
27.6
152
0.789855
[ "MIT" ]
InstantBusinessNetwork/IBN
Source/Server/WebAsp/Pages/TariffRequests.aspx.cs
554
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="FastObservableCollection.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.Collections { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using IoC; using Services; /// <summary> /// Fast implementation of <see cref="ObservableCollection{T}"/> where the change notifications /// can be suspended. /// </summary> /// <typeparam name="T">Type of the elements contained by this collection.</typeparam> #if NET [Serializable] #endif public class FastObservableCollection<T> : ObservableCollection<T> { #region Constants private static readonly IDispatcherService _dispatcherService; #endregion #region Fields private bool _suspendChangeNotifications; #endregion #region Constructors /// <summary> /// Initializes static members of the <see cref="FastObservableCollection{T}"/> class. /// </summary> static FastObservableCollection() { var dependencyResolver = IoCConfiguration.DefaultDependencyResolver; _dispatcherService = dependencyResolver.Resolve<IDispatcherService>(); } /// <summary> /// Initializes a new instance of the <see cref="FastObservableCollection{T}" /> class. /// </summary> public FastObservableCollection() { AutomaticallyDispatchChangeNotifications = true; } /// <summary> /// Initializes a new instance of the <see cref="FastObservableCollection{T}" /> class. /// </summary> /// <param name="collection">The collection.</param> public FastObservableCollection(IEnumerable<T> collection) : this() { AddItems(collection); } #endregion #region Properties /// <summary> /// Gets or sets a value indicating whether change to the collection is made when /// its notifications are suspended. /// </summary> /// <value><c>true</c> if this instance is has been changed while notifications are /// suspended; otherwise, <c>false</c>.</value> public bool IsDirty { get; protected set; } /// <summary> /// Gets a value indicating whether change notifications are suspended. /// </summary> /// <value> /// <c>True</c> if notifications are suspended, otherwise, <c>false</c>. /// </value> public bool NotificationsSuspended { get { return _suspendChangeNotifications; } } /// <summary> /// Gets or sets a value indicating whether events should automatically be dispatched to the UI thread. /// </summary> /// <value><c>true</c> if events should automatically be dispatched to the UI thread; otherwise, <c>false</c>.</value> public bool AutomaticallyDispatchChangeNotifications { get; set; } #endregion #region Methods /// <summary> /// Inserts the elements of the specified collection at the specified index. /// </summary> /// <param name="collection">The collection.</param> /// <param name="index">The start index.</param> /// <exception cref="ArgumentNullException">The <paramref name="collection"/> is <c>null</c>.</exception> public virtual void InsertItems(IEnumerable<T> collection, int index) { Argument.IsNotNull("collection", collection); using (SuspendChangeNotifications()) { foreach (var item in collection) { Insert(index++, item); } } } /// <summary> /// Inserts the elements of the specified collection at the specified index. /// </summary> /// <param name="collection">The collection.</param> /// <param name="index">The start index.</param> /// <exception cref="ArgumentNullException">The <paramref name="collection"/> is <c>null</c>.</exception> public virtual void InsertItems(IEnumerable collection, int index) { Argument.IsNotNull("collection", collection); using (SuspendChangeNotifications()) { foreach (var item in collection) { ((IList)this).Insert(index++, item); } } } /// <summary> /// Raises <see cref="E:System.Collections.Specialized.INotifyCollectionChanged.CollectionChanged" /> with /// <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Reset" /> changed action. /// </summary> public void Reset() { NotifyChanges(); } /// <summary> /// Adds the specified items to the collection without causing a change notification for all items. /// <para /> /// This method will raise a change notification at the end. /// </summary> /// <param name="collection">The collection.</param> /// <exception cref="ArgumentNullException">The <paramref name="collection"/> is <c>null</c>.</exception> public void AddItems(IEnumerable<T> collection) { Argument.IsNotNull("collection", collection); using (SuspendChangeNotifications()) { foreach (var item in collection) { Add(item); } } } /// <summary> /// Adds the specified items to the collection without causing a change notification for all items. /// <para /> /// This method will raise a change notification at the end. /// </summary> /// <param name="collection">The collection.</param> /// <exception cref="ArgumentNullException">The <paramref name="collection"/> is <c>null</c>.</exception> public void AddItems(IEnumerable collection) { Argument.IsNotNull("collection", collection); using (SuspendChangeNotifications()) { foreach (var item in collection) { ((IList) this).Add(item); } } } /// <summary> /// Removes the specified items from the collection without causing a change notification for all items. /// <para /> /// This method will raise a change notification at the end. /// </summary> /// <param name="collection">The collection.</param> /// <exception cref="ArgumentNullException">The <paramref name="collection"/> is <c>null</c>.</exception> public void RemoveItems(IEnumerable<T> collection) { Argument.IsNotNull("collection", collection); using (SuspendChangeNotifications()) { foreach (var item in collection) { Remove(item); } } } /// <summary> /// Removes the specified items from the collection without causing a change notification for all items. /// <para /> /// This method will raise a change notification at the end. /// </summary> /// <param name="collection">The collection.</param> /// <exception cref="ArgumentNullException">The <paramref name="collection"/> is <c>null</c>.</exception> public void RemoveItems(IEnumerable collection) { Argument.IsNotNull("collection", collection); using (SuspendChangeNotifications()) { foreach (var item in collection) { ((IList) this).Remove(item); } } } /// <summary> /// Suspends the change notifications until the returned <see cref="IDisposable"/> is disposed. /// <example> /// <code> /// <![CDATA[ /// var fastCollection = new FastObservableCollection<int>(); /// using (fastCollection.SuspendChangeNotificaftions()) /// { /// // Adding or removing events inside here will not raise events /// fastCollection.Add(1); /// fastCollection.Add(2); /// fastCollection.Add(3); /// /// fastCollection.Remove(3); /// fastCollection.Remove(2); /// fastCollection.Remove(1); /// } /// ]]> /// </code> /// </example> /// </summary> /// <returns>IDisposable.</returns> public IDisposable SuspendChangeNotifications() { return new DisposableToken<FastObservableCollection<T>>(this, x => { x.Instance._suspendChangeNotifications = true; }, x => { x.Instance._suspendChangeNotifications = (bool) x.Tag; if (x.Instance.IsDirty && !x.Instance._suspendChangeNotifications) { x.Instance.IsDirty = false; x.Instance.NotifyChanges(); } }, _suspendChangeNotifications); } /// <summary> /// Notifies external classes of property changes. /// </summary> protected void NotifyChanges() { OnPropertyChanged(new PropertyChangedEventArgs("Count")); OnPropertyChanged(new PropertyChangedEventArgs("Item[]")); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } /// <summary> /// Raises the <see cref="ObservableCollection{T}.CollectionChanged" /> event, but also makes sure the event is dispatched to the UI thread. /// </summary> /// <param name="e">The <see cref="NotifyCollectionChangedEventArgs" /> instance containing the event data.</param> protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { if (!_suspendChangeNotifications) { if (AutomaticallyDispatchChangeNotifications) { _dispatcherService.BeginInvokeIfRequired(() => base.OnCollectionChanged(e)); } else { base.OnCollectionChanged(e); } return; } IsDirty = true; } /// <summary> /// Raises the <c>ObservableCollection{T}.PropertyChanged</c> event, but also makes sure the event is dispatched to the UI thread. /// </summary> /// <param name="e">The <see cref="PropertyChangedEventArgs" /> instance containing the event data.</param> protected override void OnPropertyChanged(PropertyChangedEventArgs e) { if (!_suspendChangeNotifications) { if (AutomaticallyDispatchChangeNotifications) { _dispatcherService.BeginInvokeIfRequired(() => base.OnPropertyChanged(e)); } else { base.OnPropertyChanged(e); } } } #endregion } }
37.401254
148
0.545051
[ "MIT" ]
crazeydave/Catel
src/Catel.MVVM/Catel.MVVM.Shared/Collections/FastObservableCollection.cs
11,933
C#
namespace Azi.Cloud.DokanNet { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Common; using Newtonsoft.Json; using Tools; using FileInformation = global::DokanNet.FileInformation; public delegate Task StatisticUpdateDelegate(IHttpCloud cloud, StatisticUpdateReason reason, AStatisticFileInfo info); public enum StatisticUpdateReason { UploadAdded, UploadFinished, DownloadAdded, DownloadFinished, DownloadFailed, UploadFailed, Progress, UploadAborted, UploadState } public class FSProvider : IDisposable, IFSProvider { private readonly IHttpCloud cloud; private readonly HashSet<string> excludedFiles = new HashSet<string> { "desktop.ini", "folder.jpg", "folder.gif" }; private readonly ItemsTreeCache itemsTreeCache = new ItemsTreeCache(); private readonly StatisticUpdateDelegate onStatisticsUpdated; private readonly UploadService uploadService; private string cachePath; private bool disposedValue; // To detect redundant calls public FSProvider(IHttpCloud cloud, StatisticUpdateDelegate statisticUpdate) { onStatisticsUpdated = statisticUpdate; this.cloud = cloud; SmallFilesCache = new SmallFilesCache(cloud) { OnDownloadStarted = info => { onStatisticsUpdated(cloud, StatisticUpdateReason.DownloadAdded, new DownloadStatisticInfo(info)); }, OnDownloaded = info => { onStatisticsUpdated( cloud, StatisticUpdateReason.DownloadFinished, new DownloadStatisticInfo(info)); }, OnDownloadFailed = info => { onStatisticsUpdated(cloud, StatisticUpdateReason.DownloadFailed, new DownloadStatisticInfo(info)); } }; uploadService = new UploadService(2, cloud) { OnUploadFailed = UploadFailed, OnUploadFinished = UploadFinished, OnUploadProgress = async (item, done) => { await onStatisticsUpdated( cloud, StatisticUpdateReason.Progress, new UploadStatisticInfo(item) { Done = done }); }, OnUploadAdded = async item => { itemsTreeCache.Add(item.ToFSItem()); await onStatisticsUpdated(cloud, StatisticUpdateReason.UploadAdded, new UploadStatisticInfo(item)); }, OnUploadState = async (item, state) => { await onStatisticsUpdated( cloud, StatisticUpdateReason.UploadState, new UploadStatisticInfo(item) { State = state }); } }; uploadService.Start(); } public string CachePath { get { return cachePath; } set { var val = Path.GetFullPath(value); if (cachePath == val) { return; } if (cachePath != null) { SmallFilesCache.ClearAllInBackground(); } cachePath = val; SmallFilesCache.CachePath = val; uploadService.CachePath = val; } } public bool CheckFileHash { get { return uploadService.CheckFileHash; } set { uploadService.CheckFileHash = value; } } public string FileSystemName => "Cloud Drive"; public SmallFilesCache SmallFilesCache { get; } public long SmallFilesCacheSize { get { return SmallFilesCache.CacheSize; } set { SmallFilesCache.CacheSize = value; } } public long SmallFileSizeLimit { get; set; } = 20 * 1024 * 1024; public string VolumeName { get; set; } public async Task BuildItemInfo(FSItem item) { var info = await cloud.Nodes.GetNodeExtended(item.Id); var str = JsonConvert.SerializeObject(info); item.Info = Encoding.UTF8.GetBytes(str); } public void CancelUpload(string id) { uploadService.CancelUpload(id); } public async Task ClearSmallFilesCache() { await SmallFilesCache.ClearAllInBackground(); } public async Task CreateDir(string filePath) { var dir = Path.GetDirectoryName(filePath); var dirNode = await FetchNode(dir); var name = Path.GetFileName(filePath); var node = await cloud.Nodes.CreateFolder(dirNode.Id, name); itemsTreeCache.Add(node.SetParentPath(Path.GetDirectoryName(filePath)).Build()); } public async Task DeleteDir(string filePath) { var item = await FetchNode(filePath); if (item != null) { if (!item.IsDir) { throw new InvalidOperationException("Not dir"); } await DeleteItem(filePath, item); itemsTreeCache.DeleteDir(filePath); } else { throw new FileNotFoundException(); } } public async Task DeleteFile(string filePath) { var item = await FetchNode(filePath); if (item != null) { if (item.IsDir) { throw new InvalidOperationException("Not file"); } await DeleteItem(filePath, item); itemsTreeCache.DeleteFile(filePath); } else { throw new FileNotFoundException(); } try { SmallFilesCache.Delete(item); } catch (FileNotFoundException) { Log.Trace("Skip, File is not in SmallFilesCache"); } } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); // TODO: uncomment the following line if the finalizer is overridden above. // GC.SuppressFinalize(this); } public async Task<bool> Exists(string filePath) { return await FetchNode(filePath) != null; } public async Task<FSItem> FetchNode(string itemPath) { if (itemPath == "\\" || itemPath == string.Empty) { return (await cloud.Nodes.GetRoot()).BuildRoot(); } if (!itemPath.StartsWith("\\")) { itemPath = "\\" + itemPath; } if (excludedFiles.Contains(Path.GetFileName(itemPath))) { return null; } var cached = itemsTreeCache.GetItem(itemPath); if (cached != null) { if (cached.NotExistingDummy) { // Log.Warn("NonExisting path from cache: " + itemPath); return null; } return cached; } var folders = new LinkedList<string>(); var curpath = itemPath; FSItem item = null; do { folders.AddFirst(Path.GetFileName(curpath)); curpath = Path.GetDirectoryName(curpath); if (curpath == "\\" || string.IsNullOrEmpty(curpath)) { break; } item = itemsTreeCache.GetItem(curpath); } while (item == null); if (item == null) { item = (await cloud.Nodes.GetRoot()).BuildRoot(); } if (curpath == "\\") { curpath = string.Empty; } foreach (var name in folders) { var newpath = curpath + "\\" + name; var newnode = await cloud.Nodes.GetChild(item.Id, name); if (newnode == null) { itemsTreeCache.AddItemOnly(FSItem.MakeNotExistingDummy(newpath)); // Log.Error("NonExisting path from server: " + itemPath); return null; } item = newnode.SetParentPath(curpath).Build(); itemsTreeCache.Add(item); curpath = newpath; } return item; } public async Task<long> GetAvailableFreeSpace() => await cloud.GetAvailableFreeSpace(); public async Task<IList<FSItem>> GetDirItems(string folderPath) { if (!folderPath.StartsWith("\\")) { folderPath = "\\" + folderPath; } var cached = itemsTreeCache.GetDir(folderPath); if (cached != null) { // Log.Warn("Got cached dir:\r\n " + string.Join("\r\n ", cached)); return (await Task.WhenAll(cached.Select(FetchNode))).Where(i => i != null).ToList(); } var folderNode = await FetchNode(folderPath); var nodes = await cloud.Nodes.GetChildren(folderNode?.Id); var items = new List<FSItem>(nodes.Count); var curdir = folderPath; if (curdir == "\\") { curdir = string.Empty; } foreach (var node in nodes) { items.Add(node.SetParentPath(curdir).Build()); } // Log.Warn("Got real dir:\r\n " + string.Join("\r\n ", items.Select(i => i.Path))); itemsTreeCache.AddDirItems(folderPath, items); return items; } public async Task<byte[]> GetExtendedInfo(string[] streamNameGroups, FSItem item) { switch (streamNameGroups[1]) { case CloudDokanNetAssetInfo.StreamNameShareReadOnly: return Encoding.UTF8.GetBytes(await cloud.Nodes.ShareNode(item.Id, NodeShareType.ReadOnly)); case CloudDokanNetAssetInfo.StreamNameShareReadWrite: return Encoding.UTF8.GetBytes(await cloud.Nodes.ShareNode(item.Id, NodeShareType.ReadWrite)); default: return new byte[0]; } } public async Task<FileInformation?> GetItemInfo(string fileName) { var item = await FetchNode(fileName); if (item == null) { return null; } var result = new FileInformation { Length = item.Length, FileName = item.Name, Attributes = item.IsDir ? FileAttributes.Directory : FileAttributes.Normal, LastAccessTime = item.LastAccessTime, LastWriteTime = item.LastWriteTime, CreationTime = item.CreationTime }; var info = SmallFilesCache.GetItemInfo(item); if (info != null) { result.LastAccessTime = item.LastAccessTime > info.LastAccessTimeUtc ? item.LastAccessTime : info.LastAccessTimeUtc; result.LastWriteTime = item.LastWriteTime > info.LastWriteTimeUtc ? item.LastWriteTime : info.LastWriteTimeUtc; } return result; } public async Task<long> GetTotalFreeSpace() => await cloud.GetTotalFreeSpace(); public async Task<long> GetTotalSize() => await cloud.GetTotalSize(); public async Task<long> GetTotalUsedSpace() => await cloud.GetTotalUsedSpace(); public async Task MoveFile(string oldPath, string newPath, bool replace) { if (oldPath == newPath) { return; } Log.Trace($"Move: {oldPath} to {newPath} replace:{replace}"); var oldDir = Path.GetDirectoryName(oldPath); var oldName = Path.GetFileName(oldPath); var newDir = Path.GetDirectoryName(newPath); var newName = Path.GetFileName(newPath); if (oldDir == null) { throw new InvalidOperationException($"oldDir is null for '{oldPath}'"); } if (newName == null) { throw new InvalidOperationException($"newName is null for '{newPath}'"); } var item = await FetchNode(oldPath); await WaitForReal(item, 25000); if (oldName != newName) { if (item.Length > 0 || item.IsDir) { item = (await cloud.Nodes.Rename(item.Id, newName)).SetParentPath(oldDir).Build(); } else { item = new FSItem(item) { Path = Path.Combine(oldDir, newName) }; } if (item == null) { throw new InvalidOperationException("Can not rename"); } } if (oldDir != newDir) { var oldDirNodeTask = FetchNode(oldDir); var newDirNodeTask = FetchNode(newDir); Task.WaitAll(oldDirNodeTask, newDirNodeTask); if (item.Length > 0 || item.IsDir) { item = cloud.Nodes.Move(item.Id, (await oldDirNodeTask).Id, (await newDirNodeTask).Id).Result.SetParentPath(newDir).Build(); if (item == null) { throw new InvalidOperationException("Can not move"); } } else { item = new FSItem(item) { Path = newPath }; } } if (item.IsDir) { itemsTreeCache.MoveDir(oldPath, item); } else { itemsTreeCache.MoveFile(oldPath, item); } } public async Task<IBlockStream> OpenFile(string filePath, FileMode mode, FileAccess fileAccess, FileShare share, FileOptions options) { var item = await FetchNode(filePath); if (fileAccess == FileAccess.Read) { if (item == null) { return null; } Log.Trace($"Opening {filePath} for Read"); if (!item.IsUploading && item.Length < SmallFileSizeLimit) { return SmallFilesCache.OpenReadWithDownload(item); } var result = SmallFilesCache.OpenReadCachedOnly(item); if (result != null) { return result; } await WaitForReal(item, 25000); await onStatisticsUpdated(cloud, StatisticUpdateReason.DownloadAdded, new DownloadStatisticInfo(item)); var buffered = new BufferedHttpCloudBlockReader(item, cloud) { OnClose = async () => { await onStatisticsUpdated( cloud, StatisticUpdateReason.DownloadFinished, new DownloadStatisticInfo(item)); } }; return buffered; } if (item == null) { Log.Trace($"Creating {filePath} as New because mode:{mode} and {((item == null) ? "item is null" : "length is 0")}"); var dir = Path.GetDirectoryName(filePath); var dirItem = await FetchNode(dir); if (dirItem == null) { throw new FileNotFoundException($"Parent folder not found: {dir}"); } //item = FSItem.MakeUploading(filePath, Guid.NewGuid().ToString(), dirItem.Id, 0); //var file = uploadService.OpenNew(item); //SmallFilesCache.AddAsLink(item, file.UploadCachePath); //itemsTreeCache.Add(item); //return file; return new NewFileBlockWriter(null, string.Empty); } await WaitForReal(item, 25000); if (mode == FileMode.Create || mode == FileMode.Truncate) { Log.Trace($"Opening {filePath} as Truncate because mode:{mode} and length {item.Length}"); //item.Length = 0; //SmallFilesCache.Delete(item); //item.MakeUploading(); //var file = uploadService.OpenTruncate(item); //return file; return new NewFileBlockWriter(null, string.Empty); } if (mode == FileMode.Open || mode == FileMode.Append || mode == FileMode.OpenOrCreate) { Log.Trace($"Opening {filePath} as ReadWrite because mode:{mode} and length {item.Length}"); if (item.Length < SmallFileSizeLimit) { var file = SmallFilesCache.OpenReadWrite(item); file.OnChangedAndClosed = async (it, path) => { it.LastWriteTime = DateTime.UtcNow; if (!it.IsUploading) { it.MakeUploading(); var olditemPath = Path.Combine(SmallFilesCache.CachePath, item.Id); var newitemPath = Path.Combine(uploadService.CachePath, item.Id); if (File.Exists(newitemPath)) { File.Delete(newitemPath); } try { File.Move(olditemPath, newitemPath); SmallFilesCache.AddExisting(it); } catch (Exception e) { Log.Error(e); } } await uploadService.AddOverwrite(it); }; return file; } Log.Warn("File is too big for ReadWrite: " + filePath); } return null; } public ByteArrayBlockWriter OpenUploadHere(FSItem item) { Log.Trace("Upload from Shell"); var result = new ByteArrayBlockWriter(); result.OnClose = () => { try { var bytes = result.Content.ToArray(); var str = Encoding.UTF8.GetString(bytes); var list = JsonConvert.DeserializeObject<CloudDokanNetUploadHereInfo>(str); Task.Factory.StartNew(async () => await MakeUploads(item, list.Files), TaskCreationOptions.LongRunning); return Task.FromResult(0); } catch (Exception ex) { Log.Error("UploadHere error", ex); throw; } }; return result; } public void StopUpload() { uploadService.Stop(); } protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { itemsTreeCache.Dispose(); uploadService.Dispose(); } disposedValue = true; } } private async Task<FSItem> CheckCreateFolder(FSItem parent, string name) { var node = await cloud.Nodes.GetChild(parent.Id, name); if (node != null) { return node.SetParentPath(parent.Path).Build(); } var result = (await cloud.Nodes.CreateFolder(parent.Id, name)).SetParentPath(parent.Path).Build(); itemsTreeCache.Add(result); return result; } private async Task DeleteItem(string filePath, FSItem item) { try { if (item.ParentIds.Count == 1) { if (item.IsUploading) { uploadService.CancelUpload(item.Id); } else { await cloud.Nodes.Trash(item.Id); } } else { var dir = Path.GetDirectoryName(filePath); var dirItem = await FetchNode(dir); await cloud.Nodes.Remove(dirItem.Id, item.Id); } } catch (AggregateException ex) { throw ex.Flatten(); } catch (CloudException ex) when (ex.Error == HttpStatusCode.NotFound || ex.Error == HttpStatusCode.Conflict) { Log.Warn(ex.Error.ToString()); } } private async Task MakeUploads(FSItem dest, IEnumerable<string> files) { try { var currentfiles = new Queue<UploadTaskItem>(files.Select(f => new UploadTaskItem { Parent = dest, File = f })); while (currentfiles.Count > 0) { var item = currentfiles.Dequeue(); if (Directory.Exists(item.File)) { var created = await CheckCreateFolder(item.Parent, Path.GetFileName(item.File)); if (created != null) { foreach (var file in Directory.EnumerateFileSystemEntries(item.File)) { currentfiles.Enqueue(new UploadTaskItem { Parent = created, File = file }); } } } else { try { await uploadService.AddUpload(item.Parent, item.File); } catch (Exception e) { Log.Error(e); } } } } catch (Exception ex) { Log.Error(ex); } } private async Task UploadFailed(UploadInfo uploaditem, FailReason reason, string message) { switch (reason) { case FailReason.FileNotFound: case FailReason.Conflict: case FailReason.ContentIdMismatch: case FailReason.NoFolderNode: await onStatisticsUpdated(cloud, StatisticUpdateReason.UploadAborted, new UploadStatisticInfo(uploaditem, message)); return; case FailReason.Cancelled: if (!uploaditem.Overwrite) { itemsTreeCache.DeleteFile(uploaditem.Path); } await onStatisticsUpdated(cloud, StatisticUpdateReason.UploadFinished, new UploadStatisticInfo(uploaditem)); return; case FailReason.NoResultNode: break; case FailReason.NoOverwriteNode: break; case FailReason.Unexpected: break; default: throw new ArgumentOutOfRangeException(nameof(reason), reason, null); } await onStatisticsUpdated(cloud, StatisticUpdateReason.UploadFailed, new UploadStatisticInfo(uploaditem, message)); itemsTreeCache.DeleteFile(uploaditem.Path); } private Task UploadFinished(UploadInfo item, FSItem.Builder node) { onStatisticsUpdated(cloud, StatisticUpdateReason.UploadFinished, new UploadStatisticInfo(item)); var newitem = node.SetParentPath(Path.GetDirectoryName(item.Path)).Build(); itemsTreeCache.Update(newitem); return Task.FromResult(0); } private async Task WaitForReal(FSItem item, int timeout) { var timeouttime = DateTime.UtcNow.AddMilliseconds(timeout); while (item.IsUploading) { if (DateTime.UtcNow > timeouttime) { throw new TimeoutException(); } await Task.Delay(1000); item = await FetchNode(item.Path); } } private class UploadTaskItem { public string File { get; set; } public FSItem Parent { get; set; } } } }
32.952736
144
0.470257
[ "MIT" ]
nguyendotuong/sse
amazon-clouddrive-dokan/FSProvider.cs
26,496
C#
// This file was automatically generated and may be regenerated at any // time. To ensure any changes are retained, modify the tool with any segment/component/group/field name // or type changes. namespace Machete.HL7Schema.V26 { using HL7; /// <summary> /// PPV_PCA_ORDER (Group) - /// </summary> public interface PPV_PCA_ORDER : HL7V26Layout { /// <summary> /// ORC /// </summary> Segment<ORC> ORC { get; } /// <summary> /// ORDER_DETAIL /// </summary> Layout<PPV_PCA_ORDER_DETAIL> OrderDetail { get; } } }
25.541667
105
0.587276
[ "Apache-2.0" ]
AreebaAroosh/Machete
src/Machete.HL7Schema/Generated/V26/Groups/PPV_PCA_ORDER.cs
613
C#
// Copyright (c) 2016, SolidCP // SolidCP is distributed under the Creative Commons Share-alike license // // SolidCP is a fork of WebsitePanel: // Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using SolidCP.EnterpriseServer; using SolidCP.Providers.Virtualization; using System.Web; using System; namespace SolidCP.Portal { // TODO: Move this extension to a separate file later. public static class VirtualMachinesExtensions { #region Privates with specific purposes (eq. caching, usability, performance and etc) /// <summary> /// This method supports the Portal internal infrastructure and is not intended to be used directly from your code. Gets a cached copy of virtual machine object of the specified type or retrieves it for the first time and then caches it. /// </summary> /// <typeparam name="T">Type of virtual machine to be retrieved (possible types are VirtualMachine|VMInfo)</typeparam> /// <param name="cacheIdentityKey">Virtual machine item id</param> /// <param name="getVmFunc">Function to retrieve the virtual machine data from Enterprise Server</param> /// <returns>An instance of the specified virtual machine</returns> internal static T GetCachedVirtualMachine<T>(object cacheIdentityKey, Func<T> getVmFunc) { // TODO: Make this method private when all dependents will be consolidated in the extension. string cacheKey = "CachedVirtualMachine_" + cacheIdentityKey; if (HttpContext.Current.Items[cacheKey] != null) return (T)HttpContext.Current.Items[cacheKey]; // load virtual machine T virtualMachine = getVmFunc(); // place to cache if (virtualMachine != null) HttpContext.Current.Items[cacheKey] = virtualMachine; return virtualMachine; } #endregion #region Extension methods /// <summary> /// Gets a cached copy of virtual machine object of the specified type or retrieves it for the first time and then caches it. /// </summary> /// <param name="client"></param> /// <param name="itemId">Virtual machine id</param> /// <returns>An instance of the virtual machine speficied</returns> public static VMInfo GetCachedVirtualMachine(this esVirtualizationServerForPrivateCloud client, int itemId) { return GetCachedVirtualMachine<VMInfo>( itemId, () => ES.Services.VPSPC.GetVirtualMachineItem(itemId)); } #endregion } public class VirtualMachinesHelper { public static bool IsVirtualMachineManagementAllowed(int packageId) { bool manageAllowed = false; PackageContext cntx = PackagesHelper.GetCachedPackageContext(packageId); if (cntx.Quotas.ContainsKey(Quotas.VPS_MANAGING_ALLOWED)) manageAllowed = !cntx.Quotas[Quotas.VPS_MANAGING_ALLOWED].QuotaExhausted; if (PanelSecurity.EffectiveUser.Role == UserRole.Administrator) manageAllowed = true; else if (PanelSecurity.EffectiveUser.Role == UserRole.Reseller) { // check if the reseller is allowed to manage on its parent level PackageInfo package = ES.Services.Packages.GetPackage(PanelSecurity.PackageId); if (package.UserId != PanelSecurity.EffectiveUserId) { cntx = PackagesHelper.GetCachedPackageContext(package.ParentPackageId); if (cntx != null && cntx.Quotas.ContainsKey(Quotas.VPS_MANAGING_ALLOWED)) manageAllowed = !cntx.Quotas[Quotas.VPS_MANAGING_ALLOWED].QuotaExhausted; } } return manageAllowed; } // TODO: Move this method to the corresponding extension later. public static VirtualMachine GetCachedVirtualMachine(int itemId) { return VirtualMachinesExtensions.GetCachedVirtualMachine<VirtualMachine>( itemId, () => ES.Services.VPS.GetVirtualMachineItem(itemId)); } #region Virtual Machines VirtualMachineMetaItemsPaged vms; public VirtualMachineMetaItem[] GetVirtualMachines(int packageId, string filterColumn, string filterValue, string sortColumn, int maximumRows, int startRowIndex) { vms = ES.Services.VPS.GetVirtualMachines(packageId, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows, true); return vms.Items; } public int GetVirtualMachinesCount(int packageId, string filterColumn, string filterValue) { return vms.Count; } #endregion #region Package IP Addresses PackageIPAddressesPaged packageAddresses; public PackageIPAddress[] GetPackageIPAddresses(int packageId, IPAddressPool pool, string filterColumn, string filterValue, string sortColumn, int maximumRows, int startRowIndex) { packageAddresses = ES.Services.Servers.GetPackageIPAddresses(packageId, 0, pool, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows, true); return packageAddresses.Items; } public int GetPackageIPAddressesCount(int packageId, IPAddressPool pool, string filterColumn, string filterValue) { return packageAddresses.Count; } public PackageIPAddress[] GetPackageIPAddresses(int packageId, int orgId, IPAddressPool pool, string filterColumn, string filterValue, string sortColumn, int maximumRows, int startRowIndex) { packageAddresses = ES.Services.Servers.GetPackageIPAddresses(packageId, orgId, pool, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows, true); return packageAddresses.Items; } public int GetPackageIPAddressesCount(int packageId, int orgId, IPAddressPool pool, string filterColumn, string filterValue) { return packageAddresses.Count; } #endregion #region Package Private IP Addresses PrivateIPAddressesPaged privateAddresses; public PrivateIPAddress[] GetPackagePrivateIPAddresses(int packageId, string filterColumn, string filterValue, string sortColumn, int maximumRows, int startRowIndex) { privateAddresses = ES.Services.VPS.GetPackagePrivateIPAddressesPaged(packageId, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows); return privateAddresses.Items; } public int GetPackagePrivateIPAddressesCount(int packageId, string filterColumn, string filterValue) { return privateAddresses.Count; } #endregion } }
47.893258
245
0.679648
[ "BSD-3-Clause" ]
NAGeorge/SolidCP-fork
SolidCP/Sources/SolidCP.WebPortal/DesktopModules/SolidCP/Code/Helpers/VirtualMachinesHelper.cs
8,525
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Aws.WafRegional { /// <summary> /// Manages an association with WAF Regional Web ACL. /// /// &gt; **Note:** An Application Load Balancer can only be associated with one WAF Regional WebACL. /// /// ## Application Load Balancer Association Example /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var ipset = new Aws.WafRegional.IpSet("ipset", new Aws.WafRegional.IpSetArgs /// { /// IpSetDescriptors = /// { /// new Aws.WafRegional.Inputs.IpSetIpSetDescriptorArgs /// { /// Type = "IPV4", /// Value = "192.0.7.0/24", /// }, /// }, /// }); /// var fooRule = new Aws.WafRegional.Rule("fooRule", new Aws.WafRegional.RuleArgs /// { /// MetricName = "tfWAFRule", /// Predicates = /// { /// new Aws.WafRegional.Inputs.RulePredicateArgs /// { /// DataId = ipset.Id, /// Negated = false, /// Type = "IPMatch", /// }, /// }, /// }); /// var fooWebAcl = new Aws.WafRegional.WebAcl("fooWebAcl", new Aws.WafRegional.WebAclArgs /// { /// DefaultAction = new Aws.WafRegional.Inputs.WebAclDefaultActionArgs /// { /// Type = "ALLOW", /// }, /// MetricName = "foo", /// Rules = /// { /// new Aws.WafRegional.Inputs.WebAclRuleArgs /// { /// Action = new Aws.WafRegional.Inputs.WebAclRuleActionArgs /// { /// Type = "BLOCK", /// }, /// Priority = 1, /// RuleId = fooRule.Id, /// }, /// }, /// }); /// var fooVpc = new Aws.Ec2.Vpc("fooVpc", new Aws.Ec2.VpcArgs /// { /// CidrBlock = "10.1.0.0/16", /// }); /// var available = Output.Create(Aws.GetAvailabilityZones.InvokeAsync()); /// var fooSubnet = new Aws.Ec2.Subnet("fooSubnet", new Aws.Ec2.SubnetArgs /// { /// AvailabilityZone = available.Apply(available =&gt; available.Names[0]), /// CidrBlock = "10.1.1.0/24", /// VpcId = fooVpc.Id, /// }); /// var bar = new Aws.Ec2.Subnet("bar", new Aws.Ec2.SubnetArgs /// { /// AvailabilityZone = available.Apply(available =&gt; available.Names[1]), /// CidrBlock = "10.1.2.0/24", /// VpcId = fooVpc.Id, /// }); /// var fooLoadBalancer = new Aws.Alb.LoadBalancer("fooLoadBalancer", new Aws.Alb.LoadBalancerArgs /// { /// Internal = true, /// Subnets = /// { /// fooSubnet.Id, /// bar.Id, /// }, /// }); /// var fooWebAclAssociation = new Aws.WafRegional.WebAclAssociation("fooWebAclAssociation", new Aws.WafRegional.WebAclAssociationArgs /// { /// ResourceArn = fooLoadBalancer.Arn, /// WebAclId = fooWebAcl.Id, /// }); /// } /// /// } /// ``` /// /// ## API Gateway Association Example /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var ipset = new Aws.WafRegional.IpSet("ipset", new Aws.WafRegional.IpSetArgs /// { /// IpSetDescriptors = /// { /// new Aws.WafRegional.Inputs.IpSetIpSetDescriptorArgs /// { /// Type = "IPV4", /// Value = "192.0.7.0/24", /// }, /// }, /// }); /// var fooRule = new Aws.WafRegional.Rule("fooRule", new Aws.WafRegional.RuleArgs /// { /// MetricName = "tfWAFRule", /// Predicates = /// { /// new Aws.WafRegional.Inputs.RulePredicateArgs /// { /// DataId = ipset.Id, /// Negated = false, /// Type = "IPMatch", /// }, /// }, /// }); /// var fooWebAcl = new Aws.WafRegional.WebAcl("fooWebAcl", new Aws.WafRegional.WebAclArgs /// { /// DefaultAction = new Aws.WafRegional.Inputs.WebAclDefaultActionArgs /// { /// Type = "ALLOW", /// }, /// MetricName = "foo", /// Rules = /// { /// new Aws.WafRegional.Inputs.WebAclRuleArgs /// { /// Action = new Aws.WafRegional.Inputs.WebAclRuleActionArgs /// { /// Type = "BLOCK", /// }, /// Priority = 1, /// RuleId = fooRule.Id, /// }, /// }, /// }); /// var testRestApi = new Aws.ApiGateway.RestApi("testRestApi", new Aws.ApiGateway.RestApiArgs /// { /// }); /// var testResource = new Aws.ApiGateway.Resource("testResource", new Aws.ApiGateway.ResourceArgs /// { /// ParentId = testRestApi.RootResourceId, /// PathPart = "test", /// RestApi = testRestApi.Id, /// }); /// var testMethod = new Aws.ApiGateway.Method("testMethod", new Aws.ApiGateway.MethodArgs /// { /// Authorization = "NONE", /// HttpMethod = "GET", /// ResourceId = testResource.Id, /// RestApi = testRestApi.Id, /// }); /// var testMethodResponse = new Aws.ApiGateway.MethodResponse("testMethodResponse", new Aws.ApiGateway.MethodResponseArgs /// { /// HttpMethod = testMethod.HttpMethod, /// ResourceId = testResource.Id, /// RestApi = testRestApi.Id, /// StatusCode = "400", /// }); /// var testIntegration = new Aws.ApiGateway.Integration("testIntegration", new Aws.ApiGateway.IntegrationArgs /// { /// HttpMethod = testMethod.HttpMethod, /// IntegrationHttpMethod = "GET", /// ResourceId = testResource.Id, /// RestApi = testRestApi.Id, /// Type = "HTTP", /// Uri = "http://www.example.com", /// }); /// var testIntegrationResponse = new Aws.ApiGateway.IntegrationResponse("testIntegrationResponse", new Aws.ApiGateway.IntegrationResponseArgs /// { /// HttpMethod = testIntegration.HttpMethod, /// ResourceId = testResource.Id, /// RestApi = testRestApi.Id, /// StatusCode = testMethodResponse.StatusCode, /// }); /// var testDeployment = new Aws.ApiGateway.Deployment("testDeployment", new Aws.ApiGateway.DeploymentArgs /// { /// RestApi = testRestApi.Id, /// }); /// var testStage = new Aws.ApiGateway.Stage("testStage", new Aws.ApiGateway.StageArgs /// { /// Deployment = testDeployment.Id, /// RestApi = testRestApi.Id, /// StageName = "test", /// }); /// var association = new Aws.WafRegional.WebAclAssociation("association", new Aws.WafRegional.WebAclAssociationArgs /// { /// ResourceArn = testStage.Arn, /// WebAclId = fooWebAcl.Id, /// }); /// } /// /// } /// ``` /// </summary> public partial class WebAclAssociation : Pulumi.CustomResource { /// <summary> /// ARN of the resource to associate with. For example, an Application Load Balancer or API Gateway Stage. /// </summary> [Output("resourceArn")] public Output<string> ResourceArn { get; private set; } = null!; /// <summary> /// The ID of the WAF Regional WebACL to create an association. /// </summary> [Output("webAclId")] public Output<string> WebAclId { get; private set; } = null!; /// <summary> /// Create a WebAclAssociation resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public WebAclAssociation(string name, WebAclAssociationArgs args, CustomResourceOptions? options = null) : base("aws:wafregional/webAclAssociation:WebAclAssociation", name, args ?? new WebAclAssociationArgs(), MakeResourceOptions(options, "")) { } private WebAclAssociation(string name, Input<string> id, WebAclAssociationState? state = null, CustomResourceOptions? options = null) : base("aws:wafregional/webAclAssociation:WebAclAssociation", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing WebAclAssociation resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static WebAclAssociation Get(string name, Input<string> id, WebAclAssociationState? state = null, CustomResourceOptions? options = null) { return new WebAclAssociation(name, id, state, options); } } public sealed class WebAclAssociationArgs : Pulumi.ResourceArgs { /// <summary> /// ARN of the resource to associate with. For example, an Application Load Balancer or API Gateway Stage. /// </summary> [Input("resourceArn", required: true)] public Input<string> ResourceArn { get; set; } = null!; /// <summary> /// The ID of the WAF Regional WebACL to create an association. /// </summary> [Input("webAclId", required: true)] public Input<string> WebAclId { get; set; } = null!; public WebAclAssociationArgs() { } } public sealed class WebAclAssociationState : Pulumi.ResourceArgs { /// <summary> /// ARN of the resource to associate with. For example, an Application Load Balancer or API Gateway Stage. /// </summary> [Input("resourceArn")] public Input<string>? ResourceArn { get; set; } /// <summary> /// The ID of the WAF Regional WebACL to create an association. /// </summary> [Input("webAclId")] public Input<string>? WebAclId { get; set; } public WebAclAssociationState() { } } }
41.050633
154
0.488976
[ "ECL-2.0", "Apache-2.0" ]
JakeGinnivan/pulumi-aws
sdk/dotnet/WafRegional/WebAclAssociation.cs
12,972
C#
using UnityEngine; namespace UnityAtoms { [CreateAssetMenu(menuName = "Unity Atoms/Molecules/Timer/Start Timer")] public class StartTimer : VoidAction { [SerializeField] private Timer Timer = null; public override void Do() { Timer.Start(); } } }
18.647059
75
0.59306
[ "MIT" ]
AKOM-Studio/unity-atoms
Source/Molecules/Timer/StartTimer.cs
317
C#
using System.Collections.Generic; using SFA.DAS.Payments.DCFS.Infrastructure.Data; using SFA.DAS.ProviderPayments.Calc.Shared.Infrastructure.Data.Entities; namespace SFA.DAS.ProviderPayments.Calc.Shared.Infrastructure.Data.Repositories { public class RequiredPaymentRepository : DcfsRepository, IRequiredPaymentRepository { public RequiredPaymentRepository(string connectionString) : base(connectionString) { } public IEnumerable<RequiredPaymentEntity> GetRefundsForProvider(long ukprn) { const string sql = @" SELECT * FROM PaymentsDue.RequiredPayments WHERE Ukprn = @ukprn AND AmountDue < 0 AND Id NOT In (Select RequiredPaymentIdForReversal from Adjustments.ManualAdjustments) "; return Query<RequiredPaymentEntity>(sql, new { ukprn }); } } }
36.307692
103
0.65572
[ "MIT" ]
SkillsFundingAgency/das-providerpayments
src/Shared/SFA.DAS.ProviderPayments.Calc.Shared.Infrastructure/Data/Repositories/RequiredPaymentRepository.cs
946
C#
namespace TrashMob.Shared.Persistence { public interface ISecretRepository { string GetSecret(string name); } }
16.625
38
0.684211
[ "Apache-2.0" ]
ArijitCloud/TrashMob
TrashMob.Shared/Persistence/ISecretRepository.cs
135
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace EmailSaveAndSender { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
27.75
70
0.714715
[ "Apache-2.0" ]
CraigReedWilliams61819842004/EmailSaverAndSender
EmailSaveAndSender/Global.asax.cs
668
C#
#pragma warning disable 0472,0414 using System; using System.Text; using System.IO; using System.Collections; using System.ComponentModel; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Xml.Serialization; using BLToolkit.Aspects; using BLToolkit.DataAccess; using BLToolkit.EditableObjects; using BLToolkit.Data; using BLToolkit.Data.DataProvider; using BLToolkit.Mapping; using BLToolkit.Reflection; using bv.common.Configuration; using bv.common.Enums; using bv.common.Core; using bv.model.BLToolkit; using bv.model.Model; using bv.model.Helpers; using bv.model.Model.Extenders; using bv.model.Model.Core; using bv.model.Model.Handlers; using bv.model.Model.Validators; using eidss.model.Core; using eidss.model.Enums; namespace eidss.model.Schema { [XmlType(AnonymousType = true)] public abstract partial class VectorFieldTest : EditableObject<VectorFieldTest> , IObject , IDisposable , ILookupUsage { [MapField(_str_idfPensideTest), NonUpdatable, PrimaryKey] public abstract Int64 idfPensideTest { get; set; } [LocalizedDisplayName("strPensideTypeName")] [MapField(_str_idfsPensideTestName)] public abstract Int64? idfsPensideTestName { get; set; } protected Int64? idfsPensideTestName_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsPensideTestName).OriginalValue; } } protected Int64? idfsPensideTestName_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsPensideTestName).PreviousValue; } } [LocalizedDisplayName(_str_strPensideTestTypeName)] [MapField(_str_strPensideTestTypeName)] public abstract String strPensideTestTypeName { get; set; } protected String strPensideTestTypeName_Original { get { return ((EditableValue<String>)((dynamic)this)._strPensideTestTypeName).OriginalValue; } } protected String strPensideTestTypeName_Previous { get { return ((EditableValue<String>)((dynamic)this)._strPensideTestTypeName).PreviousValue; } } [LocalizedDisplayName(_str_idfVectorSurveillanceSession)] [MapField(_str_idfVectorSurveillanceSession)] public abstract Int64? idfVectorSurveillanceSession { get; set; } protected Int64? idfVectorSurveillanceSession_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfVectorSurveillanceSession).OriginalValue; } } protected Int64? idfVectorSurveillanceSession_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfVectorSurveillanceSession).PreviousValue; } } [LocalizedDisplayName(_str_idfVector)] [MapField(_str_idfVector)] public abstract Int64? idfVector { get; set; } protected Int64? idfVector_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfVector).OriginalValue; } } protected Int64? idfVector_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfVector).PreviousValue; } } [LocalizedDisplayName(_str_idfsVectorType)] [MapField(_str_idfsVectorType)] public abstract Int64 idfsVectorType { get; set; } protected Int64 idfsVectorType_Original { get { return ((EditableValue<Int64>)((dynamic)this)._idfsVectorType).OriginalValue; } } protected Int64 idfsVectorType_Previous { get { return ((EditableValue<Int64>)((dynamic)this)._idfsVectorType).PreviousValue; } } [LocalizedDisplayName("idfsVectorType")] [MapField(_str_strVectorTypeName)] public abstract String strVectorTypeName { get; set; } protected String strVectorTypeName_Original { get { return ((EditableValue<String>)((dynamic)this)._strVectorTypeName).OriginalValue; } } protected String strVectorTypeName_Previous { get { return ((EditableValue<String>)((dynamic)this)._strVectorTypeName).PreviousValue; } } [LocalizedDisplayName(_str_idfMaterial)] [MapField(_str_idfMaterial)] public abstract Int64 idfMaterial { get; set; } protected Int64 idfMaterial_Original { get { return ((EditableValue<Int64>)((dynamic)this)._idfMaterial).OriginalValue; } } protected Int64 idfMaterial_Previous { get { return ((EditableValue<Int64>)((dynamic)this)._idfMaterial).PreviousValue; } } [LocalizedDisplayName("VectorSample.strFieldBarcode")] [MapField(_str_strFieldBarcode)] public abstract String strFieldBarcode { get; set; } protected String strFieldBarcode_Original { get { return ((EditableValue<String>)((dynamic)this)._strFieldBarcode).OriginalValue; } } protected String strFieldBarcode_Previous { get { return ((EditableValue<String>)((dynamic)this)._strFieldBarcode).PreviousValue; } } [LocalizedDisplayName(_str_idfsSampleType)] [MapField(_str_idfsSampleType)] public abstract Int64 idfsSampleType { get; set; } protected Int64 idfsSampleType_Original { get { return ((EditableValue<Int64>)((dynamic)this)._idfsSampleType).OriginalValue; } } protected Int64 idfsSampleType_Previous { get { return ((EditableValue<Int64>)((dynamic)this)._idfsSampleType).PreviousValue; } } [LocalizedDisplayName("idfsSampleType")] [MapField(_str_strSampleName)] public abstract String strSampleName { get; set; } protected String strSampleName_Original { get { return ((EditableValue<String>)((dynamic)this)._strSampleName).OriginalValue; } } protected String strSampleName_Previous { get { return ((EditableValue<String>)((dynamic)this)._strSampleName).PreviousValue; } } [LocalizedDisplayName(_str_datFieldCollectionDate)] [MapField(_str_datFieldCollectionDate)] public abstract DateTime? datFieldCollectionDate { get; set; } protected DateTime? datFieldCollectionDate_Original { get { return ((EditableValue<DateTime?>)((dynamic)this)._datFieldCollectionDate).OriginalValue; } } protected DateTime? datFieldCollectionDate_Previous { get { return ((EditableValue<DateTime?>)((dynamic)this)._datFieldCollectionDate).PreviousValue; } } [LocalizedDisplayName("idfPensideTestTestDate")] [MapField(_str_datTestDate)] public abstract DateTime? datTestDate { get; set; } protected DateTime? datTestDate_Original { get { return ((EditableValue<DateTime?>)((dynamic)this)._datTestDate).OriginalValue; } } protected DateTime? datTestDate_Previous { get { return ((EditableValue<DateTime?>)((dynamic)this)._datTestDate).PreviousValue; } } [LocalizedDisplayName("idfPensideTestTestCategory")] [MapField(_str_idfsPensideTestCategory)] public abstract Int64? idfsPensideTestCategory { get; set; } protected Int64? idfsPensideTestCategory_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsPensideTestCategory).OriginalValue; } } protected Int64? idfsPensideTestCategory_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsPensideTestCategory).PreviousValue; } } [LocalizedDisplayName(_str_strPensideTestCategoryName)] [MapField(_str_strPensideTestCategoryName)] public abstract String strPensideTestCategoryName { get; set; } protected String strPensideTestCategoryName_Original { get { return ((EditableValue<String>)((dynamic)this)._strPensideTestCategoryName).OriginalValue; } } protected String strPensideTestCategoryName_Previous { get { return ((EditableValue<String>)((dynamic)this)._strPensideTestCategoryName).PreviousValue; } } [LocalizedDisplayName("idfPensideTestTestedByPerson")] [MapField(_str_idfTestedByPerson)] public abstract Int64? idfTestedByPerson { get; set; } protected Int64? idfTestedByPerson_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfTestedByPerson).OriginalValue; } } protected Int64? idfTestedByPerson_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfTestedByPerson).PreviousValue; } } [LocalizedDisplayName(_str_strCollectedByPerson)] [MapField(_str_strCollectedByPerson)] public abstract String strCollectedByPerson { get; set; } protected String strCollectedByPerson_Original { get { return ((EditableValue<String>)((dynamic)this)._strCollectedByPerson).OriginalValue; } } protected String strCollectedByPerson_Previous { get { return ((EditableValue<String>)((dynamic)this)._strCollectedByPerson).PreviousValue; } } [LocalizedDisplayName("idfPensideTestTestedByOffice")] [MapField(_str_idfTestedByOffice)] public abstract Int64? idfTestedByOffice { get; set; } protected Int64? idfTestedByOffice_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfTestedByOffice).OriginalValue; } } protected Int64? idfTestedByOffice_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfTestedByOffice).PreviousValue; } } [LocalizedDisplayName(_str_strCollectedByOffice)] [MapField(_str_strCollectedByOffice)] public abstract String strCollectedByOffice { get; set; } protected String strCollectedByOffice_Original { get { return ((EditableValue<String>)((dynamic)this)._strCollectedByOffice).OriginalValue; } } protected String strCollectedByOffice_Previous { get { return ((EditableValue<String>)((dynamic)this)._strCollectedByOffice).PreviousValue; } } [LocalizedDisplayName("FT.PensideTestResult")] [MapField(_str_idfsPensideTestResult)] public abstract Int64? idfsPensideTestResult { get; set; } protected Int64? idfsPensideTestResult_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsPensideTestResult).OriginalValue; } } protected Int64? idfsPensideTestResult_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsPensideTestResult).PreviousValue; } } [LocalizedDisplayName(_str_strPensideTestResultName)] [MapField(_str_strPensideTestResultName)] public abstract String strPensideTestResultName { get; set; } protected String strPensideTestResultName_Original { get { return ((EditableValue<String>)((dynamic)this)._strPensideTestResultName).OriginalValue; } } protected String strPensideTestResultName_Previous { get { return ((EditableValue<String>)((dynamic)this)._strPensideTestResultName).PreviousValue; } } [LocalizedDisplayName("FT.strDisease")] [MapField(_str_idfsDiagnosis)] public abstract Int64? idfsDiagnosis { get; set; } protected Int64? idfsDiagnosis_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsDiagnosis).OriginalValue; } } protected Int64? idfsDiagnosis_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsDiagnosis).PreviousValue; } } [LocalizedDisplayName(_str_strDiagnosisName)] [MapField(_str_strDiagnosisName)] public abstract String strDiagnosisName { get; set; } protected String strDiagnosisName_Original { get { return ((EditableValue<String>)((dynamic)this)._strDiagnosisName).OriginalValue; } } protected String strDiagnosisName_Previous { get { return ((EditableValue<String>)((dynamic)this)._strDiagnosisName).PreviousValue; } } [LocalizedDisplayName(_str_intOrder)] [MapField(_str_intOrder)] public abstract Int32? intOrder { get; set; } protected Int32? intOrder_Original { get { return ((EditableValue<Int32?>)((dynamic)this)._intOrder).OriginalValue; } } protected Int32? intOrder_Previous { get { return ((EditableValue<Int32?>)((dynamic)this)._intOrder).PreviousValue; } } [LocalizedDisplayName("Vector.strVectorID")] [MapField(_str_strVectorID)] public abstract String strVectorID { get; set; } protected String strVectorID_Original { get { return ((EditableValue<String>)((dynamic)this)._strVectorID).OriginalValue; } } protected String strVectorID_Previous { get { return ((EditableValue<String>)((dynamic)this)._strVectorID).PreviousValue; } } #region Set/Get values #region filed_info definifion protected class field_info { internal string _name; internal string _formname; internal string _type; internal Func<VectorFieldTest, object> _get_func; internal Action<VectorFieldTest, string> _set_func; internal Action<VectorFieldTest, VectorFieldTest, CompareModel, DbManagerProxy> _compare_func; } internal const string _str_Parent = "Parent"; internal const string _str_IsNew = "IsNew"; internal const string _str_idfPensideTest = "idfPensideTest"; internal const string _str_idfsPensideTestName = "idfsPensideTestName"; internal const string _str_strPensideTestTypeName = "strPensideTestTypeName"; internal const string _str_idfVectorSurveillanceSession = "idfVectorSurveillanceSession"; internal const string _str_idfVector = "idfVector"; internal const string _str_idfsVectorType = "idfsVectorType"; internal const string _str_strVectorTypeName = "strVectorTypeName"; internal const string _str_idfMaterial = "idfMaterial"; internal const string _str_strFieldBarcode = "strFieldBarcode"; internal const string _str_idfsSampleType = "idfsSampleType"; internal const string _str_strSampleName = "strSampleName"; internal const string _str_datFieldCollectionDate = "datFieldCollectionDate"; internal const string _str_datTestDate = "datTestDate"; internal const string _str_idfsPensideTestCategory = "idfsPensideTestCategory"; internal const string _str_strPensideTestCategoryName = "strPensideTestCategoryName"; internal const string _str_idfTestedByPerson = "idfTestedByPerson"; internal const string _str_strCollectedByPerson = "strCollectedByPerson"; internal const string _str_idfTestedByOffice = "idfTestedByOffice"; internal const string _str_strCollectedByOffice = "strCollectedByOffice"; internal const string _str_idfsPensideTestResult = "idfsPensideTestResult"; internal const string _str_strPensideTestResultName = "strPensideTestResultName"; internal const string _str_idfsDiagnosis = "idfsDiagnosis"; internal const string _str_strDiagnosisName = "strDiagnosisName"; internal const string _str_intOrder = "intOrder"; internal const string _str_strVectorID = "strVectorID"; internal const string _str_strPensideTestName = "strPensideTestName"; internal const string _str_strPensideTestCategory = "strPensideTestCategory"; internal const string _str_strPensideTestResult = "strPensideTestResult"; internal const string _str_strDiagnosis = "strDiagnosis"; internal const string _str_strTestedByOffice = "strTestedByOffice"; internal const string _str_strTestedByPerson = "strTestedByPerson"; internal const string _str_strSampleFieldBarcode = "strSampleFieldBarcode"; internal const string _str_strVectorSubTypeName = "strVectorSubTypeName"; internal const string _str_ParentVector = "ParentVector"; internal const string _str_Samples = "Samples"; internal const string _str_SamplesSelectList = "SamplesSelectList"; internal const string _str_ParentSample = "ParentSample"; internal const string _str_CaseObjectIdent = "CaseObjectIdent"; internal const string _str_Vectors = "Vectors"; internal const string _str_TestType = "TestType"; internal const string _str_TestCategory = "TestCategory"; internal const string _str_Diagnosis = "Diagnosis"; internal const string _str_TestResult = "TestResult"; internal const string _str_DiagnosisFiltered = "DiagnosisFiltered"; internal const string _str_TestResultFiltered = "TestResultFiltered"; internal const string _str_TestedByPerson = "TestedByPerson"; internal const string _str_TestedByOffice = "TestedByOffice"; private static readonly field_info[] _field_infos = { new field_info { _name = _str_idfPensideTest, _formname = _str_idfPensideTest, _type = "Int64", _get_func = o => o.idfPensideTest, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64(val); if (o.idfPensideTest != newval) o.idfPensideTest = newval; }, _compare_func = (o, c, m, g) => { if (o.idfPensideTest != c.idfPensideTest || o.IsRIRPropChanged(_str_idfPensideTest, c)) m.Add(_str_idfPensideTest, o.ObjectIdent + _str_idfPensideTest, o.ObjectIdent2 + _str_idfPensideTest, o.ObjectIdent3 + _str_idfPensideTest, "Int64", o.idfPensideTest == null ? "" : o.idfPensideTest.ToString(), o.IsReadOnly(_str_idfPensideTest), o.IsInvisible(_str_idfPensideTest), o.IsRequired(_str_idfPensideTest)); } }, new field_info { _name = _str_idfsPensideTestName, _formname = _str_idfsPensideTestName, _type = "Int64?", _get_func = o => o.idfsPensideTestName, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsPensideTestName != newval) o.TestType = o.TestTypeLookup.FirstOrDefault(c => c.idfsPensideTestName == newval); if (o.idfsPensideTestName != newval) o.idfsPensideTestName = newval; }, _compare_func = (o, c, m, g) => { if (o.idfsPensideTestName != c.idfsPensideTestName || o.IsRIRPropChanged(_str_idfsPensideTestName, c)) m.Add(_str_idfsPensideTestName, o.ObjectIdent + _str_idfsPensideTestName, o.ObjectIdent2 + _str_idfsPensideTestName, o.ObjectIdent3 + _str_idfsPensideTestName, "Int64?", o.idfsPensideTestName == null ? "" : o.idfsPensideTestName.ToString(), o.IsReadOnly(_str_idfsPensideTestName), o.IsInvisible(_str_idfsPensideTestName), o.IsRequired(_str_idfsPensideTestName)); } }, new field_info { _name = _str_strPensideTestTypeName, _formname = _str_strPensideTestTypeName, _type = "String", _get_func = o => o.strPensideTestTypeName, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strPensideTestTypeName != newval) o.strPensideTestTypeName = newval; }, _compare_func = (o, c, m, g) => { if (o.strPensideTestTypeName != c.strPensideTestTypeName || o.IsRIRPropChanged(_str_strPensideTestTypeName, c)) m.Add(_str_strPensideTestTypeName, o.ObjectIdent + _str_strPensideTestTypeName, o.ObjectIdent2 + _str_strPensideTestTypeName, o.ObjectIdent3 + _str_strPensideTestTypeName, "String", o.strPensideTestTypeName == null ? "" : o.strPensideTestTypeName.ToString(), o.IsReadOnly(_str_strPensideTestTypeName), o.IsInvisible(_str_strPensideTestTypeName), o.IsRequired(_str_strPensideTestTypeName)); } }, new field_info { _name = _str_idfVectorSurveillanceSession, _formname = _str_idfVectorSurveillanceSession, _type = "Int64?", _get_func = o => o.idfVectorSurveillanceSession, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfVectorSurveillanceSession != newval) o.idfVectorSurveillanceSession = newval; }, _compare_func = (o, c, m, g) => { if (o.idfVectorSurveillanceSession != c.idfVectorSurveillanceSession || o.IsRIRPropChanged(_str_idfVectorSurveillanceSession, c)) m.Add(_str_idfVectorSurveillanceSession, o.ObjectIdent + _str_idfVectorSurveillanceSession, o.ObjectIdent2 + _str_idfVectorSurveillanceSession, o.ObjectIdent3 + _str_idfVectorSurveillanceSession, "Int64?", o.idfVectorSurveillanceSession == null ? "" : o.idfVectorSurveillanceSession.ToString(), o.IsReadOnly(_str_idfVectorSurveillanceSession), o.IsInvisible(_str_idfVectorSurveillanceSession), o.IsRequired(_str_idfVectorSurveillanceSession)); } }, new field_info { _name = _str_idfVector, _formname = _str_idfVector, _type = "Int64?", _get_func = o => o.idfVector, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfVector != newval) o.idfVector = newval; }, _compare_func = (o, c, m, g) => { if (o.idfVector != c.idfVector || o.IsRIRPropChanged(_str_idfVector, c)) m.Add(_str_idfVector, o.ObjectIdent + _str_idfVector, o.ObjectIdent2 + _str_idfVector, o.ObjectIdent3 + _str_idfVector, "Int64?", o.idfVector == null ? "" : o.idfVector.ToString(), o.IsReadOnly(_str_idfVector), o.IsInvisible(_str_idfVector), o.IsRequired(_str_idfVector)); } }, new field_info { _name = _str_idfsVectorType, _formname = _str_idfsVectorType, _type = "Int64", _get_func = o => o.idfsVectorType, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64(val); if (o.idfsVectorType != newval) o.idfsVectorType = newval; }, _compare_func = (o, c, m, g) => { if (o.idfsVectorType != c.idfsVectorType || o.IsRIRPropChanged(_str_idfsVectorType, c)) m.Add(_str_idfsVectorType, o.ObjectIdent + _str_idfsVectorType, o.ObjectIdent2 + _str_idfsVectorType, o.ObjectIdent3 + _str_idfsVectorType, "Int64", o.idfsVectorType == null ? "" : o.idfsVectorType.ToString(), o.IsReadOnly(_str_idfsVectorType), o.IsInvisible(_str_idfsVectorType), o.IsRequired(_str_idfsVectorType)); } }, new field_info { _name = _str_strVectorTypeName, _formname = _str_strVectorTypeName, _type = "String", _get_func = o => o.strVectorTypeName, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strVectorTypeName != newval) o.strVectorTypeName = newval; }, _compare_func = (o, c, m, g) => { if (o.strVectorTypeName != c.strVectorTypeName || o.IsRIRPropChanged(_str_strVectorTypeName, c)) m.Add(_str_strVectorTypeName, o.ObjectIdent + _str_strVectorTypeName, o.ObjectIdent2 + _str_strVectorTypeName, o.ObjectIdent3 + _str_strVectorTypeName, "String", o.strVectorTypeName == null ? "" : o.strVectorTypeName.ToString(), o.IsReadOnly(_str_strVectorTypeName), o.IsInvisible(_str_strVectorTypeName), o.IsRequired(_str_strVectorTypeName)); } }, new field_info { _name = _str_idfMaterial, _formname = _str_idfMaterial, _type = "Int64", _get_func = o => o.idfMaterial, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64(val); if (o.idfMaterial != newval) o.idfMaterial = newval; }, _compare_func = (o, c, m, g) => { if (o.idfMaterial != c.idfMaterial || o.IsRIRPropChanged(_str_idfMaterial, c)) m.Add(_str_idfMaterial, o.ObjectIdent + _str_idfMaterial, o.ObjectIdent2 + _str_idfMaterial, o.ObjectIdent3 + _str_idfMaterial, "Int64", o.idfMaterial == null ? "" : o.idfMaterial.ToString(), o.IsReadOnly(_str_idfMaterial), o.IsInvisible(_str_idfMaterial), o.IsRequired(_str_idfMaterial)); } }, new field_info { _name = _str_strFieldBarcode, _formname = _str_strFieldBarcode, _type = "String", _get_func = o => o.strFieldBarcode, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strFieldBarcode != newval) o.strFieldBarcode = newval; }, _compare_func = (o, c, m, g) => { if (o.strFieldBarcode != c.strFieldBarcode || o.IsRIRPropChanged(_str_strFieldBarcode, c)) m.Add(_str_strFieldBarcode, o.ObjectIdent + _str_strFieldBarcode, o.ObjectIdent2 + _str_strFieldBarcode, o.ObjectIdent3 + _str_strFieldBarcode, "String", o.strFieldBarcode == null ? "" : o.strFieldBarcode.ToString(), o.IsReadOnly(_str_strFieldBarcode), o.IsInvisible(_str_strFieldBarcode), o.IsRequired(_str_strFieldBarcode)); } }, new field_info { _name = _str_idfsSampleType, _formname = _str_idfsSampleType, _type = "Int64", _get_func = o => o.idfsSampleType, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64(val); if (o.idfsSampleType != newval) o.idfsSampleType = newval; }, _compare_func = (o, c, m, g) => { if (o.idfsSampleType != c.idfsSampleType || o.IsRIRPropChanged(_str_idfsSampleType, c)) m.Add(_str_idfsSampleType, o.ObjectIdent + _str_idfsSampleType, o.ObjectIdent2 + _str_idfsSampleType, o.ObjectIdent3 + _str_idfsSampleType, "Int64", o.idfsSampleType == null ? "" : o.idfsSampleType.ToString(), o.IsReadOnly(_str_idfsSampleType), o.IsInvisible(_str_idfsSampleType), o.IsRequired(_str_idfsSampleType)); } }, new field_info { _name = _str_strSampleName, _formname = _str_strSampleName, _type = "String", _get_func = o => o.strSampleName, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strSampleName != newval) o.strSampleName = newval; }, _compare_func = (o, c, m, g) => { if (o.strSampleName != c.strSampleName || o.IsRIRPropChanged(_str_strSampleName, c)) m.Add(_str_strSampleName, o.ObjectIdent + _str_strSampleName, o.ObjectIdent2 + _str_strSampleName, o.ObjectIdent3 + _str_strSampleName, "String", o.strSampleName == null ? "" : o.strSampleName.ToString(), o.IsReadOnly(_str_strSampleName), o.IsInvisible(_str_strSampleName), o.IsRequired(_str_strSampleName)); } }, new field_info { _name = _str_datFieldCollectionDate, _formname = _str_datFieldCollectionDate, _type = "DateTime?", _get_func = o => o.datFieldCollectionDate, _set_func = (o, val) => { var newval = ParsingHelper.ParseDateTimeNullable(val); if (o.datFieldCollectionDate != newval) o.datFieldCollectionDate = newval; }, _compare_func = (o, c, m, g) => { if (o.datFieldCollectionDate != c.datFieldCollectionDate || o.IsRIRPropChanged(_str_datFieldCollectionDate, c)) m.Add(_str_datFieldCollectionDate, o.ObjectIdent + _str_datFieldCollectionDate, o.ObjectIdent2 + _str_datFieldCollectionDate, o.ObjectIdent3 + _str_datFieldCollectionDate, "DateTime?", o.datFieldCollectionDate == null ? "" : o.datFieldCollectionDate.ToString(), o.IsReadOnly(_str_datFieldCollectionDate), o.IsInvisible(_str_datFieldCollectionDate), o.IsRequired(_str_datFieldCollectionDate)); } }, new field_info { _name = _str_datTestDate, _formname = _str_datTestDate, _type = "DateTime?", _get_func = o => o.datTestDate, _set_func = (o, val) => { var newval = ParsingHelper.ParseDateTimeNullable(val); if (o.datTestDate != newval) o.datTestDate = newval; }, _compare_func = (o, c, m, g) => { if (o.datTestDate != c.datTestDate || o.IsRIRPropChanged(_str_datTestDate, c)) m.Add(_str_datTestDate, o.ObjectIdent + _str_datTestDate, o.ObjectIdent2 + _str_datTestDate, o.ObjectIdent3 + _str_datTestDate, "DateTime?", o.datTestDate == null ? "" : o.datTestDate.ToString(), o.IsReadOnly(_str_datTestDate), o.IsInvisible(_str_datTestDate), o.IsRequired(_str_datTestDate)); } }, new field_info { _name = _str_idfsPensideTestCategory, _formname = _str_idfsPensideTestCategory, _type = "Int64?", _get_func = o => o.idfsPensideTestCategory, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsPensideTestCategory != newval) o.TestCategory = o.TestCategoryLookup.FirstOrDefault(c => c.idfsBaseReference == newval); if (o.idfsPensideTestCategory != newval) o.idfsPensideTestCategory = newval; }, _compare_func = (o, c, m, g) => { if (o.idfsPensideTestCategory != c.idfsPensideTestCategory || o.IsRIRPropChanged(_str_idfsPensideTestCategory, c)) m.Add(_str_idfsPensideTestCategory, o.ObjectIdent + _str_idfsPensideTestCategory, o.ObjectIdent2 + _str_idfsPensideTestCategory, o.ObjectIdent3 + _str_idfsPensideTestCategory, "Int64?", o.idfsPensideTestCategory == null ? "" : o.idfsPensideTestCategory.ToString(), o.IsReadOnly(_str_idfsPensideTestCategory), o.IsInvisible(_str_idfsPensideTestCategory), o.IsRequired(_str_idfsPensideTestCategory)); } }, new field_info { _name = _str_strPensideTestCategoryName, _formname = _str_strPensideTestCategoryName, _type = "String", _get_func = o => o.strPensideTestCategoryName, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strPensideTestCategoryName != newval) o.strPensideTestCategoryName = newval; }, _compare_func = (o, c, m, g) => { if (o.strPensideTestCategoryName != c.strPensideTestCategoryName || o.IsRIRPropChanged(_str_strPensideTestCategoryName, c)) m.Add(_str_strPensideTestCategoryName, o.ObjectIdent + _str_strPensideTestCategoryName, o.ObjectIdent2 + _str_strPensideTestCategoryName, o.ObjectIdent3 + _str_strPensideTestCategoryName, "String", o.strPensideTestCategoryName == null ? "" : o.strPensideTestCategoryName.ToString(), o.IsReadOnly(_str_strPensideTestCategoryName), o.IsInvisible(_str_strPensideTestCategoryName), o.IsRequired(_str_strPensideTestCategoryName)); } }, new field_info { _name = _str_idfTestedByPerson, _formname = _str_idfTestedByPerson, _type = "Int64?", _get_func = o => o.idfTestedByPerson, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfTestedByPerson != newval) o.TestedByPerson = o.TestedByPersonLookup.FirstOrDefault(c => c.idfPerson == newval); if (o.idfTestedByPerson != newval) o.idfTestedByPerson = newval; }, _compare_func = (o, c, m, g) => { if (o.idfTestedByPerson != c.idfTestedByPerson || o.IsRIRPropChanged(_str_idfTestedByPerson, c)) m.Add(_str_idfTestedByPerson, o.ObjectIdent + _str_idfTestedByPerson, o.ObjectIdent2 + _str_idfTestedByPerson, o.ObjectIdent3 + _str_idfTestedByPerson, "Int64?", o.idfTestedByPerson == null ? "" : o.idfTestedByPerson.ToString(), o.IsReadOnly(_str_idfTestedByPerson), o.IsInvisible(_str_idfTestedByPerson), o.IsRequired(_str_idfTestedByPerson)); } }, new field_info { _name = _str_strCollectedByPerson, _formname = _str_strCollectedByPerson, _type = "String", _get_func = o => o.strCollectedByPerson, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strCollectedByPerson != newval) o.strCollectedByPerson = newval; }, _compare_func = (o, c, m, g) => { if (o.strCollectedByPerson != c.strCollectedByPerson || o.IsRIRPropChanged(_str_strCollectedByPerson, c)) m.Add(_str_strCollectedByPerson, o.ObjectIdent + _str_strCollectedByPerson, o.ObjectIdent2 + _str_strCollectedByPerson, o.ObjectIdent3 + _str_strCollectedByPerson, "String", o.strCollectedByPerson == null ? "" : o.strCollectedByPerson.ToString(), o.IsReadOnly(_str_strCollectedByPerson), o.IsInvisible(_str_strCollectedByPerson), o.IsRequired(_str_strCollectedByPerson)); } }, new field_info { _name = _str_idfTestedByOffice, _formname = _str_idfTestedByOffice, _type = "Int64?", _get_func = o => o.idfTestedByOffice, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfTestedByOffice != newval) o.TestedByOffice = o.TestedByOfficeLookup.FirstOrDefault(c => c.idfInstitution == newval); if (o.idfTestedByOffice != newval) o.idfTestedByOffice = newval; }, _compare_func = (o, c, m, g) => { if (o.idfTestedByOffice != c.idfTestedByOffice || o.IsRIRPropChanged(_str_idfTestedByOffice, c)) m.Add(_str_idfTestedByOffice, o.ObjectIdent + _str_idfTestedByOffice, o.ObjectIdent2 + _str_idfTestedByOffice, o.ObjectIdent3 + _str_idfTestedByOffice, "Int64?", o.idfTestedByOffice == null ? "" : o.idfTestedByOffice.ToString(), o.IsReadOnly(_str_idfTestedByOffice), o.IsInvisible(_str_idfTestedByOffice), o.IsRequired(_str_idfTestedByOffice)); } }, new field_info { _name = _str_strCollectedByOffice, _formname = _str_strCollectedByOffice, _type = "String", _get_func = o => o.strCollectedByOffice, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strCollectedByOffice != newval) o.strCollectedByOffice = newval; }, _compare_func = (o, c, m, g) => { if (o.strCollectedByOffice != c.strCollectedByOffice || o.IsRIRPropChanged(_str_strCollectedByOffice, c)) m.Add(_str_strCollectedByOffice, o.ObjectIdent + _str_strCollectedByOffice, o.ObjectIdent2 + _str_strCollectedByOffice, o.ObjectIdent3 + _str_strCollectedByOffice, "String", o.strCollectedByOffice == null ? "" : o.strCollectedByOffice.ToString(), o.IsReadOnly(_str_strCollectedByOffice), o.IsInvisible(_str_strCollectedByOffice), o.IsRequired(_str_strCollectedByOffice)); } }, new field_info { _name = _str_idfsPensideTestResult, _formname = _str_idfsPensideTestResult, _type = "Int64?", _get_func = o => o.idfsPensideTestResult, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsPensideTestResult != newval) o.TestResult = o.TestResultLookup.FirstOrDefault(c => c.idfsPensideTestResult == newval); if (o.idfsPensideTestResult != newval) o.idfsPensideTestResult = newval; }, _compare_func = (o, c, m, g) => { if (o.idfsPensideTestResult != c.idfsPensideTestResult || o.IsRIRPropChanged(_str_idfsPensideTestResult, c)) m.Add(_str_idfsPensideTestResult, o.ObjectIdent + _str_idfsPensideTestResult, o.ObjectIdent2 + _str_idfsPensideTestResult, o.ObjectIdent3 + _str_idfsPensideTestResult, "Int64?", o.idfsPensideTestResult == null ? "" : o.idfsPensideTestResult.ToString(), o.IsReadOnly(_str_idfsPensideTestResult), o.IsInvisible(_str_idfsPensideTestResult), o.IsRequired(_str_idfsPensideTestResult)); } }, new field_info { _name = _str_strPensideTestResultName, _formname = _str_strPensideTestResultName, _type = "String", _get_func = o => o.strPensideTestResultName, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strPensideTestResultName != newval) o.strPensideTestResultName = newval; }, _compare_func = (o, c, m, g) => { if (o.strPensideTestResultName != c.strPensideTestResultName || o.IsRIRPropChanged(_str_strPensideTestResultName, c)) m.Add(_str_strPensideTestResultName, o.ObjectIdent + _str_strPensideTestResultName, o.ObjectIdent2 + _str_strPensideTestResultName, o.ObjectIdent3 + _str_strPensideTestResultName, "String", o.strPensideTestResultName == null ? "" : o.strPensideTestResultName.ToString(), o.IsReadOnly(_str_strPensideTestResultName), o.IsInvisible(_str_strPensideTestResultName), o.IsRequired(_str_strPensideTestResultName)); } }, new field_info { _name = _str_idfsDiagnosis, _formname = _str_idfsDiagnosis, _type = "Int64?", _get_func = o => o.idfsDiagnosis, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsDiagnosis != newval) o.Diagnosis = o.DiagnosisLookup.FirstOrDefault(c => c.idfsDiagnosis == newval); if (o.idfsDiagnosis != newval) o.idfsDiagnosis = newval; }, _compare_func = (o, c, m, g) => { if (o.idfsDiagnosis != c.idfsDiagnosis || o.IsRIRPropChanged(_str_idfsDiagnosis, c)) m.Add(_str_idfsDiagnosis, o.ObjectIdent + _str_idfsDiagnosis, o.ObjectIdent2 + _str_idfsDiagnosis, o.ObjectIdent3 + _str_idfsDiagnosis, "Int64?", o.idfsDiagnosis == null ? "" : o.idfsDiagnosis.ToString(), o.IsReadOnly(_str_idfsDiagnosis), o.IsInvisible(_str_idfsDiagnosis), o.IsRequired(_str_idfsDiagnosis)); } }, new field_info { _name = _str_strDiagnosisName, _formname = _str_strDiagnosisName, _type = "String", _get_func = o => o.strDiagnosisName, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strDiagnosisName != newval) o.strDiagnosisName = newval; }, _compare_func = (o, c, m, g) => { if (o.strDiagnosisName != c.strDiagnosisName || o.IsRIRPropChanged(_str_strDiagnosisName, c)) m.Add(_str_strDiagnosisName, o.ObjectIdent + _str_strDiagnosisName, o.ObjectIdent2 + _str_strDiagnosisName, o.ObjectIdent3 + _str_strDiagnosisName, "String", o.strDiagnosisName == null ? "" : o.strDiagnosisName.ToString(), o.IsReadOnly(_str_strDiagnosisName), o.IsInvisible(_str_strDiagnosisName), o.IsRequired(_str_strDiagnosisName)); } }, new field_info { _name = _str_intOrder, _formname = _str_intOrder, _type = "Int32?", _get_func = o => o.intOrder, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt32Nullable(val); if (o.intOrder != newval) o.intOrder = newval; }, _compare_func = (o, c, m, g) => { if (o.intOrder != c.intOrder || o.IsRIRPropChanged(_str_intOrder, c)) m.Add(_str_intOrder, o.ObjectIdent + _str_intOrder, o.ObjectIdent2 + _str_intOrder, o.ObjectIdent3 + _str_intOrder, "Int32?", o.intOrder == null ? "" : o.intOrder.ToString(), o.IsReadOnly(_str_intOrder), o.IsInvisible(_str_intOrder), o.IsRequired(_str_intOrder)); } }, new field_info { _name = _str_strVectorID, _formname = _str_strVectorID, _type = "String", _get_func = o => o.strVectorID, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strVectorID != newval) o.strVectorID = newval; }, _compare_func = (o, c, m, g) => { if (o.strVectorID != c.strVectorID || o.IsRIRPropChanged(_str_strVectorID, c)) m.Add(_str_strVectorID, o.ObjectIdent + _str_strVectorID, o.ObjectIdent2 + _str_strVectorID, o.ObjectIdent3 + _str_strVectorID, "String", o.strVectorID == null ? "" : o.strVectorID.ToString(), o.IsReadOnly(_str_strVectorID), o.IsInvisible(_str_strVectorID), o.IsRequired(_str_strVectorID)); } }, new field_info { _name = _str_strPensideTestName, _formname = _str_strPensideTestName, _type = "string", _get_func = o => o.strPensideTestName, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { if (o.strPensideTestName != c.strPensideTestName || o.IsRIRPropChanged(_str_strPensideTestName, c)) { m.Add(_str_strPensideTestName, o.ObjectIdent + _str_strPensideTestName, o.ObjectIdent2 + _str_strPensideTestName, o.ObjectIdent3 + _str_strPensideTestName, "string", o.strPensideTestName == null ? "" : o.strPensideTestName.ToString(), o.IsReadOnly(_str_strPensideTestName), o.IsInvisible(_str_strPensideTestName), o.IsRequired(_str_strPensideTestName)); } } }, new field_info { _name = _str_strPensideTestCategory, _formname = _str_strPensideTestCategory, _type = "string", _get_func = o => o.strPensideTestCategory, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { if (o.strPensideTestCategory != c.strPensideTestCategory || o.IsRIRPropChanged(_str_strPensideTestCategory, c)) { m.Add(_str_strPensideTestCategory, o.ObjectIdent + _str_strPensideTestCategory, o.ObjectIdent2 + _str_strPensideTestCategory, o.ObjectIdent3 + _str_strPensideTestCategory, "string", o.strPensideTestCategory == null ? "" : o.strPensideTestCategory.ToString(), o.IsReadOnly(_str_strPensideTestCategory), o.IsInvisible(_str_strPensideTestCategory), o.IsRequired(_str_strPensideTestCategory)); } } }, new field_info { _name = _str_strPensideTestResult, _formname = _str_strPensideTestResult, _type = "string", _get_func = o => o.strPensideTestResult, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { if (o.strPensideTestResult != c.strPensideTestResult || o.IsRIRPropChanged(_str_strPensideTestResult, c)) { m.Add(_str_strPensideTestResult, o.ObjectIdent + _str_strPensideTestResult, o.ObjectIdent2 + _str_strPensideTestResult, o.ObjectIdent3 + _str_strPensideTestResult, "string", o.strPensideTestResult == null ? "" : o.strPensideTestResult.ToString(), o.IsReadOnly(_str_strPensideTestResult), o.IsInvisible(_str_strPensideTestResult), o.IsRequired(_str_strPensideTestResult)); } } }, new field_info { _name = _str_strDiagnosis, _formname = _str_strDiagnosis, _type = "string", _get_func = o => o.strDiagnosis, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { if (o.strDiagnosis != c.strDiagnosis || o.IsRIRPropChanged(_str_strDiagnosis, c)) { m.Add(_str_strDiagnosis, o.ObjectIdent + _str_strDiagnosis, o.ObjectIdent2 + _str_strDiagnosis, o.ObjectIdent3 + _str_strDiagnosis, "string", o.strDiagnosis == null ? "" : o.strDiagnosis.ToString(), o.IsReadOnly(_str_strDiagnosis), o.IsInvisible(_str_strDiagnosis), o.IsRequired(_str_strDiagnosis)); } } }, new field_info { _name = _str_strTestedByOffice, _formname = _str_strTestedByOffice, _type = "string", _get_func = o => o.strTestedByOffice, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { if (o.strTestedByOffice != c.strTestedByOffice || o.IsRIRPropChanged(_str_strTestedByOffice, c)) { m.Add(_str_strTestedByOffice, o.ObjectIdent + _str_strTestedByOffice, o.ObjectIdent2 + _str_strTestedByOffice, o.ObjectIdent3 + _str_strTestedByOffice, "string", o.strTestedByOffice == null ? "" : o.strTestedByOffice.ToString(), o.IsReadOnly(_str_strTestedByOffice), o.IsInvisible(_str_strTestedByOffice), o.IsRequired(_str_strTestedByOffice)); } } }, new field_info { _name = _str_strTestedByPerson, _formname = _str_strTestedByPerson, _type = "string", _get_func = o => o.strTestedByPerson, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { if (o.strTestedByPerson != c.strTestedByPerson || o.IsRIRPropChanged(_str_strTestedByPerson, c)) { m.Add(_str_strTestedByPerson, o.ObjectIdent + _str_strTestedByPerson, o.ObjectIdent2 + _str_strTestedByPerson, o.ObjectIdent3 + _str_strTestedByPerson, "string", o.strTestedByPerson == null ? "" : o.strTestedByPerson.ToString(), o.IsReadOnly(_str_strTestedByPerson), o.IsInvisible(_str_strTestedByPerson), o.IsRequired(_str_strTestedByPerson)); } } }, new field_info { _name = _str_strSampleFieldBarcode, _formname = _str_strSampleFieldBarcode, _type = "string", _get_func = o => o.strSampleFieldBarcode, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { if (o.strSampleFieldBarcode != c.strSampleFieldBarcode || o.IsRIRPropChanged(_str_strSampleFieldBarcode, c)) { m.Add(_str_strSampleFieldBarcode, o.ObjectIdent + _str_strSampleFieldBarcode, o.ObjectIdent2 + _str_strSampleFieldBarcode, o.ObjectIdent3 + _str_strSampleFieldBarcode, "string", o.strSampleFieldBarcode == null ? "" : o.strSampleFieldBarcode.ToString(), o.IsReadOnly(_str_strSampleFieldBarcode), o.IsInvisible(_str_strSampleFieldBarcode), o.IsRequired(_str_strSampleFieldBarcode)); } } }, new field_info { _name = _str_strVectorSubTypeName, _formname = _str_strVectorSubTypeName, _type = "string", _get_func = o => o.strVectorSubTypeName, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { if (o.strVectorSubTypeName != c.strVectorSubTypeName || o.IsRIRPropChanged(_str_strVectorSubTypeName, c)) { m.Add(_str_strVectorSubTypeName, o.ObjectIdent + _str_strVectorSubTypeName, o.ObjectIdent2 + _str_strVectorSubTypeName, o.ObjectIdent3 + _str_strVectorSubTypeName, "string", o.strVectorSubTypeName == null ? "" : o.strVectorSubTypeName.ToString(), o.IsReadOnly(_str_strVectorSubTypeName), o.IsInvisible(_str_strVectorSubTypeName), o.IsRequired(_str_strVectorSubTypeName)); } } }, new field_info { _name = _str_ParentVector, _formname = _str_ParentVector, _type = "Vector", _get_func = o => o.ParentVector, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { } }, new field_info { _name = _str_Samples, _formname = _str_Samples, _type = "EditableList<VectorSample>", _get_func = o => o.Samples, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { } }, new field_info { _name = _str_SamplesSelectList, _formname = _str_SamplesSelectList, _type = "BvSelectList", _get_func = o => o.SamplesSelectList, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { } }, new field_info { _name = _str_ParentSample, _formname = _str_ParentSample, _type = "VectorSample", _get_func = o => o.ParentSample, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { } }, new field_info { _name = _str_CaseObjectIdent, _formname = _str_CaseObjectIdent, _type = "string", _get_func = o => o.CaseObjectIdent, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { if (o.CaseObjectIdent != c.CaseObjectIdent || o.IsRIRPropChanged(_str_CaseObjectIdent, c)) { m.Add(_str_CaseObjectIdent, o.ObjectIdent + _str_CaseObjectIdent, o.ObjectIdent2 + _str_CaseObjectIdent, o.ObjectIdent3 + _str_CaseObjectIdent, "string", o.CaseObjectIdent == null ? "" : o.CaseObjectIdent.ToString(), o.IsReadOnly(_str_CaseObjectIdent), o.IsInvisible(_str_CaseObjectIdent), o.IsRequired(_str_CaseObjectIdent)); } } }, new field_info { _name = _str_Vectors, _formname = _str_Vectors, _type = "EditableList<Vector>", _get_func = o => o.Vectors, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { } }, new field_info { _name = _str_TestType, _formname = _str_TestType, _type = "Lookup", _get_func = o => { if (o.TestType == null) return null; return o.TestType.idfsPensideTestName; }, _set_func = (o, val) => { o.TestType = o.TestTypeLookup.Where(c => c.idfsPensideTestName.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m, g) => { bool bChangeLookupContent = o.IsLookupContentChanged(g, _str_TestType, c); if (o.idfsPensideTestName != c.idfsPensideTestName || o.IsRIRPropChanged(_str_TestType, c) || bChangeLookupContent) { m.Add(_str_TestType, o.ObjectIdent + _str_TestType, o.ObjectIdent2 + _str_TestType, o.ObjectIdent3 + _str_TestType, "Lookup", o.idfsPensideTestName == null ? "" : o.idfsPensideTestName.ToString(), o.IsReadOnly(_str_TestType), o.IsInvisible(_str_TestType), o.IsRequired(_str_TestType), bChangeLookupContent ? o.TestTypeLookup.Select(i => new CompareModel.ComboBoxItem() { id = i.KeyLookup, name = i.ToStringProp }).ToList() : null); } } }, new field_info { _name = _str_TestType + "Lookup", _formname = _str_TestType + "Lookup", _type = "LookupContent", _get_func = o => o.TestTypeLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { }, }, new field_info { _name = _str_TestCategory, _formname = _str_TestCategory, _type = "Lookup", _get_func = o => { if (o.TestCategory == null) return null; return o.TestCategory.idfsBaseReference; }, _set_func = (o, val) => { o.TestCategory = o.TestCategoryLookup.Where(c => c.idfsBaseReference.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m, g) => { bool bChangeLookupContent = o.IsLookupContentChanged(g, _str_TestCategory, c); if (o.idfsPensideTestCategory != c.idfsPensideTestCategory || o.IsRIRPropChanged(_str_TestCategory, c) || bChangeLookupContent) { m.Add(_str_TestCategory, o.ObjectIdent + _str_TestCategory, o.ObjectIdent2 + _str_TestCategory, o.ObjectIdent3 + _str_TestCategory, "Lookup", o.idfsPensideTestCategory == null ? "" : o.idfsPensideTestCategory.ToString(), o.IsReadOnly(_str_TestCategory), o.IsInvisible(_str_TestCategory), o.IsRequired(_str_TestCategory), bChangeLookupContent ? o.TestCategoryLookup.Select(i => new CompareModel.ComboBoxItem() { id = i.KeyLookup, name = i.ToStringProp }).ToList() : null); } } }, new field_info { _name = _str_TestCategory + "Lookup", _formname = _str_TestCategory + "Lookup", _type = "LookupContent", _get_func = o => o.TestCategoryLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { }, }, new field_info { _name = _str_Diagnosis, _formname = _str_Diagnosis, _type = "Lookup", _get_func = o => { if (o.Diagnosis == null) return null; return o.Diagnosis.idfsDiagnosis; }, _set_func = (o, val) => { o.Diagnosis = o.DiagnosisLookup.Where(c => c.idfsDiagnosis.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m, g) => { bool bChangeLookupContent = o.IsLookupContentChanged(g, _str_Diagnosis, c); if (o.idfsDiagnosis != c.idfsDiagnosis || o.IsRIRPropChanged(_str_Diagnosis, c) || bChangeLookupContent) { m.Add(_str_Diagnosis, o.ObjectIdent + _str_Diagnosis, o.ObjectIdent2 + _str_Diagnosis, o.ObjectIdent3 + _str_Diagnosis, "Lookup", o.idfsDiagnosis == null ? "" : o.idfsDiagnosis.ToString(), o.IsReadOnly(_str_Diagnosis), o.IsInvisible(_str_Diagnosis), o.IsRequired(_str_Diagnosis), bChangeLookupContent ? o.DiagnosisLookup.Select(i => new CompareModel.ComboBoxItem() { id = i.KeyLookup, name = i.ToStringProp }).ToList() : null); } } }, new field_info { _name = _str_Diagnosis + "Lookup", _formname = _str_Diagnosis + "Lookup", _type = "LookupContent", _get_func = o => o.DiagnosisLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { }, }, new field_info { _name = _str_TestResult, _formname = _str_TestResult, _type = "Lookup", _get_func = o => { if (o.TestResult == null) return null; return o.TestResult.idfsPensideTestResult; }, _set_func = (o, val) => { o.TestResult = o.TestResultLookup.Where(c => c.idfsPensideTestResult.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m, g) => { bool bChangeLookupContent = o.IsLookupContentChanged(g, _str_TestResult, c); if (o.idfsPensideTestResult != c.idfsPensideTestResult || o.IsRIRPropChanged(_str_TestResult, c) || bChangeLookupContent) { m.Add(_str_TestResult, o.ObjectIdent + _str_TestResult, o.ObjectIdent2 + _str_TestResult, o.ObjectIdent3 + _str_TestResult, "Lookup", o.idfsPensideTestResult == null ? "" : o.idfsPensideTestResult.ToString(), o.IsReadOnly(_str_TestResult), o.IsInvisible(_str_TestResult), o.IsRequired(_str_TestResult), bChangeLookupContent ? o.TestResultLookup.Select(i => new CompareModel.ComboBoxItem() { id = i.KeyLookup, name = i.ToStringProp }).ToList() : null); } } }, new field_info { _name = _str_TestResult + "Lookup", _formname = _str_TestResult + "Lookup", _type = "LookupContent", _get_func = o => o.TestResultLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { }, }, new field_info { _name = _str_DiagnosisFiltered, _formname = _str_DiagnosisFiltered, _type = "Lookup", _get_func = o => { if (o.DiagnosisFiltered == null) return null; return o.DiagnosisFiltered.idfsDiagnosis; }, _set_func = (o, val) => { o.DiagnosisFiltered = o.DiagnosisFilteredLookup.Where(c => c.idfsDiagnosis.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m, g) => { bool bChangeLookupContent = o.IsLookupContentChanged(g, _str_DiagnosisFiltered, c); if (o.idfsDiagnosis != c.idfsDiagnosis || o.IsRIRPropChanged(_str_DiagnosisFiltered, c) || bChangeLookupContent) { m.Add(_str_DiagnosisFiltered, o.ObjectIdent + _str_DiagnosisFiltered, o.ObjectIdent2 + _str_DiagnosisFiltered, o.ObjectIdent3 + _str_DiagnosisFiltered, "Lookup", o.idfsDiagnosis == null ? "" : o.idfsDiagnosis.ToString(), o.IsReadOnly(_str_DiagnosisFiltered), o.IsInvisible(_str_DiagnosisFiltered), o.IsRequired(_str_DiagnosisFiltered), bChangeLookupContent ? o.DiagnosisFilteredLookup.Select(i => new CompareModel.ComboBoxItem() { id = i.KeyLookup, name = i.ToStringProp }).ToList() : null); } } }, new field_info { _name = _str_DiagnosisFiltered + "Lookup", _formname = _str_DiagnosisFiltered + "Lookup", _type = "LookupContent", _get_func = o => o.DiagnosisFilteredLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { }, }, new field_info { _name = _str_TestResultFiltered, _formname = _str_TestResultFiltered, _type = "Lookup", _get_func = o => { if (o.TestResultFiltered == null) return null; return o.TestResultFiltered.idfsPensideTestResult; }, _set_func = (o, val) => { o.TestResultFiltered = o.TestResultFilteredLookup.Where(c => c.idfsPensideTestResult.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m, g) => { bool bChangeLookupContent = o.IsLookupContentChanged(g, _str_TestResultFiltered, c); if (o.idfsPensideTestResult != c.idfsPensideTestResult || o.IsRIRPropChanged(_str_TestResultFiltered, c) || bChangeLookupContent) { m.Add(_str_TestResultFiltered, o.ObjectIdent + _str_TestResultFiltered, o.ObjectIdent2 + _str_TestResultFiltered, o.ObjectIdent3 + _str_TestResultFiltered, "Lookup", o.idfsPensideTestResult == null ? "" : o.idfsPensideTestResult.ToString(), o.IsReadOnly(_str_TestResultFiltered), o.IsInvisible(_str_TestResultFiltered), o.IsRequired(_str_TestResultFiltered), bChangeLookupContent ? o.TestResultFilteredLookup.Select(i => new CompareModel.ComboBoxItem() { id = i.KeyLookup, name = i.ToStringProp }).ToList() : null); } } }, new field_info { _name = _str_TestResultFiltered + "Lookup", _formname = _str_TestResultFiltered + "Lookup", _type = "LookupContent", _get_func = o => o.TestResultFilteredLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { }, }, new field_info { _name = _str_TestedByPerson, _formname = _str_TestedByPerson, _type = "Lookup", _get_func = o => { if (o.TestedByPerson == null) return null; return o.TestedByPerson.idfPerson; }, _set_func = (o, val) => { o.TestedByPerson = o.TestedByPersonLookup.Where(c => c.idfPerson.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m, g) => { bool bChangeLookupContent = o.IsLookupContentChanged(g, _str_TestedByPerson, c); if (o.idfTestedByPerson != c.idfTestedByPerson || o.IsRIRPropChanged(_str_TestedByPerson, c) || bChangeLookupContent) { m.Add(_str_TestedByPerson, o.ObjectIdent + _str_TestedByPerson, o.ObjectIdent2 + _str_TestedByPerson, o.ObjectIdent3 + _str_TestedByPerson, "Lookup", o.idfTestedByPerson == null ? "" : o.idfTestedByPerson.ToString(), o.IsReadOnly(_str_TestedByPerson), o.IsInvisible(_str_TestedByPerson), o.IsRequired(_str_TestedByPerson), bChangeLookupContent ? o.TestedByPersonLookup.Select(i => new CompareModel.ComboBoxItem() { id = i.KeyLookup, name = i.ToStringProp }).ToList() : null); } } }, new field_info { _name = _str_TestedByPerson + "Lookup", _formname = _str_TestedByPerson + "Lookup", _type = "LookupContent", _get_func = o => o.TestedByPersonLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { }, }, new field_info { _name = _str_TestedByOffice, _formname = _str_TestedByOffice, _type = "Lookup", _get_func = o => { if (o.TestedByOffice == null) return null; return o.TestedByOffice.idfInstitution; }, _set_func = (o, val) => { o.TestedByOffice = o.TestedByOfficeLookup.Where(c => c.idfInstitution.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m, g) => { bool bChangeLookupContent = o.IsLookupContentChanged(g, _str_TestedByOffice, c); if (o.idfTestedByOffice != c.idfTestedByOffice || o.IsRIRPropChanged(_str_TestedByOffice, c) || bChangeLookupContent) { m.Add(_str_TestedByOffice, o.ObjectIdent + _str_TestedByOffice, o.ObjectIdent2 + _str_TestedByOffice, o.ObjectIdent3 + _str_TestedByOffice, "Lookup", o.idfTestedByOffice == null ? "" : o.idfTestedByOffice.ToString(), o.IsReadOnly(_str_TestedByOffice), o.IsInvisible(_str_TestedByOffice), o.IsRequired(_str_TestedByOffice), bChangeLookupContent ? o.TestedByOfficeLookup.Select(i => new CompareModel.ComboBoxItem() { id = i.KeyLookup, name = i.ToStringProp }).ToList() : null); } } }, new field_info { _name = _str_TestedByOffice + "Lookup", _formname = _str_TestedByOffice + "Lookup", _type = "LookupContent", _get_func = o => o.TestedByOfficeLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m, g) => { }, }, new field_info() }; #endregion private string _getType(string name) { var i = _field_infos.FirstOrDefault(n => n._name == name); return i == null ? "" : i._type; } private object _getValue(string name) { var i = _field_infos.FirstOrDefault(n => n._name == name); return i == null ? null : i._get_func(this); } private void _setValue(string name, string val) { var i = _field_infos.FirstOrDefault(n => n._name == name); if (i != null) i._set_func(this, val); } internal CompareModel _compare(IObject o, CompareModel ret) { if (ret == null) ret = new CompareModel(); if (o == null) return ret; VectorFieldTest obj = (VectorFieldTest)o; using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { Accessor.Instance(null)._LoadLookups(manager, obj); foreach (var i in _field_infos) if (i != null && i._compare_func != null) i._compare_func(this, obj, ret, manager); } return ret; } #endregion [LocalizedDisplayName(_str_TestType)] [Relation(typeof(PensideTestLookup), eidss.model.Schema.PensideTestLookup._str_idfsPensideTestName, _str_idfsPensideTestName)] public PensideTestLookup TestType { get { return _TestType == null ? null : ((long)_TestType.Key == 0 ? null : _TestType); } set { var oldVal = _TestType; _TestType = value == null ? null : ((long) value.Key == 0 ? null : value); if (_TestType != oldVal) { if (idfsPensideTestName != (_TestType == null ? new Int64?() : (Int64?)_TestType.idfsPensideTestName)) idfsPensideTestName = _TestType == null ? new Int64?() : (Int64?)_TestType.idfsPensideTestName; OnPropertyChanged(_str_TestType); } } } private PensideTestLookup _TestType; public List<PensideTestLookup> TestTypeLookup { get { return _TestTypeLookup; } } private List<PensideTestLookup> _TestTypeLookup = new List<PensideTestLookup>(); [LocalizedDisplayName(_str_TestCategory)] [Relation(typeof(BaseReference), eidss.model.Schema.BaseReference._str_idfsBaseReference, _str_idfsPensideTestCategory)] public BaseReference TestCategory { get { return _TestCategory == null ? null : ((long)_TestCategory.Key == 0 ? null : _TestCategory); } set { var oldVal = _TestCategory; _TestCategory = value == null ? null : ((long) value.Key == 0 ? null : value); if (_TestCategory != oldVal) { if (idfsPensideTestCategory != (_TestCategory == null ? new Int64?() : (Int64?)_TestCategory.idfsBaseReference)) idfsPensideTestCategory = _TestCategory == null ? new Int64?() : (Int64?)_TestCategory.idfsBaseReference; OnPropertyChanged(_str_TestCategory); } } } private BaseReference _TestCategory; public BaseReferenceList TestCategoryLookup { get { return _TestCategoryLookup; } } private BaseReferenceList _TestCategoryLookup = new BaseReferenceList("rftPensideTestCategory"); [LocalizedDisplayName(_str_Diagnosis)] [Relation(typeof(Diagnosis2PensideTestMatrixLookup), eidss.model.Schema.Diagnosis2PensideTestMatrixLookup._str_idfsDiagnosis, _str_idfsDiagnosis)] public Diagnosis2PensideTestMatrixLookup Diagnosis { get { return _Diagnosis == null ? null : ((long)_Diagnosis.Key == 0 ? null : _Diagnosis); } set { var oldVal = _Diagnosis; _Diagnosis = value == null ? null : ((long) value.Key == 0 ? null : value); if (_Diagnosis != oldVal) { if (idfsDiagnosis != (_Diagnosis == null ? new Int64?() : (Int64?)_Diagnosis.idfsDiagnosis)) idfsDiagnosis = _Diagnosis == null ? new Int64?() : (Int64?)_Diagnosis.idfsDiagnosis; OnPropertyChanged(_str_Diagnosis); } } } private Diagnosis2PensideTestMatrixLookup _Diagnosis; public List<Diagnosis2PensideTestMatrixLookup> DiagnosisLookup { get { return _DiagnosisLookup; } } private List<Diagnosis2PensideTestMatrixLookup> _DiagnosisLookup = new List<Diagnosis2PensideTestMatrixLookup>(); [LocalizedDisplayName(_str_TestResult)] [Relation(typeof(TypeFieldTestToResultMatrixLookup), eidss.model.Schema.TypeFieldTestToResultMatrixLookup._str_idfsPensideTestResult, _str_idfsPensideTestResult)] public TypeFieldTestToResultMatrixLookup TestResult { get { return _TestResult == null ? null : ((long)_TestResult.Key == 0 ? null : _TestResult); } set { var oldVal = _TestResult; _TestResult = value == null ? null : ((long) value.Key == 0 ? null : value); if (_TestResult != oldVal) { if (idfsPensideTestResult != (_TestResult == null ? new Int64?() : (Int64?)_TestResult.idfsPensideTestResult)) idfsPensideTestResult = _TestResult == null ? new Int64?() : (Int64?)_TestResult.idfsPensideTestResult; OnPropertyChanged(_str_TestResult); } } } private TypeFieldTestToResultMatrixLookup _TestResult; public List<TypeFieldTestToResultMatrixLookup> TestResultLookup { get { return _TestResultLookup; } } private List<TypeFieldTestToResultMatrixLookup> _TestResultLookup = new List<TypeFieldTestToResultMatrixLookup>(); [LocalizedDisplayName(_str_DiagnosisFiltered)] [Relation(typeof(Diagnosis2PensideTestMatrixLookup), eidss.model.Schema.Diagnosis2PensideTestMatrixLookup._str_idfsDiagnosis, _str_idfsDiagnosis)] public Diagnosis2PensideTestMatrixLookup DiagnosisFiltered { get { return _DiagnosisFiltered == null ? null : ((long)_DiagnosisFiltered.Key == 0 ? null : _DiagnosisFiltered); } set { var oldVal = _DiagnosisFiltered; _DiagnosisFiltered = value == null ? null : ((long) value.Key == 0 ? null : value); if (_DiagnosisFiltered != oldVal) { if (idfsDiagnosis != (_DiagnosisFiltered == null ? new Int64?() : (Int64?)_DiagnosisFiltered.idfsDiagnosis)) idfsDiagnosis = _DiagnosisFiltered == null ? new Int64?() : (Int64?)_DiagnosisFiltered.idfsDiagnosis; OnPropertyChanged(_str_DiagnosisFiltered); } } } private Diagnosis2PensideTestMatrixLookup _DiagnosisFiltered; public List<Diagnosis2PensideTestMatrixLookup> DiagnosisFilteredLookup { get { return _DiagnosisFilteredLookup; } } private List<Diagnosis2PensideTestMatrixLookup> _DiagnosisFilteredLookup = new List<Diagnosis2PensideTestMatrixLookup>(); [LocalizedDisplayName(_str_TestResultFiltered)] [Relation(typeof(TypeFieldTestToResultMatrixLookup), eidss.model.Schema.TypeFieldTestToResultMatrixLookup._str_idfsPensideTestResult, _str_idfsPensideTestResult)] public TypeFieldTestToResultMatrixLookup TestResultFiltered { get { return _TestResultFiltered == null ? null : ((long)_TestResultFiltered.Key == 0 ? null : _TestResultFiltered); } set { var oldVal = _TestResultFiltered; _TestResultFiltered = value == null ? null : ((long) value.Key == 0 ? null : value); if (_TestResultFiltered != oldVal) { if (idfsPensideTestResult != (_TestResultFiltered == null ? new Int64?() : (Int64?)_TestResultFiltered.idfsPensideTestResult)) idfsPensideTestResult = _TestResultFiltered == null ? new Int64?() : (Int64?)_TestResultFiltered.idfsPensideTestResult; OnPropertyChanged(_str_TestResultFiltered); } } } private TypeFieldTestToResultMatrixLookup _TestResultFiltered; public List<TypeFieldTestToResultMatrixLookup> TestResultFilteredLookup { get { return _TestResultFilteredLookup; } } private List<TypeFieldTestToResultMatrixLookup> _TestResultFilteredLookup = new List<TypeFieldTestToResultMatrixLookup>(); [LocalizedDisplayName(_str_TestedByPerson)] [Relation(typeof(PersonLookup), eidss.model.Schema.PersonLookup._str_idfPerson, _str_idfTestedByPerson)] public PersonLookup TestedByPerson { get { return _TestedByPerson == null ? null : ((long)_TestedByPerson.Key == 0 ? null : _TestedByPerson); } set { var oldVal = _TestedByPerson; _TestedByPerson = value == null ? null : ((long) value.Key == 0 ? null : value); if (_TestedByPerson != oldVal) { if (idfTestedByPerson != (_TestedByPerson == null ? new Int64?() : (Int64?)_TestedByPerson.idfPerson)) idfTestedByPerson = _TestedByPerson == null ? new Int64?() : (Int64?)_TestedByPerson.idfPerson; OnPropertyChanged(_str_TestedByPerson); } } } private PersonLookup _TestedByPerson; public List<PersonLookup> TestedByPersonLookup { get { return _TestedByPersonLookup; } } private List<PersonLookup> _TestedByPersonLookup = new List<PersonLookup>(); [LocalizedDisplayName(_str_TestedByOffice)] [Relation(typeof(OrganizationLookup), eidss.model.Schema.OrganizationLookup._str_idfInstitution, _str_idfTestedByOffice)] public OrganizationLookup TestedByOffice { get { return _TestedByOffice == null ? null : ((long)_TestedByOffice.Key == 0 ? null : _TestedByOffice); } set { var oldVal = _TestedByOffice; _TestedByOffice = value == null ? null : ((long) value.Key == 0 ? null : value); if (_TestedByOffice != oldVal) { if (idfTestedByOffice != (_TestedByOffice == null ? new Int64?() : (Int64?)_TestedByOffice.idfInstitution)) idfTestedByOffice = _TestedByOffice == null ? new Int64?() : (Int64?)_TestedByOffice.idfInstitution; OnPropertyChanged(_str_TestedByOffice); } } } private OrganizationLookup _TestedByOffice; public List<OrganizationLookup> TestedByOfficeLookup { get { return _TestedByOfficeLookup; } } private List<OrganizationLookup> _TestedByOfficeLookup = new List<OrganizationLookup>(); private BvSelectList _getList(string name) { switch(name) { case _str_TestType: return new BvSelectList(TestTypeLookup, eidss.model.Schema.PensideTestLookup._str_idfsPensideTestName, null, TestType, _str_idfsPensideTestName); case _str_TestCategory: return new BvSelectList(TestCategoryLookup, eidss.model.Schema.BaseReference._str_idfsBaseReference, null, TestCategory, _str_idfsPensideTestCategory); case _str_Diagnosis: return new BvSelectList(DiagnosisLookup, eidss.model.Schema.Diagnosis2PensideTestMatrixLookup._str_idfsDiagnosis, null, Diagnosis, _str_idfsDiagnosis); case _str_TestResult: return new BvSelectList(TestResultLookup, eidss.model.Schema.TypeFieldTestToResultMatrixLookup._str_idfsPensideTestResult, null, TestResult, _str_idfsPensideTestResult); case _str_DiagnosisFiltered: return new BvSelectList(DiagnosisFilteredLookup, eidss.model.Schema.Diagnosis2PensideTestMatrixLookup._str_idfsDiagnosis, null, DiagnosisFiltered, _str_idfsDiagnosis); case _str_TestResultFiltered: return new BvSelectList(TestResultFilteredLookup, eidss.model.Schema.TypeFieldTestToResultMatrixLookup._str_idfsPensideTestResult, null, TestResultFiltered, _str_idfsPensideTestResult); case _str_TestedByPerson: return new BvSelectList(TestedByPersonLookup, eidss.model.Schema.PersonLookup._str_idfPerson, null, TestedByPerson, _str_idfTestedByPerson); case _str_TestedByOffice: return new BvSelectList(TestedByOfficeLookup, eidss.model.Schema.OrganizationLookup._str_idfInstitution, null, TestedByOffice, _str_idfTestedByOffice); } return null; } [XmlIgnore] [LocalizedDisplayName("strPensideTypeName")] public string strPensideTestName { get { return new Func<VectorFieldTest, string>(c => c.TestType == null ? String.Empty : c.TestType.strPensideTypeName)(this); } } [XmlIgnore] [LocalizedDisplayName("idfPensideTestTestCategory")] public string strPensideTestCategory { get { return new Func<VectorFieldTest, string>(c => c.TestCategory == null ? String.Empty : c.TestCategory.name)(this); } } [XmlIgnore] [LocalizedDisplayName("FT.PensideTestResult")] public string strPensideTestResult { get { return new Func<VectorFieldTest, string>(c => c.TestResultFiltered == null ? String.Empty : c.TestResultFiltered.strPensideTestResultName)(this); } } [XmlIgnore] [LocalizedDisplayName("FT.strDisease")] public string strDiagnosis { get { return new Func<VectorFieldTest, string>(c => c.DiagnosisFiltered == null ? String.Empty : c.DiagnosisFiltered.DiagnosisName)(this); } } [XmlIgnore] [LocalizedDisplayName("idfPensideTestTestedByOffice")] public string strTestedByOffice { get { return new Func<VectorFieldTest, string>(c => c.TestedByOffice == null ? String.Empty : c.TestedByOffice.name)(this); } } [XmlIgnore] [LocalizedDisplayName("idfPensideTestTestedByPerson")] public string strTestedByPerson { get { return new Func<VectorFieldTest, string>(c => c.TestedByPerson == null ? String.Empty : c.TestedByPerson.FullName)(this); } } [XmlIgnore] [LocalizedDisplayName("VectorSample.strFieldBarcode")] public string strSampleFieldBarcode { get { return new Func<VectorFieldTest, string>(c => c.ParentSample == null ? String.Empty : c.ParentSample.strFieldBarcode)(this); } } [XmlIgnore] [LocalizedDisplayName("idfsVectorSubType")] public string strVectorSubTypeName { get { return new Func<VectorFieldTest, string>(c => ((c.ParentVector != null) && (c.ParentVector.VectorSubType != null)) ? c.ParentVector.VectorSubType.name : String.Empty)(this); } } [XmlIgnore] [LocalizedDisplayName(_str_ParentVector)] public Vector ParentVector { get { return new Func<VectorFieldTest, Vector>(c => Parent as Vector)(this); } } [XmlIgnore] [LocalizedDisplayName(_str_Samples)] public EditableList<VectorSample> Samples { get { return new Func<VectorFieldTest, EditableList<VectorSample>>(c => c.ParentVector == null ? new EditableList<VectorSample>() : c.ParentVector.Samples)(this); } } [XmlIgnore] [LocalizedDisplayName(_str_SamplesSelectList)] public BvSelectList SamplesSelectList { get { return new Func<VectorFieldTest, BvSelectList>(c => c.Samples == null ? null : new BvSelectList(c.Samples, "idfMaterial", "strFieldBarcode", c.ParentSample, "idfMaterial"))(this); } } [XmlIgnore] [LocalizedDisplayName(_str_ParentSample)] public VectorSample ParentSample { get { return new Func<VectorFieldTest, VectorSample>(c => c.Samples == null ? null : c.Samples.FirstOrDefault(s => s.idfMaterial == c.idfMaterial))(this); } } [XmlIgnore] [LocalizedDisplayName(_str_CaseObjectIdent)] public string CaseObjectIdent { get { return new Func<VectorFieldTest, string>(c => "Vectors_" + c.idfVectorSurveillanceSession + "_")(this); } } [XmlIgnore] [LocalizedDisplayName(_str_Vectors)] public EditableList<Vector> Vectors { get { return new Func<VectorFieldTest, EditableList<Vector>>(c => c.ParentVector == null ? new EditableList<Vector>() : c.ParentVector.Vectors)(this); } } protected CacheScope m_CS; protected Accessor _getAccessor() { return Accessor.Instance(m_CS); } private IObjectPermissions m_permissions = null; internal IObjectPermissions _permissions { get { return m_permissions; } set { m_permissions = value; } } internal string m_ObjectName = "VectorFieldTest"; #region Parent and Clone supporting [XmlIgnore] public IObject Parent { get { return m_Parent; } set { m_Parent = value; /*OnPropertyChanged(_str_Parent);*/ } } private IObject m_Parent; internal void _setParent() { } partial void Cloned(); partial void ClonedWithSetup(); private bool bIsClone; public override object Clone() { var ret = base.Clone() as VectorFieldTest; ret.bIsClone = true; ret.Cloned(); ret.m_Parent = this.Parent; ret.m_IsMarkedToDelete = this.m_IsMarkedToDelete; ret.m_IsForcedToDelete = this.m_IsForcedToDelete; ret._setParent(); if (this.IsDirty && !ret.IsDirty) ret.SetChange(); else if (!this.IsDirty && ret.IsDirty) ret.RejectChanges(); return ret; } public IObject CloneWithSetup(DbManagerProxy manager, bool bRestricted = false) { var ret = base.Clone() as VectorFieldTest; ret.m_Parent = this.Parent; ret.m_IsMarkedToDelete = this.m_IsMarkedToDelete; ret.m_IsForcedToDelete = this.m_IsForcedToDelete; ret.m_IsNew = this.IsNew; ret.m_ObjectName = this.m_ObjectName; Accessor.Instance(null)._SetupLoad(manager, ret, true); ret.ClonedWithSetup(); ret.DeepAcceptChanges(); ret._setParent(); ret._permissions = _permissions; return ret; } public VectorFieldTest CloneWithSetup() { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { return CloneWithSetup(manager) as VectorFieldTest; } } #endregion #region IObject implementation public object Key { get { return idfPensideTest; } } public string KeyName { get { return "idfPensideTest"; } } public object KeyLookup { get { return idfPensideTest; } } public string ToStringProp { get { return ToString(); } } private bool m_IsNew; public bool IsNew { get { return m_IsNew; } } [XmlIgnore] [LocalizedDisplayName("HasChanges")] public bool HasChanges { get { return IsDirty ; } } public new void RejectChanges() { var _prev_idfsPensideTestName_TestType = idfsPensideTestName; var _prev_idfsPensideTestCategory_TestCategory = idfsPensideTestCategory; var _prev_idfsDiagnosis_Diagnosis = idfsDiagnosis; var _prev_idfsPensideTestResult_TestResult = idfsPensideTestResult; var _prev_idfsDiagnosis_DiagnosisFiltered = idfsDiagnosis; var _prev_idfsPensideTestResult_TestResultFiltered = idfsPensideTestResult; var _prev_idfTestedByPerson_TestedByPerson = idfTestedByPerson; var _prev_idfTestedByOffice_TestedByOffice = idfTestedByOffice; base.RejectChanges(); if (_prev_idfsPensideTestName_TestType != idfsPensideTestName) { _TestType = _TestTypeLookup.FirstOrDefault(c => c.idfsPensideTestName == idfsPensideTestName); } if (_prev_idfsPensideTestCategory_TestCategory != idfsPensideTestCategory) { _TestCategory = _TestCategoryLookup.FirstOrDefault(c => c.idfsBaseReference == idfsPensideTestCategory); } if (_prev_idfsDiagnosis_Diagnosis != idfsDiagnosis) { _Diagnosis = _DiagnosisLookup.FirstOrDefault(c => c.idfsDiagnosis == idfsDiagnosis); } if (_prev_idfsPensideTestResult_TestResult != idfsPensideTestResult) { _TestResult = _TestResultLookup.FirstOrDefault(c => c.idfsPensideTestResult == idfsPensideTestResult); } if (_prev_idfsDiagnosis_DiagnosisFiltered != idfsDiagnosis) { _DiagnosisFiltered = _DiagnosisFilteredLookup.FirstOrDefault(c => c.idfsDiagnosis == idfsDiagnosis); } if (_prev_idfsPensideTestResult_TestResultFiltered != idfsPensideTestResult) { _TestResultFiltered = _TestResultFilteredLookup.FirstOrDefault(c => c.idfsPensideTestResult == idfsPensideTestResult); } if (_prev_idfTestedByPerson_TestedByPerson != idfTestedByPerson) { _TestedByPerson = _TestedByPersonLookup.FirstOrDefault(c => c.idfPerson == idfTestedByPerson); } if (_prev_idfTestedByOffice_TestedByOffice != idfTestedByOffice) { _TestedByOffice = _TestedByOfficeLookup.FirstOrDefault(c => c.idfInstitution == idfTestedByOffice); } } public void DeepRejectChanges() { RejectChanges(); } public void DeepAcceptChanges() { AcceptChanges(); } private bool m_bForceDirty; public override void AcceptChanges() { m_bForceDirty = false; base.AcceptChanges(); } [XmlIgnore] [LocalizedDisplayName("IsDirty")] public override bool IsDirty { get { return m_bForceDirty || base.IsDirty; } } public void SetChange() { m_bForceDirty = true; } public void DeepSetChange() { SetChange(); } public bool MarkToDelete() { return _Delete(false); } public string ObjectName { get { return m_ObjectName; } } public string ObjectIdent { get { return ObjectName + "_" + Key.ToString() + "_"; } } public string ObjectIdent2 { get { return ObjectIdent; } } public string ObjectIdent3 { get { return ObjectIdent; } } public IObjectAccessor GetAccessor() { return _getAccessor(); } public IObjectPermissions GetPermissions() { return _permissions; } private IObjectEnvironment _environment; public IObjectEnvironment Environment { get { return _environment; } set { _environment = value; } } public bool IsValidObject { get { return _isValid; } } public bool ReadOnly { get { return _readOnly || !_isValid; } set { _readOnly = value; } } public bool IsReadOnly(string name) { return _isReadOnly(name); } public bool IsInvisible(string name) { return _isInvisible(name); } public bool IsRequired(string name) { return _isRequired(m_isRequired, name); } public bool IsHiddenPersonalData(string name) { return _isHiddenPersonalData(name); } public string GetType(string name) { return _getType(name); } public object GetValue(string name) { return _getValue(name); } public void SetValue(string name, string val) { _setValue(name, val); } public CompareModel Compare(IObject o) { return _compare(o, null); } public BvSelectList GetList(string name) { return _getList(name); } public event ValidationEvent Validation; public event ValidationEvent ValidationEnd; public event AfterPostEvent AfterPost; public Dictionary<string, string> GetFieldTags(string name) { return null; } #endregion private bool IsRIRPropChanged(string fld, VectorFieldTest c) { return IsReadOnly(fld) != c.IsReadOnly(fld) || IsInvisible(fld) != c.IsInvisible(fld) || IsRequired(fld) != c._isRequired(m_isRequired, fld); } private bool IsLookupContentChanged(DbManagerProxy manager, string fld, VectorFieldTest c) { var thisLookup = GetValue(fld + "Lookup") as IList; var thatLookup = c.GetValue(fld + "Lookup") as IList; bool bChangeLookupContent = thisLookup.Count != thatLookup.Count; if (!bChangeLookupContent) { for (int i = 0; i < thisLookup.Count; i++) { if (((thisLookup[i] as IObject).Key as IComparable).CompareTo((thatLookup[i] as IObject).Key) != 0 && (thisLookup[i] as IObject).ToStringProp != null && ((thisLookup[i] as IObject).ToStringProp as IComparable).CompareTo((thatLookup[i] as IObject).ToStringProp) != 0) { bChangeLookupContent = true; break; } } } return bChangeLookupContent; } public VectorFieldTest() { } partial void Changed(string fieldName); partial void Created(DbManagerProxy manager); partial void Loaded(DbManagerProxy manager); partial void Deleted(); partial void ParsedFormCollection(NameValueCollection form); partial void ParsingFormCollection(NameValueCollection form); private bool m_IsForcedToDelete; [LocalizedDisplayName("IsForcedToDelete")] public bool IsForcedToDelete { get { return m_IsForcedToDelete; } } private bool m_IsMarkedToDelete; [LocalizedDisplayName("IsMarkedToDelete")] public bool IsMarkedToDelete { get { return m_IsMarkedToDelete; } } public void _SetupMainHandler() { PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(VectorFieldTest_PropertyChanged); } public void _RevokeMainHandler() { PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(VectorFieldTest_PropertyChanged); } private void VectorFieldTest_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { (sender as VectorFieldTest).Changed(e.PropertyName); if (e.PropertyName == _str_idfsPensideTestName) OnPropertyChanged(_str_strPensideTestName); if (e.PropertyName == _str_idfsPensideTestCategory) OnPropertyChanged(_str_strPensideTestCategory); if (e.PropertyName == _str_idfsPensideTestResult) OnPropertyChanged(_str_strPensideTestResult); if (e.PropertyName == _str_idfsDiagnosis) OnPropertyChanged(_str_strDiagnosis); if (e.PropertyName == _str_idfTestedByOffice) OnPropertyChanged(_str_strTestedByOffice); if (e.PropertyName == _str_idfTestedByPerson) OnPropertyChanged(_str_strTestedByPerson); if (e.PropertyName == _str_ParentSample) OnPropertyChanged(_str_strSampleFieldBarcode); if (e.PropertyName == _str_Parent) OnPropertyChanged(_str_strVectorSubTypeName); if (e.PropertyName == _str_Parent) OnPropertyChanged(_str_ParentVector); if (e.PropertyName == _str_ParentVector) OnPropertyChanged(_str_Samples); if (e.PropertyName == _str_Samples) OnPropertyChanged(_str_SamplesSelectList); if (e.PropertyName == _str_idfMaterial) OnPropertyChanged(_str_ParentSample); if (e.PropertyName == _str_idfVectorSurveillanceSession) OnPropertyChanged(_str_CaseObjectIdent); if (e.PropertyName == _str_ParentVector) OnPropertyChanged(_str_Vectors); } public bool ForceToDelete() { return _Delete(true); } internal bool _Delete(bool isForceDelete) { if (!_ValidateOnDelete()) return false; _DeletingExtenders(); m_IsMarkedToDelete = true; m_IsForcedToDelete = m_IsForcedToDelete ? m_IsForcedToDelete : isForceDelete; OnPropertyChanged("IsMarkedToDelete"); _DeletedExtenders(); Deleted(); return true; } private bool _ValidateOnDelete(bool bReport = true) { return Accessor.Instance(null).ValidateCanDelete(this); } private void _DeletingExtenders() { VectorFieldTest obj = this; } private void _DeletedExtenders() { VectorFieldTest obj = this; } public bool OnValidation(ValidationModelException ex) { if (Validation != null) { var args = new ValidationEventArgs(ex.MessageId, ex.FieldName, ex.PropertyName, ex.Pars, ex.ValidatorType, ex.Obj, ex.ValidationType); Validation(this, args); return args.Continue; } return false; } public bool OnValidationEnd(ValidationModelException ex) { if (ValidationEnd != null) { var args = new ValidationEventArgs(ex.MessageId, ex.FieldName, ex.PropertyName, ex.Pars, ex.ValidatorType, ex.Obj, ex.ValidationType); ValidationEnd(this, args); return args.Continue; } return false; } public void OnAfterPost() { if (AfterPost != null) { AfterPost(this, EventArgs.Empty); } } public FormSize FormSize { get { return FormSize.Undefined; } } private bool _isInvisible(string name) { return false; } private static string[] readonly_names1 = "TestedByPerson".Split(new char[] { ',' }); private static string[] readonly_names2 = "strSampleName,datFieldCollectionDate,strVectorID,strVectorTypeName,strVectorSubTypeName".Split(new char[] { ',' }); private bool _isReadOnly(string name) { if (readonly_names1.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VectorFieldTest, bool>(c => TestedByOffice == null)(this); if (readonly_names2.Where(c => c == name).Count() > 0) return ReadOnly || new Func<VectorFieldTest, bool>(c => true)(this); return ReadOnly || new Func<VectorFieldTest, bool>(c => false)(this); } private bool m_isValid = true; internal bool _isValid { get { return m_isValid; } set { m_isValid = value; } } private bool m_readOnly; private bool _readOnly { get { return m_readOnly; } set { m_readOnly = value; } } internal Dictionary<string, Func<VectorFieldTest, bool>> m_isRequired; private bool _isRequired(Dictionary<string, Func<VectorFieldTest, bool>> isRequiredDict, string name) { if (isRequiredDict != null && isRequiredDict.ContainsKey(name)) return isRequiredDict[name](this); return false; } public void AddRequired(string name, Func<VectorFieldTest, bool> func) { if (m_isRequired == null) m_isRequired = new Dictionary<string, Func<VectorFieldTest, bool>>(); if (!m_isRequired.ContainsKey(name)) m_isRequired.Add(name, func); } internal Dictionary<string, Func<VectorFieldTest, bool>> m_isHiddenPersonalData; private bool _isHiddenPersonalData(string name) { if (m_isHiddenPersonalData != null && m_isHiddenPersonalData.ContainsKey(name)) return m_isHiddenPersonalData[name](this); return false; } public void AddHiddenPersonalData(string name, Func<VectorFieldTest, bool> func) { if (m_isHiddenPersonalData == null) m_isHiddenPersonalData = new Dictionary<string, Func<VectorFieldTest, bool>>(); if (!m_isHiddenPersonalData.ContainsKey(name)) m_isHiddenPersonalData.Add(name, func); } #region IDisposable Members private bool bIsDisposed; protected bool bNeedLookupRemove; ~VectorFieldTest() { Dispose(); } public void Dispose() { if (!bIsDisposed) { bIsDisposed = true; m_Parent = null; m_permissions = null; this.ClearModelObjEventInvocations(); if (bNeedLookupRemove) { LookupManager.RemoveObject("PensideTestLookup", this); LookupManager.RemoveObject("rftPensideTestCategory", this); LookupManager.RemoveObject("Diagnosis2PensideTestMatrixLookup", this); LookupManager.RemoveObject("TypeFieldTestToResultMatrixLookup", this); LookupManager.RemoveObject("Diagnosis2PensideTestMatrixLookup", this); LookupManager.RemoveObject("TypeFieldTestToResultMatrixLookup", this); LookupManager.RemoveObject("PersonLookup", this); LookupManager.RemoveObject("OrganizationLookup", this); } } GC.SuppressFinalize(this); } #endregion #region ILookupUsage Members public void ReloadLookupItem(DbManagerProxy manager, string lookup_object) { if (lookup_object == "PensideTestLookup") _getAccessor().LoadLookup_TestType(manager, this); if (lookup_object == "rftPensideTestCategory") _getAccessor().LoadLookup_TestCategory(manager, this); if (lookup_object == "Diagnosis2PensideTestMatrixLookup") _getAccessor().LoadLookup_Diagnosis(manager, this); if (lookup_object == "TypeFieldTestToResultMatrixLookup") _getAccessor().LoadLookup_TestResult(manager, this); if (lookup_object == "Diagnosis2PensideTestMatrixLookup") _getAccessor().LoadLookup_DiagnosisFiltered(manager, this); if (lookup_object == "TypeFieldTestToResultMatrixLookup") _getAccessor().LoadLookup_TestResultFiltered(manager, this); if (lookup_object == "PersonLookup") _getAccessor().LoadLookup_TestedByPerson(manager, this); if (lookup_object == "OrganizationLookup") _getAccessor().LoadLookup_TestedByOffice(manager, this); } #endregion public void ParseFormCollection(NameValueCollection form, bool bParseLookups = true, bool bParseRelations = true) { ParsingFormCollection(form); if (bParseLookups) { _field_infos.Where(i => i._type == "Lookup").ToList().ForEach(a => { if (form[ObjectIdent + a._formname] != null) a._set_func(this, form[ObjectIdent + a._formname]);} ); } _field_infos.Where(i => i._type != "Lookup" && i._type != "Child" && i._type != "Relation" && i._type != null) .ToList().ForEach(a => { if (form.AllKeys.Contains(ObjectIdent + a._formname)) a._set_func(this, form[ObjectIdent + a._formname]);} ); if (bParseRelations) { } ParsedFormCollection(form); } #region Class for web grid public class VectorFieldTestGridModel : IGridModelItem { public string ErrorMessage { get; set; } public long ItemKey { get; set; } public Int64 idfPensideTest { get; set; } public String strVectorID { get; set; } public String strVectorTypeName { get; set; } public string strVectorSubTypeName { get; set; } public Int64 idfMaterial { get; set; } public string strSampleFieldBarcode { get; set; } public String strSampleName { get; set; } public DateTimeWrap datFieldCollectionDate { get; set; } public Int64? idfsPensideTestName { get; set; } public string strPensideTestName { get; set; } public Int64? idfsPensideTestCategory { get; set; } public string strPensideTestCategory { get; set; } public DateTimeWrap datTestDate { get; set; } public Int64? idfTestedByOffice { get; set; } public string strTestedByOffice { get; set; } public Int64? idfTestedByPerson { get; set; } public string strTestedByPerson { get; set; } public Int64? idfsPensideTestResult { get; set; } public string strPensideTestResult { get; set; } public Int64? idfsDiagnosis { get; set; } public string strDiagnosis { get; set; } } public partial class VectorFieldTestGridModelList : List<VectorFieldTestGridModel>, IGridModelList, IGridModelListLoad { public long ListKey { get; protected set; } public List<string> Columns { get; protected set; } public List<string> Hiddens { get; protected set; } public Dictionary<string, string> Labels { get; protected set; } public Dictionary<string, ActionMetaItem> Actions { get; protected set; } public List<string> Keys { get; protected set; } public bool IsHiddenPersonalData(string name) { return Meta._isHiddenPersonalData(name); } public IObjectMeta ObjectMeta { get { return Accessor.Instance(null); } } public VectorFieldTestGridModelList() { } public void Load(long key, IEnumerable items, string errMes) { LoadGridModelList(key, items as IEnumerable<VectorFieldTest>, errMes); } public VectorFieldTestGridModelList(long key, IEnumerable items, string errMes) { LoadGridModelList(key, items as IEnumerable<VectorFieldTest>, errMes); } public VectorFieldTestGridModelList(long key, IEnumerable<VectorFieldTest> items) { LoadGridModelList(key, items, null); } public VectorFieldTestGridModelList(long key) { LoadGridModelList(key, new List<VectorFieldTest>(), null); } partial void filter(List<VectorFieldTest> items); private void LoadGridModelList(long key, IEnumerable<VectorFieldTest> items, string errMes) { ListKey = key; Columns = new List<string> {_str_strVectorID,_str_strVectorTypeName,_str_strVectorSubTypeName,_str_idfMaterial,_str_strSampleFieldBarcode,_str_strSampleName,_str_datFieldCollectionDate,_str_idfsPensideTestName,_str_strPensideTestName,_str_idfsPensideTestCategory,_str_strPensideTestCategory,_str_datTestDate,_str_idfTestedByOffice,_str_strTestedByOffice,_str_idfTestedByPerson,_str_strTestedByPerson,_str_idfsPensideTestResult,_str_strPensideTestResult,_str_idfsDiagnosis,_str_strDiagnosis}; Hiddens = new List<string> {_str_idfPensideTest}; Keys = new List<string> {_str_idfPensideTest}; Labels = new Dictionary<string, string> {{_str_strVectorID, "Vector.strVectorID"},{_str_strVectorTypeName, "idfsVectorType"},{_str_strVectorSubTypeName, "idfsVectorSubType"},{_str_idfMaterial, _str_idfMaterial},{_str_strSampleFieldBarcode, "VectorSample.strFieldBarcode"},{_str_strSampleName, "idfsSampleType"},{_str_datFieldCollectionDate, _str_datFieldCollectionDate},{_str_idfsPensideTestName, "strPensideTypeName"},{_str_strPensideTestName, "strPensideTypeName"},{_str_idfsPensideTestCategory, "idfPensideTestTestCategory"},{_str_strPensideTestCategory, "idfPensideTestTestCategory"},{_str_datTestDate, "idfPensideTestTestDate"},{_str_idfTestedByOffice, "idfPensideTestTestedByOffice"},{_str_strTestedByOffice, "idfPensideTestTestedByOffice"},{_str_idfTestedByPerson, "idfPensideTestTestedByPerson"},{_str_strTestedByPerson, "idfPensideTestTestedByPerson"},{_str_idfsPensideTestResult, "FT.PensideTestResult"},{_str_strPensideTestResult, "FT.PensideTestResult"},{_str_idfsDiagnosis, "FT.strDisease"},{_str_strDiagnosis, "FT.strDisease"}}; Actions = new Dictionary<string, ActionMetaItem> {}; VectorFieldTest.Meta.Actions.ForEach(a => Actions.Add("@" + a.Name, a)); var list = new List<VectorFieldTest>(items); filter(list); AddRange(list.Where(c => !c.IsMarkedToDelete).Select(c => new VectorFieldTestGridModel() { ItemKey=c.idfPensideTest,strVectorID=c.strVectorID,strVectorTypeName=c.strVectorTypeName,strVectorSubTypeName=c.strVectorSubTypeName,idfMaterial=c.idfMaterial,strSampleFieldBarcode=c.strSampleFieldBarcode,strSampleName=c.strSampleName,datFieldCollectionDate=c.datFieldCollectionDate,idfsPensideTestName=c.idfsPensideTestName,strPensideTestName=c.strPensideTestName,idfsPensideTestCategory=c.idfsPensideTestCategory,strPensideTestCategory=c.strPensideTestCategory,datTestDate=c.datTestDate,idfTestedByOffice=c.idfTestedByOffice,strTestedByOffice=c.strTestedByOffice,idfTestedByPerson=c.idfTestedByPerson,strTestedByPerson=c.strTestedByPerson,idfsPensideTestResult=c.idfsPensideTestResult,strPensideTestResult=c.strPensideTestResult,idfsDiagnosis=c.idfsDiagnosis,strDiagnosis=c.strDiagnosis })); if (Count > 0) { this.Last().ErrorMessage = errMes; } } } #endregion #region Accessor public abstract partial class Accessor : DataAccessor<VectorFieldTest> , IObjectAccessor , IObjectMeta , IObjectValidator , IObjectCreator , IObjectCreator<VectorFieldTest> , IObjectSelectDetailList , IObjectPost { #region IObjectAccessor public string KeyName { get { return "idfPensideTest"; } } #endregion public delegate void on_action(VectorFieldTest obj); private static Accessor g_Instance = CreateInstance<Accessor>(); private CacheScope m_CS; public static Accessor Instance(CacheScope cs) { if (cs == null) return g_Instance; lock(cs) { object acc = cs.Get(typeof (Accessor)); if (acc != null) { return acc as Accessor; } Accessor ret = CreateInstance<Accessor>(); ret.m_CS = cs; cs.Add(typeof(Accessor), ret); return ret; } } private PensideTestLookup.Accessor TestTypeAccessor { get { return eidss.model.Schema.PensideTestLookup.Accessor.Instance(m_CS); } } private BaseReference.Accessor TestCategoryAccessor { get { return eidss.model.Schema.BaseReference.Accessor.Instance(m_CS); } } private Diagnosis2PensideTestMatrixLookup.Accessor DiagnosisAccessor { get { return eidss.model.Schema.Diagnosis2PensideTestMatrixLookup.Accessor.Instance(m_CS); } } private TypeFieldTestToResultMatrixLookup.Accessor TestResultAccessor { get { return eidss.model.Schema.TypeFieldTestToResultMatrixLookup.Accessor.Instance(m_CS); } } private Diagnosis2PensideTestMatrixLookup.Accessor DiagnosisFilteredAccessor { get { return eidss.model.Schema.Diagnosis2PensideTestMatrixLookup.Accessor.Instance(m_CS); } } private TypeFieldTestToResultMatrixLookup.Accessor TestResultFilteredAccessor { get { return eidss.model.Schema.TypeFieldTestToResultMatrixLookup.Accessor.Instance(m_CS); } } private PersonLookup.Accessor TestedByPersonAccessor { get { return eidss.model.Schema.PersonLookup.Accessor.Instance(m_CS); } } private OrganizationLookup.Accessor TestedByOfficeAccessor { get { return eidss.model.Schema.OrganizationLookup.Accessor.Instance(m_CS); } } public virtual List<IObject> SelectDetailList(DbManagerProxy manager, object ident, int? HACode = null) { return _SelectList(manager , (Int64?)ident , null , null ).Cast<IObject>().ToList(); } public virtual List<VectorFieldTest> SelectList(DbManagerProxy manager , Int64? idfVector ) { return _SelectList(manager , idfVector , delegate(VectorFieldTest obj) { } , delegate(VectorFieldTest obj) { } ); } public List<VectorFieldTest> _SelectList(DbManagerProxy manager , Int64? idfVector , on_action loading, on_action loaded ) { var ret = _SelectListInternal(manager , idfVector , loading , loaded ); return ret; } public virtual List<VectorFieldTest> _SelectListInternal(DbManagerProxy manager , Int64? idfVector , on_action loading, on_action loaded ) { VectorFieldTest _obj = null; try { MapResultSet[] sets = new MapResultSet[1]; List<VectorFieldTest> objs = new List<VectorFieldTest>(); sets[0] = new MapResultSet(typeof(VectorFieldTest), objs); manager .SetSpCommand("spVectorFieldTest_SelectDetail" , manager.Parameter("@idfVector", idfVector) , manager.Parameter("@LangID", ModelUserContext.CurrentLanguage) ) .ExecuteResultSet(sets); foreach(var obj in objs) { _obj = obj; obj.m_CS = m_CS; if (loading != null) loading(obj); _SetupLoad(manager, obj); if (loaded != null) loaded(obj); } return objs; } catch(DataException e) { throw DbModelException.Create(_obj, e); } } internal void _SetupLoad(DbManagerProxy manager, VectorFieldTest obj, bool bCloning = false) { if (obj == null) return; // loading extenters - begin // loading extenters - end if (!bCloning) { } _LoadLookups(manager, obj); obj._setParent(); // loaded extenters - begin // loaded extenters - end _SetupHandlers(obj); _SetupChildHandlers(obj, null); _SetPermitions(obj._permissions, obj); _SetupRequired(obj); _SetupPersonalDataRestrictions(obj); obj._SetupMainHandler(); obj.AcceptChanges(); } internal void _SetPermitions(IObjectPermissions permissions, VectorFieldTest obj) { if (obj != null) { obj._permissions = permissions; if (obj._permissions != null) { } } } private VectorFieldTest _CreateNew(DbManagerProxy manager, IObject Parent, int? HACode, on_action creating, on_action created, bool isFake = false) { VectorFieldTest obj = null; try { obj = VectorFieldTest.CreateInstance(); obj.m_CS = m_CS; obj.m_IsNew = true; obj.Parent = Parent; if (creating != null) creating(obj); // creating extenters - begin obj.idfPensideTest = (new GetNewIDExtender<VectorFieldTest>()).GetScalar(manager, obj, isFake); obj.idfVector = new Func<VectorFieldTest, long?>(c => c.ParentVector != null ? c.ParentVector.idfVector : obj.idfVector)(obj); obj.idfsVectorType = new Func<VectorFieldTest, long>(c => c.ParentVector != null ? c.ParentVector.idfsVectorType : obj.idfsVectorType)(obj); obj.strVectorID = new Func<VectorFieldTest, string>(c => c.ParentVector != null ? c.ParentVector.strVectorID : String.Empty)(obj); obj.strVectorTypeName = new Func<VectorFieldTest, string>(c => ((c.ParentVector != null) && (c.ParentVector.VectorType != null)) ? c.ParentVector.VectorType.strTranslatedName : String.Empty)(obj); obj.strSampleName = new Func<VectorFieldTest, string>(c => c.ParentSample != null ? c.ParentSample.strSampleName : String.Empty)(obj); obj.datFieldCollectionDate = new Func<VectorFieldTest, DateTime?>(c => c.ParentSample != null ? c.ParentSample.datCollectionDateTime : obj.datFieldCollectionDate)(obj); obj.idfVectorSurveillanceSession = new Func<VectorFieldTest, long?>(c => c.ParentVector == null ? c.idfVectorSurveillanceSession : c.ParentVector.idfVectorSurveillanceSession)(obj); // creating extenters - end _LoadLookups(manager, obj); _SetupHandlers(obj); _SetupChildHandlers(obj, null); obj._SetupMainHandler(); obj._setParent(); // created extenters - begin // created extenters - end if (created != null) created(obj); obj.Created(manager); _SetPermitions(obj._permissions, obj); _SetupRequired(obj); _SetupPersonalDataRestrictions(obj); return obj; } catch(DataException e) { throw DbModelException.Create(obj, e); } } public VectorFieldTest CreateNewT(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null); } public IObject CreateNew(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null); } public VectorFieldTest CreateFakeT(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null, true); } public IObject CreateFake(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null, true); } public VectorFieldTest CreateWithParamsT(DbManagerProxy manager, IObject Parent, List<object> pars) { return _CreateNew(manager, Parent, null, null, null); } public IObject CreateWithParams(DbManagerProxy manager, IObject Parent, List<object> pars) { return _CreateNew(manager, Parent, null, null, null); } public VectorFieldTest CreateT(DbManagerProxy manager, IObject Parent, List<object> pars) { return Create(manager, Parent ); } public IObject Create(DbManagerProxy manager, IObject Parent, List<object> pars) { return CreateT(manager, Parent, pars); } public VectorFieldTest Create(DbManagerProxy manager, IObject Parent ) { return _CreateNew(manager, Parent , null , obj => { } , obj => { } ); } public ActResult ViewOnDetailForm(DbManagerProxy manager, VectorFieldTest obj, List<object> pars) { return ViewOnDetailForm(manager, obj ); } public ActResult ViewOnDetailForm(DbManagerProxy manager, VectorFieldTest obj ) { return true; } private void _SetupChildHandlers(VectorFieldTest obj, object newobj) { if (newobj == null || newobj == obj.ParentVector) { var o = obj.ParentVector; if (o != null) { var item = o; o.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "datCollectionDateTime") { obj.datFieldCollectionDate = new Func<VectorFieldTest, DateTime?>(c => c.ParentVector.datCollectionDateTime)(obj); } }; } } } private void _SetupHandlers(VectorFieldTest obj) { obj.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == _str_datTestDate) { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { obj.LockNotifyChanges(); obj.CancelMemberLastChanges(_str_datTestDate); obj.OnValidationEnd(ex); obj.UnlockNotifyChanges(); } } if (e.PropertyName == _str_datFieldCollectionDate) { var ex = ChainsValidate(obj); if (ex != null && !obj.OnValidation(ex)) { obj.LockNotifyChanges(); obj.CancelMemberLastChanges(_str_datFieldCollectionDate); obj.OnValidationEnd(ex); obj.UnlockNotifyChanges(); } } }; obj.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == _str_idfMaterial) { obj.strSampleName = new Func<VectorFieldTest, string>(c => c.Samples == null ? "" : c.Samples.Where(s => s.idfMaterial == c.idfMaterial).FirstOrDefault().strSampleName)(obj); } if (e.PropertyName == _str_idfMaterial) { obj.datFieldCollectionDate = new Func<VectorFieldTest, DateTime?>(c => c.Samples == null ? c.datFieldCollectionDate : c.Samples.Where(s => s.idfMaterial == c.idfMaterial).FirstOrDefault().datFieldCollectionDate)(obj); } if (e.PropertyName == _str_idfsPensideTestName) { obj.TestType = new Func<VectorFieldTest, PensideTestLookup>(c => c.TestTypeLookup.Where(x => x.idfsPensideTestName == c.idfsPensideTestName).FirstOrDefault())(obj); } if (e.PropertyName == _str_idfsPensideTestCategory) { obj.TestCategory = new Func<VectorFieldTest, BaseReference>(c => c.TestCategoryLookup.Where(x => x.idfsBaseReference == c.idfsPensideTestCategory).FirstOrDefault())(obj); } if (e.PropertyName == _str_idfTestedByOffice) { obj.TestedByOffice = new Func<VectorFieldTest, OrganizationLookup>(c => c.TestedByOfficeLookup.Where(x => x.idfInstitution == c.idfTestedByOffice).FirstOrDefault())(obj); } if (e.PropertyName == _str_idfTestedByPerson) { obj.TestedByPerson = new Func<VectorFieldTest, PersonLookup>(c => c.TestedByPersonLookup.Where(x => x.idfPerson == c.idfTestedByPerson).FirstOrDefault())(obj); } if (e.PropertyName == _str_idfTestedByOffice) { obj.TestedByPerson = (new SetScalarHandler()).Handler(obj, obj.idfTestedByOffice, obj.idfTestedByOffice_Previous, obj.TestedByPerson, (o, fld, prev_fld) => null); } if (e.PropertyName == _str_idfsPensideTestName) { obj.Diagnosis = (new SetScalarHandler()).Handler(obj, obj.idfsPensideTestName, obj.idfsPensideTestName_Previous, obj.Diagnosis, (o, fld, prev_fld) => null); } if (e.PropertyName == _str_idfsPensideTestName) { obj.TestResult = (new SetScalarHandler()).Handler(obj, obj.idfsPensideTestName, obj.idfsPensideTestName_Previous, obj.TestResult, (o, fld, prev_fld) => null); } if (e.PropertyName == _str_idfsPensideTestName) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) LoadLookup_TestType(manager, obj); } if (e.PropertyName == _str_idfsPensideTestName) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) LoadLookup_Diagnosis(manager, obj); } if (e.PropertyName == _str_idfsPensideTestName) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) LoadLookup_TestResult(manager, obj); } if (e.PropertyName == _str_idfTestedByOffice) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) LoadLookup_TestedByPerson(manager, obj); } if (e.PropertyName == _str_idfsPensideTestName) { obj.DiagnosisFiltered = (new SetScalarHandler()).Handler(obj, obj.idfsPensideTestName, obj.idfsPensideTestName_Previous, obj.DiagnosisFiltered, (o, fld, prev_fld) => null); } if (e.PropertyName == _str_idfsPensideTestName) { obj.TestResultFiltered = (new SetScalarHandler()).Handler(obj, obj.idfsPensideTestName, obj.idfsPensideTestName_Previous, obj.TestResultFiltered, (o, fld, prev_fld) => null); } if (e.PropertyName == _str_idfsPensideTestName) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) LoadLookup_DiagnosisFiltered(manager, obj); } if (e.PropertyName == _str_idfsPensideTestName) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) LoadLookup_TestResultFiltered(manager, obj); } }; } public void LoadLookup_TestType(DbManagerProxy manager, VectorFieldTest obj) { obj.TestTypeLookup.Clear(); obj.TestTypeLookup.Add(TestTypeAccessor.CreateNewT(manager, null)); obj.TestTypeLookup.AddRange(TestTypeAccessor.SelectLookupList(manager ) .Where(c => obj.idfsVectorType == 0 ? true : c.idfsVectorType == obj.idfsVectorType) .Where(c => (c.intRowStatus == 0) || (c.idfsPensideTestName == obj.idfsPensideTestName)) .ToList()); if (obj.idfsPensideTestName != null && obj.idfsPensideTestName != 0) { obj.TestType = obj.TestTypeLookup .SingleOrDefault(c => c.idfsPensideTestName == obj.idfsPensideTestName); } LookupManager.AddObject("PensideTestLookup", obj, TestTypeAccessor.GetType(), "_SelectListInternal"); obj.bNeedLookupRemove = true; } public void LoadLookup_TestCategory(DbManagerProxy manager, VectorFieldTest obj) { obj.TestCategoryLookup.Clear(); obj.TestCategoryLookup.Add(TestCategoryAccessor.CreateNewT(manager, null)); obj.TestCategoryLookup.AddRange(TestCategoryAccessor.rftPensideTestCategory_SelectList(manager ) .Where(c => (c.intRowStatus == 0) || (c.idfsBaseReference == obj.idfsPensideTestCategory)) .ToList()); if (obj.idfsPensideTestCategory != null && obj.idfsPensideTestCategory != 0) { obj.TestCategory = obj.TestCategoryLookup .SingleOrDefault(c => c.idfsBaseReference == obj.idfsPensideTestCategory); } LookupManager.AddObject("rftPensideTestCategory", obj, TestCategoryAccessor.GetType(), "rftPensideTestCategory_SelectList", "_SelectListInternal"); obj.bNeedLookupRemove = true; } public void LoadLookup_Diagnosis(DbManagerProxy manager, VectorFieldTest obj) { obj.DiagnosisLookup.Clear(); obj.DiagnosisLookup.Add(DiagnosisAccessor.CreateNewT(manager, null)); obj.DiagnosisLookup.AddRange(DiagnosisAccessor.SelectLookupList(manager ) .Where(c => c.idfsPensideTestName == (obj.idfsPensideTestName.HasValue && obj.idfsPensideTestName.Value != 0 ? obj.idfsPensideTestName.Value : c.idfsPensideTestName)) .Where(c => (c.intRowStatus == 0) || (c.idfsDiagnosis == obj.idfsDiagnosis)) .ToList()); if (obj.idfsDiagnosis != null && obj.idfsDiagnosis != 0) { obj.Diagnosis = obj.DiagnosisLookup .SingleOrDefault(c => c.idfsDiagnosis == obj.idfsDiagnosis); } LookupManager.AddObject("Diagnosis2PensideTestMatrixLookup", obj, DiagnosisAccessor.GetType(), "_SelectListInternal"); obj.bNeedLookupRemove = true; } public void LoadLookup_TestResult(DbManagerProxy manager, VectorFieldTest obj) { obj.TestResultLookup.Clear(); obj.TestResultLookup.Add(TestResultAccessor.CreateNewT(manager, null)); obj.TestResultLookup.AddRange(TestResultAccessor.SelectLookupList(manager ) .Where(c => c.idfsPensideTestName == (obj.idfsPensideTestName.HasValue && obj.idfsPensideTestName.Value != 0 ? obj.idfsPensideTestName.Value : c.idfsPensideTestName)) .Where(c => (c.intRowStatus == 0) || (c.idfsPensideTestResult == obj.idfsPensideTestResult)) .ToList()); if (obj.idfsPensideTestResult != null && obj.idfsPensideTestResult != 0) { obj.TestResult = obj.TestResultLookup .SingleOrDefault(c => c.idfsPensideTestResult == obj.idfsPensideTestResult); } LookupManager.AddObject("TypeFieldTestToResultMatrixLookup", obj, TestResultAccessor.GetType(), "_SelectListInternal"); obj.bNeedLookupRemove = true; } public void LoadLookup_DiagnosisFiltered(DbManagerProxy manager, VectorFieldTest obj) { obj.DiagnosisFilteredLookup.Clear(); obj.DiagnosisFilteredLookup.Add(DiagnosisFilteredAccessor.CreateNewT(manager, null)); obj.DiagnosisFilteredLookup.AddRange(DiagnosisFilteredAccessor.SelectLookupList(manager ) .Where(c => c.idfsPensideTestName == (obj.idfsPensideTestName.HasValue && obj.idfsPensideTestName.Value != 0 ? obj.idfsPensideTestName.Value : -1)) .Where(c => (c.intRowStatus == 0) || (c.idfsDiagnosis == obj.idfsDiagnosis)) .ToList()); if (obj.idfsDiagnosis != null && obj.idfsDiagnosis != 0) { obj.DiagnosisFiltered = obj.DiagnosisFilteredLookup .SingleOrDefault(c => c.idfsDiagnosis == obj.idfsDiagnosis); } LookupManager.AddObject("Diagnosis2PensideTestMatrixLookup", obj, DiagnosisFilteredAccessor.GetType(), "_SelectListInternal"); obj.bNeedLookupRemove = true; } public void LoadLookup_TestResultFiltered(DbManagerProxy manager, VectorFieldTest obj) { obj.TestResultFilteredLookup.Clear(); obj.TestResultFilteredLookup.Add(TestResultFilteredAccessor.CreateNewT(manager, null)); obj.TestResultFilteredLookup.AddRange(TestResultFilteredAccessor.SelectLookupList(manager ) .Where(c => c.idfsPensideTestName == (obj.idfsPensideTestName.HasValue && obj.idfsPensideTestName.Value != 0 ? obj.idfsPensideTestName.Value : -1)) .Where(c => (c.intRowStatus == 0) || (c.idfsPensideTestResult == obj.idfsPensideTestResult)) .ToList()); if (obj.idfsPensideTestResult != null && obj.idfsPensideTestResult != 0) { obj.TestResultFiltered = obj.TestResultFilteredLookup .SingleOrDefault(c => c.idfsPensideTestResult == obj.idfsPensideTestResult); } LookupManager.AddObject("TypeFieldTestToResultMatrixLookup", obj, TestResultFilteredAccessor.GetType(), "_SelectListInternal"); obj.bNeedLookupRemove = true; } public void LoadLookup_TestedByPerson(DbManagerProxy manager, VectorFieldTest obj) { obj.TestedByPersonLookup.Clear(); obj.TestedByPersonLookup.Add(TestedByPersonAccessor.CreateNewT(manager, null)); obj.TestedByPersonLookup.AddRange(TestedByPersonAccessor.SelectLookupList(manager , new Func<VectorFieldTest, long?>(c => c.idfTestedByOffice)(obj) , null , false , null ) .Where(c => (c.intRowStatus == 0) || (c.idfPerson == obj.idfTestedByPerson)) .ToList()); if (obj.idfTestedByPerson != null && obj.idfTestedByPerson != 0) { obj.TestedByPerson = obj.TestedByPersonLookup .SingleOrDefault(c => c.idfPerson == obj.idfTestedByPerson); } LookupManager.AddObject("PersonLookup", obj, TestedByPersonAccessor.GetType(), "_SelectListInternal"); obj.bNeedLookupRemove = true; } public void LoadLookup_TestedByOffice(DbManagerProxy manager, VectorFieldTest obj) { obj.TestedByOfficeLookup.Clear(); obj.TestedByOfficeLookup.Add(TestedByOfficeAccessor.CreateNewT(manager, null)); obj.TestedByOfficeLookup.AddRange(TestedByOfficeAccessor.SelectLookupList(manager , null , null ) .Where(c => (((c.intHACode??0) & (int)HACode.Vector) != 0) || c.idfInstitution == obj.idfTestedByOffice) .Where(c => (c.intRowStatus == 0) || (c.idfInstitution == obj.idfTestedByOffice)) .ToList()); if (obj.idfTestedByOffice != null && obj.idfTestedByOffice != 0) { obj.TestedByOffice = obj.TestedByOfficeLookup .SingleOrDefault(c => c.idfInstitution == obj.idfTestedByOffice); } LookupManager.AddObject("OrganizationLookup", obj, TestedByOfficeAccessor.GetType(), "_SelectListInternal"); obj.bNeedLookupRemove = true; } internal void _LoadLookups(DbManagerProxy manager, VectorFieldTest obj) { LoadLookup_TestType(manager, obj); LoadLookup_TestCategory(manager, obj); LoadLookup_Diagnosis(manager, obj); LoadLookup_TestResult(manager, obj); LoadLookup_DiagnosisFiltered(manager, obj); LoadLookup_TestResultFiltered(manager, obj); LoadLookup_TestedByPerson(manager, obj); LoadLookup_TestedByOffice(manager, obj); } [SprocName("spVectorFieldTest_CanDelete")] protected abstract void _canDelete(DbManagerProxy manager, Int64? idfVectorFieldTest, out Boolean Result ); [SprocName("spVectorFieldTest_Delete")] protected abstract void _postDelete(DbManagerProxy manager , Int64? ID ); protected void _postDeletePredicate(DbManagerProxy manager , Int64? ID ) { _postDelete(manager, ID); } [SprocName("spVectorFieldTest_Post")] protected abstract void _post(DbManagerProxy manager, int Action, [Direction.InputOutput("idfPensideTest", "datTestDate")] VectorFieldTest obj); protected void _postPredicate(DbManagerProxy manager, int Action, [Direction.InputOutput("idfPensideTest", "datTestDate")] VectorFieldTest obj) { _post(manager, Action, obj); } public bool Post(DbManagerProxy manager, IObject obj, bool bChildObject = false) { bool bSuccess = false; int iDeadlockAttemptsCount = BaseSettings.DeadlockAttemptsCount; for (int iAttemptNumber = 0; iAttemptNumber < iDeadlockAttemptsCount; iAttemptNumber++) { bool bTransactionStarted = false; try { VectorFieldTest bo = obj as VectorFieldTest; if (!bo.IsNew && bo.IsMarkedToDelete) // delete { } else if (bo.IsNew && !bo.IsMarkedToDelete) // insert { } else if (!bo.IsMarkedToDelete) // update { } if (!manager.IsTransactionStarted) { bTransactionStarted = true; manager.BeginTransaction(); } bSuccess = _PostNonTransaction(manager, obj as VectorFieldTest, bChildObject); if (bTransactionStarted) { if (bSuccess) { obj.DeepAcceptChanges(); manager.CommitTransaction(); } else { manager.RollbackTransaction(); } } if (bSuccess && bo.IsNew && !bo.IsMarkedToDelete) // insert { bo.m_IsNew = false; } if (bSuccess && bTransactionStarted) { bo.OnAfterPost(); } break; } catch(Exception e) { if (bTransactionStarted) { manager.RollbackTransaction(); if (DbModelException.IsDeadlockException(e)) { System.Threading.Thread.Sleep(BaseSettings.DeadlockDelay); continue; } } if (e is DataException) { throw DbModelException.Create(obj, e as DataException); } if (e is System.Data.SqlClient.SqlException) { throw DbModelException.Create(obj, e as System.Data.SqlClient.SqlException); } else throw; } } return bSuccess; } private bool _PostNonTransaction(DbManagerProxy manager, VectorFieldTest obj, bool bChildObject) { bool bHasChanges = obj.HasChanges; if (!obj.IsNew && obj.IsMarkedToDelete) // delete { if (!ValidateCanDelete(manager, obj)) return false; _postPredicate(manager, 8, obj); } else if (!obj.IsMarkedToDelete) // insert/update { if (!bChildObject) if (!Validate(manager, obj, true, true, true)) return false; // posting extenters - begin // posting extenters - end if (obj.IsNew && !obj.IsMarkedToDelete && obj.HasChanges) _postPredicate(manager, 4, obj); else if (!obj.IsNew && !obj.IsMarkedToDelete && obj.HasChanges) _postPredicate(manager, 16, obj); // posted extenters - begin // posted extenters - end } //obj.AcceptChanges(); return true; } public bool ValidateCanDelete(VectorFieldTest obj) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { return ValidateCanDelete(manager, obj); } } public bool ValidateCanDelete(DbManagerProxy manager, VectorFieldTest obj) { try { if (!obj.IsForcedToDelete) { bool result = false; _canDelete(manager , obj.idfPensideTest , out result ); if (!result) { throw new ValidationModelException("msgCantDelete", "_on_delete", "_on_delete", null, null, ValidationEventType.Error, obj); } } } catch(ValidationModelException ex) { if (!obj.OnValidation(ex)) { obj.OnValidationEnd(ex); return false; } else obj.m_IsForcedToDelete = true; } return true; } protected ValidationModelException ChainsValidate(VectorFieldTest obj) { try { new ChainsValidatorDateTime<VectorFieldTest>(obj, "datTestDate", c => true, obj.datTestDate, obj.GetType(), false, listdatTestDate => { listdatTestDate.Add( new ChainsValidatorDateTime<VectorFieldTest>(obj, "datFieldCollectionDate", c => true, obj.datFieldCollectionDate, obj.GetType(), false, listdatFieldCollectionDate => { listdatFieldCollectionDate.Add( new ChainsValidatorDateTime<VectorFieldTest>(obj, "CurrentDate", c => true, DateTime.Now, null, false, listCurrentDate => { })); })); }).Process(); } catch(ValidationModelException ex) { return ex; } return null; } protected bool ChainsValidate(VectorFieldTest obj, bool bRethrowException) { ValidationModelException ex = ChainsValidate(obj); if (ex != null) { if (bRethrowException) throw ex; if (!obj.OnValidation(ex)) { obj.OnValidationEnd(ex); return false; } } return true; } public bool Validate(DbManagerProxy manager, IObject obj, bool bPostValidation, bool bChangeValidation, bool bDeepValidation, bool bRethrowException = false) { return Validate(manager, obj as VectorFieldTest, bPostValidation, bChangeValidation, bDeepValidation, bRethrowException); } public bool Validate(DbManagerProxy manager, VectorFieldTest obj, bool bPostValidation, bool bChangeValidation, bool bDeepValidation, bool bRethrowException = false) { if (!ChainsValidate(obj, bRethrowException)) return false; try { if (bPostValidation) { (new RequiredValidator( "idfMaterial", "idfMaterial","", ValidationEventType.Error )).Validate(c => true, obj, obj.idfMaterial); (new RequiredValidator( "idfsPensideTestName", "idfsPensideTestName","", ValidationEventType.Error )).Validate(c => true, obj, obj.idfsPensideTestName); (new PredicateValidator("errNoDiagnosisForTestResult", "idfsDiagnosis", "idfsDiagnosis", "idfsDiagnosis", new object[] { }, ValidationEventType.Error )).Validate(obj, c => c.idfsPensideTestResult != null ? c.idfsDiagnosis != null : true ); } if (bChangeValidation) { } if (bDeepValidation) { } } catch(ValidationModelException ex) { if (bRethrowException) throw; if (!obj.OnValidation(ex)) { obj.OnValidationEnd(ex); return false; } } return true; } private void _SetupRequired(VectorFieldTest obj) { obj .AddRequired("idfMaterial", c => true); obj .AddRequired("idfsPensideTestName", c => true); obj .AddRequired("TestType", c => true); } private void _SetupPersonalDataRestrictions(VectorFieldTest obj) { } #region IObjectMeta public int? MaxSize(string name) { return Meta.Sizes.ContainsKey(name) ? (int?)Meta.Sizes[name] : null; } public bool RequiredByField(string name, IObject obj) { return Meta.RequiredByField.ContainsKey(name) ? Meta.RequiredByField[name](obj as VectorFieldTest) : false; } public bool RequiredByProperty(string name, IObject obj) { return Meta.RequiredByProperty.ContainsKey(name) ? Meta.RequiredByProperty[name](obj as VectorFieldTest) : false; } public List<SearchPanelMetaItem> SearchPanelMeta { get { return Meta.SearchPanelMeta; } } public List<GridMetaItem> GridMeta { get { return Meta.GridMeta; } } public List<ActionMetaItem> Actions { get { return Meta.Actions; } } public string DetailPanel { get { return "VectorFieldTestDetail"; } } public string HelpIdWin { get { return ""; } } public string HelpIdWeb { get { return ""; } } public string HelpIdHh { get { return ""; } } public string SqlSortOrder { get { return Meta.sqlSortOrder; } } #endregion } #region Meta public static class Meta { public static string spSelect = "spVectorFieldTest_SelectDetail"; public static string spCount = ""; public static string spPost = "spVectorFieldTest_Post"; public static string spInsert = ""; public static string spUpdate = ""; public static string spDelete = "spVectorFieldTest_Delete"; public static string spCanDelete = "spVectorFieldTest_CanDelete"; public static string sqlSortOrder = ""; public static Dictionary<string, int> Sizes = new Dictionary<string, int>(); public static Dictionary<string, Func<VectorFieldTest, bool>> RequiredByField = new Dictionary<string, Func<VectorFieldTest, bool>>(); public static Dictionary<string, Func<VectorFieldTest, bool>> RequiredByProperty = new Dictionary<string, Func<VectorFieldTest, bool>>(); public static List<SearchPanelMetaItem> SearchPanelMeta = new List<SearchPanelMetaItem>(); public static List<GridMetaItem> GridMeta = new List<GridMetaItem>(); public static List<ActionMetaItem> Actions = new List<ActionMetaItem>(); private static Dictionary<string, List<Func<bool>>> m_isHiddenPersonalData = new Dictionary<string, List<Func<bool>>>(); internal static bool _isHiddenPersonalData(string name) { if (m_isHiddenPersonalData.ContainsKey(name)) return m_isHiddenPersonalData[name].Aggregate(false, (s,c) => s | c()); return false; } private static void AddHiddenPersonalData(string name, Func<bool> func) { if (!m_isHiddenPersonalData.ContainsKey(name)) m_isHiddenPersonalData.Add(name, new List<Func<bool>>()); m_isHiddenPersonalData[name].Add(func); } static Meta() { Sizes.Add(_str_strPensideTestTypeName, 2000); Sizes.Add(_str_strVectorTypeName, 2000); Sizes.Add(_str_strFieldBarcode, 200); Sizes.Add(_str_strSampleName, 2000); Sizes.Add(_str_strPensideTestCategoryName, 2000); Sizes.Add(_str_strCollectedByPerson, 400); Sizes.Add(_str_strCollectedByOffice, 2000); Sizes.Add(_str_strPensideTestResultName, 2000); Sizes.Add(_str_strDiagnosisName, 2000); Sizes.Add(_str_strVectorID, 50); if (!RequiredByField.ContainsKey("idfMaterial")) RequiredByField.Add("idfMaterial", c => true); if (!RequiredByProperty.ContainsKey("idfMaterial")) RequiredByProperty.Add("idfMaterial", c => true); if (!RequiredByField.ContainsKey("idfsPensideTestName")) RequiredByField.Add("idfsPensideTestName", c => true); if (!RequiredByProperty.ContainsKey("idfsPensideTestName")) RequiredByProperty.Add("idfsPensideTestName", c => true); GridMeta.Add(new GridMetaItem( _str_idfPensideTest, _str_idfPensideTest, null, false, false, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_strVectorID, "Vector.strVectorID", null, true, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_strVectorTypeName, "idfsVectorType", null, false, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_strVectorSubTypeName, "idfsVectorSubType", null, false, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_idfMaterial, _str_idfMaterial, null, true, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_strSampleFieldBarcode, "VectorSample.strFieldBarcode", null, true, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_strSampleName, "idfsSampleType", null, true, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_datFieldCollectionDate, _str_datFieldCollectionDate, null, false, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_idfsPensideTestName, "strPensideTypeName", null, true, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_strPensideTestName, "strPensideTypeName", null, true, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_idfsPensideTestCategory, "idfPensideTestTestCategory", null, false, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_strPensideTestCategory, "idfPensideTestTestCategory", null, false, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_datTestDate, "idfPensideTestTestDate", null, true, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_idfTestedByOffice, "idfPensideTestTestedByOffice", null, false, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_strTestedByOffice, "idfPensideTestTestedByOffice", null, false, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_idfTestedByPerson, "idfPensideTestTestedByPerson", null, false, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_strTestedByPerson, "idfPensideTestTestedByPerson", null, false, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_idfsPensideTestResult, "FT.PensideTestResult", null, true, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_strPensideTestResult, "FT.PensideTestResult", null, true, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_idfsDiagnosis, "FT.strDisease", null, true, true, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_strDiagnosis, "FT.strDisease", null, true, true, true, true, true, null )); Actions.Add(new ActionMetaItem( "Create", ActionTypes.Create, true, "", "", (manager, c, pars) => new ActResult(true, Accessor.Instance(null).Create(manager, c, pars)), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"", "", /*from BvMessages*/"", /*from BvMessages*/"", "", /*from BvMessages*/"", ActionsAlignment.Left, ActionsPanelType.Group, ActionsAppType.All ), false, null, null, null, null, (c, a, b, p) => false, false, false, null, false, new ActionMetaItem[] { } )); Actions.Add(new ActionMetaItem( "Edit", ActionTypes.Edit, true, "", "", (manager, c, pars) => new ActResult(true, c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"", "", /*from BvMessages*/"", /*from BvMessages*/"", "", /*from BvMessages*/"", ActionsAlignment.Left, ActionsPanelType.Group, ActionsAppType.All ), false, null, null, null, null, (c, a, b, p) => false, false, false, null, false, new ActionMetaItem[] { } )); Actions.Add(new ActionMetaItem( "ViewOnDetailForm", ActionTypes.Action, true, "", "", (manager, c, pars) => Accessor.Instance(null).ViewOnDetailForm(manager, (VectorFieldTest)c, pars), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strViewOnDetailForm_Id", "", /*from BvMessages*/"tooltipViewOnDetailForm_Id", /*from BvMessages*/"", "", /*from BvMessages*/"", ActionsAlignment.Right, ActionsPanelType.Group, ActionsAppType.All ), true, null, null, (c, p, b) => c != null && !c.Key.Equals(PredefinedObjectId.FakeListObject), null, null, false, false, null, false, new ActionMetaItem[] { } )); Actions.Add(new ActionMetaItem( "Delete", ActionTypes.Delete, false, String.Empty, String.Empty, (manager, c, pars) => ((VectorFieldTest)c).MarkToDelete(), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strDelete_Id", "Delete_Remove", /*from BvMessages*/"tooltipDelete_Id", /*from BvMessages*/"", "", /*from BvMessages*/"tooltipDelete_Id", ActionsAlignment.Right, ActionsPanelType.Group, ActionsAppType.All ), false, null, null, null, null, null, false )); Actions.Add(new ActionMetaItem( "Ok", ActionTypes.Ok, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(true, c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strOK_Id", "", /*from BvMessages*/"tooltipOK_Id", /*from BvMessages*/"", "", /*from BvMessages*/"tooltipOK_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, null, null, null, false )); Actions.Add(new ActionMetaItem( "Cancel", ActionTypes.Cancel, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(true, c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strCancel_Id", "", /*from BvMessages*/"tooltipCancel_Id", /*from BvMessages*/"strOK_Id", "", /*from BvMessages*/"tooltipCancel_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, null, null, null, false )); _SetupPersonalDataRestrictions(); } private static void _SetupPersonalDataRestrictions() { } } #endregion #endregion } }
51.626193
1,059
0.541898
[ "BSD-2-Clause" ]
EIDSS/EIDSS-Legacy
EIDSS v6.1/eidss.model/Schema/VectorFieldTest.model.cs
173,053
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Xml; using Umbraco.Core; using Umbraco.Core.Models.EntityBase; using Umbraco.Core.Services; using Umbraco.Web.Trees; using umbraco.BusinessLogic; using umbraco.BusinessLogic.Actions; using umbraco.cms.businesslogic.media; using umbraco.cms.businesslogic.web; using umbraco.interfaces; namespace umbraco.cms.presentation.Trees { /// <summary> /// All ITree's should inherit from BaseTree. /// </summary> public abstract class BaseTree : ITree, ITreeService //, IApplicationEventHandler { public BaseTree(string application) { this.app = application; } protected const string FolderIcon = "icon-folder"; protected const string FolderIconOpen = "icon-folder"; /// <summary> /// Returns the node definition of the root node for this tree /// </summary> public XmlTreeNode RootNode { get { Initialize(); return m_initNode; } } /// <summary> /// By default the init actions that are allowed for all trees are Create, Reload Nodes. /// These are the menu items that show up in the context menu for the root node of the current tree. /// Should be used in conjunction with the RootNode property /// </summary> public List<IAction> RootNodeActions { get { Initialize(); return m_initActions; } } /// <summary> /// The actions that are allowed to be performed on this tree. These are the items that may show up on the /// context menu for a given node. /// </summary> public List<IAction> AllowedActions { get { Initialize(); return m_allowedActions; } } /// <summary> /// The tree alias name. By default, if a BaseTree is instantiated by it's TreeDefinition, then the TreeAlias will be /// the name defined in the database. Inheritors can override this property to set the TreeAlias to whatever they choose. /// </summary> public virtual string TreeAlias { get { if (string.IsNullOrEmpty(m_treeAlias)) { TreeDefinition treeDef = TreeDefinitionCollection.Instance.FindTree(this); m_treeAlias = (treeDef != null ? treeDef.Tree.Alias : ""); } return m_treeAlias; } internal set { m_treeAlias = value; } } private string m_treeAlias; #region ITreeService Members /// <summary> /// By default the start node id will be -1 which will return all of the nodes /// </summary> public virtual int StartNodeID { get { return -1; } } public bool ShowContextMenu { get { return m_showContextMenu; } set { m_showContextMenu = value; } } public bool IsDialog { get { return m_isDialog; } set { m_isDialog = value; } } /// <summary> /// The NodeKey is a string representation of the nodeID. Generally this is used for tree's whos node's unique key value is a string in instead /// of an integer such as folder names. /// </summary> public string NodeKey { get { return m_nodeKey; } set { m_nodeKey = value; } } public string FunctionToCall { get { return m_functionToCall; } set { m_functionToCall = value; } } public TreeDialogModes DialogMode { get { return m_dialogMode; } set { m_dialogMode = value; } } #endregion #region ITree Members /// <summary> /// The ID of the node to render. This is generally set before calling the render method of the tree. If it is not set then the /// StartNodeID property is used as the node ID to render. /// </summary> public virtual int id { set { m_id = value; } get { return m_id; } } public virtual string app { set { m_app = value; } get { return m_app; } } /// <summary> /// Renders out any JavaScript methods that may be required for tree functionality. Generally used to load the editor page when /// a user clicks on a tree node. /// </summary> /// <param name="Javascript"></param> public abstract void RenderJS(ref StringBuilder Javascript); /// <summary> /// This will call the new Render method which works using a typed XmlTree object instead of the untyped XmlDocument object. /// This can still be overriden but is only for backwards compatibility. /// </summary> /// <param name="Tree"></param> [Obsolete("Use the other Render method instead")] public virtual void Render(ref XmlDocument Tree) { //call our render method by passing in the XmlTree instead of the XmlDocument Render(ref m_xTree); //now that we have an XmlTree object filled, we'll serialize it back to the XmlDocument of the ITree Tree.LoadXml(m_xTree.ToString(SerializedTreeType.XmlTree)); } /// <summary> /// Classes need to override thid method to create the nodes for the XmlTree /// </summary> /// <param name="tree"></param> public abstract void Render(ref XmlTree tree); #endregion protected int m_id; protected string m_app; protected XmlTreeNode m_initNode; private List<IAction> m_initActions = new List<IAction>(); private List<IAction> m_allowedActions = new List<IAction>(); //these are the request parameters that can be specified. //since we want to remove the querystring/httpcontext dependency from //our trees, we need to define these as properties. private bool m_showContextMenu = true; private bool m_isDialog = false; private TreeDialogModes m_dialogMode = TreeDialogModes.none; private string m_nodeKey = ""; private string m_functionToCall = ""; private bool m_isInitialized = false; private XmlTree m_xTree = new XmlTree(); /// <summary> /// Provides easy access to the ServiceContext /// </summary> protected internal ServiceContext Services { get { return ApplicationContext.Current.Services; } } /// <summary> /// Initializes the class if it hasn't been done already /// </summary> protected void Initialize() { if (!m_isInitialized) { //VERY IMPORTANT! otherwise it will go infinite loop! m_isInitialized = true; CreateAllowedActions(); //first create the allowed actions //raise the event, allow developers to modify the collection var nodeActions = new NodeActionsEventArgs(false, m_allowedActions); OnNodeActionsCreated(nodeActions); m_allowedActions = nodeActions.AllowedActions; CreateRootNodeActions();//then create the root node actions var rootActions = new NodeActionsEventArgs(true, m_initActions); OnNodeActionsCreated(rootActions); m_initActions = rootActions.AllowedActions; CreateRootNode(); //finally, create the root node itself } } /// <summary> /// This method creates the Root node definition for the tree. /// Inheritors must override this method to create their own definition. /// </summary> /// <param name="rootNode"></param> protected abstract void CreateRootNode(ref XmlTreeNode rootNode); protected void CreateRootNode() { m_initNode = XmlTreeNode.CreateRoot(this); m_initNode.Icon = FolderIcon; m_initNode.OpenIcon = FolderIconOpen; CreateRootNode(ref m_initNode); } /// <summary> /// This method creates the IAction list for the tree's root node. /// Inheritors can override this method to create their own Context menu. /// </summary> /// <param name="actions"></param> protected virtual void CreateRootNodeActions(ref List<IAction> actions) { actions.AddRange(GetDefaultRootNodeActions()); } protected void CreateRootNodeActions() { CreateRootNodeActions(ref m_initActions); } /// <summary> /// This method creates the AllowedActions IAction list for the tree's nodes. /// Inheritors can override this method to create their own Context menu. /// </summary> /// <param name="actions"></param> protected virtual void CreateAllowedActions(ref List<IAction> actions) { actions.Add(ActionDelete.Instance); //raise the event, allow developers to modify the collection var e = new NodeActionsEventArgs(false, actions); OnNodeActionsCreated(e); actions = e.AllowedActions; } protected void CreateAllowedActions() { CreateAllowedActions(ref m_allowedActions); } /// <summary> /// A helper method to re-generate the root node for the current tree. /// </summary> /// <returns></returns> public XmlTreeNode GenerateRootNode() { XmlTreeNode node = XmlTreeNode.CreateRoot(this); this.CreateRootNode(ref node); return node; } /// <summary> /// This method can initialize the ITreeService parameters for this class with another ITreeService object. /// This method could be used for Dependency Injection. /// </summary> /// <param name="treeParams"></param> public void SetTreeParameters(ITreeService treeParams) { this.DialogMode = treeParams.DialogMode; this.NodeKey = treeParams.NodeKey; this.FunctionToCall = treeParams.FunctionToCall; this.IsDialog = treeParams.IsDialog; this.ShowContextMenu = treeParams.ShowContextMenu; this.id = treeParams.StartNodeID; if (!treeParams.ShowContextMenu) this.RootNode.Menu = null; } /// <summary> /// Returns the tree service url to render the tree /// </summary> /// <returns></returns> public string GetTreeInitUrl() { TreeService treeSvc = new TreeService(this.StartNodeID, TreeAlias, null, null, TreeDialogModes.none, ""); return treeSvc.GetInitUrl(); } /// <summary> /// Returns the tree service url to return the tree xml structure from the root node /// </summary> /// <returns></returns> public string GetTreeServiceUrl() { return GetTreeServiceUrl(this.StartNodeID); } /// <summary> /// Returns the tree service url to return the tree xml structure from the node passed in /// </summary> /// <param name="id"></param> /// <returns></returns> public string GetTreeServiceUrl(int id) { // updated by NH to pass showcontextmenu, isdialog and dialogmode variables TreeService treeSvc = new TreeService(id, TreeAlias, this.ShowContextMenu, this.IsDialog, this.DialogMode, ""); return treeSvc.GetServiceUrl(); } /// <summary> /// Returns the tree service url to return the tree xml structure based on a string node key. /// </summary> /// <param name="nodeKey"></param> /// <returns></returns> public string GetTreeServiceUrl(string nodeKey) { TreeService treeSvc = new TreeService(-1, TreeAlias, this.ShowContextMenu, this.IsDialog, this.DialogMode, "", nodeKey); return treeSvc.GetServiceUrl(); } /// <summary> /// Returns the tree service url to render the tree in dialog mode /// </summary> /// <returns></returns> public virtual string GetTreeDialogUrl() { TreeService treeSvc = new TreeService(this.StartNodeID, TreeAlias, false, true, this.DialogMode, ""); return treeSvc.GetServiceUrl(); } /// <summary> /// Returns the tree service url to render tree xml structure from the node passed in, in dialog mode. /// </summary> /// <param name="id"></param> /// <returns></returns> public virtual string GetTreeDialogUrl(int id) { TreeService treeSvc = new TreeService(id, TreeAlias, false, true, this.DialogMode, ""); return treeSvc.GetServiceUrl(); } /// <summary> /// Returns the serialized data for the nodeId passed in. /// </summary> /// <remarks> /// This may not work with ITrees that don't support the BaseTree structure with TreeService. /// If a tree implements other query string data to make it work, this may not function since /// it only relies on the 3 parameters. /// </remarks> /// <param name="alias"></param> /// <param name="nodeId"></param> /// <returns></returns> public string GetSerializedNodeData(string nodeId) { XmlTree xTree = new XmlTree(); int id; if (int.TryParse(nodeId, out id)) this.id = id; else this.NodeKey = nodeId; this.Render(ref xTree); return xTree.ToString(); } /// <summary> /// Returns a boolean value indicating if the ITree passed in is an extension of BaseTree. /// This is used to preserve backwards compatibility previous to version 5. /// </summary> /// <param name="tree"></param> /// <returns></returns> public static bool IsBaseTree(ITree tree) { return typeof(BaseTree).IsAssignableFrom(tree.GetType()); } /// <summary> /// Converts an ITree into a BaseTree. This is used for Legacy trees that don't inherit from BaseTree already. /// </summary> /// <param name="tree"></param> /// <param name="alias"></param> /// <param name="appAlias"></param> /// <param name="iconClosed"></param> /// <param name="iconOpened"></param> /// <param name="action"></param> /// <returns></returns> public static BaseTree FromITree(ITree tree, string alias, string appAlias, string iconClosed, string iconOpened, string action) { TreeService treeSvc = new TreeService(null, alias, null, null, TreeDialogModes.none, appAlias); //create the generic XmlTreeNode and fill it with the properties from the db NullTree nullTree = new NullTree(appAlias); XmlTreeNode node = XmlTreeNode.CreateRoot(nullTree); node.Text = BaseTree.GetTreeHeader(alias);; node.Action = action; node.Source = treeSvc.GetServiceUrl(); node.Icon = iconClosed; node.OpenIcon = iconOpened; node.NodeType = "init" + alias; node.NodeType = alias; node.NodeID = "init"; node.Menu = BaseTree.GetDefaultRootNodeActions(); //convert the tree to a LegacyTree LegacyTree bTree = new LegacyTree(tree, appAlias, node); return bTree; } /// <summary> /// Returns the default actions for a root node /// </summary> /// <returns></returns> public static List<IAction> GetDefaultRootNodeActions() { List<IAction> actions = new List<IAction>(); actions.Add(ActionNew.Instance); actions.Add(ContextMenuSeperator.Instance); actions.Add(ActionRefresh.Instance); return actions; } /// <summary> /// Returns the tree header title. If the alias isn't found in the language files, then it will /// return the title stored in the umbracoAppTree table. /// </summary> /// <param name="alias"></param> /// <returns></returns> public static string GetTreeHeader(string alias) { string treeCaption = ui.Text(alias); //this is a hack. the tree header title should be in the language files, however, if it is not, we're just //going to make it equal to what is specified in the db. if (treeCaption.Length > 0 && treeCaption.Substring(0, 1) == "[") { ApplicationTree tree = ApplicationTree.getByAlias(alias); if (tree != null) return tree.Title.SplitPascalCasing().ToFirstUpperInvariant(); } return treeCaption; } #region Events //These events are poorly designed because they cannot be implemented in the tree inheritance structure, //it would be up to the individual trees to ensure they launch the events which is not ideal. //they are also named in appropriately in regards to standards and because everything is by ref, there is no need to //have 2 events, makes no difference if you want to modify the contents of the data. public delegate void BeforeNodeRenderEventHandler(ref XmlTree sender, ref XmlTreeNode node, EventArgs e); public delegate void AfterNodeRenderEventHandler(ref XmlTree sender, ref XmlTreeNode node, EventArgs e); public static event BeforeNodeRenderEventHandler BeforeNodeRender; public static event AfterNodeRenderEventHandler AfterNodeRender; public static event EventHandler<TreeEventArgs> BeforeTreeRender; public static event EventHandler<TreeEventArgs> AfterTreeRender; /// <summary> /// Raises the <see cref="E:BeforeNodeRender"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected virtual void OnBeforeNodeRender(ref XmlTree sender, ref XmlTreeNode node, EventArgs e) { if (sender != null && node != null) { if (BeforeNodeRender != null) BeforeNodeRender(ref sender, ref node, e); } } /// <summary> /// Raises the <see cref="E:AfterNodeRender"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected virtual void OnAfterNodeRender(ref XmlTree sender, ref XmlTreeNode node, EventArgs e) { if (AfterNodeRender != null) AfterNodeRender(ref sender, ref node, e); } protected virtual void OnBeforeTreeRender(object sender, TreeEventArgs e) { if (BeforeTreeRender != null) BeforeTreeRender(sender, e); } protected virtual void OnAfterTreeRender(object sender, TreeEventArgs e) { if (AfterTreeRender != null) AfterTreeRender(sender, e); } [Obsolete("Do not use this method to raise events, it is no longer used and will cause very high performance spikes!")] protected internal virtual void OnBeforeTreeRender(IEnumerable<IUmbracoEntity> sender, TreeEventArgs e, bool isContent) { if (BeforeTreeRender != null) { if (isContent) { BeforeTreeRender(sender.Select(x => new Document(x, false)).ToArray(), e); } else { BeforeTreeRender(sender.Select(x => new Media(x, false)).ToArray(), e); } } } [Obsolete("Do not use this method to raise events, it is no longer used and will cause very high performance spikes!")] protected internal virtual void OnAfterTreeRender(IEnumerable<IUmbracoEntity> sender, TreeEventArgs e, bool isContent) { if (AfterTreeRender != null) { if (isContent) { AfterTreeRender(sender.Select(x => new Document(x, false)).ToArray(), e); } else { AfterTreeRender(sender.Select(x => new Media(x, false)).ToArray(), e); } } } /// <summary> /// Returns true if there are subscribers to either BeforeTreeRender or AfterTreeRender /// </summary> internal bool HasEntityBasedEventSubscribers { get { return BeforeTreeRender != null || AfterTreeRender != null; } } /// <summary> /// Event that is raised once actions are assigned to nodes /// </summary> public static event EventHandler<NodeActionsEventArgs> NodeActionsCreated; protected virtual void OnNodeActionsCreated(NodeActionsEventArgs e) { if (NodeActionsCreated != null) NodeActionsCreated(this, e); } #endregion //void IApplicationEventHandler.OnApplicationInitialized(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) //{ //} //void IApplicationEventHandler.OnApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) //{ //} //void IApplicationEventHandler.OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) //{ // TreeController.TreeNodesRendering += TreeController_TreeNodesRendering; //} //static void TreeController_TreeNodesRendering(TreeController sender, TreeNodesRenderingEventArgs e) //{ // var baseTree = new NullTree(""); // var legacyTree = new XmlTree(); // var toRemove = new List<TreeNode>(); // foreach (var node in e.Nodes) // { // //make the legacy node // var xNode = XmlTreeNode.Create(baseTree); // xNode.HasChildren = node.HasChildren; // xNode.IconClass = node.Icon; // xNode.NodeID = node.NodeId; // xNode.NodeType = sender.TreeAlias; // xNode.Text = node.Title; // xNode.TreeType = sender.TreeAlias; // //we cannot support this // //xNode.OpenIcon = node.Icon; // //xNode.Menu = ?? // baseTree.OnBeforeNodeRender(ref legacyTree, ref xNode, new EventArgs()); // //if the user has nulled this item, then we need to remove it // if (xNode == null) // { // toRemove.Add(node); // } // else // { // //add to the legacy tree - this mimics what normally happened in legacy trees // legacyTree.Add(xNode); // //now fire the after event // baseTree.OnAfterNodeRender(ref legacyTree, ref xNode, new EventArgs()); // //ok now we need to determine if we need to map any changes back to the real node // // these are the only properties that can be mapped back. // node.HasChildren = xNode.HasChildren; // node.Icon = xNode.IconClass; // if (xNode.Icon.IsNullOrWhiteSpace() == false) // { // node.Icon = xNode.Icon; // } // node.NodeType = xNode.NodeType; // node.Title = xNode.Text; // } // } // //now remove the nodes that were removed // foreach (var r in toRemove) // { // e.Nodes.Remove(r); // } //} } }
38.418321
153
0.566524
[ "MIT" ]
Abhith/Umbraco-CMS
src/Umbraco.Web/umbraco.presentation/umbraco/Trees/BaseTree.cs
25,166
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using CoreDDC.Config; namespace CoreDDC { public sealed class UpdateEngine { private readonly CoreDDCConfig config; public UpdateEngine(CoreDDCConfig config) { this.config = config; } public async Task<IPAddress> GetCurrentAddress(CancellationToken cancellationToken) {/* var providers = config.AddressProviders.ToList(); var results = new List<Task<IPAddress>>(); for (var i = 0; i < Math.Min(config.AddressLookupSettings.MinimumAgreeingProviderCount, providers.Count); i++) results.Add(CreateProvider<IPublicIPAddressProvider>(providers[i].ProviderType).Get(providers[i], cancellationToken)); await Task.WhenAll(results.Take(config.AddressLookupSettings.MinimumAgreeingProviderCount)); */ throw new NotImplementedException(); } private static T CreateProvider<T>(string typeName) => (T)Activator.CreateInstance(Type.GetType(typeName, true, true)); public Task UpdateAll(IPAddress newAddress, bool didChange, CancellationToken cancellationToken) => Task.WhenAll( from provider in config.UpdateProviders where didChange || provider.UpdateOnlyIfAddressChanges select CreateProvider<IDynamicDnsProvider>(provider.ProviderType) .Update(provider, newAddress, cancellationToken)); } }
36.363636
134
0.675625
[ "MIT" ]
jnm2/CoreDDC
src/CoreDDC/UpdateEngine.cs
1,602
C#
using System.Reflection; 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("SitemapGenerator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("SitemapGenerator")] [assembly: AssemblyCopyright("Copyright © Microsoft 2013")] [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("f5aa4943-dd42-49d7-8bab-b8cee11681c9")] // 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")]
36.538462
85
0.724912
[ "MIT" ]
ExcellentChoise/SitemapGenerator
SitemapGenerator/Properties/AssemblyInfo.cs
1,428
C#
// An example class for receiving and sending OSC messages with more than one remote partners // Here we expect messages from a Processing application that sends mouse positions (x,y) via port 8000 // The script should be added as a Unity Component to some 3D Unity object. using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityOSC; public class OSCExample3 : MonoBehaviour { // we are going to use two senders, for sending to two different remote apps string senderName1, senderName2; static int counter = 0; // used for incrementing message value // Use this for initialization void Start () { // We want to receive data from our applications, which are sending on port 7000 and port 8000 OSC.ReceiverPort(7000); OSC.ReceiverPort(8000); // We want to send data to our Processing applications, via port 50505 and 9000. // We expect that the Processing applications are running on the same machine, so we use // the special "local host" IP address 127.0.0.1 // Since we now have two "senders", we record their send names. senderName1=OSC.SenderAddress("127.0.0.1", 5050); senderName2=OSC.SenderAddress("127.0.0.1", 9000); // Register our "callback" method for messages labeled with address "/processing/mouse/" // This applies to messages from both port 7000 and port 8000. OSC.OnReceive("/processing/mouse/", MouseHandler); } // MouseHandler is our "callback" method, that will be called (by OSC) // It gets a List of <OSCArguments> representing the data being sent. // We expect two float values, representing a mouse position, and an extra string value. public void MouseHandler(List<OSCArgument> data) { // data[0] and data[1[ are floats with a mouse position, // data[2] is a string with some "message text" float x = data[0].floatValue; float y = data[1].floatValue; string msg = data [2].stringValue; float z = transform.position.z; float scale = 10.0f; Debug.Log ("Mouse position: " + x + ", " + y + " Text message: " + msg + "\n"); Vector3 newPos = new Vector3(scale*x, scale*y, z); transform.position = newPos; // Send different messages to our two remote applications. counter++; OSC.Send(senderName1, "/unity/test", (counter + 111) ); OSC.Send(senderName2, "/unity/test", (counter + 2222) ); } }
41.589286
103
0.717905
[ "MIT" ]
SaxionACT-Art-and-Technology/Unity-OSC
OSCUnityExample/UnityOscExample/Assets/Scripts/OSCExample3.cs
2,331
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; using System.Threading; using DataHandling; namespace NetworkModules { public interface INetConnector { int Available{get;} bool isConnected(); /* public StreamHandler getStreamHandler() { return _sh; } */ string getDestIp(); void ConnectToServer(string server, int port, int readTimeout = 0, int writeTimeout = 0); void ServerReady(string server, int port, int readTimeout = 0, int writeTimeout = 0); void setServerInfo(string server, int port, int readTimeout = 0, int writeTimeout = 0); void ReadyForClient(); void Connect(bool runReceiveThreadWhenConnected); void Disconnect(Func<int> runFuncBeforeCloseSocket=null); int readFromNet(Byte[] buff, int offset, int size); int write(Byte[] buff, int offset, int size); InterfaceFunctions Interface { get; } event ConnectionEventHandler E_Connection; event NetworkErrorEventHandler E_NetError; event TransferEventHandler E_OnReceived; } }
27.23913
97
0.656026
[ "Apache-2.0" ]
wootra/TestNetConnector
CommonModules/NetworkModules2/Interfaces/INetConnector.cs
1,255
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ADP_Tests.resources { public class Jenkins { public static string Browser = System.Environment.GetEnvironmentVariable("Browser"); public static string Environment = System.Environment.GetEnvironmentVariable("Environment"); public static string Impersonate = System.Environment.GetEnvironmentVariable("User to impersonate"); public static string BretId = System.Environment.GetEnvironmentVariable("BRET ID"); public static string Mep = System.Environment.GetEnvironmentVariable("MEP Company Code"); public static string CompanyCode = System.Environment.GetEnvironmentVariable("Benefits BOB Company Code"); public static string Env() { if (Environment.Equals("prod")) { Environment = "http://bsg-mobile-prod/dist/#/lobby"; } else if (Environment.Equals("dev")) { Environment = "http://bsg-mobile-dev/dist/#/lobby"; } else if (Environment.Equals("staging")) { Environment = "http://bsg-mobile-staging/dist/#/lobby"; } return Environment; } } }
35.756757
114
0.633409
[ "Apache-2.0" ]
adpautomation/ADPAutomation
ADP_Tests/ADP_Tests/resources/Jenkins.cs
1,325
C#
using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace CefNet.JSInterop { [StructLayout(LayoutKind.Explicit, Pack = 4, Size = 20)] public struct XrayHandle { [FieldOffset(0)] public long frame; [FieldOffset(8)] public XrayDataType dataType; [FieldOffset(12)] public IntPtr gcHandle; [FieldOffset(12)] public double fRaw; [FieldOffset(12)] public long iRaw; public XrayHandle(long frameid, IntPtr handle, XrayDataType dataType) { this.dataType = dataType; iRaw = 0; fRaw = 0; frame = frameid; this.gcHandle = handle; } public void Release() { if (gcHandle == IntPtr.Zero) return; GCHandle handle = GCHandle.FromIntPtr(this.gcHandle); gcHandle = IntPtr.Zero; if (handle.Target is XrayObject obj) obj.ReleaseHandle(); } public XrayObject GetTarget(CefFrame frame) { if (this.gcHandle == IntPtr.Zero) return null; if(frame is null || frame.Identifier != this.frame) throw new ObjectDeadException(); GCHandle handle = GCHandle.FromIntPtr(this.gcHandle); return (XrayObject)handle.Target; } public static readonly XrayHandle Zero; public static XrayHandle FromDateTime(DateTime t) { var h = new XrayHandle(); h.dataType = XrayDataType.Date; h.iRaw = t.ToBinary(); return h; } public unsafe CefBinaryValue ToCfxBinaryValue() { CefBinaryValue value; GCHandle handle = GCHandle.Alloc(this, GCHandleType.Pinned); value = new CefBinaryValue(handle.AddrOfPinnedObject(), sizeof(XrayHandle)); handle.Free(); return value; } public object ToObject() { switch(this.dataType) { case XrayDataType.Date: return DateTime.FromBinary(iRaw); case XrayDataType.Object: case XrayDataType.Function: case XrayDataType.CorsRedirect: return this; } throw new NotSupportedException(); } internal CefV8Value ToCefV8Value(CefFrame frame) { switch (this.dataType) { case XrayDataType.Date: return new CefV8Value(DateTime.FromBinary(iRaw)); case XrayDataType.Object: case XrayDataType.Function: XrayObject xray = this.GetTarget(frame); if (xray == null) throw new InvalidCastException(); return xray.Value; } throw new NotSupportedException(); } //public unsafe string Dump() //{ // var buffer = new byte[sizeof(XrayHandle)]; // fixed(byte* buf = buffer) // { // Marshal.StructureToPtr(this, (IntPtr)buf, false); // } // return string.Join(", ", buffer); //} public unsafe static XrayHandle FromCfxBinaryValue(CefBinaryValue v) { var xray = new XrayHandle(); v.GetData((IntPtr)(void*)&xray, sizeof(XrayHandle), 0); return xray; } public static unsafe bool operator ==(XrayHandle a, XrayHandle b) { ulong* a64 = (ulong*)&a; ulong* b64 = (ulong*)&b; uint* a32 = (uint*)&a; uint* b32 = (uint*)&b; return *a64 == *b64 && *(a64 + 1) == *(b64 + 1) && *(a32 + 4) == *(b32 + 4); } public static unsafe bool operator !=(XrayHandle a, XrayHandle b) { return !(a == b); } public override bool Equals(object obj) { if (obj is XrayHandle a) return this == a; return false; } public override int GetHashCode() { return base.GetHashCode(); } } }
22.29932
79
0.663514
[ "MIT" ]
AigioL/CefNet
CefNet/JSInterop/XrayHandle.cs
3,280
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Diagnostics { public class PullDiagnosticTests : AbstractLanguageServerProtocolTests { #region Document Diagnostics [Fact] public async Task TestNoDocumentDiagnosticsForClosedFilesWithFSAOff() { var markup = @"class A {"; using var workspace = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); var results = await RunGetDocumentPullDiagnosticsAsync( workspace, workspace.CurrentSolution.Projects.Single().Documents.Single()); Assert.Empty(results.Single().Diagnostics); } [Fact] public async Task TestDocumentDiagnosticsForOpenFilesWithFSAOff() { var markup = @"class A {"; using var workspace = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. workspace.Documents.Single().GetTextBuffer(); var results = await RunGetDocumentPullDiagnosticsAsync( workspace, workspace.CurrentSolution.Projects.Single().Documents.Single()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); } [Fact] public async Task TestNoDocumentDiagnosticsForOpenFilesWithFSAOffIfInPushMode() { var markup = @"class A {"; using var workspace = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects, pullDiagnostics: false); // Calling GetTextBuffer will effectively open the file. workspace.Documents.Single().GetTextBuffer(); var results = await RunGetDocumentPullDiagnosticsAsync( workspace, workspace.CurrentSolution.Projects.Single().Documents.Single()); Assert.Empty(results.Single().Diagnostics); } [Fact] public async Task TestDocumentDiagnosticsForRemovedDocument() { var markup = @"class A {"; using var workspace = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. workspace.Documents.Single().GetTextBuffer(); var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); // Get the diagnostics for the solution containing the doc. var solution = document.Project.Solution; var queue = CreateRequestQueue(solution); var server = GetLanguageServer(solution); await WaitForDiagnosticsAsync(workspace); var results = await server.ExecuteRequestAsync<DocumentDiagnosticsParams, DiagnosticReport[]>( queue, MSLSPMethods.DocumentPullDiagnosticName, CreateDocumentDiagnosticParams(document), new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); // Now remove the doc. workspace.OnDocumentRemoved(workspace.Documents.Single().Id); UpdateSolutionProvider(workspace, workspace.CurrentSolution); // And get diagnostic again, using the same doc-id as before. await WaitForDiagnosticsAsync(workspace); results = await server.ExecuteRequestAsync<DocumentDiagnosticsParams, DiagnosticReport[]>( queue, MSLSPMethods.DocumentPullDiagnosticName, new DocumentDiagnosticsParams { PreviousResultId = results.Single().ResultId, TextDocument = ProtocolConversions.DocumentToTextDocumentIdentifier(document) }, new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); Assert.Null(results.Single().Diagnostics); Assert.Null(results.Single().ResultId); } [Fact] public async Task TestNoChangeIfDocumentDiagnosticsCalledTwice() { var markup = @"class A {"; using var workspace = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. workspace.Documents.Single().GetTextBuffer(); var results = await RunGetDocumentPullDiagnosticsAsync( workspace, workspace.CurrentSolution.Projects.Single().Documents.Single()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); var resultId = results.Single().ResultId; results = await RunGetDocumentPullDiagnosticsAsync( workspace, workspace.CurrentSolution.Projects.Single().Documents.Single(), previousResultId: resultId); Assert.Null(results.Single().Diagnostics); Assert.Equal(resultId, results.Single().ResultId); } [Fact] public async Task TestDocumentDiagnosticsRemovedAfterErrorIsFixed() { var markup = @"class A {"; using var workspace = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. var buffer = workspace.Documents.Single().GetTextBuffer(); var results = await RunGetDocumentPullDiagnosticsAsync( workspace, workspace.CurrentSolution.Projects.Single().Documents.Single()); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); buffer.Insert(buffer.CurrentSnapshot.Length, "}"); results = await RunGetDocumentPullDiagnosticsAsync( workspace, workspace.CurrentSolution.Projects.Single().Documents.Single()); Assert.Empty(results[0].Diagnostics); } [Fact] public async Task TestDocumentDiagnosticsRemainAfterErrorIsNotFixed() { var markup = @"class A {"; using var workspace = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. var buffer = workspace.Documents.Single().GetTextBuffer(); var results = await RunGetDocumentPullDiagnosticsAsync( workspace, workspace.CurrentSolution.Projects.Single().Documents.Single()); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 9 }, results[0].Diagnostics.Single().Range.Start); buffer.Insert(0, " "); results = await RunGetDocumentPullDiagnosticsAsync( workspace, workspace.CurrentSolution.Projects.Single().Documents.Single(), previousResultId: results[0].ResultId); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 10 }, results[0].Diagnostics.Single().Range.Start); } [Fact] public async Task TestStreamingDocumentDiagnostics() { var markup = @"class A {"; using var workspace = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. workspace.Documents.Single().GetTextBuffer(); var progress = BufferedProgress.Create<DiagnosticReport>(null); var results = await RunGetDocumentPullDiagnosticsAsync( workspace, workspace.CurrentSolution.Projects.Single().Documents.Single(), progress: progress); Assert.Null(results); Assert.Equal("CS1513", progress.GetValues()!.Single().Diagnostics.Single().Code); } #endregion #region Workspace Diagnostics [Fact] public async Task TestNoWorkspaceDiagnosticsForClosedFilesWithFSAOff() { var markup1 = @"class A {"; var markup2 = ""; using var workspace = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.OpenFilesAndProjects); var results = await RunGetWorkspacePullDiagnosticsAsync(workspace); Assert.Empty(results); } [Fact] public async Task TestWorkspaceDiagnosticsForClosedFilesWithFSAOn() { var markup1 = @"class A {"; var markup2 = ""; using var workspace = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(workspace); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); } [Fact] public async Task TestNoWorkspaceDiagnosticsForClosedFilesWithFSAOnAndInPushMode() { var markup1 = @"class A {"; var markup2 = ""; using var workspace = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution, pullDiagnostics: false); var results = await RunGetWorkspacePullDiagnosticsAsync(workspace); Assert.Equal(2, results.Length); Assert.Empty(results[0].Diagnostics); Assert.Empty(results[1].Diagnostics); } [Fact] public async Task TestWorkspaceDiagnosticsForRemovedDocument() { var markup1 = @"class A {"; var markup2 = ""; using var workspace = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(workspace); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); workspace.OnDocumentRemoved(workspace.Documents.First().Id); UpdateSolutionProvider(workspace, workspace.CurrentSolution); var results2 = await RunGetWorkspacePullDiagnosticsAsync( workspace, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); // First doc should show up as removed. Assert.Equal(2, results2.Length); Assert.Null(results2[0].Diagnostics); Assert.Null(results2[0].ResultId); // Second doc should show up as unchanged. Assert.Null(results2[1].Diagnostics); Assert.Equal(results[1].ResultId, results2[1].ResultId); } private static DiagnosticParams[] CreateDiagnosticParamsFromPreviousReports(WorkspaceDiagnosticReport[] results) { return results.Select(r => new DiagnosticParams { TextDocument = r.TextDocument, PreviousResultId = r.ResultId }).ToArray(); } [Fact] public async Task TestNoChangeIfWorkspaceDiagnosticsCalledTwice() { var markup1 = @"class A {"; var markup2 = ""; using var workspace = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(workspace); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); var results2 = await RunGetWorkspacePullDiagnosticsAsync( workspace, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); Assert.Equal(2, results2.Length); Assert.Null(results2[0].Diagnostics); Assert.Null(results2[1].Diagnostics); Assert.Equal(results[0].ResultId, results2[0].ResultId); Assert.Equal(results[1].ResultId, results2[1].ResultId); } [Fact] public async Task TestWorkspaceDiagnosticsRemovedAfterErrorIsFixed() { var markup1 = @"class A {"; var markup2 = ""; using var workspace = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(workspace); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); var buffer = workspace.Documents.First().GetTextBuffer(); buffer.Insert(buffer.CurrentSnapshot.Length, "}"); var results2 = await RunGetWorkspacePullDiagnosticsAsync( workspace, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); Assert.Equal(2, results2.Length); Assert.Empty(results2[0].Diagnostics); Assert.Null(results2[1].Diagnostics); Assert.NotEqual(results[0].ResultId, results2[0].ResultId); Assert.Equal(results[1].ResultId, results2[1].ResultId); } [Fact] public async Task TestWorkspaceDiagnosticsRemainAfterErrorIsNotFixed() { var markup1 = @"class A {"; var markup2 = ""; using var workspace = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(workspace); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 9 }, results[0].Diagnostics.Single().Range.Start); Assert.Empty(results[1].Diagnostics); var buffer = workspace.Documents.First().GetTextBuffer(); buffer.Insert(0, " "); var results2 = await RunGetWorkspacePullDiagnosticsAsync(workspace); Assert.Equal("CS1513", results2[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 10 }, results2[0].Diagnostics.Single().Range.Start); Assert.Empty(results2[1].Diagnostics); Assert.NotEqual(results[1].ResultId, results2[1].ResultId); } [Fact] public async Task TestStreamingWorkspaceDiagnostics() { var markup1 = @"class A {"; var markup2 = ""; using var workspace = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(workspace); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 9 }, results[0].Diagnostics.Single().Range.Start); var progress = BufferedProgress.Create<DiagnosticReport>(null); results = await RunGetWorkspacePullDiagnosticsAsync(workspace, progress: progress); Assert.Null(results); Assert.Equal("CS1513", progress.GetValues()![0].Diagnostics![0].Code); } #endregion private static async Task<DiagnosticReport[]> RunGetDocumentPullDiagnosticsAsync( TestWorkspace workspace, Document document, string? previousResultId = null, IProgress<DiagnosticReport[]>? progress = null) { var solution = document.Project.Solution; var queue = CreateRequestQueue(solution); var server = GetLanguageServer(solution); await WaitForDiagnosticsAsync(workspace); var result = await server.ExecuteRequestAsync<DocumentDiagnosticsParams, DiagnosticReport[]>( queue, MSLSPMethods.DocumentPullDiagnosticName, CreateDocumentDiagnosticParams(document, previousResultId, progress), new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); return result; } private static async Task<WorkspaceDiagnosticReport[]> RunGetWorkspacePullDiagnosticsAsync( TestWorkspace workspace, DiagnosticParams[]? previousResults = null, IProgress<WorkspaceDiagnosticReport[]>? progress = null) { var solution = workspace.CurrentSolution; var queue = CreateRequestQueue(solution); var server = GetLanguageServer(solution); await WaitForDiagnosticsAsync(workspace); var result = await server.ExecuteRequestAsync<WorkspaceDocumentDiagnosticsParams, WorkspaceDiagnosticReport[]>( queue, MSLSPMethods.WorkspacePullDiagnosticName, CreateWorkspaceDiagnosticParams(previousResults, progress), new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); return result; } private static async Task WaitForDiagnosticsAsync(TestWorkspace workspace) { var listenerProvider = workspace.GetService<IAsynchronousOperationListenerProvider>(); await listenerProvider.GetWaiter(FeatureAttribute.Workspace).ExpeditedWaitAsync(); await listenerProvider.GetWaiter(FeatureAttribute.SolutionCrawler).ExpeditedWaitAsync(); await listenerProvider.GetWaiter(FeatureAttribute.DiagnosticService).ExpeditedWaitAsync(); } private static DocumentDiagnosticsParams CreateDocumentDiagnosticParams( Document document, string? previousResultId = null, IProgress<DiagnosticReport[]>? progress = null) { return new DocumentDiagnosticsParams { TextDocument = ProtocolConversions.DocumentToTextDocumentIdentifier(document), PreviousResultId = previousResultId, PartialResultToken = progress, }; } private static WorkspaceDocumentDiagnosticsParams CreateWorkspaceDiagnosticParams( DiagnosticParams[]? previousResults = null, IProgress<WorkspaceDiagnosticReport[]>? progress = null) { return new WorkspaceDocumentDiagnosticsParams { PreviousResults = previousResults, PartialResultToken = progress, }; } private TestWorkspace CreateTestWorkspaceWithDiagnostics(string markup, BackgroundAnalysisScope scope, bool pullDiagnostics = true) { var workspace = CreateTestWorkspace(markup, out _); InitializeDiagnostics(scope, workspace, pullDiagnostics); return workspace; } private TestWorkspace CreateTestWorkspaceWithDiagnostics(string[] markups, BackgroundAnalysisScope scope, bool pullDiagnostics = true) { var workspace = CreateTestWorkspace(markups, out _); InitializeDiagnostics(scope, workspace, pullDiagnostics); return workspace; } private static void InitializeDiagnostics(BackgroundAnalysisScope scope, TestWorkspace workspace, bool pullDiagnostics) { workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions( workspace.Options .WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp, scope) .WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.VisualBasic, scope) .WithChangedOption(InternalDiagnosticsOptions.NormalDiagnosticMode, pullDiagnostics ? DiagnosticMode.Pull : DiagnosticMode.Push))); var analyzerReference = new TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var registrationService = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); registrationService.Register(workspace); var diagnosticService = (DiagnosticService)workspace.ExportProvider.GetExportedValue<IDiagnosticService>(); diagnosticService.Register(new TestHostDiagnosticUpdateSource(workspace)); } } }
42.460784
174
0.655599
[ "MIT" ]
HurricanKai/roslyn
src/Features/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.cs
21,657
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Es.V20180416.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class GetRequestTargetNodeTypesResponse : AbstractModel { /// <summary> /// 接收请求的目标节点类型列表 /// </summary> [JsonProperty("TargetNodeTypes")] public string[] TargetNodeTypes{ get; set; } /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamArraySimple(map, prefix + "TargetNodeTypes.", this.TargetNodeTypes); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
31.392157
93
0.653342
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Es/V20180416/Models/GetRequestTargetNodeTypesResponse.cs
1,685
C#
using DbSafe; using Microsoft.VisualStudio.TestTools.UnitTesting; using ProductBL.Domain; using SqlDbSafe; using System; using System.Collections.Generic; using System.Linq; namespace ProductDAL.Tests { [TestClass] public class ProductDbTest { private ProductDb _target; private IDbSafeManager _dbSafe; private Category _category1 = new Category { Id = 1, Name = "category-1" }; private Category _category2 = new Category { Id = 2, Name = "category-2" }; private Category _category3 = new Category { Id = 3, Name = "category-3" }; private ProductSummary _productSummary1 = new ProductSummary { Id = 1, Code = "code-1", Name = "product-1", Category = "category-1", Supplier = "supplier-1" }; private ProductSummary _productSummary2 = new ProductSummary { Id = 2, Code = "code-2", Name = "product-2", Category = "category-1", Supplier = "supplier-2" }; private ProductSummary _productSummary3 = new ProductSummary { Id = 3, Code = "code-3", Name = "product-3", Category = "category-2", Supplier = "supplier-1" }; private Product _product2 = new Product { Id = 2, Code = "code-2", Name = "product-2", CategoryId = 1, SupplierId = 2, Cost = 102.10m, Description = "desc-2", ListPrice = 112.10m, ReleaseDate = new DateTime(2000, 1, 2), CreatedOn = new DateTime(2000, 1, 1, 10, 11, 12) }; private Product _product100 = new Product { Code = "code-100", Name = "product-100", CategoryId = 1, SupplierId = 2, Cost = 1000m, Description = "desc-100", ListPrice = 1100m, ReleaseDate = new DateTime(2010, 10, 10), CreatedOn = new DateTime(2010, 1, 1, 12, 12, 12) }; public TestContext TestContext { get; set; } [TestInitialize] public void Initialize() { _target = new ProductDb { Log = TestContext.WriteLine }; _dbSafe = SqlDbSafeManager.Initialize("product-db-test.xml") .SetConnectionString("ProductEntities-Test-Framework") .ExecuteScripts("delete-products", "delete-categories", "delete-suppliers", "reseed-product-table") .LoadTables("categories", "suppliers", "products") .RegisterFormatter(typeof(DateTime), new DateTimeFormatter("yyyy-MM-dd HH:mm:ss")) .RegisterFormatter("ReleaseDate", new DateTimeFormatter("yyyy-MM-dd")) .RegisterFormatter(typeof(decimal), new DecimalFormatter("0.00")); Console.WriteLine($"IsGlobalConfig: {_dbSafe.Config.IsGlobalConfig}, SerializeTests: {_dbSafe.Config.SerializeTests}, ReuseConnection: {_dbSafe.Config.ReuseConnection}"); } [TestCleanup] public void Cleanup() { _dbSafe?.Completed(); } [TestMethod] public void GetCategories_Must_return_all_the_categories() { var expected = new List<Category>() { _category1, _category2, _category3 }; var actual = _target.GetCategories(); AssertCategories(expected, actual); } [TestMethod] public void GetProductSummaries_Must_return_all_the_product_summaries() { var expected = new List<ProductSummary>() { _productSummary1, _productSummary2, _productSummary3 }; var actual = _target.GetProductSummaries(); AssertProductSummaries(expected, actual); } [TestMethod] public void GetProduct_Given_product_id_Must_return_correct_product() { var actual = _target.GetProduct(2); AssertProduct(_product2, actual); } [TestMethod] public void GetProduct_Given_not_found_product_id_Must_return_null() { var actual = _target.GetProduct(1000); Assert.IsNull(actual); } [TestMethod] public void AddProduct_Given_product_Must_insert_new_record() { _dbSafe.ExecuteScripts("mock_get_date"); _target.AddProduct(_product100); _dbSafe.AssertDatasetVsScript("products-after-insert", "select-all-products", "Id"); } [TestMethod] public void AddProduct_Given_product_with_an_invalid_category_Must_raise_an_exception() { _product100.CategoryId = 100; try { _target.AddProduct(_product100); Assert.Fail("An exception was not raised."); } catch (Exception ex) { Assert.AreEqual("Category not found", ex.InnerException.Message); } } [TestMethod] public void AddProduct_Given_product_Must_return_id_of_new_record() { var actual = _target.AddProduct(_product100); Assert.AreEqual(100, actual); } [TestMethod] public void UpdateSupplier_Given_supplier_Must_update_record_and_return_true() { var supplier2 = new Supplier { Id = 2, Name = "supplier-2-updated", ContactName = "contact-name-2-updated", ContactPhone = "100-200-9999", ContactEmail = "email-2-updated@test.com" }; var actual = _target.UpdateSupplier(supplier2); Assert.IsTrue(actual); _dbSafe.AssertDatasetVsScript("suppliers-updated", "select-all-suppliers", "Id"); } [TestMethod] public void UpdateSupplier_Given_an_id_that_does_not_exist_Must_return_false_whiout_updating_any_record() { var supplier2 = new Supplier { Id = 200, Name = "supplier-2-updated", ContactName = "contact-name-2-updated", ContactPhone = "100-200-9999", ContactEmail = "email-2-updated@test.com" }; var actual = _target.UpdateSupplier(supplier2); Assert.IsFalse(actual); _dbSafe.AssertDatasetVsScript("suppliers", "select-all-suppliers", "Id"); } private void AssertCategories(IList<Category> expected, IList<Category> actual) { Assert.AreEqual(expected.Count, actual.Count); foreach (var expectedCategory in expected) { var actualCategory = actual.FirstOrDefault(a => a.Id == expectedCategory.Id); Assert.IsNotNull(actualCategory, $"Category with Id '{expectedCategory.Id}' not found."); AssertCategory(expectedCategory, actualCategory); } } private void AssertCategory(Category expected, Category actual) { Assert.AreEqual(expected.Id, actual.Id); Assert.AreEqual(expected.Name, actual.Name); } private void AssertProductSummaries(IList<ProductSummary> expected, IList<ProductSummary> actual) { Assert.AreEqual(expected.Count, actual.Count); foreach (var expectedProductSummary in expected) { var actualSummary = actual.FirstOrDefault(a => a.Id == expectedProductSummary.Id); Assert.IsNotNull(actualSummary, $"Category with Id '{expectedProductSummary.Id}' not found."); AssertProductSummary(expectedProductSummary, actualSummary); } } private void AssertProductSummary(ProductSummary expected, ProductSummary actual) { Assert.AreEqual(expected.Category, actual.Category); Assert.AreEqual(expected.Code, actual.Code); Assert.AreEqual(expected.Id, actual.Id); Assert.AreEqual(expected.Name, actual.Name); Assert.AreEqual(expected.Supplier, actual.Supplier); } private void AssertProduct(Product expected, Product actual) { Assert.AreEqual(expected.CategoryId, actual.CategoryId); Assert.AreEqual(expected.Code, actual.Code); Assert.AreEqual(expected.Cost, actual.Cost); Assert.AreEqual(expected.Description, actual.Description); Assert.AreEqual(expected.Id, actual.Id); Assert.AreEqual(expected.ListPrice, actual.ListPrice); Assert.AreEqual(expected.Name, actual.Name); Assert.AreEqual(expected.SupplierId, actual.SupplierId); Assert.AreEqual(expected.ReleaseDate, actual.ReleaseDate); Assert.AreEqual(expected.CreatedOn, actual.CreatedOn); } private string FormatDateTime(DateTime value) { if (value.TimeOfDay == TimeSpan.Zero) { return value.ToString("yyyy-MM-dd"); } else { return value.ToString("yyyy-MM-dd HH:mm:ss"); } } private string FormatDateTimeWithMs(DateTime value) { if (value.TimeOfDay == TimeSpan.Zero) { return value.ToString("yyyy-MM-dd"); } if (value.TimeOfDay.Milliseconds == 0) { return value.ToString("yyyy-MM-dd HH:mm:ss"); } return value.ToString("yyyy-MM-dd HH:mm:ss.fff"); } } }
38.305785
279
0.602913
[ "MIT" ]
dbsafe/dbsafe-demo
ProductDAL.Tests/ProductDbTest.cs
9,272
C#
using Harmony; using PhoenixPoint.Geoscape.Entities; using PhoenixPoint.Geoscape.Entities.Missions; namespace AssortedAdjustments.LimitedWar { internal static class Store { internal static int GameDifficulty = 1; // Default to Veteran in case anything goes wrong internal static IGeoFactionMissionParticipant LastAttacker = null; internal static GeoHavenDefenseMission DefenseMission = null; } // Store mission for other patches [HarmonyPatch(typeof(GeoHavenDefenseMission), "UpdateGeoscapeMissionState")] public static class GeoHavenDefenseMission_UpdateGeoscapeMissionState_Patch { public static bool Prepare() { //return Config.LimitFactionAttacksToZones || Config.LimitPandoranAttacksToZones; return Config.Enable; } public static void Prefix(GeoHavenDefenseMission __instance) { Store.DefenseMission = __instance; } public static void Postfix() { Store.DefenseMission = null; } } }
31.382353
97
0.691659
[ "MIT" ]
Mad-Mods-Phoenix-Point/AssortedAdjustments
Source/AssortedAdjustments/Patches/LimitedWar/Store.cs
1,069
C#
/* * Original author: Brendan MacLean <brendanx .at. u.washington.edu>, * MacCoss Lab, Department of Genome Sciences, UW * * Copyright 2009 University of Washington - Seattle, WA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using pwiz.Skyline.Model; using pwiz.Skyline.Model.DocSettings; using pwiz.Skyline.Model.DocSettings.Extensions; using pwiz.Skyline.Properties; using pwiz.SkylineTestUtil; namespace pwiz.SkylineTestA { /// <summary> /// Tests for <see cref="IsotopeLabelType"/> modifications. /// </summary> [TestClass] public class IsotypeModTest : AbstractUnitTest { private static readonly IsotopeLabelType LABEL_TYPE13_C = new IsotopeLabelType("KR 13C", IsotopeLabelType.FirstHeavy); private static readonly IsotopeLabelType LABEL_TYPE15_N = new IsotopeLabelType("All 15N", IsotopeLabelType.FirstHeavy + 1); private static readonly List<StaticMod> HEAVY_MODS_13_C = new List<StaticMod> { new StaticMod("13C K", "K", ModTerminus.C, null, LabelAtoms.C13, null, null), new StaticMod("13C R", "R", ModTerminus.C, null, LabelAtoms.C13, null, null), }; private static readonly List<StaticMod> HEAVY_MODS_15_N = new List<StaticMod> { new StaticMod("15N", null, null, null, LabelAtoms.N15, null, null), }; [TestMethod] public void MultiLabelTypeTest() { int startRev = 0; SrmDocument document = new SrmDocument(SrmSettingsList.GetDefault().ChangeTransitionInstrument(inst => inst.ChangeMaxMz(1800))); // Add some FASTA IdentityPath path, pathRoot = IdentityPath.ROOT; SrmDocument docFasta = document.ImportFasta(new StringReader(ExampleText.TEXT_FASTA_YEAST_LIB), false, pathRoot, out path); const int initProt = 2, initPep = 26, initTran = 89; AssertEx.IsDocumentState(docFasta, ++startRev, initProt, initPep, initTran); // Add multiple heavy types var settings = docFasta.Settings.ChangePeptideModifications(mods => new PeptideModifications(mods.StaticModifications, new[] { new TypedModifications(LABEL_TYPE13_C, HEAVY_MODS_13_C), new TypedModifications(LABEL_TYPE15_N, HEAVY_MODS_15_N) })); var docMulti = docFasta.ChangeSettings(settings); // Make sure the contents of the resulting document are as expected. int countProteinTermTran, countProteinTerm; VerifyMultiLabelContent(docFasta, docMulti, out countProteinTerm, out countProteinTermTran); int multiGroupCount = initPep*3 - countProteinTerm; int multiTranCount = initTran*3 - countProteinTermTran; AssertEx.IsDocumentState(docMulti, ++startRev, initProt, initPep, multiGroupCount, multiTranCount); // Turn off auto-manage children on all peptides var listPepGroups = new List<DocNode>(); foreach (PeptideGroupDocNode nodePepGroup in docMulti.MoleculeGroups) { var listPeptides = new List<DocNode>(); foreach (PeptideDocNode nodePep in nodePepGroup.Children) listPeptides.Add(nodePep.ChangeAutoManageChildren(false)); listPepGroups.Add(nodePepGroup.ChangeChildren(listPeptides)); } var docNoAuto = (SrmDocument) docMulti.ChangeChildren(listPepGroups); startRev++; // Switch back to settings without isotope labels var docNoAutoLight = docNoAuto.ChangeSettings(docFasta.Settings); // The document should return to its initial state AssertEx.IsDocumentState(docNoAutoLight, ++startRev, initProt, initPep, initTran); // Switch back to Settings with isotope labels var docNoAutoLabeled = docNoAutoLight.ChangeSettings(docMulti.Settings); // The number of nodes should not change AssertEx.IsDocumentState(docNoAutoLabeled, ++startRev, initProt, initPep, initTran); // Remove all document nodes var docEmpty = (SrmDocument) docNoAutoLabeled.ChangeChildren(new PeptideGroupDocNode[0]); // Paste FASTA back in var docRePaste = docEmpty.ImportFasta(new StringReader(ExampleText.TEXT_FASTA_YEAST_LIB), false, pathRoot, out path); // This should produce the same document as the original settings change Assert.AreEqual(docMulti, docRePaste); } [TestMethod] public void MultiLabelTypeListTest() { TestSmallMolecules = false; // we don't expect to roundtrip export/import of transition lists for non-proteomic molecules int startRev = 0; SrmDocument document = new SrmDocument(SrmSettingsList.GetDefault().ChangeTransitionInstrument(inst => inst.ChangeMaxMz(1800))); // Add some FASTA IdentityPath path, pathRoot = IdentityPath.ROOT; SrmDocument docFasta = document.ImportFasta(new StringReader(ExampleText.TEXT_FASTA_YEAST_LIB), false, pathRoot, out path); const int initProt = 2, initPep = 26, initTran = 89; AssertEx.IsDocumentState(docFasta, ++startRev, initProt, initPep, initTran); // Add multiple heavy types var settings = docFasta.Settings.ChangePeptideModifications(mods => new PeptideModifications(mods.StaticModifications, new[] { new TypedModifications(LABEL_TYPE13_C, HEAVY_MODS_13_C), new TypedModifications(LABEL_TYPE15_N, HEAVY_MODS_15_N) })); var docMulti = docFasta.ChangeSettings(settings); // CONSIDER: make explicit S-Lens, cone voltage, CE etc roundtrip? // docMulti.MoleculeTransitionGroups.FirstOrDefault().ChangeExplicitValues(ExplicitTransitionGroupValues.TEST) // Make sure transition lists export to various formats and roundtrip VerifyExportRoundTrip(new ThermoMassListExporter(docMulti), docFasta); // Add Oxidation (M) as a static modification to challenge new mass list importing flexibility VerifyExportRoundTrip(new AbiMassListExporter(AddOxidationM(docMulti)), AddOxidationM(docFasta)); VerifyExportRoundTrip(new AgilentMassListExporter(docMulti), docFasta); VerifyExportRoundTrip(new WatersMassListExporter(docMulti), docFasta); } private SrmDocument AddOxidationM(SrmDocument doc) { return doc.ChangeSettings( doc.Settings.ChangePeptideModifications(mod => { var staticMods = mod.StaticModifications.ToList(); staticMods.Add(UniMod.GetModification("Oxidation (M)", true).ChangeVariable(false)); return mod.ChangeStaticModifications(staticMods); })); } [TestMethod] public void MultiLabelExplicitSerialTest() { // Create a simple document and add two peptides SrmDocument document = new SrmDocument(SrmSettingsList.GetDefault()); const string pepSequence1 = "QFVLSCVILR"; const string pepSequence2 = "DIEVYCDGAITTK"; var reader = new StringReader(string.Join("\n", new[] {">peptides1", pepSequence1, pepSequence2})); IdentityPath path; document = document.ImportFasta(reader, true, IdentityPath.ROOT, out path); Assert.AreEqual(2, document.PeptideCount); // Add some modifications in two new label types var modCarb = new StaticMod("Carbamidomethyl Cysteine", "C", null, "C2H3ON"); var modOther = new StaticMod("Another Cysteine", "C", null, "CO8N2"); var staticMods = new[] {modCarb, modOther}; var mod15N = new StaticMod("All 15N", null, null, null, LabelAtoms.N15, null, null); var modK13C = new StaticMod("13C K", "K", ModTerminus.C, null, LabelAtoms.C13, null, null); var modR13C = new StaticMod("13C R", "R", ModTerminus.C, null, LabelAtoms.C13, null, null); var modV13C = new StaticMod("Heavy V", "V", null, null, LabelAtoms.C13 | LabelAtoms.N15, null, null); var heavyMods = new[] { mod15N, modK13C, modR13C, modV13C }; var labelTypeAA = new IsotopeLabelType("heavy AA", IsotopeLabelType.FirstHeavy); var labelTypeAll = new IsotopeLabelType("heavy All", IsotopeLabelType.FirstHeavy + 1); var settings = document.Settings; settings = settings.ChangePeptideModifications(mods => new PeptideModifications(mods.StaticModifications, new[] { new TypedModifications(labelTypeAA, new[] {modK13C, modR13C}), new TypedModifications(labelTypeAll, new[] {mod15N}) })); document = document.ChangeSettings(settings); Assert.AreEqual(6, document.PeptideTransitionGroupCount); // Add modifications to light and heavy AA in the first peptide path = document.GetPathTo((int) SrmDocument.Level.Molecules, 0); var nodePepMod = (PeptideDocNode) document.FindNode(path); var explicitMod = new ExplicitMods(nodePepMod.Peptide, new[] {new ExplicitMod(pepSequence1.IndexOf('C'), modOther)}, new[] {new TypedExplicitModifications(nodePepMod.Peptide, labelTypeAA, new ExplicitMod[0])}); document = document.ChangePeptideMods(path, explicitMod, staticMods, heavyMods); Assert.AreEqual(5, document.PeptideTransitionGroupCount); // Add a modification to heavy All in the second peptide path = document.GetPathTo((int)SrmDocument.Level.Molecules, 1); nodePepMod = (PeptideDocNode)document.FindNode(path); explicitMod = new ExplicitMods(nodePepMod.Peptide, null, new[] { new TypedExplicitModifications(nodePepMod.Peptide, labelTypeAll, new[] {new ExplicitMod(pepSequence2.IndexOf('V'), modV13C)}) }); document = document.ChangePeptideMods(path, explicitMod, staticMods, heavyMods); Assert.AreEqual(5, document.PeptideTransitionGroupCount); AssertEx.Serializable(document, 3, AssertEx.DocumentCloned); } private static void VerifyExportRoundTrip(AbstractMassListExporter exporter, SrmDocument docFasta) { var docImport = AssertEx.RoundTripTransitionList(exporter); int countProteinTermTran, countProteinTerm; VerifyMultiLabelContent(docFasta, docImport, out countProteinTerm, out countProteinTermTran); } private static void VerifyMultiLabelContent(SrmDocument docFasta, SrmDocument docMulti, out int countProteinTerm, out int countProteinTermTran) { countProteinTerm = 0; countProteinTermTran = 0; var dictPeptides = new Dictionary<string, PeptideDocNode>(); foreach (var nodePep in docFasta.Peptides) dictPeptides.Add(nodePep.Peptide.Sequence, nodePep); foreach (var nodePep in docMulti.Peptides) { PeptideDocNode nodePepOld; Assert.IsTrue(dictPeptides.TryGetValue(nodePep.Peptide.Sequence, out nodePepOld)); // Make sure precursor m/z values are changing in the right direction TransitionGroupDocNode nodeGroupPrev = null; foreach (TransitionGroupDocNode nodeGroup in nodePep.Children) { if (nodeGroupPrev != null) Assert.IsTrue(nodeGroup.PrecursorMz > nodeGroupPrev.PrecursorMz + 1); nodeGroupPrev = nodeGroup; } if (nodePep.TransitionGroupCount == 2) { if (nodePep.Peptide.FastaSequence != null && nodePep.Peptide.End != nodePep.Peptide.FastaSequence.Sequence.Length) Assert.AreEqual(3, nodePep.Children.Count); countProteinTerm++; countProteinTermTran += nodePepOld.TransitionCount; } else { Assert.AreEqual(nodePepOld.TransitionCount * 3, nodePep.TransitionCount); var nodeGroup13C = (TransitionGroupDocNode)nodePep.Children[1]; Assert.AreEqual(LABEL_TYPE13_C, nodeGroup13C.TransitionGroup.LabelType); } var nodeGroup15N = (TransitionGroupDocNode)nodePep.Children[nodePep.TransitionGroupCount - 1]; Assert.AreEqual(LABEL_TYPE15_N, nodeGroup15N.TransitionGroup.LabelType); } // Should be only one protein-terminal peptide Assert.AreEqual(1, countProteinTerm); } } }
52.513011
141
0.627283
[ "Apache-2.0" ]
shze/pwizard-deb
pwiz_tools/Skyline/TestA/IsotypeModTest.cs
14,126
C#
// Copyright (c) 2019 Jennifer Messerly // This code is licensed under MIT license (see LICENSE for details) using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Kingmaker; using Kingmaker.AreaLogic; using Kingmaker.Assets.UI.LevelUp; using Kingmaker.Blueprints; using Kingmaker.Blueprints.Classes; using Kingmaker.Blueprints.Classes.Prerequisites; using Kingmaker.Blueprints.Classes.Selection; using Kingmaker.Blueprints.Classes.Spells; using Kingmaker.Blueprints.Facts; using Kingmaker.Blueprints.Items; using Kingmaker.Blueprints.Items.Equipment; using Kingmaker.Blueprints.Root; using Kingmaker.Controllers; using Kingmaker.Controllers.Combat; using Kingmaker.Controllers.Units; using Kingmaker.Designers; using Kingmaker.Designers.Mechanics.Buffs; using Kingmaker.Designers.Mechanics.Facts; using Kingmaker.Designers.Mechanics.Recommendations; using Kingmaker.ElementsSystem; using Kingmaker.EntitySystem.Entities; using Kingmaker.EntitySystem.Stats; using Kingmaker.Enums; using Kingmaker.Enums.Damage; using Kingmaker.Localization; using Kingmaker.PubSubSystem; using Kingmaker.RuleSystem; using Kingmaker.RuleSystem.Rules; using Kingmaker.RuleSystem.Rules.Abilities; using Kingmaker.RuleSystem.Rules.Damage; using Kingmaker.UI.Common; using Kingmaker.UI.LevelUp; using Kingmaker.UI.ServiceWindow.CharacterScreen; using Kingmaker.UI.Tooltip; using Kingmaker.UnitLogic; using Kingmaker.UnitLogic.Abilities; using Kingmaker.UnitLogic.Abilities.Blueprints; using Kingmaker.UnitLogic.Abilities.Components; using Kingmaker.UnitLogic.Abilities.Components.Base; using Kingmaker.UnitLogic.ActivatableAbilities; using Kingmaker.UnitLogic.Buffs; using Kingmaker.UnitLogic.Buffs.Actions; using Kingmaker.UnitLogic.Buffs.Blueprints; using Kingmaker.UnitLogic.Buffs.Components; using Kingmaker.UnitLogic.Class.LevelUp; using Kingmaker.UnitLogic.Class.LevelUp.Actions; using Kingmaker.UnitLogic.Commands; using Kingmaker.UnitLogic.Commands.Base; using Kingmaker.UnitLogic.FactLogic; using Kingmaker.UnitLogic.Mechanics; using Kingmaker.UnitLogic.Mechanics.Actions; using Kingmaker.UnitLogic.Mechanics.Components; using Kingmaker.UnitLogic.Parts; using Kingmaker.Utility; using Kingmaker.View; using Kingmaker.Visual.Animation.Kingmaker.Actions; using Kingmaker.Visual.Sound; using Newtonsoft.Json; using UnityEngine; using static Kingmaker.RuleSystem.RulebookEvent; namespace EldritchArcana { static class OracleArchetypes { static LibraryScriptableObject library => Main.library; static BlueprintCharacterClass oracle => OracleClass.oracle; static BlueprintCharacterClass[] oracleArray => OracleClass.oracleArray; internal static List<BlueprintArchetype> Create(BlueprintFeatureSelection mystery, BlueprintFeatureSelection revelation, BlueprintFeature mysteryClassSkills) { var archetypes = new List<BlueprintArchetype>(); archetypes.Add(CreateSeeker(revelation, mysteryClassSkills)); archetypes.Add(CreateAncientLorekeeper(mystery, mysteryClassSkills)); //archetypes.Add(CreateDivineHerbalist(revelation, mysteryClassSkills)); // TODO: oracle archetypes? Ideas // - Divine Herbalist (paladin feel -- lay on hands & chance to cure conditions, popular choice with Life) // - Dual Cursed (very popular choice, not too hard to implement other than the spells, see below.) // - Elementalist Oracle (not too bad if Admixture subschool is implemented.) // - ... // // Dual Cursed: // - Fortune: is basically the same as Rewind Time, so it's already implemented. // - Misfortune: forcing enemies to reroll saving throws is generally the best use // of this ability; a toggle could be used to enable this for all enemies. Similar // to Persistent Spell. // - Ill Omen spell: kind of like Rewind Time but reversed, must take worse rolls. // - Oracle's burden: a bit tricky because the curses are not really designed to work // on return archetypes; } static BlueprintArchetype CreateAncientLorekeeper(BlueprintFeatureSelection mysteries, BlueprintFeature mysteryClassSkills) { var lorekeeper = Helpers.Create<BlueprintArchetype>(a => { a.name = "AncientLorekeeperArchetype"; a.LocalizedName = Helpers.CreateString($"{a.name}.Name", "Ancient Lorekeeper"); a.LocalizedDescription = Helpers.CreateString($"{a.name}.Description", "The ancient lorekeeper is a repository for all the beliefs and vast knowledge of an elven people. They show a strong interest in and understanding of histories and creation legends at a young age, and as they mature their calling to serve as the memory of their long-lived people becomes clear to all who know them.\n" + "An ancient lorekeeper adds Knowledge (arcana) to their list of class skills. This replaces the bonus skills the ancient lorekeeper gains from their mystery."); }); Helpers.SetField(lorekeeper, "m_ParentClass", oracle); library.AddAsset(lorekeeper, "df571bf056a941babe0903e94430dc9d"); lorekeeper.RemoveFeatures = new LevelEntry[] { Helpers.LevelEntry(1, mysteryClassSkills), }; var classSkill = Helpers.CreateFeature("AncientLorekeeperClassSkills", UIUtility.GetStatText(StatType.SkillKnowledgeArcana), "An ancient lorekeeper adds Knowledge (arcana) to their class skills.", "a6edf10077d24a95b6d8a701b8fb51d5", null, FeatureGroup.None, Helpers.Create<AddClassSkill>(a => a.Skill = StatType.SkillKnowledgeArcana)); var entries = new List<LevelEntry> { Helpers.LevelEntry(1, classSkill), }; var elvenArcana = CreateElvenArcana(); for (int level = 2; level <= 18; level += 2) { entries.Add(Helpers.LevelEntry(level, elvenArcana)); } lorekeeper.AddFeatures = entries.ToArray(); // Enable archetype prerequisites var patchDescription = "Archetype prerequisites (such as Ancient Lorekeeper)"; Main.ApplyPatch(typeof(CharBSelectorLayer_FillData_Patch), patchDescription); Main.ApplyPatch(typeof(DescriptionTemplatesLevelup_LevelUpClassPrerequisites_Patch), patchDescription); Main.ApplyPatch(typeof(CharacterBuildController_SetRace_Patch), patchDescription); lorekeeper.SetComponents( Helpers.PrerequisiteFeaturesFromList(Helpers.elf, Helpers.halfElf)); // Adjust prerequisites for mysteries foreach (var mystery in mysteries.AllFeatures) { if (mystery == TimeMystery.mystery) { mystery.AddComponent(Helpers.Create<PrerequisiteArchetypeLevel>(p => { p.Archetype = lorekeeper; p.CharacterClass = oracle; })); } else { mystery.AddComponent(Helpers.Create<PrerequisiteNoArchetype>(p => { p.Archetype = lorekeeper; p.CharacterClass = oracle; })); } } return lorekeeper; } static BlueprintFeature CreateElvenArcana() { var elvenMagic = library.Get<BlueprintFeature>("55edf82380a1c8540af6c6037d34f322"); var chooseSpell = Helpers.CreateParamSelection<SelectAnySpellAtComputedLevel>( "AncientLorekeeperElvenArcana", "Elven Arcana", "At 2nd level, an ancient lorekeeper’s mastery of elven legends and philosophy has allowed them to master one spell used by elven wizards. They select one spell from the sorcerer/ wizard spell list that is at least one level lower than the highest-level oracle spell they can cast. The ancient lorekeeper gains this as a bonus spell known. The spell is treated as one level higher than its true level for all purposes. The ancient lorekeeper may choose an additional spell at 4th, 6th, 8th, 10th, 12th, 14th, 16th, and 18th levels.\n" + "This ability replaces the bonus spells they would normally gain at these levels from their chosen mystery.", "aee6d141ddd545c287f64e553ab0bf04", elvenMagic.Icon, FeatureGroup.None, Helpers.wizardSpellList.CreateLearnSpell(oracle, penalty: 1)); chooseSpell.Ranks = 9; chooseSpell.SpellList = Helpers.wizardSpellList; chooseSpell.SpellcasterClass = oracle; chooseSpell.SpellLevelPenalty = 1; var selection = Helpers.CreateFeatureSelection($"{chooseSpell.name}Selection", chooseSpell.Name, chooseSpell.Description, "51ed5bf78de74e0cb6e55024bb948f7e", chooseSpell.Icon, FeatureGroup.None); selection.SetFeatures(chooseSpell); return selection; } static BlueprintArchetype CreateSeeker(BlueprintFeatureSelection revelation, BlueprintFeature mysteryClassSkills) { var seeker = Helpers.Create<BlueprintArchetype>(a => { a.name = "SeekerOracleArchetype"; a.LocalizedName = Helpers.CreateString($"{a.name}.Name", "Seeker"); a.LocalizedDescription = Helpers.CreateString($"{a.name}.Description", "Oracles gain their magical powers through strange and mysterious ways, be they chosen by fate or blood. While most might be content with their strange powers, some oracles join the Pathfinders specifically to find out more about their mysteries and determine the genesis and history of their eldritch talents. These spellcasters are known among the Spells as seekers, after their obsession with researching ancient texts and obscure ruins for any clues they can find about their heritage and histories."); }); Helpers.SetField(seeker, "m_ParentClass", oracle); library.AddAsset(seeker, "15c95e56e3414c089b624b50c18127a0"); seeker.RemoveFeatures = new LevelEntry[] { Helpers.LevelEntry(1, mysteryClassSkills), Helpers.LevelEntry(3, revelation), Helpers.LevelEntry(15, revelation), }; seeker.AddFeatures = new LevelEntry[] { Helpers.LevelEntry(1, CreateSeekerTinkering()), Helpers.LevelEntry(3, CreateSeekerLore()), Helpers.LevelEntry(15, CreateSeekerMagic()), }; return seeker; } static BlueprintFeature CreateSeekerTinkering() { var trapfinding = library.Get<BlueprintFeature>("dbb6b3bffe6db3547b31c3711653838e"); var tinkering = Helpers.CreateFeature("SeekerTinkering", "Tinkering", "Seekers often look to ancient devices, old tomes, and strange magical items in order to learn more about their oracle mysteries. As a result of this curiosity and thanks to an innate knack at deciphering the strange and weird, a seeker adds half their oracle level on Perception checks made to locate traps (minimum +1). If the seeker also possesses levels in rogue or another class that provides the trapfinding ability, those levels stack with their oracle levels for determining their overall bonus on these skill checks.\nThis ability replaces all of the bonus class skills they would otherwise normally gain from their mystery.", "fe8c5a9648414b35ae86176b7d77ea2b", trapfinding.Icon, FeatureGroup.None, Helpers.CreateContextRankConfig(ContextRankBaseValueType.ClassLevel, ContextRankProgression.Div2, min: 1, classes: oracleArray), Helpers.CreateAddContextStatBonus(StatType.SkillPerception, ModifierDescriptor.UntypedStackable)); return tinkering; } static BlueprintFeature CreateSeekerLore() { var arcaneCombatCastingAdept = library.Get<BlueprintFeature>("7aa83ee3526a946419561d8d1aa09e75"); var feat = Helpers.CreateFeature("SeekerLore", "Seeker Lore", "By 3rd level, a seeker has already learned much about their mystery, and is more comfortable using the bonus spells gained by that mystery. They gain a +4 bonus on all concentration checks, on caster level checks made to overcome spell resistance with their bonus spells.\nThis ability replaces the revelation gained at 3rd level.", "64270d88d68f4aaca5dd986fd6b60f1c", arcaneCombatCastingAdept.Icon, FeatureGroup.None, Helpers.Create<ConcentrationBonusForGrantedSpells>(c => c.Class = oracle), Helpers.Create<SpellPenetrationBonusForGrantedSpells>(s => s.Class = oracle)); return feat; } static BlueprintFeature CreateSeekerMagic() { var arcaneSchoolPower = library.Get<BlueprintFeatureSelection>("3524a71d57d99bb4b835ad20582cf613"); var feat = Helpers.CreateFeature("SeekerMagic", "Seeker Magic", "At 15th level, a seeker becomes skilled at modifying their mystery spells with metamagic. When a seeker applies a metamagic feat to any bonus spells granted by their mystery, they reduce the metamagic feat’s spell level adjustment by 1. Thus, applying a Metamagic feat like Extend Spell to a spell does not change its effective spell level at all, while applying Quicken Spell only increases the spell’s effective spell level by 3 instead of by 4. This reduction to the spell level adjustment for Metamagic feats does not stack with similar reductions from other abilities.\nThis ability replaces the revelation gained at 15th level.", "201005185def4d7687a94c81b9b9394d", arcaneSchoolPower.Icon, FeatureGroup.None, Helpers.Create<ReduceMetamagicCostForGrantedSpells>(r => r.Class = oracle)); return feat; } internal static bool IsGrantedSpell(UnitDescriptor unit, BlueprintAbility spell) { return unit.Progression.Features.Enumerable .SelectMany(f => f.Blueprint.GetComponents<AddKnownSpell>()) .Any(a => a.Spell == spell); } internal static bool MeetsPrerequisites(BlueprintArchetype archetype, UnitDescriptor unit, LevelUpState state) { bool? all = null; bool? any = null; foreach (var prerequisite in archetype.GetComponents<Prerequisite>()) { var passed = prerequisite.Check(null, unit, state); if (prerequisite.Group == Prerequisite.GroupType.All) { all = (!all.HasValue) ? passed : (all.Value && passed); } else { any = (!any.HasValue) ? passed : (any.Value || passed); } } var result = (!all.HasValue || all.Value) && (!any.HasValue || any.Value); return result; } } public class SpellPenetrationBonusForGrantedSpells : RuleInitiatorLogicComponent<RuleSpellResistanceCheck> { public BlueprintCharacterClass Class; public int Bonus = 4; public override void OnEventAboutToTrigger(RuleSpellResistanceCheck evt) { if (evt.Ability.Type != AbilityType.Spell) return; // TODO: ideally we could check the spellbook used to cast the spell. var spellbook = Owner.GetSpellbook(Class); if (spellbook == null || !spellbook.IsKnown(evt.Ability)) return; if (OracleArchetypes.IsGrantedSpell(Owner, evt.Ability)) { evt.AdditionalSpellPenetration += Bonus; } } public override void OnEventDidTrigger(RuleSpellResistanceCheck evt) { } } public class ConcentrationBonusForGrantedSpells : RuleInitiatorLogicComponent<RuleCalculateAbilityParams> { public BlueprintCharacterClass Class; public int Bonus = 4; public override void OnEventAboutToTrigger(RuleCalculateAbilityParams evt) { if (evt.Spellbook != Owner.GetSpellbook(Class)) return; if (OracleArchetypes.IsGrantedSpell(Owner, evt.Spell)) { evt.AddBonusConcentration(Bonus); } } public override void OnEventDidTrigger(RuleCalculateAbilityParams evt) { } } public class ReduceMetamagicCostForGrantedSpells : RuleInitiatorLogicComponent<RuleApplyMetamagic> { public BlueprintCharacterClass Class; public int Reduction = 1; // True if this doesn't stack with other metamagic reductions public bool DoesNotStack = true; public override void OnEventAboutToTrigger(RuleApplyMetamagic evt) { if (evt.Spellbook != Owner.GetSpellbook(Class)) return; if (OracleArchetypes.IsGrantedSpell(Owner, evt.Spell)) { Log.Write($"Reduce cost of spell: {evt.Spell.name} by {Reduction}"); evt.ReduceCost(Reduction); } } public override void OnEventDidTrigger(RuleApplyMetamagic evt) { // Make sure this doesn't stack with other bonuses. var result = evt.Result; var totalReduction = (int)get_CostReduction(evt); if (DoesNotStack && totalReduction > Reduction) { int withoutThisReduction = totalReduction - Reduction; set_CostReduction(evt, Math.Max(withoutThisReduction, Reduction)); evt.OnTrigger(Rulebook.CurrentContext); } } static FastGetter get_CostReduction = Helpers.CreateFieldGetter<RuleApplyMetamagic>("m_CostReduction"); static FastSetter set_CostReduction = Helpers.CreateFieldSetter<RuleApplyMetamagic>("m_CostReduction"); } [Harmony12.HarmonyPatch(typeof(DescriptionTemplatesLevelup), "LevelUpClassPrerequisites", typeof(DescriptionBricksBox), typeof(TooltipData), typeof(bool))] static class DescriptionTemplatesLevelup_LevelUpClassPrerequisites_Patch { static void Postfix(DescriptionTemplatesLevelup __instance, DescriptionBricksBox box, TooltipData data, bool b) { try { if (data?.Archetype == null || Main.settings?.RelaxAncientLorekeeper == true) return; Prerequisites(__instance, box, data.Archetype.GetComponents<Prerequisite>()); } catch (Exception e) { Log.Error(e); } } static readonly FastInvoke Prerequisites = Helpers.CreateInvoker<DescriptionTemplatesLevelup>("Prerequisites", new Type[] { typeof(DescriptionBricksBox), typeof(IEnumerable<Prerequisite>) }); } [Harmony12.HarmonyPatch(typeof(CharBSelectorLayer), "FillData", typeof(BlueprintCharacterClass), typeof(BlueprintArchetype[]), typeof(CharBFeatureSelector))] static class CharBSelectorLayer_FillData_Patch { static void Postfix(CharBSelectorLayer __instance, BlueprintCharacterClass charClass, BlueprintArchetype[] archetypesList) { try { var self = __instance; var items = self.SelectorItems; if (items == null || archetypesList == null || items.Count == 0 || Main.settings?.RelaxAncientLorekeeper == true) { return; } // Note: conceptually this is the same as `CharBSelectorLayer.FillDataLightClass()`, // but for archetypes. // TODO: changing race won't refresh the prereq, although it does update if you change class. var state = Game.Instance.UI.CharacterBuildController.LevelUpController.State; foreach (var item in items) { var archetype = item?.Archetype; if (archetype == null || !archetypesList.Contains(archetype)) continue; item.Show(state: true); item.Toggle.interactable = item.enabled = OracleArchetypes.MeetsPrerequisites(archetype, state.Unit, state); var classData = state.Unit.Progression.GetClassData(state.SelectedClass); self.SilentSwitch(classData.Archetypes.Contains(archetype), item); } } catch (Exception e) { Log.Error(e); } } } [Harmony12.HarmonyPatch(typeof(CharacterBuildController), "SetRace", typeof(BlueprintRace))] static class CharacterBuildController_SetRace_Patch { static bool Prefix(CharacterBuildController __instance, BlueprintRace race) { try { if (race == null || Main.settings?.RelaxAncientLorekeeper == true) return true; var self = __instance; var levelUp = self.LevelUpController; var @class = levelUp.State.SelectedClass; if (@class == null) return true; if (@class.Archetypes.Any(a => a.GetComponents<Prerequisite>() != null)) { self.SetArchetype(null); } } catch (Exception e) { Log.Error(e); } return true; } } }
50.583721
652
0.665303
[ "MIT" ]
OldIronEyes/pathfinder-mods
EldritchArcana/Oracle/OracleArchetypes.cs
21,757
C#
using CounterStrike.Models.Guns.Contracts; using CounterStrike.Models.Guns.TypeGuns; using CounterStrike.Repositories.Contracts; using CounterStrike.Utilities.Messages; using System; using System.Collections.Generic; using System.Linq; namespace CounterStrike.Models.Maps.TypeMaps { public class GunRepository : IRepository { private List<IGun> models; public GunRepository() { this.models = new List<IGun>(); } public IReadOnlyCollection<IGun> Models => models.AsReadOnly(); public void Add(IGun gun) { if (gun == null) { throw new ArgumentException(ExceptionMessages.InvalidGunRepository); } else { models.Add(gun); } } public bool Remove(IGun gun) { if (models.Contains(gun)) { models.Remove(gun); return true; } return false; } public IGun FindByName(string name) { IGun gunToReturn = models.FirstOrDefault(x => x.Name == name); if (gunToReturn != default) { return gunToReturn; } return null; } } }
22.220339
84
0.530892
[ "MIT" ]
m-Mitkov/Csharp-Advanced-2020
OOP/ExmaPreparation/C#OOPExam-12Apr2020/01. Structure_Skeleton/CounterStrike/Repositories/TypeRepositories/GunRepository.cs
1,313
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using Microsoft.VisualStudio.TestTools.UnitTesting; using DeliveryManageSystem; using DeliveryManageSystem.Controllers; namespace DeliveryManageSystem.Tests.Controllers { [TestClass] public class HomeControllerTest { [TestMethod] public void Index() { // Arrange HomeController controller = new HomeController(); // Act ViewResult result = controller.Index() as ViewResult; // Assert Assert.IsNotNull(result); } [TestMethod] public void About() { // Arrange HomeController controller = new HomeController(); // Act ViewResult result = controller.About() as ViewResult; // Assert Assert.AreEqual("Your application description page.", result.ViewBag.Message); } [TestMethod] public void Contact() { // Arrange HomeController controller = new HomeController(); // Act ViewResult result = controller.Contact() as ViewResult; // Assert Assert.IsNotNull(result); } } }
23.8
90
0.582124
[ "MIT" ]
programxiaobai/DeliveryManageSystem
DeliveryManageSystem/DeliveryManageSystem.Tests/Controllers/HomeControllerTest.cs
1,311
C#
namespace navdi2 { using System.Collections.Generic; public class Ents : INavdiEnt { public bool active {get;private set;} public int maxSize {get;private set;} public bool full {get{return maxSize>=0&&ents.Count>=maxSize;}} ///<description>if an Ents object is 'permanent' it does not empty when Deactivated. its contents are thus 'permanent'.</description> public bool permanent {get;private set;} protected HashSet<INavdiEnt> ents; protected HashSet<INavdiEnt> pendingEnts; public Ents(int maxSize = -1, bool permanent = false) { this.active = false; this.maxSize = maxSize; this.permanent = permanent; this.ents = new HashSet<INavdiEnt>(); this.pendingEnts = new HashSet<INavdiEnt>(); } virtual public bool PendingAdd(INavdiEnt ent) { if (!this.active&&!this.permanent) { Dj.Error("Can't PendingAdd to inactive Ents "+this); return false; } if (maxSize>=0&&ents.Count>=maxSize) { Dj.Error("Can't PendingAdd to full Ents "+this+" (at capacity of "+maxSize+")"); ent.Deactivated(); return false; } if (pendingEnts.Add(ent)&&this.active) ent.Activated(); return true; } virtual public bool Add(INavdiEnt ent) { if (!this.active&&!this.permanent) { Dj.Error("Can't Add to inactive Ents "+this); return false; } if (maxSize>=0&&ents.Count>=maxSize) { Dj.Error("Can't Add to full Ents "+this+" (at capacity of "+maxSize+")"); ent.Deactivated(); return false; } if (ents.Add(ent)&&this.active) ent.Activated(); return true; } virtual public bool Remove(INavdiEnt ent) { if (!this.active) { Dj.Error("Can't Remove from inactive Ents "+this); return false; } if (this.permanent) { Dj.Error("Can't Remove from permanent Ents "+this); return false; } if (ents.Remove(ent)) ent.Deactivated(); return true; } virtual public bool Clear() { if (this.permanent) { Dj.Error("Can't Clear permanent Ents "+this); return false; } DoEach((ent)=>{ent.Deactivated();}); ents.Clear(); return true; } public void DoEach(System.Action<INavdiEnt> eachFunction) { foreach(INavdiEnt ent in ents) eachFunction(ent); } ////INavdiEnt virtual public void Activated() { this.active = true; if (permanent) this.DoEach((ent)=>{ent.Activated();}); } virtual public void Deactivated() { if (permanent) this.DoEach((ent)=>{ent.Deactivated();}); else this.Clear(); this.active = false; } virtual public void FrequentStep() { DoEach((ent)=>{ent.FrequentStep();}); } virtual public void FixedStep() { HashSet<INavdiEnt> sleepyEnts = new HashSet<INavdiEnt>(); DoEach((ent)=>{ ent.FixedStep(); if (ent.IsSleepy()) sleepyEnts.Add(ent); // always be cleaning up sleepy ents }); foreach(INavdiEnt sleepyEnt in sleepyEnts) Remove(sleepyEnt); foreach(INavdiEnt pendingAdd in pendingEnts) ents.Add(pendingAdd); pendingEnts.Clear(); } virtual public bool IsSleepy() { return false; // never sleepy } } public class Ents<E> : Ents where E : INavdiEnt { public Ents(int maxSize = -1, bool permanent = false) : base(maxSize,permanent) {} sealed override public bool Add(INavdiEnt ent) { if (ent is E) return Add((E)ent); else throw Dj.Crashf("INavdiEnt {0} is not of expected type <{1}>", ent, typeof(E).ToString()); } virtual public bool Add(E ent) { return base.Add(ent); // ents.Add(ent); } sealed override public bool Remove(INavdiEnt ent) { if (ent is E) return Remove((E)ent); else throw Dj.Crashf("INavdiEnt {0} is not of expected type <{1}>", ent, typeof(E).ToString()); } virtual public bool Remove(E ent) { return base.Remove(ent); // ents.Remove(ent); } public int RemoveMatches(System.Func<E,bool> matchFunction) { HashSet<E> matches = new HashSet<E>(); DoEach((ent)=>{if(matchFunction(ent))matches.Add(ent);}); foreach(E match in matches)Remove(match); return matches.Count; } public void DoEach(System.Action<E> eachFunction) { foreach(E ent in ents) eachFunction(ent); } } }
40.151515
157
0.679497
[ "MIT" ]
droqen/navdi2
Ents.cs
3,975
C#
namespace Going.Plaid.Entity; /// <summary> /// <para>Metadata that captures information about the Auth features of an institution.</para> /// </summary> public record AuthMetadata { /// <summary> /// <para>Metadata specifically related to which auth methods an institution supports.</para> /// </summary> [JsonPropertyName("supported_methods")] public Entity.AuthSupportedMethods? SupportedMethods { get; init; } = default!; }
33.307692
94
0.73903
[ "MIT" ]
EdEastman/Going.Plaid
src/Plaid/Entity/AuthMetadata.cs
433
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("UsageConsole")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UsageConsole")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM [assembly: Guid("3b3d99e4-38f4-4276-893a-95ef84b4f94d")] // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale // Version secondaire // Numéro de build // Révision // // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
40.432432
103
0.750668
[ "MIT" ]
fredatgithub/AtlasReloaded
UsageConsole/Properties/AssemblyInfo.cs
1,521
C#
using LuKaSo.Zonky.Logging; using LuKaSo.Zonky.Models.Investments; using LuKaSo.Zonky.Models.Markets; using MoreLinq; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace LuKaSo.Zonky.Client { public partial class ZonkyClient { /// <summary> /// Get investor's investments /// </summary> /// <param name="page">Page number, started from 0</param> /// <param name="pageSize">Items per page</param> /// <param name="ct"></param> /// <returns></returns> public async Task<IEnumerable<Investment>> GetInvestmentsAsync(int page, int pageSize, CancellationToken ct = default) { return await HandleAuthorizedRequestAsync(() => ZonkyApi.GetInvestmentsAsync(page, pageSize, AuthorizationToken, ct), ct).ConfigureAwait(false); } /// <summary> /// Get all investor's investments /// </summary> /// <param name="ct"></param> /// <returns></returns> public async Task<IEnumerable<Investment>> GetAllInvestmentsAsync(CancellationToken ct = default) { _log.Debug($"Get all investor's participations request."); // Get data var data = await GetDataSplitRequestAsync(_maxPageSize, (page, pageSize) => GetInvestmentsAsync(page, pageSize, ct), ct).ConfigureAwait(false); // Distinct result for situation when new item is added during querying data data = data.DistinctBy(l => l.Id).ToList(); _log.Debug($"Get all investor's participations, total {data.Count} items."); return data; } /// <summary> /// Get events list for investment /// </summary> /// <param name="loanId">Loan Id</param> /// <param name="ct"></param> /// <returns></returns> public async Task<IEnumerable<InvestmentEvent>> GetInvestmentEventsAsync(int loanId, CancellationToken ct = default) { return await HandleAuthorizedRequestAsync(() => ZonkyApi.GetInvestmentEventsAsync(loanId, AuthorizationToken, ct), ct).ConfigureAwait(false); } /// <summary> /// Create primary market investment /// </summary> /// <param name="investment">Primary market investment</param> /// <param name="ct"></param> /// <returns></returns> public async Task CreatePrimaryMarketInvestmentAsync(PrimaryMarketInvestment investment, CancellationToken ct = default) { CheckTradingPrerequisites(); await HandleAuthorizedRequestAsync(() => ZonkyApi.CreatePrimaryMarketInvestmentAsync(investment, AuthorizationToken, ct), ct).ConfigureAwait(false); } /// <summary> /// Increase primary market investment /// </summary> /// <param name="investmentId">Investment Id</param> /// <param name="increaseInvestment">Primary market increase investment</param> /// <param name="ct"></param> /// <returns></returns> public async Task IncreasePrimaryMarketInvestmentAsync(int investmentId, IncreasePrimaryMarketInvestment increaseInvestment, CancellationToken ct = default) { CheckTradingPrerequisites(); await HandleAuthorizedRequestAsync(() => ZonkyApi.IncreasePrimaryMarketInvestmentAsync(investmentId, increaseInvestment, AuthorizationToken, ct), ct).ConfigureAwait(false); } /// <summary> /// Buy secondary market investment offer /// </summary> /// <param name="offerId">Id of investment offer</param> /// <param name="secondaryMarketInvestment">Secondary market investment</param> /// <param name="ct"></param> /// <returns></returns> public async Task BuySecondaryMarketInvestmentAsync(int offerId, SecondaryMarketInvestment secondaryMarketInvestment, CancellationToken ct = default) { CheckTradingPrerequisites(); await HandleAuthorizedRequestAsync(() => ZonkyApi.BuySecondaryMarketInvestmentAsync(offerId, secondaryMarketInvestment, AuthorizationToken, ct), ct).ConfigureAwait(false); } /// <summary> /// Offer investment on secondary market to sell /// </summary> /// <param name="secondaryMarketOfferSell">Secondary market offer to sell</param> /// <param name="ct"></param> /// <returns></returns> public async Task OfferInvestmentOnSecondaryMarketAsync(SecondaryMarketOfferSell secondaryMarketOfferSell, CancellationToken ct = default) { CheckTradingPrerequisites(); await HandleAuthorizedRequestAsync(() => ZonkyApi.OfferInvestmentOnSecondaryMarketAsync(secondaryMarketOfferSell, AuthorizationToken, ct), ct).ConfigureAwait(false); } /// <summary> /// Cancel offer to sell on secondary market /// </summary> /// <param name="offerId">Secondary market offer Id</param> /// <param name="ct"></param> /// <returns></returns> public async Task CancelOfferInvestmentOnSecondaryMarketAsync(int offerId, CancellationToken ct = default) { CheckTradingPrerequisites(); await HandleAuthorizedRequestAsync(() => ZonkyApi.CancelOfferInvestmentOnSecondaryMarketAsync(offerId, AuthorizationToken, ct), ct).ConfigureAwait(false); } } }
44.390244
184
0.652015
[ "MIT" ]
lkavale/LuKaSo.Zonky
src/LuKaSo.Zonky/Client/InvestmentsClient.cs
5,462
C#
/* * FancyScrollView (https://github.com/setchi/FancyScrollView) * Copyright (c) 2019 setchi * Licensed under MIT (https://github.com/setchi/FancyScrollView/blob/master/LICENSE) */ using UnityEngine.UI; namespace FancyScrollView { public enum MovementType { Unrestricted = ScrollRect.MovementType.Unrestricted, Elastic = ScrollRect.MovementType.Elastic, Clamped = ScrollRect.MovementType.Clamped } }
24.611111
85
0.722348
[ "MIT" ]
karta0898098/UnityLottery
Assets/FancyScrollView/Sources/Runtime/Scroller/MovementType.cs
445
C#
// // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Data; using System.Runtime.InteropServices; namespace IBM.Data.DB2 { public sealed class DB2Parameter : MarshalByRefObject, IDbDataParameter, IDataParameter, ICloneable { private DbType dbType = DbType.Object; private DB2Type db2Type = DB2Type.Invalid; private short db2DataType = DB2Constants.SQL_UNKNOWN_TYPE; private short db2LastUsedDataType = DB2Constants.SQL_UNKNOWN_TYPE; private ParameterDirection direction; private short db2Direction = DB2Constants.SQL_PARAM_INPUT; private bool nullable = true; private string parameterName; private string sourceColumn; private DataRowVersion sourceVersion; private object dataVal; private byte scale, precision; private int size; internal IntPtr internalBuffer; internal IntPtr internalLengthBuffer; internal int requiredMemory; #region Contructors and destructors public DB2Parameter() { direction = ParameterDirection.Input; sourceVersion = DataRowVersion.Current; } public DB2Parameter(string name, DB2Type type) { direction = ParameterDirection.Input; sourceVersion = DataRowVersion.Current; this.ParameterName = name; this.DB2Type = type; } public DB2Parameter(string name, DB2Type type, int size) { direction = ParameterDirection.Input; sourceVersion = DataRowVersion.Current; this.ParameterName = name; this.DB2Type = type; this.Size = size; } public DB2Parameter(string name, DB2Type type, int size, string sourceColumn) { direction = ParameterDirection.Input; sourceVersion = DataRowVersion.Current; this.ParameterName = name; this.DB2Type = type; this.Size = size; this.SourceColumn = sourceColumn; } public DB2Parameter(string parameterName, object value) { direction = ParameterDirection.Input; sourceVersion = DataRowVersion.Current; this.ParameterName = parameterName; this.Value = value; } public DB2Parameter(string parameterName, DB2Type db2Type, int size, ParameterDirection parameterDirection, bool isNullable, byte precision, byte scale, string srcColumn, DataRowVersion srcVersion, object value) { this.ParameterName = parameterName; this.DB2Type = db2Type; this.Size = size; this.Direction = parameterDirection; this.IsNullable = isNullable; this.Precision = precision; this.Scale = scale; this.SourceColumn = srcColumn; this.SourceVersion = srcVersion; this.Value = value; } #endregion #region Properties #region DbType Property public DB2Type DB2Type { get { return db2Type; } set { db2Type = value; switch(db2Type) { case DB2Type.Invalid: dbType = DbType.Object; db2DataType = DB2Constants.SQL_UNKNOWN_TYPE; break; case DB2Type.SmallInt: dbType = DbType.Int16; db2DataType = DB2Constants.SQL_SMALLINT; break; case DB2Type.Integer: dbType = DbType.Int32; db2DataType = DB2Constants.SQL_INTEGER; break; case DB2Type.BigInt: dbType = DbType.Int64; db2DataType = DB2Constants.SQL_BIGINT; break; case DB2Type.Real: dbType = DbType.Single; db2DataType = DB2Constants.SQL_REAL; break; case DB2Type.Double: dbType = DbType.Double; db2DataType = DB2Constants.SQL_DOUBLE; break; case DB2Type.Float: dbType = DbType.Single; db2DataType = DB2Constants.SQL_REAL; break; case DB2Type.Decimal: dbType = DbType.Decimal; db2DataType = DB2Constants.SQL_DECIMAL; break; case DB2Type.Numeric: dbType = DbType.VarNumeric; db2DataType = DB2Constants.SQL_WCHAR; break; case DB2Type.Date: dbType = DbType.Date; db2DataType = DB2Constants.SQL_TYPE_DATE; break; case DB2Type.Time: dbType = DbType.Time; db2DataType = DB2Constants.SQL_TYPE_TIME; break; case DB2Type.Timestamp: dbType = DbType.DateTime; db2DataType = DB2Constants.SQL_TYPE_TIMESTAMP; break; case DB2Type.Char: dbType = DbType.String; db2DataType = DB2Constants.SQL_WCHAR; break; case DB2Type.VarChar: dbType = DbType.StringFixedLength; db2DataType = DB2Constants.SQL_WCHAR; break; case DB2Type.LongVarChar: dbType = DbType.String; db2DataType = DB2Constants.SQL_WCHAR; break; case DB2Type.Binary: dbType = DbType.Binary; db2DataType = DB2Constants.SQL_VARBINARY; break; case DB2Type.VarBinary: dbType = DbType.Binary; db2DataType = DB2Constants.SQL_VARBINARY; break; case DB2Type.LongVarBinary: dbType = DbType.String; db2DataType = DB2Constants.SQL_WCHAR; break; case DB2Type.Graphic: dbType = DbType.StringFixedLength; db2DataType = DB2Constants.SQL_WCHAR; break; case DB2Type.VarGraphic: dbType = DbType.String; db2DataType = DB2Constants.SQL_WCHAR; break; case DB2Type.LongVarGraphic: dbType = DbType.String; db2DataType = DB2Constants.SQL_WCHAR; break; case DB2Type.Clob: dbType = DbType.String; db2DataType = DB2Constants.SQL_WCHAR; break; case DB2Type.Blob: dbType = DbType.Binary; db2DataType = DB2Constants.SQL_VARBINARY; break; case DB2Type.DbClob: dbType = DbType.String; db2DataType = DB2Constants.SQL_WCHAR; break; case DB2Type.Datalink: dbType = DbType.Byte; db2DataType = DB2Constants.SQL_VARBINARY; break; case DB2Type.RowId: dbType = DbType.Decimal; db2DataType = DB2Constants.SQL_DECIMAL; break; case DB2Type.XmlReader: dbType = DbType.String; db2DataType = DB2Constants.SQL_WCHAR; break; default: throw new NotSupportedException("Value is of unknown data type"); } } } /// /// Parameter data type /// public DbType DbType { get { return dbType; } set { dbType = value; switch(dbType) { case DbType.AnsiString: db2Type = DB2Type.VarChar; db2DataType = DB2Constants.SQL_WCHAR; break; case DbType.AnsiStringFixedLength: db2Type = DB2Type.Char; db2DataType = DB2Constants.SQL_WCHAR; break; case DbType.Binary: db2Type = DB2Type.Binary; db2DataType = DB2Constants.SQL_VARBINARY; break; case DbType.Boolean: db2Type = DB2Type.SmallInt; db2DataType = DB2Constants.SQL_BIT; break; case DbType.Byte: db2Type = DB2Type.SmallInt; db2DataType = DB2Constants.SQL_UTINYINT; break; case DbType.Currency: db2Type = DB2Type.Decimal; db2DataType = DB2Constants.SQL_DECIMAL; break; case DbType.Date: db2Type = DB2Type.Date; db2DataType = DB2Constants.SQL_TYPE_DATE; break; case DbType.DateTime: db2Type = DB2Type.Timestamp; db2DataType = DB2Constants.SQL_TYPE_TIMESTAMP; break; case DbType.Decimal: db2Type = DB2Type.Decimal; db2DataType = DB2Constants.SQL_DECIMAL; break; case DbType.Double: db2Type = DB2Type.Double; db2DataType = DB2Constants.SQL_DOUBLE; break; case DbType.Guid: db2Type = DB2Type.Binary; db2DataType = DB2Constants.SQL_WCHAR; break; case DbType.Int16: db2Type = DB2Type.SmallInt; db2DataType = DB2Constants.SQL_SMALLINT; break; case DbType.Int32: db2Type = DB2Type.Integer; db2DataType = DB2Constants.SQL_INTEGER; break; case DbType.Int64: db2Type = DB2Type.BigInt; db2DataType = DB2Constants.SQL_BIGINT; break; case DbType.Object: db2Type = DB2Type.Invalid; db2DataType = DB2Constants.SQL_UNKNOWN_TYPE; break; case DbType.SByte: db2Type = DB2Type.SmallInt; db2DataType = DB2Constants.SQL_UTINYINT; break; case DbType.Single: db2Type = DB2Type.Float; db2DataType = DB2Constants.SQL_REAL; break; case DbType.String: db2Type = DB2Type.VarChar; db2DataType = DB2Constants.SQL_WCHAR; break; case DbType.StringFixedLength: db2Type = DB2Type.Char; db2DataType = DB2Constants.SQL_WCHAR; break; case DbType.Time: db2Type = DB2Type.Time; db2DataType = DB2Constants.SQL_TYPE_TIME; break; case DbType.UInt16: db2Type = DB2Type.SmallInt; db2DataType = DB2Constants.SQL_SMALLINT; break; case DbType.UInt32: db2Type = DB2Type.Integer; db2DataType = DB2Constants.SQL_INTEGER; break; case DbType.UInt64: db2Type = DB2Type.BigInt; db2DataType = DB2Constants.SQL_BIGINT; break; case DbType.VarNumeric: db2Type = DB2Type.Numeric; db2DataType = DB2Constants.SQL_WCHAR; break; default: throw new NotSupportedException("Value is of unknown data type"); } } } #endregion #region Direction /// /// In or out parameter, or both /// public ParameterDirection Direction { get { return direction; } set { direction = value; switch(direction) { default: case ParameterDirection.Input: db2Direction = DB2Constants.SQL_PARAM_INPUT; break; case ParameterDirection.Output: db2Direction = DB2Constants.SQL_PARAM_OUTPUT; break; case ParameterDirection.InputOutput: db2Direction = DB2Constants.SQL_PARAM_INPUT_OUTPUT; break; case ParameterDirection.ReturnValue: db2Direction = DB2Constants.SQL_RETURN_VALUE; break; } } } #endregion #region IsNullable /// /// Does this parameter support a null value /// public bool IsNullable { get { return nullable; } set { nullable = value; } } #endregion #region ParameterName public string ParameterName { get { return parameterName; } set { parameterName = value; } } #endregion #region SourceColumn /// /// Gets or sets the name of the source column that is mapped to the DataSet /// public string SourceColumn { get { return sourceColumn; } set { sourceColumn = value; } } #endregion #region SourceVersion /// /// DataRowVersion property /// public DataRowVersion SourceVersion { get { return sourceVersion; } set { sourceVersion = value; } } #endregion #region IDbDataParameter properties public byte Precision { get { return precision; } set { precision = value; } } public byte Scale { get { return scale; } set { scale = value; } } public int Size { get { return size; } set { size = value; } } #endregion #region Value /// /// The actual parameter data /// public object Value { get { return dataVal; } set { this.dataVal = value; } } #endregion #endregion #region inferType Method /// <summary> /// Determine the data type based on the value /// </summary> private void InferType() { if(Value == null) throw new ArgumentException("No DB2Parameter.Value found"); if(Value is IConvertible) { switch(((IConvertible)Value).GetTypeCode()) { case TypeCode.Char: dbType = DbType.Byte; db2Type = DB2Type.SmallInt; db2DataType = DB2Constants.SQL_WCHAR; break; case TypeCode.Boolean: dbType = DbType.Byte; db2Type = DB2Type.SmallInt; db2DataType = DB2Constants.SQL_BIT; break; case TypeCode.SByte: case TypeCode.Byte: dbType = DbType.Byte; db2Type = DB2Type.SmallInt; db2DataType = DB2Constants.SQL_UTINYINT; break; case TypeCode.UInt16: case TypeCode.Int16: dbType = DbType.Int16; db2Type = DB2Type.SmallInt; db2DataType = DB2Constants.SQL_SMALLINT; break; case TypeCode.UInt32: case TypeCode.Int32: dbType = DbType.Int32; db2Type = DB2Type.Integer; db2DataType = DB2Constants.SQL_INTEGER; break; case TypeCode.UInt64: case TypeCode.Int64: dbType = DbType.Int64; db2Type = DB2Type.BigInt; db2DataType = DB2Constants.SQL_BIGINT; break; case TypeCode.Single: dbType = DbType.Single; db2Type = DB2Type.Float; db2DataType = DB2Constants.SQL_REAL; break; case TypeCode.Double: dbType = DbType.Double; db2Type = DB2Type.Double; db2DataType = DB2Constants.SQL_DOUBLE; break; case TypeCode.Decimal: dbType = DbType.Decimal; db2Type = DB2Type.Decimal; db2DataType = DB2Constants.SQL_DECIMAL; break; case TypeCode.DateTime: dbType = DbType.DateTime; db2Type = DB2Type.Timestamp; db2DataType = DB2Constants.SQL_TYPE_TIMESTAMP; break; case TypeCode.String: dbType = DbType.String; db2Type = DB2Type.VarChar; db2DataType = DB2Constants.SQL_WCHAR; break; case TypeCode.Object: case TypeCode.DBNull: case TypeCode.Empty: throw new SystemException("Unknown data type"); default: throw new SystemException("Value is of unknown data type"); } } else if(Value is byte[]) { dbType = DbType.Binary; db2Type = DB2Type.VarBinary; db2DataType = DB2Constants.SQL_VARBINARY; } else if(Value is TimeSpan) { dbType = DbType.Time; db2Type = DB2Type.Time; db2DataType = DB2Constants.SQL_TYPE_TIME; } else { throw new NotSupportedException("Value is of unsupported data type"); } } #endregion internal void CalculateRequiredmemory() { //if((direction == ParameterDirection.Input) || (direction == ParameterDirection.InputOutput)) //{ // if(Value == null) // throw new ArgumentException("Value missing"); //} if(dbType == DbType.Object) { if((direction == ParameterDirection.Output) || (direction == ParameterDirection.ReturnValue)) throw new ArgumentException("Unknown type"); if((direction != ParameterDirection.Input) || !Convert.IsDBNull(Value)) { InferType(); } } if (db2DataType == DB2Constants.SQL_INTEGER) { requiredMemory = 4; } if((db2DataType == DB2Constants.SQL_VARBINARY) || (db2DataType == DB2Constants.SQL_WCHAR)) { if(Size <= 0) { if(direction != ParameterDirection.Input) throw new ArgumentException("Size not specified"); if(Value == DBNull.Value) requiredMemory = 0; else if(Value is string) requiredMemory = ((string)Value).Length; else if(Value is byte[]) requiredMemory = ((byte[])Value).Length; else throw new ArgumentException("wrong type!?"); } else { requiredMemory = Size; } if(db2DataType == DB2Constants.SQL_WCHAR) requiredMemory = (requiredMemory * 2) + 2; requiredMemory = (requiredMemory | 0xf) + 1; } requiredMemory = Math.Max(128, requiredMemory); } #region Bind /// /// Bind this parameter /// internal short Bind(IntPtr hwndStmt, short paramNum) { int inLength = requiredMemory; db2LastUsedDataType = db2DataType; short db2CType = DB2Constants.SQL_C_DEFAULT; if((direction == ParameterDirection.Input) || (direction == ParameterDirection.InputOutput)) { if(Convert.IsDBNull(Value)) { inLength = DB2Constants.SQL_NULL_DATA; if((db2DataType == DB2Constants.SQL_UNKNOWN_TYPE) || (db2DataType == DB2Constants.SQL_DECIMAL)) { db2LastUsedDataType = DB2Constants.SQL_VARGRAPHIC; db2CType = DB2Constants.SQL_C_WCHAR; } } } if((direction == ParameterDirection.Input) || (direction == ParameterDirection.InputOutput)) { switch (db2DataType) { case DB2Constants.SQL_WCHAR: string tmpString = Convert.ToString(Value); inLength = tmpString.Length; if((Size > 0) && (inLength > Size)) inLength = Size; Marshal.Copy(tmpString.ToCharArray(), 0, internalBuffer, inLength); inLength *= 2; db2LastUsedDataType = DB2Constants.SQL_VARGRAPHIC; db2CType = DB2Constants.SQL_C_WCHAR; if(inLength > 32000) { db2LastUsedDataType = DB2Constants.SQL_TYPE_BLOB; } break; case DB2Constants.SQL_VARBINARY: byte[] tmpBytes = (byte[])Value; inLength = tmpBytes.Length; if((Size > 0) && (inLength > Size)) inLength = Size; Marshal.Copy(tmpBytes, 0, internalBuffer, inLength); db2CType = DB2Constants.SQL_TYPE_BINARY; break; case DB2Constants.SQL_BIT: case DB2Constants.SQL_UTINYINT: case DB2Constants.SQL_SMALLINT: Marshal.WriteInt16(internalBuffer, Convert.ToInt16(Value)); db2CType = DB2Constants.SQL_C_SSHORT; break; case DB2Constants.SQL_INTEGER: Marshal.WriteInt32(internalBuffer, Convert.ToInt32(Value)); db2CType = DB2Constants.SQL_C_SLONG; break; case DB2Constants.SQL_BIGINT: Marshal.WriteInt64(internalBuffer, Convert.ToInt64(Value)); db2CType = DB2Constants.SQL_C_SBIGINT; break; case DB2Constants.SQL_REAL: Marshal.StructureToPtr((float)Convert.ToDouble(Value), internalBuffer, false); db2CType = DB2Constants.SQL_C_TYPE_REAL; break; case DB2Constants.SQL_DOUBLE: Marshal.StructureToPtr(Convert.ToDouble(Value), internalBuffer, false); db2CType = DB2Constants.SQL_C_DOUBLE; break; case DB2Constants.SQL_DECIMAL: byte[] tmpDecimalData = System.Text.Encoding.UTF8.GetBytes( Convert.ToDecimal(Value).ToString(System.Globalization.CultureInfo.InvariantCulture)); inLength = Math.Min(tmpDecimalData.Length, requiredMemory); Marshal.Copy(tmpDecimalData, 0, internalBuffer, inLength); db2LastUsedDataType = DB2Constants.SQL_VARCHAR; db2CType = DB2Constants.SQL_C_CHAR; break; case DB2Constants.SQL_TYPE_DATE: DateTime tmpDate = Convert.ToDateTime(Value); Marshal.WriteInt16(internalBuffer, 0, (short)tmpDate.Year); Marshal.WriteInt16(internalBuffer, 2, (short)tmpDate.Month); Marshal.WriteInt16(internalBuffer, 4, (short)tmpDate.Day); db2CType = DB2Constants.SQL_C_TYPE_DATE; break; case DB2Constants.SQL_TYPE_TIMESTAMP: DateTime tmpDateTime = Convert.ToDateTime(Value); Marshal.WriteInt16(internalBuffer, 0, (short)tmpDateTime.Year); Marshal.WriteInt16(internalBuffer, 2, (short)tmpDateTime.Month); Marshal.WriteInt16(internalBuffer, 4, (short)tmpDateTime.Day); Marshal.WriteInt16(internalBuffer, 6, (short)tmpDateTime.Hour); Marshal.WriteInt16(internalBuffer, 8, (short)tmpDateTime.Minute); Marshal.WriteInt16(internalBuffer, 10, (short)tmpDateTime.Second); Marshal.WriteInt32(internalBuffer, 12, (int)((tmpDateTime.Ticks % 10000000) * 100)); db2CType = DB2Constants.SQL_C_TYPE_TIMESTAMP; break; case DB2Constants.SQL_TYPE_TIME: TimeSpan tmpTime = (TimeSpan)Value; Marshal.WriteInt16(internalBuffer, 0, (short)tmpTime.Hours); Marshal.WriteInt16(internalBuffer, 2, (short)tmpTime.Minutes); Marshal.WriteInt16(internalBuffer, 4, (short)tmpTime.Seconds); db2CType = DB2Constants.SQL_C_TYPE_TIME; break; } } else { switch (db2DataType) { case DB2Constants.SQL_WCHAR: db2LastUsedDataType = DB2Constants.SQL_VARGRAPHIC; db2CType = DB2Constants.SQL_C_WCHAR; break; case DB2Constants.SQL_VARBINARY: db2CType = DB2Constants.SQL_TYPE_BINARY; break; case DB2Constants.SQL_BIT: case DB2Constants.SQL_UTINYINT: case DB2Constants.SQL_SMALLINT: db2CType = DB2Constants.SQL_C_SSHORT; break; case DB2Constants.SQL_INTEGER: db2CType = DB2Constants.SQL_C_SLONG; break; case DB2Constants.SQL_BIGINT: db2CType = DB2Constants.SQL_C_SBIGINT; break; case DB2Constants.SQL_REAL: db2CType = DB2Constants.SQL_C_TYPE_REAL; break; case DB2Constants.SQL_DOUBLE: db2CType = DB2Constants.SQL_C_DOUBLE; break; case DB2Constants.SQL_DECIMAL: db2LastUsedDataType = DB2Constants.SQL_VARCHAR; db2CType = DB2Constants.SQL_C_CHAR; break; case DB2Constants.SQL_TYPE_DATE: db2CType = DB2Constants.SQL_C_TYPE_DATE; break; case DB2Constants.SQL_TYPE_TIMESTAMP: db2CType = DB2Constants.SQL_C_TYPE_TIMESTAMP; break; case DB2Constants.SQL_TYPE_TIME: db2CType = DB2Constants.SQL_C_TYPE_TIME; break; } } Marshal.WriteInt32(internalLengthBuffer, inLength); short sqlRet = DB2CLIWrapper.SQLBindParameter(hwndStmt, paramNum, db2Direction, db2CType, db2LastUsedDataType, Size, Scale, internalBuffer, requiredMemory, internalLengthBuffer); return sqlRet; } #endregion object ICloneable.Clone () { DB2Parameter clone = new DB2Parameter(); clone.dbType = dbType; clone.db2Type = db2Type; clone.db2DataType = db2DataType; clone.db2LastUsedDataType = db2LastUsedDataType; clone.direction = direction; clone.db2Direction = db2Direction; clone.nullable = nullable; clone.parameterName = parameterName; clone.sourceColumn = sourceColumn; clone.sourceVersion = sourceVersion; clone.dataVal = dataVal; clone.scale = scale; clone.precision = precision; clone.size = size; if(dataVal is ICloneable) { clone.dataVal = ((ICloneable)dataVal).Clone(); } return clone; } internal void GetOutValue() { int length = Marshal.ReadInt32(internalLengthBuffer); if(length == DB2Constants.SQL_NULL_DATA) { dataVal = DBNull.Value; return; } switch(DB2Type) { case DB2Type.SmallInt: dataVal = Marshal.ReadInt16(internalBuffer); break; case DB2Type.Integer: dataVal = Marshal.ReadInt32(internalBuffer); break; case DB2Type.BigInt: dataVal = Marshal.ReadInt64(internalBuffer); break; case DB2Type.Double: dataVal = Marshal.PtrToStructure(internalBuffer, typeof(Double)); break; case DB2Type.Float: dataVal = Marshal.PtrToStructure(internalBuffer, typeof(Single)); break; case DB2Type.Char: case DB2Type.VarChar: case DB2Type.LongVarChar: case DB2Type.Graphic: case DB2Type.VarGraphic: case DB2Type.LongVarGraphic: case DB2Type.Clob: case DB2Type.DbClob: dataVal = Marshal.PtrToStringUni(internalBuffer, Math.Min(Size, length / 2)); break; case DB2Type.Binary: case DB2Type.VarBinary: case DB2Type.LongVarBinary: case DB2Type.Blob: case DB2Type.Datalink: length = Math.Min(Size, length); dataVal = new byte[length]; Marshal.Copy(internalBuffer, (byte[])dataVal, 0, length); break; case DB2Type.Decimal: dataVal = decimal.Parse(Marshal.PtrToStringAnsi(internalBuffer, length), System.Globalization.CultureInfo.InvariantCulture); break; case DB2Type.Timestamp: DateTime dtTmp = new DateTime( Marshal.ReadInt16(internalBuffer, 0), // year Marshal.ReadInt16(internalBuffer, 2), // month Marshal.ReadInt16(internalBuffer, 4), // day Marshal.ReadInt16(internalBuffer, 6), // hour Marshal.ReadInt16(internalBuffer, 8), // minute Marshal.ReadInt16(internalBuffer, 10));// second dataVal = dtTmp.AddTicks(Marshal.ReadInt32(internalBuffer, 12) / 100); // nanoseconds break; case DB2Type.Date: dataVal = new DateTime( Marshal.ReadInt16(internalBuffer, 0), Marshal.ReadInt16(internalBuffer, 2), Marshal.ReadInt16(internalBuffer, 4)); break; case DB2Type.Time: dataVal = new TimeSpan( Marshal.ReadInt16(internalBuffer, 0), // Hour Marshal.ReadInt16(internalBuffer, 2), // Minute Marshal.ReadInt16(internalBuffer, 4)); // Second break; case DB2Type.Invalid: case DB2Type.Real: case DB2Type.Numeric: case DB2Type.RowId: case DB2Type.XmlReader: throw new NotImplementedException(); default: throw new NotSupportedException("unknown data type"); } } } }
37.394886
214
0.646509
[ "Apache-2.0" ]
121468615/mono
mcs/class/IBM.Data.DB2/IBM.Data.DB2/DB2Parameter.cs
26,326
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> //------------------------------------------------------------------------------ namespace PlaylistSystem.Account { public partial class VerifyPhoneNumber { /// <summary> /// ErrorMessage control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal ErrorMessage; /// <summary> /// PhoneNumber control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.HiddenField PhoneNumber; /// <summary> /// Code control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox Code; } }
33.069767
84
0.509142
[ "MIT" ]
ahansb/WebFormsExam
Web-forms-Exam-2016/Exam/Account/VerifyPhoneNumber.aspx.designer.cs
1,424
C#
using System; using System.Collections.Generic; using System.Linq; using Web1xbet.Entities; namespace Web1xbet.Infrastructure.Repositories { public class BetRepository : EntityBaseRepository<Bet>, IBetRepository { public BetRepository(BetContext context) : base(context) { } public List<Bet> GetAllBet(User user) { try { var result = base.FindBy(bet => bet.UserId == user.Id).ToList(); return result; } catch (Exception) { return null; } } public bool CancelBet(int id) { try { var result = base.FindBy(bet => bet.Id == id).ToList().First(); base.Delete(result); base.Commit(); return true; } catch (Exception) { return false; } } public Bet ChangeBet(Bet newBet) { try { var result = base.FindBy(bet => bet.Id == newBet.Id).ToList().First(); base.Edit(newBet); base.Commit(); return newBet; } catch (Exception) { return null; } } } }
23.706897
86
0.438545
[ "MIT" ]
stiks96/web_1xbet
Infrastructure/Repositories/BetRepository.cs
1,375
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Reflection; namespace Microsoft.TestCommon { /// <summary> /// MSTest assertion class to provide convenience and assert methods for generic types /// whose type parameters are not known at compile time. /// </summary> public class GenericTypeAssert { private static readonly GenericTypeAssert singleton = new GenericTypeAssert(); public static GenericTypeAssert Singleton { get { return singleton; } } /// <summary> /// Asserts the given <paramref name="genericBaseType"/> is a generic type and creates a new /// bound generic type using <paramref name="genericParameterType"/>. It then asserts there /// is a constructor that will accept <paramref name="parameterTypes"/> and returns it. /// </summary> /// <param name="genericBaseType">The unbound generic base type.</param> /// <param name="genericParameterType">The type of the single generic parameter to apply to create a bound generic type.</param> /// <param name="parameterTypes">The list of parameter types for a constructor that must exist.</param> /// <returns>The <see cref="ConstructorInfo"/> of that constructor which may be invoked to create that new generic type.</returns> public ConstructorInfo GetConstructor( Type genericBaseType, Type genericParameterType, params Type[] parameterTypes ) { Assert.NotNull(genericBaseType); Assert.True(genericBaseType.IsGenericTypeDefinition); Assert.NotNull(genericParameterType); Assert.NotNull(parameterTypes); Type genericType = genericBaseType.MakeGenericType(new Type[] { genericParameterType }); ConstructorInfo ctor = genericType.GetConstructor(parameterTypes); Assert.True( ctor != null, String.Format( "Test error: failed to locate generic ctor for type '{0}<{1}>',", genericBaseType.Name, genericParameterType.Name ) ); return ctor; } /// <summary> /// Asserts the given <paramref name="genericBaseType"/> is a generic type and creates a new /// bound generic type using <paramref name="genericParameterType"/>. It then asserts there /// is a constructor that will accept <paramref name="parameterTypes"/> and returns it. /// </summary> /// <param name="genericBaseType">The unbound generic base type.</param> /// <param name="genericParameterTypes">The types of the generic parameters to apply to create a bound generic type.</param> /// <param name="parameterTypes">The list of parameter types for a constructor that must exist.</param> /// <returns>The <see cref="ConstructorInfo"/> of that constructor which may be invoked to create that new generic type.</returns> public ConstructorInfo GetConstructor( Type genericBaseType, Type[] genericParameterTypes, params Type[] parameterTypes ) { Assert.NotNull(genericBaseType); Assert.True(genericBaseType.IsGenericTypeDefinition); Assert.NotNull(genericParameterTypes); Assert.NotNull(parameterTypes); Type genericType = genericBaseType.MakeGenericType(genericParameterTypes); ConstructorInfo ctor = genericType.GetConstructor(parameterTypes); Assert.True( ctor != null, String.Format( "Test error: failed to locate generic ctor for type '{0}<>',", genericBaseType.Name ) ); return ctor; } /// <summary> /// Creates a new bound generic type and invokes the constructor matched from <see cref="parameterTypes"/>. /// </summary> /// <param name="genericBaseType">The unbound generic base type.</param> /// <param name="genericParameterType">The type of the single generic parameter to apply to create a bound generic type.</param> /// <param name="parameterTypes">The list of parameter types for a constructor that must exist.</param> /// <param name="parameterValues">The list of values to supply to the constructor</param> /// <returns>The instance created by calling that constructor.</returns> public object InvokeConstructor( Type genericBaseType, Type genericParameterType, Type[] parameterTypes, object[] parameterValues ) { ConstructorInfo ctor = GetConstructor( genericBaseType, genericParameterType, parameterTypes ); Assert.NotNull(parameterValues); Assert.Equal(parameterTypes.Length, parameterValues.Length); return ctor.Invoke(parameterValues); } /// <summary> /// Creates a new bound generic type and invokes the constructor matched from <see cref="parameterTypes"/>. /// </summary> /// <param name="genericBaseType">The unbound generic base type.</param> /// <param name="genericParameterTypse">The types of the generic parameters to apply to create a bound generic type.</param> /// <param name="parameterTypes">The list of parameter types for a constructor that must exist.</param> /// <param name="parameterValues">The list of values to supply to the constructor</param> /// <returns>The instance created by calling that constructor.</returns> public object InvokeConstructor( Type genericBaseType, Type[] genericParameterTypes, Type[] parameterTypes, object[] parameterValues ) { ConstructorInfo ctor = GetConstructor( genericBaseType, genericParameterTypes, parameterTypes ); Assert.NotNull(parameterValues); Assert.Equal(parameterTypes.Length, parameterValues.Length); return ctor.Invoke(parameterValues); } /// <summary> /// Creates a new bound generic type and invokes the constructor matched from the types of <paramref name="parameterValues"/>. /// </summary> /// <param name="genericBaseType">The unbound generic base type.</param> /// <param name="genericParameterType">The type of the single generic parameter to apply to create a bound generic type.</param> /// <param name="parameterValues">The list of values to supply to the constructor. It must be possible to determine the</param> /// <returns>The instance created by calling that constructor.</returns> public object InvokeConstructor( Type genericBaseType, Type genericParameterType, params object[] parameterValues ) { Assert.NotNull(genericBaseType); Assert.True(genericBaseType.IsGenericTypeDefinition); Assert.NotNull(genericParameterType); Type genericType = genericBaseType.MakeGenericType(new Type[] { genericParameterType }); ConstructorInfo ctor = FindConstructor(genericType, parameterValues); Assert.True( ctor != null, String.Format( "Test error: failed to locate generic ctor for type '{0}<{1}>',", genericBaseType.Name, genericParameterType.Name ) ); return ctor.Invoke(parameterValues); } /// <summary> /// Creates a new bound generic type and invokes the constructor matched from the types of <paramref name="parameterValues"/>. /// </summary> /// <param name="genericBaseType">The unbound generic base type.</param> /// <param name="genericParameterTypes">The types of the generic parameters to apply to create a bound generic type.</param> /// <param name="parameterValues">The list of values to supply to the constructor. It must be possible to determine the</param> /// <returns>The instance created by calling that constructor.</returns> public object InvokeConstructor( Type genericBaseType, Type[] genericParameterTypes, params object[] parameterValues ) { Assert.NotNull(genericBaseType); Assert.True(genericBaseType.IsGenericTypeDefinition); Assert.NotNull(genericParameterTypes); Type genericType = genericBaseType.MakeGenericType(genericParameterTypes); ConstructorInfo ctor = FindConstructor(genericType, parameterValues); Assert.True( ctor != null, String.Format( "Test error: failed to locate generic ctor for type '{0}<>',", genericBaseType.Name ) ); return ctor.Invoke(parameterValues); } /// <summary> /// Creates a new bound generic type and invokes the constructor matched from <see cref="parameterTypes"/>. /// </summary> /// <typeparam name="T">The type of object the constuctor is expected to yield.</typeparam> /// <param name="genericBaseType">The unbound generic base type.</param> /// <param name="genericParameterType">The type of the single generic parameter to apply to create a bound generic type.</param> /// <param name="parameterTypes">The list of parameter types for a constructor that must exist.</param> /// <param name="parameterValues">The list of values to supply to the constructor</param> /// <returns>An instance of type <typeparamref name="T"/>.</returns> public T InvokeConstructor<T>( Type genericBaseType, Type genericParameterType, Type[] parameterTypes, object[] parameterValues ) { ConstructorInfo ctor = GetConstructor( genericBaseType, genericParameterType, parameterTypes ); Assert.NotNull(parameterValues); Assert.Equal(parameterTypes.Length, parameterValues.Length); return (T)ctor.Invoke(parameterValues); } /// <summary> /// Creates a new bound generic type and invokes the constructor matched from <see cref="parameterTypes"/>. /// </summary> /// <typeparam name="T">The type of object the constuctor is expected to yield.</typeparam> /// <param name="genericBaseType">The unbound generic base type.</param> /// <param name="genericParameterTypes">The types of the generic parameters to apply to create a bound generic type.</param> /// <param name="parameterTypes">The list of parameter types for a constructor that must exist.</param> /// <param name="parameterValues">The list of values to supply to the constructor</param> /// <returns>An instance of type <typeparamref name="T"/>.</returns> public T InvokeConstructor<T>( Type genericBaseType, Type[] genericParameterTypes, Type[] parameterTypes, object[] parameterValues ) { ConstructorInfo ctor = GetConstructor( genericBaseType, genericParameterTypes, parameterTypes ); Assert.NotNull(parameterValues); Assert.Equal(parameterTypes.Length, parameterValues.Length); return (T)ctor.Invoke(parameterValues); } /// <summary> /// Creates a new bound generic type and invokes the constructor matched from <see cref="parameterTypes"/>. /// </summary> /// <typeparam name="T">The type of object the constuctor is expected to yield.</typeparam> /// <param name="genericBaseType">The unbound generic base type.</param> /// <param name="genericParameterType">The type of the single generic parameter to apply to create a bound generic type.</param> /// <param name="parameterValues">The list of values to supply to the constructor. It must be possible to determine the</param> /// <returns>The instance created by calling that constructor.</returns> /// <returns>An instance of type <typeparamref name="T"/>.</returns> public T InvokeConstructor<T>( Type genericBaseType, Type genericParameterType, params object[] parameterValues ) { Assert.NotNull(genericBaseType); Assert.True(genericBaseType.IsGenericTypeDefinition); Assert.NotNull(genericParameterType); Type genericType = genericBaseType.MakeGenericType(new Type[] { genericParameterType }); ConstructorInfo ctor = FindConstructor(genericType, parameterValues); Assert.True( ctor != null, String.Format( "Test error: failed to locate generic ctor for type '{0}<{1}>',", genericBaseType.Name, genericParameterType.Name ) ); return (T)ctor.Invoke(parameterValues); } /// <summary> /// Creates a new bound generic type and invokes the constructor matched from <see cref="parameterTypes"/>. /// </summary> /// <typeparam name="T">The type of object the constuctor is expected to yield.</typeparam> /// <param name="genericBaseType">The unbound generic base type.</param> /// <param name="genericParameterTypes">The types of the generic parameters to apply to create a bound generic type.</param> /// <param name="parameterValues">The list of values to supply to the constructor. It must be possible to determine the</param> /// <returns>The instance created by calling that constructor.</returns> /// <returns>An instance of type <typeparamref name="T"/>.</returns> public T InvokeConstructor<T>( Type genericBaseType, Type[] genericParameterTypes, params object[] parameterValues ) { Assert.NotNull(genericBaseType); Assert.True(genericBaseType.IsGenericTypeDefinition); Assert.NotNull(genericParameterTypes); Type genericType = genericBaseType.MakeGenericType(genericParameterTypes); ConstructorInfo ctor = FindConstructor(genericType, parameterValues); Assert.True( ctor != null, String.Format( "Test error: failed to locate generic ctor for type '{0}<>',", genericBaseType.Name ) ); return (T)ctor.Invoke(parameterValues); } /// <summary> /// Asserts the given instance is one from a generic type of the specified parameter type. /// </summary> /// <typeparam name="T">The type of instance.</typeparam> /// <param name="instance">The instance to test.</param> /// <param name="genericTypeParameter">The type of the generic parameter to which the instance's generic type should have been bound.</param> public void IsCorrectGenericType<T>(T instance, Type genericTypeParameter) where T : class { Assert.NotNull(instance); Assert.NotNull(genericTypeParameter); Assert.True(instance.GetType().IsGenericType); Type[] genericArguments = instance.GetType().GetGenericArguments(); Type genericArgument = Assert.Single(genericArguments); Assert.Equal(genericTypeParameter, genericArgument); } /// <summary> /// Invokes via Reflection the method on the given instance. /// </summary> /// <param name="instance">The instance to use.</param> /// <param name="methodName">The name of the method to call.</param> /// <param name="parameterTypes">The types of the parameters to the method.</param> /// <param name="parameterValues">The values to supply to the method.</param> /// <returns>The results of the method.</returns> public object InvokeMethod( object instance, string methodName, Type[] parameterTypes, object[] parameterValues ) { Assert.NotNull(instance); Assert.NotNull(parameterTypes); Assert.NotNull(parameterValues); Assert.Equal(parameterTypes.Length, parameterValues.Length); MethodInfo methodInfo = instance.GetType().GetMethod(methodName, parameterTypes); Assert.NotNull(methodInfo); return methodInfo.Invoke(instance, parameterValues); } /// <summary> /// Invokes via Reflection the static method on the given type. /// </summary> /// <param name="type">The type containing the method.</param> /// <param name="methodName">The name of the method to call.</param> /// <param name="parameterTypes">The types of the parameters to the method.</param> /// <param name="parameterValues">The values to supply to the method.</param> /// <returns>The results of the method.</returns> public object InvokeMethod( Type type, string methodName, Type[] parameterTypes, object[] parameterValues ) { Assert.NotNull(type); Assert.NotNull(parameterTypes); Assert.NotNull(parameterValues); Assert.Equal(parameterTypes.Length, parameterValues.Length); MethodInfo methodInfo = type.GetMethod(methodName, parameterTypes); Assert.NotNull(methodInfo); return methodInfo.Invoke(null, parameterValues); } /// <summary> /// Invokes via Reflection the static method on the given type. /// </summary> /// <param name="type">The type containing the method.</param> /// <param name="methodName">The name of the method to call.</param> /// <param name="genericParameterType">The generic parameter type of the method.</param> /// <param name="parameterTypes">The types of the parameters to the method.</param> /// <param name="parameterValues">The values to supply to the method.</param> /// <returns>The results of the method.</returns> public MethodInfo CreateGenericMethod( Type type, string methodName, Type genericParameterType, Type[] parameterTypes ) { Assert.NotNull(type); Assert.NotNull(parameterTypes); Assert.NotNull(genericParameterType); //MethodInfo methodInfo = type.GetMethod(methodName, parameterTypes); MethodInfo methodInfo = type.GetMethods() .Where( (m) => m.Name.Equals(methodName, StringComparison.OrdinalIgnoreCase) && m.IsGenericMethod && AreAssignableFrom(m.GetParameters(), parameterTypes) ) .FirstOrDefault(); Assert.NotNull(methodInfo); Assert.True(methodInfo.IsGenericMethod); MethodInfo genericMethod = methodInfo.MakeGenericMethod(genericParameterType); Assert.NotNull(genericMethod); return genericMethod; } /// <summary> /// Invokes via Reflection the static generic method on the given type. /// </summary> /// <param name="type">The type containing the method.</param> /// <param name="methodName">The name of the method to call.</param> /// <param name="genericParameterType">The generic parameter type of the method.</param> /// <param name="parameterTypes">The types of the parameters to the method.</param> /// <param name="parameterValues">The values to supply to the method.</param> /// <returns>The results of the method.</returns> public object InvokeGenericMethod( Type type, string methodName, Type genericParameterType, Type[] parameterTypes, object[] parameterValues ) { MethodInfo methodInfo = CreateGenericMethod( type, methodName, genericParameterType, parameterTypes ); Assert.Equal(parameterTypes.Length, parameterValues.Length); return methodInfo.Invoke(null, parameterValues); } /// <summary> /// Invokes via Reflection the generic method on the given instance. /// </summary> /// <param name="instance">The instance on which to invoke the method.</param> /// <param name="methodName">The name of the method to call.</param> /// <param name="genericParameterType">The generic parameter type of the method.</param> /// <param name="parameterTypes">The types of the parameters to the method.</param> /// <param name="parameterValues">The values to supply to the method.</param> /// <returns>The results of the method.</returns> public object InvokeGenericMethod( object instance, string methodName, Type genericParameterType, Type[] parameterTypes, object[] parameterValues ) { Assert.NotNull(instance); MethodInfo methodInfo = CreateGenericMethod( instance.GetType(), methodName, genericParameterType, parameterTypes ); Assert.Equal(parameterTypes.Length, parameterValues.Length); return methodInfo.Invoke(instance, parameterValues); } /// <summary> /// Invokes via Reflection the generic method on the given instance. /// </summary> /// <typeparam name="T">The type of the return value from the method.</typeparam> /// <param name="instance">The instance on which to invoke the method.</param> /// <param name="methodName">The name of the method to call.</param> /// <param name="genericParameterType">The generic parameter type of the method.</param> /// <param name="parameterTypes">The types of the parameters to the method.</param> /// <param name="parameterValues">The values to supply to the method.</param> /// <returns>The results of the method.</returns> public T InvokeGenericMethod<T>( object instance, string methodName, Type genericParameterType, Type[] parameterTypes, object[] parameterValues ) { return (T)InvokeGenericMethod( instance, methodName, genericParameterType, parameterTypes, parameterValues ); } /// <summary> /// Invokes via Reflection the method on the given instance. /// </summary> /// <param name="instance">The instance to use.</param> /// <param name="methodName">The name of the method to call.</param> /// <param name="parameterValues">The values to supply to the method.</param> /// <returns>The results of the method.</returns> public object InvokeMethod( object instance, string methodName, params object[] parameterValues ) { Assert.NotNull(instance); MethodInfo methodInfo = FindMethod(instance.GetType(), methodName, parameterValues); Assert.NotNull(methodInfo); return methodInfo.Invoke(instance, parameterValues); } /// <summary> /// Invokes via Reflection the static method on the given type. /// </summary> /// <param name="instance">The instance to use.</param> /// <param name="methodName">The name of the method to call.</param> /// <param name="parameterValues">The values to supply to the method.</param> /// <returns>The results of the method.</returns> public object InvokeMethod(Type type, string methodName, params object[] parameterValues) { Assert.NotNull(type); MethodInfo methodInfo = FindMethod(type, methodName, parameterValues); Assert.NotNull(methodInfo); return methodInfo.Invoke(null, parameterValues); } /// <summary> /// Invokes via Reflection the method on the given instance. /// </summary> /// <param name="instance">The instance to use.</param> /// <param name="methodName">The name of the method to call.</param> /// <param name="genericParameterType">The type of the generic parameter.</param> /// <param name="parameterValues">The values to supply to the method.</param> /// <returns>The results of the method.</returns> public object InvokeGenericMethod( object instance, string methodName, Type genericParameterType, params object[] parameterValues ) { Assert.NotNull(instance); Assert.NotNull(genericParameterType); MethodInfo methodInfo = FindMethod(instance.GetType(), methodName, parameterValues); Assert.NotNull(methodInfo); Assert.True(methodInfo.IsGenericMethod); MethodInfo genericMethod = methodInfo.MakeGenericMethod(genericParameterType); return genericMethod.Invoke(instance, parameterValues); } /// <summary> /// Invokes via Reflection the method on the given instance. /// </summary> /// <param name="instance">The instance to use.</param> /// <param name="methodName">The name of the method to call.</param> /// <param name="genericParameterType">The type of the generic parameter.</param> /// <param name="parameterValues">The values to supply to the method.</param> /// <returns>The results of the method.</returns> public object InvokeGenericMethod( Type type, string methodName, Type genericParameterType, params object[] parameterValues ) { Assert.NotNull(type); Assert.NotNull(genericParameterType); MethodInfo methodInfo = FindMethod(type, methodName, parameterValues); Assert.NotNull(methodInfo); Assert.True(methodInfo.IsGenericMethod); MethodInfo genericMethod = methodInfo.MakeGenericMethod(genericParameterType); return genericMethod.Invoke(null, parameterValues); } /// <summary> /// Retrieves the value from the specified property. /// </summary> /// <param name="instance">The instance containing the property value.</param> /// <param name="propertyName">The name of the property.</param> /// <param name="failureMessage">The error message to prefix any test assertions.</param> /// <returns>The value returned from the property.</returns> public object GetProperty(object instance, string propertyName, string failureMessage) { PropertyInfo propertyInfo = instance.GetType().GetProperty(propertyName); Assert.NotNull(propertyInfo); return propertyInfo.GetValue(instance, null); } private static bool AreAssignableFrom( Type[] parameterTypes, params object[] parameterValues ) { Assert.NotNull(parameterTypes); Assert.NotNull(parameterValues); if (parameterTypes.Length != parameterValues.Length) { return false; } for (int i = 0; i < parameterTypes.Length; ++i) { if (!parameterTypes[i].IsInstanceOfType(parameterValues[i])) { return false; } } return true; } private static bool AreAssignableFrom( ParameterInfo[] parameterInfos, params Type[] parameterTypes ) { Assert.NotNull(parameterInfos); Assert.NotNull(parameterTypes); Type[] parameterInfoTypes = parameterInfos .Select<ParameterInfo, Type>((info) => info.ParameterType) .ToArray(); if (parameterInfoTypes.Length != parameterTypes.Length) { return false; } for (int i = 0; i < parameterInfoTypes.Length; ++i) { // Generic parameters are assumed to be assignable if (parameterInfoTypes[i].IsGenericParameter) { continue; } if (!parameterInfoTypes[i].IsAssignableFrom(parameterTypes[i])) { return false; } } return true; } private static bool AreAssignableFrom( ParameterInfo[] parameterInfos, params object[] parameterValues ) { Assert.NotNull(parameterInfos); Assert.NotNull(parameterValues); Type[] parameterTypes = parameterInfos .Select<ParameterInfo, Type>((info) => info.ParameterType) .ToArray(); return AreAssignableFrom(parameterTypes, parameterValues); } private static ConstructorInfo FindConstructor(Type type, params object[] parameterValues) { Assert.NotNull(type); Assert.NotNull(parameterValues); return type.GetConstructors() .FirstOrDefault((c) => AreAssignableFrom(c.GetParameters(), parameterValues)); } private static MethodInfo FindMethod( Type type, string methodName, params object[] parameterValues ) { Assert.NotNull(type); Assert.False(String.IsNullOrWhiteSpace(methodName)); Assert.NotNull(parameterValues); return type.GetMethods() .FirstOrDefault( (m) => String.Equals(m.Name, methodName, StringComparison.Ordinal) && AreAssignableFrom(m.GetParameters(), parameterValues) ); } } }
45.369723
149
0.601206
[ "Apache-2.0" ]
belav/AspNetWebStack
test/Microsoft.TestCommon/Microsoft/TestCommon/GenericTypeAssert.cs
31,171
C#
using System; namespace prototype { class Program { static void Main (string[] args) { var user = new User(); user.Name = "Mohammadreza Tarkhan"; user.Age = 20; var address = new Address(); address.City = "Tehran"; address.Country = "Iran"; user.Address = address; Console.WriteLine("{0}: {1} - {2}", user.Name, user.Age, user.Address.City); var newShallowUser = user.ShallowCopy(); user.Name = "Bernard Someson"; address.City = "NY"; Console.WriteLine("{0}: {1} - {2}", newShallowUser.Name, newShallowUser.Age, newShallowUser.Address.City); var deepCopy = user.DeepCopy(); user.Name = "Behnam Baziyar"; address.City = "London"; Console.WriteLine("{0}: {1} - {2}", deepCopy.Name, deepCopy.Age, deepCopy.Address.City); Console.WriteLine("press any key to exit"); Console.ReadLine(); } } }
23.243243
109
0.643023
[ "MIT" ]
mrtarkhan/CreationalDesignPatterns
prototype/prototype/Program.cs
862
C#
using System; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; namespace AppUIBasics.ControlPages { public sealed partial class DataGridPage : Page { public DataGridPage() { this.InitializeComponent(); } private async void LaunchToolkitButton_Click(object sender, RoutedEventArgs e) { // Set the recommended app var options = new Windows.System.LauncherOptions { PreferredApplicationPackageFamilyName = "Microsoft.UWPCommunityToolkitSampleApp_8wekyb3d8bbwe", PreferredApplicationDisplayName = "Windows Community Toolkit" }; await Windows.System.Launcher.LaunchUriAsync(new Uri("uwpct://controls?sample=datagrid"), options); } } }
29.962963
111
0.647713
[ "MIT" ]
Microsoft/Xaml-Controls-Gallery
WinUIGallery/ControlPages/DataGridPage.xaml.cs
811
C#
/* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2020 Colin Green (sharpneat@gmail.com) * * SharpNEAT is free software; you can redistribute it and/or modify * it under the terms of The MIT License (MIT). * * You should have received a copy of the MIT License * along with SharpNEAT; if not, see https://opensource.org/licenses/MIT. */ using System.Drawing; using System.Windows.Forms; using ZedGraph; namespace SharpNeat.Windows.App { /// <summary> /// Form for displaying a graph plot of summary information (e.g. distribution curves). /// </summary> public partial class SummaryGraphForm : Form { readonly SummaryDataSource[] _dataSourceArray; PointPairList[] _pointPlotArray; GraphPane _graphPane; readonly Color[] _plotColorArr = new Color[] { Color.LightSlateGray, Color.LightBlue, Color.LightGreen }; #region Constructor /// <summary> /// Construct the form with the provided details and data sources. /// </summary> public SummaryGraphForm( string title, string xAxisTitle, string y1AxisTitle, string y2AxisTitle, SummaryDataSource[] dataSourceArray) { InitializeComponent(); this.Text = $"SharpNEAT - {title}"; _dataSourceArray = dataSourceArray; InitGraph(title, xAxisTitle, y1AxisTitle, y2AxisTitle, dataSourceArray); } #endregion #region Public Methods /// <summary> /// Refresh view. /// </summary> public void RefreshView() { if(this.InvokeRequired) { // Note. Must use Invoke(). BeginInvoke() will execute asynchronously and the evolution algorithm therefore // may have moved on and will be in an intermediate and indeterminate (between generations) state. this.Invoke(new MethodInvoker(delegate() { RefreshView(); })); return; } if(this.IsDisposed) { return; } // Update plot points for each series in turn. int sourceCount = _dataSourceArray.Length; for(int i=0; i < sourceCount; i++) { SummaryDataSource ds = _dataSourceArray[i]; Point2DDouble[] pointArr = ds.GetPointArray(); PointPairList ppl = _pointPlotArray[i]; EnsurePointPairListLength(ppl, pointArr.Length); for(int j=0; j < pointArr.Length; j++) { ppl[j].X = pointArr[j].X; ppl[j].Y = pointArr[j].Y; } } // Trigger graph to redraw. zed.AxisChange(); Refresh(); } #endregion #region Private Methods private void InitGraph( string title, string xAxisTitle, string y1AxisTitle, string y2AxisTitle, SummaryDataSource[] dataSourceArray) { _graphPane = zed.GraphPane; _graphPane.Title.Text = title; _graphPane.XAxis.Title.Text = xAxisTitle; _graphPane.XAxis.MajorGrid.IsVisible = true; _graphPane.YAxis.Title.Text = y1AxisTitle; _graphPane.YAxis.MajorGrid.IsVisible = true; _graphPane.Y2Axis.Title.Text = y2AxisTitle; _graphPane.Y2Axis.MajorGrid.IsVisible = false; // Create point-pair lists and bind them to the graph control. int sourceCount = dataSourceArray.Length; _pointPlotArray = new PointPairList[sourceCount]; for(int i=0; i < sourceCount; i++) { SummaryDataSource ds = dataSourceArray[i]; _pointPlotArray[i] =new PointPairList(); Color color = _plotColorArr[i % 3]; BarItem barItem = _graphPane.AddBar(ds.Name, _pointPlotArray[i], color); barItem.Bar.Fill = new Fill(color); _graphPane.BarSettings.MinClusterGap = 0; barItem.IsY2Axis = (ds.YAxis == 1); } } private static void EnsurePointPairListLength(PointPairList ppl, int length) { int delta = length - ppl.Count; if(delta > 0) { // Add additional points. for(int i=0; i < delta; i++) { ppl.Add(0.0, 0.0); } } else if(delta < 0) { // Remove excess points. ppl.RemoveRange(length, -delta); } } #endregion } }
32.32
124
0.542904
[ "MIT" ]
sohrabsaran/sharpneat-refactor
src/SharpNeat.Windows.App/SummaryGraphForm.cs
4,850
C#
using System; using System.Collections.Generic; using System.Linq; using LogImporter.Configurations; using LogImporter.Database; using LogImporter.GeoIp; using LogImporter.Transformations; namespace LogImporter { public class Kernel { public void Run(IOptions options) { if (options == null) throw new ArgumentNullException("options"); var configuration = new W3CExtended(); var reader = new LogReader(configuration); IDbAdapter db = new SqlServerAdapter(options.ConnectionString, options.TableName); var files = new FileRepository(options.Directory, options.Pattern); // Create the table in db (if not existent) if (options.CreateTable) { db.EnsureTable(); } using (var service = new GeoIpLookupService()) { // Initialize log parser var parser = new LogParser( reader, files, db, new CleanUrlTransformation(), new GeoLookupTransformation(service)); long count; LogEntry lastEntry = db.GetLastEntry(); if (options.Force || lastEntry == null) { ConsoleWriter.WriteInfo("Importing all log files..."); parser.ParseEntries(out count, options.RenameFile); } else { IEnumerable<string> importedFileNames = db.GetFileNames(); ConsoleWriter.WriteInfo("{0} files already in database.", importedFileNames.Count()); ConsoleWriter.WriteInfo("Importing only new entries...", importedFileNames.Count()); parser.ParseEntries(importedFileNames, lastEntry, out count, options.RenameFile); } ConsoleWriter.WriteSuccess("Imported {0} log entries.", count); } } } }
32.230769
105
0.539857
[ "MIT" ]
sozezzo/LogImporter
source/LogImporter/Kernel.cs
2,097
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace aws { [JsiiInterface(nativeType: typeof(IWafv2RuleGroupRuleStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleHeader), fullyQualifiedName: "aws.Wafv2RuleGroupRuleStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleHeader")] public interface IWafv2RuleGroupRuleStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleHeader { [JsiiProperty(name: "name", typeJson: "{\"primitive\":\"string\"}")] string Name { get; } [JsiiTypeProxy(nativeType: typeof(IWafv2RuleGroupRuleStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleHeader), fullyQualifiedName: "aws.Wafv2RuleGroupRuleStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleHeader")] internal sealed class _Proxy : DeputyBase, aws.IWafv2RuleGroupRuleStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleHeader { private _Proxy(ByRefValue reference): base(reference) { } [JsiiProperty(name: "name", typeJson: "{\"primitive\":\"string\"}")] public string Name { get => GetInstanceProperty<string>()!; } } } }
46.516129
294
0.75104
[ "MIT" ]
scottenriquez/cdktf-alpha-csharp-testing
resources/.gen/aws/aws/IWafv2RuleGroupRuleStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleHeader.cs
1,442
C#
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace Script53_Episodio_173_ { static class Program { /// <summary> /// Ponto de entrada principal para o aplicativo. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
22.5
65
0.610101
[ "MIT" ]
R0drigoG0mes/C-Sharp
Script53_Episodio(173)/Script53_Episodio(173)/Program.cs
497
C#
// © Anamnesis. // Licensed under the MIT license. namespace Anamnesis.Character.Views { using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Threading.Tasks; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; using Anamnesis; using Anamnesis.GameData; using Anamnesis.Memory; using Anamnesis.Services; using PropertyChanged; using XivToolsWpf.DependencyProperties; /// <summary> /// Interaction logic for FacialFeaturesControl.xaml. /// </summary> [AddINotifyPropertyChangedInterface] public partial class FacialFeaturesControl : UserControl { public static readonly IBind<ActorCustomizeMemory.FacialFeature> ValueDp = Binder.Register<ActorCustomizeMemory.FacialFeature, FacialFeaturesControl>(nameof(Value), OnValueChanged); public static readonly IBind<ActorCustomizeMemory.Genders> GenderDp = Binder.Register<ActorCustomizeMemory.Genders, FacialFeaturesControl>(nameof(Gender), OnGenderChanged); public static readonly IBind<ActorCustomizeMemory.Tribes> TribeDp = Binder.Register<ActorCustomizeMemory.Tribes, FacialFeaturesControl>(nameof(Tribe), OnTribeChanged); public static readonly IBind<byte> HeadDp = Binder.Register<byte, FacialFeaturesControl>(nameof(Head), OnHeadChanged); private readonly List<Option> features = new List<Option>(); private bool locked = false; public FacialFeaturesControl() { this.InitializeComponent(); OnValueChanged(this, this.Value); } public ActorCustomizeMemory.Genders Gender { get => GenderDp.Get(this); set => GenderDp.Set(this, value); } public ActorCustomizeMemory.Tribes Tribe { get => TribeDp.Get(this); set => TribeDp.Set(this, value); } public byte Head { get => HeadDp.Get(this); set => HeadDp.Set(this, value); } public ActorCustomizeMemory.FacialFeature Value { get => ValueDp.Get(this); set => ValueDp.Set(this, value); } private static void OnGenderChanged(FacialFeaturesControl sender, ActorCustomizeMemory.Genders value) { sender.GetFeatures(); OnValueChanged(sender, sender.Value); } private static void OnTribeChanged(FacialFeaturesControl sender, ActorCustomizeMemory.Tribes value) { sender.GetFeatures(); OnValueChanged(sender, sender.Value); } private static void OnHeadChanged(FacialFeaturesControl sender, byte value) { sender.GetFeatures(); OnValueChanged(sender, sender.Value); } private static void OnValueChanged(FacialFeaturesControl sender, ActorCustomizeMemory.FacialFeature value) { sender.locked = true; foreach (Option op in sender.features) { op.Selected = sender.Value.HasFlag(op.Value); } sender.locked = false; } private void GetFeatures() { this.locked = true; this.FeaturesList.ItemsSource = null; if (this.Tribe == 0) return; ImageSource[]? facialFeatures = null; if (GameDataService.CharacterMakeTypes != null) { foreach (ICharaMakeType set in GameDataService.CharacterMakeTypes) { if (set.Tribe != this.Tribe) continue; if (set.Gender != this.Gender) continue; facialFeatures = set.FacialFeatures.ToArray(); break; } } if (facialFeatures == null) return; this.features.Clear(); for (byte i = 0; i < 7; i++) { int id = (this.Head - 1) + (8 * i); if (id < 0 || id >= facialFeatures.Length) continue; Option op = new Option(); op.Icon = facialFeatures[id]; op.Value = this.GetValue(i); op.Index = id; this.features.Add(op); } Option legacyTattoo = new Option(); legacyTattoo.Value = ActorCustomizeMemory.FacialFeature.LegacyTattoo; this.features.Add(legacyTattoo); this.FeaturesList.ItemsSource = this.features; this.locked = false; } private ActorCustomizeMemory.FacialFeature GetValue(int index) { switch (index) { case 0: return ActorCustomizeMemory.FacialFeature.First; case 1: return ActorCustomizeMemory.FacialFeature.Second; case 2: return ActorCustomizeMemory.FacialFeature.Third; case 3: return ActorCustomizeMemory.FacialFeature.Fourth; case 4: return ActorCustomizeMemory.FacialFeature.Fifth; case 5: return ActorCustomizeMemory.FacialFeature.Sixth; case 6: return ActorCustomizeMemory.FacialFeature.Seventh; } throw new Exception("Invalid index value"); } private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { if (this.locked) return; ActorCustomizeMemory.FacialFeature flags = ActorCustomizeMemory.FacialFeature.None; foreach (Option? op in this.FeaturesList.SelectedItems) { if (op == null) continue; flags |= op.Value; } this.Value = flags; } [AddINotifyPropertyChangedInterface] private class Option { public ActorCustomizeMemory.FacialFeature Value { get; set; } public ImageSource? Icon { get; set; } public int Index { get; set; } public bool Selected { get; set; } } } }
26.855615
183
0.72262
[ "MIT" ]
imchillin/Anamnesis
Anamnesis/Character/Views/FacialFeaturesControl.xaml.cs
5,025
C#
namespace DavinoComputers.Services.Data.Tests.Data { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DavinoComputers.Data.Models; public static class TestSubCategoriesData { public static IEnumerable<SubCategory> FakeSubCategories => new List<SubCategory>() { new SubCategory { Name = "CPU", Id = 1 }, new SubCategory { Name = "GPU", Id = 2 }, new SubCategory { Name = "RAM", Id = 3 }, new SubCategory { Name = "Mother Boards", Id = 4 }, new SubCategory { Name = "Power Supply", Id = 5 }, new SubCategory { Name = "Computer Cases", Id = 6 }, }; } }
31
65
0.578065
[ "MIT" ]
Ivan-D-Ivanov/ASP.NET-Project-D-Computers
Tests/DavinoComputers.Services.Data.Tests/Data/TestSubCategoriesData.cs
777
C#
using System; using Newtonsoft.Json; namespace TdLib { /// <summary> /// Autogenerated TDLib APIs /// </summary> public static partial class TdApi { public partial class ChatActionBar : Object { /// <summary> /// The chat is a private or secret chat and the other user can be added to the contact list using the method addContact /// </summary> public class ChatActionBarAddContact : ChatActionBar { /// <summary> /// Data type for serialization /// </summary> [JsonProperty("@type")] public override string DataType { get; set; } = "chatActionBarAddContact"; /// <summary> /// Extra data attached to the message /// </summary> [JsonProperty("@extra")] public override string Extra { get; set; } } } } }
30.78125
132
0.51066
[ "MIT" ]
0x25CBFC4F/tdsharp
TDLib.Api/Objects/ChatActionBarAddContact.cs
985
C#
//--------------------------------------------------------------------- // <copyright file="OpenApiWriterTestHelper.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- using System; using System.IO; namespace Microsoft.OData.OpenAPI.Tests { internal static class OpenApiWriterTestHelper { internal static string WriteToJson(this IOpenApiWritable element, Action<IOpenApiWriter, IOpenApiWritable> before = null, Action<IOpenApiWriter, IOpenApiWritable> after = null) { Action<IOpenApiWriter> action = writer => { before?.Invoke(writer, element); element?.Write(writer); after?.Invoke(writer, element); writer?.Flush(); }; return Write(OpenApiTarget.Json, action); } internal static string WriteToYaml(this IOpenApiWritable element, Action<IOpenApiWriter, IOpenApiWritable> before = null, Action<IOpenApiWriter, IOpenApiWritable> after = null) { Action<IOpenApiWriter> action = writer => { before?.Invoke(writer, element); element?.Write(writer); after?.Invoke(writer, element); writer?.Flush(); }; return Write(OpenApiTarget.Yaml, action); } internal static string Write(this IOpenApiWritable element, OpenApiTarget target, Action<IOpenApiWriter, IOpenApiWritable> before = null, Action<IOpenApiWriter, IOpenApiWritable> after = null) { Action<IOpenApiWriter> action = writer => { before?.Invoke(writer, element); element?.Write(writer); after?.Invoke(writer, element); writer?.Flush(); }; return Write(target, action); } internal static string Write(this Action<IOpenApiWriter> action, OpenApiTarget target) { MemoryStream stream = new MemoryStream(); IOpenApiWriter writer; if (target == OpenApiTarget.Yaml) { writer = new OpenApiYamlWriter(new StreamWriter(stream)); } else { writer = new OpenApiJsonWriter(new StreamWriter(stream)); } action(writer); writer.Flush(); stream.Position = 0; return new StreamReader(stream).ReadToEnd(); } internal static string Write(OpenApiTarget target, Action<IOpenApiWriter> action) { MemoryStream stream = new MemoryStream(); IOpenApiWriter writer; if (target == OpenApiTarget.Yaml) { writer = new OpenApiYamlWriter(new StreamWriter(stream)); } else { writer = new OpenApiJsonWriter(new StreamWriter(stream)); } action(writer); writer.Flush(); stream.Position = 0; return new StreamReader(stream).ReadToEnd(); } } }
33.59
126
0.531706
[ "Apache-2.0" ]
BrendanBeachBC/jag-spd-spice
interfaces/OData.OpenAPI/Microsoft.OData.OpenAPI.Tests/Common/OpenApiWriterTestHelper.cs
3,361
C#