content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System.Diagnostics.Tracing; namespace Microsoft.Practices.EnterpriseLibrary.SemanticLogging.OutProc.Tests.TestObjects { public sealed class TestEventSource : EventSource { public const int InformationalEventId = 4; public const int AuditSuccessEventId = 20; public const int ErrorEventId = 5; public const int CriticalEventId = 6; public const int LogAlwaysEventId = 7; public const int VerboseEventId = 100; public const int NonDefaultOpcodeNonDefaultVersionEventId = 103; public const int EventWithoutPayloadNorMessageId = 200; public const int EventWithPayloadId = 201; public const int EventWithMessageId = 202; public const int EventWithPayloadAndMessageId = 203; public const int EventIdForAllParameters = 150; public const int EventWithMultiplePayloadsId = 205; public const int ErrorWithKeywordDiagnosticEventId = 1020; public const int CriticalWithKeywordPageEventId = 1021; public const int CriticalWithTaskNameEventId = 1500; public static readonly TestEventSource Logger = new TestEventSource(); public class Keywords { public const EventKeywords Page = (EventKeywords)1; public const EventKeywords DataBase = (EventKeywords)2; public const EventKeywords Diagnostic = (EventKeywords)4; public const EventKeywords Perf = (EventKeywords)8; } public class Tasks { public const EventTask Page = (EventTask)1; public const EventTask DBQuery = (EventTask)2; } } }
41.209302
122
0.694695
[ "Apache-2.0" ]
Meetsch/semantic-logging
BVT/SLAB.Tests/SemanticLogging.OutProc.Tests/TestObjects/TestEventSource.cs
1,774
C#
using System; using System.Collections.Generic; using ESFA.DC.ILR.Model.Interface; using ESFA.DC.ILR.Tests.Model; using ESFA.DC.ILR.ValidationService.Interface; using ESFA.DC.ILR.ValidationService.Rules.LearningDelivery.CompStatus; using ESFA.DC.ILR.ValidationService.Rules.Tests.Abstract; using FluentAssertions; using Moq; using Xunit; namespace ESFA.DC.ILR.ValidationService.Rules.Tests.LearningDelivery.CompStatus { public class CompStatus_07RuleTests : AbstractRuleTests<CompStatus_06Rule> { [Fact] public void RuleName() { NewRule().RuleName.Should().Be("CompStatus_07"); } [Fact] public void AimTypeCondition_Pass() { var aimType = 1; NewRule().AimTypeConditionMet(aimType).Should().BeTrue(); } [Fact] public void AimTypeCondition_Fails() { var aimType = 2; NewRule().AimTypeConditionMet(aimType).Should().BeFalse(); } [Fact] public void FundModelContion_Pass() { var fundModel = 36; NewRule().FundModelConditionMet(fundModel).Should().BeTrue(); } [Fact] public void FundModelCondition_Fails() { var fundModel = 81; NewRule().FundModelConditionMet(fundModel).Should().BeFalse(); } [Fact] public void ProgTypeCondition_Pass() { int progType = 25; NewRule().ProgTypeConditionMet(progType).Should().BeTrue(); } [Theory] [InlineData(21)] [InlineData(null)] public void ProgTypeCondition_Fails(int? progType) { NewRule().ProgTypeConditionMet(progType).Should().BeFalse(); } [Fact] public void LearnActEndDateCondition_Pass_AsDateIsEqual() { var learnActEndDate = new DateTime(2019, 08, 01); NewRule().LearnActEndDateConditionMet(learnActEndDate).Should().BeTrue(); } [Fact] public void LearnActEndDateCondition_Pass_AsDateisGreater() { var learnActEndDate = new DateTime(2019, 09, 11); NewRule().LearnActEndDateConditionMet(learnActEndDate).Should().BeTrue(); } [Theory] [InlineData("01/07/2019")] [InlineData(null)] public void LearnActEndDateCondition_Fails(string strActEndDate) { DateTime? learnActEndDate = string.IsNullOrEmpty(strActEndDate) ? (DateTime?)null : DateTime.Parse(strActEndDate); NewRule().LearnActEndDateConditionMet(learnActEndDate).Should().BeFalse(); } [Fact] public void AchDateCondition_Pass() { DateTime achDate = new DateTime(2019, 08, 01); NewRule().AchDateConditionMet(achDate).Should().BeTrue(); } [Fact] public void AchDateCondition_Fails_IsNull() { DateTime? achDate = null; NewRule().AchDateConditionMet(achDate).Should().BeFalse(); } [Fact] public void CompStatusCondition_Pass() { var compStatus = 3; NewRule().CompStatusConditionMet(compStatus).Should().BeTrue(); } [Fact] public void CompStatusCondition_Fail() { var compStatus = 2; NewRule().CompStatusConditionMet(compStatus).Should().BeFalse(); } [Fact] public void ConditionMet_Pass() { var aimType = 1; var fundModel = 36; var progType = 25; var compStatus = 3; var learnActEndDate = new DateTime(2019, 08, 01); var achDate = learnActEndDate.AddMonths(2); var rule = NewRule().ConditionMet(aimType, fundModel, progType, compStatus, learnActEndDate, achDate); rule.Should().BeTrue(); } [Theory] [InlineData(2, 36, 25, 3, "01/08/2019", "01/08/2019")] // aimType condition returns FALSE [InlineData(1, 81, 25, 3, "01/08/2019", "01/08/2019")] // fundModel condition returns FALSE [InlineData(1, 36, 24, 3, "01/08/2019", "01/08/2019")] // progType condition returns FALSE [InlineData(1, 36, 25, 2, "01/08/2019", "01/08/2019")] // compStatus condition returns FALSE [InlineData(1, 36, 25, 3, null, "01/08/2019")] // LearnActEndDateConditionMet condition is NULL returns FALSE [InlineData(1, 36, 25, 3, "01/07/2019", "01/10/2019")] // LearnActEndDateCondition FALSE as date is Lower than 01/08/2019 [InlineData(1, 36, 25, 3, "01/12/2019", null)] // AchDate condition is NULL returns FALSE public void ConditionMet_Fails(int aimType, int fundModel, int? progType, int compStatus, string strLearnActEndDate, string strAchDate) { DateTime? learnActEndDate = string.IsNullOrEmpty(strLearnActEndDate) ? (DateTime?)null : DateTime.Parse(strLearnActEndDate); DateTime? achDate = string.IsNullOrEmpty(strAchDate) ? (DateTime?)null : DateTime.Parse(strAchDate); var rule = NewRule().ConditionMet(aimType, fundModel, progType, compStatus, learnActEndDate, achDate); rule.Should().BeFalse(); } [Fact] public void Validate_Error() { var learner = new TestLearner() { LearningDeliveries = new List<ILearningDelivery>() { new TestLearningDelivery() { AimType = 1, FundModel = 36, ProgTypeNullable = 25, CompStatus = 3, LearnActEndDateNullable = new DateTime(2019, 09, 21), AchDateNullable = new DateTime(2019, 09, 21), } } }; using (var validationErrorHandlerMock = BuildValidationErrorHandlerMockForError()) { NewRule(validationErrorHandlerMock.Object).Validate(learner); } } [Fact] public void Validate_NoErrors() { var learner = new TestLearner() { LearningDeliveries = new List<ILearningDelivery>() { new TestLearningDelivery() { AimType = 2, FundModel = 81, LearnActEndDateNullable = new DateTime(2019, 06, 21), AchDateNullable = null } } }; using (var validationErrorHandlerMock = BuildValidationErrorHandlerMockForNoError()) { NewRule(validationErrorHandlerMock.Object).Validate(learner); } } [Fact] public void BuildErrorMessageParameters() { var validationErrorHandlerMock = new Mock<IValidationErrorHandler>(); var fundModel = 36; var progType = 25; var compStatus = 3; var learnActEndDate = new DateTime(2019, 07, 01); var achDate = learnActEndDate.AddMonths(1); validationErrorHandlerMock.Setup(veh => veh.BuildErrorMessageParameter("FundModel", fundModel)).Verifiable(); validationErrorHandlerMock.Setup(veh => veh.BuildErrorMessageParameter("ProgType", progType)).Verifiable(); validationErrorHandlerMock.Setup(veh => veh.BuildErrorMessageParameter("CompStatus", compStatus)).Verifiable(); validationErrorHandlerMock.Setup(veh => veh.BuildErrorMessageParameter("LearnStartDate", "01/07/2019")).Verifiable(); validationErrorHandlerMock.Setup(veh => veh.BuildErrorMessageParameter("AchDate", "01/08/2019")).Verifiable(); NewRule(validationErrorHandlerMock.Object).BuildErrorMessageParameters(fundModel, progType, compStatus, learnActEndDate, achDate); validationErrorHandlerMock.Verify(); } private CompStatus_07Rule NewRule(IValidationErrorHandler validationErrorHandler = null) { return new CompStatus_07Rule(validationErrorHandler); } } }
36.49115
143
0.587608
[ "MIT" ]
SkillsFundingAgency/DC-ILR-2021-ValidationService
src/ESFA.DC.ILR.ValidationService.Rules.Tests/LearningDelivery/CompStatus/CompStatus_07RuleTests.cs
8,249
C#
/* ============================================================================ Namespace Name: WizardWrx.DLLServices2 Class Name: SysDateFormatters File Name: SysDateFormatters.cs Synopsis: This class implements my stalwart ReformatSysDate_P6C date formatting algorithm as 100% managed code. Remarks: This class is implicitly sealed. Instances of it cannot be created, and the class cannot be inherited. If you insist on saving your format strings, store them in its sibling class, TimeDisplayFormatter, and call these methods through it. References: 1) DayOfWeek Enumeration http://msdn.microsoft.com/en-us/library/system.dayofweek.aspx 2) DateTimeFormatInfo.AbbreviatedDayNames Property http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.abbreviateddaynames.aspx 3) DateTimeFormatInfo Class http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx Author: David A. Gray License: Copyright (C) 2012-2016, David A. Gray. 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 David A. Gray, nor the names of his 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 David A. Gray 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. ---------------------------------------------------------------------------- Revision History ---------------------------------------------------------------------------- Date Version Author Synopsis ---------- ------- ------ -------------------------------------------------- 2012/02/26 1.7 DAG This class makes its first appearance. 2012/03/03 1.8 DAG Comment the public constants. 2012/09/03 2.6 DAG Complete the constellation by adding ReformatNow and ReformatUtcNow. 2013/02/17 2.96 DAG Add RFD_MM_DD_YY, which defines the archaic short (eight character) date format. The archaic format is required by ZZRdInts, and probably others, sooner or later. For unrelated reasons, this version of the assembly gets a strong name. 2013/11/24 3.1 DAG 1) Add the following overlooked, but often required compact date formats. ---------------------------------- Mask Symbol --------------- ------------------ YYYYMMDD_hhmmss RFDYYYYMMDD_HHMMSS YYYYMMDD RFDYYYYMMDD HHMMSS RFDHHMMSS ---------------------------------- 2) Correct a couple of typographical errors in the internal documentation that I discovered while scanning for the above-cited formatting masks. The executable code is unaffected. 2014/06/07 5.0 DAG Major namespace reorganization. 2014/06/23 5.1 DAG Documentation corrections. 2014/09/14 5.2 DAG Copy into to WizardWrx.DLLServices2 class library, which is built against the Microsoft .NET Framework, version 3.5, to take advantage of its new TimeZoneInfo class, required by the new Util class, which brings together assorted constants and methods developed for various applications. 2015/06/06 5.4 DAG Break completely free from WizardWrx.SharedUtl2. 2015/06/20 5.5 DAG Relocate to WizardWrx.DLLServices2 namespace and class library. 2016/04/10 6.0 DAG Scan for typographical errors flagged by the spelling checker add-in, and correct what I find, and update the formatting and marking of blocks. ============================================================================ */ using System; using System.Collections.Generic; using System.Text; /* Added by DAG */ using System.Globalization; using WizardWrx; namespace WizardWrx.DLLServices2 { /// <summary> /// This class implements my stalwart date formatter, ReformatSysDateP6C, /// which I created initially as a Windows Interface Language (WIL, /// a. k. a. WinBatch) library function, Reformat_Date_YmdHms_P6C, in /// October 2001, although its roots go back much further in my WIL script /// development. /// /// Since static classes are implicitly sealed, this class cannot be inherited. /// </summary> /// <seealso cref="DisplayFormats"/> /// <seealso cref="TimeDisplayFormatter"/> public static class SysDateFormatters { #region Public constants define the substitution tokens and a selection of useful format strings. /// <summary> /// The strings in this array are the substitution tokens supported by /// the date formatters in this class. /// </summary> public static readonly string [ ] RSD_TOKENS = { @"^MMMM" , @"^MMM" , @"^MM" , @"^DD" , @"^D" , @"^YYYY" , @"^YY" , @"^hh" , @"^h" , @"^mm" , @"^ss" , @"^WWWW" , @"^WWW" , @"^WW" , @"^ttt" }; // public static readonly string [ ] RSD_TOKENS /// <summary> /// Apply the following format to a date: YYYY/MM/DD /// /// With respect to the date only, this format confirms to the ISO 8601 /// standard for time representation. /// /// Only the date is returned, all four digits of the year are included, /// and the month and day have leading zeros if either is less than 10. /// </summary> public const string RFD_YYYY_MM_DD = @"^YYYY/^MM/^DD"; /// <summary> /// Apply the following format to a date: MM/DD/YY /// /// This is the standard short format used in the USA. /// /// Only the date is returned, including only the year of century, and /// the month and day have leading zeros if either is less than 10. /// </summary> public const string RFD_MM_DD_YY = @"^MM/^DD/^YY"; /// <summary> /// Apply the following format to a date: MM/DD/YYYY /// /// This is the standard format used in the USA. /// /// Only the date is returned, all four digits of the year are included, /// and the month and day have leading zeros if either is less than 10. /// </summary> public const string RFD_MM_DD_YYYY = @"^MM/^DD/^YYYY"; /// <summary> /// Apply the following format to a date: DD/MM/YYYY /// /// This is the standard format used in most of the English speaking /// world, by all military organizations of which I am aware, Europeans, /// and others who take their lead from any of the above groups. /// /// Only the date is returned, all four digits of the year are included, /// and the month and day have leading zeros if either is less than 10. /// </summary> public const string RFD_DD_MM_YYYY = @"^DD/^MM/^YYYY"; /// <summary> /// Apply the following format to a time: hh:mm /// /// The returned string represents the hours on a 24 hour clock. /// /// At present, 12 hour (AM/PM) representation is unsupported. /// /// This is a standard format used in most of the English speaking /// world, by all military organizations of which I am aware, Europeans, /// and others who take their lead from any of the above groups. /// /// Only the time is returned, and the hour and minute have leading /// zeros if either is less than 10. /// </summary> public const string RFD_HH_MM = @"^hh:^mm"; /// <summary> /// Apply the following format to a time: hh:mm:ss /// /// The returned string represents the hours on a 24 hour clock. /// /// At present, 12 hour (AM/PM) representation is unsupported. /// /// This is a standard format used in most of the English speaking /// world, by all military organizations of which I am aware, Europeans, /// and others who take their lead from any of the above groups. /// /// Only the time is returned, and the hour, minute, and second have /// leading zeros if any of them is less than 10. /// </summary> public const string RFD_HH_MM_SS = @"^hh:^mm:^ss"; /// <summary> /// Apply the following format to a time: hh:mm:ss.ttt /// /// The returned string represents the hours on a 24 hour clock. /// /// At present, 12 hour (AM/PM) representation is unsupported. /// /// The final token, ttt, is the milliseconds portion of the time, /// which is reported with leading zeros. /// /// This is an extension of a standard format used in most of the /// English speaking world, by all military organizations of which I am /// aware, Europeans, and others who take their lead from any of the /// above groups. /// /// Only the time is returned, and the hour, minute, and second have /// leading zeros if any of them is less than 10. /// </summary> public const string RFD_HH_MM_SS_TTT = @"^hh:^mm:^ss.^ttt"; /// <summary> /// Apply the following format to a date and time: YYYY/MM/DD hh:mm:ss /// /// The returned string represents the hours on a 24 hour clock. /// /// At present, 12 hour (AM/PM) representation is unsupported. /// /// This format conforms fully to the ISO 8601 standard for time /// representation. /// /// The month, day, hour, minute, and second have leading zeros if any /// of them is less than 10. /// </summary> public const string RFD_YYYY_MM_DD_HH_MM_SS = @"^YYYY/^MM/^DD ^hh:^mm:^ss"; /// <summary> /// Apply the following format to a date and time: YYYY/MM/DD hh:mm:ss.ttt /// /// The returned string represents the hours on a 24 hour clock. /// /// At present, 12 hour (AM/PM) representation is unsupported. /// /// This format conforms fully to the ISO 8601 standard for time /// representation. /// /// The final token, ttt, is the milliseconds portion of the time, /// which is reported with leading zeros. /// /// The month, day, hour, minute, and second have leading zeros if any /// of them is less than 10. /// </summary> public const string RFD_YYYY_MM_DD_HH_MM_SS_TTT = @"^YYYY/^MM/^DD ^hh:^mm:^ss.^ttt"; /// <summary> /// Apply the following format to a date: WWW DD/MM/YYYY /// /// The first token, WWW, represents the three letter abbreviation of /// the weekday name, which is derived from the regional settings in the /// Windows Control Panel. The returned string conforms to the settings /// in the UICulture of the calling thread. /// /// This is the standard format used in most of the English speaking /// world, by all military organizations of which I am aware, Europeans, /// and others who take their lead from any of the above groups. /// /// Only the date is returned, all four digits of the year are included, /// and the month and day have leading zeros if either is less than 10. /// </summary> public const string RFD_WWW_DD_MM_YYYY = @"^WWW ^DD/^MM/^YYYY"; /// <summary> /// Apply the following format to a date: WWW DD/MM/YYYY /// /// The first token, WWW, represents the three letter abbreviation of /// the weekday name, which is derived from the regional settings in the /// Windows Control Panel. The returned string conforms to the settings /// in the UICulture of the calling thread. /// /// This is the standard format used in the USA. /// /// Only the date is returned, all four digits of the year are included, /// and the month and day have leading zeros if either is less than 10. /// </summary> public const string RFD_WWW_MM_DD_YYYY = @"^WWW ^MM/^DD/^YYYY"; /// <summary> /// Apply the following format to a date: WW DD/MM/YYYY /// /// The first token, WW, represents enough of the three letter weekday /// name abbreviation, which is derived from the regional settings in /// the Windows Control Panel, to uniquely identify the weekday. The /// returned string conforms to the settings in the UICulture of the /// calling thread. /// /// This is the standard format used in most of the English speaking /// world, by all military organizations of which I am aware, Europeans, /// and others who take their lead from any of the above groups. /// /// Only the date is returned, all four digits of the year are included, /// and the month and day have leading zeros if either is less than 10. /// </summary> public const string RFD_WW_DD_MM_YYYY = @"^WW ^DD/^MM/^YYYY"; /// <summary> /// Apply the following format to a date: WW DD/MM/YYYY /// /// The first token, WW, represents enough of the three letter weekday /// name abbreviation, which is derived from the regional settings in /// the Windows Control Panel, to uniquely identify the weekday. The /// returned string conforms to the settings in the UICulture of the /// calling thread. /// /// This is the standard format used in the USA. /// /// Only the date is returned, all four digits of the year are included, /// and the month and day have leading zeros if either is less than 10. /// </summary> public const string RFD_WW_MM_DD_YYYY = @"^WW ^MM/^DD/^YYYY"; /// <summary> /// Apply the following format to a date: WWWW DD/MM/YYYY /// /// The first token, WWWW, represents full name of the weekday, which is /// derived from the regional settings in the Windows Control Panel. The /// returned string conforms to the settings in the UICulture of the /// calling thread. /// /// This is the standard format used in most of the English speaking /// world, by all military organizations of which I am aware, Europeans, /// and others who take their lead from any of the above groups. /// /// Only the date is returned, all four digits of the year are included, /// and the month and day have leading zeros if either is less than 10. /// </summary> public const string RFD_WWWW_DD_MM_YYYY = @"^WWWW, ^DD/^MM/^YYYY"; /// <summary> /// Apply the following format to a date: WWWW DD/MM/YYYY /// /// The first token, WWWW, represents full name of the weekday, which is /// derived from the regional settings in the Windows Control Panel. The /// returned string conforms to the settings in the UICulture of the /// calling thread. /// /// This is the standard format used in the USA. /// /// Only the date is returned, all four digits of the year are included, /// and the month and day have leading zeros if either is less than 10. /// </summary> public const string RFD_WWWW_MM_DD_YYYY = @"^WWWW, ^MM/^DD/^YYYY"; /// <summary> /// Apply the following format to a date and time: YYYYMMDD_hhmmss /// /// The returned string represents the hours on a 24 hour clock. /// /// At present, 12 hour (AM/PM) representation is unsupported. /// /// This format conforms fully to the ISO 8601 standard for time /// representation. /// /// The month, day, hour, minute, and second have leading zeros if any /// of them is less than 10. /// </summary> public const string RFDYYYYMMDD_HHMMSS = @"^YYYY^MM^DD_^hh^mm^ss"; /// <summary> /// Apply the following format to a date and time: YYYYMMDD /// /// The returned string represents the hours on a 24 hour clock. /// /// At present, 12 hour (AM/PM) representation is unsupported. /// /// This format conforms fully to the ISO 8601 standard for time /// representation. /// /// The month and day have leading zeros if either is less than 10. /// </summary> public const string RFDYYYYMMDD = @"^YYYY^MM^DD"; /// <summary> /// Apply the following format to a date and time: hhmmss /// /// The returned string represents the hours on a 24 hour clock. /// /// At present, 12 hour (AM/PM) representation is unsupported. /// /// This format conforms fully to the ISO 8601 standard for time /// representation. /// /// The hour, minute, and second have leading zeros if any of them is /// less than 10. /// </summary> public const string RFDHHMMSS = @"^hh^mm^ss"; #endregion // Public constants define the substitution tokens and a selection of useful format strings. #region Although static, this class requires several tables that are initialized at compile time. enum FormattingAlgorithm { ApplyFormatToDateTime , TwoLetterWeekday } // FormattingAlgorithm static readonly FormattingAlgorithm [ ] RSD_ALGORITHM = { FormattingAlgorithm.ApplyFormatToDateTime , FormattingAlgorithm.ApplyFormatToDateTime , FormattingAlgorithm.ApplyFormatToDateTime , FormattingAlgorithm.ApplyFormatToDateTime , FormattingAlgorithm.ApplyFormatToDateTime , FormattingAlgorithm.ApplyFormatToDateTime , FormattingAlgorithm.ApplyFormatToDateTime , FormattingAlgorithm.ApplyFormatToDateTime , FormattingAlgorithm.ApplyFormatToDateTime , FormattingAlgorithm.ApplyFormatToDateTime , FormattingAlgorithm.ApplyFormatToDateTime , FormattingAlgorithm.ApplyFormatToDateTime , FormattingAlgorithm.ApplyFormatToDateTime , FormattingAlgorithm.TwoLetterWeekday , FormattingAlgorithm.ApplyFormatToDateTime }; // FormattingAlgorithm [ ] RSD_ALGORITHM = static readonly string [ ] RSD_BCL_FORMATS = { @"MMMM" , @"MMM" , @"MM" , @"dd" , @"%d" , // See http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#UsingSingleSpecifiers. @"yyyy" , @"yy" , @"HH" , @"%H" , // See http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#UsingSingleSpecifiers. @"mm" , @"ss" , @"dddd" , @"ddd" , @"^WW" , // There is no custom format string that corresponds to ^WW. @"fff" }; // string [ ] RSD_BCL_FORMATS #endregion // Although static, this class requires several tables that are initialized at compile time. #region In addition to the hard coded tables, this class uses another table, and a scalar which holds the size of the three hard coded tables, which are initialized at run time by the static constructor. static readonly string [ ] RSD_WEEKDAY_2LTRS; static readonly int _intNDefinedTokens; #endregion // In addition to the hard coded tables, this class uses another table, and a scalar which holds the size of the three hard coded tables, which are initialized at run time by the static constructor. #region The static constructor initializes the two-letter weekday table based on the current UI culture. static SysDateFormatters ( ) { const int DAYS_IN_WEEK = 7; const int ONE_LETTER = ArrayInfo.NEXT_INDEX; const int SECOND_LETTER_INDEX = ArrayInfo.NEXT_INDEX; const string TWO_LETTERS = @"{0}{1}"; const string UNBALANCED_ERRMSG = @"The static SysDateFormatters constructor has detected unbalanced string arrays.{2}Length of array RSD_TOKENS = {0}{2}Length of array RSD_BCL_FORMATS = {1}"; // ---------------------------------------------------------------- // Sanity check the sizes of the three arrays that were initialized // at compile time. All three must be the same size. // ---------------------------------------------------------------- int intRSDTokenArraySize = RSD_TOKENS.Length; int intBCLFormatArraySize = RSD_BCL_FORMATS.Length; int intAlgorithmArraySize = RSD_ALGORITHM.Length; if ( intRSDTokenArraySize == intBCLFormatArraySize ) if ( intAlgorithmArraySize == intRSDTokenArraySize ) _intNDefinedTokens = intRSDTokenArraySize; else throw new Exception ( string.Format ( UNBALANCED_ERRMSG , intRSDTokenArraySize , intBCLFormatArraySize , Environment.NewLine ) ); // ---------------------------------------------------------------- // The fourth array, RSD_WEEKDAY_2LTRS, is initialized by this // constructor, because the required values are unknown until this // constructor executes. // ---------------------------------------------------------------- RSD_WEEKDAY_2LTRS = new string [ DAYS_IN_WEEK ]; string [ ] astrAbbrWdayNames = CultureInfo.CurrentUICulture.DateTimeFormat.AbbreviatedDayNames; char [ ] achrFirstLetter = new char [ DAYS_IN_WEEK ]; Dictionary<char , int> dctTimesUsed = new Dictionary<char , int> ( DAYS_IN_WEEK ); int intDayIndex = ArrayInfo.ARRAY_INVALID_INDEX; // ---------------------------------------------------------------- // Isolate and count the first letter. // ---------------------------------------------------------------- foreach ( string strWeekdayName in astrAbbrWdayNames ) { char [ ] achrFirstLtrOfWday = strWeekdayName.ToCharArray ( ArrayInfo.ARRAY_FIRST_ELEMENT , ONE_LETTER ); achrFirstLetter [ ++intDayIndex ] = achrFirstLtrOfWday [ ArrayInfo.ARRAY_FIRST_ELEMENT ]; if ( dctTimesUsed.ContainsKey ( achrFirstLetter [ intDayIndex ] ) ) { // Letter already used at least once. ++dctTimesUsed [ achrFirstLetter [ intDayIndex ] ]; } // TRUE block, if ( dctTimesUsed.ContainsKey ( achrFirstLetter [ intDayIndex ] ) ) else { // First use of this letter. dctTimesUsed [ achrFirstLetter [ intDayIndex ] ] = ONE_LETTER; } // FALSE block, if ( dctTimesUsed.ContainsKey ( achrFirstLetter [ intDayIndex ] ) ) } // foreach ( string strWeekdayName in astrAbbrWdayNames ) // ---------------------------------------------------------------- // Assemble the two-letter abbreviations, and load them into the // string array. If one letter is enough to uniquely identify a day // of the week, confine the abbreviation to the initial letter. If // a second letter is required, append the second character of the // weekday name. // ---------------------------------------------------------------- intDayIndex = ArrayInfo.ARRAY_INVALID_INDEX; // Reset. foreach ( string strWeekdayName in astrAbbrWdayNames ) { char chrFirstLetter = achrFirstLetter [ ++intDayIndex ]; if ( dctTimesUsed [ chrFirstLetter ] == ONE_LETTER ) { // Letter is used once only, so it uniquely identifies the weekday. RSD_WEEKDAY_2LTRS [ intDayIndex ] = chrFirstLetter.ToString ( ); } // TRUE block, if ( dctTimesUsed [ chrFirstLetter ] == ONE_LETTER ) else { // Letter is used more than once. Get the second letter. char [ ] achrSecondLetter = strWeekdayName.ToCharArray ( SECOND_LETTER_INDEX , ONE_LETTER ); RSD_WEEKDAY_2LTRS [ intDayIndex ] = string.Format ( TWO_LETTERS , chrFirstLetter , achrSecondLetter [ ArrayInfo.ARRAY_FIRST_ELEMENT ] ); } // FALSE block, if ( dctTimesUsed [ chrFirstLetter ] == ONE_LETTER ) } // foreach ( string strWeekdayName in astrAbbrWdayNames ) } // static SysDateFormatters constructor #endregion // The static constructor initializes the two-letter weekday table based on the current UI culture. #region Public static methods are the reason this class exists. /// <summary> /// This method has a nearly exact analogue in the constellations of WIL /// User Defined Functions that gave rise to its immediate predecessor, /// a like named function implemented in straight C, with a little help /// from the Windows National Language Subsystem, which underlies the /// CultureInfo class. /// </summary> /// <param name="pstrFormat"> /// This System.String is a combination of tokens and literal text that /// governs the formatting of the date. /// </param> /// <returns> /// The return value is a string containing the current date and time, /// formatted according to the rules spelled out in format string /// pstrFormat. /// </returns> public static string ReformatNow ( string pstrFormat ) { return ReformatSysDate ( DateTime.Now , pstrFormat ); } /// <summary> /// In the original constellation of WinBatch functions and their C /// descendants, this function took the form of an optional argument to /// ReformatNow. I think I prefer this way. /// </summary> /// <param name="pstrFormat"> /// This System.String is a combination of tokens and literal text that /// governs the formatting of the date. /// </param> /// <returns> /// The return value is a string containing the current UTC time, /// formatted according to the rules spelled out in format string /// pstrFormat. /// </returns> public static string ReformatUtcNow ( string pstrFormat ) { return ReformatSysDate ( DateTime.UtcNow , pstrFormat ); } /// <summary> /// ReformatSysDate is the core function of the constellation of /// routines that grew from the original WIL script. Substitution tokens /// drive construction of a formatted date string. /// </summary> /// <param name="pdtm"> /// This System.DateTime is the time to be formatted. /// </param> /// <param name="pstrFormat"> /// This System.String is a combination of tokens and literal text that /// governs the formatting of the date. /// </param> /// <returns> /// The return value is a string containing the date and/or time in /// argument pdtm, formatted according to the rules spelled out in /// format string pstrFormat. /// </returns> public static string ReformatSysDate ( DateTime pdtm , string pstrFormat ) { const string ARG_PDTM = @"pdtm"; const string ARG_PSTRFORMAT = @"pstrFormat"; const string ERRMSG_INTERNAL_ERROR_UNSUPP_ALG = @"An internal error has been detected in routine ReformatSysDate.{2}An unexpected FormattingAlgorithm of {0} has been encountered while processing the following input string:{2}{1}"; if ( pdtm == null ) throw new ArgumentNullException ( ARG_PDTM , Properties.Resources.ERRMSG_ARG_IS_NULL ); if ( string.IsNullOrEmpty ( pstrFormat ) ) throw new ArgumentException ( Properties.Resources.ERRMSG_ARG_IS_NULL_OR_EMPTY , ARG_PSTRFORMAT ); StringBuilder rsbFormattedDate = new StringBuilder ( pstrFormat , EstimateFinalLength ( ref pstrFormat ) ); for ( int intCurrToken = ArrayInfo.ARRAY_FIRST_ELEMENT ; intCurrToken < _intNDefinedTokens ; intCurrToken++ ) { // Unless a token appears in the format string, everything inside the switch block, and the switch, itself, is wasted effort. if ( pstrFormat.IndexOf ( RSD_TOKENS [ intCurrToken ] ) > ArrayInfo.ARRAY_INVALID_INDEX ) { // This token is used. switch ( RSD_ALGORITHM [ intCurrToken ] ) { case FormattingAlgorithm.ApplyFormatToDateTime: { // In order to reuse the name, strValue must be confined in a closure. string strValue = pdtm.ToString ( RSD_BCL_FORMATS [ intCurrToken ] ); rsbFormattedDate.Replace ( RSD_TOKENS [ intCurrToken ] , strValue ); } // The string, strValue goes out of scope. break; case FormattingAlgorithm.TwoLetterWeekday: { // In order to reuse the name, strValue must be confined in a block. string strValue = RSD_WEEKDAY_2LTRS [ ( int ) pdtm.DayOfWeek ]; rsbFormattedDate.Replace ( RSD_TOKENS [ intCurrToken ] , strValue ); } // The string, strValue goes out of scope. break; default: string strMsg = string.Format ( ERRMSG_INTERNAL_ERROR_UNSUPP_ALG , // Format string ( int ) RSD_ALGORITHM [ intCurrToken ] , // Token 0 pstrFormat , // Token 1 Environment.NewLine ); // Token 2 throw new Exception ( strMsg ); } // switch ( RSD_ALGORITHM [ intCurrToken ] ) } // if ( pstrFormat.IndexOf ( RSD_TOKENS [ intCurrToken ] ) > ArrayInfo.ARRAY_INVALID_INDEX ) } // for (int intCurrToken=ArrayInfo.ARRAY_FIRST_ELEMENT;intCurrToken<_intNDefinedTokens;intCurrToken++) return rsbFormattedDate.ToString ( ); } // ReformatSysDate #endregion // Public static methods are the reason this class exists. #region Private methods simplify the public methods. private static int EstimateFinalLength ( ref string pstrFormat ) { return pstrFormat.Length * 2; } // private static int EstimateFinalLength #endregion // Private methods simplify the public methods. } // public class SysDateFormatters } // partial namespace WizardWrx.DLLServices2
46.792732
242
0.557109
[ "BSD-3-Clause" ]
txwizard/DLLServices2
DLLServices2/SysDateFormatters.cs
34,769
C#
namespace PatniListi.Services.Data { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using PatniListi.Data.Common.Repositories; using PatniListi.Data.Models; using PatniListi.Data.Models.Enums; using PatniListi.Services.Mapping; public class CarsService : ICarsService { private readonly IDeletableEntityRepository<Car> carsRepository; public CarsService(IDeletableEntityRepository<Car> carsRepository) { this.carsRepository = carsRepository; } public async Task<Car> CreateAsync(string model, string licensePlate, string fuelType, double startKilometers, int averageConsumption, int tankCapacity, double initialFuel, string companyId) { var car = new Car { Model = model, LicensePlate = licensePlate, FuelType = (Fuel)Enum.Parse(typeof(Fuel), fuelType), StartKilometers = startKilometers, AverageConsumption = averageConsumption, TankCapacity = tankCapacity, InitialFuel = initialFuel, CompanyId = companyId, }; await this.carsRepository.AddAsync(car); await this.carsRepository.SaveChangesAsync(); return car; } public async Task<bool> DeleteAsync(string id, string companyId) { var car = await this.carsRepository .All() .Where(c => c.Id == id && c.CompanyId == companyId) .FirstOrDefaultAsync(); if (car == null) { return false; } this.carsRepository.Delete(car); await this.carsRepository.SaveChangesAsync(); return true; } public async Task EditAsync(string id, string model, string licensePlate, string fuelType, double startKilometers, int averageConsumption, int tankCapacity, double initialFuel, string companyId, DateTime createdOn, string modifiedBy, string fullName) { var car = this.GetById(id); car.Model = model; car.LicensePlate = licensePlate; car.FuelType = (Fuel)Enum.Parse(typeof(Fuel), fuelType); car.StartKilometers = startKilometers; car.AverageConsumption = averageConsumption; car.TankCapacity = tankCapacity; car.InitialFuel = initialFuel; car.CompanyId = companyId; car.CreatedOn = createdOn; car.ModifiedBy = modifiedBy; this.carsRepository.Update(car); await this.carsRepository.SaveChangesAsync(); } public IQueryable<T> GetAll<T>(string companyId) { return this.carsRepository .AllAsNoTracking() .Where(c => c.CompanyId == companyId) .OrderBy(c => c.Model) .To<T>(); } public IQueryable<T> GetCarsByUser<T>(string userId, string companyId) { return this.carsRepository .AllAsNoTracking() .OrderBy(c => c.Model) .Where(c => c.CompanyId == companyId && c.CarUsers.Any(cu => cu.UserId == userId)) .To<T>(); } public IEnumerable<SelectListItem> GetAll(string companyId) { return this.carsRepository .AllAsNoTracking() .Where(c => c.CompanyId == companyId) .OrderBy(c => c.Model) .Select(c => new SelectListItem { Value = c.Id, Text = $"{c.Model} - {c.LicensePlate}", }) .ToList(); } public IEnumerable<SelectListItem> GetAllCarsByUserId(string userId, string companyId) { var cars = this.carsRepository .AllAsNoTracking() .Where(c => c.CompanyId == companyId && c.CarUsers.Any(cu => cu.UserId == userId)) .OrderBy(c => c.Model) .Select(cu => new SelectListItem { Value = cu.Id, Text = cu.Model, }) .ToList(); return cars; } public double GetCurrentLitresByCarId(string id) { var litres = this.carsRepository .AllAsNoTracking() .Where(c => c.Id == id) .Select(i => i.Invoices.Sum(i => i.Quantity)) .SingleOrDefault(); return litres; } public double GetCurrentTravelledDistanceByCarId(string carId, string transportWorkTicketId = null) { var travelledDistance = 0.00; if (transportWorkTicketId != null) { travelledDistance = this.carsRepository .AllAsNoTracking() .Where(c => c.Id == carId) .Select(i => i.TransportWorkTickets.Where(tr => tr.Id != transportWorkTicketId).Sum(i => i.TravelledDistance)) .SingleOrDefault(); } else { travelledDistance = this.carsRepository .AllAsNoTracking() .Where(c => c.Id == carId) .Select(i => i.TransportWorkTickets.Sum(i => i.TravelledDistance)) .SingleOrDefault(); } return travelledDistance; } public double GetCurrentFuelConsumptionByCarId(string carId, string transportWorkTicketId = null) { var fuelConsumption = 0.00; if (transportWorkTicketId != null) { fuelConsumption = this.carsRepository .AllAsNoTracking() .Where(c => c.Id == carId) .Select(i => i.TransportWorkTickets.Where(tr => tr.Id != transportWorkTicketId).Sum(i => i.FuelConsumption)) .SingleOrDefault(); } else { fuelConsumption = this.carsRepository .AllAsNoTracking() .Where(c => c.Id == carId) .Select(i => i.TransportWorkTickets.Sum(i => i.FuelConsumption)) .SingleOrDefault(); } return fuelConsumption; } public async Task<T> GetDetailsAsync<T>(string id) { var viewModel = await this.carsRepository .AllAsNoTracking() .Include(c => c.CarUsers) .Where(c => c.Id == id) .To<T>() .SingleOrDefaultAsync(); return viewModel; } public IEnumerable<SelectListItem> GetFuelType() { return new List<SelectListItem> { new SelectListItem { Value = "Бензин", Text = "Бензин" }, new SelectListItem { Value = "Дизел", Text = "Дизел" }, new SelectListItem { Value = "Газ", Text = "Газ" }, }; } public bool IsLicensePlateExist(string licensePlate) { var exists = this.carsRepository .AllAsNoTrackingWithDeleted() .Any(c => c.LicensePlate == licensePlate); if (exists) { return true; } return false; } public string GetLicensePlateById(string id) { return this.carsRepository .AllAsNoTracking() .Where(c => c.Id == id) .Select(c => c.LicensePlate) .SingleOrDefault(); } public Car GetById(string id) { return this.carsRepository .AllAsNoTracking() .FirstOrDefault(c => c.Id == id); } } }
34.380165
258
0.505649
[ "MIT" ]
deedeedextor/PatniListi
Services/PatniListi.Services.Data/CarsService.cs
8,350
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using System.Text.Json; using System.Text.Json.Serialization; using Azure.Core; namespace Azure.Analytics.Synapse.Artifacts.Models { [JsonConverter(typeof(SapOpenHubLinkedServiceConverter))] public partial class SapOpenHubLinkedService : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("type"); writer.WriteStringValue(Type); if (Optional.IsDefined(ConnectVia)) { writer.WritePropertyName("connectVia"); writer.WriteObjectValue(ConnectVia); } if (Optional.IsDefined(Description)) { writer.WritePropertyName("description"); writer.WriteStringValue(Description); } if (Optional.IsCollectionDefined(Parameters)) { writer.WritePropertyName("parameters"); writer.WriteStartObject(); foreach (var item in Parameters) { writer.WritePropertyName(item.Key); writer.WriteObjectValue(item.Value); } writer.WriteEndObject(); } if (Optional.IsCollectionDefined(Annotations)) { writer.WritePropertyName("annotations"); writer.WriteStartArray(); foreach (var item in Annotations) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } writer.WritePropertyName("typeProperties"); writer.WriteStartObject(); writer.WritePropertyName("server"); writer.WriteObjectValue(Server); writer.WritePropertyName("systemNumber"); writer.WriteObjectValue(SystemNumber); writer.WritePropertyName("clientId"); writer.WriteObjectValue(ClientId); if (Optional.IsDefined(Language)) { writer.WritePropertyName("language"); writer.WriteObjectValue(Language); } if (Optional.IsDefined(SystemId)) { writer.WritePropertyName("systemId"); writer.WriteObjectValue(SystemId); } if (Optional.IsDefined(UserName)) { writer.WritePropertyName("userName"); writer.WriteObjectValue(UserName); } if (Optional.IsDefined(Password)) { writer.WritePropertyName("password"); writer.WriteObjectValue(Password); } if (Optional.IsDefined(MessageServer)) { writer.WritePropertyName("messageServer"); writer.WriteObjectValue(MessageServer); } if (Optional.IsDefined(MessageServerService)) { writer.WritePropertyName("messageServerService"); writer.WriteObjectValue(MessageServerService); } if (Optional.IsDefined(LogonGroup)) { writer.WritePropertyName("logonGroup"); writer.WriteObjectValue(LogonGroup); } if (Optional.IsDefined(EncryptedCredential)) { writer.WritePropertyName("encryptedCredential"); writer.WriteObjectValue(EncryptedCredential); } writer.WriteEndObject(); foreach (var item in AdditionalProperties) { writer.WritePropertyName(item.Key); writer.WriteObjectValue(item.Value); } writer.WriteEndObject(); } internal static SapOpenHubLinkedService DeserializeSapOpenHubLinkedService(JsonElement element) { string type = default; Optional<IntegrationRuntimeReference> connectVia = default; Optional<string> description = default; Optional<IDictionary<string, ParameterSpecification>> parameters = default; Optional<IList<object>> annotations = default; object server = default; object systemNumber = default; object clientId = default; Optional<object> language = default; Optional<object> systemId = default; Optional<object> userName = default; Optional<SecretBase> password = default; Optional<object> messageServer = default; Optional<object> messageServerService = default; Optional<object> logonGroup = default; Optional<object> encryptedCredential = default; IDictionary<string, object> additionalProperties = default; Dictionary<string, object> additionalPropertiesDictionary = new Dictionary<string, object>(); foreach (var property in element.EnumerateObject()) { if (property.NameEquals("type")) { type = property.Value.GetString(); continue; } if (property.NameEquals("connectVia")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } connectVia = IntegrationRuntimeReference.DeserializeIntegrationRuntimeReference(property.Value); continue; } if (property.NameEquals("description")) { description = property.Value.GetString(); continue; } if (property.NameEquals("parameters")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } Dictionary<string, ParameterSpecification> dictionary = new Dictionary<string, ParameterSpecification>(); foreach (var property0 in property.Value.EnumerateObject()) { dictionary.Add(property0.Name, ParameterSpecification.DeserializeParameterSpecification(property0.Value)); } parameters = dictionary; continue; } if (property.NameEquals("annotations")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List<object> array = new List<object>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(item.GetObject()); } annotations = array; continue; } if (property.NameEquals("typeProperties")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } foreach (var property0 in property.Value.EnumerateObject()) { if (property0.NameEquals("server")) { server = property0.Value.GetObject(); continue; } if (property0.NameEquals("systemNumber")) { systemNumber = property0.Value.GetObject(); continue; } if (property0.NameEquals("clientId")) { clientId = property0.Value.GetObject(); continue; } if (property0.NameEquals("language")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } language = property0.Value.GetObject(); continue; } if (property0.NameEquals("systemId")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } systemId = property0.Value.GetObject(); continue; } if (property0.NameEquals("userName")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } userName = property0.Value.GetObject(); continue; } if (property0.NameEquals("password")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } password = SecretBase.DeserializeSecretBase(property0.Value); continue; } if (property0.NameEquals("messageServer")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } messageServer = property0.Value.GetObject(); continue; } if (property0.NameEquals("messageServerService")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } messageServerService = property0.Value.GetObject(); continue; } if (property0.NameEquals("logonGroup")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } logonGroup = property0.Value.GetObject(); continue; } if (property0.NameEquals("encryptedCredential")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } encryptedCredential = property0.Value.GetObject(); continue; } } continue; } additionalPropertiesDictionary.Add(property.Name, property.Value.GetObject()); } additionalProperties = additionalPropertiesDictionary; return new SapOpenHubLinkedService(type, connectVia.Value, description.Value, Optional.ToDictionary(parameters), Optional.ToList(annotations), additionalProperties, server, systemNumber, clientId, language.Value, systemId.Value, userName.Value, password.Value, messageServer.Value, messageServerService.Value, logonGroup.Value, encryptedCredential.Value); } internal partial class SapOpenHubLinkedServiceConverter : JsonConverter<SapOpenHubLinkedService> { public override void Write(Utf8JsonWriter writer, SapOpenHubLinkedService model, JsonSerializerOptions options) { writer.WriteObjectValue(model); } public override SapOpenHubLinkedService Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using var document = JsonDocument.ParseValue(ref reader); return DeserializeSapOpenHubLinkedService(document.RootElement); } } } }
43.935691
367
0.47885
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/SapOpenHubLinkedService.Serialization.cs
13,664
C#
/* * Copyright 2018 JDCLOUD.COM * * 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. * * Live-Video * 直播管理API * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ using System; using System.Collections.Generic; using System.Text; using JDCloudSDK.Core.Service; using JDCloudSDK.Core.Annotation; namespace JDCloudSDK.Live.Apis { /// <summary> /// 关闭回看 /// </summary> public class CloseLiveRestartRequest : JdcloudRequest { ///<summary> /// 回看的播放域名 ///Required:true ///</summary> [Required] public string RestartDomain{ get; set; } } }
24.916667
76
0.68311
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Live/Apis/CloseLiveRestartRequest.cs
1,226
C#
using System.Collections.Generic; using System.Windows.Media; namespace HandyControl.Tools.Extension; /// <summary> /// Color extension class /// </summary> public static class ColorExtension { /// <summary> /// Convert color to decimal representation (rgb order is reversed) /// </summary> /// <param name="color"></param> /// <returns></returns> public static int ToInt32(this Color color) => color.R << 16 | color.G << 8 | color.B; /// <summary> /// Convert color to decimal representation (rgb order is reversed) /// </summary> /// <param name="color"></param> /// <returns></returns> public static int ToInt32Reverse(this Color color) => color.R | color.G << 8 | color.B << 18; internal static List<byte> ToList(this Color color) => new() { color.R, color.G, color.B }; }
26.636364
97
0.608646
[ "MIT" ]
Muzsor/HandyControls
src/Shared/HandyControl_Shared/Tools/Extension/ColorExtension.cs
881
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.Linq.Expressions; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace ExpressionEvaluator.Transformer { public class CastExpressionTransformer : IExpressionTransformer<Expression, CastExpressionSyntax> { public static CastExpressionTransformer INSTANCE = new CastExpressionTransformer(); public Expression ToExpression(Context context, CastExpressionSyntax castExpSyntax) { Type type = context.ExportedTypes().FirstOrDefault(v => v.Name == castExpSyntax.Type.ToString()); if (type == null) { type = Type.GetType(castExpSyntax.Type.ToString()); } return Expression.Convert(ExpressionFactory.ToExpression(context, castExpSyntax.Expression), type); } } }
39.414634
111
0.731436
[ "Apache-2.0" ]
sriksun/ExpressionEvaluator
ExpressionEvaluator/Transformer/CastExpressionTransformer.cs
1,618
C#
namespace System.Net.Http { public sealed class HttpListenerResponseHeaders : HttpListenerHeaders { private HttpListenerHeaderValueCollection<string> contentEncoding; private Uri location; public HttpListenerResponseHeaders(HttpListenerResponse response) { Response = response; } public Uri Location { get { if (location == null) { string locationString; if (TryGetValue("Location", out locationString)) { location = new Uri(locationString); } } return location; } set { if (!value.Equals(location)) { location = value; if (location == null) return; this["Location"] = location.ToString(); } } } #region Content Headers public HttpListenerHeaderValueCollection<string> ContentEncoding => contentEncoding ?? (contentEncoding = new HttpListenerHeaderValueCollection<string>(this, "Content-Encoding")); internal HttpListenerResponse Response { get; set; } #endregion } }
28.479167
187
0.498903
[ "Unlicense" ]
sassembla/LocalHttpFileServer
HttpListener/System.Net.Http.HttpListener/HttpListenerResponseHeaders.cs
1,369
C#
namespace Dadata { public class ProfileClient : ProfileClientSync { public ProfileClient(string token, string secret, string baseUrl = BASE_URL) : base(token, secret, baseUrl) { } } }
25.625
119
0.687805
[ "MIT" ]
AristarkhLetskin/dadata-csharp
Dadata/ProfileClient.cs
207
C#
using System; using Thuria.Helium.Core; namespace Thuria.Helium.Akka.Messages { /// <summary> /// Helium Execute SQL Query Message /// </summary> public class HeliumExecuteSqlQueryMessage : HeliumStatefulMessage { /// <summary> /// Helium Execute SQL Query Message Constructor /// </summary> /// <param name="dbContextName">Database Context Name</param> /// <param name="heliumAction">Helium Action</param> /// <param name="sqlQuery">SQL Query to be executed</param> public HeliumExecuteSqlQueryMessage(string dbContextName, HeliumAction heliumAction, string sqlQuery) { if (string.IsNullOrWhiteSpace(dbContextName)) { throw new ArgumentNullException(nameof(dbContextName)); } if (string.IsNullOrWhiteSpace(sqlQuery)) { throw new ArgumentNullException(nameof(sqlQuery)); } DatabaseContextName = dbContextName; HeliumAction = heliumAction; SqlQuery = sqlQuery; } /// <summary> /// Database Context Name /// </summary> public string DatabaseContextName { get; } /// <summary> /// Helium Action /// </summary> public HeliumAction HeliumAction { get; } /// <summary> /// SQL Query to be executed /// </summary> public string SqlQuery { get; } } }
30.069767
111
0.662026
[ "Apache-2.0" ]
DracoRSA/Thuria.Helium
src/Thuria.Helium.Akka/Messages/HeliumExecuteSqlQueryMessage.cs
1,295
C#
/* * eZmax API Definition (Full) * * This API expose all the functionnalities for the eZmax and eZsign applications. * * The version of the OpenAPI document: 1.1.7 * Contact: support-api@ezmax.ca * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using RestSharp; using Xunit; using eZmaxApi.Client; using eZmaxApi.Api; // uncomment below to import models //using eZmaxApi.Model; namespace eZmaxApi.Test.Api { /// <summary> /// Class for testing ObjectEzsigntemplatepackagesignerApi /// </summary> /// <remarks> /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the API endpoint. /// </remarks> public class ObjectEzsigntemplatepackagesignerApiTests : IDisposable { private ObjectEzsigntemplatepackagesignerApi instance; public ObjectEzsigntemplatepackagesignerApiTests() { instance = new ObjectEzsigntemplatepackagesignerApi(); } public void Dispose() { // Cleanup when everything is done. } /// <summary> /// Test an instance of ObjectEzsigntemplatepackagesignerApi /// </summary> [Fact] public void InstanceTest() { // TODO uncomment below to test 'IsType' ObjectEzsigntemplatepackagesignerApi //Assert.IsType<ObjectEzsigntemplatepackagesignerApi>(instance); } /// <summary> /// Test EzsigntemplatepackagesignerCreateObjectV1 /// </summary> [Fact] public void EzsigntemplatepackagesignerCreateObjectV1Test() { // TODO uncomment below to test the method and replace null with proper value //EzsigntemplatepackagesignerCreateObjectV1Request ezsigntemplatepackagesignerCreateObjectV1Request = null; //var response = instance.EzsigntemplatepackagesignerCreateObjectV1(ezsigntemplatepackagesignerCreateObjectV1Request); //Assert.IsType<EzsigntemplatepackagesignerCreateObjectV1Response>(response); } /// <summary> /// Test EzsigntemplatepackagesignerDeleteObjectV1 /// </summary> [Fact] public void EzsigntemplatepackagesignerDeleteObjectV1Test() { // TODO uncomment below to test the method and replace null with proper value //int pkiEzsigntemplatepackagesignerID = null; //var response = instance.EzsigntemplatepackagesignerDeleteObjectV1(pkiEzsigntemplatepackagesignerID); //Assert.IsType<EzsigntemplatepackagesignerDeleteObjectV1Response>(response); } /// <summary> /// Test EzsigntemplatepackagesignerEditObjectV1 /// </summary> [Fact] public void EzsigntemplatepackagesignerEditObjectV1Test() { // TODO uncomment below to test the method and replace null with proper value //int pkiEzsigntemplatepackagesignerID = null; //EzsigntemplatepackagesignerEditObjectV1Request ezsigntemplatepackagesignerEditObjectV1Request = null; //var response = instance.EzsigntemplatepackagesignerEditObjectV1(pkiEzsigntemplatepackagesignerID, ezsigntemplatepackagesignerEditObjectV1Request); //Assert.IsType<EzsigntemplatepackagesignerEditObjectV1Response>(response); } /// <summary> /// Test EzsigntemplatepackagesignerGetObjectV1 /// </summary> [Fact] public void EzsigntemplatepackagesignerGetObjectV1Test() { // TODO uncomment below to test the method and replace null with proper value //int pkiEzsigntemplatepackagesignerID = null; //var response = instance.EzsigntemplatepackagesignerGetObjectV1(pkiEzsigntemplatepackagesignerID); //Assert.IsType<EzsigntemplatepackagesignerGetObjectV1Response>(response); } } }
38.083333
160
0.690494
[ "MIT" ]
ezmaxinc/eZmax-SDK-csharp-netcore
src/eZmaxApi.Test/Api/ObjectEzsigntemplatepackagesignerApiTests.cs
4,113
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using VRTK; public class ControllerHaptics : MonoBehaviour { public GameObject LeftController; public GameObject RightController; public float strength = 0.5f; public float duration = 1f; public float pulseInterval = 0.2f; private bool isVibrating = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void VibrateControllers() { if (isVibrating) return; Debug.Log("Vibrating..."); isVibrating = true; StartCoroutine(KeepVibrating()); } public void CancelControllerVibrations() { Debug.Log("Vibration cancelled"); VRTK_ControllerHaptics.CancelHapticPulse(VRTK_ControllerReference.GetControllerReference(LeftController)); VRTK_ControllerHaptics.CancelHapticPulse(VRTK_ControllerReference.GetControllerReference(RightController)); isVibrating = false; } IEnumerator KeepVibrating() { while (isVibrating) { VRTK_ControllerHaptics.TriggerHapticPulse(VRTK_ControllerReference.GetControllerReference(LeftController), strength, duration, pulseInterval); VRTK_ControllerHaptics.TriggerHapticPulse(VRTK_ControllerReference.GetControllerReference(RightController), strength, duration, pulseInterval); yield return new WaitForSeconds(duration); } } }
28
155
0.715633
[ "MIT" ]
Vytek/EveryDayIsHalloween
Assets/Scripts/ControllerHaptics.cs
1,486
C#
// !! FChecksum: 0C4A49E6DAF084B90DB86D1713572953E54EA612726E9C57035FC4A86045F6F292AC41474D7D19E9DCEA5C5CCCE0223FDF65F95BCBA3D646DDC42CDE4DA77ED7 //Official Location: https://github.com/andreboe/PubCode/blob/main/PubCode.Robocopy_v1.cs //DO NOT MODIFY. THIS FILE IS FROZEN. IF NEED BE, A NEW STANDALONE VERSION WILL BE ISSUED. ////////////////////////////////////////////////////////////////////////////////////////// //ALL USAGE OF THIS FILE IN PROJECTS SHALL BE DONE BY LINKING THE FILE. NOT COPYING IT. ////////////////////////////////////////////////////////////////////////////////////////// #region License; This is free and unencumbered software released into the public domain. /// This is free and unencumbered software released into the public domain. /// /// Anyone is free to copy, modify, publish, use, compile, sell, or /// distribute this software, either in source code form or as a compiled /// binary, for any purpose, commercial or non-commercial, and by any /// means. /// /// In jurisdictions that recognize copyright laws, the author or authors /// of this software dedicate any and all copyright interest in the /// software to the public domain. We make this dedication for the benefit /// of the public at large and to the detriment of our heirs and /// successors. We intend this dedication to be an overt act of /// relinquishment in perpetuity of all present and future rights to this /// software under copyright law. /// /// 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 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. /// /// For more information, please refer to <https://unlicense.org/> #endregion using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace PubCode.Robocopy_v1 //v2021.4.20.1 { public static class Robocopy { public static void MIR(string param_ReInit_FROM, string param_ReInit_TO, bool pressEnterToContineBeforeDisplayingResults, string errorCrumb = "") { errorCrumb += "|Robocopy.PubCode.Robocopy_v1.cs~MIR"; try { var unixTimeNow = (int)(DateTime.UtcNow - DateTime.Parse("1970-01-01")).TotalSeconds; var logfilePath = Path.Combine(Path.GetTempPath(), $"zRobocopy.PubCode.Robocopy_v1.MIR.{unixTimeNow}.{RandomNumber(1000, 9999)}.log"); if (File.Exists(logfilePath)) File.Delete(logfilePath); string prmOutput_OutputString = ""; string prmOutput_ErrorString = ""; string statusText = null; string errorText = null; try { RoboCopy_Mirror(param_ReInit_FROM, param_ReInit_TO, out prmOutput_OutputString, out prmOutput_ErrorString, out statusText, out errorText, logfilePath, errorCrumb); } catch (Exception ex) { throw new Exception($"FAILURE/ERROR; ###errorCrumb:[[{errorCrumb}]]###; MIR({param_ReInit_FROM}, {param_ReInit_TO}, {pressEnterToContineBeforeDisplayingResults})", ex); } string logfileContents = null; if (File.Exists(logfilePath)) { logfileContents = System.IO.File.ReadAllText(logfilePath); File.Delete(logfilePath); } if (pressEnterToContineBeforeDisplayingResults) { Console.WriteLine("Press [Enter] to continue"); Console.ReadLine(); } Console.WriteLine($"statusText: \r\n{new string('-', 50)}\r\n{statusText ?? "null"}\r\n\r\n"); Console.WriteLine($"errorText: \r\n{new string('-', 50)}\r\n{errorText ?? "null"}\r\n\r\n"); Console.WriteLine($"prmOutput_OutputString: \r\n{new string('-', 50)}\r\n{prmOutput_OutputString ?? "null"}\r\n\r\n"); Console.WriteLine($"prmOutput_ErrorString: \r\n{new string('-', 50)}\r\n{prmOutput_ErrorString ?? "null"}\r\n\r\n"); Console.WriteLine($"logfileContents: \r\n{new string('-', 50)}\r\n{logfileContents ?? "null"}\r\n\r\n"); } catch (Exception ex) { Console.Error.WriteLine($"{ex}"); } } private static void RoboCopy_Mirror(string from_folder, string to_folder, out string prmOutput_OutputString, out string prmOutput_ErrorString, out string statusText, out string errorText, string logfilePath, string errorCrumb) { errorCrumb += "|Robocopy.PubCode.Robocopy_v1.cs~RoboCopy_Mirror"; Validate_parameters_and_throw_Exception_if_not_valid_for_Robocopy_mirror_command(from_folder, to_folder, errorCrumb); var RobocopyLog_FileNm = logfilePath; // Path.Combine(Path.GetTempPath(), logfileName); var RoboCopyArgs = BuildRoboCopyArgString____thisRunsInsideAProcess(from_folder, to_folder, RobocopyLog_FileNm); // http://net-informations.com/q/mis/robocopy.html int ExitCode = 0; try { ExitCode = RunProccess("robocopy.exe", RoboCopyArgs, out prmOutput_OutputString, out prmOutput_ErrorString, null, errorCrumb); } catch (Exception ex) { throw new Exception($"FAILURE/ERROR; ###errorCrumb:[[{errorCrumb}]]###; RoboCopy_Mirror({from_folder}, {to_folder}, out prmOutput_OutputString, out prmOutput_ErrorString, out statusText, out errorText, out logfilePath)", ex); } // Process our return codes var switchExpr = ExitCode; statusText = null; errorText = null; switch (switchExpr) { case 0: // Nothing to copy { statusText = $" No Files Deployed. ExitCode: ({ExitCode}) - See Robocopy logs"; break; } case 1: // Things copied successfully { statusText = $" File Deployed. ExitCode: ({ExitCode}) - See Robocopy logs"; break; } case 2: // Some Extra files or directories were detected. No files were copied Examine the output log for details. { statusText = $" Some Extra files or directories were detected. No files were copied. ExitCode: ({ExitCode}) - See Robocopy logs"; break; } case 3: // (2+1) Some files were copied. Additional files were present. No failure was encountered. { statusText = $" Some files were copied. Additional files were present. No failure was encountered. ExitCode: ({ExitCode}) - See Robocopy logs"; // Oops! there was an issue break; } default: { errorText = $"[ERROR] There was an error copying files. See Robocopy logs. Exit Code ({ExitCode}"; break; } } if (prmOutput_OutputString != null) { while (true) { if (true && !prmOutput_OutputString.StartsWith("\r") && !prmOutput_OutputString.StartsWith("\n") && !prmOutput_OutputString.StartsWith("\t") && !prmOutput_OutputString.StartsWith(" ") && true) break; if (prmOutput_OutputString.StartsWith("\r")) prmOutput_OutputString = prmOutput_OutputString.Substring(1); if (prmOutput_OutputString.StartsWith("\n")) prmOutput_OutputString = prmOutput_OutputString.Substring(1); if (prmOutput_OutputString.StartsWith("\t")) prmOutput_OutputString = prmOutput_OutputString.Substring(1); if (prmOutput_OutputString.StartsWith(" ")) prmOutput_OutputString = prmOutput_OutputString.Substring(1); } } if (string.IsNullOrWhiteSpace(statusText)) statusText = null; if (string.IsNullOrWhiteSpace(errorText)) errorText = null; if (string.IsNullOrWhiteSpace(prmOutput_OutputString)) prmOutput_OutputString = null; if (string.IsNullOrWhiteSpace(prmOutput_ErrorString)) prmOutput_ErrorString = null; } private static int RunProccess(string prmProcessName, string prmArguments, out string prmOutput_OutputString, out string prmOutput_ErrorString, string prmWorkingDirectory, string errorCrumb) { errorCrumb += "|Robocopy.PubCode.Robocopy_v1.cs~Validate_parameters_and_throw_Exception_if_not_valid_for_Robocopy_mirror_command"; Console.WriteLine($"Process.Run: \"{prmProcessName}\" {prmArguments}"); prmOutput_OutputString = ""; prmOutput_ErrorString = ""; string retValue = string.Empty; string OutputString; string ErrorString; int ExitCode; try { using (var myProcess = new Process()) { // Setup the command ProcessStartInfo startInfo; startInfo = new ProcessStartInfo() { FileName = prmProcessName, WindowStyle = ProcessWindowStyle.Hidden, Arguments = prmArguments, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; if (prmWorkingDirectory != null) { startInfo.WorkingDirectory = prmWorkingDirectory; } myProcess.StartInfo = startInfo; myProcess.Start(); OutputString = myProcess.StandardOutput.ReadToEnd(); ErrorString = myProcess.StandardError.ReadToEnd(); myProcess.WaitForExit(); ExitCode = myProcess.ExitCode; myProcess.Close(); } prmOutput_OutputString = OutputString; prmOutput_ErrorString = ErrorString; } catch (Exception ex) { throw new Exception($"FAILURE/ERROR; ###errorCrumb:[[{errorCrumb}]]###; RunProccess(\"{prmProcessName ?? "(null)"}\", \"{prmArguments ?? "(null)"}\", \"{prmOutput_OutputString ?? "(null)"}\", \"{prmOutput_ErrorString ?? "(null)"}\", \"{prmWorkingDirectory??"(null)"}\"), prmArguments={prmArguments}", ex); } return ExitCode; } private static string getOSInfo() { var os = Environment.OSVersion; var vs = os.Version; string operatingSystem = ""; if (os.Platform == PlatformID.Win32Windows) { var switchExpr = vs.Minor; switch (switchExpr) { case 0: { operatingSystem = "95"; break; } case 10: { if ((vs.Revision.ToString() ?? "") == "2222A") { operatingSystem = "98SE"; } else { operatingSystem = "98"; } break; } case 90: { operatingSystem = "Me"; break; } default: { break; } } } else if (os.Platform == PlatformID.Win32NT) { var switchExpr1 = vs.Major; switch (switchExpr1) { case 3: { operatingSystem = "NT 3.51"; break; } case 4: { operatingSystem = "NT 4.0"; break; } case 5: { if (vs.Minor == 0) { operatingSystem = "2000"; } else { operatingSystem = "XP"; } break; } case 6: { if (vs.Minor == 0) { operatingSystem = "Vista"; } else if (vs.Minor == 1) { operatingSystem = "7"; } else if (vs.Minor == 2) { operatingSystem = "8"; } else { operatingSystem = "8.1"; } break; } case 10: { operatingSystem = "10"; break; } default: { break; } } } if (!string.IsNullOrEmpty(operatingSystem)) { operatingSystem = "Windows " + operatingSystem; if (!string.IsNullOrEmpty(os.ServicePack)) { operatingSystem += " " + os.ServicePack; } } return operatingSystem; } private static bool os_is_Win7() { return getOSInfo().StartsWith("Windows 7"); } private static string BuildRoboCopyArgString____thisRunsInsideAProcess(string prmSourceFolder, string prmTargetFolder, string prmRobocopyLog) { var strBldr = new StringBuilder(); strBldr.Append($"\"{prmSourceFolder}\" \"{prmTargetFolder}\" "); strBldr.Append("/MIR /R:10 /NODCOPY /E "); if (os_is_Win7()) strBldr.Replace("/NODCOPY", ""); // This option is not compatible with Windows 7 strBldr.Append($"/LOG+:\"{prmRobocopyLog}\" "); return strBldr.ToString(); } private static void Validate_parameters_and_throw_Exception_if_not_valid_for_Robocopy_mirror_command(string from_folder, string to_folder, string errorCrumb) { errorCrumb += "|Robocopy.PubCode.Robocopy_v1.cs~Validate_parameters_and_throw_Exception_if_not_valid_for_Robocopy_mirror_command"; if (string.IsNullOrWhiteSpace(from_folder)) throw new Exception($"FAILURE/ERROR; ###errorCrumb:[[{errorCrumb}]]###; from_folder is empty string. RoboCopy_Mirror(\"{from_folder}\", \"{to_folder}\")"); if (string.IsNullOrWhiteSpace(to_folder)) throw new Exception($"FAILURE/ERROR; ###errorCrumb:[[{errorCrumb}]]###; to_folder is empty string. RoboCopy_Mirror(\"{from_folder}\", \"{to_folder}\")"); from_folder = from_folder.Trim(); to_folder = to_folder.Trim(); if (new char[] { '\\', '/' }.Contains(from_folder[from_folder.Length - 1])) throw new Exception($"FAILURE/ERROR; ###errorCrumb:[[{errorCrumb}]]###; from_folder are not allowed to end with a \"{from_folder[from_folder.Length - 1]}\" when used as a Robocopy mirror folder parameter. RoboCopy_Mirror(\"{from_folder}\", \"{to_folder}\")"); if (new char[] { '\\', '/' }.Contains(to_folder[to_folder.Length - 1])) throw new Exception($"FAILURE/ERROR; ###errorCrumb:[[{errorCrumb}]]###; to_folder are not allowed to end with a \"{to_folder[to_folder.Length - 1]}\" when used as a Robocopy mirror folder parameter. RoboCopy_Mirror(\"{from_folder}\", \"{to_folder}\")"); if (!Directory.Exists(from_folder)) throw new Exception($"FAILURE/ERROR; ###errorCrumb:[[{errorCrumb}]]###; from_folder does not exist. RoboCopy_Mirror(\"{from_folder}\", \"{to_folder}\")"); if (!Directory.Exists(to_folder)) throw new Exception($"FAILURE/ERROR; ###errorCrumb:[[{errorCrumb}]]###; to_folder does not exist. RoboCopy_Mirror(\"{from_folder}\", \"{to_folder}\")"); } // Instantiate random number generator. private static readonly Random _random = new Random(); // Generates a random number within a range. private static int RandomNumber(int min, int max) { return _random.Next(min, max); } } }
46.712121
322
0.500649
[ "Unlicense" ]
andreboe/PubCode
PubCode.Robocopy_v1.cs
18,498
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 13.05.2021. using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.LessThan.Complete.NullableTimeOnly.NullableTimeOnly{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Nullable<System.TimeOnly>; using T_DATA2 =System.Nullable<System.TimeOnly>; using T_DATA1_U=System.TimeOnly; using T_DATA2_U=System.TimeOnly; //////////////////////////////////////////////////////////////////////////////// //class TestSet_001__fields__01__VV public static class TestSet_001__fields__01__VV { private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2"; private const string c_NameOf__COL_DATA1 ="COL_TYPE_TIME"; private const string c_NameOf__COL_DATA2 ="COL2_TYPE_TIME"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA1)] public T_DATA1 COL_DATA1 { get; set; } [Column(c_NameOf__COL_DATA2)] public T_DATA2 COL_DATA2 { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 c_value1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1233)).Add(new System.TimeSpan(900)); T_DATA2 c_value2=new T_DATA2_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(0)); System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => (r.COL_DATA1 /*OP{*/ < /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N("t",c_NameOf__COL_DATA1).T(" < ").N("t",c_NameOf__COL_DATA2).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_001 //Helper methods -------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA1 valueForColData1, T_DATA2 valueForColData2) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_DATA1 =valueForColData1; newRecord.COL_DATA2 =valueForColData2; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet_001__fields__01__VV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.LessThan.Complete.NullableTimeOnly.NullableTimeOnly
31.225166
151
0.57667
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/LessThan/Complete/NullableTimeOnly/NullableTimeOnly/TestSet_001__fields__01__VV.cs
4,717
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RoadCollider : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
14.411765
43
0.702041
[ "MIT" ]
Benny93/TestRun
Assets/Scripts/Environment/RoadCollider.cs
247
C#
namespace Microsoft.Maui.Controls.PlatformConfiguration.AndroidSpecific { using FormsElement = Maui.Controls.Application; public enum WindowSoftInputModeAdjust { Pan, Resize, Unspecified } public static class Application { public static readonly BindableProperty WindowSoftInputModeAdjustProperty = BindableProperty.Create("WindowSoftInputModeAdjust", typeof(WindowSoftInputModeAdjust), typeof(Application), WindowSoftInputModeAdjust.Pan); public static WindowSoftInputModeAdjust GetWindowSoftInputModeAdjust(BindableObject element) { return (WindowSoftInputModeAdjust)element.GetValue(WindowSoftInputModeAdjustProperty); } public static void SetWindowSoftInputModeAdjust(BindableObject element, WindowSoftInputModeAdjust value) { element.SetValue(WindowSoftInputModeAdjustProperty, value); } public static WindowSoftInputModeAdjust GetWindowSoftInputModeAdjust(this IPlatformElementConfiguration<Android, FormsElement> config) { return GetWindowSoftInputModeAdjust(config.Element); } public static IPlatformElementConfiguration<Android, FormsElement> UseWindowSoftInputModeAdjust(this IPlatformElementConfiguration<Android, FormsElement> config, WindowSoftInputModeAdjust value) { SetWindowSoftInputModeAdjust(config.Element, value); return config; } } }
33.05
196
0.83056
[ "MIT" ]
3DSX/maui
src/Controls/src/Core/PlatformConfiguration/AndroidSpecific/Application.cs
1,322
C#
using System; using System.Collections.Generic; using System.Text; using Jeelu.SimplusD; namespace Jeelu.SimplusPagePreviewer { static public class ActiveTmpltAndSnip { static Dictionary<string, TmpltXmlDocument> _activeTmpltDictionary; static Dictionary<string, SnipXmlElement> _activeSnipDictionary; /// <summary> /// 获取已经运行过Tohtml的TmpltDoc实例,以便ToCSS的产生 /// </summary> static public Dictionary<string, TmpltXmlDocument> ActiveTmpltDictionary { get { return _activeTmpltDictionary; } } /// <summary> /// 获取已经运行过Tohtml的SnipEle实例,以便ToCSS的产生 /// </summary> static public Dictionary<string, SnipXmlElement> ActiveSnipDictionary { get { return _activeSnipDictionary; } } /// <summary> /// 将已经运行过Tohtml的TmpltDoc实例加入字典,以便ToCSS的产生 /// </summary> static public void AddTmpltDocIntoDictionary(TmpltXmlDocument tmpltDoc) { if (_activeTmpltDictionary == null) { _activeTmpltDictionary = new Dictionary<string, TmpltXmlDocument>(); _activeTmpltDictionary.Add(tmpltDoc.Id, tmpltDoc); } else { if (_activeTmpltDictionary.ContainsKey(tmpltDoc.Id)==true) { _activeTmpltDictionary[tmpltDoc.Id] = tmpltDoc; } else { _activeTmpltDictionary.Add(tmpltDoc.Id, tmpltDoc); } } } /// <summary> /// 将已经运行过Tohtml的SnipEle实例加入字典,以便ToCSS的产生 /// </summary> static public void AddSnipElementIntoDictionary(SnipXmlElement snipEle) { if (_activeSnipDictionary == null) { _activeSnipDictionary = new Dictionary<string, SnipXmlElement>(); _activeSnipDictionary.Add(snipEle.Id, snipEle); } else { if (!_activeSnipDictionary.ContainsKey(snipEle.Id)) { _activeSnipDictionary.Add(snipEle.Id, snipEle); } } } /// <summary> /// 将指定的SnipEle从字典中删除 /// </summary> static public void DeleteSnipElementDictionary(string snipId) { _activeSnipDictionary.Remove(snipId); } /// <summary> /// 将指定的TmpltDoc从字典中删除 /// </summary> static public void DeleteTmpltDocmentDictionary(string tmpltId) { _activeTmpltDictionary.Remove(tmpltId); } } }
28.595745
83
0.55506
[ "Apache-2.0" ]
xknife-erian/nknife.jeelusrc
NKnife.App.WebsiteBuilder/Simplus.AppTools/Simplus.PagePreviewer/Service/ActiveTmpltAndSnip.cs
2,870
C#
using System; using System.Dynamic; namespace NConstrictor { public class PyDynamic : DynamicObject { private PyObject _pyObject; public PyDynamic(PyObject pyObject) { _pyObject = pyObject; } // メンバ呼び出し public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { PyObject tuppleArgs = PyTuple.New(args.Length); for (int i = 0; i < args.Length; i++) { if (args[i] is int[] intArray) { PyTuple.SetItem(tuppleArgs, i, (PyArray<int>)intArray); } else if (args[i] is float[] floatArray) { PyTuple.SetItem(tuppleArgs, i, (PyArray<float>)floatArray); } else if (args[i] is double[] doubleArray) { PyTuple.SetItem(tuppleArgs, i, (PyArray<double>)doubleArray); } else if (args[i] is PyArray<float> floatPyArray) { PyTuple.SetItem(tuppleArgs, i, floatPyArray); } else if (args[i] is PyArray<double> doublePyArray) { PyTuple.SetItem(tuppleArgs, i, doublePyArray); } else if (args[i] is PyArray<int> intPyArray) { PyTuple.SetItem(tuppleArgs, i, intPyArray); } else { PyTuple.SetItem(tuppleArgs, i, (PyObject)args[i]); } } result = PyObject.CallObject(_pyObject[binder.Name], tuppleArgs); return true; } // プロパティに値を設定しようとしたときに呼ばれる public override bool TrySetMember(SetMemberBinder binder, object value) { Py.IncRef(_pyObject); if (value is int[] intArray) { _pyObject[binder.Name] = (PyArray<int>)intArray; } else if (value is float[] floatArray) { _pyObject[binder.Name] = (PyArray<float>)floatArray; } else if (value is double[] doubleArray) { _pyObject[binder.Name] = (PyArray<double>)doubleArray; } else if (value is PyArray<float> floatPyArray) { _pyObject[binder.Name] = floatPyArray; } else if (value is PyArray<double> doublePyArray) { _pyObject[binder.Name] = doublePyArray; } else if (value is PyArray<int> intPyArray) { _pyObject[binder.Name] = intPyArray; } else { _pyObject[binder.Name] = (PyObject)value; } return true; } // プロパティから値を取得しようとしたときに呼ばれる public override bool TryGetMember(GetMemberBinder binder, out object result) { Py.IncRef(_pyObject); result = _pyObject[binder.Name]; return true; } public static implicit operator PyObject(PyDynamic main) { return main._pyObject; } } }
30.284404
105
0.485005
[ "Apache-2.0" ]
harujoh/NConstrictor
NConstrictor/PyDynamic.cs
3,411
C#
using System; using System.Threading.Tasks; using Coravel.Events.Interfaces; namespace UnitTests.Events.EventsAndListeners { public class TestListener2ForEvent1 : IListener<TestEvent1> { private Action _a; public TestListener2ForEvent1(Action a){ this._a = a; } public Task HandleAsync(TestEvent1 dipatchedEvent) { this._a(); return Task.CompletedTask; } } }
22.8
63
0.633772
[ "MIT" ]
Blinke/coravel
Src/UnitTests/CoravelUnitTests/Events/EventsAndListeners/TestListener2ForEvent1.cs
456
C#
using CleanArchitecture.Application.UnitTests.Common; using CleanArchitecture.Application.Families.Commands.UpdateFamily; using Shouldly; using Xunit; namespace CleanArchitecture.Application.UnitTests.Families.Commands.UpdateFamily { public class UpdateFamilyCommandValidatorTests : CommandTestBase { [Fact] public void IsValid_ShouldBeTrue_WhenRequiredFieldsAreSet() { var command = new UpdateFamilyCommand { Id = 1, GuestId = 1, ConfirmationCode = "Test ConfirmationCode Update", Address1 = "Test Address1 Update", Address2 = "Test Address2 Update", City = "Test City Update", StateId = 1, Zip = "Test Zip Update" }; var validator = new UpdateFamilyCommandValidator(Context); var result = validator.Validate(command); result.IsValid.ShouldBe(true); } [Fact] public void IsValid_ShouldBeFalse_WhenRequiredFieldsAreNotSet() { var command = new UpdateFamilyCommand(); var validator = new UpdateFamilyCommandValidator(Context); var result = validator.Validate(command); result.IsValid.ShouldBe(false); } } }
29.755556
80
0.608663
[ "MIT" ]
dkm8923/WeddingAppCore
tests/Application.UnitTests/Families/Commands/UpdateFamily/UpdateFamilyCommandValidatorTests.cs
1,341
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Network.V20190901.Outputs { [OutputType] public sealed class P2SVpnGatewayResponse { /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> public readonly string Etag; /// <summary> /// Resource ID. /// </summary> public readonly string? Id; /// <summary> /// Resource location. /// </summary> public readonly string Location; /// <summary> /// Resource name. /// </summary> public readonly string Name; /// <summary> /// List of all p2s connection configurations of the gateway. /// </summary> public readonly ImmutableArray<Outputs.P2SConnectionConfigurationResponse> P2SConnectionConfigurations; /// <summary> /// The provisioning state of the P2S VPN gateway resource. /// </summary> public readonly string ProvisioningState; /// <summary> /// Resource tags. /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// Resource type. /// </summary> public readonly string Type; /// <summary> /// The VirtualHub to which the gateway belongs. /// </summary> public readonly Outputs.SubResourceResponse? VirtualHub; /// <summary> /// All P2S VPN clients' connection health status. /// </summary> public readonly Outputs.VpnClientConnectionHealthResponse VpnClientConnectionHealth; /// <summary> /// The scale unit for this p2s vpn gateway. /// </summary> public readonly int? VpnGatewayScaleUnit; /// <summary> /// The VpnServerConfiguration to which the p2sVpnGateway is attached to. /// </summary> public readonly Outputs.SubResourceResponse? VpnServerConfiguration; [OutputConstructor] private P2SVpnGatewayResponse( string etag, string? id, string location, string name, ImmutableArray<Outputs.P2SConnectionConfigurationResponse> p2SConnectionConfigurations, string provisioningState, ImmutableDictionary<string, string>? tags, string type, Outputs.SubResourceResponse? virtualHub, Outputs.VpnClientConnectionHealthResponse vpnClientConnectionHealth, int? vpnGatewayScaleUnit, Outputs.SubResourceResponse? vpnServerConfiguration) { Etag = etag; Id = id; Location = location; Name = name; P2SConnectionConfigurations = p2SConnectionConfigurations; ProvisioningState = provisioningState; Tags = tags; Type = type; VirtualHub = virtualHub; VpnClientConnectionHealth = vpnClientConnectionHealth; VpnGatewayScaleUnit = vpnGatewayScaleUnit; VpnServerConfiguration = vpnServerConfiguration; } } }
32.462264
111
0.611741
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Network/V20190901/Outputs/P2SVpnGatewayResponse.cs
3,441
C#
#region Header // --------------------------------------------------------------------------------- // <copyright file="PurchaseOKMessageComposer.cs" company="https://github.com/sant0ro/Yupi"> // Copyright (c) 2016 Claudio Santoro, TheDoctor // </copyright> // <license> // 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. // </license> // --------------------------------------------------------------------------------- #endregion Header namespace Yupi.Messages.Catalog { using System; using System.Collections.Generic; using Yupi.Messages.Encoders; using Yupi.Model.Domain; using Yupi.Protocol.Buffers; public class PurchaseOKMessageComposer : Yupi.Messages.Contracts.PurchaseOkComposer { #region Methods public override void Compose(Yupi.Protocol.ISender session, CatalogOffer offer) { using (ServerMessage message = Pool.GetMessageBuffer(Id)) { message.Append(offer); } } #endregion Methods } }
39.301887
92
0.652424
[ "MIT" ]
TheDoct0r11/Yupi
Yupi.Messages/Composer/Catalog/PurchaseOKMessageComposer.cs
2,085
C#
namespace Admin.Core.Service { public abstract class IBaseService { } }
13.285714
38
0.602151
[ "MIT" ]
Twtcer/Admin.Core
Admin.Core.Service/Base/IBaseService.cs
95
C#
using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Service.Core.Client.Services; using Service.UserTokenAccount.Domain.Models; using Service.UserTokenAccount.Grpc; using Service.UserTokenAccount.Grpc.Models; using Service.UserTokenAccount.Mappers; using Service.UserTokenAccount.Postgres.Models; using Service.UserTokenAccount.Postgres.Services; namespace Service.UserTokenAccount.Services { public class UserTokenAccountService : IUserTokenAccountService { private readonly ILogger<UserTokenAccountService> _logger; private readonly IOperationRepository _operationRepository; private readonly IAccountRepository _accountRepository; private readonly ISystemClock _systemClock; private static readonly SemaphoreSlim OperationLocker = new SemaphoreSlim(1, 1); public UserTokenAccountService(ILogger<UserTokenAccountService> logger, IOperationRepository operationRepository, IAccountRepository accountRepository, ISystemClock systemClock) { _logger = logger; _operationRepository = operationRepository; _accountRepository = accountRepository; _systemClock = systemClock; } public async ValueTask<OperationsGrpcResponse> GetOperationsAsync(GetOperationsGrpcRequest request) { UserTokenOperationEntity[] entities = await _operationRepository.GetEntitiesAsync(request.UserId, request.Movement, request.Source, request.ProductType); return new OperationsGrpcResponse { Operations = entities.Select(entity => entity.ToGrpcModel()).ToArray() }; } public async ValueTask<NewOperationGrpcResponse> NewOperationAsync(NewOperationGrpcRequest request) { await OperationLocker.WaitAsync(); string userId = request.UserId; try { if (!await ValidateRequest(request)) { _logger.LogWarning("Insufficient account value for request: {@request}", request); return NewOperationGrpcResponse.Error(TokenOperationResult.InsufficientAccount); } bool newEntityResult = await _operationRepository.NewEntityAsync(request.ToModel(_systemClock.Now)); if (!newEntityResult) return NewOperationGrpcResponse.Error(TokenOperationResult.Failed); decimal? newAccountValue = await _accountRepository.UpdateValueAsync(userId); if (newAccountValue == null || newAccountValue < 0) { _logger.LogError("Invalid account value ({$newValue}) saved after new operation with user account for request {@request}", newAccountValue, request); return NewOperationGrpcResponse.Error(TokenOperationResult.Failed); } return new NewOperationGrpcResponse { Value = newAccountValue.Value, Result = TokenOperationResult.Ok }; } finally { OperationLocker.Release(); } } private async ValueTask<bool> ValidateRequest(NewOperationGrpcRequest request) { if (request.Movement != TokenOperationMovement.Outcome) return true; decimal accountValue = await GetAccountValue(request.UserId); return accountValue >= request.Value; } private ValueTask<decimal> GetAccountValue(string userId) => _accountRepository.GetValueAsync(userId); public async ValueTask<AccountGrpcResponse> GetAccountAsync(GetAccountGrpcRequest request) => new AccountGrpcResponse { Value = await _accountRepository.GetValueAsync(request.UserId) }; } }
34.040816
179
0.78717
[ "MIT" ]
MyJetEducation/Service.UserTokenAccount
src/Service.UserTokenAccount/Services/UserTokenAccountService.cs
3,338
C#
using System.Data; using Microsoft.SqlServer.TransactSql.ScriptDom; namespace Dibix.Sdk.CodeGeneration { public sealed class ExecStoredProcedureSqlStatementFormatter : SqlStatementFormatter, ISqlStatementFormatter { protected override FormattedSqlStatement Format(SqlStatementDescriptor statementDescriptor, StatementList statementList) => new FormattedSqlStatement(statementDescriptor.ProcedureName, CommandType.StoredProcedure); } }
46.5
223
0.821505
[ "Apache-2.0" ]
Serviceware/Dibix
src/Dibix.Sdk/CodeGeneration/Formatter/ExecStoredProcedureSqlStatementFormatter.cs
467
C#
using System; using System.Reflection; namespace VBScriptTranslator.RuntimeSupport.Implementations { public static class MissingMemberException_Extensions { public static bool RelatesTo(this MissingMemberException source, Type type, string memberNameIfAny) { if (source == null) throw new ArgumentNullException("source"); if (type == null) throw new ArgumentNullException("type"); // If a default member is requested, then a number of things may happen. If the request comes from VBScript then it will likely be requested as "[DISPID=0]", // in which case that string will appear in the exception message. If a request is made through an IReflect.InvokeMember call then the member may appear blank. // If a request is made through a Type.InvokeMember call then the blank string may be replaced with the member identified by the DefaultMemberAttribute that // the type has (if it has one) - eg. typeof(string) will specify "Chars" as the target member (since that is what the DefaultMemberAttribute specifies). // - So first, try the simplest match case, where there is no funny business if (source.Message.Contains("'" + type.FullName + "." + memberNameIfAny + "'")) return true; // If that doesn't succeed, and it looks like the request was for the default member, then try the various default member options if (string.IsNullOrWhiteSpace(memberNameIfAny) || (memberNameIfAny == "[DISPID=0]")) { var defaultMemberNameOfTargetType = type.GetCustomAttribute<DefaultMemberAttribute>(inherit: true); if (defaultMemberNameOfTargetType != null) { // TODO: I don't even know if this is correct any more return source.Message.Contains("'" + type.FullName + "." + defaultMemberNameOfTargetType.MemberName + "'") || source.Message.Contains("'" + type.FullName + ".[DISPID=0]'") || source.Message.Contains("'" + type.FullName + ".'"); } } return false; } } }
58
172
0.608621
[ "MIT" ]
Magicianred/vbscripttranslator
RuntimeSupport/Implementations/MissingMemberException_Extensions.cs
2,322
C#
namespace Nibbles.Utils { internal enum TerminalFormatting { None = 0, BoldBright = 1, Underline = 4, Negative = 7, NoUnderline = 24, NoNegative = 27, ForegroundBlack = 30, ForegroundRed = 31, ForegroundGreen = 32, ForegroundYellow = 33, ForegroundBlue = 34, ForegroundMagenta = 35, ForegroundCyan = 36, ForegroundWhite = 37, ForegroundDefault = 39, BackgroundBlack = 40, BackgroundRed = 41, BackgroundGreen = 42, BackgroundYellow = 43, BackgroundBlue = 44, BackgroundMagenta = 45, BackgroundCyan = 46, BackgroundWhite = 47, BackgroundDefault = 49, BrightForegroundBlack = 90, BrightForegroundRed = 91, BrightForegroundGreen = 92, BrightForegroundYellow = 93, BrightForegroundBlue = 94, BrightForegroundMagenta = 95, BrightForegroundCyan = 96, BrightForegroundWhite = 97, BrightBackgroundBlack = 100, BrightBackgroundRed = 101, BrightBackgroundGreen = 102, BrightBackgroundYellow = 103, BrightBackgroundBlue = 104, BrightBackgroundMagenta = 105, BrightBackgroundCyan = 106, BrightBackgroundWhite = 107 } }
16.023256
38
0.575472
[ "MIT" ]
kpreisser/Nibbles
Nibbles/Utils/TerminalFormatting.cs
1,380
C#
namespace Swashbuckle.AspNetCore.SwaggerGen.Test { public class FakeControllers { public class NotAnnotated {} [SwaggerOperationFilter(typeof(VendorExtensionsOperationFilter))] public class AnnotatedWithSwaggerOperationFilter {} /// <summary> /// summary for AnnotatedWithXml /// </summary> public class AnnotatedWithXml {} } }
23.444444
73
0.627962
[ "MIT" ]
devbrsa/Swashbuckle.AspNetCore
test/Swashbuckle.AspNetCore.SwaggerGen.Test/TestFixtures/Fakes/FakeControllers.cs
424
C#
using System; namespace PoshCode.Pansies.ColorSpaces.Comparisons { /// <summary> /// Implements the Cie94 method of delta-e: http://en.wikipedia.org/wiki/Color_difference#CIE94 /// </summary> public class Cie94Comparison : IColorSpaceComparison { /// <summary> /// Application type defines constants used in the Cie94 comparison /// </summary> public enum Application { GraphicArts, Textiles } internal ApplicationConstants Constants { get; private set; } /// <summary> /// Create new Cie94Comparison. Defaults to GraphicArts application type. /// </summary> public Cie94Comparison() { Constants = new ApplicationConstants(Application.GraphicArts); } /// <summary> /// Create new Cie94Comparison for specific application type. /// </summary> /// <param name="application"></param> public Cie94Comparison(Application application) { Constants = new ApplicationConstants(application); } /// <summary> /// Compare colors using the Cie94 algorithm. The first color (a) will be used as the reference color. /// </summary> /// <param name="a">Reference color</param> /// <param name="b">Comparison color</param> /// <returns></returns> public double Compare(IColorSpace a, IColorSpace b) { var labA = a.To<Lab>(); var labB = b.To<Lab>(); var deltaL = labA.L - labB.L; var deltaA = labA.A - labB.A; var deltaB = labA.B - labB.B; var c1 = Math.Sqrt(labA.A * labA.A + labA.B * labA.B); var c2 = Math.Sqrt(labB.A * labB.A + labB.B * labB.B); var deltaC = c1 - c2; var deltaH = deltaA * deltaA + deltaB * deltaB - deltaC * deltaC; deltaH = deltaH < 0 ? 0 : Math.Sqrt(deltaH); const double sl = 1.0; const double kc = 1.0; const double kh = 1.0; var sc = 1.0 + Constants.K1 * c1; var sh = 1.0 + Constants.K2 * c1; var deltaLKlsl = deltaL / (Constants.Kl * sl); var deltaCkcsc = deltaC / (kc * sc); var deltaHkhsh = deltaH / (kh * sh); var i = deltaLKlsl * deltaLKlsl + deltaCkcsc * deltaCkcsc + deltaHkhsh * deltaHkhsh; return i < 0 ? 0 : Math.Sqrt(i); } internal class ApplicationConstants { internal double Kl { get; private set; } internal double K1 { get; private set; } internal double K2 { get; private set; } public ApplicationConstants(Application application) { switch (application) { case Application.GraphicArts: Kl = 1.0; K1 = .045; K2 = .015; break; case Application.Textiles: Kl = 2.0; K1 = .048; K2 = .014; break; } } } } }
32.929293
110
0.50184
[ "MIT" ]
Jaykul/Pansies
Source/Assembly/ColorSpaces/Comparisons/Cie94Comparison.cs
3,262
C#
using CommandLine; namespace SeedCacheFromListOfUkprns { public class CommandLineOptions { [Option('p', "path", Required = true, HelpText = "Path to file with list of UKPRNs")] public string Path { get; set; } [Option('u', "ukrlp-url", Required = true, HelpText = "Url of UKRLP soap endpoint")] public string UkrlpUrl { get; set; } [Option('i', "ukrlp-stakeholder-id", Required = true, HelpText = "Stakeholder id for UKRLP API")] public string UkrlpStakeholderId { get; set; } [Option('c', "connection-string", Required = true, HelpText = "Connection string for cache storage")] public string TableStorageConnectionString { get; set; } [Option('t', "provider-table-name", Required = true, HelpText = "Providers table name")] public string ProviderTableName { get; set; } [Option('s', "state-table-name", Required = true, HelpText = "State table name")] public string StateTableName { get; set; } } }
39.666667
109
0.606909
[ "MIT" ]
DFE-Digital/spi-ukrlp-adapter
src/SeedCacheFromListOfUkprns/CommandLineOptions.cs
1,071
C#
namespace Nancy.Core.Http { using System; using System.Diagnostics; [DebuggerDisplay("{ToString(), nq}")] public partial struct MediaType : IEquatable<MediaType> { private MediaType(string value) { this.Value = value; } public string Value { get; } public bool IsWildcard => this.Value.Equals("*", StringComparison.OrdinalIgnoreCase); public bool Equals(MediaType other) { return string.Equals(this.Value, other.Value, StringComparison.OrdinalIgnoreCase); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } return obj is MediaType && this.Equals((MediaType) obj); } public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(this.Value); } public bool Matches(MediaType other) { return this.IsWildcard || other.IsWildcard || this.Equals(other); } public static bool operator ==(MediaType left, MediaType right) { return Equals(left, right); } public static implicit operator MediaType(string value) { return FromString(value); } public static bool operator !=(MediaType left, MediaType right) { return !Equals(left, right); } public override string ToString() { return this.Value; } } }
24.8125
94
0.559194
[ "Apache-2.0" ]
khellang/nancy-bootstrapper-prototype
src/Nancy.Core/Http/MediaType.cs
1,590
C#
namespace MyProject.Authorization { public static class PermissionNames { public const string Pages_Tenants = "Pages.Tenants"; public const string Pages_Users = "Pages.Users"; public const string Pages_Roles = "Pages.Roles"; public const string Pages_PhoneBook = "Pages.PhoneBook"; public const string Pages_PhoneBook_CreatePerson = "Pages.PhoneBook.CreatePerson"; public const string Pages_PhoneBook_DeletePerson = "Pages.PhoneBook.DeletePerson"; public const string Pages_PhoneBook_EditPerson = "Pages.PhoneBook.EditPerson"; } }
30.3
90
0.719472
[ "MIT" ]
mangelsr/ASP.NET-Boilerplate-template
aspnet-core/src/MyProject.Core/Authorization/PermissionNames.cs
608
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("2.DancingMoves(Batman returns)")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("2.DancingMoves(Batman returns)")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("d3487118-b0de-43dd-9376-f23cd5b6964c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.72973
84
0.745987
[ "MIT" ]
shopOFF/Telerik-Academy-Courses
CSharp-Part-2/C#2 Homeworks & Exams/TelerikExamCSharp2/2.DancingMoves(Batman returns)/Properties/AssemblyInfo.cs
1,436
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. // Sourced from https://github.com/dotnet/core-setup/tree/be8d8e3486b2bf598ed69d39b1629a24caaba45e/tools-local/tasks, needs to be kept in sync using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.Extensions.DependencyModel; using NuGet.Common; using NuGet.ProjectModel; using RepoTasks.Utilities; namespace RepoTasks { public class ProcessSharedFrameworkDeps : Task { [Required] public string AssetsFilePath { get; set; } [Required] public string DepsFilePath { get; set; } [Required] public string OutputPath { get; set; } [Required] public string FrameworkName { get; set; } // When generating the .deps.json file, these files are used to replace "project" libraries with "packages". public ITaskItem[] ResolvedPackageProjectReferences { get; set; } public string[] PackagesToRemove { get; set; } [Required] public string Runtime { get; set; } public override bool Execute() { ExecuteCore(); return true; } private void ExecuteCore() { DependencyContext context; using (var depsStream = File.OpenRead(DepsFilePath)) { context = new DependencyContextJsonReader().Read(depsStream); } var lockFile = LockFileUtilities.GetLockFile(AssetsFilePath, NullLogger.Instance); if (lockFile == null) { throw new ArgumentException($"Could not load a LockFile at '{AssetsFilePath}'.", nameof(AssetsFilePath)); } var manager = new RuntimeGraphManager(); var graph = manager.Collect(lockFile); var expandedGraph = manager.Expand(graph, Runtime); // Remove the runtime entry for the project which generates the original deps.json. For example, there is no Microsoft.AspNetCore.App.dll. var trimmedRuntimeLibraries = RuntimeReference.RemoveSharedFxRuntimeEntry(context.RuntimeLibraries, FrameworkName); trimmedRuntimeLibraries = ResolveProjectsAsPackages(ResolvedPackageProjectReferences, trimmedRuntimeLibraries); if (PackagesToRemove != null && PackagesToRemove.Any()) { trimmedRuntimeLibraries = RuntimeReference.RemoveReferences(trimmedRuntimeLibraries, PackagesToRemove); } context = new DependencyContext( context.Target, CompilationOptions.Default, Array.Empty<CompilationLibrary>(), trimmedRuntimeLibraries, expandedGraph ); using (var depsStream = File.Create(OutputPath)) { new DependencyContextWriter().Write(context, depsStream); } } private IEnumerable<RuntimeLibrary> ResolveProjectsAsPackages(ITaskItem[] resolvedProjects, IEnumerable<RuntimeLibrary> compilationLibraries) { var projects = resolvedProjects.ToDictionary(k => k.GetMetadata("PackageId"), k => k, StringComparer.OrdinalIgnoreCase); foreach (var library in compilationLibraries) { if (projects.TryGetValue(library.Name, out var project)) { Log.LogMessage("Replacing the library entry for {0}", library.Name); var packagePath = project.ItemSpec; var packageId = library.Name; var version = library.Version; string packageHash; using (var sha512 = SHA512.Create()) { packageHash = "sha512-" + sha512.ComputeHashAsBase64(File.OpenRead(packagePath), leaveStreamOpen: false); } yield return new RuntimeLibrary("package", library.Name, library.Version, packageHash, library.RuntimeAssemblyGroups, library.NativeLibraryGroups, library.ResourceAssemblies, library.Dependencies, serviceable: true, path: $"{library.Name}/{library.Version}".ToLowerInvariant(), hashPath: $"{library.Name}.{library.Version}.nupkg.sha512".ToLowerInvariant()); } else { yield return library; } } } } }
38.015504
150
0.593597
[ "Apache-2.0" ]
akrisiun/AspNetCore
build/tasks/ProcessSharedFrameworkDeps.cs
4,904
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Billing { using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; /// <summary> /// BillingProfilesOperations operations. /// </summary> internal partial class BillingProfilesOperations : IServiceOperations<BillingManagementClient>, IBillingProfilesOperations { /// <summary> /// Initializes a new instance of the BillingProfilesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal BillingProfilesOperations(BillingManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the BillingManagementClient /// </summary> public BillingManagementClient Client { get; private set; } /// <summary> /// Lists all billing profiles for a user which that user has access to. /// </summary> /// <param name='billingAccountName'> /// billing Account Id. /// </param> /// <param name='expand'> /// May be used to expand the invoiceSections. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<BillingProfileListResult>> ListByBillingAccountWithHttpMessagesAsync(string billingAccountName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (billingAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "billingAccountName"); } string apiVersion = "2019-10-01-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("billingAccountName", billingAccountName); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByBillingAccount", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles").ToString(); _url = _url.Replace("{billingAccountName}", System.Uri.EscapeDataString(billingAccountName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<BillingProfileListResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<BillingProfileListResult>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get the billing profile by id. /// </summary> /// <param name='billingAccountName'> /// billing Account Id. /// </param> /// <param name='billingProfileName'> /// Billing Profile Id. /// </param> /// <param name='expand'> /// May be used to expand the invoiceSections. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<BillingProfile>> GetWithHttpMessagesAsync(string billingAccountName, string billingProfileName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (billingAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "billingAccountName"); } if (billingProfileName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "billingProfileName"); } string apiVersion = "2019-10-01-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("billingAccountName", billingAccountName); tracingParameters.Add("billingProfileName", billingProfileName); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}").ToString(); _url = _url.Replace("{billingAccountName}", System.Uri.EscapeDataString(billingAccountName)); _url = _url.Replace("{billingProfileName}", System.Uri.EscapeDataString(billingProfileName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<BillingProfile>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<BillingProfile>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// The operation to create a BillingProfile. /// </summary> /// <param name='billingAccountName'> /// billing Account Id. /// </param> /// <param name='billingProfileName'> /// Billing Profile Id. /// </param> /// <param name='parameters'> /// Request parameters supplied to the Create BillingProfile operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<BillingProfile,BillingProfilesCreateHeaders>> CreateWithHttpMessagesAsync(string billingAccountName, string billingProfileName, BillingProfileCreationRequest parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<BillingProfile,BillingProfilesCreateHeaders> _response = await BeginCreateWithHttpMessagesAsync(billingAccountName, billingProfileName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// The operation to update a billing profile. /// </summary> /// <param name='billingAccountName'> /// billing Account Id. /// </param> /// <param name='billingProfileName'> /// Billing Profile Id. /// </param> /// <param name='parameters'> /// Request parameters supplied to the update billing profile operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<BillingProfile,BillingProfilesUpdateHeaders>> UpdateWithHttpMessagesAsync(string billingAccountName, string billingProfileName, BillingProfile parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<BillingProfile,BillingProfilesUpdateHeaders> _response = await BeginUpdateWithHttpMessagesAsync(billingAccountName, billingProfileName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// The operation to create a BillingProfile. /// </summary> /// <param name='billingAccountName'> /// billing Account Id. /// </param> /// <param name='billingProfileName'> /// Billing Profile Id. /// </param> /// <param name='parameters'> /// Request parameters supplied to the Create BillingProfile operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<BillingProfile,BillingProfilesCreateHeaders>> BeginCreateWithHttpMessagesAsync(string billingAccountName, string billingProfileName, BillingProfileCreationRequest parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (billingAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "billingAccountName"); } if (billingProfileName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "billingProfileName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } string apiVersion = "2019-10-01-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("billingAccountName", billingAccountName); tracingParameters.Add("billingProfileName", billingProfileName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}").ToString(); _url = _url.Replace("{billingAccountName}", System.Uri.EscapeDataString(billingAccountName)); _url = _url.Replace("{billingProfileName}", System.Uri.EscapeDataString(billingProfileName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<BillingProfile,BillingProfilesCreateHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<BillingProfile>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<BillingProfilesCreateHeaders>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// The operation to update a billing profile. /// </summary> /// <param name='billingAccountName'> /// billing Account Id. /// </param> /// <param name='billingProfileName'> /// Billing Profile Id. /// </param> /// <param name='parameters'> /// Request parameters supplied to the update billing profile operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<BillingProfile,BillingProfilesUpdateHeaders>> BeginUpdateWithHttpMessagesAsync(string billingAccountName, string billingProfileName, BillingProfile parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (billingAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "billingAccountName"); } if (billingProfileName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "billingProfileName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } string apiVersion = "2019-10-01-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("billingAccountName", billingAccountName); tracingParameters.Add("billingProfileName", billingProfileName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}").ToString(); _url = _url.Replace("{billingAccountName}", System.Uri.EscapeDataString(billingAccountName)); _url = _url.Replace("{billingProfileName}", System.Uri.EscapeDataString(billingProfileName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<BillingProfile,BillingProfilesUpdateHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<BillingProfile>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<BillingProfilesUpdateHeaders>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
46.675916
344
0.575009
[ "MIT" ]
Bhaskers-Blu-Org2/Partner-Center-PowerShell
src/Billing/BillingProfilesOperations.cs
42,055
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Graph.RBAC { using System; using System.Collections.Generic; using System.Linq; internal static partial class SdkInfo { public static IEnumerable<Tuple<string, string, string>> ApiInfo_GraphRbacManagementClient { get { return new Tuple<string, string, string>[] { new Tuple<string, string, string>("GraphRbacManagementClient", "Applications", "1.6"), new Tuple<string, string, string>("GraphRbacManagementClient", "DeletedApplications", "1.6"), new Tuple<string, string, string>("GraphRbacManagementClient", "Domains", "1.6"), new Tuple<string, string, string>("GraphRbacManagementClient", "Groups", "1.6"), new Tuple<string, string, string>("GraphRbacManagementClient", "OAuth2PermissionGrant", "1.6"), new Tuple<string, string, string>("GraphRbacManagementClient", "Objects", "1.6"), new Tuple<string, string, string>("GraphRbacManagementClient", "ServicePrincipals", "1.6"), new Tuple<string, string, string>("GraphRbacManagementClient", "SignedInUser", "1.6"), new Tuple<string, string, string>("GraphRbacManagementClient", "Users", "1.6"), }.AsEnumerable(); } } // BEGIN: Code Generation Metadata Section public static readonly String AutoRestVersion = "latest"; public static readonly String AutoRestBootStrapperVersion = "autorest@2.0.4283"; public static readonly String AutoRestCmdExecuted = "cmd.exe /c autorest.cmd https://github.com/Azure/azure-rest-api-specs/blob/master/specification/graphrbac/data-plane/readme.md --csharp --version=latest --reflect-api-versions --csharp-sdks-folder=C:\\graph\\azure-sdk-for-net\\src\\SDKs"; public static readonly String GithubForkName = "Azure"; public static readonly String GithubBranchName = "master"; public static readonly String GithubCommidId = "86b303185361978f61feb1c20be1e3cf48a98260"; public static readonly String CodeGenerationErrors = ""; public static readonly String GithubRepoName = "azure-rest-api-specs"; // END: Code Generation Metadata Section } }
52.021277
297
0.675665
[ "MIT" ]
0xced/azure-sdk-for-net
src/SDKs/Graph.RBAC/Graph.RBAC/Generated/SdkInfo_GraphRbacManagementClient.cs
2,445
C#
namespace BookShop.Server.Common.Models.Books { using System.ComponentModel.DataAnnotations; using AutoMapper; using Data.Models; using Data.Models.Enums; using Mappings.Contracts; public class AddBookRequestModel : IMapFrom<Book>, IHaveCustomMappings { [StringLength(50, MinimumLength = 2)] public string Title { get; set; } [StringLength(400)] public string Description { get; set; } [Range(0, 200)] public decimal Price { get; set; } [Range(0, int.MaxValue)] public int Copies { get; set; } public EditionType Edition { get; set; } public int AuthorId { get; set; } public string CategoriesNames { get; set; } public void CreateMappings(IMapperConfigurationExpression configuration) { configuration.CreateMap<Book, AddBookRequestModel>() .ForMember(b => b.CategoriesNames, opts => opts.Ignore()) .ReverseMap(); } } }
28.222222
80
0.617126
[ "MIT" ]
IvayloKodov/My-Projects
BookShop/Server/BookShop.Server.Common/Models/Books/AddBookRequestModel.cs
1,018
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; namespace ProjectManager.Projects { public class ProjectReader : XmlTextReader { protected int version; public ProjectReader(string filename, Project project) : base(new FileStream(filename,FileMode.Open,FileAccess.Read)) { Project = project; WhitespaceHandling = WhitespaceHandling.None; } protected Project Project { get; } public virtual Project ReadProject() { MoveToContent(); ProcessRootNode(); while (Read()) ProcessNode(Name); Close(); PostProcess(); return Project; } protected virtual void PostProcess() { if (version > 1) return; // import FD3 project if (Project.OutputType == OutputType.Unknown) Project.OutputType = Project.MovieOptions.DefaultOutput(Project.MovieOptions.Platform); else if (Project.OutputType == OutputType.OtherIDE && (!string.IsNullOrEmpty(Project.PreBuildEvent) || !string.IsNullOrEmpty(Project.PostBuildEvent))) Project.OutputType = OutputType.CustomBuild; } protected virtual void ProcessRootNode() { version = 1; int.TryParse(GetAttribute("version") ?? "1", out version); } protected virtual void ProcessNode(string name) { switch (name) { case "output": ReadOutputOptions(); break; case "classpaths": ReadClasspaths(); break; case "compileTargets": ReadCompileTargets(); break; case "hiddenPaths": ReadHiddenPaths(); break; case "preBuildCommand": ReadPreBuildCommand(); break; case "postBuildCommand": ReadPostBuildCommand(); break; case "options": ReadProjectOptions(); break; case "storage": ReadPluginStorage(); break; } } void ReadPluginStorage() { if (IsEmptyElement) { Read(); return; } ReadStartElement("storage"); while (Name == "entry") { string key = GetAttribute("key"); if (IsEmptyElement) { Read(); continue; } Read(); if (key != null) Project.storage.Add(key, Value); Read(); ReadEndElement(); } ReadEndElement(); } public void ReadOutputOptions() { ReadStartElement("output"); while (Name == "movie") { MoveToFirstAttribute(); switch (Name) { case "disabled": Project.OutputType = BoolValue ? OutputType.OtherIDE : OutputType.Application; break; case "outputType": if (Enum.IsDefined(typeof(OutputType), Value)) Project.OutputType = (OutputType)Enum.Parse(typeof(OutputType), Value); break; case "input": Project.InputPath = OSPath(Value); break; case "path": Project.OutputPath = OSPath(Value); break; case "fps": Project.MovieOptions.Fps = IntValue; break; case "width": Project.MovieOptions.Width = IntValue; break; case "height": Project.MovieOptions.Height = IntValue; break; case "version": Project.MovieOptions.MajorVersion = IntValue; break; case "minorVersion": Project.MovieOptions.MinorVersion = IntValue; break; case "platform": Project.MovieOptions.Platform = Value; break; case "background": Project.MovieOptions.Background = Value; break; case "preferredSDK": Project.PreferredSDK = Value; break; } Read(); } ReadEndElement(); } public void ReadClasspaths() { ReadStartElement("classpaths"); ReadPaths("class",Project.Classpaths); ReadEndElement(); } public void ReadCompileTargets() { ReadStartElement("compileTargets"); ReadPaths("compile",Project.CompileTargets); ReadEndElement(); } public void ReadHiddenPaths() { ReadStartElement("hiddenPaths"); ReadPaths("hidden",Project.HiddenPaths); ReadEndElement(); } public void ReadPreBuildCommand() { if (!IsEmptyElement) { ReadStartElement("preBuildCommand"); Project.PreBuildEvent = ReadString().Trim(); ReadEndElement(); } } public void ReadPostBuildCommand() { Project.AlwaysRunPostBuild = Convert.ToBoolean(GetAttribute("alwaysRun")); if (!IsEmptyElement) { ReadStartElement("postBuildCommand"); Project.PostBuildEvent = ReadString().Trim(); ReadEndElement(); } } public void ReadProjectOptions() { ReadStartElement("options"); while (Name == "option") { MoveToFirstAttribute(); switch (Name) { case "showHiddenPaths": Project.ShowHiddenPaths = BoolValue; break; case "testMovie": // Be tolerant of unknown strings (older .fdp projects might have these) var acceptableValues = new List<string>(Enum.GetNames(typeof(TestMovieBehavior))); if (acceptableValues.Contains(Value)) Project.TestMovieBehavior = (TestMovieBehavior)Enum.Parse(typeof(TestMovieBehavior), Value, true); else Project.TestMovieBehavior = TestMovieBehavior.NewTab; break; case "defaultBuildTargets": if (!string.IsNullOrEmpty(Value.Trim()) && Value.Contains(",")) { string[] cleaned = Value.Trim().Split(',').Select(x => x.Trim()).ToArray<string>(); Project.MovieOptions.DefaultBuildTargets = cleaned; } break; case "testMovieCommand": Project.TestMovieCommand = Value; break; } Read(); } ReadEndElement(); } public bool BoolValue => Convert.ToBoolean(Value); public int IntValue => Convert.ToInt32(Value); public void ReadPaths(string pathNodeName, IAddPaths paths) { while (Name == pathNodeName) { paths.Add(OSPath(GetAttribute("path"))); Read(); } } protected string OSPath(string path) { if (path != null) { path = path.Replace('/', Path.DirectorySeparatorChar); path = path.Replace('\\', Path.DirectorySeparatorChar); } return path; } } }
34.920354
161
0.486569
[ "MIT" ]
YellowAfterlife/flashdevelop
External/Plugins/ProjectManager/Projects/ProjectReader.cs
7,667
C#
/* Copyright 2018 Nils Kopal <Nils.Kopal<AT>Uni-Kassel.de> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using VoluntLib2.ManagementLayer.Messages; namespace VoluntLib2.Tools { public enum CertificateValidationState { Valid, Unknown, Invalid } [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Assertion)] public class CertificateService { private const string NameOfHashAlgorithm = "SHA256"; private readonly SHA256 HashAlgorithm = SHA256Managed.Create(); private X509Certificate2 CaCertificate; private RSACryptoServiceProvider CryptoServiceProvider; public X509Certificate2 OwnCertificate { get; private set; } public string OwnName { get; private set; } public List<string> AdminCertificateList { get; set; } public List<string> BannedCertificateList { get; set; } /// <summary> /// Get the instance of the CertificateService /// </summary> private static CertificateService instance = null; public static CertificateService GetCertificateService() { if (instance == null) { instance = new CertificateService(); } return instance; } /// <summary> /// Private constructor for singleton pattern /// </summary> private CertificateService() { BannedCertificateList = new List<string>(); AdminCertificateList = new List<string>(); } /// <summary> /// Init the service with CA and own certificate /// </summary> /// <param name="caCertificate"></param> /// <param name="ownCertificate"></param> public void Init(X509Certificate2 caCertificate, X509Certificate2 ownCertificate) { CaCertificate = caCertificate; OwnCertificate = ownCertificate; if (!IsValidCertificate(ownCertificate)) { throw new InvalidDataException("Own Certificate is not valid!"); } if (!ownCertificate.HasPrivateKey) { throw new KeyNotFoundException("Private Key in own certificate not found!"); } //create the CryptoServiceProvider using the private key CryptoServiceProvider = (RSACryptoServiceProvider)ownCertificate.PrivateKey; if (CryptoServiceProvider.CspKeyContainerInfo.ProviderType == 1) { //if the Certificate's CryptoServiceProvider does not support SHA2 create a new CSP that does CryptoServiceProvider = new RSACryptoServiceProvider(new CspParameters { KeyContainerName = CryptoServiceProvider.CspKeyContainerInfo.KeyContainerName, KeyNumber = CryptoServiceProvider.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2 }) { PersistKeyInCsp = true }; } OwnName = GetSubjectNameFromCertificate(ownCertificate); AdminCertificateList = new List<string>(); BannedCertificateList = new List<string>(); } private string GetSubjectNameFromCertificate(X509Certificate2 cert) { return cert.SubjectName.Name != null ? cert.SubjectName.Name.Split('=').Last() : ""; } /// <summary> /// Verifies the signature of the given message. /// Also checks, if the certificate is banned /// </summary> /// <param name="message"></param> /// <returns></returns> public CertificateValidationState VerifySignature(Message message) { //extract certificate X509Certificate2 senderCertificate = ExtractValidCertificate(message); if (senderCertificate == null) { return CertificateValidationState.Invalid; } if (IsBannedCertificate(senderCertificate)) { return CertificateValidationState.Invalid; } //extract signature and replace with empty signature byte[] originalSignature = message.MessageHeader.SignatureData; message.MessageHeader.SignatureData = new byte[0]; byte[] data = message.Serialize(false); // Verify the signature with the hash RSACryptoServiceProvider provider = (RSACryptoServiceProvider)senderCertificate.PublicKey.Key; bool valid = provider.VerifyData(data, NameOfHashAlgorithm, originalSignature); message.MessageHeader.SignatureData = originalSignature; if (valid) { return CertificateValidationState.Valid; } return CertificateValidationState.Invalid; } /// <summary> /// Verifies if the given signature of the given data is valid. /// Also checks, if the certificate is banned or invalid /// </summary> /// <param name="data"></param> /// <param name="certificate"></param> /// <returns></returns> public CertificateValidationState VerifySignature(byte[] data, byte[] signature, X509Certificate2 certificate) { if (IsBannedCertificate(certificate)) { return CertificateValidationState.Invalid; } if (!IsValidCertificate(certificate)) { return CertificateValidationState.Invalid; } // Verify the signature with the hash RSACryptoServiceProvider provider = (RSACryptoServiceProvider)certificate.PublicKey.Key; bool valid = provider.VerifyData(data, NameOfHashAlgorithm, signature); if (valid) { return CertificateValidationState.Valid; } return CertificateValidationState.Invalid; } /// <summary> /// Signs the message, adds the sendername and the certificate /// </summary> /// <param name="message">The message</param> /// <returns></returns> public byte[] SignData(byte[] data) { return CryptoServiceProvider.SignData(data, NameOfHashAlgorithm); } /// <summary> /// Determines whether the specified message has been signed by an admin. /// </summary> /// <param name="message">The message.</param> /// <returns></returns> public bool IsAdmin(Message message) { X509Certificate2 senderCertificate = ExtractValidCertificate(message); if (senderCertificate == null) { return false; } return IsAdminCertificate(senderCertificate); } /// <summary> /// Checks, if the given certificate is an admin certificate /// </summary> /// <param name="certificate"></param> /// <returns></returns> public bool IsAdminCertificate(X509Certificate2 certificate) { //by name string senderName = GetSubjectNameFromCertificate(certificate); if (AdminCertificateList.Contains("N:" + senderName)) { return true; } //by serial number if (AdminCertificateList.Contains("SN:" + certificate.SerialNumber)) { return true; } return false; } /// <summary> /// Checks, if the given certificate is banned /// </summary> /// <param name="certificate"></param> /// <returns></returns> public bool IsBannedCertificate(X509Certificate2 certificate) { //by name string senderName = GetSubjectNameFromCertificate(certificate); if (BannedCertificateList.Contains("N:" + senderName)) { return true; } //by serial number if (BannedCertificateList.Contains("SN:" + certificate.SerialNumber)) { return true; } return false; } /// <summary> /// Returns a valid certificate or null /// </summary> /// <param name="message">The message.</param> /// <returns></returns> private X509Certificate2 ExtractValidCertificate(Message message) { X509Certificate2 senderCertificate; try { senderCertificate = new X509Certificate2(message.MessageHeader.CertificateData); } catch { return null; } //check if its valid if (IsValidCertificate(senderCertificate)) { return senderCertificate; } return null; } /// <summary> /// Determines whether the certificate is issued by our CA or not /// </summary> /// <param name="certificate">The certificate.</param> /// <returns></returns> public bool IsValidCertificate(X509Certificate2 certificate) { try { X509Chain chain = new X509Chain(false); chain.ChainPolicy.ExtraStore.Add(CaCertificate); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; if (chain.Build(certificate) == false) { return false; } if (string.IsNullOrEmpty(certificate.SubjectName.Name)) { //We dont accept certificates with no subject name return false; } if (!chain.ChainPolicy.ExtraStore.Contains(chain.ChainElements[chain.ChainElements.Count - 1].Certificate)) { //The certificate has to be signed by our CA certificate return false; } return true; } catch (Exception) { return false; } } /// <summary> /// Computes the SHA256 hash of the given byte array /// </summary> /// <param name="data"></param> /// <returns></returns> public byte[] ComputeHash(byte[] data) { return HashAlgorithm.ComputeHash(data); } } }
35.736677
123
0.579912
[ "Apache-2.0" ]
CrypToolProject/CrypTool-2
LibSource/VoluntLib2/Tools/CertificateService.cs
11,402
C#
using Microsoft.Azure.Functions.Extensions.DependencyInjection; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Hosting; using Microsoft.Extensions.DependencyInjection; using SampleFunctions._02_InputBindings.Binding; using SampleFunctions.Di; [assembly: FunctionsStartup(typeof(SampleFunctions.Startup))] [assembly: WebJobsStartup(typeof(SampleFunctions.WebJobStartup))] namespace SampleFunctions { public class Startup : FunctionsStartup { public override void Configure(IFunctionsHostBuilder builder) { builder.Services.AddSingleton<IMyClass>((s) => { return new MyClass(); }); } } public class WebJobStartup : IWebJobsStartup { public void Configure(IWebJobsBuilder builder) { builder.AddAccessTokenBinding(); } } }
27.774194
69
0.703833
[ "MIT" ]
ckittel/Azure-Functions-Samples
SampleFunctions/Startup.cs
863
C#
namespace Mallet.Shell.Forms { partial class SettingsForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.SettingsPanel = new System.Windows.Forms.TableLayoutPanel(); this.CancelButton = new System.Windows.Forms.Button(); this.OKButton = new System.Windows.Forms.Button(); this.GroupList = new System.Windows.Forms.TreeView(); this.SuspendLayout(); // // SettingsPanel // this.SettingsPanel.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.SettingsPanel.AutoScroll = true; this.SettingsPanel.ColumnCount = 1; this.SettingsPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.SettingsPanel.Location = new System.Drawing.Point(169, 12); this.SettingsPanel.Name = "SettingsPanel"; this.SettingsPanel.Padding = new System.Windows.Forms.Padding(0, 0, 20, 0); this.SettingsPanel.Size = new System.Drawing.Size(720, 411); this.SettingsPanel.TabIndex = 7; // // CancelButton // this.CancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.CancelButton.Location = new System.Drawing.Point(814, 429); this.CancelButton.Name = "CancelButton"; this.CancelButton.Size = new System.Drawing.Size(75, 23); this.CancelButton.TabIndex = 8; this.CancelButton.Text = "Cancel"; this.CancelButton.UseVisualStyleBackColor = true; this.CancelButton.Click += new System.EventHandler(this.CancelClicked); // // OKButton // this.OKButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.OKButton.Location = new System.Drawing.Point(733, 429); this.OKButton.Name = "OKButton"; this.OKButton.Size = new System.Drawing.Size(75, 23); this.OKButton.TabIndex = 8; this.OKButton.Text = "OK"; this.OKButton.UseVisualStyleBackColor = true; this.OKButton.Click += new System.EventHandler(this.OkClicked); // // GroupList // this.GroupList.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.GroupList.Location = new System.Drawing.Point(12, 12); this.GroupList.Name = "GroupList"; this.GroupList.Size = new System.Drawing.Size(151, 411); this.GroupList.TabIndex = 9; this.GroupList.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.GroupListSelectionChanged); // // SettingsForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(901, 464); this.Controls.Add(this.GroupList); this.Controls.Add(this.OKButton); this.Controls.Add(this.CancelButton); this.Controls.Add(this.SettingsPanel); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SettingsForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "SettingsForm"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.TableLayoutPanel SettingsPanel; private System.Windows.Forms.Button CancelButton; private System.Windows.Forms.Button OKButton; private System.Windows.Forms.TreeView GroupList; } }
47.336449
163
0.611056
[ "BSD-3-Clause" ]
jspicer-code/mallet
Mallet.Shell/Forms/SettingsForm.Designer.cs
5,067
C#
using PipServices3.Commons.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PipServices.Templates.Facade.Clients.Version1 { public class SessionsMemoryClientV1 : ISessionsClientV1 { public List<SessionV1> _sessions = new List<SessionV1>(); public async Task<SessionV1> CloseSessionAsync(string correlationId, string sessionId) { var session = _sessions.FirstOrDefault(x => x.Id == sessionId); if (session != null) { session.Active = false; return session; } await Task.Delay(0); return null; } public async Task<SessionV1> DeleteSessionByIdAsync(string correlationId, string sessionId) { var session = _sessions.FirstOrDefault(x => x.Id == sessionId); if (session != null) { _sessions.Remove(session); return session; } await Task.Delay(0); return null; } public async Task<SessionV1> GetSessionByIdAsync(string correlationId, string sessionId) { return await Task.FromResult(_sessions.FirstOrDefault(x => x.Id == sessionId)); } public async Task<DataPage<SessionV1>> GetSessionsAsync(string correlationId, FilterParams filter, PagingParams paging) { return await Task.FromResult(new DataPage<SessionV1>(_sessions, _sessions.Count)); } public async Task<SessionV1> OpenSessionAsync(string correlationId, string user_id, string user_name, string address, string client, object user, object data) { var session = new SessionV1(null, user_id, user_name, address, client) { User = user, Data = data }; _sessions.Add(session); return await Task.FromResult(session); } public async Task<SessionV1> StoreSessionDataAsync(string correlationId, string sessionId, object data) { return await Task.FromResult((SessionV1)null); } public async Task<SessionV1> UpdateSessionUserAsync(string correlationId, string sessionId, object user) { var session = _sessions.FirstOrDefault(x => x.Id == sessionId); if (session != null) { session.User = user; return session; } await Task.Delay(0); return null; } } }
26.469136
160
0.722015
[ "MIT" ]
pip-templates/pip-templates-facada-dotnet
src/Client/Clients/Version1/SessionsMemoryClientV1.cs
2,146
C#
// Project: Aguafrommars/TheIdServer // Copyright (c) 2022 @Olivier Lefebvre using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using System; using System.Globalization; using IO = System.IO; namespace Aguacongas.IdentityServer.Admin { /// <summary> /// Welcome fragment controller /// </summary> /// <seealso cref="Controller" /> [Route("[controller]")] public class WelcomeFragmentController : Controller { private readonly IWebHostEnvironment _environment; /// <summary> /// Initializes a new instance of the <see cref="WelcomeFragmentController"/> class. /// </summary> /// <param name="environment">The environment.</param> /// <exception cref="ArgumentNullException">environment</exception> public WelcomeFragmentController(IWebHostEnvironment environment) { _environment = environment ?? throw new ArgumentNullException(nameof(environment)); } /// <summary> /// Gets welcome fragment html code depending the current culture and environmeent. /// </summary> /// <returns></returns> [HttpGet] public FileResult Get() { var path = $"{_environment.WebRootPath}/{_environment.EnvironmentName}-welcome-fragment.{CultureInfo.CurrentCulture.Name}.html"; if (IO.File.Exists(path)) { return File(IO.File.OpenRead(path), "text/htnl"); } path = $"{_environment.WebRootPath}/{_environment.EnvironmentName}-welcome-fragment.html"; if (IO.File.Exists(path)) { return File(IO.File.OpenRead(path), "text/htnl"); } path = $"{_environment.WebRootPath}/welcome-fragment.{CultureInfo.CurrentCulture.Name}.html"; if (IO.File.Exists(path)) { return File(IO.File.OpenRead(path), "text/htnl"); } path = $"{_environment.WebRootPath}/welcome-fragment.html"; if (IO.File.Exists(path)) { return File(IO.File.OpenRead(path), "text/htnl"); } return null; } } }
36.163934
140
0.598821
[ "Apache-2.0" ]
LibertyEngineeringMovement/TheIdServer
src/IdentityServer/Aguacongas.IdentityServer.Admin/WelcomeFragmentController.cs
2,208
C#
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using Newtonsoft.Json; using WubbyCorp.Extensions; using WubbyCorp.GameData; namespace WubbyCorp.CustomControls { [JsonObject(MemberSerialization.OptIn)] public partial class Company : UserControl { public Company() { InitializeComponent(); // Not sure if I like the wubbyCado icon on the button or not //BuyButton.ImageAlign = ContentAlignment.MiddleRight; //BuyButton.TextImageRelation = TextImageRelation.TextBeforeImage; //BuyButton.Image = ImageUtils.ResizeImage(Properties.Resources.wubbyCado, 24, 24); } private void Company_Load(object sender, EventArgs e) { if (GameDataManager.Configuration.Companies.ContainsKey(CompanyDisplayNameFormatted())) { Multiplier = GameDataManager.Configuration.Companies[CompanyDisplayNameFormatted()].Multiplier; ProductionInterval = GameDataManager.Configuration.Companies[CompanyDisplayNameFormatted()].ProductionInterval; Production = GameDataManager.Configuration.Companies[CompanyDisplayNameFormatted()].Production; BuyPrice = GameDataManager.Configuration.Companies[CompanyDisplayNameFormatted()].BuyPrice; BuyAmount = GameDataManager.Configuration.Companies[CompanyDisplayNameFormatted()].BuyAmount; CompanyLevel = GameDataManager.Configuration.Companies[CompanyDisplayNameFormatted()].CompanyLevel; } SetBuyButtonText(); ProductionTimer.Start(); } private void BuyButton_Click(object sender, EventArgs e) { double buyCost = (BuyPrice * BuyAmount); // TODO Subtract from the total WubbyCados } private void CompanyLogoPictureBox_MouseDown(object sender, MouseEventArgs e) => WubbyCadosManager.Add(1D); private void ProductionTimer_Tick(object sender, EventArgs e) { } private void SetBuyButtonText() { (double value, string dictionaryWord) = (BuyPrice * BuyAmount).ToDictionaryWord(); BuyButton.Text = $"Buy (x{BuyAmount}) for {((BuyPrice > 999D) ? value.ToString("N2") : value.ToString("N0"))} {((string.IsNullOrEmpty(dictionaryWord)) ? "" : $"{dictionaryWord} ")}WubbyCado{((BuyPrice == 1D) ? "" : "s")}"; } public event PropertyChangedEventHandler MultiplierChanged; protected void OnMultiplierChanged(string propertyName) => MultiplierChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); private int _Multiplier = 1; /// <summary> /// Gets or sets the multiplier used to calculate the <see cref="Production"/>. /// </summary> [JsonProperty] public int Multiplier { get => _Multiplier; set { if (!(_Multiplier == value)) { _Multiplier = value; OnMultiplierChanged(nameof(Multiplier)); } } } public event PropertyChangedEventHandler ProductionIntervalChanged; protected void OnProductionIntervalChanged(string propertyName) => ProductionIntervalChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); private int _ProductionInterval = 5000; /// <summary> /// Gets or sets how often a production cycle takes in milliseconds. /// </summary> [JsonProperty] public int ProductionInterval { get => _ProductionInterval; set { if (!(_ProductionInterval == value)) { _ProductionInterval = value; OnProductionIntervalChanged(nameof(ProductionInterval)); if (!(ProductionTimer.Interval == ProductionInterval)) { if (ProductionTimer.Enabled) { ProductionTimer.Stop(); ProductionTimer.Interval = ProductionInterval; ProductionTimer.Start(); } else { ProductionTimer.Interval = ProductionInterval; } } } } } public event PropertyChangedEventHandler ProductionChanged; protected void OnProductionChanged(string propertyName) => ProductionChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); private double _Production; /// <summary> /// Gets or sets how many WubbyCados to make in a single <see cref="ProductionInterval"/>. /// </summary> [JsonProperty] public double Production { get => _Production; set { if (!(_Production == value)) { _Production = value; OnProductionChanged(nameof(Production)); } } } public event PropertyChangedEventHandler BuyPriceChanged; protected void OnBuyPriceChanged(string propertyName) => BuyPriceChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); private double _BuyPrice = 1D; /// <summary> /// Gets or sets the cost of the next <see cref="CompanyLevel"/> in WubbyCados. /// </summary> [JsonProperty] public double BuyPrice { get => _BuyPrice; set { if (!(_BuyPrice == value)) { _BuyPrice = value; OnBuyPriceChanged(nameof(BuyPrice)); SetBuyButtonText(); } } } public event PropertyChangedEventHandler BuyAmountChanged; protected void OnBuyAmountChanged(string propertyName) => BuyAmountChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); private int _BuyAmount = 1; /// <summary> /// Gets or sets how many <see cref="CompanyLevel"/> to buy. /// </summary> [JsonProperty] public int BuyAmount { get => _BuyAmount; set { if (!(_BuyAmount == value)) { _BuyAmount = value; OnBuyAmountChanged(nameof(BuyAmount)); SetBuyButtonText(); } } } public event PropertyChangedEventHandler BuyButtonEnabledChanged; protected void OnBuyButtonEnabledChanged(string propertyName) => BuyButtonEnabledChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); /// <summary> /// Gets or sets a value indicating whether the control can respond to user interaction. /// </summary> public bool BuyButtonEnabled { get => BuyButton.Enabled; set { if (!(BuyButton.Enabled == value)) { if (BuyButton.InvokeRequired) { Invoke(new Action(() => BuyButton.Enabled = value)); } else { BuyButton.Enabled = value; } OnBuyButtonEnabledChanged(nameof(BuyButtonEnabled)); } } } public event PropertyChangedEventHandler MarqueeEnabledChanged; protected void OnMarqueeEnabledChanged(string propertyName) => MarqueeEnabledChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); private bool _MarqueeEnabled = false; /// <summary> /// Gets or sets a value indicating whether the progress bar marquee is enabled. /// </summary> public bool MarqueeEnabled { get => _MarqueeEnabled; set { if (!(_MarqueeEnabled == value)) { _MarqueeEnabled = value; if (_MarqueeEnabled) { if (BuyButton.InvokeRequired) { Invoke(new Action(() => ProductionProgressBar.Style = ProgressBarStyle.Marquee)); } else { ProductionProgressBar.Style = ProgressBarStyle.Marquee; } } else { if (BuyButton.InvokeRequired) { Invoke(new Action(() => { ProductionProgressBar.Value = 0; ProductionProgressBar.Style = ProgressBarStyle.Blocks; })); } else { ProductionProgressBar.Value = 0; ProductionProgressBar.Style = ProgressBarStyle.Blocks; } } OnMarqueeEnabledChanged(nameof(BuyButtonEnabled)); } } } public event PropertyChangedEventHandler CompanyLogoChanged; protected void OnCompanyLogoChanged(string propertyName) => CompanyLogoChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); /// <summary> /// Gets or sets an image for the company logo. /// </summary> public Image CompanyLogo { get => CompanyLogoPictureBox.Image; set { if (!(CompanyLogoPictureBox.Image == value)) { if (CompanyLogoPictureBox.InvokeRequired) { Invoke(new Action(() => CompanyLogoPictureBox.Image = value)); } else { CompanyLogoPictureBox.Image = value; } OnCompanyLogoChanged(nameof(CompanyLogo)); } } } public event PropertyChangedEventHandler CompanyDisplayNameChanged; protected void OnCompanyDisplayNameChanged(string propertyName) => CompanyDisplayNameChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); /// <summary> /// Gets the company display name formatted with no spaces. /// </summary> public string CompanyDisplayNameFormatted() => CompanyDisplayName.Replace(" ", string.Empty); /// <summary> /// Gets or sets the company display name. /// </summary> public string CompanyDisplayName { get => CompanyDisplayNameLabel.Text; set { if (!(CompanyDisplayNameLabel.Text == value)) { if (CompanyDisplayNameLabel.InvokeRequired) { Invoke(new Action(() => CompanyDisplayNameLabel.Text = value)); } else { CompanyDisplayNameLabel.Text = value; } OnCompanyDisplayNameChanged(nameof(CompanyDisplayName)); } } } public event PropertyChangedEventHandler CompanyTaglineChanged; protected void OnCompanyTaglineChanged(string propertyName) => CompanyTaglineChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); /// <summary> /// Gets or sets the company tagline. /// </summary> public string CompanyTagline { get => CompanyTaglineLabel.Text; set { if (!(CompanyTaglineLabel.Text == value)) { if (CompanyTaglineLabel.InvokeRequired) { Invoke(new Action(() => CompanyTaglineLabel.Text = value)); } else { CompanyTaglineLabel.Text = value; } OnCompanyTaglineChanged(nameof(CompanyTagline)); } } } public event PropertyChangedEventHandler CompanyLevelChanged; protected void OnCompanyLevelChanged(string propertyName) => CompanyLevelChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); /// <summary> /// Gets or sets the company level. /// </summary> [JsonProperty] public string CompanyLevel { get => CompanyLevelLabel.Text; set { if (!(CompanyLevelLabel.Text == value)) { if (CompanyLevelLabel.InvokeRequired) { Invoke(new Action(() => CompanyLevelLabel.Text = value)); } else { CompanyLevelLabel.Text = value; } OnCompanyLevelChanged(nameof(CompanyLevel)); } } } } }
41.163934
234
0.566866
[ "Unlicense" ]
Xathz/WubbyCorp
WubbyCorp/CustomControls/Company.cs
12,557
C#
using System; using System.Collections.Generic; using UnityEngine.Assertions; namespace EZAddresser.Editor.Foundation.Observable { /// <summary> /// Subject. /// </summary> /// <typeparam name="T"></typeparam> internal class Subject<T> : IObserver<T>, IObservable<T> { private readonly HashSet<IObserver<T>> _observers = new HashSet<IObserver<T>>(); /// <summary> /// If <see cref="Dispose" /> is already called, return true. /// </summary> public bool DidDispose { get; private set; } /// <summary> /// If <see cref="OnCompleted" /> or <see cref="OnError" /> is already called, return true. /// </summary> public bool DidTerminate { get; private set; } public Exception Error { get; private set; } public IDisposable Subscribe(IObserver<T> observer) { Assert.IsNotNull(observer); Assert.IsFalse(DidDispose); // If already has been terminated. if (DidTerminate) { if (Error != null) { observer.OnError(Error); } else { observer.OnCompleted(); } } _observers.Add(observer); return new Disposable(() => OnObserverDispose(observer)); } public void OnNext(T value) { Assert.IsFalse(DidDispose); Assert.IsFalse(DidTerminate); foreach (var observer in _observers) { observer.OnNext(value); } } public void OnError(Exception error) { Assert.IsNotNull(error); Assert.IsFalse(DidDispose); Assert.IsFalse(DidTerminate); foreach (var observer in _observers) { observer.OnError(error); } DidTerminate = true; Error = error; } public void OnCompleted() { Assert.IsFalse(DidDispose); Assert.IsFalse(DidTerminate); foreach (var observer in _observers) { observer.OnCompleted(); } DidTerminate = true; } public void Dispose() { Assert.IsFalse(DidDispose); _observers.Clear(); DidDispose = true; } private void OnObserverDispose(IObserver<T> value) { Assert.IsTrue(_observers.Contains(value)); _observers.Remove(value); } } }
25.825243
103
0.502632
[ "MIT" ]
Haruma-K/EZAddresser
Packages/com.harumak.ezaddresser/Editor/Foundation/Observable/Subject.cs
2,662
C#
using System.Collections.Generic; namespace Pims.Tools.Core.Keycloak.Models { /// <summary> /// ProtocolMapperModel class, provides a model to represent a keycloak protocol mapper. /// </summary> public class ProtocolMapperModel { #region Properties /// <summary> /// get/set - A primary key for the protocol mapper. /// </summary> public string Id { get; set; } /// <summary> /// get/set - A unique name to identify the protocol mapper. /// </summary> public string Name { get; set; } /// <summary> /// get/set - A protocol. /// </summary> public string Protocol { get; set; } /// <summary> /// get/set - The protocol mapper. /// </summary> public string ProtocolMapper { get; set; } /// <summary> /// get/set - The protocol mapper configuration. /// </summary> public Dictionary<string, string> Config { get; set; } #endregion #region Constructors /// <summary> /// Creates a new instance of a ProtocolMapperModel class. /// </summary> public ProtocolMapperModel() { } #endregion } }
27.555556
92
0.550806
[ "Apache-2.0" ]
Bruce451/PIMS
tools/core/Keycloak/Models/ProtocolMapperModel.cs
1,240
C#
using System; using System.Reflection; namespace AspNetIdentityWebAPIDemo.Areas.HelpPage.ModelDescriptions { public interface IModelDocumentationProvider { string GetDocumentation(MemberInfo member); string GetDocumentation(Type type); } }
22.416667
67
0.762082
[ "Apache-2.0" ]
RyanPan/CodeBook
src/AspNetIdentityWebAPIDemo/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs
269
C#
using System; using System.Collections.Generic; using System.Threading; using System.Linq; using RelaSharp.CLR; namespace RelaSharp.Examples { class SingleCounterReadIndicator : IRelaExample { class ReadIndicator { private CLRAtomicLong _numReaders; public void Arrive() { RInterlocked.Increment(ref _numReaders); } public void Depart() { RInterlocked.Decrement(ref _numReaders); } public bool IsEmpty => RInterlocked.Read(ref _numReaders) == 0; } private static IRelaEngine RE = RelaEngine.RE; public string Name => "A read-indicator implemented as single counter"; public string Description => "1 writing threads, 2 reading threads"; public bool ExpectedToFail => false; public IReadOnlyList<Action> ThreadEntries { get; } private bool _moreConfigurations = true; private int _numReading = 0; private ReadIndicator _readIndicator; public SingleCounterReadIndicator() { ThreadEntries = new Action[]{ReadingThread,WritingThread}.ToList(); } public void OnBegin() { } public void OnFinished() { } private void WritingThread() { int numWrites = 3; for(int i = 0; i < numWrites; ++i) { while(!_readIndicator.IsEmpty) { RE.Yield(); } RE.Assert(_numReading == 0, $"Write in progress but _numReading is {_numReading}"); } } private void ReadingThread() { int numReads = 3; for(int i = 0; i < numReads; ++i) { _readIndicator.Arrive(); _numReading++; _readIndicator.Depart(); _numReading--; } } public void PrepareForIteration() { _numReading = 0; _readIndicator = new ReadIndicator(); } public bool SetNextConfiguration() { var result = _moreConfigurations; _moreConfigurations = false; return result; } } }
25.021277
99
0.519558
[ "MIT" ]
nicknash/RelaSharp
Examples/CLR/SingleCounterReadIndicator.cs
2,352
C#
using System; public delegate R Function<R>(); public struct GenStruct<T> { } public class Gen<T> { public GenStruct<T> delFunc() { return default(GenStruct<T>); } public object makeDel() { return new Function<GenStruct<T>>(delFunc); } } public class main { public static int Main() { Gen<string> gs = new Gen<string>(); object del = gs.makeDel(); return 0; } }
14.8
51
0.56982
[ "MIT" ]
belav/runtime
src/mono/mono/tests/generic-delegate-ctor.2.cs
444
C#
using System.Text.Json.Serialization; namespace Horizon.Payment.Alipay.Domain { /// <summary> /// PaymentAbilityQueryResponse Data Structure. /// </summary> public class PaymentAbilityQueryResponse : AlipayObject { /// <summary> /// 附加信息,json格式字符串。暂时包含信息:是否是支付宝钱包用户,是否是数字娱乐行业活跃用户。 /// </summary> [JsonPropertyName("extra_infos")] public string ExtraInfos { get; set; } /// <summary> /// 接口返回的支付能力等级 /// </summary> [JsonPropertyName("level")] public string Level { get; set; } /// <summary> /// 返回的单据号 /// </summary> [JsonPropertyName("order_id")] public string OrderId { get; set; } } }
25.344828
59
0.571429
[ "Apache-2.0" ]
bluexray/Horizon.Sample
Horizon.Payment.Alipay/Domain/PaymentAbilityQueryResponse.cs
857
C#
/********************************************* 作者:曹旭升 QQ:279060597 访问博客了解详细介绍及更多内容: http://blog.shengxunwei.com **********************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Sheng.SailingEase.Kernal; namespace Sheng.SailingEase.Core { class UIElementDataListColumnEntityTypes : UIElementDataListColumnEntityTypesAbstract { private static InstanceLazy<UIElementDataListColumnEntityTypes> _instance = new InstanceLazy<UIElementDataListColumnEntityTypes>(() => new UIElementDataListColumnEntityTypes()); public static UIElementDataListColumnEntityTypes Instance { get { return _instance.Value; } } private UIElementDataListColumnEntityTypes() { _collection = new UIElementDataListColumnEntityTypeCollection(); _collection.Add(typeof(UIElementDataListTextBoxColumnEntity)); UIElementEntityTypes.Instance.AddRange(_collection); } } }
36.333333
114
0.634862
[ "MIT" ]
ckalvin-hub/Sheng.Winform.IDE
SourceCode/Source/Core/Entity/UIElement/DataList/UIElementDataListColumnEntityTypes.cs
1,138
C#
sealed class LiteralToken : Token { public LiteralToken(object value) : base(null, TokenType.Literal) { _value = value; } public override string Text { get { return _value.ToString(); } } public object Value { get { return _value; } } private readonly object _value; }
16.173913
39
0.532258
[ "MIT" ]
gsscoder/exprengine
src/ExpressionEngine/Parser/LiteralToken.cs
374
C#
using System.Collections.Generic; using Alipay.AopSdk.Core.Response; namespace Alipay.AopSdk.Core.Request { /// <summary> /// AOP API: alipay.acquire.cancel /// </summary> public class AlipayAcquireCancelRequest : IAopRequest<AlipayAcquireCancelResponse> { /// <summary> /// 操作员ID。 /// </summary> public string OperatorId { get; set; } /// <summary> /// 操作员的类型: 0:支付宝操作员 1:商户的操作员 如果传入其它值或者为空,则默认设置为1 /// </summary> public string OperatorType { get; set; } /// <summary> /// 支付宝合作商户网站唯一订单号。 /// </summary> public string OutTradeNo { get; set; } /// <summary> /// 该交易在支付宝系统中的交易流水号。 最短16位,最长64位。 如果同时传了out_trade_no和trade_no,则以trade_no为准。 /// </summary> public string TradeNo { get; set; } #region IAopRequest Members private bool needEncrypt; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "alipay.acquire.cancel"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public IDictionary<string, string> GetParameters() { var parameters = new AopDictionary(); parameters.Add("operator_id", OperatorId); parameters.Add("operator_type", OperatorType); parameters.Add("out_trade_no", OutTradeNo); parameters.Add("trade_no", TradeNo); return parameters; } public AopObject GetBizModel() { return bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
18.956835
84
0.686528
[ "MIT" ]
ArcherTrister/LeXun.Alipay.AopSdk
src/Alipay.AopSdk.Core/Request/AlipayAcquireCancelRequest.cs
2,827
C#
using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System; namespace Xamarin.Android.Tasks { /// <summary> /// This task splits a property into an item group, considering the following delimiters: /// ; - MSBuild default /// , - Historically supported by Xamarin.Android /// </summary> public class SplitProperty : Task { static readonly char [] Delimiters = { ',', ';' }; public string Value { get; set; } [Output] public string [] Output { get; set; } public override bool Execute () { if (Value != null) { Output = Value.Split (Delimiters, StringSplitOptions.RemoveEmptyEntries); } return true; } } }
22.166667
90
0.673684
[ "MIT" ]
06051979/xamarin-android
src/Xamarin.Android.Build.Tasks/Tasks/SplitProperty.cs
667
C#
using Docker.DotNet; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; namespace YS.Docker.Impl.Dotnet { public class ServiceLoader : IServiceLoader { public void LoadServices(IServiceCollection services, IConfiguration configuration) { var options = configuration.GetConfigOrNew<DockerOptions>(); services.AddSingleton<IDockerClient, DockerClient>((sc)=> { var dockerConfig = new DockerClientConfiguration(new Uri(options.EndPoint)); return dockerConfig.CreateClient(); }); } } }
31.142857
92
0.671254
[ "MIT" ]
yscorecore/YS.Docker
YS.Docker.Impl.Dotnet/ServiceLoader.cs
656
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Collections.Generic { internal sealed class ICollectionDebugView<T> { private readonly ICollection<T> _collection; public ICollectionDebugView(ICollection<T> collection) { if (collection == null) { throw new ArgumentNullException("collection"); } _collection = collection; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items { get { T[] items = new T[_collection.Count]; _collection.CopyTo(items, 0); return items; } } } }
26.285714
71
0.583696
[ "MIT" ]
er0dr1guez/corefx
src/System.Collections/src/System/Collections/Generic/ICollectionDebugView.cs
920
C#
using System.Collections.Generic; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using PizzaBox.Domain.Abstracts; using PizzaBox.Domain.Models; namespace PizzaBox.Storage { public class PizzaBoxContext : DbContext { public PizzaBoxContext(DbContextOptions<PizzaBoxContext> options) : base(options){} public DbSet<Store> Stores { get; set; } public DbSet<Topping> Topping {get; set;} public DbSet<Order> Orders{get;set;} public DbSet<Crust> Crust {get; set;} public DbSet<Size> Size {get; set;} public DbSet<User> Users { get; set; } public DbSet<APizzaModel> Pizzas {get;set;} protected override void OnModelCreating(ModelBuilder builder) { builder.Entity<Store>().HasKey(s => s.EntityId); builder.Entity<User>().HasKey(u => u.EntityId); builder.Entity<APizzaModel>().HasKey(p => p.EntityId); builder.Entity<Order>().HasKey(o => o.EntityId); builder.Entity<Topping>().HasKey(t => t.EntityId); builder.Entity<Size>().HasKey(v => v.EntityId); builder.Entity<Crust>().HasKey(c => c.EntityId); builder.Entity<User>().Property(c=> c.EntityId).ValueGeneratedNever(); builder.Entity<Order>().Property(c=> c.EntityId).ValueGeneratedNever(); builder.Entity<Crust>().Property(c=> c.EntityId).ValueGeneratedNever(); builder.Entity<Size>().Property(c=> c.EntityId).ValueGeneratedNever(); builder.Entity<Topping>().Property(c=> c.EntityId).ValueGeneratedNever(); builder.Entity<Store>().Property(c=> c.EntityId).ValueGeneratedNever(); builder.Entity<APizzaModel>().Property(c=> c.EntityId).ValueGeneratedNever(); SeedData(builder); } protected void SeedData(ModelBuilder builder) { builder.Entity<Store>(b => { b.HasData(new List<Store>{ new Store() {Name = "One"}, new Store() {Name = "Two"}, new Store() {Name = "Three"} }); }); builder.Entity<User>().HasData(new List<User> { new User() {Name = "Isaiah"}, new User() {Name = "Fred"}, new User() {Name = "Other"} }); builder.Entity<Topping>().HasData(new List<Topping> { new Topping(){name ="Pepperoni", price = 2}, new Topping(){name ="Pineapple",price = 6}, new Topping(){name ="Bacon",price = 3}, new Topping(){name ="Gold",price = 100}, new Topping(){name ="Jalapenos",price = 60}, new Topping(){name = "Cheese",price = 1} }); builder.Entity<Size>().HasData(new List<Size> { new Size{name ="Small",price = 12}, new Size{name ="Medium",price =16}, new Size{name ="Large",price = 22}, new Size{name ="X-Large",price = 28} }); builder.Entity<Crust>().HasData(new List<Crust> { new Crust{name ="Thin",price = 2}, new Crust{name ="Thick",price = 3}, new Crust{name ="Stuffed",price =5} }); } } }
38.382022
91
0.537471
[ "MIT" ]
Saixah/p1
aspnet/PizzaBox.Storage/PizzaBoxContext.cs
3,416
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Fx.Portability.ObjectModel; using Microsoft.Fx.Portability.Proxy; using Microsoft.Fx.Portability.Resources; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Microsoft.Fx.Portability { public sealed class ApiPortService : IDisposable, IApiPortService { internal static class Endpoints { internal const string Analyze = "/api/analyze"; internal const string Targets = "/api/target"; internal const string UsedApi = "/api/usage"; internal const string FxApi = "/api/fxapi"; internal const string FxApiSearch = "/api/fxapi/search"; internal const string ResultFormat = "/api/resultformat"; internal const string DefaultResultFormat = "/api/resultformat/default"; } private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(10); private readonly CompressedHttpClient _client; public ApiPortService(string endpoint, ProductInformation info, IProxyProvider proxyProvider = null) : this(endpoint, BuildMessageHandler(endpoint, proxyProvider), info) { } public ApiPortService(string endpoint, HttpMessageHandler httpMessageHandler, ProductInformation info) { if (string.IsNullOrWhiteSpace(endpoint)) { throw new ArgumentOutOfRangeException(nameof(endpoint), endpoint, LocalizedStrings.MustBeValidEndpoint); } if (info == null) { throw new ArgumentNullException(nameof(info)); } _client = new CompressedHttpClient(info, httpMessageHandler) { BaseAddress = new Uri(endpoint), Timeout = Timeout }; } public async Task<ServiceResponse<AnalyzeResponse>> SendAnalysisAsync(AnalyzeRequest a) { return await _client.CallAsync<AnalyzeRequest, AnalyzeResponse>(HttpMethod.Post, Endpoints.Analyze, a); } public async Task<ServiceResponse<IEnumerable<ReportingResultWithFormat>>> SendAnalysisAsync(AnalyzeRequest a, IEnumerable<string> format) { var formatInformation = await GetResultFormatsAsync(format); return await _client.CallAsync(HttpMethod.Post, Endpoints.Analyze, a, formatInformation); } public async Task<ServiceResponse<IEnumerable<AvailableTarget>>> GetTargetsAsync() { return await _client.CallAsync<IEnumerable<AvailableTarget>>(HttpMethod.Get, Endpoints.Targets); } public async Task<ServiceResponse<AnalyzeResponse>> GetAnalysisAsync(string submissionId) { var submissionUrl = UrlBuilder.Create(Endpoints.Analyze).AddPath(submissionId).Url; return await _client.CallAsync<AnalyzeResponse>(HttpMethod.Get, submissionUrl); } public async Task<ServiceResponse<ReportingResultWithFormat>> GetAnalysisAsync(string submissionId, string format) { var formatInformation = await GetResultFormatsAsync(string.IsNullOrWhiteSpace(format) ? null : new[] { format }); var submissionUrl = UrlBuilder.Create(Endpoints.Analyze).AddPath(submissionId).Url; return await _client.CallAsync(HttpMethod.Get, submissionUrl, formatInformation); } public async Task<ServiceResponse<ApiInformation>> GetApiInformationAsync(string docId) { string sendAnalysis = UrlBuilder .Create(Endpoints.FxApi) .AddQuery("docId", docId) .Url; return await _client.CallAsync<ApiInformation>(HttpMethod.Get, sendAnalysis); } public async Task<ServiceResponse<IReadOnlyCollection<ApiDefinition>>> SearchFxApiAsync(string query, int? top = null) { var url = UrlBuilder .Create(Endpoints.FxApiSearch) .AddQuery("q", query) .AddQuery("top", top); return await _client.CallAsync<IReadOnlyCollection<ApiDefinition>>(HttpMethod.Get, url.Url); } /// <summary> /// Returns a list of valid DocIds from the PortabilityService /// </summary> /// <param name="docIds">Enumerable of DocIds</param> public async Task<ServiceResponse<IReadOnlyCollection<ApiInformation>>> QueryDocIdsAsync(IEnumerable<string> docIds) { return await _client.CallAsync<IEnumerable<string>, IReadOnlyCollection<ApiInformation>>(HttpMethod.Post, Endpoints.FxApi, docIds); } public async Task<ServiceResponse<IEnumerable<ResultFormatInformation>>> GetResultFormatsAsync() { return await _client.CallAsync<IEnumerable<ResultFormatInformation>>(HttpMethod.Get, Endpoints.ResultFormat); } public async Task<ServiceResponse<ResultFormatInformation>> GetDefaultResultFormatAsync() { return await _client.CallAsync<ResultFormatInformation>(HttpMethod.Get, Endpoints.DefaultResultFormat); } public void Dispose() { _client.Dispose(); } private async Task<IEnumerable<ResultFormatInformation>> GetResultFormatsAsync(IEnumerable<string> formats) { if (!formats?.Any() ?? true) //no "resultFormat" string option provider by user { var defaultFormat = await GetDefaultResultFormatAsync(); return new[] { defaultFormat.Response }; } else { var requestedFormats = new HashSet<string>(formats, StringComparer.OrdinalIgnoreCase); var resultFormats = await GetResultFormatsAsync(); var formatInformation = resultFormats.Response .Where(r => requestedFormats.Contains(r.DisplayName)); var unknownFormats = requestedFormats .Except(formatInformation.Select(f => f.DisplayName), StringComparer.OrdinalIgnoreCase); if (unknownFormats.Any()) { throw new UnknownReportFormatException(unknownFormats); } return formatInformation; } } private static HttpMessageHandler BuildMessageHandler(string endpoint, IProxyProvider proxyProvider) { if (string.IsNullOrWhiteSpace(endpoint)) { throw new ArgumentOutOfRangeException(nameof(endpoint), endpoint, LocalizedStrings.MustBeValidEndpoint); } // Create the URI directly from a string (rather than using a hard-coded scheme or port) because // even though production use of ApiPort should always use HTTPS, developers using a non-production // portability service URL (via the -e command line parameter) may need to specify a different // scheme or port. var uri = new Uri(endpoint); var clientHandler = new HttpClientHandler { #if !FEATURE_SERVICE_POINT_MANAGER SslProtocols = CompressedHttpClient.SupportedSSLProtocols, #endif Proxy = proxyProvider?.GetProxy(uri), AutomaticDecompression = (DecompressionMethods.GZip | DecompressionMethods.Deflate) }; if (clientHandler.Proxy == null) { return clientHandler; } return new ProxyAuthenticationHandler(clientHandler, proxyProvider); } } }
40.910995
146
0.645636
[ "MIT" ]
G-Research/dotnet-apiport
src/lib/Microsoft.Fx.Portability/ApiPortService.cs
7,816
C#
using System; using Robust.Shared.Analyzers; using Robust.Shared.Audio.Midi; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; namespace Content.Shared.Instruments; [NetworkedComponent, Friend(typeof(SharedInstrumentSystem))] public class SharedInstrumentComponent : Component { public override string Name => "Instrument"; [ViewVariables] public bool Playing { get; set; } [ViewVariables] public uint LastSequencerTick { get; set; } [DataField("program"), ViewVariables(VVAccess.ReadWrite)] public byte InstrumentProgram { get; set; } [DataField("bank"), ViewVariables(VVAccess.ReadWrite)] public byte InstrumentBank { get; set; } [DataField("allowPercussion"), ViewVariables(VVAccess.ReadWrite)] public bool AllowPercussion { get; set; } [DataField("allowProgramChange"), ViewVariables(VVAccess.ReadWrite)] public bool AllowProgramChange { get ; set; } [DataField("respectMidiLimits"), ViewVariables(VVAccess.ReadWrite)] public bool RespectMidiLimits { get; set; } [ViewVariables(VVAccess.ReadWrite)] public bool DirtyRenderer { get; set; } } /// <summary> /// This message is sent to the client to completely stop midi input and midi playback. /// </summary> [Serializable, NetSerializable] public class InstrumentStopMidiEvent : EntityEventArgs { public EntityUid Uid { get; } public InstrumentStopMidiEvent(EntityUid uid) { Uid = uid; } } /// <summary> /// This message is sent to the client to start the synth. /// </summary> [Serializable, NetSerializable] public class InstrumentStartMidiEvent : EntityEventArgs { public EntityUid Uid { get; } public InstrumentStartMidiEvent(EntityUid uid) { Uid = uid; } } /// <summary> /// This message carries a MidiEvent to be played on clients. /// </summary> [Serializable, NetSerializable] public class InstrumentMidiEventEvent : EntityEventArgs { public EntityUid Uid { get; } public MidiEvent[] MidiEvent { get; } public InstrumentMidiEventEvent(EntityUid uid, MidiEvent[] midiEvent) { Uid = uid; MidiEvent = midiEvent; } } [Serializable, NetSerializable] public class InstrumentState : ComponentState { public bool Playing { get; } public byte InstrumentProgram { get; } public byte InstrumentBank { get; } public bool AllowPercussion { get; } public bool AllowProgramChange { get; } public bool RespectMidiLimits { get; } public InstrumentState(bool playing, byte instrumentProgram, byte instrumentBank, bool allowPercussion, bool allowProgramChange, bool respectMidiLimits, uint sequencerTick = 0) { Playing = playing; InstrumentProgram = instrumentProgram; InstrumentBank = instrumentBank; AllowPercussion = allowPercussion; AllowProgramChange = allowProgramChange; RespectMidiLimits = respectMidiLimits; } } [NetSerializable, Serializable] public enum InstrumentUiKey { Key, }
27.823009
180
0.719148
[ "MIT" ]
Antares-30XX/Antares
Content.Shared/Instruments/SharedInstrumentComponent.cs
3,144
C#
using Nuki.Communication.API; using Nuki.Communication.SemanticTypes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Nuki.Communication.Connection.Bluetooth.Commands.Response { public class RecieveConfigCommand : RecieveBaseCommand, INukiConfigMessage { public UniqueClientID UniqueClientID { get { return GetData<UniqueClientID>(nameof(UniqueClientID)); } } public string Name { get { return GetData<string>(nameof(Name)); } } /// <summary> /// The latitude of the Nuki Smartlock’s geoposition /// </summary> public float Latitude { get { return GetData<float>(nameof(Latitude)); } } /// <summary> /// The longitude of the Nuki Smartlock’s geoposition. /// </summary> public float Longitude { get { return GetData<float>(nameof(Longitude)); } } /// <summary> /// This flag indicates whether or not the door shall /// be unlatched bymanually operatinga doorhandle fromthe outside. /// </summary> public bool AutoUnlatch { get { return GetData<bool>(nameof(AutoUnlatch)); } } /// <summary> /// This flag indicates whether or not the pairing mode should beenabled. /// </summary> public bool PairingEnabled  { get { return GetData<bool>(nameof(PairingEnabled)); } } /// <summary> /// This flag indicates whether or not the button should be enabled. /// </summary> public bool ButtonEnabled  { get { return GetData<bool>(nameof(ButtonEnabled)); } } /// <summary> /// This flag indicates whether or not the LED should be enabled to signal an unlocked door. /// </summary> public bool LEDEnabled  { get { return GetData<bool>(nameof(LEDEnabled)); } } /// <summary> /// The LED brightness level. Possible values are 0 to 5  /// 0 = off, …, 5 = max /// </summary> public byte LEDBrightness { get { return GetData<byte>(nameof(LEDBrightness)); } } /// <summary> /// /// </summary> public NukiTimeStamp CurrentTime { get { return GetData<NukiTimeStamp>(nameof(CurrentTime)); } } public Int16 UTCOffset { get { return GetData<Int16>(nameof(UTCOffset)); } } public NukiDSTSetting DSTMode { get { return GetData<NukiDSTSetting>(nameof(DSTMode)); } } /// <summary> /// This flag indicates whether or not a Nuki Fob hasbeen pairedto thisNuki. /// </summary> public bool HasFob  { get { return GetData<bool>(nameof(HasFob)); } } /// <summary> /// The desired action, if a Nuki Fob is pressed once. /// </summary> public NukiFobAction FobAction1 { get { return GetData<NukiFobAction>(nameof(FobAction1)); } } /// <summary> /// The desired action, if a Nuki Fob is pressed twice. /// </summary> public NukiFobAction FobAction2 { get { return GetData<NukiFobAction>(nameof(FobAction2)); } } /// <summary> /// The desired action, if a Nuki Fob is pressed three times. /// </summary> public NukiFobAction FobAction3 { get { return GetData<NukiFobAction>(nameof(FobAction3)); } } public RecieveConfigCommand() : base(NukiCommandType.Config, InitFields()) { } protected static IEnumerable<FieldParserBase> InitFields() { yield return new FieldParser<UniqueClientID>(nameof(UniqueClientID), 4, (buffer, start, length) => new UniqueClientID(BitConverter.ToUInt32(buffer, start))); yield return new FieldParser<string>(nameof(Name), 32, (b, s, l) => Encoding.ASCII.GetString(b, s, l)); yield return new FieldParser<float>(nameof(Latitude), 4, (b, s, l) => BitConverter.ToSingle(b,s)); yield return new FieldParser<float>(nameof(Longitude), 4, (b, s, l) => BitConverter.ToSingle(b, s)); yield return new FieldParser<bool>(nameof(AutoUnlatch), 1, (b, s, l) => b[s] != 0); yield return new FieldParser<bool>(nameof(PairingEnabled), 1, (b, s, l) => b[s] != 0); yield return new FieldParser<bool>(nameof(ButtonEnabled), 1, (b, s, l) => b[s] != 0); yield return new FieldParser<bool>(nameof(LEDEnabled), 1, (b, s, l) => b[s] != 0); yield return new FieldParser<byte>(nameof(LEDBrightness), 1, (b, s, l) => b[s]); yield return new FieldParser<NukiTimeStamp>(nameof(CurrentTime), 7, (b, s, l) => NukiTimeStamp.FromBytes(b, s)); yield return new FieldParser<Int16>(nameof(UTCOffset), 2, (b, s, l) => BitConverter.ToInt16(b, s)); yield return new FieldParser<NukiDSTSetting>(nameof(DSTMode), 1, (b, s, l) => (NukiDSTSetting) b[s]); yield return new FieldParser<bool>(nameof(HasFob), 1, (b, s, l) => b[s] != 0); yield return new FieldParser<NukiFobAction>(nameof(FobAction1), 1, (b, s, l) => (NukiFobAction)b[s]); yield return new FieldParser<NukiFobAction>(nameof(FobAction2), 1, (b, s, l) => (NukiFobAction)b[s]); yield return new FieldParser<NukiFobAction>(nameof(FobAction3), 1, (b, s, l) => (NukiFobAction)b[s]); } } }
53.414141
124
0.619138
[ "Apache-2.0" ]
BoBiene/Nuki
Nuki.Communication/Connection/Bluetooth/Commands/Response/RecieveConfigCommand.cs
5,387
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using GraphQL; using Indico.Exception; using Indico.Jobs; using Indico.Storage; using Newtonsoft.Json.Linq; namespace Indico.Mutation { [Obsolete("This is the V1 Version of the object. Please use V2 where possible.")] /// <summary> /// OCR PDF, TIF, JPG and PNG files /// </summary> public class DocumentExtraction : IMutation<List<Job>> { private readonly IndicoClient _client; /// <summary> /// List of files to process /// </summary> public List<string> Files { get; set; } /// <summary> /// Get/Set the JSON Configuration for DocumentExtraction /// </summary> public JObject JsonConfig { get; set; } /// <summary> /// DocumentExtraction constructor /// <param name="client">IndicoClient client</param> /// </summary> public DocumentExtraction(IndicoClient client) => _client = client; private async Task<JArray> Upload(List<string> filePaths) { var uploadRequest = new UploadFile(_client) { Files = filePaths }; var arr = await uploadRequest.Call(); return arr; } private async Task<GraphQLResponse<dynamic>> ExecRequest(CancellationToken cancellationToken = default) { JArray fileMetadata; var files = new List<object>(); fileMetadata = await Upload(Files); foreach (JObject uploadMeta in fileMetadata) { var meta = new JObject { { "name", (string)uploadMeta.GetValue("name") }, { "path", (string)uploadMeta.GetValue("path") }, { "upload_type", (string)uploadMeta.GetValue("upload_type") } }; var file = new { filename = (string)uploadMeta.GetValue("name"), filemeta = meta.ToString() }; files.Add(file); } string query = @" mutation DocumentExtraction($files: [FileInput]!, $jsonConfig: JSONString) { documentExtraction(files: $files, jsonConfig: $jsonConfig) { jobIds } } "; var request = new GraphQLRequest() { Query = query, OperationName = "DocumentExtraction", Variables = new { files, JsonConfig = JsonConfig.ToString() } }; return await _client.GraphQLHttpClient.SendMutationAsync<dynamic>(request, cancellationToken); } /// <summary> /// Executes OCR and returns Jobs /// <returns>List of Jobs</returns> /// </summary> public async Task<List<Job>> Exec(CancellationToken cancellationToken = default) { var response = await ExecRequest(cancellationToken); if (response.Errors != null) { throw new GraphQLException(response.Errors); } var jobIds = (JArray)response.Data.documentExtraction.jobIds; return jobIds.Select(id => new Job(_client.GraphQLHttpClient, (string)id)).ToList(); } /// <summary> /// Executes a single OCR request /// <param name="path">pathname of the file to OCR</param> /// <param name="cancellationToken">Cancellation token to stop execution.</param> /// <returns>Job</returns> /// </summary> public async Task<Job> Exec(string path, CancellationToken cancellationToken = default) { Files = new List<string>() { path }; var response = await ExecRequest(cancellationToken); if (response.Errors != null) { throw new GraphQLException(response.Errors); } var jobIds = (JArray)response.Data.documentExtraction.jobIds; return new Job(_client.GraphQLHttpClient, (string)jobIds[0]); } } }
33.763359
112
0.52747
[ "MIT" ]
IndicoDataSolutions/indico-client-csharp
Indico/Mutation/DocumentExtraction.cs
4,425
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using shoppinstore.Models; using shoppinstore.Persistence; namespace shoppinstore.Repository { public interface IOrderRepository:IRepository<Order> { void AddRanges(IEnumerable<Order> entities); void AddProductToCart(Product product, int quantity); List<CartItems> ShowCartItems(); void RemoveProductFromList(int id); void clearShoppingCart(); int? CalculateCost(int? price); int? ReduceCartCostIfProductRemoved(int? price); List<Order> OrderList(int id,string userID,int ShippingID); } }
28.416667
67
0.727273
[ "Apache-2.0" ]
bakido/shoppinstore
shoppinstore/Repository/IOrderRepository.cs
684
C#
/* * Copyright 2020 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 ssm-2014-11-06.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.SimpleSystemsManagement.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SimpleSystemsManagement.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for InvocationDoesNotExistException Object /// </summary> public class InvocationDoesNotExistExceptionUnmarshaller : IErrorResponseUnmarshaller<InvocationDoesNotExistException, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public InvocationDoesNotExistException Unmarshall(JsonUnmarshallerContext context) { return this.Unmarshall(context, new ErrorResponse()); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <param name="errorResponse"></param> /// <returns></returns> public InvocationDoesNotExistException Unmarshall(JsonUnmarshallerContext context, ErrorResponse errorResponse) { context.Read(); InvocationDoesNotExistException unmarshalledObject = new InvocationDoesNotExistException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { } return unmarshalledObject; } private static InvocationDoesNotExistExceptionUnmarshaller _instance = new InvocationDoesNotExistExceptionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static InvocationDoesNotExistExceptionUnmarshaller Instance { get { return _instance; } } } }
35.988235
153
0.680941
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/SimpleSystemsManagement/Generated/Model/Internal/MarshallTransformations/InvocationDoesNotExistExceptionUnmarshaller.cs
3,059
C#
using System.Collections.Generic; using System.Linq; using PizzaBox.Domain.Abstracts; namespace PizzaBox.Domain.Models { public class Order : AModel { public Customer Customer { get; set; } public AStore Store { get; set; } public APizza Pizza { get; set; } public double TotalCost { get { return Pizza.Crust.price + Pizza.Size.price + Pizza.Toppings.Sum(t => t.price); } } } }
30.142857
123
0.661137
[ "MIT" ]
MrJJLand/project_pizzabox
PizzaBox.Domain/Models/Order.cs
422
C#
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace UI { /// <summary> /// Provides a thread-safe wrapper of ObservableCollection that is still observable. /// Additionally, the contents of the wrapped ObservableCollection are exposed by ToString() /// for easy viewing in text-elements. /// </summary> public class ThreadsafeObservableStringCollection : ICollection<string>, INotifyCollectionChanged, INotifyPropertyChanged { private readonly object _sync = new object(); private readonly ObservableCollection<string> _collection = new ObservableCollection<string>(); private StringBuilder _builder = new StringBuilder(); public ThreadsafeObservableStringCollection() { //Propagate events from the observable collection _collection.CollectionChanged += (sender, args) => CollectionChanged?.Invoke(sender, args); } public override string ToString() { lock (_sync) { if(_builder == null) PopulateStringBuilder(); return _builder.ToString(); } } private void PopulateStringBuilder() { _builder = new StringBuilder(); foreach (var item in _collection) { _builder.AppendLine(item); } } private void AddToBuilder(string item) { if (_builder == null) { PopulateStringBuilder(); } else { _builder.AppendLine(item); } } #region Events public event NotifyCollectionChangedEventHandler CollectionChanged; public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion #region ICollection<> public IEnumerator<string> GetEnumerator() { lock (_sync) { return new List<string>(_collection).GetEnumerator(); } } IEnumerator IEnumerable.GetEnumerator() { lock (_sync) { return new List<string>(_collection).GetEnumerator(); } } public void Add(string item) { lock (_sync) { _collection.Add(item); AddToBuilder(item); OnPropertyChanged(nameof(Count)); } } public void Clear() { lock (_sync) { _collection.Clear(); _builder = null; OnPropertyChanged(nameof(Count)); } } public bool Contains(string item) { lock (_sync) { return _collection.Contains(item); } } public void CopyTo(string[] array, int arrayIndex) { lock (_sync) { _collection.CopyTo(array, arrayIndex); } } public bool Remove(string item) { lock (_sync) { var val = _collection.Remove(item); _builder = null; OnPropertyChanged(nameof(Count)); return val; } } public int Count => _collection.Count; public bool IsReadOnly => false; #endregion } }
26.452703
125
0.547382
[ "MIT" ]
Jameak/ImageDownloader
src/UI/ThreadsafeObservableStringCollection.cs
3,917
C#
using System; using Aop.Api.Domain; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: alipay.open.servicemarket.commodity.shop.offline /// </summary> public class AlipayOpenServicemarketCommodityShopOfflineRequest : IAopRequest<AlipayOpenServicemarketCommodityShopOfflineResponse> { /// <summary> /// 下架商户门店 /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.open.servicemarket.commodity.shop.offline"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
24.019802
134
0.617477
[ "MIT" ]
erikzhouxin/CSharpSolution
OSS/Alipay/F2FPayDll/Projects/alipay-sdk-NET20161213174056/Request/AlipayOpenServicemarketCommodityShopOfflineRequest.cs
2,438
C#
using KeyManagement.Repository.Entities; using Microsoft.EntityFrameworkCore; namespace KeyManagement.Repository { public class DataContext : DbContext { public DataContext(DbContextOptions<DataContext> options) : base(options) { } public DbSet<Key> Keys { get; set; } public DbSet<KeySet> KeySets { get; set; } public DbSet<KeyEvent> KeyEvents { get; set; } } }
25.058824
81
0.661972
[ "Apache-2.0" ]
scottjones4k/keymanagement
KeyManagement.Repository/DataContext.cs
428
C#
using pbrt.Core; using pbrt.Films; using pbrt.Media; namespace pbrt.Cameras { public class OrthographicCamera : ProjectiveCamera { public Vector3F DxCamera { get; set; } public Vector3F DyCamera { get; set; } public OrthographicCamera(Transform cameraToWorld, Bounds2F screenWindow, Film film, Medium medium, float lensRadius=0f, float focalDistance=1e6f, float shutterOpen = 0f, float shutterClose = 1f) : base(cameraToWorld, Orthographic(0, 1), screenWindow, shutterOpen, shutterClose, lensRadius, focalDistance, film, medium) { DxCamera = RasterToCamera.Apply(new Vector3F(1, 0, 0)); DyCamera = RasterToCamera.Apply(new Vector3F(0, 1, 0)); } public static Transform Orthographic(float zNear, float zFar) { var translate = Transform.Translate(new Vector3F(0, 0, -zNear)); var scale = Transform.Scale(1, 1, 1 / (zFar - zNear)); return scale * translate; } public override float GenerateRay(CameraSample sample, out Ray ray) { // Compute raster and camera sample positions Point3F pFilm = new Point3F(sample.PFilm.X, sample.PFilm.Y, 0); Point3F pCamera = RasterToCamera.Apply(pFilm); ray = new Ray(pCamera, new Vector3F(0, 0, 1)); // Modify ray for depth of field if (LensRadius > 0) { // Sample point on lens Point2F pLens = LensRadius * MathUtils.ConcentricSampleDisk(sample.PLens); // Compute point on plane of focus float ft = FocalDistance / ray.D.Z; Point3F pFocus = ray.At(ft); // Update ray for effect of lens ray.O = new Point3F(pLens.X, pLens.Y, 0); ray.D = (pFocus - ray.O).Normalized(); } ray.Time = MathUtils.Lerp(sample.Time, ShutterOpen, ShutterClose); ray.Medium = Medium; ray = CameraToWorld.Apply(ray); return 1; } public override float GenerateRayDifferential(CameraSample sample, out RayDifferential ray) { // Compute main orthographic viewing ray // Compute raster and camera sample positions>> Point3F pFilm = new Point3F(sample.PFilm.X, sample.PFilm.Y, 0); Point3F pCamera = RasterToCamera.Apply(pFilm); ray = new RayDifferential(pCamera, new Vector3F(0, 0, 1)); //Modify ray for depth of field //Compute ray differentials for OrthographicCamera if (LensRadius > 0) { // Compute OrthographicCamera ray differentials accounting for lens // Sample point on lens Point2F pLens = LensRadius * MathUtils.ConcentricSampleDisk(sample.PLens); float ft = FocalDistance / ray.D.Z; var vectorFocusZ = new Vector3F(0, 0, ft); Point3F pFocusX = pCamera + DxCamera + vectorFocusZ; ray.RxOrigin = new Point3F(pLens.X, pLens.Y, 0); ray.RxDirection = (pFocusX - ray.RxOrigin).Normalized(); Point3F pFocusY = pCamera + DyCamera + vectorFocusZ; ray.RyOrigin = new Point3F(pLens.X, pLens.Y, 0); ray.RyDirection = (pFocusY - ray.RyOrigin).Normalized(); } else { ray.RxOrigin = ray.O + DxCamera; ray.RyOrigin = ray.O + DyCamera; ray.RxDirection = ray.RyDirection = ray.D; } ray.Time = MathUtils.Lerp(sample.Time, ShutterOpen, ShutterClose); ray.HasDifferentials = true; ray.Medium = Medium; ray = CameraToWorld.Apply(ray); return 1; } } }
40.153061
135
0.563659
[ "Unlicense" ]
fremag/pbrt
pbrt/pbrt/Cameras/OrthographicCamera.cs
3,935
C#
// Copyright © 2015 - Present RealDimensions Software, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // 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 chocolatey.package.validator.infrastructure.app.rules { using NuGet; using infrastructure.rules; using utility; public class IconUrlValidRequirement : BasePackageRule { public override string ValidationFailureMessage { get { return @"The IconUrl element in the nuspec file should be a valid Url. Please correct this [More...](https://docs.chocolatey.org/en-us/community-repository/moderation/package-validator/rules/cpmr0031)"; } } public override PackageValidationOutput is_valid(IPackage package) { var valid = true; if (package.IconUrl != null) { valid = Utility.url_is_valid(package.IconUrl, ProxyAddress, ProxyUserName, ProxyPassword); } return valid; } } }
35.357143
196
0.672727
[ "Apache-2.0" ]
chocolatey/package-validator
src/chocolatey.package.validator/infrastructure.app/rules/IconUrlValidRequirement.cs
1,488
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CreateBlock { public Mesh blockMesh; private CreateChunk chunk; // thoughts /* - find all top blocks after first chunk data pass - determine which blocks are subject to have a smoothed block added on top - if the block above the top block does not have any neighbors, do not add a smoothing block - if the block above the top block DOES have neighbors, a smoothing block should be added */ public CreateBlock(Vector3 position, CreateChunk.BlockData blockData, CreateChunk chunk){ this.chunk = chunk; if (blockData.BlockType == MeshController.BlockType.AIR || blockData.Smoothed) return; // no need to check if quads should be generated List<CreateQuad> quads = new List<CreateQuad>(); //create quad array to pass all sides // generate regular block if (chunk.NeighCheck((int)position.x, (int)position.y - 1, (int)position.z) != MeshController.BlockState.OTHER) quads.Add(new CreateQuad(MeshController.BlockSide.BOTTOM, position, blockData.BlockType)); if (chunk.NeighCheck((int)position.x, (int)position.y + 1, (int)position.z) != MeshController.BlockState.OTHER) quads.Add(new CreateQuad(MeshController.BlockSide.TOP, position, blockData.BlockType)); if (chunk.NeighCheck((int)position.x - 1, (int)position.y, (int)position.z) != MeshController.BlockState.OTHER) quads.Add(new CreateQuad(MeshController.BlockSide.LEFT, position, blockData.BlockType)); if (chunk.NeighCheck((int)position.x + 1, (int)position.y, (int)position.z) != MeshController.BlockState.OTHER) quads.Add(new CreateQuad(MeshController.BlockSide.RIGHT, position, blockData.BlockType)); if (chunk.NeighCheck((int)position.x, (int)position.y, (int)position.z + 1) != MeshController.BlockState.OTHER) quads.Add(new CreateQuad(MeshController.BlockSide.FRONT, position, blockData.BlockType)); if (chunk.NeighCheck((int)position.x, (int)position.y, (int)position.z - 1) != MeshController.BlockState.OTHER) quads.Add(new CreateQuad(MeshController.BlockSide.BACK, position, blockData.BlockType)); if (quads.Count == 0) return; // no need to allocate memory for face generation Mesh[] sideMeshes = new Mesh[quads.Count]; //assign quads to meshes for (int i = 0; i < quads.Count; i++){ sideMeshes[i] = quads[i].mesh; } blockMesh = MeshController.MergeMeshes(sideMeshes); //merge meshes blockMesh.name = $"Cube_{position.x}_{position.y}_{position.z}"; } }
61.162791
210
0.706844
[ "Apache-2.0" ]
rambo5x/Senior-Project
SeniorProject3D/Assets/Scripts/Generation/CreateBlock.cs
2,630
C#
#region license // Copyright (c) 2020 rubicon IT GmbH, www.rubicon.eu // Copyright (c) 2005 - 2009 Ayende Rahien (ayende@ayende.com) // 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 Ayende Rahien 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 OWNER 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. #endregion using System; using System.IO; using System.Reflection; using NUnit.Framework; using Rhino.Mocks.Exceptions; using Rhino.Mocks.Interfaces; namespace Rhino.Mocks.Tests { public delegate object ObjectDelegateWithNoParams(); public class MockingDelegatesTests { private MockRepository mocks; private delegate object ObjectDelegateWithNoParams(); private delegate void VoidDelegateWithParams(string a); private delegate string StringDelegateWithParams(int a, string b); private delegate int IntDelegateWithRefAndOutParams(ref int a, out string b); [SetUp] public void SetUp() { mocks = new MockRepository(); } [Test] public void CallingMockedDelegatesWithoutOn() { ObjectDelegateWithNoParams d1 = (ObjectDelegateWithNoParams)mocks.StrictMock(typeof(ObjectDelegateWithNoParams)); Expect.Call(d1()).Return(1); mocks.ReplayAll(); Assert.AreEqual(1, d1()); } [Test] public void MockTwoDelegatesWithTheSameName() { ObjectDelegateWithNoParams d1 = (ObjectDelegateWithNoParams)mocks.StrictMock(typeof(ObjectDelegateWithNoParams)); Tests.ObjectDelegateWithNoParams d2 = (Tests.ObjectDelegateWithNoParams)mocks.StrictMock(typeof(Tests.ObjectDelegateWithNoParams)); Expect.On(d1).Call(d1()).Return(1); Expect.On(d2).Call(d2()).Return(2); mocks.ReplayAll(); Assert.AreEqual(1, d1()); Assert.AreEqual(2, d2()); mocks.VerifyAll(); } [Test] public void MockObjectDelegateWithNoParams() { ObjectDelegateWithNoParams d = (ObjectDelegateWithNoParams)mocks.StrictMock(typeof(ObjectDelegateWithNoParams)); Expect.On(d).Call(d()).Return("abc"); Expect.On(d).Call(d()).Return("def"); mocks.Replay(d); Assert.AreEqual("abc", d()); Assert.AreEqual("def", d()); try { d(); Assert.False(true, "Expected an expectation violation to occur."); } catch (ExpectationViolationException) { // Expected. } } [Test] public void MockVoidDelegateWithNoParams() { VoidDelegateWithParams d = (VoidDelegateWithParams)mocks.StrictMock(typeof(VoidDelegateWithParams)); d("abc"); d("efg"); mocks.Replay(d); d("abc"); d("efg"); try { d("hij"); Assert.False(true, "Expected an expectation violation to occur."); } catch (ExpectationViolationException) { // Expected. } } [Test] public void MockStringDelegateWithParams() { StringDelegateWithParams d = (StringDelegateWithParams)mocks.StrictMock(typeof(StringDelegateWithParams)); Expect.On(d).Call(d(1, "111")).Return("abc"); Expect.On(d).Call(d(2, "222")).Return("def"); mocks.Replay(d); Assert.AreEqual("abc", d(1, "111")); Assert.AreEqual("def", d(2, "222")); try { d(3, "333"); Assert.False(true, "Expected an expectation violation to occur."); } catch (ExpectationViolationException) { // Expected. } } [Test] public void MockIntDelegateWithRefAndOutParams() { IntDelegateWithRefAndOutParams d = (IntDelegateWithRefAndOutParams)mocks.StrictMock(typeof(IntDelegateWithRefAndOutParams)); int a = 3; string b = null; Expect.On(d).Call(d(ref a, out b)).Do(new IntDelegateWithRefAndOutParams(Return1_Plus2_A)); mocks.Replay(d); Assert.AreEqual(1, d(ref a, out b)); Assert.AreEqual(5, a); Assert.AreEqual("A", b); try { d(ref a, out b); Assert.False(true, "Expected an expectation violation to occur."); } catch (ExpectationViolationException) { // Expected. } } [Test] public void InterceptsDynamicInvokeAlso() { IntDelegateWithRefAndOutParams d = (IntDelegateWithRefAndOutParams)mocks.StrictMock(typeof(IntDelegateWithRefAndOutParams)); int a = 3; string b = null; Expect.On(d).Call(d(ref a, out b)).Do(new IntDelegateWithRefAndOutParams(Return1_Plus2_A)); mocks.Replay(d); object[] args = new object[] { 3, null }; Assert.AreEqual(1, d.DynamicInvoke(args)); Assert.AreEqual(5, args[0]); Assert.AreEqual("A", args[1]); try { d.DynamicInvoke(args); Assert.False(true, "Expected an expectation violation to occur."); } catch (TargetInvocationException ex) { // Expected. Assert.True(ex.InnerException is ExpectationViolationException); } } [Test] public void DelegateBaseTypeCannotBeMocked() { Assert.Throws<InvalidOperationException> ( () => mocks.StrictMock (typeof (Delegate)), "Cannot mock the Delegate base type."); } private int Return1_Plus2_A(ref int a, out string b) { a += 2; b = "A"; return 1; } [Test] public void GenericDelegate() { Action<int> action = mocks.StrictMock<Action<int>>(); for (int i = 0; i < 10; i++) { action(i); } mocks.ReplayAll(); ForEachFromZeroToNine(action); mocks.VerifyAll(); } private void ForEachFromZeroToNine(Action<int> act) { for (int i = 0; i < 10; i++) { act(i); } } } }
32.376518
143
0.578717
[ "BSD-3-Clause" ]
rubicon-oss/CoreRhinoMocks
Rhino.Mocks.Tests/MockingDelegatesTests.cs
7,999
C#
using System.Reflection; namespace Totem.Timeline.Area { /// <summary> /// A method observing an event within a <see cref="Flow"/> /// </summary> public abstract class FlowMethod { internal FlowMethod(MethodInfo info, EventType eventType) { Info = info; EventType = eventType; } public readonly MethodInfo Info; public readonly EventType EventType; } }
20.947368
61
0.670854
[ "MIT" ]
AlexanderJohnston/Totem
src/Totem.Timeline/Area/FlowMethod.cs
398
C#
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculus.com/licenses/LICENSE-3.3 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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 UnityEngine; using UnityEditor; using UnityEditor.Callbacks; using System; using System.IO; [InitializeOnLoad] class OVRMoonlightLoader { private const string prefName = "OVRMoonlightLoader_Enabled"; private const string menuItemName = "Tools/Oculus/Use Required Project Settings"; static bool setPrefsForUtilities; [MenuItem(menuItemName)] static void ToggleUtilities() { setPrefsForUtilities = !setPrefsForUtilities; } static OVRMoonlightLoader() { EditorApplication.delayCall += EnforceInputManagerBindings; #if UNITY_ANDROID EditorApplication.delayCall += EnforceOSIG; #endif EditorApplication.update += EnforceBundleId; EditorApplication.update += EnforceVRSupport; EditorApplication.update += EnforceInstallLocation; EditorApplication.update += EnforcePlayerPrefs; setPrefsForUtilities = PlayerPrefs.GetInt(prefName, 1) != 0; if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.Android) return; if (PlayerSettings.defaultInterfaceOrientation != UIOrientation.LandscapeLeft) { Debug.Log("MoonlightLoader: Setting orientation to Landscape Left"); // Default screen orientation must be set to landscape left. PlayerSettings.defaultInterfaceOrientation = UIOrientation.LandscapeLeft; } if (!PlayerSettings.virtualRealitySupported) { // NOTE: This value should not affect the main window surface // when Built-in VR support is enabled. // NOTE: On Adreno Lollipop, it is an error to have antiAliasing set on the // main window surface with front buffer rendering enabled. The view will // render black. // On Adreno KitKat, some tiling control modes will cause the view to render // black. if (QualitySettings.antiAliasing != 0 && QualitySettings.antiAliasing != 1) { Debug.Log("MoonlightLoader: Disabling antiAliasing"); QualitySettings.antiAliasing = 1; } } if (QualitySettings.vSyncCount != 0) { Debug.Log("MoonlightLoader: Setting vsyncCount to 0"); // We sync in the TimeWarp, so we don't want unity syncing elsewhere. QualitySettings.vSyncCount = 0; } } static void EnforceVRSupport() { if (!setPrefsForUtilities) return; if (PlayerSettings.virtualRealitySupported) return; var mgrs = GameObject.FindObjectsOfType<OVRManager>(); for (int i = 0; i < mgrs.Length; ++i) { if (mgrs [i].isActiveAndEnabled) { Debug.Log ("Enabling Unity VR support"); PlayerSettings.virtualRealitySupported = true; #if UNITY_5_6_OR_NEWER bool oculusFound = false; foreach (var device in UnityEngine.VR.VRSettings.supportedDevices) oculusFound |= (device == "Oculus"); if (!oculusFound) Debug.LogError("Please add Oculus to the list of supported devices to use the Utilities."); #endif return; } } } private static void EnforceBundleId() { if (!setPrefsForUtilities) return; if (!PlayerSettings.virtualRealitySupported) return; #if UNITY_5_6_OR_NEWER if (PlayerSettings.applicationIdentifier == "" || PlayerSettings.applicationIdentifier == "com.Company.ProductName") { string defaultBundleId = "com.oculus.UnitySample"; Debug.LogWarning("\"" + PlayerSettings.applicationIdentifier + "\" is not a valid bundle identifier. Defaulting to \"" + defaultBundleId + "\"."); PlayerSettings.applicationIdentifier = defaultBundleId; } #else if (PlayerSettings.bundleIdentifier == "" || PlayerSettings.bundleIdentifier == "com.Company.ProductName") { string defaultBundleId = "com.oculus.UnitySample"; Debug.LogWarning("\"" + PlayerSettings.bundleIdentifier + "\" is not a valid bundle identifier. Defaulting to \"" + defaultBundleId + "\"."); PlayerSettings.bundleIdentifier = defaultBundleId; } #endif } private static void EnforceInstallLocation() { if (!setPrefsForUtilities) return; PlayerSettings.Android.preferredInstallLocation = AndroidPreferredInstallLocation.Auto; } private static void EnforceInputManagerBindings() { if (!setPrefsForUtilities) return; try { BindAxis(new Axis() { name = "Oculus_GearVR_LThumbstickX", axis = 0, }); BindAxis(new Axis() { name = "Oculus_GearVR_LThumbstickY", axis = 1, invert = true }); BindAxis(new Axis() { name = "Oculus_GearVR_RThumbstickX", axis = 2, }); BindAxis(new Axis() { name = "Oculus_GearVR_RThumbstickY", axis = 3, invert = true }); BindAxis(new Axis() { name = "Oculus_GearVR_DpadX", axis = 4, }); BindAxis(new Axis() { name = "Oculus_GearVR_DpadY", axis = 5, invert = true }); BindAxis(new Axis() { name = "Oculus_GearVR_LIndexTrigger", axis = 12, }); BindAxis(new Axis() { name = "Oculus_GearVR_RIndexTrigger", axis = 11, }); } catch { Debug.LogError("Failed to apply Oculus GearVR input manager bindings."); } } private static void EnforceOSIG() { if (!setPrefsForUtilities) return; // Don't bug the user in play mode. if (Application.isPlaying) return; // Don't warn if the project may be set up for submission or global signing. if (File.Exists("Assets/Plugins/Android/AndroidManifest.xml")) return; var files = Directory.GetFiles("Assets/Plugins/Android/assets"); bool foundPossibleOsig = false; for (int i = 0; i < files.Length; ++i) { if (!files[i].Contains(".txt")) { foundPossibleOsig = true; break; } } if (!foundPossibleOsig) Debug.LogWarning("Missing Gear VR OSIG at Assets/Plugins/Android/assets. Please see https://dashboard.oculus.com/tools/osig-generator"); } private static void EnforcePlayerPrefs() { int newValue = (setPrefsForUtilities) ? 1 : 0; int oldValue = PlayerPrefs.GetInt(prefName); if (newValue != oldValue) { PlayerPrefs.SetInt (prefName, newValue); PlayerPrefs.Save (); } Menu.SetChecked(menuItemName, setPrefsForUtilities); } private class Axis { public string name = String.Empty; public string descriptiveName = String.Empty; public string descriptiveNegativeName = String.Empty; public string negativeButton = String.Empty; public string positiveButton = String.Empty; public string altNegativeButton = String.Empty; public string altPositiveButton = String.Empty; public float gravity = 0.0f; public float dead = 0.001f; public float sensitivity = 1.0f; public bool snap = false; public bool invert = false; public int type = 2; public int axis = 0; public int joyNum = 0; } private static void BindAxis(Axis axis) { SerializedObject serializedObject = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/InputManager.asset")[0]); SerializedProperty axesProperty = serializedObject.FindProperty("m_Axes"); SerializedProperty axisIter = axesProperty.Copy(); axisIter.Next(true); axisIter.Next(true); while (axisIter.Next(false)) { if (axisIter.FindPropertyRelative("m_Name").stringValue == axis.name) { // Axis already exists. Don't create binding. return; } } axesProperty.arraySize++; serializedObject.ApplyModifiedProperties(); SerializedProperty axisProperty = axesProperty.GetArrayElementAtIndex(axesProperty.arraySize - 1); axisProperty.FindPropertyRelative("m_Name").stringValue = axis.name; axisProperty.FindPropertyRelative("descriptiveName").stringValue = axis.descriptiveName; axisProperty.FindPropertyRelative("descriptiveNegativeName").stringValue = axis.descriptiveNegativeName; axisProperty.FindPropertyRelative("negativeButton").stringValue = axis.negativeButton; axisProperty.FindPropertyRelative("positiveButton").stringValue = axis.positiveButton; axisProperty.FindPropertyRelative("altNegativeButton").stringValue = axis.altNegativeButton; axisProperty.FindPropertyRelative("altPositiveButton").stringValue = axis.altPositiveButton; axisProperty.FindPropertyRelative("gravity").floatValue = axis.gravity; axisProperty.FindPropertyRelative("dead").floatValue = axis.dead; axisProperty.FindPropertyRelative("sensitivity").floatValue = axis.sensitivity; axisProperty.FindPropertyRelative("snap").boolValue = axis.snap; axisProperty.FindPropertyRelative("invert").boolValue = axis.invert; axisProperty.FindPropertyRelative("type").intValue = axis.type; axisProperty.FindPropertyRelative("axis").intValue = axis.axis; axisProperty.FindPropertyRelative("joyNum").intValue = axis.joyNum; serializedObject.ApplyModifiedProperties(); } }
35.284672
150
0.702524
[ "MIT" ]
Reality-Virtually-Hackathon/Proxemix
Assets/OVR/Editor/OVRMoonlightLoader.cs
9,668
C#
namespace WebStore.Data.Configurations { using WebStore.Data.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; public class ApplicationUserConfiguration : IEntityTypeConfiguration<ApplicationUser> { public void Configure(EntityTypeBuilder<ApplicationUser> appUser) { appUser .HasMany(e => e.Claims) .WithOne() .HasForeignKey(e => e.UserId) .IsRequired() .OnDelete(DeleteBehavior.Restrict); appUser .HasMany(e => e.Logins) .WithOne() .HasForeignKey(e => e.UserId) .IsRequired() .OnDelete(DeleteBehavior.Restrict); appUser .HasMany(e => e.Roles) .WithOne() .HasForeignKey(e => e.UserId) .IsRequired() .OnDelete(DeleteBehavior.Restrict); } } }
29.970588
89
0.534838
[ "MIT" ]
MarinBalashkov/MyAspNetCoreProject_WebStore
Data/WebStore.Data/Configurations/ApplicationUserConfiguration.cs
1,021
C#
namespace Rollbar.Net.AspNet { using System; using System.Linq; using System.Web; using System.Web.Hosting; using Rollbar.Common; using Rollbar.Diagnostics; using Rollbar.DTOs; /// <summary> /// Class HttpResponsePackageDecorator. /// Implements the <see cref="Rollbar.RollbarPackageDecoratorBase" /> /// </summary> /// <seealso cref="Rollbar.RollbarPackageDecoratorBase" /> public class HttpResponsePackageDecorator : RollbarPackageDecoratorBase { /// <summary> /// The HTTP response /// </summary> private readonly HttpResponseBase _httpResponse; /// <summary> /// Initializes a new instance of the <see cref="HttpResponsePackageDecorator"/> class. /// </summary> /// <param name="packageToDecorate">The package to decorate.</param> /// <param name="httpResponse">The HTTP response.</param> public HttpResponsePackageDecorator(IRollbarPackage packageToDecorate, HttpResponse httpResponse) : this(packageToDecorate, httpResponse, false) { } /// <summary> /// Initializes a new instance of the <see cref="HttpResponsePackageDecorator"/> class. /// </summary> /// <param name="packageToDecorate">The package to decorate.</param> /// <param name="httpResponse">The HTTP response.</param> /// <param name="mustApplySynchronously">if set to <c>true</c> [must apply synchronously].</param> public HttpResponsePackageDecorator(IRollbarPackage packageToDecorate, HttpResponse httpResponse, bool mustApplySynchronously) : this(packageToDecorate, new HttpResponseWrapper(httpResponse), mustApplySynchronously) { } /// <summary> /// Initializes a new instance of the <see cref="HttpResponsePackageDecorator"/> class. /// </summary> /// <param name="packageToDecorate">The package to decorate.</param> /// <param name="httpResponse">The HTTP response.</param> public HttpResponsePackageDecorator(IRollbarPackage packageToDecorate, HttpResponseBase httpResponse) : this(packageToDecorate, httpResponse, false) { } /// <summary> /// Initializes a new instance of the <see cref="HttpResponsePackageDecorator"/> class. /// </summary> /// <param name="packageToDecorate">The package to decorate.</param> /// <param name="httpResponse">The HTTP response.</param> /// <param name="mustApplySynchronously">if set to <c>true</c> [must apply synchronously].</param> public HttpResponsePackageDecorator(IRollbarPackage packageToDecorate, HttpResponseBase httpResponse, bool mustApplySynchronously) : base(packageToDecorate, mustApplySynchronously) { Assumption.AssertNotNull(httpResponse, nameof(httpResponse)); this._httpResponse = httpResponse; } /// <summary> /// Decorates the specified rollbar data. /// </summary> /// <param name="rollbarData">The rollbar data.</param> protected override void Decorate(Data? rollbarData) { if(rollbarData == null) { return; } if(this._httpResponse == null || rollbarData == null) { return; //nothing to do... } if (rollbarData.Response == null) { rollbarData.Response = new Response(); } rollbarData.Response.StatusCode = this._httpResponse.StatusCode; rollbarData.Response.Headers = this._httpResponse.Headers?.ToCompactStringDictionary(); // some custom fields goodies: rollbarData.Response.Add("sub_status_code", this._httpResponse.SubStatusCode); if (!string.IsNullOrWhiteSpace(this._httpResponse.Status)) { rollbarData.Response.Add("status", this._httpResponse.Status); } if (!string.IsNullOrWhiteSpace(this._httpResponse.Charset)) { rollbarData.Response.Add("charset", this._httpResponse.Charset); } if (!string.IsNullOrWhiteSpace(this._httpResponse.RedirectLocation)) { rollbarData.Response.Add("redirect_location", this._httpResponse.RedirectLocation); } if (!string.IsNullOrWhiteSpace(this._httpResponse.StatusDescription)) { rollbarData.Response.Add("status_description", this._httpResponse.StatusDescription); } } } }
40.982456
139
0.62393
[ "MIT" ]
rollbar/Rollbar.NET
Rollbar.Net.AspNet/HttpResponsePackageDecorator.cs
4,674
C#
using System.Linq; using System.Collections.Generic; using System.Threading.Tasks; using HelloWebApi.Contexts; using HelloWebApi.Models; using Microsoft.EntityFrameworkCore; namespace HelloWebApi.Repositories { public class ProductRepository : IProductRepository { private readonly NorthwindSlimContext _context; public ProductRepository(NorthwindSlimContext context) { _context = context; } public async Task<IEnumerable<Product>> GetProducts() { return await _context.Products .Include(p => p.Category) .OrderBy(p => p.ProductName) .ToListAsync(); } public async Task<Product> GetProduct(int id) { return await _context.Products .Include(p => p.Category) .SingleOrDefaultAsync(p => p.ProductId == id); } public void CreateProduct(Product product) { _context.Products.Add(product); } public void UpdateProduct(Product product) { _context.Products.Update(product); } public async Task DeleteProduct(int id) { var product = await _context.Products.FindAsync(id); _context.Products.Remove(product); } public async Task LoadCategory(Product product) { await _context.Entry(product) .Reference(p => p.Category) .LoadAsync(); } } }
26.842105
64
0.584314
[ "MIT" ]
tonysneed/Kliant.AspNetCore-Angular
Exercises/08-Angular-CLI/08b_AngularWebApi/_AspNetWebApi/Repositories/ProductRepository.cs
1,530
C#
// Copyright (c) 2008-2020, Hazelcast, Inc. 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. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading; using Hazelcast.Client.Network; using Hazelcast.Core; using Hazelcast.Logging; using Hazelcast.Net.Ext; using Hazelcast.Util; using static Hazelcast.Util.ValidationUtil; namespace Hazelcast.Client.Spi { internal partial class ClusterService { private static readonly ILogger Logger = Logging.Logger.GetLogger(typeof(ClusterService)); private const int InitialMembersTimeoutMillis = 120_000; private readonly HazelcastClient _client; private readonly ConnectionManager _connectionManager; private readonly InvocationService _clientInvocationService; private readonly PartitionService _partitionService; private static readonly MemberListSnapshot EmptySnapshot = new MemberListSnapshot(-1, new Dictionary<Guid, IMember>()); private readonly AtomicReference<MemberListSnapshot> _memberListSnapshot = new AtomicReference<MemberListSnapshot>(EmptySnapshot); private readonly ConcurrentDictionary<Guid, IMembershipListener> _listeners = new ConcurrentDictionary<Guid, IMembershipListener>(); private readonly IReadOnlyCollection<string> _labels; private readonly object _clusterViewLock = new object(); private CountdownEvent _initialListFetchedLatch = new CountdownEvent(1); internal string ClusterName { get; } public ClusterService(HazelcastClient client) { _client = client; _labels = new ReadOnlyCollection<string>(_client.Configuration.Labels.ToList()); _connectionManager = _client.ConnectionManager; _partitionService = client.PartitionService; _clientInvocationService = client.InvocationService; ClusterName = _client.Configuration.ClusterName; } public IMember GetMember(Guid guid) { _memberListSnapshot.Get().Members.TryGetValue(guid, out var member); return member; } public ICollection<IMember> Members => _memberListSnapshot.Get().Members.Values; public int Count => Members.Count; public IEnumerable<IMember> DataMemberList => _memberListSnapshot.Get().Members.Values.Where(member => !member.IsLiteMember); public long ClusterTime => Clock.CurrentTimeMillis(); public Guid AddMembershipListener(IMembershipListener listener) { CheckNotNull(listener, NullListenerIsNotAllowed); lock (_clusterViewLock) { var id = AddMembershipListenerWithoutInit(listener); if (listener is IInitialMembershipListener) { var cluster = ((IHazelcastInstance) _client).Cluster; var members = Members; //if members are empty,it means initial event did not arrive yet //it will be redirected to listeners when it arrives see #handleInitialMembershipEvent if (members.Count != 0) { var @event = new InitialMembershipEvent(cluster, members); ((IInitialMembershipListener) listener).Init(@event); } } return id; } } private Guid AddMembershipListenerWithoutInit(IMembershipListener listener) { var id = Guid.NewGuid(); _listeners.TryAdd(id, listener); return id; } public bool RemoveMembershipListener(Guid registrationId) { CheckNotNull(registrationId, "registrationId can't be null"); return _listeners.TryRemove(registrationId, out _); } public void Start(ICollection<IEventListener> configuredListeners) { ListenerService.RegisterConfigListeners<IMembershipListener>(configuredListeners, AddMembershipListenerWithoutInit); _connectionManager.AddConnectionListener(this); } public void WaitInitialMemberListFetched() { try { var success = _initialListFetchedLatch.Wait(InitialMembersTimeoutMillis); if (!success) { throw new InvalidOperationException("Could not get initial member list from cluster!"); } } catch (ThreadInterruptedException e) { throw ExceptionUtil.Rethrow(e); } } public void ClearMemberListVersion() { lock (_clusterViewLock) { if (Logger.IsFinestEnabled) { Logger.Finest("Resetting the member list version "); } var clusterViewSnapshot = _memberListSnapshot.Get(); //This check is necessary so that `clearMemberListVersion` when handling auth response will not //intervene with client failover logic if (clusterViewSnapshot != EmptySnapshot) { _memberListSnapshot.Set(new MemberListSnapshot(0, clusterViewSnapshot.Members)); } } } private void ApplyInitialState(int version, ICollection<MemberInfo> memberInfos) { var snapshot = CreateSnapshot(version, memberInfos); _memberListSnapshot.Set(snapshot); Logger.Info(snapshot.ToString()); var members = snapshot.Members.Values; var @event = new InitialMembershipEvent(((IHazelcastInstance) _client).Cluster, members); foreach (var listener in _listeners.Values) { if (listener is IInitialMembershipListener initialMembershipListener) { initialMembershipListener.Init(@event); } } } private MemberListSnapshot CreateSnapshot(int memberListVersion, ICollection<MemberInfo> memberInfos) { var newMembers = memberInfos.ToDictionary<MemberInfo, Guid, IMember>(memberInfo => memberInfo.Uuid, memberInfo => memberInfo); return new MemberListSnapshot(memberListVersion, newMembers); } private List<MembershipEvent> DetectMembershipEvents(ICollection<IMember> prevMembers, ICollection<IMember> currentMembers) { var newMembers = new List<IMember>(); var deadMembers = new HashSet<IMember>(prevMembers); foreach (var member in currentMembers) { if (!deadMembers.Remove(member)) { newMembers.Add(member); } } var events = new List<MembershipEvent>(); // removal events should be added before added events foreach (var member in deadMembers) { events.Add(new MembershipEvent(((IHazelcastInstance) _client).Cluster, member, MembershipEvent.MemberRemoved, currentMembers)); var connection = _connectionManager.GetConnection(member.Uuid); connection?.Close(null, new TargetDisconnectedException("The client has closed the connection to this member," + " after receiving a member left event from the cluster. " + connection)); } foreach (var member in newMembers) { events.Add(new MembershipEvent(((IHazelcastInstance) _client).Cluster, member, MembershipEvent.MemberAdded, currentMembers)); } if (events.Count != 0) { var snapshot = _memberListSnapshot.Get(); if (snapshot.Members.Values.Count != 0) { Logger.Info(snapshot.ToString()); } } return events; } public void HandleMembersViewEvent(int memberListVersion, ICollection<MemberInfo> memberInfos) { if (Logger.IsFinestEnabled) { var snapshot = CreateSnapshot(memberListVersion, memberInfos); Logger.Finest( $"Handling new snapshot with membership version: {memberListVersion} members: {snapshot}"); } var clusterViewSnapshot = _memberListSnapshot.Get(); if (clusterViewSnapshot == EmptySnapshot) { lock (_clusterViewLock) { clusterViewSnapshot = _memberListSnapshot.Get(); if (clusterViewSnapshot == EmptySnapshot) { //this means this is the first time client connected to cluster ApplyInitialState(memberListVersion, memberInfos); _initialListFetchedLatch.Signal(); return; } } } var events = new List<MembershipEvent>(); if (memberListVersion >= clusterViewSnapshot.Version) { lock (_clusterViewLock) { clusterViewSnapshot = _memberListSnapshot.Get(); if (memberListVersion >= clusterViewSnapshot.Version) { ICollection<IMember> prevMembers = clusterViewSnapshot.Members.Values; var snapshot = CreateSnapshot(memberListVersion, memberInfos); _memberListSnapshot.Set(snapshot); ICollection<IMember> currentMembers = snapshot.Members.Values; events = DetectMembershipEvents(prevMembers, currentMembers); } } } FireEvents(events); } private void FireEvents(List<MembershipEvent> events) { foreach (var membershipEvent in events) { if (Logger.IsFinestEnabled) { Logger.Finest($"Fire Event:{membershipEvent}"); } foreach (var listener in _listeners.Values) { try { if (membershipEvent.GetEventType() == MembershipEvent.MemberAdded) { listener.MemberAdded(membershipEvent); } else { listener.MemberRemoved(membershipEvent); } } catch (Exception e) { if (Logger.IsFinestEnabled) { Logger.Finest("Exception occured during membership listener callback.", e); } } } } } private class MemberListSnapshot { public MemberListSnapshot(int version, Dictionary<Guid, IMember> members) { Version = version; Members = members; } public int Version { get; } public Dictionary<Guid, IMember> Members { get; } public override string ToString() { ICollection<IMember> members = Members.Values; var sb = new StringBuilder("\n\nMembers ["); sb.Append(members.Count); sb.Append("] {"); foreach (var member in members) { sb.Append("\n\t").Append(member); } sb.Append("\n}\n"); return sb.ToString(); } } } }
39.247678
143
0.56851
[ "Apache-2.0" ]
mogatti/hazelcast-csharp-client
Hazelcast.Net/Hazelcast.Client.Spi/ClusterService.cs
12,677
C#
namespace LamarExample { public interface IPurchasingService { } }
11.285714
39
0.683544
[ "MIT" ]
pirocorp/ASP.NET-Core-Playground
02. ASP.NET Core In Action/Chapter19/E_LamarExample/LamarExample/Services/IPurchasingService.cs
79
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.ContainerService.V20200701.Outputs { /// <summary> /// Profile for Windows VMs in the container service cluster. /// </summary> [OutputType] public sealed class ManagedClusterWindowsProfileResponse { /// <summary> /// Specifies the password of the administrator account. &lt;br&gt;&lt;br&gt; **Minimum-length:** 8 characters &lt;br&gt;&lt;br&gt; **Max-length:** 123 characters &lt;br&gt;&lt;br&gt; **Complexity requirements:** 3 out of 4 conditions below need to be fulfilled &lt;br&gt; Has lower characters &lt;br&gt;Has upper characters &lt;br&gt; Has a digit &lt;br&gt; Has a special character (Regex match [\W_]) &lt;br&gt;&lt;br&gt; **Disallowed values:** "abc@123", "P@$$w0rd", "P@ssw0rd", "P@ssword123", "Pa$$word", "pass@word1", "Password!", "Password1", "Password22", "iloveyou!" /// </summary> public readonly string? AdminPassword; /// <summary> /// Specifies the name of the administrator account. &lt;br&gt;&lt;br&gt; **restriction:** Cannot end in "." &lt;br&gt;&lt;br&gt; **Disallowed values:** "administrator", "admin", "user", "user1", "test", "user2", "test1", "user3", "admin1", "1", "123", "a", "actuser", "adm", "admin2", "aspnet", "backup", "console", "david", "guest", "john", "owner", "root", "server", "sql", "support", "support_388945a0", "sys", "test2", "test3", "user4", "user5". &lt;br&gt;&lt;br&gt; **Minimum-length:** 1 character &lt;br&gt;&lt;br&gt; **Max-length:** 20 characters /// </summary> public readonly string AdminUsername; /// <summary> /// The licenseType to use for Windows VMs. Windows_Server is used to enable Azure Hybrid User Benefits for Windows VMs. /// </summary> public readonly string? LicenseType; [OutputConstructor] private ManagedClusterWindowsProfileResponse( string? adminPassword, string adminUsername, string? licenseType) { AdminPassword = adminPassword; AdminUsername = adminUsername; LicenseType = licenseType; } } }
53.065217
582
0.64236
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/ContainerService/V20200701/Outputs/ManagedClusterWindowsProfileResponse.cs
2,441
C#
namespace NewPizza.Migrations { using System; using System.Data.Entity.Migrations; public partial class Adres : DbMigration { public override void Up() { CreateTable( "dbo.Adres", c => new { Id = c.Int(nullable: false, identity: true), AcikAdres = c.String(), Sehir = c.String(), Ilce = c.String(), UserId = c.String(), }) .PrimaryKey(t => t.Id); } public override void Down() { DropTable("dbo.Adres"); } } }
24.533333
68
0.383152
[ "MIT" ]
mfrkndmrl/mvcPizzaSiparis
NewPizza/Migrations/201705161312510_Adres.cs
736
C#
using UnityEngine; public static class StaticComponent { public static float currentSpeed; public static float GetCurrentSpeed() { return currentSpeed; } public static void SetCurrentSpeed(float speed) { currentSpeed = speed; } }
18.25
52
0.633562
[ "MIT" ]
XenMoros/Cerditos_Jugueteria
SuicideTeddy/Assets/Scripts/StaticComponent.cs
294
C#
/** * (C) Copyright IBM Corp. 2017, 2020. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Linq; using System; using System.IO; using IBM.Watson.NaturalLanguageUnderstanding.v1.Model; using IBM.Cloud.SDK.Core.Util; using Newtonsoft.Json; using System.Collections.Generic; namespace IBM.Watson.NaturalLanguageUnderstanding.v1.IntegrationTests { [TestClass] public class NaturalLanguageUnderstandingIntegrationTests { private static string apikey; private static string endpoint; private NaturalLanguageUnderstandingService service; private static string credentials = string.Empty; private string versionDate = "2017-02-27"; private string nluText = "Analyze various features of text content at scale. Provide text, raw HTML, or a public URL, and IBM Watson Natural Language Understanding will give you results for the features you request. The service cleans HTML content before analysis by default, so the results can ignore most advertisements and other unwanted content."; [TestInitialize] public void Setup() { service = new NaturalLanguageUnderstandingService(versionDate); } [TestMethod] public void Analyze_Success() { var text = nluText; var features = new Features() { Keywords = new KeywordsOptions() { Limit = 8, Sentiment = true, Emotion = true }, Categories = new CategoriesOptions() { Limit = 10 } }; service.WithHeader("X-Watson-Test", "1"); var result = service.Analyze( features: features, text: text, clean: true, fallbackToRaw: true, returnAnalyzedText: true, language: "en" ); Assert.IsNotNull(result); Assert.IsTrue(result.Result.Categories.Count > 0); Assert.IsTrue(result.Result.Keywords.Count > 0); } [TestMethod] public void ListModels_Success() { service.WithHeader("X-Watson-Test", "1"); var result = service.ListModels(); Assert.IsNotNull(result.Result); } [TestMethod] public void AnalyzeWithCategories() { service.WithHeader("X-Watson-Test", "1"); var result = service.Analyze( url: "www.ibm.com", features: new Features() { Categories = new CategoriesOptions() { Limit = 3 } } ); Assert.IsNotNull(result.Result); Assert.IsNotNull(result.Result.Categories); Assert.IsTrue(result.Result.Categories.Count == 3); Assert.IsTrue(result.Result.RetrievedUrl.Contains("www.ibm.com")); } [TestMethod] public void AnalyzeWithConcepts() { service.WithHeader("X-Watson-Test", "1"); var result = service.Analyze( url: "www.ibm.com", features: new Features() { Concepts = new ConceptsOptions() { Limit = 3 } } ); Assert.IsNotNull(result.Result); Assert.IsNotNull(result.Result.Concepts); Assert.IsTrue(result.Result.Concepts.Count == 3); Assert.IsTrue(result.Result.RetrievedUrl.Contains("www.ibm.com")); } [TestMethod] public void AnalyzeWithEmotion() { service.WithHeader("X-Watson-Test", "1"); var result = service.Analyze( html: "<html><head><title>Fruits</title></head><body><h1>Apples and Oranges</h1><p>I love apples! I don't like oranges.</p></body></html>", features: new Features() { Emotion = new EmotionOptions() { Targets = new List<string> { "apples", "oranges" } } } ); Assert.IsNotNull(result.Result); Assert.IsNotNull(result.Result.Emotion); Assert.IsNotNull(result.Result.Emotion.Targets); Assert.IsTrue(result.Result.Emotion.Targets.Count == 2); Assert.IsTrue(result.Result.Emotion.Targets[0].Text == "apples"); Assert.IsTrue(result.Result.Emotion.Targets[1].Text == "oranges"); Assert.IsNotNull(result.Result.Emotion.Document); Assert.IsNotNull(result.Result.Emotion.Document.Emotion); } [TestMethod] public void AnalyzeWithEntities() { service.WithHeader("X-Watson-Test", "1"); var result = service.Analyze( url: "www.cnn.com", features: new Features() { Entities = new EntitiesOptions() { Sentiment = true, Limit = 1 } } ); Assert.IsNotNull(result.Result); Assert.IsNotNull(result.Result.Entities); Assert.IsTrue(result.Result.Entities.Count == 1); Assert.IsTrue(result.Result.RetrievedUrl.Contains("www.cnn.com")); } [TestMethod] public void AnalyzeWithKeywords() { service.WithHeader("X-Watson-Test", "1"); var result = service.Analyze( url: "www.ibm.com", features: new Features() { Keywords = new KeywordsOptions() { Sentiment = true, Emotion = true, Limit = 2 } } ); Assert.IsNotNull(result.Result); Assert.IsNotNull(result.Result.Keywords); Assert.IsTrue(result.Result.Keywords.Count == 2); Assert.IsNotNull(result.Result.Keywords[0].Sentiment); Assert.IsNotNull(result.Result.Keywords[0].Emotion); Assert.IsNotNull(result.Result.Keywords[1].Sentiment); Assert.IsNotNull(result.Result.Keywords[1].Emotion); Assert.IsTrue(result.Result.RetrievedUrl.Contains("www.ibm.com")); } [TestMethod] public void AnalyzeWithMetadata() { service.WithHeader("X-Watson-Test", "1"); var result = service.Analyze( url: "www.ibm.com", features: new Features() { Metadata = new FeaturesResultsMetadata() } ); Assert.IsNotNull(result.Result); Assert.IsNotNull(result.Result.Metadata); Assert.IsNotNull(result.Result.Metadata.Title); Assert.IsNotNull(result.Result.Metadata.PublicationDate); Assert.IsTrue(result.Result.RetrievedUrl.Contains("www.ibm.com")); } [TestMethod] public void AnalyzeWithRelations() { service.WithHeader("X-Watson-Test", "1"); var result = service.Analyze( text: "Leonardo DiCaprio won Best Actor in a Leading Role for his performance.", features: new Features() { Relations = new RelationsOptions() } ); Assert.IsNotNull(result.Result); Assert.IsNotNull(result.Result.Relations); Assert.IsTrue(result.Result.Relations.Count == 1); Assert.IsNotNull(result.Result.Relations[0].Sentence); } [TestMethod] public void AnalyzeWithSemanticRoles() { service.WithHeader("X-Watson-Test", "1"); var result = service.Analyze( text: "IBM has one of the largest workforces in the world", features: new Features() { SemanticRoles = new SemanticRolesOptions() } ); Assert.IsNotNull(result.Result); Assert.IsNotNull(result.Result.SemanticRoles); Assert.IsTrue(result.Result.SemanticRoles.Count > 0); Assert.IsTrue(result.Result.SemanticRoles[0].Subject.Text == "IBM"); Assert.IsTrue(result.Result.SemanticRoles[0].Sentence == "IBM has one of the largest workforces in the world"); } [TestMethod] public void AnalyzeWithSentiment() { service.WithHeader("X-Watson-Test", "1"); string text = "In 2009, Elliot Turner launched AlchemyAPI to process the written word," + " with all of its quirks and nuances, and got immediate traction."; var result = service.Analyze( text: text, features: new Features() { Sentiment = new SentimentOptions() { Targets = new List<string>() { "Elliot Turner" } } } ); Assert.IsNotNull(result.Result); Assert.IsNotNull(result.Result.Sentiment); Assert.IsNotNull(result.Result.Sentiment.Targets); Assert.IsTrue(result.Result.Sentiment.Targets.Count == 1); Assert.IsTrue(result.Result.Sentiment.Targets[0].Text == "Elliot Turner"); Assert.IsNotNull(result.Result.Sentiment.Document); } [TestMethod] public void AnalyzeWithSyntax() { service.WithHeader("X-Watson-Test", "1"); var result = service.Analyze( text: "With great power comes great responsibility", features: new Features() { Syntax = new SyntaxOptions() { Sentences = true, Tokens = new SyntaxOptionsTokens() { Lemma = true, PartOfSpeech = true } } } ); Assert.IsNotNull(result.Result); Assert.IsNotNull(result.Result.Syntax); Assert.IsNotNull(result.Result.Syntax.Tokens); Assert.IsTrue(result.Result.Syntax.Tokens.Count > 0); Assert.IsNotNull(result.Result.Syntax.Tokens[0].Lemma); Assert.IsNotNull(result.Result.Syntax.Sentences); Assert.IsTrue(result.Result.Syntax.Sentences.Count > 0); Assert.IsTrue(result.Result.Syntax.Sentences[0].Text == "With great power comes great responsibility"); } } }
37.825949
360
0.517945
[ "Apache-2.0" ]
darkmatter2222/dotnet-standard-sdk
src/IBM.Watson.NaturalLanguageUnderstanding.v1/Test/Integration/NaturalLanguageUnderstandingIntegrationTests.cs
11,955
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 sselIndReports { public partial class AggNNIN { /// <summary> /// ppRep control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::LNF.Web.Controls.PeriodPicker ppRep; /// <summary> /// ppAgg control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::LNF.Web.Controls.PeriodPicker ppAgg; /// <summary> /// btnReport 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.Button btnReport; /// <summary> /// btnBack 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.LinkButton btnBack; /// <summary> /// lblWarning 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.Label lblWarning; /// <summary> /// gv1 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.GridView gv1; /// <summary> /// gv2 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.GridView gv2; /// <summary> /// gv3 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.GridView gv3; } }
33.420455
84
0.517171
[ "MIT" ]
lurienanofab/sselindreports
sselIndReports/AggNNIN.aspx.designer.cs
2,943
C#
using System; namespace essentialMix.Web; [Flags] public enum XmlIndexMatchType : short { None = 0, Type = 1, Name = 1 << 1 }
11.818182
37
0.676923
[ "MIT" ]
asm2025/essentialMix
Standard/essentialMix/Web/XmlIndexMatchType.cs
130
C#
using Data.Model; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; namespace Data.Dao { public class ClassroomDao { public List<Classroom> FindAll() { using (var db = new DatabaseContext()) { return db.Classrooms.Include(c => c.InstalledSoftware).ToList(); } } public Classroom FindById(string id) { using (var db = new DatabaseContext()) { var classroom = db.Classrooms.Include(c => c.InstalledSoftware).FirstOrDefault(c => c.Id == id); return classroom; } } public bool IdTaken(string id) { return FindById(id) != null; } public void Add(Classroom classroom) { using (var db = new DatabaseContext()) { foreach (var software in classroom.InstalledSoftware) { db.Entry(software).State = EntityState.Unchanged; } db.Classrooms.Add(classroom); db.SaveChanges(); } } public void Remove(string classroomId) { using (var db = new DatabaseContext()) { var classroom = db.Classrooms.FirstOrDefault(c => c.Id == classroomId); if (classroom == null) return; db.Classrooms.Remove(classroom); try { db.SaveChanges(); } catch (Exception e) { } } } public void Update(Classroom classroom) { using (var db = new DatabaseContext()) { var original = db.Classrooms.Include(c => c.InstalledSoftware) .FirstOrDefault(c => c.Id == classroom.Id); if (original != null) { original.InstalledSoftware.Clear(); foreach (var software in classroom.InstalledSoftware) { var originalSoftware = db.Softwares.FirstOrDefault(s => s.Id == software.Id); db.Entry(originalSoftware).State = EntityState.Unchanged; original.InstalledSoftware.Add(originalSoftware); } original.UpdateWithoutSoftware(classroom); db.Entry(original).State = EntityState.Modified; db.SaveChanges(); } } } public string FindAvailableDemoId(string id) { using (var db = new DatabaseContext()) { var availableId = id; var num = 1; while (db.Classrooms.FirstOrDefault(c => c.Id == availableId) != null) { availableId = id + num++; } return availableId; } } } }
30.235294
112
0.466926
[ "MIT" ]
code10ftn/computer-center
Data/Dao/ClassroomDao.cs
3,086
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.WafV2.Inputs { public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementByteMatchStatementFieldToMatchBodyArgs : Pulumi.ResourceArgs { public WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementByteMatchStatementFieldToMatchBodyArgs() { } } }
33.85
159
0.787297
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementByteMatchStatementFieldToMatchBodyArgs.cs
677
C#
using MyLittleShop.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MyLittleShop.ViewModels { public class HomeViewModel { public IEnumerable<Item> ItemsOfTheWeek { get; set; } } }
19.214286
61
0.739777
[ "MIT" ]
krzysztofkobrenczuk/MyLittleShop
MyLittleShop/src/MyLittleShop/ViewModels/HomeViewModel.cs
271
C#
namespace NeoSharp.VM.NeoVM { public class InteropServiceAdapter : Neo.VM.IInteropService { /// <summary> /// Base service /// </summary> private readonly InteropService _service; /// <summary> /// This class is dependent of the ApplicationEngine, /// because is not possible to convert from ExecutionEngine to IExecutionEngine right now /// </summary> private readonly ExecutionEngineBase _engine; /// <summary> /// Constructor /// </summary> /// <param name="engine">Execution Engine</param> /// <param name="service">Base Service</param> public InteropServiceAdapter(ExecutionEngineBase engine, InteropService service) { _service = service; _engine = engine; } /// <summary> /// Invoke of NeoVM /// </summary> /// <param name="method">Method</param> /// <param name="engine">Engine</param> /// <returns>Return true if works</returns> public bool Invoke(byte[] method, Neo.VM.ExecutionEngine engine) { return _service.Invoke(method, _engine); } } }
31.894737
98
0.575083
[ "MIT" ]
corollari/neo-sharp
src/NeoSharp.VM.NeoVM/InteropServiceAdapter.cs
1,214
C#
using Qaelo.Data.AccommodationData; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Qaelo.Web.Users.Accommodation { public partial class Accommodation : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { //List<Qaelo.Models.AccommodationModel.RoomAd> rooms = lblNoOfAds.Text = new AccommodationConnection().getAllRoomAds().Count.ToString(); lblNoOfReservations.Text = new AccommodationConnection().getAllReservations().Count.ToString(); } } }
31.904762
108
0.692537
[ "MIT" ]
ThabangSirrve/Qaelo
Qaelo/Qaelo/Web/Users/Accommodation/Accommodation.Master.cs
672
C#
namespace SyntSky.GoodGame.Api.V4.Emums; public enum GameGroupType { Game, Group }
12.285714
41
0.767442
[ "MIT" ]
SyntSky/GoodGame
SyntSky.GoodGame.Api.V4/Emums/GameGroupType.cs
88
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/mfcaptureengine.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { [Guid("72D6135B-35E9-412C-B926-FD5265F2A885")] [NativeTypeName("struct IMFCaptureSink : IUnknown")] public unsafe partial struct IMFCaptureSink { public void** lpVtbl; [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvObject) { return ((delegate* unmanaged<IMFCaptureSink*, Guid*, void**, int>)(lpVtbl[0]))((IMFCaptureSink*)Unsafe.AsPointer(ref this), riid, ppvObject); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* unmanaged<IMFCaptureSink*, uint>)(lpVtbl[1]))((IMFCaptureSink*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* unmanaged<IMFCaptureSink*, uint>)(lpVtbl[2]))((IMFCaptureSink*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int GetOutputMediaType([NativeTypeName("DWORD")] uint dwSinkStreamIndex, [NativeTypeName("IMFMediaType **")] IMFMediaType** ppMediaType) { return ((delegate* unmanaged<IMFCaptureSink*, uint, IMFMediaType**, int>)(lpVtbl[3]))((IMFCaptureSink*)Unsafe.AsPointer(ref this), dwSinkStreamIndex, ppMediaType); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int GetService([NativeTypeName("DWORD")] uint dwSinkStreamIndex, [NativeTypeName("const GUID &")] Guid* rguidService, [NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("IUnknown **")] IUnknown** ppUnknown) { return ((delegate* unmanaged<IMFCaptureSink*, uint, Guid*, Guid*, IUnknown**, int>)(lpVtbl[4]))((IMFCaptureSink*)Unsafe.AsPointer(ref this), dwSinkStreamIndex, rguidService, riid, ppUnknown); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int AddStream([NativeTypeName("DWORD")] uint dwSourceStreamIndex, [NativeTypeName("IMFMediaType *")] IMFMediaType* pMediaType, [NativeTypeName("IMFAttributes *")] IMFAttributes* pAttributes, [NativeTypeName("DWORD *")] uint* pdwSinkStreamIndex) { return ((delegate* unmanaged<IMFCaptureSink*, uint, IMFMediaType*, IMFAttributes*, uint*, int>)(lpVtbl[5]))((IMFCaptureSink*)Unsafe.AsPointer(ref this), dwSourceStreamIndex, pMediaType, pAttributes, pdwSinkStreamIndex); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int Prepare() { return ((delegate* unmanaged<IMFCaptureSink*, int>)(lpVtbl[6]))((IMFCaptureSink*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int RemoveAllStreams() { return ((delegate* unmanaged<IMFCaptureSink*, int>)(lpVtbl[7]))((IMFCaptureSink*)Unsafe.AsPointer(ref this)); } } }
50.013333
259
0.682218
[ "MIT" ]
Perksey/terrafx.interop.windows
sources/Interop/Windows/um/mfcaptureengine/IMFCaptureSink.cs
3,753
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.QuickInfo { internal partial class ContentControlService { /// <summary> /// Class which allows us to provide a delay-created tooltip for our reference entries. /// </summary> private class LazyToolTip : ForegroundThreadAffinitizedObject { private readonly Func<DisposableToolTip> _createToolTip; private readonly FrameworkElement _element; private DisposableToolTip _disposableToolTip; private LazyToolTip( IThreadingContext threadingContext, FrameworkElement element, Func<DisposableToolTip> createToolTip) : base(threadingContext, assertIsForeground: true) { _element = element; _createToolTip = createToolTip; // Set ourselves as the tooltip of this text block. This will let WPF know that // it should attempt to show tooltips here. When WPF wants to show the tooltip // though we'll hear about it "ToolTipOpening". When that happens, we'll swap // out ourselves with a real tooltip that is lazily created. When that tooltip // is the dismissed, we'll release the resources associated with it and we'll // reattach ourselves. _element.ToolTip = this; element.ToolTipOpening += this.OnToolTipOpening; element.ToolTipClosing += this.OnToolTipClosing; } public static void AttachTo(FrameworkElement element, IThreadingContext threadingContext, Func<DisposableToolTip> createToolTip) => new LazyToolTip(threadingContext, element, createToolTip); private void OnToolTipOpening(object sender, ToolTipEventArgs e) { AssertIsForeground(); Debug.Assert(_element.ToolTip == this); Debug.Assert(_disposableToolTip == null); _disposableToolTip = _createToolTip(); _element.ToolTip = _disposableToolTip.ToolTip; } private void OnToolTipClosing(object sender, ToolTipEventArgs e) { AssertIsForeground(); Debug.Assert(_disposableToolTip != null); Debug.Assert(_element.ToolTip == _disposableToolTip.ToolTip); _element.ToolTip = this; _disposableToolTip.Dispose(); _disposableToolTip = null; } } } }
39.306667
140
0.625848
[ "MIT" ]
06needhamt/roslyn
src/EditorFeatures/Core.Wpf/QuickInfo/LazyToolTip.cs
2,950
C#
using System.Windows.Controls; namespace Samples.Tutorials.MvvmSample { /// <summary> /// Interaction logic for ClockPopup.xaml /// </summary> public partial class ClockPopup : UserControl { public ClockPopup() { InitializeComponent(); } } }
17.2
46
0.705426
[ "MIT" ]
HavenDV/H.NotifyIcon.WPF
samples/Sample Project/Tutorials/09 - MVVM/ClockPopup.xaml.cs
260
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.UnitTestFramework; using Xunit; namespace ImplementNotifyPropertyChangedCS.UnitTests { public class IsExpandableTests : CodeActionProviderTestFixture { protected override string LanguageName { get { return LanguageNames.CSharp; } } [Fact] public void TryGetAccessors1() { const string Code = "class C { int P { get }"; var property = SyntaxFactory.ParseCompilationUnit(Code).DescendantNodes().OfType<PropertyDeclarationSyntax>().First(); AccessorDeclarationSyntax getter; AccessorDeclarationSyntax setter; var result = ExpansionChecker.TryGetAccessors(property, out getter, out setter); Assert.False(result); } [Fact] public void TryGetAccessors2() { const string Code = "class C { int P { get; }"; var property = SyntaxFactory.ParseCompilationUnit(Code).DescendantNodes().OfType<PropertyDeclarationSyntax>().First(); AccessorDeclarationSyntax getter; AccessorDeclarationSyntax setter; var result = ExpansionChecker.TryGetAccessors(property, out getter, out setter); Assert.False(result); } [Fact] public void TryGetAccessors3() { const string Code = "class C { int P { get; set }"; var property = SyntaxFactory.ParseCompilationUnit(Code).DescendantNodes().OfType<PropertyDeclarationSyntax>().First(); AccessorDeclarationSyntax getter; AccessorDeclarationSyntax setter; var result = ExpansionChecker.TryGetAccessors(property, out getter, out setter); Assert.True(result); } [Fact] public void TryGetAccessors4() { const string Code = "class C { int P { get; set; }"; var property = SyntaxFactory.ParseCompilationUnit(Code).DescendantNodes().OfType<PropertyDeclarationSyntax>().First(); AccessorDeclarationSyntax getter; AccessorDeclarationSyntax setter; var result = ExpansionChecker.TryGetAccessors(property, out getter, out setter); Assert.True(result); } private bool IsExpandableProperty(string code) { var document = CreateDocument(code); var property = document.GetSyntaxRootAsync().Result.DescendantNodes().OfType<PropertyDeclarationSyntax>().First(); return ExpansionChecker.GetExpandablePropertyInfo(property, document.GetSemanticModelAsync().Result) != null; } [Fact] public void IsExpandableProperty1() { const string Code = "class C { int P { get }"; Assert.False(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty2() { const string Code = "class C { int P { get; }"; Assert.False(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty3() { const string Code = "class C { int P { get; set }"; Assert.False(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty4() { const string Code = "class C { int P { get; set; }"; Assert.True(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty5() { const string Code = "class C { int P { get { } set { } }"; Assert.False(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty6() { const string Code = "class C { int P { get { return 1; } set { } }"; Assert.False(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty7() { const string Code = "class C { int P { get { return P; } set { } }"; Assert.False(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty8() { const string Code = "class C { int f; int P { get { return f; } set { } }"; Assert.False(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty9() { const string Code = "class C { int f; int P { get { return f; } set { f = value; } }"; Assert.True(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty10() { const string Code = "class C { int f; int P { get { return f; } set { if (f != value) f = value; } }"; Assert.True(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty11() { const string Code = "class C { int f; int P { get { return f; } set { if (value != f) f = value; } }"; Assert.True(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty12() { const string Code = "class C { int f; int P { get { return f; } set { if (f != value) { f = value; } } }"; Assert.True(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty13() { const string Code = "class C { int f; int P { get { return f; } set { if (value != f) { f = value; } } }"; Assert.True(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty14() { const string Code = "class C { int f; int P { get { return f; } set { if (f == value) f = value; } }"; Assert.False(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty15() { const string Code = "class C { int f; int P { get { return f; } set { if (f != 1) f = value; } }"; Assert.False(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty16() { const string Code = "class C { int f; int P { get { return f; } set { if (f != value) { return; } } }"; Assert.False(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty17() { const string Code = "class C { int f; int f2; int P { get { return f; } set { if (f != value) { f2 = value; } } }"; Assert.False(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty18() { const string Code = "class C { int f; int P { get { return f; } set { if (f == value) return; f = value; } }"; Assert.True(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty19() { const string Code = "class C { int f; int P { get { return f; } set { if (f == value) { return; } f = value; } }"; Assert.True(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty20() { const string Code = "class C { int f; int P { get { return f; } set { if (f != value) { return; } f = value; } }"; Assert.False(IsExpandableProperty(Code)); } [Fact] public void IsExpandableProperty21() { const string Code = "class C { int f; int P { get { return f; } set { if (f == value) { return; } f = 1; } }"; Assert.False(IsExpandableProperty(Code)); } } }
33.709402
161
0.557302
[ "Apache-2.0" ]
0x53A/roslyn
src/Samples/CSharp/ImplementNotifyPropertyChanged/Test/IsExpandableTests.cs
7,890
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using RadarSoft.RadarCube.CellSet; using RadarSoft.RadarCube.Controls; using RadarSoft.RadarCube.Layout; using RadarSoft.RadarCube.Serialization; namespace RadarSoft.RadarCube.Engine { internal class LineMap : IStreamedObject { private Dictionary<Level, HashSet<Member>> map; private Dictionary<Level, HashSet<Member>> request = new Dictionary<Level, HashSet<Member>>(); internal void Clear() { map = null; if (request != null) request.Clear(); request = null; } private Dictionary<Level, HashSet<Member>> CloneMap(Dictionary<Level, HashSet<Member>> item) { var res = new Dictionary<Level, HashSet<Member>>(); foreach (var v in item) res.Add(v.Key, v.Value == null ? null : new HashSet<Member>(v.Value)); return res; } internal void AddRequest(DrillAction member, DrillAction member2, Line line) { if (request == null) request = new Dictionary<Level, HashSet<Member>>(); if (member == null) { request.Clear(); foreach (var l in line.Levels) request.Add(l, null); return; } IEnumerable<Member> mms = member.Members; if (member2 != null) mms = mms.Union(member2.Members); foreach (var m in mms) { HashSet<Member> mm; if (!request.TryGetValue(m.Level, out mm)) { mm = new HashSet<Member>(); request.Add(m.Level, mm); } if (mm != null) mm.Add(m); } } internal void ClearRequestMap() { if (request != null) request.Clear(); request = null; } internal void DoRetrieveData(Line line) { Dictionary<Level, HashSet<Member>> newmap; var req = DoMergeRequests2(line, out newmap); if (line.fM.Grid.Engine.CalculatedByServer(line.Measure) && req != null) { foreach (var v in req.Where(item => item.Value == null).ToArray()) req.Remove(v.Key); line.fM.FGrid.Engine.RetrieveLine2(req, line); } map = newmap; if (request != null) request.Clear(); } private Dictionary<Level, HashSet<Member>> DoMergeRequests2(Line line, out Dictionary<Level, HashSet<Member>> newmap) { if (request == null) { newmap = map; return null; } Normalize(request, line, false); if (map == null) { line.ClearData(); newmap = CloneMap(request); return request; } foreach (var k in map) if (request[k.Key] == null && k.Value != null) { line.ClearData(); newmap = CloneMap(request); return request; } Normalize(map, line, true); Tuple<Level, HashSet<Member>> diff = null; foreach (var k in request) { var hm = map[k.Key]; if (hm == null) continue; var md = new HashSet<Member>(k.Value.Except(hm)); if (md.Count > 0) { if (diff != null) if (diff.Item1 == k.Key) { foreach (var m in md) diff.Item2.Add(m); } else { newmap = CloneMap(request); line.ClearData(); return request; } diff = new Tuple<Level, HashSet<Member>>(k.Key, md); } } if (diff == null) { newmap = map; return null; } newmap = new Dictionary<Level, HashSet<Member>>(); var newreq = new Dictionary<Level, HashSet<Member>>(); foreach (var k in map) if (diff.Item1 != k.Key) { newmap.Add(k.Key, k.Value == null ? null : new HashSet<Member>(k.Value)); newreq.Add(k.Key, k.Value); } else { newmap.Add(k.Key, new HashSet<Member>(k.Value.Union(diff.Item2))); newreq.Add(k.Key, new HashSet<Member>(diff.Item2)); } return newreq; } private void Normalize(Dictionary<Level, HashSet<Member>> rq, Line line, bool addLevelsOnly) { if (!addLevelsOnly) { var tmp = new HashSet<Level>(); foreach (var v in rq) if (v.Value != null && CellSet.CellSet.enable_CompleteMembersCount_Little_Count(v)) tmp.Add(v.Key); foreach (var v in tmp) rq.Remove(v); } IEnumerable<Level> ll = line.Levels; if (addLevelsOnly) { if (request != null) ll = ll.Union(request.Keys); } else { if (map != null) ll = ll.Union(map.Keys); } foreach (var l in ll) if (!rq.ContainsKey(l)) rq.Add(l, null); } internal void AddRequest(Dictionary<Level, Member> d) { if (request == null) request = new Dictionary<Level, HashSet<Member>>(); foreach (var k in d) { HashSet<Member> mm; if (!request.TryGetValue(k.Key, out mm)) { mm = new HashSet<Member>(); request.Add(k.Key, mm); } if (!mm.Contains(k.Value)) mm.Add(k.Value); } } #region IStreamedObject Members void IStreamedObject.WriteStream(BinaryWriter writer, object options) { StreamUtils.WriteTag(writer, Tags.tgLineMap); if (map != null) { StreamUtils.WriteTag(writer, Tags.tgLineMap_Map); StreamUtils.WriteInt32(writer, map.Count); foreach (var ll in map) { StreamUtils.WriteString(writer, ll.Key.UniqueName); if (ll.Value != null) { StreamUtils.WriteInt32(writer, ll.Value.Count); foreach (var m in ll.Value) StreamUtils.WriteString(writer, m.UniqueName); } else { StreamUtils.WriteInt32(writer, -1); } } } StreamUtils.WriteTag(writer, Tags.tgLineMap_EOT); } void IStreamedObject.ReadStream(BinaryReader reader, object options) { var g = (OlapControl) options; if (map == null) map = new Dictionary<Level, HashSet<Member>>(); else map.Clear(); StreamUtils.CheckTag(reader, Tags.tgLineMap); for (var exit = false; !exit;) { var tag = StreamUtils.ReadTag(reader); switch (tag) { case Tags.tgLineMap_Map: var lcnt = StreamUtils.ReadInt32(reader); for (var j = 0; j < lcnt; j++) { var uniqName = StreamUtils.ReadString(reader); var l = g.Dimensions.FindLevel(uniqName); var mcnt = StreamUtils.ReadInt32(reader); if (mcnt >= 0) { var mm = new HashSet<Member>(); for (var k = 0; k < mcnt; k++) { var mname = StreamUtils.ReadString(reader); if (l != null) { var m = l.FindMember(mname); if (m != null) mm.Add(m); } } if (l != null) map.Add(l, mm); } else if (l != null) { map.Add(l, null); } } break; case Tags.tgLineMap_EOT: exit = true; break; default: StreamUtils.SkipValue(reader); break; } } } #endregion } }
33.068259
103
0.404273
[ "MIT" ]
RadarSoft/radarcube-olap-analysis
src/Engine/LineMap.cs
9,689
C#
using System; using System.Reflection; namespace Xunit { class AppDomainManager_NoAppDomain : IAppDomainManager { readonly string assemblyFileName; public AppDomainManager_NoAppDomain(string assemblyFileName) { this.assemblyFileName = assemblyFileName; } public bool HasAppDomain => false; public TObject CreateObject<TObject>(AssemblyName assemblyName, string typeName, params object[] args) { try { #if NETFRAMEWORK var type = Assembly.Load(assemblyName).GetType(typeName, throwOnError: true); #else var type = Type.GetType($"{typeName}, {assemblyName.FullName}", throwOnError: true); #endif return (TObject)Activator.CreateInstance(type, args); } catch (TargetInvocationException ex) { ex.InnerException.RethrowWithNoStackTraceLoss(); return default(TObject); } } #if NETFRAMEWORK public TObject CreateObjectFrom<TObject>(string assemblyLocation, string typeName, params object[] args) { try { var type = Assembly.LoadFrom(assemblyLocation).GetType(typeName, throwOnError: true); return (TObject)Activator.CreateInstance(type, args); } catch (TargetInvocationException ex) { ex.InnerException.RethrowWithNoStackTraceLoss(); return default(TObject); } } #endif public void Dispose() { } } }
30.301887
112
0.595268
[ "Apache-2.0" ]
0x0309/xunit
src/xunit.runner.utility/AppDomain/AppDomainManager_NoAppDomain.cs
1,606
C#
/* Copyright (c) Citrix Systems Inc. * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using XenAdmin.Core; using XenAPI; namespace XenAdmin.Actions { public class AddHostToPoolAction : PoolAbstractAction { private readonly List<Host> _hostsToRelicense; private readonly List<Host> _hostsToCpuMask; private readonly List<Host> _hostsToAdConfigure; public AddHostToPoolAction(Pool poolToJoin, Host joiningHost, Func<Host, AdUserAndPassword> getAdCredentials, Func<HostAbstractAction, Pool, long, long, bool> acceptNTolChanges, Action<List<LicenseFailure>, string> doOnLicensingFailure) : base(joiningHost.Connection, string.Format(Messages.ADDING_SERVER_TO_POOL, joiningHost.Name, poolToJoin.Name), getAdCredentials, acceptNTolChanges, doOnLicensingFailure) { this.Pool = poolToJoin; this.Host = joiningHost; Host master = Helpers.GetMaster(poolToJoin); _hostsToRelicense = new List<Host>(); _hostsToCpuMask = new List<Host>(); _hostsToAdConfigure = new List<Host>(); if (PoolJoinRules.FreeHostPaidMaster(joiningHost, master, false)) _hostsToRelicense.Add(joiningHost); if (!PoolJoinRules.CompatibleCPUs(joiningHost, master, false)) _hostsToCpuMask.Add(joiningHost); if (!PoolJoinRules.CompatibleAdConfig(joiningHost, master, false)) _hostsToAdConfigure.Add(joiningHost); this.Description = Messages.WAITING; AddCommonAPIMethodsToRoleCheck(); // SaveChanges in the ClearNonSharedSrs ApiMethodsToRoleCheck.Add("pool.set_name_label"); ApiMethodsToRoleCheck.Add("pool.set_name_description"); ApiMethodsToRoleCheck.Add("pool.set_other_config"); ApiMethodsToRoleCheck.Add("pool.add_to_other_config"); ApiMethodsToRoleCheck.Add("pool.set_gui_config"); ApiMethodsToRoleCheck.Add("pool.add_to_gui_config"); ApiMethodsToRoleCheck.Add("pool.set_default_SR"); ApiMethodsToRoleCheck.Add("pool.set_suspend_image_SR"); ApiMethodsToRoleCheck.Add("pool.set_crash_dump_SR"); ApiMethodsToRoleCheck.Add("pool.remove_from_other_config"); ApiMethodsToRoleCheck.Add("pool.remove_tags"); ApiMethodsToRoleCheck.Add("pool.set_wlb_enabled"); ApiMethodsToRoleCheck.Add("pool.set_wlb_verify_cert"); ApiMethodsToRoleCheck.Add("pool.join"); } protected override void Run() { this.Description = Messages.POOLCREATE_ADDING; // Use a try catch here for RBAC errors as they are a special case compared to other actions try { FixLicensing(Pool, _hostsToRelicense, DoOnLicensingFailure); FixAd(Pool, _hostsToAdConfigure, GetAdCredentials); bool fixedCpus = FixCpus(Pool, _hostsToCpuMask, AcceptNTolChanges); if (fixedCpus) Session = NewSession(); // We've rebooted the server, so we need to grab the new session RelatedTask = XenAPI.Pool.async_join(Session, Pool.Connection.Hostname, Pool.Connection.Username, Pool.Connection.Password); PollToCompletion(0, 90); } catch (Exception e) { Failure f = e as Failure; // I think we shouldn't trigger this any more, because it's now checked in PoolJoinRules. // But let's leave it here in case. SRET. if (f != null && f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED) { Session[] sessions = new Session[] { Session, Pool.Connection.Session }; // Special parse to cope with multiple connections. Failure.ParseRBACFailure(f, sessions); // Will not get RBAC parsed again after the throw as we have altered the error description in ParseRBACFailure throw f; } throw; } // We need a master session for ClearNonSharedSrs. // No need to log out the slave session, because the server is going to reset its database anyway. Session = NewSession(Pool.Connection); ClearNonSharedSrs(Pool); this.Description = Messages.POOLCREATE_ADDED; } protected override void OnCompleted() { if (Succeeded) { ConnectionsManager.ClearCacheAndRemoveConnection(Host.Connection); } ClearAllDelegates(); base.OnCompleted(); } } }
47.795455
141
0.638136
[ "BSD-2-Clause" ]
cheng-z/xenadmin
XenModel/Actions/Pool/AddHostToPoolAction.cs
6,311
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Diagnostics; namespace Microsoft.CodeAnalysis.Interactive { internal static class ProcessExtensions { internal static bool IsAlive(this Process process) { try { return !process.HasExited; } catch { return false; } } } }
24.363636
160
0.572761
[ "Apache-2.0" ]
0x53A/roslyn
src/Interactive/Features/Interactive/Core/ProcessExtensions.cs
536
C#
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ namespace System.Management.Automation.Internal { /// <summary> /// This is a singleton object that is used to indicate a void return result. /// </summary> /// <remarks> /// It's a singleton class. Sealed to prevent subclassing. Any operation that /// returns no actual value should return this object AutomationNull.Value. /// Anything that evaluates an MSH expression should be prepared to deal /// with receiving this result and discarding it. When received in an /// evaluation where a value is required, it should be replaced with null. /// </remarks> public static class AutomationNull { #region private_members // Private member for Value. #endregion private_members #region public_property /// <summary> /// Returns the singleton instance of this object. /// </summary> public static PSObject Value { get; } = new PSObject(); #endregion public_property } } // namespace System.Management.Automation
34.5
81
0.592593
[ "Apache-2.0", "MIT" ]
HydAu/PowerShell
src/System.Management.Automation/engine/AutomationNull.cs
1,242
C#