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
public class Order { public virtual string OrderId { get; set; } }
18.5
48
0.648649
[ "Apache-2.0" ]
Cogax/docs.particular.net
samples/router/update-and-publish/Router_3/Frontend/Order.cs
73
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.V20200901.Outputs { /// <summary> /// Desired outbound IP resources for the cluster load balancer. /// </summary> [OutputType] public sealed class ManagedClusterLoadBalancerProfileResponseOutboundIPs { /// <summary> /// A list of public IP resources. /// </summary> public readonly ImmutableArray<Outputs.ResourceReferenceResponse> PublicIPs; [OutputConstructor] private ManagedClusterLoadBalancerProfileResponseOutboundIPs(ImmutableArray<Outputs.ResourceReferenceResponse> publicIPs) { PublicIPs = publicIPs; } } }
31.193548
129
0.706308
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/ContainerService/V20200901/Outputs/ManagedClusterLoadBalancerProfileResponseOutboundIPs.cs
967
C#
namespace JSON_Processing { using Newtonsoft.Json; public class Link { [JsonProperty("@rel")] public string Rel { get; set; } [JsonProperty("@href")] public string Href { get; set; } } }
17
40
0.554622
[ "MIT" ]
Telerik-Homework-ValentinRangelov/Homework
Databases and SQL/JSON-Processing/JSON-Processing/JSON-Processing/Link.cs
240
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace TournamentAssistantUI.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.709677
151
0.585502
[ "MIT" ]
Auros/TournamentAssistant
TournamentAssistantUI/Properties/Settings.Designer.cs
1,078
C#
using Microsoft.Coyote.SystematicTesting; using Plang.Compiler; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using UnitTests.Core; namespace UnitTests.Runners { internal class CoyoteRunner : ICompilerTestRunner { private static readonly string CoyoteAssemblyLocation = Path.GetDirectoryName(typeof(TestingEngine).GetTypeInfo().Assembly.Location); private readonly FileInfo[] nativeSources; private readonly FileInfo[] sources; public CoyoteRunner(FileInfo[] sources) { this.sources = sources; nativeSources = new FileInfo[] { }; } public CoyoteRunner(FileInfo[] sources, FileInfo[] nativeSources) { this.sources = sources; this.nativeSources = nativeSources; } private void FileCopy(string src, string target, bool overwrite) { // during parallel testing we might get "The process cannot access the file because it is being used by another process." int retries = 5; while (retries-- > 0) { try { File.Copy(src, target, overwrite); return; } catch (System.IO.IOException) { if (retries == 1) { throw; } System.Threading.Thread.Sleep(1000); } } } public int? RunTest(DirectoryInfo scratchDirectory, out string stdout, out string stderr) { FileInfo[] compiledFiles = DoCompile(scratchDirectory).ToArray(); CreateFileWithMainFunction(scratchDirectory); CreateProjectFile(scratchDirectory); string coyoteExtensionsPath = Path.Combine(Constants.SolutionDirectory, "Bld", "Drops", Constants.BuildConfiguration, "Binaries", "CoyoteRuntime.dll"); FileCopy(coyoteExtensionsPath, Path.Combine(scratchDirectory.FullName, "CoyoteRuntime.dll"), true); foreach (FileInfo nativeFile in nativeSources) { FileCopy(nativeFile.FullName, Path.Combine(scratchDirectory.FullName, nativeFile.Name), true); } string[] args = new[] { "build", "Test.csproj" }; int exitCode = ProcessHelper.RunWithOutput(scratchDirectory.FullName, out stdout, out stderr, "dotnet", args); if (exitCode == 0) { exitCode = RunCoyoteTester(scratchDirectory.FullName, Path.Combine(scratchDirectory.FullName, "Test.dll"), out string testStdout, out string testStderr); stdout += testStdout; stderr += testStderr; // TODO: bug Coyote folks to either set an exit code or print obvious indicator that can be machine-processed. if (testStdout.Contains("buggy schedules")) { exitCode = 1; } } return exitCode; } private void CreateFileWithMainFunction(DirectoryInfo dir) { string testCode = @" using Microsoft.Coyote; using Microsoft.Coyote.SystematicTesting; using System; using System.Linq; namespace Main { public class _TestRegression { public static void Main(string[] args) { // Optional: increases verbosity level to see the Coyote runtime log. Configuration configuration = Configuration.Create().WithTestingIterations(100); configuration.WithMaxSchedulingSteps(1000); TestingEngine engine = TestingEngine.Create(configuration, DefaultImpl.Execute); engine.Run(); string bug = engine.TestReport.BugReports.FirstOrDefault(); if (bug != null) { Console.WriteLine(bug); Environment.Exit(1); } Environment.Exit(0); // for debugging: /* For replaying a bug and single stepping Configuration configuration = Configuration.Create(); configuration.WithVerbosityEnabled(true); // update the path to the schedule file. configuration.WithReplayStrategy(""AfterNewUpdate.schedule""); TestingEngine engine = TestingEngine.Create(configuration, DefaultImpl.Execute); engine.Run(); string bug = engine.TestReport.BugReports.FirstOrDefault(); if (bug != null) { Console.WriteLine(bug); } */ } } }"; using (StreamWriter outputFile = new StreamWriter(Path.Combine(dir.FullName, "Test.cs"), false)) { outputFile.WriteLine(testCode); } } private void CreateProjectFile(DirectoryInfo dir) { string projectFileContents = @" <Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <TargetFramework >netcoreapp3.1</TargetFramework> <ApplicationIcon /> <OutputType>Exe</OutputType> <StartupObject /> <LangVersion >latest</LangVersion> <OutputPath>.</OutputPath> </PropertyGroup > <PropertyGroup Condition = ""'$(Configuration)|$(Platform)'=='Debug|AnyCPU'""> <WarningLevel>0</WarningLevel> </PropertyGroup> <ItemGroup> <PackageReference Include=""Microsoft.Coyote"" Version=""1.0.5""/> <Reference Include = ""CoyoteRuntime.dll""/> </ItemGroup> </Project>"; using (StreamWriter outputFile = new StreamWriter(Path.Combine(dir.FullName, "Test.csproj"), false)) { outputFile.WriteLine(projectFileContents); } } private int RunCoyoteTester(string directory, string dllPath, out string stdout, out string stderr) { return ProcessHelper.RunWithOutput(directory, out stdout, out stderr, "dotnet", dllPath); } private IEnumerable<FileInfo> DoCompile(DirectoryInfo scratchDirectory) { Compiler compiler = new Compiler(); TestExecutionStream outputStream = new TestExecutionStream(scratchDirectory); CompilationJob compilationJob = new CompilationJob(outputStream, CompilerOutput.Coyote, sources, "Main"); compiler.Compile(compilationJob); return outputStream.OutputFiles; } } }
36.238889
163
0.597271
[ "MIT" ]
KelvinLi2020/P
Tst/UnitTests/Runners/CoyoteRunner.cs
6,525
C#
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using CharSheet.Api.Services; using CharSheet.Api.Models; namespace CharSheet.Api.Controllers { [ApiController] [Route("/api/templates")] public class TemplatesController : ControllerBase { private readonly IBusinessService _service; public TemplatesController( IBusinessService service) { this._service = service; } #region Action Methods [HttpGet("")] public async Task<ActionResult<IEnumerable<TemplateModel>>> GetTemplates(Boolean user = false) { try { if (user) { var identity = HttpContext.User.Identity as ClaimsIdentity; var userId = Guid.Parse(identity.Claims.First(claim => claim.Type == "Id").Value); return Ok(await _service.GetTemplates(userId)); } return Ok(await _service.GetTemplates()); } catch { return BadRequest(); } } [HttpGet("{id}")] public async Task<ActionResult> GetTemplate(Guid? id) { try { return Ok(await _service.GetTemplate(id)); } catch { return BadRequest(); } } [HttpPost("")] [Authorize] public async Task<ActionResult<TemplateModel>> CreateTemplate(TemplateModel templateModel) { try { if (ModelState.IsValid) { var identity = HttpContext.User.Identity as ClaimsIdentity; var userId = Guid.Parse(identity.Claims.First(claim => claim.Type == "Id").Value); templateModel = await _service.CreateTemplate(templateModel, userId); return CreatedAtAction(nameof(GetTemplates), new { id = templateModel.TemplateId }, templateModel); } else { throw new InvalidOperationException("Model state invalid."); } } catch { return BadRequest(); } } #endregion } }
30.518519
119
0.527913
[ "MIT" ]
042020-dotnet-uta/johnKear-repo2
project2/CharSheetApi/CharSheet.Api/Controllers/TemplatesController.cs
2,472
C#
using System.Collections.Concurrent; using System.Collections.Generic; using ImageCasterCore.Api; using ImageCasterCore.Configuration.Checkers; using ImageCasterCore.Extensions; using ImageMagick; namespace ImageCasterCore.Checkers { /// <summary> /// Verify that all images are sized two powers of two. /// Computers work much faster with images that have heights and widths /// that are powers of two, so it can be desirable in many cases, especially /// game development to ensure images fit this rule, even if it means padding white space. /// </summary> public class PowerOfTwoChecker : IChecker { public List<PowerOfTwoConfig> Config { get; } public PowerOfTwoChecker(List<PowerOfTwoConfig> config) { this.Config = config.RequireNonNull(); } public IEnumerable<Failure> Check() { List<Failure> failures = new List<Failure>(); foreach (PowerOfTwoConfig config in Config) { DataResolver resolver = new DataResolver(config.Source); List<ResolvedData> resolvedFiles = resolver.Data; foreach (ResolvedData resolvedFile in resolvedFiles) { using (IMagickImage magickImage = resolvedFile.ToMagickImage()) { if (!IsPowerOfTwo((uint) magickImage.Height, (uint) magickImage.Width)) { failures.Add(new Failure(resolvedFile, "dimensions are not powers of 2.")); } } } } return failures; } public bool IsPowerOfTwo(params uint[] values) { foreach (uint value in values) { if ((value & value - 1) == 0 && value != 0) { return true; } } return false; } } }
32.190476
103
0.546351
[ "Apache-2.0" ]
Elypia/ImageCaster
src/ImageCasterCore/Checkers/PowerOfTwoChecker.cs
2,028
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("MiTagger")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MiTagger")] [assembly: AssemblyCopyright("")] [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("a2cfc5e4-82d1-4521-836b-b3aefa0c9eb4")] // 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.4.0")] [assembly: AssemblyFileVersion("1.0.4.0")]
36.945946
84
0.746159
[ "MIT" ]
dxzl/MiTagger
MiTagger/Properties/AssemblyInfo.cs
1,369
C#
using System; using Xunit; namespace Examples.Counter.Tests { public class AppStateTests { [Fact] public void Constructor_DefaultsCounterToZero() { var sut = new AppState(); Assert.Equal(0, sut.CounterValue); } [Fact] public void ConstructorWithParams_SetsCounter() { var sut = new AppState(2); Assert.Equal(2, sut.CounterValue); } } }
15.416667
49
0.694595
[ "MIT" ]
industriousone/industrious-redux
Examples.Counter/Examples.Counter.Tests/AppStateTests.cs
370
C#
using System; using System.Collections.Generic; using System.Windows.Threading; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Newtonsoft.Json; using Microsoft.VisualBasic; using UtilsNS; using System.Data.SqlTypes; namespace AOMmaster { /// <summary> /// Interaction logic for AOMmasterUC.xaml /// </summary> public partial class AOMmasterUC : UserControl { Dictionary<string, SemiAxisUC> semis; //MW-TTL dev3 pin24 Hardware hardware; public AOMmasterUC() { InitializeComponent(); semis = new Dictionary<string, SemiAxisUC>() { ["2DMOT"] = SemiAxisUC0, ["Push"] = SemiAxisUC1, ["X-positive"] = SemiAxisUC2, ["X-negative"] = SemiAxisUC3, ["Y-positive"] = SemiAxisUC4, ["Y-negative"] = SemiAxisUC5, ["Z-positive"] = SemiAxisUC6, ["Z-negative"] = SemiAxisUC7, ["3DMOT-1"] = SemiAxisUC8, ["3DMOT-2"] = SemiAxisUC9, ["2DMOT-1"] = SemiAxisUC10, ["2DMOT-2"] = SemiAxisUC11, ["Detection"] = SemiAxisUC12 }; } Dictionary<string, Dictionary<string, string>> semiValues { get { Dictionary<string, Dictionary<string, string>> sv = new Dictionary<string, Dictionary<string, string>>(); foreach (KeyValuePair<string, SemiAxisUC> semi in semis) { sv[semi.Key] = new Dictionary<string, string>() { ["Enabled"] = semi.Value.Enabled.ToString(), ["VCO-volt"] = semi.Value.VCO_V.ToString("G5"), ["VCA-volt"] = semi.Value.VCA_V.ToString("G5"), ["VCO-unit"] = semi.Value.VCO_U.ToString(), ["VCA-unit"] = semi.Value.VCA_U.ToString() }; } return sv; } set { foreach (KeyValuePair<string, SemiAxisUC> semi in semis) { if (!value.ContainsKey(semi.Key)) continue; if (!value[semi.Key].ContainsKey("Enabled")) continue; semi.Value.Enabled = Convert.ToBoolean(value[semi.Key]["Enabled"]); semi.Value.VCO_U = false; semi.Value.VCA_U = false; // set to volts semi.Value.VCO_V = Convert.ToDouble(value[semi.Key]["VCO-volt"]); semi.Value.VCA_V = Convert.ToDouble(value[semi.Key]["VCA-volt"]); semi.Value.VCO_U = Convert.ToBoolean(value[semi.Key]["VCO-unit"]); semi.Value.VCA_U = Convert.ToBoolean(value[semi.Key]["VCA-unit"]); } } } public bool readSemiValues(string fn) { string ffn = System.IO.Path.ChangeExtension(fn, ".stg"); if (File.Exists(ffn)) { string json = System.IO.File.ReadAllText(ffn); semiValues = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(json); return true; } else return false; } public void writeSemiValues(string fn) { string json = JsonConvert.SerializeObject(semiValues); System.IO.File.WriteAllText(System.IO.Path.ChangeExtension(fn,".stg"), json); } public void log(string txt, bool detail) { if (txt.Substring(0, 5) == "Error") { Utils.log(tbLogger, txt, Brushes.Red); return; } if (!chkLog.IsChecked.Value) return; SolidColorBrush clr = detail ? Brushes.DarkGreen : Brushes.Navy; if (detail) { if (chkDetailed.IsChecked.Value) Utils.log(tbLogger, txt, clr); } else Utils.log(tbLogger, txt, clr); } private void btnClear_Click(object sender, RoutedEventArgs e) { tbLogger.Document.Blocks.Clear(); } public void Init() { hardware = new Hardware(); hardware.configHardware("Dev3", "Dev2", -10, 10); int i = 0; Color clr = Brushes.Black.Color; AnalogConfig vco = new AnalogConfig(); vco.title = "VCO"; vco.calibr = new List<Point>(); AnalogConfig vca = new AnalogConfig(); vca.title = "VCA"; vca.calibr = new List<Point>(); vco.minVolt = hardware.analogMin; vca.minVolt = hardware.analogMin; vco.maxVolt = hardware.analogMax; vca.maxVolt = hardware.analogMax; // regular semis foreach (KeyValuePair<string, SemiAxisUC> semi in semis) { if (semi.Value.Custom) continue; vco.chnNumb = 4+i; vca.chnNumb = 20+i; switch (i) { case 0: clr = Brushes.Goldenrod.Color; break; case 1: clr = Brushes.OrangeRed.Color; break; case 2: case 3: clr = Brushes.Teal.Color; break; case 4: case 5: clr = Brushes.LimeGreen.Color; break; case 6: case 7: clr = Brushes.Blue.Color; break; } semi.Value.Config(semi.Key, i, vco, vca, clr); if (i.Equals(7)) break; i++; } // custion semis vco.title = "3DMOTCoil"; vco.chnNumb = 18; vca.title = "xbias3DCoil"; vca.chnNumb = 15; semis["3DMOT-1"].Config("3DMOT-1", "DetTTL", 21, vco, vca, Brushes.Goldenrod.Color); vco.title = "ybias3DCoil"; vco.chnNumb = 16; vca.title = "zbias3DCoil"; vca.chnNumb = 17; semis["3DMOT-2"].Config("3DMOT-2", "FreeDO1", 25, vco, vca, Brushes.Goldenrod.Color); vco.title = "2DMOTCoil"; vco.chnNumb = 19; vca.title = "xbias2DCoil"; vca.chnNumb = 13; semis["2DMOT-1"].Config("2DMOT-1", "M2TTL", 20, vco, vca, Brushes.Teal.Color); vco.title = "ybias2DCoil"; vco.chnNumb = 14; vca.title = ""; vca.chnNumb = -1; semis["2DMOT-2"].Config("2DMOT-2", "MWTTL", 24, vco, vca, Brushes.Teal.Color); vco.title = "VCO"; vco.chnNumb = 0; vca.title = "VCA"; vca.chnNumb = 1; semis["Detection"].Config("Detection", "Enabled", 26, vco, vca, Brushes.Coral.Color); foreach (KeyValuePair<string, SemiAxisUC> semi in semis) { semi.Value.analogVCO.OnAnalogChanged += new AnalogUC.AnalogChangedHandler(hardware.AnalogOut); semi.Value.analogVCA.OnAnalogChanged += new AnalogUC.AnalogChangedHandler(hardware.AnalogOut); semi.Value.OnDigitalChanged += new SemiAxisUC.DigitalChangedHandler(hardware.WriteSingleOut); semi.Value.OnLog += new SemiAxisUC.LogHandler(log); semi.Value.analogVCO.OnLog += new AnalogUC.LogHandler(log); semi.Value.analogVCA.OnLog += new AnalogUC.LogHandler(log); semi.Value.analogVCO.OnSelect += new AnalogUC.SelectHandler(setCalibration); semi.Value.analogVCA.OnSelect += new AnalogUC.SelectHandler(setCalibration); } hardware.OnLog += new Hardware.LogHandler(log); CalibrUC1.btnDone.Click += new RoutedEventHandler(getCalibration); CalibrUC1.btnCancel.Click += new RoutedEventHandler(getCalibration); CalibrUC1.btnInsertVal.Click += new RoutedEventHandler(insertValue); } readonly string lastSettingFile = "default.stg"; private DispatcherTimer dTimer; private void AOMmasterUC0_Loaded(object sender, RoutedEventArgs e) { Init(); dTimer = new DispatcherTimer(); dTimer.Tick += new EventHandler(dTimer_Tick); dTimer.Interval = new TimeSpan(0, 0, 1); dTimer.Start(); } private void dTimer_Tick(object sender, EventArgs e) { readSemiValues(Utils.configPath + lastSettingFile); dTimer.Stop(); UpdateSettings(); log("Default setting loaded", false); } public void Closing() { writeSemiValues(Utils.configPath + lastSettingFile); foreach (KeyValuePair<string, SemiAxisUC> semi in semis) { semi.Value.Closing(); } } public void UpdateSettings() { int idx = listSettings.SelectedIndex; string[] files = Directory.GetFiles(Utils.configPath, "*.stg"); listSettings.Items.Clear(); foreach (var ffn in files) { string fn = System.IO.Path.GetFileName(ffn); if (fn == "default.stg") continue; ListBoxItem lbi = new ListBoxItem(); lbi.Content = fn; lbi.Foreground = Brushes.Navy; lbi.FontSize = 14; listSettings.Items.Add(lbi); } if(listSettings.Items.Count > 0) { if (idx == -1) listSettings.SelectedIndex = 0; else listSettings.SelectedIndex = idx; } } private void btnUpdate_Click(object sender, RoutedEventArgs e) { if (sender == btnAdd) { string newSetting = Interaction.InputBox("Name the new setting"); if (newSetting != "") { writeSemiValues(Utils.configPath + newSetting); UpdateSettings(); log("> Add new setting file: " + newSetting, false); } return; } if (listSettings.SelectedIndex == -1) Utils.TimedMessageBox("No setting has been selected"); ListBoxItem lbi = (listSettings.SelectedItem as ListBoxItem); string selSetting = lbi.Content.ToString(); if (sender == btnUpdate) { readSemiValues(Utils.configPath + selSetting); log("> Update state by " + selSetting, false); } if (sender == btnRemove) { if (MessageBox.Show("Do you really ???", "BIG QUESTION", MessageBoxButton.YesNo) == MessageBoxResult.Yes) File.Delete(Utils.configPath + selSetting); log("> Remove setting file: " + selSetting, false); } if (sender == btnReplace) { File.Delete(Utils.configPath + selSetting); writeSemiValues(Utils.configPath + selSetting); log("> Replace setting file: " + selSetting, false); } UpdateSettings(); } #region calibration private AnalogUC whichAnalog(AnalogConfig ac) { foreach (KeyValuePair<string, SemiAxisUC> semi in semis) { if ((ac.groupTitle == semi.Value.analogVCO.analogConfig.groupTitle) && (ac.title == semi.Value.analogVCO.analogConfig.title)) { return semi.Value.analogVCO; } if ((ac.groupTitle == semi.Value.analogVCA.analogConfig.groupTitle) && (ac.title == semi.Value.analogVCA.analogConfig.title)) { return semi.Value.analogVCA; } } return null; } AnalogConfig selectAC = new AnalogConfig(); // ac buffer public void setCalibration(ref AnalogConfig ac) { AnalogUC analog = whichAnalog(ac); if(Utils.isNull(analog)) { Utils.TimedMessageBox("Analog channel not found", "Problem", 2500); return; } if (tiCalibr.Visibility == Visibility.Visible) { Utils.TimedMessageBox("Another calibration is in progress", "Problem", 2500); analog.Selected = false; return; } selectAC.Assign(ac); tiCalibr.Visibility = Visibility.Visible; tiLog.Visibility = Visibility.Collapsed; tiSetting.Visibility = Visibility.Collapsed; tabControl.SelectedIndex = 1; CalibrUC1.Init(selectAC); } private void getCalibration(object sender, RoutedEventArgs e) { AnalogUC auc = whichAnalog(selectAC); auc.Selected = false; tiCalibr.Visibility = Visibility.Collapsed; tiLog.Visibility = Visibility.Visible; tiSetting.Visibility = Visibility.Visible; tabControl.SelectedIndex = 0; if (!(sender is Button)) return; if ((sender as Button).Name == "btnCancel") return; auc.Config(CalibrUC1.analogConfig, false); } private void insertValue(object sender, RoutedEventArgs e) { CalibrUC1.insertValue(whichAnalog(selectAC).target); } #endregion } }
42.751553
153
0.531018
[ "MIT" ]
ColdMatter/Navigator
AOMmaster/AOMmasterUC.xaml.cs
13,768
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the chime-2018-05-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Chime.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Chime.Model.Internal.MarshallTransformations { /// <summary> /// CreateVoiceConnector Request Marshaller /// </summary> public class CreateVoiceConnectorRequestMarshaller : IMarshaller<IRequest, CreateVoiceConnectorRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((CreateVoiceConnectorRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreateVoiceConnectorRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Chime"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-05-01"; request.HttpMethod = "POST"; request.ResourcePath = "/voice-connectors"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetAwsRegion()) { context.Writer.WritePropertyName("AwsRegion"); context.Writer.Write(publicRequest.AwsRegion); } if(publicRequest.IsSetName()) { context.Writer.WritePropertyName("Name"); context.Writer.Write(publicRequest.Name); } if(publicRequest.IsSetRequireEncryption()) { context.Writer.WritePropertyName("RequireEncryption"); context.Writer.Write(publicRequest.RequireEncryption); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static CreateVoiceConnectorRequestMarshaller _instance = new CreateVoiceConnectorRequestMarshaller(); internal static CreateVoiceConnectorRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateVoiceConnectorRequestMarshaller Instance { get { return _instance; } } } }
35.327434
155
0.622745
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/Chime/Generated/Model/Internal/MarshallTransformations/CreateVoiceConnectorRequestMarshaller.cs
3,992
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.Azure.IIoT.OpcUa.Subscriber.Handlers { using Microsoft.Azure.IIoT.OpcUa.Subscriber; using Microsoft.Azure.IIoT.OpcUa.Subscriber.Models; using Microsoft.Azure.IIoT.OpcUa.Protocol; using Microsoft.Azure.IIoT.Hub; using Opc.Ua; using Opc.Ua.Extensions; using Opc.Ua.PubSub; using Serilog; using System; using System.IO; using System.Threading.Tasks; using System.Collections.Generic; using System.Linq; /// <summary> /// Publisher message handling /// </summary> public sealed class MonitoredItemSampleBinaryHandler : IDeviceTelemetryHandler { /// <inheritdoc/> public string MessageSchema => Core.MessageSchemaTypes.MonitoredItemMessageBinary; /// <summary> /// Create handler /// </summary> /// <param name="encoder"></param> /// <param name="handlers"></param> /// <param name="logger"></param> public MonitoredItemSampleBinaryHandler(IVariantEncoderFactory encoder, IEnumerable<ISubscriberMessageProcessor> handlers, ILogger logger) { _encoder = encoder ?? throw new ArgumentNullException(nameof(encoder)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _handlers = handlers?.ToList() ?? throw new ArgumentNullException(nameof(handlers)); } /// <inheritdoc/> public async Task HandleAsync(string deviceId, string moduleId, byte[] payload, IDictionary<string, string> properties, Func<Task> checkpoint) { try { var context = new ServiceMessageContext(); var decoder = new BinaryDecoder(new MemoryStream(payload), context); var messages = decoder.ReadBoolean(null) // is Batch? ? decoder.ReadEncodeableArray(null, typeof(MonitoredItemMessage)) as MonitoredItemMessage[] : (decoder.ReadEncodeable(null, typeof(MonitoredItemMessage)) as MonitoredItemMessage).YieldReturn(); foreach (var message in messages) { var type = BuiltInType.Null; var codec = _encoder.Create(context); var sample = new MonitoredItemMessageModel { PublisherId = (message.ExtensionFields != null && message.ExtensionFields.TryGetValue("PublisherId", out var publisherId)) ? publisherId : message.ApplicationUri ?? message.EndpointUrl, DataSetWriterId = (message.ExtensionFields != null && message.ExtensionFields.TryGetValue("DataSetWriterId", out var dataSetWriterId)) ? dataSetWriterId : message.EndpointUrl ?? message.ApplicationUri, NodeId = message.NodeId.AsString(context), DisplayName = message.DisplayName, Timestamp = message.Timestamp, SequenceNumber = message.SequenceNumber, Value = message?.Value == null ? null : codec.Encode(message.Value.WrappedValue, out type), DataType = type == BuiltInType.Null ? null : type.ToString(), Status = (message?.Value?.StatusCode.Code == StatusCodes.Good) ? null : StatusCode.LookupSymbolicId(message.Value.StatusCode.Code), SourceTimestamp = (message?.Value?.SourceTimestamp == DateTime.MinValue) ? null : message?.Value?.SourceTimestamp, SourcePicoseconds = (message?.Value?.SourcePicoseconds == 0) ? null : message?.Value?.SourcePicoseconds, ServerTimestamp = (message?.Value?.ServerTimestamp == DateTime.MinValue) ? null : message?.Value?.ServerTimestamp, ServerPicoseconds = (message?.Value?.ServerPicoseconds == 0) ? null : message?.Value?.ServerPicoseconds, EndpointId = (message.ExtensionFields != null && message.ExtensionFields.TryGetValue("EndpointId", out var endpointId)) ? endpointId : message.ApplicationUri ?? message.EndpointUrl }; await Task.WhenAll(_handlers.Select(h => h.HandleSampleAsync(sample))); } } catch (Exception ex) { _logger.Error(ex,"Publishing messages failed - skip"); } } /// <inheritdoc/> public Task OnBatchCompleteAsync() { return Task.CompletedTask; } private readonly IVariantEncoderFactory _encoder; private readonly ILogger _logger; private readonly List<ISubscriberMessageProcessor> _handlers; } }
50.885714
108
0.566161
[ "MIT" ]
GBBBAS/Industrial-IoT
components/opc-ua/src/Microsoft.Azure.IIoT.OpcUa.Subscriber/src/Handlers/MonitoredItemSampleBinaryHandler.cs
5,343
C#
using UnityEngine; namespace RabbitStewdio.Unity.WeaponSystem.Weapons.Guns { public class HitAreaMarker: MonoBehaviour { // a simple marker object that assists in aiming. It makes it // faster to find a valid target spot to shoot at. Without it // we either shoot at the ground (where the rigidbody position // is or shoot at the center of the bounding box (and thus may // actually miss the target. } }
32.785714
70
0.679739
[ "MIT" ]
tmorgner/WeaponSystem
Assets/Plugins/WeaponSystem/Scripts/Weapons/Guns/HitAreaMarker.cs
461
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Management.Automation; using System.Diagnostics.CodeAnalysis; // // Now define the set of commands for manipulating modules. // namespace Microsoft.PowerShell.Commands { #region New-Module /// <summary> /// Implements a cmdlet that creates a dynamic module from a scriptblock.. /// </summary> [Cmdlet(VerbsCommon.New, "Module", DefaultParameterSetName = "ScriptBlock", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=141554")] [OutputType(typeof(PSModuleInfo))] public sealed class NewModuleCommand : ModuleCmdletBase { /// <summary> /// This parameter specifies the name to assign to the dynamic module. /// </summary> [Parameter(ParameterSetName = "Name", Mandatory = true, ValueFromPipeline = true, Position = 0)] public string Name { set { _name = value; } get { return _name; } } private string _name; /// <summary> /// Specify a scriptblock to use for the module body... /// </summary> [Parameter(ParameterSetName = "Name", Mandatory = true, Position = 1)] [Parameter(ParameterSetName = "ScriptBlock", Mandatory = true, Position = 0)] [ValidateNotNull] public ScriptBlock ScriptBlock { get { return _scriptBlock; } set { _scriptBlock = value; } } private ScriptBlock _scriptBlock; /// <summary> /// This parameter specifies the patterns matching the functions to import from the module... /// </summary> [Parameter] [ValidateNotNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] public string[] Function { set { if (value == null) return; _functionImportList = value; // Create the list of patterns to match at parameter bind time // so errors will be reported before loading the module... BaseFunctionPatterns = new List<WildcardPattern>(); foreach (string pattern in _functionImportList) { BaseFunctionPatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase)); } } get { return _functionImportList; } } private string[] _functionImportList = Utils.EmptyArray<string>(); /// <summary> /// This parameter specifies the patterns matching the cmdlets to import from the module... /// </summary> [Parameter] [ValidateNotNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] public string[] Cmdlet { set { if (value == null) return; _cmdletImportList = value; // Create the list of patterns to match at parameter bind time // so errors will be reported before loading the module... BaseCmdletPatterns = new List<WildcardPattern>(); foreach (string pattern in _cmdletImportList) { BaseCmdletPatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase)); } } get { return _cmdletImportList; } } private string[] _cmdletImportList = Utils.EmptyArray<string>(); /// <summary> /// This parameter causes the session state instance to be written... /// </summary> [Parameter] public SwitchParameter ReturnResult { get { return (SwitchParameter)_returnResult; } set { _returnResult = value; } } private bool _returnResult; /// <summary> /// This parameter causes the session state instance to be written... /// </summary> [Parameter] public SwitchParameter AsCustomObject { get { return (SwitchParameter)_asCustomObject; } set { _asCustomObject = value; } } private bool _asCustomObject; /// <summary> /// The arguments to pass to the scriptblock used to create the module. /// </summary> [Parameter(ValueFromRemainingArguments = true)] [Alias("Args")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] public object[] ArgumentList { get { return _arguments; } set { _arguments = value; } } private object[] _arguments; /// <summary> /// Create the new module... /// </summary> protected override void EndProcessing() { // Create a module from a scriptblock... if (_scriptBlock != null) { string gs = System.Guid.NewGuid().ToString(); if (string.IsNullOrEmpty(_name)) { _name = PSModuleInfo.DynamicModulePrefixString + gs; } try { Context.Modules.IncrementModuleNestingDepth(this, _name); List<object> results = null; PSModuleInfo localModule = null; try { // The path for a "dynamic" module will be a GUID so it's unique. localModule = Context.Modules.CreateModule(_name, gs, _scriptBlock, null, out results, _arguments); // Export all functions and variables if no exports were specified... if (!localModule.SessionState.Internal.UseExportList) { List<WildcardPattern> cmdletPatterns = BaseCmdletPatterns ?? MatchAll; List<WildcardPattern> functionPatterns = BaseFunctionPatterns ?? MatchAll; ModuleIntrinsics.ExportModuleMembers(this, localModule.SessionState.Internal, functionPatterns, cmdletPatterns, BaseAliasPatterns, BaseVariablePatterns, null); } } catch (RuntimeException e) { // Preserve the inner module invocation info... e.ErrorRecord.PreserveInvocationInfoOnce = true; WriteError(e.ErrorRecord); } // If the module was created successfully, then process the result... if (localModule != null) { if (_returnResult) { // import the specified members... ImportModuleMembers(localModule, string.Empty /* no -Prefix for New-Module cmdlet */); WriteObject(results, true); } else if (_asCustomObject) { WriteObject(localModule.AsCustomObject()); } else { // import the specified members... ImportModuleMembers(localModule, string.Empty /* no -Prefix for New-Module cmdlet */); WriteObject(localModule); } } } finally { Context.Modules.DecrementModuleNestingCount(); } return; } } } #endregion }
35.877193
146
0.526406
[ "MIT" ]
DCtheGeek/PowerShell
src/System.Management.Automation/engine/Modules/NewModuleCommand.cs
8,180
C#
namespace MyApp.Client; public static class AppRoles { public const string Admin = nameof(Admin); public const string Employee = nameof(Employee); public const string Manager = nameof(Manager); public static string[] All { get; set; } = { Admin, Employee, Manager }; }
27.090909
77
0.674497
[ "MIT" ]
NetCoreTemplates/blazor-wasm
MyApp.Client/Auth/AppRoles.cs
290
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using KafkaNet; using KafkaNet.Model; using KafkaNet.Protocol; namespace QueueWatcher { public partial class Watcher : Form, IKafkaLog { private BrokerRouter _router = null; internal BrokerRouter router { get { if(_router == null) { if(!String.IsNullOrWhiteSpace(servers.Text)) { List<Uri> uris = new List<Uri>(); foreach(string server in servers.Text.Split(new char[] {' ', '|'})) { uris.Add(new Uri(server)); } var options = new KafkaOptions(uris.ToArray()) { Log = this }; _router = new BrokerRouter(options); } } return _router; } } private Producer _producer = null; internal Producer producer { get { if(_producer == null && router != null && !String.IsNullOrWhiteSpace(topic.Text)) { _producer = new Producer(router, 10); } return _producer; } } public Watcher() { InitializeComponent(); int workers, completionPortThreads; ThreadPool.GetAvailableThreads(out workers, out completionPortThreads); if(workers == 0) { ThreadPool.GetMaxThreads(out workers, out completionPortThreads); ThreadPool.SetMaxThreads(workers + 5, completionPortThreads + 5); } } private Thread sendThread = null; private void send_Click(object sender, EventArgs e) { List<KafkaNet.Protocol.Message> messages = new List<KafkaNet.Protocol.Message>(); messages.Add(new KafkaNet.Protocol.Message(message.Text)); var task = producer.SendMessageAsync(topic.Text, messages); } private delegate void AddEntryDelegate(string message); public void AddEntry(string message) { if (this.messages.InvokeRequired) { this.Invoke(new AddEntryDelegate(this.AddEntry), new object[] { message }); return; } ListViewItem item = new ListViewItem(new string[] { message }); messages.Items.Add(item); messages.Items[messages.Items.Count - 1].EnsureVisible(); while (messages.Items.Count > 1000) messages.Items.RemoveAt(0); } private Task followTask = null; private CancellationTokenSource cancelFollow = null; private void follow_Click(object sender, EventArgs e) { if (cancelFollow != null) { cancelFollow.Cancel(); cancelFollow = null; } cancelFollow = new CancellationTokenSource(); followTask = Task.Run(() => { var consumer = new Consumer(new ConsumerOptions(topic.Text, router)); foreach (var message in consumer.Consume(cancelFollow.Token)) { AddEntry(Encoding.UTF8.GetString(message.Value)); } }); } private delegate void LogEntryDelegate(string message, string severity); public void LogEntry(string message, string severity) { if (this.messages.InvokeRequired) { this.Invoke(new LogEntryDelegate(this.LogEntry), new object[] { message, severity }); return; } ListViewItem item = new ListViewItem(new string[] { severity, message }); log.Items.Add(item); log.Items[log.Items.Count - 1].EnsureVisible(); while (log.Items.Count > 1000) log.Items.RemoveAt(0); } public void DebugFormat(string format, params object[] args) { LogEntry(String.Format(format, args), "Debug"); } public void InfoFormat(string format, params object[] args) { LogEntry(String.Format(format, args), "Info"); } public void WarnFormat(string format, params object[] args) { LogEntry(String.Format(format, args), "Warn"); } public void ErrorFormat(string format, params object[] args) { LogEntry(String.Format(format, args), "Error"); } public void FatalFormat(string format, params object[] args) { LogEntry(String.Format(format, args), "Fatal"); } private void copyToolStripMenuItem_Click(object sender, EventArgs e) { if(messages.SelectedItems.Count == 1) { Clipboard.Clear(); Clipboard.SetText(messages.SelectedItems[0].Text); } } } }
25.421687
89
0.670616
[ "Apache-2.0" ]
nekstrom/kafka-net
src/QueueWatcher/Watcher.cs
4,222
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CreateAzureStencilsFromSVG.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CreateAzureStencilsFromSVG.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
44
192
0.617543
[ "MIT" ]
AddyV/CreateAzureStencilsFromSVG
Properties/Resources.Designer.cs
2,818
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using CMS.Base; using CMS.CustomTables; using CMS.DataEngine; using CMS.DocumentEngine; using CMS.EventLog; using CMS.Base.Web.UI; using CMS.Helpers; using CMS.Localization; using CMS.Membership; using CMS.OnlineForms; using CMS.SiteProvider; using CultureInfo = System.Globalization.CultureInfo; using TreeNode = CMS.DocumentEngine.TreeNode; /// <summary> /// Common methods. /// </summary> public static class Functions { #region "Methods" /// <summary> /// Returns connection string used throughout the application. /// </summary> public static string GetConnectionString() { return ConnectionHelper.GetSqlConnectionString(); } /// <summary> /// Creates and returns a new, initialized instance of TreeProvider with current user set. /// </summary> public static TreeProvider GetTreeProvider() { TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); return tree; } /// <summary> /// Returns User ID of the current user. /// </summary> public static int GetUserID() { return MembershipContext.AuthenticatedUser.UserID; } /// <summary> /// Returns true if the current user is authorized to access the given resource (module) with required permission. /// </summary> /// <param name="resourceName">Resource name</param> /// <param name="permissionName">Permission name</param> public static bool IsAuthorizedPerResource(string resourceName, string permissionName) { return MembershipContext.AuthenticatedUser.IsAuthorizedPerResource(resourceName, permissionName); } /// <summary> /// Returns true if the current user is authorized to access the given class (document type) with required permission. /// </summary> /// <param name="className">Class name in format application.class</param> /// <param name="permissionName">Name of the required permission</param> public static bool IsAuthorizedPerClass(string className, string permissionName) { return MembershipContext.AuthenticatedUser.IsAuthorizedPerClassName(className, permissionName); } /// <summary> /// Redirects user to the "Access Denied" page. /// </summary> /// <param name="resourceName">Name of the resource that cannot be accessed</param> /// <param name="permissionName">Name of the permission that is not allowed</param> public static void RedirectToAccessDenied(string resourceName, string permissionName) { if (HttpContext.Current != null) { URLHelper.Redirect(AdministrationUrlHelper.GetAccessDeniedUrl(resourceName, permissionName, null)); } } /// <summary> /// Returns preferred UI culture of the current user. /// </summary> public static CultureInfo GetPreferredUICulture() { return CultureHelper.PreferredUICultureInfo; } /// <summary> /// Returns current alias path based on base alias path setting and "aliaspath" querystring parameter. /// </summary> public static string GetAliasPath() { return DocumentContext.CurrentPageInfo.NodeAliasPath; } /// <summary> /// Returns preferred culture code (as string). You can modify this function so that it determines the preferred culture using some other algorithm. /// </summary> public static string GetPreferredCulture() { return LocalizationContext.PreferredCultureCode; } /// <summary> /// Returns type (such as "cms.article") of the current document. /// </summary> public static string GetDocumentType() { return DocumentContext.CurrentPageInfo.ClassName; } /// <summary> /// Returns type (such as "cms.article") of the specified document. /// </summary> /// <param name="aliasPath">Alias path of the document</param> public static string GetDocumentType(string aliasPath) { TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); TreeNode node = tree.SelectSingleNode(SiteContext.CurrentSiteName, aliasPath, LocalizationContext.PreferredCultureCode); if (node != null) { return node.NodeClassName; } else { return null; } } /// <summary> /// Returns node representing the current page. /// </summary> public static TreeNode GetCurrentPage() { return DocumentContext.CurrentDocument; } /// <summary> /// Returns node representing the current document. /// </summary> public static TreeNode GetCurrentDocument() { return DocumentContext.CurrentDocument; } /// <summary> /// Returns true if the current user is member of the given role. /// </summary> /// <param name="roleName">Role name</param> public static bool IsInRole(string roleName) { return MembershipContext.AuthenticatedUser.IsInRole(roleName, SiteContext.CurrentSiteName); } /// <summary> /// Writes event to the event log. /// </summary> /// <param name="eventType">Type of the event. I = information, E = error, W = warning</param> /// <param name="source">Source of the event (Content, Administration, etc.)</param> /// <param name="eventCode">Event code (Security, Update, Delete, etc.)</param> /// <param name="nodeId">ID value of the document</param> /// <param name="nodeNamePath">NamePath value of the document</param> /// <param name="eventDescription">Detailed description of the event</param> public static void LogEvent(string eventType, string source, string eventCode, int nodeId, string nodeNamePath, string eventDescription) { int siteId = 0; if (SiteContext.CurrentSite != null) { siteId = SiteContext.CurrentSite.SiteID; } EventLogProvider.LogEvent(eventType, source, eventCode, eventDescription, RequestContext.RawURL, MembershipContext.AuthenticatedUser.UserID, RequestContext.UserName, nodeId, nodeNamePath, RequestContext.UserHostAddress, siteId); } /// <summary> /// Returns first N levels of the given alias path, N+1 if CMSWebSiteBaseAliasPath is set. /// </summary> /// <param name="aliasPath">Alias path</param> /// <param name="level">Number of levels to be returned</param> public static string GetPathLevel(string aliasPath, int level) { return TreePathUtils.GetPathLevel(aliasPath, level); } /// <summary> /// Encodes URL(just redirection for use with aspx code. /// </summary> /// <param name="url">URL to encode</param> public static string UrlPathEncode(object url) { string path = ValidationHelper.GetString(url, ""); if (HttpContext.Current != null) { return HttpContext.Current.Server.UrlPathEncode(path); } return ""; } /// <summary> /// Returns the text of the specified region. /// </summary> /// <param name="aliasPath">Alias path of the region MenuItem</param> /// <param name="regionID">Region ID to get the text from</param> public static string GetEditableRegionText(string aliasPath, string regionID) { try { TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); TreeNode node = tree.SelectSingleNode(SiteContext.CurrentSiteName, aliasPath, LocalizationContext.PreferredCultureCode); if (node != null) { PageInfo pi = new PageInfo(); pi.LoadContentXml(Convert.ToString(node.GetValue("DocumentContent"))); return Convert.ToString(pi.EditableRegions[regionID.ToLowerCSafe()]); } } catch { } return null; } /// <summary> /// Returns the text of the specified region. /// </summary> /// <param name="aliasPath">Alias path of the region MenuItem</param> /// <param name="regionID">Region ID to get the text from</param> /// <param name="maxLength">Maximum text length</param> public static string GetEditableRegionText(string aliasPath, string regionID, int maxLength) { string text = GetEditableRegionText(aliasPath, regionID); if (!string.IsNullOrEmpty(text)) { if (text.Length > maxLength) { int lastSpace = text.LastIndexOfCSafe(" ", maxLength - 4); if (lastSpace < maxLength / 2) { lastSpace = maxLength - 1; } int lastStartTag = text.LastIndexOfCSafe("<", lastSpace); int lastEndTag = text.LastIndexOfCSafe(">", lastSpace); if (lastStartTag < lastSpace && lastEndTag < lastStartTag) { lastSpace = lastStartTag; } text = text.Substring(0, lastSpace).Trim() + " ..."; } } return text; } /// <summary> /// Resolves the dynamic control macros within the parent controls collection and loads the dynamic controls instead. /// </summary> /// <param name="parent">Parent control of the control tree to resolve</param> public static void ResolveDynamicControls(Control parent) { ControlsHelper.ResolveDynamicControls(parent); } /// <summary> /// Returns true if given path is excluded from URL rewriting. /// </summary> /// <param name="requestPath">Path to be checked</param> public static bool IsExcluded(string requestPath) { string customExcludedPaths = ""; // Get Custom excluded URLs path if (SiteContext.CurrentSite != null && SiteContext.CurrentSiteName != null && SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSExcludedURLs") != null) { customExcludedPaths = SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSExcludedURLs"); } return URLHelper.IsExcluded(requestPath, customExcludedPaths); } /// <summary> /// Returns the virtual path to the Admin root directory. /// </summary> public static string GetCMSDeskPath() { return "~/Admin"; } /// <summary> /// Returns URL of the document specified by alias path. /// </summary> /// <param name="aliasPath">Alias path of the document</param> public static string GetUrl(object aliasPath) { return DocumentURLProvider.GetUrl(Convert.ToString(aliasPath)); } /// <summary> /// Returns URL of the document specified by alias path or URL path. /// </summary> /// <param name="aliasPath">Alias path of the document</param> /// <param name="urlPath">URL path of the document</param> public static string GetUrl(object aliasPath, object urlPath) { return DocumentURLProvider.GetUrl(Convert.ToString(aliasPath), Convert.ToString(urlPath)); } /// <summary> /// Returns formatted username in format: username. /// Allows you to customize how the usernames will look like throughout the admin UI. /// </summary> /// <param name="username">Source user name</param> /// <param name="isLiveSite">Indicates if returned username should be displayed on live site</param> public static string GetFormattedUserName(string username, bool isLiveSite) { return GetFormattedUserName(username, null, null, isLiveSite); } /// <summary> /// Returns formatted username in format: fullname (username). /// Allows you to customize how the usernames will look like throughout the admin UI. /// </summary> /// <param name="username">Source user name</param> /// <param name="fullname">Source full name</param> /// <param name="isLiveSite">Indicates if returned username should be displayed on live site</param> public static string GetFormattedUserName(string username, string fullname = null, bool isLiveSite = false) { return GetFormattedUserName(username, fullname, null, isLiveSite); } /// <summary> /// Returns formatted username in format: fullname (nickname) if nickname specified otherwise fullname (username). /// Allows you to customize how the usernames will look like throughout various modules. /// </summary> /// <param name="username">Source user name</param> /// <param name="fullname">Source full name</param> /// <param name="nickname">Source nick name</param> /// <param name="isLiveSite">Indicates if returned username should be displayed on live site</param> public static string GetFormattedUserName(string username, string fullname, string nickname, bool isLiveSite = false) { return UserInfoProvider.GetFormattedUserName(username, fullname, nickname, isLiveSite); } /// <summary> /// Clear all hashtables. /// </summary> public static void ClearHashtables() { ModuleManager.ClearHashtables(); } #endregion #region "Macros" /// <summary> /// Builds and returns the list of object types that can contain macros. /// </summary> /// <param name="include">Object types to include in the list</param> /// <param name="exclude">Object types to exclude from the list</param> /// <remarks> /// Excludes the object types that cannot contain macros. /// </remarks> public static IEnumerable<string> GetObjectTypesWithMacros(IEnumerable<string> include = null, IEnumerable<string> exclude = null) { // Get the system object types var objectTypes = ObjectTypeManager.ObjectTypesWithMacros; // Include custom table object types objectTypes = objectTypes.Union(GetCustomTableObjectTypes()); // Include biz form object types objectTypes = objectTypes.Union(GetFormObjectTypes()); // Include object types if (include != null) { objectTypes = objectTypes.Union(include); } // Exclude object types if (exclude != null) { objectTypes = objectTypes.Except(exclude); } objectTypes = objectTypes.Where(t => { try { var typeInfo = ObjectTypeManager.GetTypeInfo(t); return (!typeInfo.IsListingObjectTypeInfo && typeInfo.ContainsMacros); } catch (Exception) { return false; } }); return objectTypes; } /// <summary> /// Gets all custom table object types /// </summary> public static IEnumerable<string> GetCustomTableObjectTypes() { return DataClassInfoProvider.GetClasses() .WhereTrue("ClassIsCustomTable") .Columns("ClassName") .Select(r => CustomTableItemProvider.GetObjectType(r["ClassName"].ToString())); } /// <summary> /// Gets all BizForms object types /// </summary> public static IEnumerable<string> GetFormObjectTypes() { return DataClassInfoProvider.GetClasses() .WhereTrue("ClassIsForm") .Columns("ClassName") .Select(r => BizFormItemProvider.GetObjectType(r["ClassName"].ToString())); } #endregion }
34.489224
237
0.624695
[ "MIT" ]
CMeeg/kentico-contrib
src/CMS/Old_App_Code/CMS/Functions.cs
16,005
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Reflection; using Xunit; namespace System.Reflection.Compatibility.UnitTests.TypeTests { public class GenericGetDefaultMembersTest { public static void TryGetDefaultMembers(string AssemblyQualifiedNameOfTypeToGet, string[] expectedDefaultMembers) { Type typeToCheck; //Run tests typeToCheck = Type.GetType(AssemblyQualifiedNameOfTypeToGet); Assert.NotNull(typeToCheck); MemberInfo[] defaultMembersReturned = typeToCheck.GetDefaultMembers(); Assert.Equal(defaultMembersReturned.Length, expectedDefaultMembers.Length); int foundIndex; Array.Sort(expectedDefaultMembers); for (int i = 0; i < defaultMembersReturned.Length; i++) { foundIndex = Array.BinarySearch(expectedDefaultMembers, defaultMembersReturned[i].ToString()); Assert.False(foundIndex < 0, "An unexpected member " + defaultMembersReturned[i].ToString() + " was returned"); } } public static string ArrayToCommaList(string[] ArrayToConvert) { string returnString = ""; if (ArrayToConvert.Length > 0) { returnString = ArrayToConvert[0]; for (int i = 1; i < ArrayToConvert.Length; i++) { returnString += ", " + ArrayToConvert[i]; } } return returnString; } public static string ArrayToCommaList(MemberInfo[] ArrayToConvert) { string returnString = ""; if (ArrayToConvert.Length > 0) { returnString = ArrayToConvert[0].ToString(); for (int i = 1; i < ArrayToConvert.Length; i++) { returnString += ", " + ArrayToConvert[i].ToString(); } } return returnString; } [Fact] public void Test1() { TryGetDefaultMembers("System.Reflection.Compatibility.UnitTests.TypeTests.GenericArrayWrapperClass`1[System.String]", new string[] { "System.String Item [Int32]" }); } [Fact] public void Test2() { TryGetDefaultMembers("System.Reflection.Compatibility.UnitTests.TypeTests.GenericArrayWrapperClass`1", new string[] { "T Item [Int32]" }); } [Fact] public void Test3() { //Test003 TryGetDefaultMembers("System.Reflection.Compatibility.UnitTests.TypeTests.GenericClass`1", new string[] { "T ReturnAndSetField(T)" }); } [Fact] public void Test4() { //Test004 TryGetDefaultMembers("System.Reflection.Compatibility.UnitTests.TypeTests.GenericClass`1[System.Int32]", new string[] { "Int32 ReturnAndSetField(Int32)" }); } } // build warnings about unused fields are not applicable to // reflection test cases #pragma warning disable 0169 #pragma warning disable 0067 #region Generics helper classes public class NonGenericClassString { public T method1<T, M>(T p) { return p; } public void method2(int p) { return; } } [DefaultMember("ReturnAndSetField")] public class GenericClass<T> { public T field; public GenericClass(T a) { field = a; } public T ReturnAndSetField(T newFieldValue) { field = newFieldValue; return field; } } public struct GenericStruct<T> { public T field; public T ReturnAndSetField(T newFieldValue) { field = newFieldValue; return field; } } public class GenericClass2TP<T, W> { public T field; public W field2; public T ReturnAndSetField1(T newFieldValue) { field = newFieldValue; return field; } public W ReturnAndSetField2(W newFieldValue) { field2 = newFieldValue; return field2; } } public struct GenericStruct2TP<T, W> { public T field; public W field2; public T ReturnAndSetField1(T newFieldValue) { field = newFieldValue; return field; } public W ReturnAndSetField2(W newFieldValue) { field2 = newFieldValue; return field2; } } public class GenericClassWithInterface<T> : IGenericInterface<T> { public T field; public GenericClassWithInterface(T a) { field = a; } public T ReturnAndSetFieldZero(T newFieldValue) { field = newFieldValue; return field; } public W GenericMethod<W>(W a) { return a; } } public class NonGenericClassWithGenericInterface : IGenericInterface<int> { public int field; public int ReturnAndSetFieldZero(int newFieldValue) { field = newFieldValue; return field; } } public struct GenericStructWithInterface<T> : IGenericInterface<T> { public T field; public int field2; public GenericStructWithInterface(T a) { field = a; field2 = 0; } public GenericStructWithInterface(T a, int b) { field = a; field2 = b; } public T ReturnAndSetFieldZero(T newFieldValue) { field = newFieldValue; return field; } } public interface NonGenericInterface { void SayHello(); } public interface IGenericInterface<T> { T ReturnAndSetFieldZero(T newFieldValue); } public interface IGenericInterface2<T, W> { void SetFieldOne(T newFieldValue); void SetFieldTwo(W newFieldValue); } public interface IGenericInterfaceInherits<U, V> : IGenericInterface<U>, IGenericInterface2<V, U> { V ReturnAndSetFieldThree(V newFieldValue); } public class GenericClassUsingNestedInterfaces<X, Y> : IGenericInterfaceInherits<X, Y> { public X FieldZero; public X FieldOne; public Y FieldTwo; public Y FieldThree; public GenericClassUsingNestedInterfaces(X a, X b, Y c, Y d) { FieldZero = a; FieldOne = b; FieldTwo = c; FieldThree = d; } public X ReturnAndSetFieldZero(X newFieldValue) { FieldZero = newFieldValue; return FieldZero; } public void SetFieldOne(Y newFieldValue) { FieldTwo = newFieldValue; } public void SetFieldTwo(X newFieldValue) { FieldOne = newFieldValue; } public Y ReturnAndSetFieldThree(Y newFieldValue) { FieldThree = newFieldValue; return FieldThree; } } public class GenericClassWithVarArgMethod<T> { public T field; public T publicField { get { return field; } set { field = value; } } public T ReturnAndSetField(T newFieldValue, params T[] moreFieldValues) { field = newFieldValue; for (int i = 0; i <= moreFieldValues.Length - 1; i++) { field = moreFieldValues[i]; } return field; } } public class ClassWithVarArgMethod { public int field; public int publicField { get { return field; } set { field = value; } } public int ReturnAndSetField(int newFieldValue, params int[] moreFieldValues) { field = newFieldValue; for (int i = 0; i <= moreFieldValues.Length - 1; i++) { field = moreFieldValues[i]; } return field; } } public class NonGenericClassWithVarArgGenericMethod { public T ReturnAndSetField<T>(T newFieldValue, params T[] moreFieldValues) { T field; field = newFieldValue; for (int i = 0; i <= moreFieldValues.Length - 1; i++) { field = moreFieldValues[i]; } return field; } } public interface IConsume { object[] StuffConsumed { get; } void Eat(object ThingEaten); object[] Puke(int Amount); } public class PackOfCarnivores<T> where T : IConsume { public T[] pPack; } public class Cat<C> : IConsume { private List<object> _pStuffConsumed = new List<object>(); public event EventHandler WeightChanged; private event EventHandler WeightStayedTheSame; private static EventHandler s_catDisappeared; public object[] StuffConsumed { get { return _pStuffConsumed.ToArray(); } } public void Eat(object ThingEaten) { _pStuffConsumed.Add(ThingEaten); } public object[] Puke(int Amount) { object[] vomit; if (_pStuffConsumed.Count < Amount) { Amount = _pStuffConsumed.Count; } vomit = _pStuffConsumed.GetRange(_pStuffConsumed.Count - Amount, Amount).ToArray(); _pStuffConsumed.RemoveRange(_pStuffConsumed.Count - Amount, Amount); return vomit; } } public class GenericArrayWrapperClass<T> { private T[] _field; private int _field1; public int myProperty { get { return 0; } set { _field1 = value; } } public GenericArrayWrapperClass(T[] fieldValues) { int size = fieldValues.Length; _field = new T[size]; for (int i = 0; i < _field.Length; i++) { _field[i] = fieldValues[i]; } } public T this[int index] { get { return _field[index]; } set { _field[index] = value; } } } public class GenericOuterClass<T> { public T field; public class GenericNestedClass<W> { public T field; public W field2; } public class NestedClass { public T field; public int field2; } } public class OuterClass { public int field; public class GenericNestedClass<W> { public int field; public W field2; } public class NestedClass { public string field; public int field2; } } #endregion #pragma warning restore 0067 #pragma warning restore 0169 }
23.971311
177
0.524363
[ "MIT" ]
bpschoch/corefx
src/System.Reflection.TypeExtensions/tests/Type/GetDefaultMembers.cs
11,698
C#
using Hearthstone_Deck_Tracker; using Hearthstone_Deck_Tracker.Utility.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using Core = Hearthstone_Deck_Tracker.API.Core; using Hearthstone_Deck_Tracker.Utility.Extensions; namespace HDT_Reconnector { public class Resize { public ResizeGrip resizeGrip; private bool resizeElement = false; private bool lmbDown = false; private Point mousePos; private UserControl panel; private FrameworkElement button; private OutlinedTextBlock buttonText; public ResizeSettings settings; public Resize(UserControl panel, FrameworkElement button, OutlinedTextBlock buttonText, ResizeSettings settings) { this.panel = panel; this.button = button; this.buttonText = buttonText; this.settings = settings; resizeGrip = new ResizeGrip(); resizeGrip.MouseDown += ResizeGrip_MouseDown; resizeGrip.MouseMove += ResizeGrip_MouseMove; resizeGrip.MouseUp += ResizeGrip_MouseUp; resizeGrip.Visibility = Visibility.Collapsed; OverlayExtensions.SetIsOverlayHitTestVisible(resizeGrip, true); } public void AddToOverlayWindowPrivate() { Dictionary<UIElement, ResizeGrip> _movableElements = (Dictionary<UIElement, ResizeGrip>)Utils.GetFieldValue(Core.OverlayWindow, "_movableElements"); _movableElements.Add(button, resizeGrip); Utils.SetFieldValue(Core.OverlayWindow, "_movableElements", _movableElements); List<FrameworkElement> _clickableElements = (List<FrameworkElement>)Utils.GetFieldValue(Core.OverlayWindow, "_clickableElements"); _clickableElements.Add(button); Utils.SetFieldValue(Core.OverlayWindow, "_clickableElements", _clickableElements); List<FrameworkElement> _hoverableElements = (List<FrameworkElement>)Utils.GetFieldValue(Core.OverlayWindow, "_hoverableElements"); _clickableElements.Add(button); Utils.SetFieldValue(Core.OverlayWindow, "_hoverableElements", _hoverableElements); } public void RemoveFromOverlayWindowPrivate() { Dictionary<UIElement, ResizeGrip> _movableElements = (Dictionary<UIElement, ResizeGrip>)Utils.GetFieldValue(Core.OverlayWindow, "_movableElements"); _movableElements.Remove(button); Utils.SetFieldValue(Core.OverlayWindow, "_movableElements", _movableElements); List<FrameworkElement> _clickableElements = (List<FrameworkElement>)Utils.GetFieldValue(Core.OverlayWindow, "_clickableElements"); _clickableElements.Remove(button); Utils.SetFieldValue(Core.OverlayWindow, "_clickableElements", _clickableElements); List<FrameworkElement> _hoverableElements = (List<FrameworkElement>)Utils.GetFieldValue(Core.OverlayWindow, "_hoverableElements"); _clickableElements.Remove(button); Utils.SetFieldValue(Core.OverlayWindow, "_hoverableElements", _hoverableElements); } private void ResizeGrip_MouseUp(object sender, MouseButtonEventArgs e) { lmbDown = false; resizeElement = false; resizeGrip.ReleaseMouseCapture(); } private void ResizeGrip_MouseDown(object sender, MouseButtonEventArgs e) { resizeGrip.CaptureMouse(); lmbDown = true; var pos = User32.GetMousePos(); mousePos = new Point(pos.X, pos.Y); var relativePos = panel.PointFromScreen(mousePos); if (Utils.PointInsideControl(relativePos, button.Width, button.Height, new Thickness(0))) { if (Math.Abs(relativePos.X - button.Width) < 30 && Math.Abs(relativePos.Y - button.Height) < 30) { resizeElement = true; } } } private void ResizeGrip_MouseMove(object sender, MouseEventArgs e) { if (!lmbDown) return; var pos = User32.GetMousePos(); var newPos = new Point(pos.X, pos.Y); var delta = new Point((newPos.X - mousePos.X), (newPos.Y - mousePos.Y)); mousePos = newPos; if (resizeElement) { // Maintain the button's shape, and fontsize >= 6 var ratio = Math.Max(6 / settings.FontSize, 1 + delta.Y / button.Height); settings.Height *= ratio; settings.Width *= ratio; settings.FontSize *= ratio; } else { var scaleY = Core.OverlayWindow.Height / Utils.Resolution.Y; var scaleX = Core.OverlayWindow.Width / Utils.Resolution.X; // Ensure the top and left are inside the game window settings.Top = Math.Max(0, Math.Min(Utils.Resolution.Y - settings.Height, settings.Top + delta.Y / scaleY)); settings.Left = Math.Max(0, Math.Min(Utils.Resolution.X - settings.Width, settings.Left + delta.X / scaleX)); } UpdatePosition(true); } public void UpdatePosition(bool updateResizeGrip = false) { var scaleY = Core.OverlayWindow.Height / Utils.Resolution.Y; var scaleX = Core.OverlayWindow.Width / Utils.Resolution.X; // To keep the button's shape and size, here just apply autoscaling (0.8~1.3) button.Width = settings.Width * Core.OverlayWindow.AutoScaling; button.Height = settings.Height * Core.OverlayWindow.AutoScaling; buttonText.FontSize = settings.FontSize * Core.OverlayWindow.AutoScaling; // Ensure the button is inside the game window var newTop = Math.Max(0, Math.Min(Core.OverlayWindow.Height - button.Height, settings.Top * scaleY)); var newLeft = Math.Max(0, Math.Min(Core.OverlayWindow.Width - button.Width, settings.Left * scaleX)); Canvas.SetTop(panel, newTop); Canvas.SetLeft(panel, newLeft); Canvas.SetTop(button, newTop); Canvas.SetLeft(button, newLeft); if (updateResizeGrip) { resizeGrip.Width = button.Width; resizeGrip.Height = button.Height; Canvas.SetTop(resizeGrip, newTop); Canvas.SetLeft(resizeGrip, newLeft); } } } }
40.585799
160
0.624581
[ "Apache-2.0" ]
haoruan/HDT-Reconnector
HDT-Reconnector/Resize.cs
6,861
C#
/* * _____ ______ * /_ / ____ ____ ____ _________ / __/ /_ * / / / __ \/ __ \/ __ \/ ___/ __ \/ /_/ __/ * / /__/ /_/ / / / / /_/ /\_ \/ /_/ / __/ /_ * /____/\____/_/ /_/\__ /____/\____/_/ \__/ * /____/ * * Authors: * 钟峰(Popeye Zhong) <zongsoft@gmail.com> * * Copyright (C) 2010-2020 Zongsoft Studio <http://www.zongsoft.com> * * This file is part of Zongsoft.Core library. * * The Zongsoft.Core is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3.0 of the License, * or (at your option) any later version. * * The Zongsoft.Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the Zongsoft.Core library. If not, see <http://www.gnu.org/licenses/>. */ using System; namespace Zongsoft.Messaging { public class MessageTopicSubscriptionOptions { #region 单例字段 public static readonly MessageTopicSubscriptionOptions Default = new MessageTopicSubscriptionOptions(MessageReliability.MostOnce); #endregion #region 构造函数 public MessageTopicSubscriptionOptions(MessageReliability reliability = MessageReliability.MostOnce, MessageFallbackBehavior fallbackBehavior = MessageFallbackBehavior.Backoff) { this.Reliability = reliability; this.FallbackBehavior = fallbackBehavior; } #endregion #region 公共属性 /// <summary>获取或设置订阅消息回调的可靠性。</summary> public MessageReliability Reliability { get; set; } /// <summary>获取或设置订阅回调失败的重试策略。</summary> public MessageFallbackBehavior FallbackBehavior { get; set; } #endregion } }
34.122807
178
0.698715
[ "MIT" ]
Zongsoft/Zongsoft.Framework
Zongsoft.Core/src/Messaging/MessageTopicSubscriptionOptions.cs
2,041
C#
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // package ssa -- go2cs converted at 2020 October 09 05:39:33 UTC // import "cmd/compile/internal/ssa" ==> using ssa = go.cmd.compile.@internal.ssa_package // Original source: C:\Go\src\cmd\compile\internal\ssa\sparseset.go using static go.builtin; namespace go { namespace cmd { namespace compile { namespace @internal { public static partial class ssa_package { // from https://research.swtch.com/sparse // in turn, from Briggs and Torczon private partial struct sparseSet { public slice<ID> dense; public slice<int> sparse; } // newSparseSet returns a sparseSet that can represent // integers between 0 and n-1 private static ptr<sparseSet> newSparseSet(long n) { return addr(new sparseSet(dense:nil,sparse:make([]int32,n))); } private static long cap(this ptr<sparseSet> _addr_s) { ref sparseSet s = ref _addr_s.val; return len(s.sparse); } private static long size(this ptr<sparseSet> _addr_s) { ref sparseSet s = ref _addr_s.val; return len(s.dense); } private static bool contains(this ptr<sparseSet> _addr_s, ID x) { ref sparseSet s = ref _addr_s.val; var i = s.sparse[x]; return i < int32(len(s.dense)) && s.dense[i] == x; } private static void add(this ptr<sparseSet> _addr_s, ID x) { ref sparseSet s = ref _addr_s.val; var i = s.sparse[x]; if (i < int32(len(s.dense)) && s.dense[i] == x) { return ; } s.dense = append(s.dense, x); s.sparse[x] = int32(len(s.dense)) - 1L; } private static void addAll(this ptr<sparseSet> _addr_s, slice<ID> a) { ref sparseSet s = ref _addr_s.val; foreach (var (_, x) in a) { s.add(x); } } private static void addAllValues(this ptr<sparseSet> _addr_s, slice<ptr<Value>> a) { ref sparseSet s = ref _addr_s.val; foreach (var (_, v) in a) { s.add(v.ID); } } private static void remove(this ptr<sparseSet> _addr_s, ID x) { ref sparseSet s = ref _addr_s.val; var i = s.sparse[x]; if (i < int32(len(s.dense)) && s.dense[i] == x) { var y = s.dense[len(s.dense) - 1L]; s.dense[i] = y; s.sparse[y] = i; s.dense = s.dense[..len(s.dense) - 1L]; } } // pop removes an arbitrary element from the set. // The set must be nonempty. private static ID pop(this ptr<sparseSet> _addr_s) { ref sparseSet s = ref _addr_s.val; var x = s.dense[len(s.dense) - 1L]; s.dense = s.dense[..len(s.dense) - 1L]; return x; } private static void clear(this ptr<sparseSet> _addr_s) { ref sparseSet s = ref _addr_s.val; s.dense = s.dense[..0L]; } private static slice<ID> contents(this ptr<sparseSet> _addr_s) { ref sparseSet s = ref _addr_s.val; return s.dense; } } }}}}
26.93985
90
0.518281
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/cmd/compile/internal/ssa/sparseset.cs
3,583
C#
using Abp.AspNetCore; using Abp.AspNetCore.TestBase; using Abp.Modules; using Abp.Reflection.Extensions; using markaz.EntityFrameworkCore; using markaz.Web.Startup; using Microsoft.AspNetCore.Mvc.ApplicationParts; namespace markaz.Web.Tests { [DependsOn( typeof(markazWebMvcModule), typeof(AbpAspNetCoreTestBaseModule) )] public class markazWebTestModule : AbpModule { public markazWebTestModule(markazEntityFrameworkModule abpProjectNameEntityFrameworkModule) { abpProjectNameEntityFrameworkModule.SkipDbContextRegistration = true; } public override void PreInitialize() { Configuration.UnitOfWork.IsTransactional = false; //EF Core InMemory DB does not support transactions. } public override void Initialize() { IocManager.RegisterAssemblyByConvention(typeof(markazWebTestModule).GetAssembly()); } public override void PostInitialize() { IocManager.Resolve<ApplicationPartManager>() .AddApplicationPartsIfNotAddedBefore(typeof(markazWebMvcModule).Assembly); } } }
31.157895
114
0.689189
[ "MIT" ]
MohammadMobasher/boilerplan
aspnet-core/test/markaz.Web.Tests/markazWebTestModule.cs
1,186
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="LocalFileImageService.cs" company="James South"> // Copyright (c) James South. // Licensed under the Apache License, Version 2.0. // </copyright> // <summary> // The local file image service for retrieving images from the file system. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ImageProcessor.Web.Services { using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using System.Web; using ImageProcessor.Web.Helpers; /// <summary> /// The local file image service for retrieving images from the file system. /// </summary> public class LocalFileImageService : IImageService { /// <summary> /// The prefix for the given implementation. /// </summary> private string prefix = string.Empty; /// <summary> /// Gets or sets the prefix for the given implementation. /// <remarks> /// This value is used as a prefix for any image requests that should use this service. /// </remarks> /// </summary> public string Prefix { get { return this.prefix; } set { this.prefix = value; } } /// <summary> /// Gets a value indicating whether the image service requests files from /// the locally based file system. /// </summary> public bool IsFileLocalService { get { return true; } } /// <summary> /// Gets or sets any additional settings required by the service. /// </summary> public Dictionary<string, string> Settings { get; set; } /// <summary> /// Gets or sets the white list of <see cref="System.Uri"/>. /// </summary> public Uri[] WhiteList { get; set; } /// <summary> /// Gets a value indicating whether the current request passes sanitizing rules. /// </summary> /// <param name="path"> /// The image path. /// </param> /// <returns> /// <c>True</c> if the request is valid; otherwise, <c>False</c>. /// </returns> public bool IsValidRequest(string path) { return ImageHelpers.IsValidImageExtension(path); } /// <summary> /// Gets the image using the given identifier. /// </summary> /// <param name="id"> /// The value identifying the image to fetch. /// </param> /// <returns> /// The <see cref="System.Byte"/> array containing the image data. /// </returns> public async Task<byte[]> GetImage(object id) { string path = id.ToString(); byte[] buffer; // Check to see if the file exists. // ReSharper disable once AssignNullToNotNullAttribute FileInfo fileInfo = new FileInfo(path); if (!fileInfo.Exists) { throw new HttpException(404, "No image exists at " + path); } using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) { buffer = new byte[file.Length]; await file.ReadAsync(buffer, 0, (int)file.Length); } return buffer; } } }
31.12605
120
0.49919
[ "Apache-2.0" ]
LaurentiuMM/ImageProcessor
src/ImageProcessor.Web/Services/LocalFileImageService.cs
3,706
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class LidarV2 : MonoBehaviour { public Camera DepthCamera; public LidarV2DepthCamera LidarV2DepthCameraObject; public float RotateFrequency = 20; public float SampleFrequency = 20000; public int Channels = 64; public float MaximalVerticalFOV = +0.2f; public float MinimalVerticalFOV = -24.9f; public float MeasurementRange = 120f; public float MeasurementAccuracy = 0.02f; public int SupersampleScale = 2; int CloudWidth; //public Queue<Texture2D> imageQueue = new Queue<Texture2D>(); public Texture2D lastImage; public Texture2D nextImage; public RawImage rawImage; public Texture2D scaledImage; int nextStartColumns = 0; int frameRenderCounter = 0; int frameActualRenderTimes = 0; float currCamTheta; int maxCamRenderWidth; int maxCamRenderHeight; public bool TryRenderPointCloud(out byte[] image) { if (lastImage == null) { image = null; return false; } image = lastImage.EncodeToJPG(); lastImage = null; return true; } void Start() { CloudWidth = Mathf.RoundToInt(SampleFrequency / RotateFrequency); lastImage = new Texture2D(CloudWidth, Channels, TextureFormat.RGB24, false); nextImage = new Texture2D(CloudWidth, Channels, TextureFormat.RGB24, false); currCamTheta = Mathf.Rad2Deg * Mathf.Atan((Mathf.Tan(Mathf.Deg2Rad * DepthCamera.fieldOfView / 2) / Mathf.Sqrt(2f))); maxCamRenderWidth = Mathf.FloorToInt((DepthCamera.fieldOfView / 360) * CloudWidth); maxCamRenderHeight = Mathf.RoundToInt(2 * currCamTheta * Channels / (MaximalVerticalFOV - MinimalVerticalFOV)); DepthCamera.targetTexture = new RenderTexture(SupersampleScale * maxCamRenderWidth, SupersampleScale * maxCamRenderHeight, 24); DepthCamera.targetTexture.Create(); DepthCamera.aspect = 1; LidarV2DepthCameraObject.Fov = DepthCamera.fieldOfView; LidarV2DepthCameraObject.SupersampleScale = SupersampleScale; } void Update() { int sampleCount = Mathf.FloorToInt(SampleFrequency * Time.deltaTime); // theta is the angle of the diag frameRenderCounter = 0; frameActualRenderTimes = 0; Render(ref nextImage, ref nextStartColumns, ref sampleCount); while (sampleCount > 0) { nextImage.Apply(); lastImage = nextImage; rawImage.texture = lastImage; nextImage = new Texture2D(CloudWidth, Channels, TextureFormat.RGB24, false); Render(ref nextImage, ref nextStartColumns, ref sampleCount); } Debug.LogFormat("DeltaTime:{0}, RenderTimes:{1}, ActualRenderTiems:{2}", Time.deltaTime, frameRenderCounter, frameActualRenderTimes); } // return successfully rendered fragment width void Render(ref Texture2D targetImage, ref int imgHorizontalPixelStart, ref int sampleCount) { frameRenderCounter++; while (maxCamRenderWidth < sampleCount && imgHorizontalPixelStart + maxCamRenderWidth < CloudWidth) { // render a whole camera ExecuteRender(ref targetImage, maxCamRenderWidth, ref imgHorizontalPixelStart, ref sampleCount); } int renderWidth = Mathf.Min(sampleCount, CloudWidth - imgHorizontalPixelStart); ExecuteRender(ref targetImage, renderWidth, ref imgHorizontalPixelStart, ref sampleCount); } void ExecuteRender(ref Texture2D targetImage,int renderWidth, ref int imgHorizontalPixelStart, ref int sampleCount) { // Rotate Camera to target angle and render DepthCamera.transform.localEulerAngles = Vector3.up * Mathf.LerpUnclamped(0, 360, (imgHorizontalPixelStart + 0.5f * renderWidth) / (float)(CloudWidth)); DepthCamera.Render(); // copy camera render texture to "readRenderTex" Texture2D readRenderTex = new Texture2D(maxCamRenderWidth, maxCamRenderHeight, TextureFormat.RGB24, false); RenderTexture.active = DepthCamera.targetTexture; readRenderTex.ReadPixels(new Rect(maxCamRenderWidth * (SupersampleScale *0.5f - 0.5f), maxCamRenderHeight * (SupersampleScale *0.5f - 0.5f), maxCamRenderWidth, maxCamRenderHeight), 0, 0); readRenderTex.Apply(); // copy texture from "readRenderTex" to related area in "targetImage" int srcX = (maxCamRenderWidth - renderWidth) / 2; int srcY = Mathf.RoundToInt(maxCamRenderHeight * (MinimalVerticalFOV + currCamTheta) / (currCamTheta + currCamTheta)); Graphics.CopyTexture(readRenderTex, 0, 0, srcX, srcY, renderWidth, Channels, targetImage, 0, 0, imgHorizontalPixelStart, 0); sampleCount -= renderWidth; imgHorizontalPixelStart += renderWidth; imgHorizontalPixelStart %= CloudWidth; frameActualRenderTimes++; } }
33.191176
189
0.767169
[ "MIT" ]
EvanWY/USelfDrivingSimulator
Assets/1_SelfDrivingCar/Scripts/LidarV2.cs
4,516
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraFollowController : MonoBehaviour { [SerializeField] private Transform CamTransform; public Transform target; public float followspeed; public void SetPlayerToFollow(Transform player) { target = player; } void LateUpdate () { if(target != null) { Vector3 targetPosition = new Vector3(target.position.x, target.position.y, this.transform.position.z); this.transform.position = Vector3.Lerp(this.transform.position, targetPosition, Time.deltaTime * followspeed); } } }
26.6
122
0.679699
[ "MIT" ]
assemyasser200/the_clothing_shop
Assets/_Game/Scripts/Utilities/CameraFollowController.cs
667
C#
/** * Couchbase Lite for .NET * * Original iOS version by Jens Alfke * Android Port by Marty Schoch, Traun Leyden * C# Port by Zack Gramana * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * Portions (c) 2013, 2014 Xamarin, 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.Collections.Generic; using Couchbase.Lite; using Couchbase.Lite.Internal; using Sharpen; namespace Couchbase.Lite { /// <summary>A Couchbase Lite Document Revision.</summary> /// <remarks> /// A Couchbase Lite Document Revision. /// Stores information about a revision -- its docID, revID, and whether it's deleted. /// It can also store the sequence number and document contents (they can be added after creation). /// </remarks> public abstract class Revision { /// <summary> /// re /// The sequence number of this revision. /// </summary> /// <remarks> /// re /// The sequence number of this revision. /// </remarks> protected internal long sequence; /// <summary>The document this is a revision of</summary> protected internal Document document; /// <summary>The ID of the parentRevision.</summary> /// <remarks>The ID of the parentRevision.</remarks> protected internal string parentRevID; /// <summary>The revision this one is a child of.</summary> /// <remarks>The revision this one is a child of.</remarks> protected internal SavedRevision parentRevision; /// <summary>Constructor</summary> /// <exclude></exclude> [InterfaceAudience.Private] internal Revision() : base() { } /// <summary>Constructor</summary> /// <exclude></exclude> [InterfaceAudience.Private] protected internal Revision(Document document) { this.document = document; } /// <summary>Get the revision's owning database.</summary> /// <remarks>Get the revision's owning database.</remarks> [InterfaceAudience.Public] public virtual Database GetDatabase() { return document.GetDatabase(); } /// <summary>Get the document this is a revision of.</summary> /// <remarks>Get the document this is a revision of.</remarks> [InterfaceAudience.Public] public virtual Document GetDocument() { return document; } /// <summary>Gets the Revision's id.</summary> /// <remarks>Gets the Revision's id.</remarks> [InterfaceAudience.Public] public abstract string GetId(); /// <summary> /// Does this revision mark the deletion of its document? /// (In other words, does it have a "_deleted" property?) /// </summary> [InterfaceAudience.Public] public virtual bool IsDeletion() { object deleted = GetProperty("_deleted"); if (deleted == null) { return false; } bool deletedBool = (bool)deleted; return deletedBool; } /// <summary>The contents of this revision of the document.</summary> /// <remarks> /// The contents of this revision of the document. /// Any keys in the dictionary that begin with "_", such as "_id" and "_rev", contain CouchbaseLite metadata. /// </remarks> /// <returns>contents of this revision of the document.</returns> [InterfaceAudience.Public] public abstract IDictionary<string, object> GetProperties(); /// <summary>The user-defined properties, without the ones reserved by CouchDB.</summary> /// <remarks> /// The user-defined properties, without the ones reserved by CouchDB. /// This is based on -properties, with every key whose name starts with "_" removed. /// </remarks> /// <returns>user-defined properties, without the ones reserved by CouchDB.</returns> [InterfaceAudience.Public] public virtual IDictionary<string, object> GetUserProperties() { IDictionary<string, object> result = new Dictionary<string, object>(); IDictionary<string, object> sourceMap = GetProperties(); foreach (string key in sourceMap.Keys) { if (!key.StartsWith("_")) { result.Put(key, sourceMap.Get(key)); } } return result; } /// <summary>The names of all attachments</summary> /// <returns></returns> [InterfaceAudience.Public] public virtual IList<string> GetAttachmentNames() { IDictionary<string, object> attachmentMetadata = GetAttachmentMetadata(); AList<string> result = new AList<string>(); if (attachmentMetadata != null) { Sharpen.Collections.AddAll(result, attachmentMetadata.Keys); } return result; } /// <summary>All attachments, as Attachment objects.</summary> /// <remarks>All attachments, as Attachment objects.</remarks> [InterfaceAudience.Public] public virtual IList<Attachment> GetAttachments() { IList<Attachment> result = new AList<Attachment>(); IList<string> attachmentNames = GetAttachmentNames(); foreach (string attachmentName in attachmentNames) { result.AddItem(GetAttachment(attachmentName)); } return result; } /// <summary>Shorthand for getProperties().get(key)</summary> [InterfaceAudience.Public] public virtual object GetProperty(string key) { return GetProperties().Get(key); } /// <summary>Looks up the attachment with the given name (without fetching its contents yet). /// </summary> /// <remarks>Looks up the attachment with the given name (without fetching its contents yet). /// </remarks> [InterfaceAudience.Public] public virtual Attachment GetAttachment(string name) { IDictionary<string, object> attachmentsMetadata = GetAttachmentMetadata(); if (attachmentsMetadata == null) { return null; } IDictionary<string, object> attachmentMetadata = (IDictionary<string, object>)attachmentsMetadata .Get(name); return new Attachment(this, name, attachmentMetadata); } /// <summary>Gets the parent Revision.</summary> /// <remarks>Gets the parent Revision.</remarks> [InterfaceAudience.Public] public abstract SavedRevision GetParent(); /// <summary>Gets the parent Revision's id.</summary> /// <remarks>Gets the parent Revision's id.</remarks> [InterfaceAudience.Public] public abstract string GetParentId(); /// <summary>Returns the history of this document as an array of CBLRevisions, in forward order. /// </summary> /// <remarks> /// Returns the history of this document as an array of CBLRevisions, in forward order. /// Older revisions are NOT guaranteed to have their properties available. /// </remarks> /// <exception cref="CouchbaseLiteException">CouchbaseLiteException</exception> /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> [InterfaceAudience.Public] public abstract IList<SavedRevision> GetRevisionHistory(); /// <summary>Compare this revision to the given revision to check for equality.</summary> /// <remarks> /// Compare this revision to the given revision to check for equality. /// The comparison makes sure that both revisions have the same revision ID. /// </remarks> /// <param name="the">revision to check for equality against</param> /// <returns>true if equal, false otherwise</returns> [InterfaceAudience.Public] public override bool Equals(object o) { bool result = false; if (o is SavedRevision) { SavedRevision other = (SavedRevision)o; if (document.GetId().Equals(other.GetDocument().GetId()) && GetId().Equals(other. GetId())) { result = true; } } return result; } /// <summary>Custom hashCode based on the hash code of the Document Id and the Revision Id /// </summary> [InterfaceAudience.Public] public override int GetHashCode() { return document.GetId().GetHashCode() ^ GetId().GetHashCode(); } /// <summary> /// Returns a string representation of this Revision, including the Document Id, the Revision Id /// and whether or not this Revision is a deletion. /// </summary> /// <remarks> /// Returns a string representation of this Revision, including the Document Id, the Revision Id /// and whether or not this Revision is a deletion. /// </remarks> [InterfaceAudience.Public] public override string ToString() { return "{" + this.document.GetId() + " #" + this.GetId() + (IsDeletion() ? "DEL" : string.Empty) + "}"; } /// <exclude></exclude> [InterfaceAudience.Private] internal virtual IDictionary<string, object> GetAttachmentMetadata() { return (IDictionary<string, object>)GetProperty("_attachments"); } /// <exclude></exclude> [InterfaceAudience.Private] internal virtual void SetSequence(long sequence) { this.sequence = sequence; } /// <exclude></exclude> [InterfaceAudience.Private] internal virtual long GetSequence() { return sequence; } /// <summary>Generation number: 1 for a new document, 2 for the 2nd revision, ...</summary> /// <remarks> /// Generation number: 1 for a new document, 2 for the 2nd revision, ... /// Extracted from the numeric prefix of the revID. /// </remarks> /// <exclude></exclude> [InterfaceAudience.Private] internal virtual int GetGeneration() { return GenerationFromRevID(GetId()); } /// <exclude></exclude> [InterfaceAudience.Private] internal static int GenerationFromRevID(string revID) { int generation = 0; int dashPos = revID.IndexOf("-"); if (dashPos > 0) { generation = System.Convert.ToInt32(Sharpen.Runtime.Substring(revID, 0, dashPos)); } return generation; } } }
32.189542
111
0.698579
[ "MIT" ]
SotoiGhost/couchbase-lite-net
Couchbase.Lite/Sharpened/Revision.cs
9,850
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using ProkonDCI.Domain.Data; using ProkonDCI.SystemOperation; using System.Windows.Threading; namespace ProkonDCI.Presentation.View { /// <summary> /// Interaction logic for ActivityInfoDialog.xaml /// </summary> public partial class DependantInfoDialog : Window, DependancyAdding.DependantInfoFormRole { public DependantInfoDialog() { InitializeComponent(); } private bool Canceled { get; set; } private void BtnCancel_Click(object sender, System.Windows.RoutedEventArgs e) { Canceled = true; Close(); } private void BtnOk_Click(object sender, System.Windows.RoutedEventArgs e) { Canceled = false; Close(); } public bool AskDependantName(out string dependantName) { dependantName = ""; this.ShowDialog(); if (!Canceled) { dependantName = NameInput.Text; return true; } return false; } } }
24.672131
85
0.616611
[ "MIT" ]
wangvnn/DCIProkon
src/ProkonDCI/Presentation/View/DependantInfoDialog.xaml.cs
1,507
C#
namespace Level2_1 { using System; using System.Collections.Generic; internal static class Program { private static readonly Dictionary<int, string> GameCache = new(); private static readonly Dictionary<int, string> Options = new(3) { {1, "rock"}, {2, "paper"}, {3, "scissors"} }; private static readonly Random Random = new(); private static int _gameId; private static void Main() { Console.WriteLine("Rock,Paper,Scissors game. Vokokhovych"); Calculate(); } private static void Help() { Console.WriteLine("A player who decides to play rock will beat another player who has chosen scissors\n" + "(\"rock crushes scissors\" or sometimes \"blunts scissors\"),but will lose to one who has\n" + "played paper (\"paper covers rock\"); a play of paper will lose\n" + "lose to a play of scissors (\"scissors cuts paper\")."); } private static void Commands() { Console.WriteLine("Available commands:\n Exit - close programme;\n Help - prints game rules\n" + "Game commands:\n rock - for rock\n paper - for paper\n scissors - for scissors."); } private static void Calculate() { var option = ""; Commands(); while (option !="exit") { option = Console.In.ReadLine(); if (option == null) { Console.WriteLine("\n**Error, try again**\n"); Commands(); Calculate(); } else { option = option.ToLower(); } string computerOption; var output = ""; switch (option) { case "exit": foreach(var (key, value) in GameCache) Console.WriteLine($"Game {key} {value}"); Environment.Exit(0); break; case "help": Help(); break; case "rock": computerOption = Options[Random.Next(1, 4)]; _gameId++; output = computerOption switch { "rock" => $"User:{option} = {computerOption} : Computer. DRAW", "paper" => $"User:{option} < {computerOption} : Computer. Computer Wins", _ => $"User:{option} > {computerOption} : Computer. User Wins" }; GameCache.Add(_gameId,output); break; case "paper": computerOption = Options[Random.Next(1, 4)]; _gameId++; output = computerOption switch { "paper" => $"User:{option} = {computerOption} : Computer. DRAW", "rock" => $"User:{option} > {computerOption} : Computer. User Wins", _ => $"User:{option} < {computerOption} : Computer. Computer Wins" }; GameCache.Add(_gameId,output); break; case "scissors": computerOption = Options[Random.Next(1, 4)]; _gameId++; output = computerOption switch { "scissors" => $"User:{option} = {computerOption} : Computer. DRAW", "paper" => $"User:{option} > {computerOption} : Computer. User Wins", _ => $"User:{option} < {computerOption} : Computer. Computer Wins" }; GameCache.Add(_gameId,output); break; default: Console.WriteLine("Error! Try again"); Calculate(); break; } Console.WriteLine(output); } } } }
40.061404
125
0.404642
[ "MIT" ]
antomys/Parimatch_Academy_Homeworks
Homework_1/Level2_1/Program.cs
4,569
C#
using System; using System.Collections.Generic; namespace Never.Serialization.Json.MethodProviders { /// <summary> /// uint 值转换 /// </summary> public class UInt32MethodProvider : ConvertMethodProvider<uint>, IConvertMethodProvider<uint> { #region ctor /// <summary> /// Gets the singleton. /// </summary> /// <value>The singleton.</value> public static UInt32MethodProvider Default { get; } = new UInt32MethodProvider(); #endregion ctor #region IMethodProvider /// <summary> /// 在流中读取字节后转换为对象 /// </summary> /// <param name="setting">配置项</param> /// <param name="reader">字符读取器</param> /// <param name="node">节点流内容</param> /// <param name="checkNullValue">是否检查空值</param> /// <returns></returns> public override uint Parse(IDeserializerReader reader, JsonDeserializeSetting setting, IContentNode node, bool checkNullValue) { if (node == null) return 0; var value = node.GetValue(); if (value.IsNullOrEmpty) return 0; try { if (checkNullValue && this.IsNullValue(value)) return 0; return ParseUInt32(value); } catch (ArgumentOutOfRangeException) { throw new ArgumentNullException(string.Format("读取发现错误,在{0}至{1}字符处,取值只能在[0-9]范围内", node.Segment.Offset.ToString(), (node.Segment.Offset + node.Segment.Count).ToString())); } catch (ArgumentException) { throw new ArgumentOutOfRangeException(node.Key, string.Format("数值溢出,在字符{0}至{1}处", node.Segment.Offset.ToString(), (node.Segment.Offset + node.Segment.Count).ToString())); } } /// <summary> /// 从对象中写入流中 /// </summary> /// <param name="writer">写入流</param> /// <param name="setting">配置项</param> /// <param name="source">源数据</param> public override void Write(ISerializerWriter writer, JsonSerializeSetting setting, uint source) { if (source == uint.MinValue) { writer.Write("0"); return; } if (source == uint.MaxValue) { writer.Write("4294967295"); return; } char[] buffer = null; /*ushort的最大长度为10*/ var maxlength = "4294967295".Length; buffer = new char[maxlength + 1]; ulong lessen = 0; KeyValuePair<char, char> item; do { lessen = source % 100; item = ZeroToHundred[lessen]; buffer[maxlength] = item.Value; buffer[maxlength - 1] = item.Key; maxlength -= 2; source = source / 100; } while (source != 0); if (item.Key == '0') { writer.Write(buffer, maxlength + 2); return; } writer.Write(buffer, maxlength + 1); return; } #endregion IMethodProvider } }
31.038095
186
0.507518
[ "MIT" ]
daniel1519/never
src/Never/Serialization/Json/MethodProviders/UInt32MethodProvider.cs
3,439
C#
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Security.AccessControl; using Umbraco.Core.IO; using Umbraco.Web.Composing; using Umbraco.Web.PublishedCache; namespace Umbraco.Web.Install { internal class FilePermissionHelper { // ensure that these directories exist and Umbraco can write to them private static readonly string[] PermissionDirs = { SystemDirectories.Css, SystemDirectories.Config, SystemDirectories.Data, SystemDirectories.Media, SystemDirectories.Masterpages, SystemDirectories.UserControls, SystemDirectories.Preview }; private static readonly string[] PackagesPermissionsDirs = { SystemDirectories.Bin, SystemDirectories.Umbraco, SystemDirectories.UserControls, SystemDirectories.Packages }; // ensure Umbraco can write to these files (the directories must exist) private static readonly string[] PermissionFiles = { }; public static bool RunFilePermissionTestSuite(out Dictionary<string, IEnumerable<string>> report) { report = new Dictionary<string, IEnumerable<string>>(); IEnumerable<string> errors; if (EnsureDirectories(PermissionDirs, out errors) == false) report["Folder creation failed"] = errors.ToList(); if (EnsureDirectories(PackagesPermissionsDirs, out errors) == false) report["File writing for packages failed"] = errors.ToList(); if (EnsureFiles(PermissionFiles, out errors) == false) report["File writing failed"] = errors.ToList(); if (TestPublishedSnapshotService(out errors) == false) report["Published snapshot environment check failed"] = errors.ToList(); if (EnsureCanCreateSubDirectory(SystemDirectories.Media, out errors) == false) report["Media folder creation failed"] = errors.ToList(); return report.Count == 0; } /// <summary> /// This will test the directories for write access /// </summary> /// <param name="directories"></param> /// <param name="errorReport"></param> /// <param name="writeCausesRestart"> /// If this is false, the easiest way to test for write access is to write a temp file, however some folder will cause /// an App Domain restart if a file is written to the folder, so in that case we need to use the ACL APIs which aren't as /// reliable but we cannot write a file since it will cause an app domain restart. /// </param> /// <returns></returns> public static bool EnsureDirectories(string[] dirs, out IEnumerable<string> errors, bool writeCausesRestart = false) { List<string> temp = null; var success = true; foreach (var dir in dirs) { // we don't want to create/ship unnecessary directories, so // here we just ensure we can access the directory, not create it var tryAccess = TryAccessDirectory(dir, !writeCausesRestart); if (tryAccess) continue; if (temp == null) temp = new List<string>(); temp.Add(dir); success = false; } errors = success ? Enumerable.Empty<string>() : temp; return success; } public static bool EnsureFiles(string[] files, out IEnumerable<string> errors) { List<string> temp = null; var success = true; foreach (var file in files) { var canWrite = TryWriteFile(file); if (canWrite) continue; if (temp == null) temp = new List<string>(); temp.Add(file); success = false; } errors = success ? Enumerable.Empty<string>() : temp; return success; } public static bool EnsureCanCreateSubDirectory(string dir, out IEnumerable<string> errors) { return EnsureCanCreateSubDirectories(new[] { dir }, out errors); } public static bool EnsureCanCreateSubDirectories(IEnumerable<string> dirs, out IEnumerable<string> errors) { List<string> temp = null; var success = true; foreach (var dir in dirs) { var canCreate = TryCreateSubDirectory(dir); if (canCreate) continue; if (temp == null) temp = new List<string>(); temp.Add(dir); success = false; } errors = success ? Enumerable.Empty<string>() : temp; return success; } public static bool TestPublishedSnapshotService(out IEnumerable<string> errors) { var publishedSnapshotService = Current.PublishedSnapshotService; return publishedSnapshotService.EnsureEnvironment(out errors); } // tries to create a sub-directory // if successful, the sub-directory is deleted // creates the directory if needed - does not delete it private static bool TryCreateSubDirectory(string dir) { try { var path = IOHelper.MapPath(dir + "/" + CreateRandomName()); Directory.CreateDirectory(path); Directory.Delete(path); return true; } catch { return false; } } // tries to create a file // if successful, the file is deleted // creates the directory if needed - does not delete it public static bool TryCreateDirectory(string dir) { try { var dirPath = IOHelper.MapPath(dir); if (Directory.Exists(dirPath) == false) Directory.CreateDirectory(dirPath); var filePath = dirPath + "/" + CreateRandomName() + ".tmp"; File.WriteAllText(filePath, "This is an Umbraco internal test file. It is safe to delete it."); File.Delete(filePath); return true; } catch { return false; } } // tries to create a file // if successful, the file is deleted // // or // // use the ACL APIs to avoid creating files // // if the directory does not exist, do nothing & success public static bool TryAccessDirectory(string dir, bool canWrite) { try { var dirPath = IOHelper.MapPath(dir); if (Directory.Exists(dirPath) == false) return true; if (canWrite) { var filePath = dirPath + "/" + CreateRandomName() + ".tmp"; File.WriteAllText(filePath, "This is an Umbraco internal test file. It is safe to delete it."); File.Delete(filePath); return true; } else { return HasWritePermission(dirPath); } } catch { return false; } } private static bool HasWritePermission(string path) { var writeAllow = false; var writeDeny = false; var accessControlList = Directory.GetAccessControl(path); if (accessControlList == null) return false; AuthorizationRuleCollection accessRules; try { accessRules = accessControlList.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); if (accessRules == null) return false; } catch (Exception) { //This is not 100% accurate btw because it could turn out that the current user doesn't //have access to read the current permissions but does have write access. //I think this is an edge case however return false; } foreach (FileSystemAccessRule rule in accessRules) { if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write) continue; if (rule.AccessControlType == AccessControlType.Allow) writeAllow = true; else if (rule.AccessControlType == AccessControlType.Deny) writeDeny = true; } return writeAllow && writeDeny == false; } // tries to write into a file // fails if the directory does not exist private static bool TryWriteFile(string file) { try { var path = IOHelper.MapPath(file); File.AppendText(path).Close(); return true; } catch { return false; } } private static string CreateRandomName() { return "umbraco-test." + Guid.NewGuid().ToString("N").Substring(0, 8); } } }
36.529183
249
0.551449
[ "MIT" ]
bharanijayasuri/umbraco8
src/Umbraco.Web/Install/FilePermissionHelper.cs
9,390
C#
using NUnit.Framework; using Shouldly; namespace dannyboy.tests.TruncateTests { public class WithGenericType : TruncateTestsBase { [Test] public void AllDataIsTruncated() { DataAccess.Truncate<Person>(); DataAccess.ExecuteScalar<int>("SELECT COUNT(*) FROM Persons") .ShouldBe(0); } } }
21.882353
73
0.599462
[ "Apache-2.0" ]
swxben/danny-boy
src/dannyboy.tests/TruncateTests/WithGenericType.cs
374
C#
// -------------------------------------------------------------------------------------------- // Copyright (c) 2019 The CefNet Authors. All rights reserved. // Licensed under the MIT license. // See the licence file in the project root for full license information. // -------------------------------------------------------------------------------------------- // Generated by CefGen // Source: include/internal/cef_types.h // -------------------------------------------------------------------------------------------- // DO NOT MODIFY! THIS IS AUTOGENERATED FILE! // -------------------------------------------------------------------------------------------- #pragma warning disable 0169, 1591, 1573 using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using CefNet.WinApi; namespace CefNet.CApi { /// <summary> /// Structure representing mouse event information. /// </summary> [StructLayout(LayoutKind.Sequential)] public unsafe partial struct cef_mouse_event_t { /// <summary> /// X coordinate relative to the left side of the view. /// </summary> public int x; /// <summary> /// Y coordinate relative to the top side of the view. /// </summary> public int y; /// <summary> /// Bit flags describing any pressed modifier keys. See /// cef_event_flags_t for values. /// </summary> public uint modifiers; } }
30.977778
96
0.516499
[ "MIT" ]
AigioL/CefNet
CefNet/Generated/Native/Types/cef_mouse_event_t.cs
1,398
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace SomeTools { public class DelegateCommand : ICommand { //A method prototype without return value. public Action<object> ExecuteCommand = null; //A method prototype return a bool type. public Func<object, bool> CanExecuteCommand = null; public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { if (CanExecuteCommand != null) { return this.CanExecuteCommand(parameter); } else { return true; } } public void Execute(object parameter) { if (this.ExecuteCommand != null) this.ExecuteCommand(parameter); } public void RaiseCanExecuteChanged() { if (CanExecuteChanged != null) { CanExecuteChanged(this, EventArgs.Empty); } } } }
24.555556
76
0.572851
[ "MIT" ]
Qian-Jin/SomeToolsForWork
SomeToolsForWork/DelegateCommand.cs
1,107
C#
#region Header // IPyramidDevice.cs // PTIRelianceLib // Cory Todd // 16-05-2018 // 7:07 AM #endregion namespace PTIRelianceLib { using System; using System.IO; using System.Runtime.Serialization; using System.Text; internal static class Extensions { /// <summary> /// Converts a big endian byte array of bytes to an unsiged word (short) /// </summary> /// <param name="b">byte array</param> /// <returns>short big endian</returns> public static ushort ToUshortBE(this byte[] b) { return (ushort) ((b[1] << 8) | b[0]); } /// <summary> /// Converts a byte[] to a big endian unsigned integer /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static uint ToUintBE(this byte[] bytes) { switch (bytes.Length) { case 4: return (uint) (bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]); case 3: return (uint) (bytes[2] << 16 | bytes[1] << 8 | bytes[0]); case 2: return (uint) (bytes[1] << 8 | bytes[0]); case 1: return bytes[0]; default: throw new ArgumentException( $"Bytes must be between 1 and 4 bytes in length, received: {bytes.Length}"); } } /// <summary> /// Converts an unsigned int to a big Endian 2-byte array /// </summary> /// <param name="u"></param> /// <returns></returns> public static byte[] ToBytesBE(this ushort u) { return new[] { (byte)(u & 0xFF), (byte)((u >> 8) & 0xFF) }; } /// <summary> /// Converts a signed int to a big Endian 4-byte array /// </summary> /// <param name="u"></param> /// <returns></returns> public static byte[] ToBytesBE(this int u) { return new[] { (byte)(u & 0xFF), (byte)((u >> 8) & 0xFF), (byte)((u >> 16) & 0xFF), (byte)((u >> 24) & 0xFF) }; } /// <summary> /// Converts an unsigned int to a big Endian 4-byte array /// </summary> /// <param name="u"></param> /// <returns></returns> public static byte[] ToBytesBE(this uint u) { return new[] { (byte)(u & 0xFF), (byte)((u >> 8) & 0xFF), (byte)((u >> 16) & 0xFF), (byte)((u >> 24) & 0xFF) }; } /// <summary> /// Converts a signed long to a big Endian 8-byte array /// </summary> /// <param name="u"></param> /// <returns></returns> public static byte[] ToBytesBE(this long u) { return new[] { (byte)(u & 0xFF), (byte)((u >> 8) & 0xFF), (byte)((u >> 16) & 0xFF), (byte)((u >> 24) & 0xFF), (byte)((u >> 32) & 0xFF), (byte)((u >> 40) & 0xFF), (byte)((u >> 48) & 0xFF), (byte)((u >> 56) & 0xFF) }; } /// <summary> /// Converts an unsigned long to a big Endian 8-byte array /// </summary> /// <param name="u"></param> /// <returns></returns> public static byte[] ToBytesBE(this ulong u) { return new[] { (byte)(u & 0xFF), (byte)((u >> 8) & 0xFF), (byte)((u >> 16) & 0xFF), (byte)((u >> 24) & 0xFF), (byte)((u >> 32) & 0xFF), (byte)((u >> 40) & 0xFF), (byte)((u >> 48) & 0xFF), (byte)((u >> 56) & 0xFF) }; } /// <summary> /// Returns a copy of this string containing only printable /// ASCII characters (32-126) /// </summary> /// <param name="s">String</param> /// <returns>Copy of string</returns> public static string StripNonPrintableChars(this string s) { if (string.IsNullOrEmpty(s)) { return string.Empty; } var builder = new StringBuilder(); foreach (var c in s) { if (c >= 32 && c < 127) { builder.Append(c); } } return builder.ToString(); } /// <summary> /// Returns a string from the default text encoding /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static string GetPrintableString(this byte[] bytes) { return Encoding.GetEncoding(0).GetString(bytes).StripNonPrintableChars(); } /// <summary> /// Returns the data formatted as specified by the format string. /// </summary> /// <param name="data">byte[]</param> /// <param name="delimiter">delimiter such as command or tab</param> /// <param name="hexPrefix">Set true to prefix each byte with 0x</param> /// <returns></returns> public static string ByteArrayToHexString(this byte[] data, string delimiter = ", ", bool hexPrefix = false) { var hex = new StringBuilder(data.Length * 2); var prefix = string.Empty; if (hexPrefix) { prefix = "0x"; } foreach (var b in data) { hex.AppendFormat("{0}{1:X2}{2}", prefix, b, delimiter); } var result = hex.ToString().Trim().TrimEnd(delimiter.ToCharArray()); return result; } /// <summary> /// Split the given array into x number of smaller arrays, each of length len /// </summary> /// <typeparam name="T"></typeparam> /// <param name="arrayIn"></param> /// <param name="len"></param> /// <returns></returns> public static T[][] Split<T>(this T[] arrayIn, int len) { var even = arrayIn.Length % len == 0; var totalLength = arrayIn.Length / len; if (!even) { totalLength++; } var newArray = new T[totalLength][]; for (var i = 0; i < totalLength; ++i) { var allocLength = len; if (!even && i == totalLength - 1) { allocLength = arrayIn.Length % len; } newArray[i] = new T[allocLength]; Array.Copy(arrayIn, i * len, newArray[i], 0, allocLength); } return newArray; } /// <summary> /// Concatenates all arrays into one /// </summary> /// <param name="args">1 or more byte arrays</param> /// <returns>byte[]</returns> public static byte[] Concat(params byte[][] args) { using (var buffer = new MemoryStream()) { foreach (var ba in args) { buffer.Write(ba, 0, ba.Length); } var bytes = new byte[buffer.Length]; buffer.Position = 0; buffer.Read(bytes, 0, bytes.Length); return bytes; } } /// <summary> /// Gets the EnumMemberAttribute on an enum field value. If the attribute /// is not set, the ToString() result will be returned instead. /// </summary> /// <param name="enumVal">The enum value</param> /// <returns>The string form of this enumVal</returns> public static string GetEnumName(this Enum enumVal) { if (enumVal == null) { return string.Empty; } var type = enumVal.GetType(); var memInfo = type.GetMember(enumVal.ToString()); if (memInfo.Length == 0) { return string.Empty; } var attributes = memInfo[0].GetCustomAttributes(typeof(EnumMemberAttribute), false); return attributes.Length > 0 && attributes[0] != null ? ((EnumMemberAttribute)attributes[0]).Value : enumVal.ToString(); } /// <summary> /// Rounds this integer to the nearest positive multiple of N /// </summary> /// <param name="i">Value to round</param> /// <param name="N">Multiple to round to</param> /// <returns></returns> public static int RoundUp(this int i, int N) { return (int)RoundUp(i, (uint)N); } /// <summary> /// Rounds this integer to the nearest positive multiple of N /// </summary> /// <param name="i">Value to round</param> /// <param name="N">Multiple to round to</param> /// <returns></returns> public static long RoundUp(this long i, int N) { return RoundUp(i, (uint)N); } /// <summary> /// Rounds this integer to the nearest positive multiple of N /// </summary> /// <param name="i">Value to round</param> /// <param name="N">Multiple to round to</param> /// <returns></returns> public static uint RoundUp(this uint i, int N) { return (uint)RoundUp(i, (uint)N); } /// <summary> /// Rounds this integer to the nearest positive multiple of N /// </summary> /// <param name="i">Value to round</param> /// <param name="N">Multiple to round to</param> /// <returns></returns> private static long RoundUp(long i, uint N) { if (N == 0) { return 0; } if (i == 0) { return N; } return (long)(Math.Ceiling(Math.Abs(i) / (double)N) * N); } } }
32.093548
123
0.467585
[ "Apache-2.0", "MIT" ]
PyramidTechnologies/PTI.Reliance.Tools
PTIRelianceLib/Internal/Extensions.cs
9,951
C#
// <auto-generated /> using System; using CherieAppBankSound.Services; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; #nullable disable namespace CherieAppBankSound.Migrations { [DbContext(typeof(MySoundContext))] partial class MySoundContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "6.0.3") .HasAnnotation("Relational:MaxIdentifierLength", 128); SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); modelBuilder.Entity("CherieAppBankSound.Models.MySound", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<byte[]>("MyAudio") .IsRequired() .HasColumnType("varbinary(max)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("MySounds"); }); #pragma warning restore 612, 618 } } }
31.404255
84
0.588076
[ "MIT" ]
Mafyou/cherieapp
CherieAppBankSound/Migrations/MySoundContextModelSnapshot.cs
1,478
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; using WRLDCWarehouse.Data; namespace WRLDCWareHouseWebApp.Migrations { [DbContext(typeof(WRLDCWarehouseDbContext))] [Migration("20190723181848_gen_station_name_unique_modify")] partial class gen_station_name_unique_modify { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn) .HasAnnotation("ProductVersion", "2.2.4-servicing-10062") .HasAnnotation("Relational:MaxIdentifierLength", 63); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.AcTransLineCkt", b => { b.Property<int>("AcTransLineCktId") .ValueGeneratedOnAdd(); b.Property<int>("AcTransmissionLineId"); b.Property<DateTime>("CODDate"); b.Property<string>("CktNumber"); b.Property<DateTime>("CommDate"); b.Property<int?>("ConductorTypeId"); b.Property<DateTime>("DeCommDate"); b.Property<DateTime>("FtcDate"); b.Property<decimal>("Length"); b.Property<string>("Name") .IsRequired(); b.Property<decimal>("SIL"); b.Property<decimal>("ThermalLimitMVA"); b.Property<DateTime>("TrialOperationDate"); b.Property<int>("WebUatId"); b.HasKey("AcTransLineCktId"); b.HasIndex("AcTransmissionLineId"); b.HasIndex("ConductorTypeId"); b.HasIndex("Name") .IsUnique(); b.HasIndex("WebUatId") .IsUnique(); b.HasIndex("AcTransLineCktId", "CktNumber") .IsUnique(); b.ToTable("AcTransLineCkts"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.AcTransLineCktOwner", b => { b.Property<int>("AcTransLineCktId"); b.Property<int>("OwnerId"); b.Property<int>("WebUatId"); b.HasKey("AcTransLineCktId", "OwnerId"); b.HasIndex("OwnerId"); b.ToTable("AcTransLineCktOwners"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.AcTransmissionLine", b => { b.Property<int>("AcTransmissionLineId") .ValueGeneratedOnAdd(); b.Property<int>("FromSubstationId"); b.Property<string>("Name") .IsRequired(); b.Property<int>("ToSubstationId"); b.Property<int>("VoltLevelId"); b.Property<int>("WebUatId"); b.HasKey("AcTransmissionLineId"); b.HasIndex("FromSubstationId"); b.HasIndex("Name") .IsUnique(); b.HasIndex("ToSubstationId"); b.HasIndex("VoltLevelId"); b.HasIndex("WebUatId") .IsUnique(); b.ToTable("AcTransmissionLines"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.Bus", b => { b.Property<int>("BusId") .ValueGeneratedOnAdd(); b.Property<string>("BusNumber"); b.Property<string>("BusType"); b.Property<string>("Name"); b.Property<int>("SubstationId"); b.Property<int>("VoltLevelId"); b.Property<int>("WebUatId"); b.HasKey("BusId"); b.HasIndex("SubstationId"); b.HasIndex("VoltLevelId"); b.HasIndex("WebUatId") .IsUnique(); b.ToTable("Buses"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.ConductorType", b => { b.Property<int>("ConductorTypeId") .ValueGeneratedOnAdd(); b.Property<string>("Name") .IsRequired(); b.Property<int>("WebUatId"); b.HasKey("ConductorTypeId"); b.HasIndex("Name") .IsUnique(); b.HasIndex("WebUatId") .IsUnique(); b.ToTable("ConductorTypes"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.Fuel", b => { b.Property<int>("FuelId") .ValueGeneratedOnAdd(); b.Property<string>("Name") .IsRequired(); b.Property<int>("WebUatId"); b.HasKey("FuelId"); b.HasIndex("Name") .IsUnique(); b.HasIndex("WebUatId") .IsUnique(); b.ToTable("Fuels"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.GeneratingStation", b => { b.Property<int>("GeneratingStationId") .ValueGeneratedOnAdd(); b.Property<int>("FuelId"); b.Property<int>("GenerationTypeId"); b.Property<int>("GeneratorClassificationId"); b.Property<string>("Name") .IsRequired(); b.Property<int>("StateId"); b.Property<int>("WebUatId"); b.HasKey("GeneratingStationId"); b.HasIndex("FuelId"); b.HasIndex("GenerationTypeId"); b.HasIndex("GeneratorClassificationId"); b.HasIndex("StateId"); b.HasIndex("WebUatId") .IsUnique(); b.HasIndex("Name", "GeneratorClassificationId", "StateId") .IsUnique(); b.ToTable("GeneratingStations"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.GeneratingStationOwner", b => { b.Property<int>("GeneratingStationId"); b.Property<int>("OwnerId"); b.Property<int>("WebUatId"); b.HasKey("GeneratingStationId", "OwnerId"); b.HasIndex("OwnerId"); b.ToTable("GeneratingStationOwners"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.GenerationType", b => { b.Property<int>("GenerationTypeId") .ValueGeneratedOnAdd(); b.Property<string>("Name") .IsRequired(); b.Property<int>("WebUatId"); b.HasKey("GenerationTypeId"); b.HasIndex("Name") .IsUnique(); b.HasIndex("WebUatId") .IsUnique(); b.ToTable("GenerationTypes"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.GenerationTypeFuel", b => { b.Property<int>("GenerationTypeId"); b.Property<int>("FuelId"); b.Property<int>("WebUatId"); b.HasKey("GenerationTypeId", "FuelId"); b.HasIndex("FuelId"); b.ToTable("GenerationTypeFuels"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.GeneratorClassification", b => { b.Property<int>("GeneratorClassificationId") .ValueGeneratedOnAdd(); b.Property<string>("Name") .IsRequired(); b.Property<int>("WebUatId"); b.HasKey("GeneratorClassificationId"); b.HasIndex("Name") .IsUnique(); b.HasIndex("WebUatId") .IsUnique(); b.ToTable("GeneratorClassifications"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.MajorSubstation", b => { b.Property<int>("MajorSubstationId") .ValueGeneratedOnAdd(); b.Property<string>("Name") .IsRequired(); b.Property<int>("StateId"); b.Property<int>("WebUatId"); b.HasKey("MajorSubstationId"); b.HasIndex("Name") .IsUnique(); b.HasIndex("StateId"); b.HasIndex("WebUatId") .IsUnique(); b.ToTable("MajorSubstations"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.Owner", b => { b.Property<int>("OwnerId") .ValueGeneratedOnAdd(); b.Property<string>("Name") .IsRequired(); b.Property<int>("WebUatId"); b.HasKey("OwnerId"); b.HasIndex("WebUatId") .IsUnique(); b.ToTable("Owners"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.Region", b => { b.Property<int>("RegionId") .ValueGeneratedOnAdd(); b.Property<string>("FullName") .IsRequired(); b.Property<string>("ShortName") .IsRequired(); b.Property<int>("WebUatId"); b.HasKey("RegionId"); b.HasIndex("FullName") .IsUnique(); b.HasIndex("ShortName") .IsUnique(); b.HasIndex("WebUatId") .IsUnique(); b.ToTable("Regions"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.State", b => { b.Property<int>("StateId") .ValueGeneratedOnAdd(); b.Property<string>("FullName") .IsRequired(); b.Property<int>("RegionId"); b.Property<string>("ShortName") .IsRequired(); b.Property<int>("WebUatId"); b.HasKey("StateId"); b.HasIndex("FullName") .IsUnique(); b.HasIndex("RegionId"); b.HasIndex("ShortName") .IsUnique(); b.HasIndex("WebUatId") .IsUnique(); b.ToTable("States"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.Substation", b => { b.Property<int>("SubstationId") .ValueGeneratedOnAdd(); b.Property<string>("BusbarScheme") .IsRequired() .ValueGeneratedOnAdd() .HasDefaultValue("NA"); b.Property<string>("Classification"); b.Property<DateTime>("CodDate"); b.Property<DateTime>("CommDate"); b.Property<DateTime>("DecommDate"); b.Property<int>("MajorSubstationId"); b.Property<string>("Name") .IsRequired(); b.Property<int>("StateId"); b.Property<int>("VoltLevelId"); b.Property<int>("WebUatId"); b.HasKey("SubstationId"); b.HasIndex("MajorSubstationId"); b.HasIndex("StateId"); b.HasIndex("VoltLevelId"); b.HasIndex("WebUatId") .IsUnique(); b.HasIndex("Name", "Classification") .IsUnique(); b.ToTable("Substations"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.SubstationOwner", b => { b.Property<int>("SubstationId"); b.Property<int>("OwnerId"); b.Property<int>("WebUatId"); b.HasKey("SubstationId", "OwnerId"); b.HasIndex("OwnerId"); b.ToTable("SubstationOwners"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.VoltLevel", b => { b.Property<int>("VoltLevelId") .ValueGeneratedOnAdd(); b.Property<string>("EntityType"); b.Property<string>("Name") .IsRequired(); b.Property<int>("WebUatId"); b.HasKey("VoltLevelId"); b.HasIndex("Name") .IsUnique(); b.HasIndex("WebUatId") .IsUnique(); b.ToTable("VoltLevels"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Frequency.MartDailyFrequencySummary", b => { b.Property<int>("MartDailyFrequencySummaryId") .ValueGeneratedOnAdd(); b.Property<decimal>("AverageFrequency") .HasColumnType("decimal(4,2)"); b.Property<DateTime>("DataDate") .HasColumnType("date"); b.Property<decimal>("FVIFrequency") .HasColumnType("decimal(5,3)"); b.Property<decimal>("MaxBlkFreq") .HasColumnType("decimal(4,2)"); b.Property<decimal>("MaxFrequency") .HasColumnType("decimal(4,2)"); b.Property<DateTime>("MaxFrequencyTime"); b.Property<decimal>("MinBlkFreq") .HasColumnType("decimal(4,2)"); b.Property<decimal>("MinFrequency") .HasColumnType("decimal(4,2)"); b.Property<DateTime>("MinFrequencyTime"); b.Property<decimal>("NumOutOfIEGCHrs") .HasColumnType("decimal(5,3)"); b.Property<decimal>("PercGreat50_05") .HasColumnType("decimal(4,2)"); b.Property<decimal>("PercGreatEq49_9LessEq50_05") .HasColumnType("decimal(4,2)"); b.Property<decimal>("PercLess48_8") .HasColumnType("decimal(4,2)"); b.Property<decimal>("PercLess49") .HasColumnType("decimal(4,2)"); b.Property<decimal>("PercLess49_2") .HasColumnType("decimal(4,2)"); b.Property<decimal>("PercLess49_5") .HasColumnType("decimal(4,2)"); b.Property<decimal>("PercLess49_7") .HasColumnType("decimal(4,2)"); b.Property<decimal>("PercLess49_9") .HasColumnType("decimal(4,2)"); b.Property<decimal>("StandardDeviationFrequency") .HasColumnType("decimal(5,3)"); b.HasKey("MartDailyFrequencySummaryId"); b.HasIndex("DataDate") .IsUnique(); b.ToTable("MartDailyFrequencySummaries"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Frequency.RawFrequency", b => { b.Property<int>("RawFrequencyId") .ValueGeneratedOnAdd(); b.Property<DateTime>("DataTime"); b.Property<decimal>("Frequency") .HasColumnType("decimal(5,3)"); b.HasKey("RawFrequencyId"); b.HasIndex("DataTime") .IsUnique(); b.ToTable("RawFrequencies"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.AcTransLineCkt", b => { b.HasOne("WRLDCWarehouse.Core.Entities.AcTransmissionLine", "AcTransmissionLine") .WithMany() .HasForeignKey("AcTransmissionLineId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("WRLDCWarehouse.Core.Entities.ConductorType", "ConductorType") .WithMany() .HasForeignKey("ConductorTypeId"); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.AcTransLineCktOwner", b => { b.HasOne("WRLDCWarehouse.Core.Entities.AcTransLineCkt", "AcTransLineCkt") .WithMany("AcTransLineCktOwners") .HasForeignKey("AcTransLineCktId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("WRLDCWarehouse.Core.Entities.Owner", "Owner") .WithMany() .HasForeignKey("OwnerId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.AcTransmissionLine", b => { b.HasOne("WRLDCWarehouse.Core.Entities.Substation", "FromSubstation") .WithMany() .HasForeignKey("FromSubstationId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("WRLDCWarehouse.Core.Entities.Substation", "ToSubstation") .WithMany() .HasForeignKey("ToSubstationId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("WRLDCWarehouse.Core.Entities.VoltLevel", "VoltLevel") .WithMany() .HasForeignKey("VoltLevelId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.Bus", b => { b.HasOne("WRLDCWarehouse.Core.Entities.Substation", "Substation") .WithMany() .HasForeignKey("SubstationId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("WRLDCWarehouse.Core.Entities.VoltLevel", "VoltLevel") .WithMany() .HasForeignKey("VoltLevelId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.GeneratingStation", b => { b.HasOne("WRLDCWarehouse.Core.Entities.Fuel", "Fuel") .WithMany() .HasForeignKey("FuelId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("WRLDCWarehouse.Core.Entities.GenerationType", "GenerationType") .WithMany() .HasForeignKey("GenerationTypeId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("WRLDCWarehouse.Core.Entities.GeneratorClassification", "GeneratorClassification") .WithMany() .HasForeignKey("GeneratorClassificationId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("WRLDCWarehouse.Core.Entities.State", "State") .WithMany() .HasForeignKey("StateId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.GeneratingStationOwner", b => { b.HasOne("WRLDCWarehouse.Core.Entities.GeneratingStation", "GeneratingStation") .WithMany("GeneratingStationOwners") .HasForeignKey("GeneratingStationId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("WRLDCWarehouse.Core.Entities.Owner", "Owner") .WithMany() .HasForeignKey("OwnerId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.GenerationTypeFuel", b => { b.HasOne("WRLDCWarehouse.Core.Entities.Fuel", "Fuel") .WithMany() .HasForeignKey("FuelId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("WRLDCWarehouse.Core.Entities.GenerationType", "GenerationType") .WithMany() .HasForeignKey("GenerationTypeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.MajorSubstation", b => { b.HasOne("WRLDCWarehouse.Core.Entities.State", "State") .WithMany() .HasForeignKey("StateId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.State", b => { b.HasOne("WRLDCWarehouse.Core.Entities.Region", "Region") .WithMany() .HasForeignKey("RegionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.Substation", b => { b.HasOne("WRLDCWarehouse.Core.Entities.MajorSubstation", "MajorSubstation") .WithMany() .HasForeignKey("MajorSubstationId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("WRLDCWarehouse.Core.Entities.State", "State") .WithMany() .HasForeignKey("StateId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("WRLDCWarehouse.Core.Entities.VoltLevel", "VoltLevel") .WithMany() .HasForeignKey("VoltLevelId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("WRLDCWarehouse.Core.Entities.SubstationOwner", b => { b.HasOne("WRLDCWarehouse.Core.Entities.Owner", "Owner") .WithMany() .HasForeignKey("OwnerId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("WRLDCWarehouse.Core.Entities.Substation", "Substation") .WithMany("SubstationOwners") .HasForeignKey("SubstationId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
33.721154
111
0.452198
[ "MIT" ]
POSOCO/wrldc_data_warehouse_csharp
WRLDCWareHouseWebApp/Migrations/20190723181848_gen_station_name_unique_modify.Designer.cs
24,551
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Verse; using TacticalGroups; using RimWorld; namespace PawnTableGrouped { class GroupWorker_ByColonyGroup : GroupWorker { class GroupComparer : IComparer<PawnTableGroup> { public int Compare(PawnTableGroup x, PawnTableGroup y) { return 0; } } public override IComparer<PawnTableGroup> GroupsSortingComparer { get; protected set; } public GroupWorker_ByColonyGroup() { GroupsSortingComparer = new GroupComparer(); } public override string Key() { return "colonygroups_group"; } public override string MenuItemTitle() { return "colony groups"; } public override TaggedString TitleForGroup(IEnumerable<Pawn> groupPawns, Pawn keyPawn) { return ""; } public override IEnumerable<PawnTableGroup> CreateGroups(Verse.WeakReference<PawnTable> table, List<Pawn> pawns, Func<IEnumerable<Pawn>, IEnumerable<Pawn>> defaultPawnSort, List<GroupColumnWorker> columnResolvers) { if (!ColonyGroupsBridge.Instance.IsActive) { yield break; } HashSet<Pawn> tablePawns = new HashSet<Pawn>(pawns); HashSet<Pawn> ungrouped = new HashSet<Pawn>(pawns); foreach (var cgGroup in ColonyGroupsBridge.AllPawnGroups().Reverse<PawnGroup>()) { ungrouped.ExceptWith(cgGroup.ActivePawns); var groupPawns = cgGroup.ActivePawns.Intersect(tablePawns).ToArray(); if (groupPawns.Length > 0) { yield return new PawnTableGroup(table, cgGroup.curGroupName ?? "", null, cgGroup.ActivePawns.Intersect(tablePawns), columnResolvers, () => { return groupPawns.Length != cgGroup.ActivePawns.Count ? $"{groupPawns.Length} of {cgGroup.ActivePawns.Count}" : $"{groupPawns.Length}"; }); } } if (ungrouped.Count > 0) { var pawnsPreservingOrder = pawns.Where(p => ungrouped.Contains(p)); yield return new PawnTableGroup(table, "Ungrouped", null, defaultPawnSort(pawnsPreservingOrder), columnResolvers); } } } }
32.855263
221
0.59151
[ "MIT" ]
krypt-lynx/PawnTableGrouped
Source/ColonyGroupsSupport/GroupingProviders/GroupWorker_ByColonyGroup.cs
2,499
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Models.Api20211030Preview { using static Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Runtime.Extensions; /// <summary>A list of Database Migrations.</summary> public partial class DatabaseMigrationListResult : Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Models.Api20211030Preview.IDatabaseMigrationListResult, Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Models.Api20211030Preview.IDatabaseMigrationListResultInternal { /// <summary>Internal Acessors for NextLink</summary> string Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Models.Api20211030Preview.IDatabaseMigrationListResultInternal.NextLink { get => this._nextLink; set { {_nextLink = value;} } } /// <summary>Internal Acessors for Value</summary> Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Models.Api20211030Preview.IDatabaseMigration[] Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Models.Api20211030Preview.IDatabaseMigrationListResultInternal.Value { get => this._value; set { {_value = value;} } } /// <summary>Backing field for <see cref="NextLink" /> property.</summary> private string _nextLink; [Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataMigration.PropertyOrigin.Owned)] public string NextLink { get => this._nextLink; } /// <summary>Backing field for <see cref="Value" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Models.Api20211030Preview.IDatabaseMigration[] _value; [Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Origin(Microsoft.Azure.PowerShell.Cmdlets.DataMigration.PropertyOrigin.Owned)] public Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Models.Api20211030Preview.IDatabaseMigration[] Value { get => this._value; } /// <summary>Creates an new <see cref="DatabaseMigrationListResult" /> instance.</summary> public DatabaseMigrationListResult() { } } /// A list of Database Migrations. public partial interface IDatabaseMigrationListResult : Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Runtime.IJsonSerializable { [Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Runtime.Info( Required = false, ReadOnly = true, Description = @"", SerializedName = @"nextLink", PossibleTypes = new [] { typeof(string) })] string NextLink { get; } [Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Runtime.Info( Required = false, ReadOnly = true, Description = @"", SerializedName = @"value", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Models.Api20211030Preview.IDatabaseMigration) })] Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Models.Api20211030Preview.IDatabaseMigration[] Value { get; } } /// A list of Database Migrations. internal partial interface IDatabaseMigrationListResultInternal { string NextLink { get; set; } Microsoft.Azure.PowerShell.Cmdlets.DataMigration.Models.Api20211030Preview.IDatabaseMigration[] Value { get; set; } } }
52.142857
272
0.720822
[ "MIT" ]
Agazoth/azure-powershell
src/DataMigration/DataMigration.Autorest/generated/api/Models/Api20211030Preview/DatabaseMigrationListResult.cs
3,581
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore; using EauClaire.Models; namespace EauClaire { public class Startup { public Startup(IWebHostEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json"); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; set; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEntityFrameworkMySql() .AddDbContext<EauClaireContext>(options => options .UseMySql(Configuration["ConnectionStrings:DefaultConnection"], ServerVersion.AutoDetect(Configuration["ConnectionStrings:DefaultConnection"]))); } public void Configure(IApplicationBuilder app) { app.UseDeveloperExceptionPage(); app.UseRouting(); app.UseEndpoints(routes => { routes.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); }); app.UseStaticFiles(); app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } } }
26.037736
153
0.68913
[ "Unlicense" ]
yesthecarlos/HairSalon
Startup.cs
1,380
C#
using Kros.Data.MsAccess; using Kros.MsAccess.Properties; using Kros.Utils; using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; namespace Kros.Data.Schema.MsAccess { /// <summary> /// The implementation of <see cref="IDatabaseSchemaLoader{T}"/> for Microsoft Access. /// </summary> public partial class MsAccessSchemaLoader : IDatabaseSchemaLoader<OleDbConnection> { #region Helper mappings private static readonly Dictionary<OleDbType, object> _defaultValueMapping = new Dictionary<OleDbType, object>() { { OleDbType.BigInt, ColumnSchema.DefaultValues.Int64 }, { OleDbType.Binary, ColumnSchema.DefaultValues.Null }, { OleDbType.Boolean, ColumnSchema.DefaultValues.Boolean }, { OleDbType.BSTR, ColumnSchema.DefaultValues.Text }, { OleDbType.Currency, ColumnSchema.DefaultValues.Decimal }, { OleDbType.Date, ColumnSchema.DefaultValues.DateTime }, { OleDbType.DBDate, ColumnSchema.DefaultValues.Date }, { OleDbType.DBTime, ColumnSchema.DefaultValues.Time }, { OleDbType.DBTimeStamp, ColumnSchema.DefaultValues.DateTime }, { OleDbType.Decimal, ColumnSchema.DefaultValues.Decimal }, { OleDbType.Double, ColumnSchema.DefaultValues.Double }, { OleDbType.Empty, ColumnSchema.DefaultValues.Null }, { OleDbType.Error, ColumnSchema.DefaultValues.Int32 }, { OleDbType.Filetime, ColumnSchema.DefaultValues.DateTime }, { OleDbType.Guid, ColumnSchema.DefaultValues.Guid }, { OleDbType.Char, ColumnSchema.DefaultValues.Text }, { OleDbType.IDispatch, ColumnSchema.DefaultValues.Null }, { OleDbType.Integer, ColumnSchema.DefaultValues.Int32 }, { OleDbType.IUnknown, ColumnSchema.DefaultValues.Null }, { OleDbType.LongVarBinary, ColumnSchema.DefaultValues.Null }, { OleDbType.LongVarChar, ColumnSchema.DefaultValues.Text }, { OleDbType.LongVarWChar, ColumnSchema.DefaultValues.Text }, { OleDbType.Numeric, ColumnSchema.DefaultValues.Decimal }, { OleDbType.PropVariant, ColumnSchema.DefaultValues.Null }, { OleDbType.Single, ColumnSchema.DefaultValues.Single }, { OleDbType.SmallInt, ColumnSchema.DefaultValues.Int16 }, { OleDbType.TinyInt, ColumnSchema.DefaultValues.SByte }, { OleDbType.UnsignedBigInt, ColumnSchema.DefaultValues.UInt64 }, { OleDbType.UnsignedInt, ColumnSchema.DefaultValues.UInt32 }, { OleDbType.UnsignedSmallInt, ColumnSchema.DefaultValues.UInt16 }, { OleDbType.UnsignedTinyInt, ColumnSchema.DefaultValues.Byte }, { OleDbType.VarBinary, ColumnSchema.DefaultValues.Null }, { OleDbType.VarChar, ColumnSchema.DefaultValues.Text }, { OleDbType.Variant, ColumnSchema.DefaultValues.Null }, { OleDbType.VarNumeric, ColumnSchema.DefaultValues.Int32 }, { OleDbType.VarWChar, ColumnSchema.DefaultValues.Text }, { OleDbType.WChar, ColumnSchema.DefaultValues.Text } }; #endregion #region Events /// <summary> /// Event raised while parsing default value of a column. It is possible to use custom parsing logic in the event handler. /// </summary> /// <remarks>When custom logic for parsing column's default value is used, the parsed value is set in /// <see cref="MsAccessParseDefaultValueEventArgs.DefaultValue"/> property and /// <see cref="MsAccessParseDefaultValueEventArgs.Handled"/> flag must be set to <see langword="true"/>.</remarks> public event EventHandler<MsAccessParseDefaultValueEventArgs> ParseDefaultValue; /// <summary> /// Raises the <see cref="ParseDefaultValue"/> event with arguments <paramref name="e"/>. /// </summary> /// <param name="e">Arguments for the event.</param> protected virtual void OnParseDefaultValue(MsAccessParseDefaultValueEventArgs e) { ParseDefaultValue?.Invoke(this, e); } #endregion #region Schema loading /// <inheritdoc cref="SupportsConnectionType(OleDbConnection)"/> bool IDatabaseSchemaLoader.SupportsConnectionType(object connection) { return SupportsConnectionType(connection as OleDbConnection); } /// <summary> /// Loads database schema for <paramref name="connection"/>. /// </summary> /// <param name="connection">Database connection.</param> /// <returns>Database schema.</returns> /// <remarks>By default, schema is loaded using new connection to the database, based on <paramref name="connection"/>. /// But if <paramref name="connection"/> is an exclusive connection, it is used directly.</remarks> /// <exception cref="ArgumentNullException"> /// The value of <paramref name="connection"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// The connection <paramref name="connection"/> is not a connection to Microsoft Access database. /// </exception> DatabaseSchema IDatabaseSchemaLoader.LoadSchema(object connection) { CheckConnection(connection); return LoadSchema(connection as OleDbConnection); } /// <summary> /// Loads table schema for table <paramref name="tableName"/> in database <paramref name="connection"/>. /// </summary> /// <param name="connection">Database connection.</param> /// <param name="tableName">Table name.</param> /// <returns>Table schema, or value <see langword="null"/> if specified table does not exist.</returns> /// <remarks>By default, schema is loaded using new connection to the database, based on <paramref name="connection"/>. /// But if <paramref name="connection"/> is an exclusive connection, it is used directly.</remarks> /// <exception cref="ArgumentNullException">The value of <paramref name="connection"/> or <paramref name="tableName"/> /// is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <list> /// <item>The connection <paramref name="connection"/> is not a connection to Microsoft Access database.</item> /// <item>The value of <paramref name="tableName"/> is empty string, or string containing whitespace characters only. /// </item> /// </list> /// </exception> TableSchema IDatabaseSchemaLoader.LoadTableSchema(object connection, string tableName) { CheckConnection(connection); return LoadTableSchema(connection as OleDbConnection, tableName); } /// <summary> /// Checks if it is poosible to load database schema for <paramref name="connection"/>. /// </summary> /// <param name="connection">Database connection.</param> /// <returns><see langword="false"/> if value of <paramref name="connection"/> is <see langword="null"/>, or it is not /// a connection to Microsoft Access database. Otherwise <see langword="true"/>.</returns> public bool SupportsConnectionType(OleDbConnection connection) { return (connection != null) && MsAccessDataHelper.IsMsAccessConnection(connection); } /// <summary> /// Loads database schema for <paramref name="connection"/>. /// </summary> /// <param name="connection">Database connection.</param> /// <returns>Database schema.</returns> /// <remarks> /// Loading schema creates a new connection to database based on <paramref name="connection"/>. If loading with /// new connection fails (for example input connection is exclusive), schema is loaded using input /// <paramref name="connection"/> directly.</remarks> /// <exception cref="ArgumentNullException">Value of <paramref name="connection"/> id <see langword="null"/>.</exception> /// <exception cref="ArgumentException">The connection <paramref name="connection"/> is not a connection /// to Microsoft Access database.</exception> public DatabaseSchema LoadSchema(OleDbConnection connection) { CheckConnection(connection); if (MsAccessDataHelper.IsExclusiveMsAccessConnection(connection.ConnectionString)) { return LoadSchemaCore(connection); } using (OleDbConnection cn = (OleDbConnection)(connection as ICloneable).Clone()) { cn.Open(); return LoadSchemaCore(cn); } } /// <summary> /// Loads table schema for table <paramref name="tableName"/> in database <paramref name="connection"/>. /// </summary> /// <param name="connection">Database connection.</param> /// <param name="tableName">Table name.</param> /// <returns>Table schema, or value <see langword="null"/> if specified table does not exist.</returns> /// <remarks> /// Loading schema creates a new connection to database based on <paramref name="connection"/>. If loading with /// new connection fails (for example input connection is exclusive), schema is loaded using input /// <paramref name="connection"/> directly.</remarks> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>Value of <paramref name="connection"/> is <see langword="null"/>.</item> /// <item>Value of <paramref name="tableName"/> is <see langword="null"/>.</item> /// </list> /// </exception> /// <exception cref="ArgumentException"> /// Value of <paramref name="tableName"/> is an empty string, or string containing whitespace characters only. /// </exception> public TableSchema LoadTableSchema(OleDbConnection connection, string tableName) { CheckConnection(connection); Check.NotNullOrWhiteSpace(tableName, nameof(tableName)); if (MsAccessDataHelper.IsExclusiveMsAccessConnection(connection.ConnectionString)) { return LoadTableSchemaCore(connection, tableName); } using (OleDbConnection cn = (OleDbConnection)(connection as ICloneable).Clone()) { cn.Open(); return LoadTableSchemaCore(cn, tableName); } } private DatabaseSchema LoadSchemaCore(OleDbConnection connection) { OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder(connection.ConnectionString); DatabaseSchema database = new DatabaseSchema(builder.DataSource); LoadTables(connection, database); LoadColumns(connection, database); LoadIndexes(connection, database); return database; } #endregion #region Tables private TableSchema LoadTableSchemaCore(OleDbConnection connection, string tableName) { TableSchema table = null; using (DataTable schemaData = GetSchemaTables(connection, tableName)) { if (schemaData.Rows.Count == 1) { table = new TableSchema(tableName); using (DataTable columnsSchemaData = GetSchemaColumns(connection, tableName)) { LoadColumns(table, columnsSchemaData); } } } return table; } private void LoadTables(OleDbConnection connection, DatabaseSchema database) { using (DataTable schemaData = GetSchemaTables(connection)) { foreach (DataRow row in schemaData.Rows) { database.Tables.Add(row.Field<string>(TablesSchemaNames.TableName)); } } } private void LoadColumns(OleDbConnection connection, DatabaseSchema database) { using (DataTable schemaData = GetSchemaColumns(connection)) { foreach (TableSchema table in database.Tables) { LoadColumns(table, schemaData); } } } private void LoadColumns(TableSchema table, DataTable columnsSchemaData) { columnsSchemaData.DefaultView.RowFilter = $"{ColumnsSchemaNames.TableName} = '{table.Name}'"; foreach (DataRowView rowView in columnsSchemaData.DefaultView) { table.Columns.Add(CreateColumnSchema(rowView.Row, table)); } } private MsAccessColumnSchema CreateColumnSchema(DataRow row, TableSchema table) { MsAccessColumnSchema column = new MsAccessColumnSchema(row.Field<string>(ColumnsSchemaNames.ColumnName)); column.AllowNull = row.Field<bool>(ColumnsSchemaNames.IsNullable); column.OleDbType = GetOleDbType(row); column.DefaultValue = GetDefaultValue(row, column, table); if (!row.IsNull(ColumnsSchemaNames.CharacterMaximumLength)) { column.Size = (int)row.Field<long>(ColumnsSchemaNames.CharacterMaximumLength); } if (!row.IsNull(ColumnsSchemaNames.NumericPrecision)) { column.Precision = Convert.ToByte(row[ColumnsSchemaNames.NumericPrecision]); } if (!row.IsNull(ColumnsSchemaNames.NumericScale)) { column.Scale = Convert.ToByte(row[ColumnsSchemaNames.NumericScale]); } return column; } private OleDbType GetOleDbType(DataRow row) { return (OleDbType)(row.Field<int>(ColumnsSchemaNames.DataType)); } private object GetDefaultValue(DataRow row, MsAccessColumnSchema column, TableSchema table) { object defaultValue = null; string defaultValueString = null; if (row.IsNull(ColumnsSchemaNames.ColumnDefault)) { defaultValue = column.AllowNull ? DBNull.Value : _defaultValueMapping[column.OleDbType]; } else { defaultValueString = GetDefaultValueString(row.Field<string>(ColumnsSchemaNames.ColumnDefault)); defaultValue = GetDefaultValueFromString(defaultValueString, column.OleDbType); } MsAccessParseDefaultValueEventArgs e = new MsAccessParseDefaultValueEventArgs( table.Name, column.Name, column.OleDbType, defaultValueString, defaultValue); OnParseDefaultValue(e); if (e.Handled) { defaultValue = e.DefaultValue; } if ((defaultValue == null) || (defaultValue == DBNull.Value)) { return column.AllowNull ? DBNull.Value : _defaultValueMapping[column.OleDbType]; } return defaultValue; } /// <summary> /// Adjusts the string <paramref name="rawDefaultValueString"/> so column's default value can be obtained from it. /// </summary> /// <param name="rawDefaultValueString">Default value string as it is stored in database.</param> /// <returns>Adjusted string - trimmed of unneeded characters.</returns> protected virtual string GetDefaultValueString(string rawDefaultValueString) { // Default value are in database stored in a way, that the value is enclosed in apostrophes. // In case of string column, it is also in quotation marks. // To remove them (Trim) is needed to do twice. return rawDefaultValueString.Trim('\'').Trim('"'); } private object GetDefaultValueFromString(string defaultValueString, OleDbType dataType) { object result = null; if ((dataType == OleDbType.VarChar) || (dataType == OleDbType.LongVarChar) || (dataType == OleDbType.VarWChar) || (dataType == OleDbType.LongVarWChar) || (dataType == OleDbType.Char) || (dataType == OleDbType.WChar)) { result = defaultValueString; } else { result = GetParseFunction(dataType)?.Invoke(defaultValueString); } return result; } private DefaultValueParsers.ParseDefaultValueFunction GetParseFunction(OleDbType dataType) { switch (dataType) { case OleDbType.BigInt: return DefaultValueParsers.ParseInt64; case OleDbType.Integer: return DefaultValueParsers.ParseInt32; case OleDbType.SmallInt: return DefaultValueParsers.ParseInt16; case OleDbType.TinyInt: return DefaultValueParsers.ParseSByte; case OleDbType.Double: case OleDbType.Numeric: return DefaultValueParsers.ParseDouble; case OleDbType.Single: return DefaultValueParsers.ParseSingle; case OleDbType.Decimal: case OleDbType.Currency: return DefaultValueParsers.ParseDecimal; case OleDbType.UnsignedBigInt: return DefaultValueParsers.ParseUInt64; case OleDbType.UnsignedInt: return DefaultValueParsers.ParseUInt32; case OleDbType.UnsignedSmallInt: return DefaultValueParsers.ParseUInt16; case OleDbType.UnsignedTinyInt: return DefaultValueParsers.ParseByte; case OleDbType.Guid: return DefaultValueParsers.ParseGuid; case OleDbType.Boolean: return DefaultValueParsers.ParseBool; case OleDbType.Date: return DefaultValueParsers.ParseDate; } return null; } #endregion #region Indexes private void LoadIndexes(OleDbConnection connection, DatabaseSchema database) { using (DataTable schemaData = connection.GetSchema(SchemaNames.Indexes)) { foreach (TableSchema table in database.Tables) { schemaData.DefaultView.RowFilter = $"{IndexesSchemaNames.TableName} = '{table.Name}'"; schemaData.DefaultView.Sort = $"{IndexesSchemaNames.IndexName}, {IndexesSchemaNames.OrdinalPosition}"; if (schemaData.DefaultView.Count > 0) { LoadIndexesForTable(table, schemaData.DefaultView); } } } } private void LoadIndexesForTable(TableSchema table, DataView schemaData) { string lastIndexName = string.Empty; IndexSchema index = null; foreach (DataRowView rowView in schemaData) { string indexName = rowView.Row.Field<string>(IndexesSchemaNames.IndexName); if (indexName != lastIndexName) { lastIndexName = indexName; index = CreateIndexSchema(table, rowView.Row); } AddColumnToIndex(index, rowView.Row); } } private IndexSchema CreateIndexSchema(TableSchema table, DataRow row) { string indexName = row.Field<string>(IndexesSchemaNames.IndexName); bool clustered = row.Field<bool>(IndexesSchemaNames.Clustered); if (row.Field<bool>(IndexesSchemaNames.PrimaryKey)) { return table.SetPrimaryKey(indexName, clustered); } else { IndexType indexType = row.Field<bool>(IndexesSchemaNames.Unique) ? IndexType.UniqueKey : IndexType.Index; return table.Indexes.Add(indexName, indexType, clustered); } } private void AddColumnToIndex(IndexSchema index, DataRow row) { index.Columns.Add( row.Field<string>(IndexesSchemaNames.ColumnName), row.Field<short>(IndexesSchemaNames.Collation) == 2 ? SortOrder.Descending : SortOrder.Ascending); } #endregion #region Helpers private void CheckConnection(object connection) { Check.NotNull(connection, nameof(connection)); if (!(this as IDatabaseSchemaLoader).SupportsConnectionType(connection)) { throw new ArgumentException(Resources.UnsupportedConnectionType, nameof(connection)); } } private DataTable GetSchemaTables(OleDbConnection connection) { return GetSchemaTables(connection, null); } private DataTable GetSchemaTables(OleDbConnection connection, string tableName) { return connection.GetSchema(SchemaNames.Tables, new string[] { null, null, tableName, TableTypes.Table }); } private DataTable GetSchemaColumns(OleDbConnection connection) { return GetSchemaColumns(connection, null); } private DataTable GetSchemaColumns(OleDbConnection connection, string tableName) { DataTable schemaData = connection.GetSchema(SchemaNames.Columns, new string[] { null, null, tableName, null }); schemaData.DefaultView.Sort = $"{ColumnsSchemaNames.TableSchema}, {ColumnsSchemaNames.TableName}, {ColumnsSchemaNames.OrdinalPosition}"; return schemaData; } #endregion } }
43.327485
130
0.609799
[ "MIT" ]
Abd-Elrazek/Kros.Libs
Kros.Utils/src/Kros.Utils.MsAccess/Data/Schema/MsAccess/MsAccessSchemaLoader.cs
22,229
C#
using System; using System.Collections.Generic; using Avalonia.Platform; namespace Avalonia.Media { /// <summary> /// Represents a piece of text with formatting. /// </summary> public class FormattedText { private readonly IPlatformRenderInterface _platform; private Size _constraint = Size.Infinity; private IFormattedTextImpl? _platformImpl; private IReadOnlyList<FormattedTextStyleSpan>? _spans; private Typeface _typeface; private double _fontSize; private string? _text; private TextAlignment _textAlignment; private TextWrapping _textWrapping; /// <summary> /// Initializes a new instance of the <see cref="FormattedText"/> class. /// </summary> public FormattedText() { _platform = AvaloniaLocator.Current.GetService<IPlatformRenderInterface>() ?? throw new InvalidOperationException("Unable to locate IPlatformRenderInterface."); } /// <summary> /// Initializes a new instance of the <see cref="FormattedText"/> class. /// </summary> /// <param name="platform">The platform render interface.</param> public FormattedText(IPlatformRenderInterface platform) { _platform = platform; } /// <summary> /// Initializes a new instance of the <see cref="FormattedText"/> class. /// </summary> /// <param name="text"></param> /// <param name="typeface"></param> /// <param name="fontSize"></param> /// <param name="textAlignment"></param> /// <param name="textWrapping"></param> /// <param name="constraint"></param> public FormattedText(string text, Typeface typeface, double fontSize, TextAlignment textAlignment, TextWrapping textWrapping, Size constraint) : this() { _text = text; _typeface = typeface; _fontSize = fontSize; _textAlignment = textAlignment; _textWrapping = textWrapping; _constraint = constraint; } /// <summary> /// Gets the bounds of the text within the <see cref="Constraint"/>. /// </summary> /// <returns>The bounds of the text.</returns> public Rect Bounds => PlatformImpl.Bounds; /// <summary> /// Gets or sets the constraint of the text. /// </summary> public Size Constraint { get => _constraint; set => Set(ref _constraint, value); } /// <summary> /// Gets or sets the base typeface. /// </summary> public Typeface Typeface { get => _typeface; set => Set(ref _typeface, value); } /// <summary> /// Gets or sets the font size. /// </summary> public double FontSize { get => _fontSize; set => Set(ref _fontSize, value); } /// <summary> /// Gets or sets a collection of spans that describe the formatting of subsections of the /// text. /// </summary> public IReadOnlyList<FormattedTextStyleSpan>? Spans { get => _spans; set => Set(ref _spans, value); } /// <summary> /// Gets or sets the text. /// </summary> public string? Text { get => _text; set => Set(ref _text, value); } /// <summary> /// Gets or sets the alignment of the text. /// </summary> public TextAlignment TextAlignment { get => _textAlignment; set => Set(ref _textAlignment, value); } /// <summary> /// Gets or sets the text wrapping. /// </summary> public TextWrapping TextWrapping { get => _textWrapping; set => Set(ref _textWrapping, value); } /// <summary> /// Gets platform-specific platform implementation. /// </summary> public IFormattedTextImpl PlatformImpl { get { if (_platformImpl == null) { _platformImpl = _platform.CreateFormattedText( _text ?? string.Empty, _typeface, _fontSize, _textAlignment, _textWrapping, _constraint, _spans); } return _platformImpl; } } /// <summary> /// Gets the lines in the text. /// </summary> /// <returns> /// A collection of <see cref="FormattedTextLine"/> objects. /// </returns> public IEnumerable<FormattedTextLine> GetLines() { return PlatformImpl.GetLines(); } /// <summary> /// Hit tests a point in the text. /// </summary> /// <param name="point">The point.</param> /// <returns> /// A <see cref="TextHitTestResult"/> describing the result of the hit test. /// </returns> public TextHitTestResult HitTestPoint(Point point) { return PlatformImpl.HitTestPoint(point); } /// <summary> /// Gets the bounds rectangle that the specified character occupies. /// </summary> /// <param name="index">The index of the character.</param> /// <returns>The character bounds.</returns> public Rect HitTestTextPosition(int index) { return PlatformImpl.HitTestTextPosition(index); } /// <summary> /// Gets the bounds rectangles that the specified text range occupies. /// </summary> /// <param name="index">The index of the first character.</param> /// <param name="length">The number of characters in the text range.</param> /// <returns>The character bounds.</returns> public IEnumerable<Rect> HitTestTextRange(int index, int length) { return PlatformImpl.HitTestTextRange(index, length); } private void Set<T>(ref T field, T value) { if (EqualityComparer<T>.Default.Equals(field, value)) { return; } field = value; _platformImpl = null; } } }
30.305556
106
0.527803
[ "MIT" ]
wieslawsoltes/Avalonia
src/Avalonia.Visuals/Media/FormattedText.cs
6,546
C#
using Core.BackgroundWorkers; using Core.Events.External; using Core.Kafka.Consumers; using Core.Kafka.Producers; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; namespace Core.Kafka; public static class Config { public static IServiceCollection AddKafkaProducer(this IServiceCollection services) { //using TryAdd to support mocking, without that it won't be possible to override in tests services.TryAddScoped<IExternalEventProducer, KafkaProducer>(); return services; } public static IServiceCollection AddKafkaConsumer(this IServiceCollection services) { //using TryAdd to support mocking, without that it won't be possible to override in tests services.TryAddSingleton<IExternalEventConsumer, KafkaConsumer>(); return services.AddHostedService(serviceProvider => { var logger = serviceProvider.GetRequiredService<ILogger<BackgroundWorker>>(); var consumer = serviceProvider.GetRequiredService<IExternalEventConsumer>(); return new BackgroundWorker( logger, consumer.StartAsync ); } ); } public static IServiceCollection AddKafkaProducerAndConsumer(this IServiceCollection services) { return services .AddKafkaProducer() .AddKafkaConsumer(); } }
32.145833
98
0.675308
[ "MIT" ]
mehdihadeli/EventSourcing.NetCore
Core.Kafka/Config.cs
1,543
C#
using Business.Abstract; using DataAccess.Abstract; using Entities.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Business.Concrete { public class ProductManager : IProductService { //EfProductDal Kullanacağız IProductDal _productDal; public ProductManager(IProductDal productDal) { _productDal = productDal; } public List<Product> GetAll() { return _productDal.GetList(); } public List<Product> GetByCategory(int categoryId) { return _productDal.GetList(p => p.CategoryId == categoryId); } public Product GetById(int productId) { return _productDal.Get(p => p.ProductId == productId); } } }
22.076923
72
0.628339
[ "Unlicense" ]
dogukanc760/NorthwindLevelTwo
Business/Concrete/ProductManager.cs
865
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using SeeMoreInventory.Models; namespace SeeMoreInventory.Pages.AdminPages { public class AdminDeleteModel : PageModel { private readonly LensContext _lensdata; [BindProperty] public MaterialType Material { get; set; } public AdminDeleteModel(LensContext context) { _lensdata = context; } public async Task<IActionResult> OnGetAsync(int? id) { if (id == null) { return NotFound(); } Material = await _lensdata.Materials.SingleOrDefaultAsync(m => m.Id == id); if (Material == null) { return NotFound(); } return Page(); } public async Task<IActionResult> OnPostAsync(int? id) { if (id == null) { return NotFound(); } Material = await _lensdata.Materials.FindAsync(id); if (Material != null) { Material.Deleted = true; await _lensdata.SaveChangesAsync(); } return RedirectToPage("./Index"); } } }
24.631579
87
0.549145
[ "MIT" ]
dwaynegreen/lens-inventory
SeeMoreInventory/Pages/AdminPages/Delete.cshtml.cs
1,404
C#
using OpenProtocolInterpreter.Converters; using System; using System.Collections.Generic; using System.Linq; namespace OpenProtocolInterpreter.Job { /// <summary> /// MID: Job ID upload reply /// Description: /// The transmission of all the valid Job IDs of the controller. /// The data field contains the number of valid Jobs currently present in the controller, and the ID of each Job. /// Message sent by: Controller /// Answer: None /// </summary> public class Mid0031 : Mid, IJob, IController { private readonly IValueConverter<int> _intConverter; private JobIdListConverter _jobListConverter; private const int LAST_REVISION = 1; public const int MID = 31; public int TotalJobs { get => GetField(1, (int)DataFields.NUMBER_OF_JOBS).GetValue(_intConverter.Convert); private set => GetField(1, (int)DataFields.NUMBER_OF_JOBS).SetValue(_intConverter.Convert, value); } public List<int> JobIds { get; set; } public Mid0031() : this(LAST_REVISION) { } public Mid0031(int revision = LAST_REVISION) : base(MID, revision) { _intConverter = new Int32Converter(); if (JobIds == null) JobIds = new List<int>(); HandleRevisions(); } /// <summary> /// Revision 1 or 2 constructor /// </summary> /// <param name="totalJobs"> /// Revision 1 range: 00-99 /// <para>Revision 2 range: 0000-9999</para> /// </param> /// <param name="jobIds"> /// Revision 1 - range: 00-99 each /// <para>Revision 2 - range: 0000-9999 each</para> /// </param> /// /// <param name="revision">Revision number (default = 2)</param> public Mid0031(int totalJobs, IEnumerable<int> jobIds, int revision = LAST_REVISION) : this(revision) { TotalJobs = totalJobs; JobIds = jobIds.ToList(); } public override string Pack() { _jobListConverter = new JobIdListConverter(_intConverter, HeaderData.Revision); TotalJobs = JobIds.Count; var eachJobField = GetField(1, (int)DataFields.EACH_JOB_ID); eachJobField.Size = (HeaderData.Revision > 1 ? 4 : 2) * TotalJobs; eachJobField.Value = _jobListConverter.Convert(JobIds); return base.Pack(); } public override Mid Parse(string package) { HeaderData = ProcessHeader(package); HandleRevisions(); _jobListConverter = new JobIdListConverter(_intConverter, HeaderData.Revision); var eachJobField = GetField(1, (int)DataFields.EACH_JOB_ID); eachJobField.Size = package.Length - eachJobField.Index; base.Parse(package); JobIds = _jobListConverter.Convert(eachJobField.Value).ToList(); return this; } protected override Dictionary<int, List<DataField>> RegisterDatafields() { return new Dictionary<int, List<DataField>>() { { 1, new List<DataField>() { new DataField((int)DataFields.NUMBER_OF_JOBS, 20, 2, '0', DataField.PaddingOrientations.LEFT_PADDED, false), new DataField((int)DataFields.EACH_JOB_ID, 22, 2, '0', DataField.PaddingOrientations.LEFT_PADDED, false) } }, { 2, new List<DataField>() } }; } /// <summary> /// Validate all fields size /// </summary> public bool Validate(out IEnumerable<string> errors) { List<string> failed = new List<string>(); if (HeaderData.Revision > 1) { if (TotalJobs < 0 || TotalJobs > 9999) failed.Add(new ArgumentOutOfRangeException(nameof(TotalJobs), "Range: 0000-9999").Message); for (int i = 0; i < JobIds.Count; i++) { int job = JobIds[i]; if (job < 0 || job > 9999) failed.Add(new ArgumentOutOfRangeException(nameof(JobIds), $"Failed at index[{i}] => Range: 0000-9999").Message); } } else { if (TotalJobs < 0 || TotalJobs > 99) failed.Add(new ArgumentOutOfRangeException(nameof(TotalJobs), "Range: 00-99").Message); for (int i = 0; i < JobIds.Count; i++) { int job = JobIds[i]; if (job < 0 || job > 99) failed.Add(new ArgumentOutOfRangeException(nameof(JobIds), $"Failed at index[{i}] => Range: 00-99").Message); } } errors = failed; return errors.Any(); } private void HandleRevisions() { if (HeaderData.Revision > 1) { GetField(1, (int)DataFields.EACH_JOB_ID).Index = 24; GetField(1, (int)DataFields.NUMBER_OF_JOBS).Size = 4; } else { GetField(1, (int)DataFields.NUMBER_OF_JOBS).Size = GetField(1, (int)DataFields.EACH_JOB_ID).Size = 2; } } public enum DataFields { NUMBER_OF_JOBS, EACH_JOB_ID } } }
35.272152
140
0.530953
[ "MIT" ]
ZEisinger/OpenProtocolInterpreter
src/OpenProtocolInterpreter/Job/Mid0031.cs
5,575
C#
namespace Hello2 { partial class frmHello2 { /// <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.btnCall = new System.Windows.Forms.Button(); this.SuspendLayout(); // // btnCall // this.btnCall.Location = new System.Drawing.Point(82, 40); this.btnCall.Name = "btnCall"; this.btnCall.Size = new System.Drawing.Size(298, 108); this.btnCall.TabIndex = 0; this.btnCall.Text = "call Hello1"; this.btnCall.UseVisualStyleBackColor = true; this.btnCall.Click += new System.EventHandler(this.btnCall_Click); // // frmHello2 // this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(611, 314); this.Controls.Add(this.btnCall); this.Name = "frmHello2"; this.Text = "Hello2"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnCall; } }
32.080645
107
0.548517
[ "MIT" ]
GreenHackersOTC/C
Hello2/Hello2/frmHello2.Designer.cs
1,991
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Starscream.Domain.Application.Commands { public class AddAbilitiesToUser { public Guid UserId { get; protected set; } public IEnumerable<Guid> AbilitiesID { get; protected set; } protected AddAbilitiesToUser() { } public AddAbilitiesToUser(Guid userId, IEnumerable<Guid> abilities ) { UserId = userId; this.AbilitiesID = abilities; } } }
21.103448
76
0.638889
[ "MIT" ]
TMComayagua/WebSite
src/Starscream.Domain/Application/Commands/AddAbilitiesToUser.cs
614
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; namespace JitTest { internal class Base { public override String ToString() { return "Base class"; } } internal class Test : Base { public override String ToString() { return "Test class"; } private static void TestFunc(Base obj) { Console.WriteLine(obj.ToString()); } private static int Main() { try { TestFunc(new Base()); TestFunc(new Test()); } catch { Console.WriteLine("Failed w/ exception"); return 1; } Console.WriteLine("Passed"); return 100; } } }
23.5
71
0.525532
[ "MIT" ]
06needhamt/runtime
src/coreclr/tests/src/JIT/Methodical/Invoke/implicit/obj.cs
940
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ImageMaths.cs" company="James South"> // Copyright (c) James South. // Licensed under the Apache License, Version 2.0. // </copyright> // <summary> // Provides reusable mathematical methods to apply to images. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ImageProcessor.Imaging.Helpers { using System; using System.Drawing; using ImageProcessor.Imaging.Colors; /// <summary> /// Provides reusable mathematical methods to apply to images. /// </summary> public static class ImageMaths { /// <summary> /// Gets a <see cref="Rectangle"/> representing the child centered relative to the parent. /// </summary> /// <param name="parent"> /// The parent <see cref="Rectangle"/>. /// </param> /// <param name="child"> /// The child <see cref="Rectangle"/>. /// </param> /// <returns> /// The centered <see cref="Rectangle"/>. /// </returns> public static RectangleF CenteredRectangle(Rectangle parent, Rectangle child) { float x = (parent.Width - child.Width) / 2.0F; float y = (parent.Height - child.Height) / 2.0F; int width = child.Width; int height = child.Height; return new RectangleF(x, y, width, height); } /// <summary> /// Restricts a value to be within a specified range. /// </summary> /// <param name="value"> /// The The value to clamp. /// </param> /// <param name="min"> /// The minimum value. If value is less than min, min will be returned. /// </param> /// <param name="max"> /// The maximum value. If value is greater than max, max will be returned. /// </param> /// <typeparam name="T"> /// The <see cref="System.Type"/> to clamp. /// </typeparam> /// <returns> /// The <see cref="IComparable{T}"/> representing the clamped value. /// </returns> public static T Clamp<T>(T value, T min, T max) where T : IComparable<T> { if (value.CompareTo(min) < 0) { return min; } if (value.CompareTo(max) > 0) { return max; } return value; } /// <summary> /// Returns value indicating whether the given number is with in the minimum and maximum /// given range. /// </summary> /// <param name="value">The The value to clamp.</param> /// <param name="min">If <paramref name="include"/>The minimum range value.</param> /// <param name="max">The maximum range value.</param> /// <param name="include">Whether to include the minimum and maximum values. Defaults to true.</param> /// <typeparam name="T">The <see cref="System.Type"/> to test.</typeparam> /// <returns> /// True if the value falls within the maximum and minimum; otherwise, false. /// </returns> public static bool InRange<T>(T value, T min, T max, bool include = true) where T : IComparable<T> { if (include) { return (value.CompareTo(min) >= 0) && (value.CompareTo(max) <= 0); } return (value.CompareTo(min) > 0) && (value.CompareTo(max) < 0); } /// <summary> /// Returns the given degrees converted to radians. /// </summary> /// <param name="angleInDegrees"> /// The angle in degrees. /// </param> /// <returns> /// The <see cref="double"/> representing the degree as radians. /// </returns> public static double DegreesToRadians(double angleInDegrees) { return angleInDegrees * (Math.PI / 180); } /// <summary> /// Gets the bounding <see cref="Rectangle"/> from the given points. /// </summary> /// <param name="topLeft"> /// The <see cref="Point"/> designating the top left position. /// </param> /// <param name="bottomRight"> /// The <see cref="Point"/> designating the bottom right position. /// </param> /// <returns> /// The bounding <see cref="Rectangle"/>. /// </returns> public static Rectangle GetBoundingRectangle(Point topLeft, Point bottomRight) { return new Rectangle(topLeft.X, topLeft.Y, bottomRight.X - topLeft.X, bottomRight.Y - topLeft.Y); } /// <summary> /// Calculates the new size after rotation. /// </summary> /// <param name="width">The width of the image.</param> /// <param name="height">The height of the image.</param> /// <param name="angleInDegrees">The angle of rotation.</param> /// <returns>The new size of the image</returns> public static Rectangle GetBoundingRotatedRectangle(int width, int height, float angleInDegrees) { // Check first clockwise. double radians = DegreesToRadians(angleInDegrees); double radiansSin = Math.Sin(radians); double radiansCos = Math.Cos(radians); double width1 = (height * radiansSin) + (width * radiansCos); double height1 = (width * radiansSin) + (height * radiansCos); // Find dimensions in the other direction radiansSin = Math.Sin(-radians); radiansCos = Math.Cos(-radians); double width2 = (height * radiansSin) + (width * radiansCos); double height2 = (width * radiansSin) + (height * radiansCos); // Get the external vertex for the rotation Rectangle result = new Rectangle( 0, 0, Convert.ToInt32(Math.Max(Math.Abs(width1), Math.Abs(width2))), Convert.ToInt32(Math.Max(Math.Abs(height1), Math.Abs(height2)))); return result; } /// <summary> /// Finds the bounding rectangle based on the first instance of any color component other /// than the given one. /// </summary> /// <param name="bitmap"> /// The <see cref="Image"/> to search within. /// </param> /// <param name="componentValue"> /// The color component value to remove. /// </param> /// <param name="channel"> /// The <see cref="RgbaComponent"/> channel to test against. /// </param> /// <returns> /// The <see cref="Rectangle"/>. /// </returns> public static Rectangle GetFilteredBoundingRectangle(Image bitmap, byte componentValue, RgbaComponent channel = RgbaComponent.B) { int width = bitmap.Width; int height = bitmap.Height; Point topLeft = new Point(); Point bottomRight = new Point(); Func<FastBitmap, int, int, byte, bool> delegateFunc; // Determine which channel to check against switch (channel) { case RgbaComponent.R: delegateFunc = (fastBitmap, x, y, b) => fastBitmap.GetPixel(x, y).R != b; break; case RgbaComponent.G: delegateFunc = (fastBitmap, x, y, b) => fastBitmap.GetPixel(x, y).G != b; break; case RgbaComponent.A: delegateFunc = (fastBitmap, x, y, b) => fastBitmap.GetPixel(x, y).A != b; break; default: delegateFunc = (fastBitmap, x, y, b) => fastBitmap.GetPixel(x, y).B != b; break; } Func<FastBitmap, int> getMinY = fastBitmap => { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (delegateFunc(fastBitmap, x, y, componentValue)) { return y; } } } return 0; }; Func<FastBitmap, int> getMaxY = fastBitmap => { for (int y = height - 1; y > -1; y--) { for (int x = 0; x < width; x++) { if (delegateFunc(fastBitmap, x, y, componentValue)) { return y; } } } return height; }; Func<FastBitmap, int> getMinX = fastBitmap => { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if (delegateFunc(fastBitmap, x, y, componentValue)) { return x; } } } return 0; }; Func<FastBitmap, int> getMaxX = fastBitmap => { for (int x = width - 1; x > -1; x--) { for (int y = 0; y < height; y++) { if (delegateFunc(fastBitmap, x, y, componentValue)) { return x; } } } return height; }; using (FastBitmap fastBitmap = new FastBitmap(bitmap)) { topLeft.Y = getMinY(fastBitmap); topLeft.X = getMinX(fastBitmap); bottomRight.Y = getMaxY(fastBitmap) + 1; bottomRight.X = getMaxX(fastBitmap) + 1; } return GetBoundingRectangle(topLeft, bottomRight); } /// <summary> /// Rotates one point around another /// <see href="http://stackoverflow.com/questions/13695317/rotate-a-point-around-another-point"/> /// </summary> /// <param name="pointToRotate">The point to rotate.</param> /// <param name="angleInDegrees">The rotation angle in degrees.</param> /// <param name="centerPoint">The centre point of rotation. If not set the point will equal /// <see cref="Point.Empty"/> /// </param> /// <returns>Rotated point</returns> public static Point RotatePoint(Point pointToRotate, double angleInDegrees, Point? centerPoint = null) { Point center = centerPoint ?? Point.Empty; double angleInRadians = DegreesToRadians(angleInDegrees); double cosTheta = Math.Cos(angleInRadians); double sinTheta = Math.Sin(angleInRadians); return new Point { X = (int)((cosTheta * (pointToRotate.X - center.X)) - ((sinTheta * (pointToRotate.Y - center.Y)) + center.X)), Y = (int)((sinTheta * (pointToRotate.X - center.X)) + ((cosTheta * (pointToRotate.Y - center.Y)) + center.Y)) }; } /// <summary> /// Returns the array of <see cref="Point"/> matching the bounds of the given rectangle. /// </summary> /// <param name="rectangle"> /// The <see cref="Rectangle"/> to return the points from. /// </param> /// <returns> /// The <see cref="Point"/> array. /// </returns> public static Point[] ToPoints(Rectangle rectangle) { return new[] { new Point(rectangle.Left, rectangle.Top), new Point(rectangle.Right, rectangle.Top), new Point(rectangle.Right, rectangle.Bottom), new Point(rectangle.Left, rectangle.Bottom) }; } /// <summary> /// Calculates the zoom needed after the rotation to ensure the canvas is covered /// by the rotated image. /// </summary> /// <param name="imageWidth">Width of the image.</param> /// <param name="imageHeight">Height of the image.</param> /// <param name="angleInDegrees">The angle in degrees.</param> /// <remarks> /// Based on <see href="http://math.stackexchange.com/questions/1070853/"/> /// </remarks> /// <returns>The zoom needed</returns> public static float ZoomAfterRotation(int imageWidth, int imageHeight, float angleInDegrees) { Rectangle rectangle = GetBoundingRotatedRectangle(imageWidth, imageHeight, angleInDegrees); return Math.Max((float)rectangle.Width / imageWidth, (float)rectangle.Height / imageHeight); } } }
37.962536
136
0.491156
[ "Apache-2.0" ]
MCOng94/test
src/ImageProcessor/Imaging/Helpers/ImageMaths.cs
13,175
C#
namespace xbuffer { public static class t_AuthorInfo9Buffer { public static t_AuthorInfo9 deserialize(byte[] buffer, ref uint offset) { // null bool _null = boolBuffer.deserialize(buffer, ref offset); if (_null) return null; // id int _id = intBuffer.deserialize(buffer, ref offset); // author string _author = stringBuffer.deserialize(buffer, ref offset); // age int _age = intBuffer.deserialize(buffer, ref offset); // money float _money = floatBuffer.deserialize(buffer, ref offset); // hashouse bool _hashouse = boolBuffer.deserialize(buffer, ref offset); // pbutctime long _pbutctime = longBuffer.deserialize(buffer, ref offset); // luckynumber int _luckynumber_length = intBuffer.deserialize(buffer, ref offset); int[] _luckynumber = new int[_luckynumber_length]; for (int i = 0; i < _luckynumber_length; i++) { _luckynumber[i] = intBuffer.deserialize(buffer, ref offset); } // value return new t_AuthorInfo9() { id = _id, author = _author, age = _age, money = _money, hashouse = _hashouse, pbutctime = _pbutctime, luckynumber = _luckynumber, }; } public static void serialize(t_AuthorInfo9 value, XSteam steam) { // null boolBuffer.serialize(value == null, steam); if (value == null) return; // id intBuffer.serialize(value.id, steam); // author stringBuffer.serialize(value.author, steam); // age intBuffer.serialize(value.age, steam); // money floatBuffer.serialize(value.money, steam); // hashouse boolBuffer.serialize(value.hashouse, steam); // pbutctime longBuffer.serialize(value.pbutctime, steam); // luckynumber intBuffer.serialize(value.luckynumber.Length, steam); for (int i = 0; i < value.luckynumber.Length; i++) { intBuffer.serialize(value.luckynumber[i], steam); } } } }
26.166667
80
0.580073
[ "Apache-2.0" ]
fqkw6/ILRuntimeMyFrame
HotFix_Project/HotFix_Project/HotFix/Data/CSOutput/BufferCode/t_AuthorInfo9Buffer.cs
2,198
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Text; using Silk.NET.Core; using Silk.NET.Core.Native; using Silk.NET.Core.Attributes; using Silk.NET.Core.Contexts; using Silk.NET.Core.Loader; #pragma warning disable 1591 namespace Silk.NET.Direct3D12 { [Guid("be36ec3b-ea85-4aeb-a45a-e9d76404a495")] [NativeName("Name", "ID3D12Resource2")] public unsafe partial struct ID3D12Resource2 { public static readonly Guid Guid = new("be36ec3b-ea85-4aeb-a45a-e9d76404a495"); public static implicit operator ID3D12Resource1(ID3D12Resource2 val) => Unsafe.As<ID3D12Resource2, ID3D12Resource1>(ref val); public static implicit operator ID3D12Resource(ID3D12Resource2 val) => Unsafe.As<ID3D12Resource2, ID3D12Resource>(ref val); public static implicit operator ID3D12Pageable(ID3D12Resource2 val) => Unsafe.As<ID3D12Resource2, ID3D12Pageable>(ref val); public static implicit operator ID3D12DeviceChild(ID3D12Resource2 val) => Unsafe.As<ID3D12Resource2, ID3D12DeviceChild>(ref val); public static implicit operator ID3D12Object(ID3D12Resource2 val) => Unsafe.As<ID3D12Resource2, ID3D12Object>(ref val); public static implicit operator Silk.NET.Core.Native.IUnknown(ID3D12Resource2 val) => Unsafe.As<ID3D12Resource2, Silk.NET.Core.Native.IUnknown>(ref val); public ID3D12Resource2 ( void** lpVtbl = null ) : this() { if (lpVtbl is not null) { LpVtbl = lpVtbl; } } [NativeName("Type", "")] [NativeName("Type.Name", "")] [NativeName("Name", "lpVtbl")] public void** LpVtbl; /// <summary>To be documented.</summary> public readonly unsafe int QueryInterface(Guid* riid, void** ppvObject) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[0])(@this, riid, ppvObject); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[0])(@this, riid, ppvObject); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[0])(@this, riid, ppvObject); } #endif return ret; } /// <summary>To be documented.</summary> public readonly unsafe int QueryInterface(Guid* riid, ref void* ppvObject) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (void** ppvObjectPtr = &ppvObject) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[0])(@this, riid, ppvObjectPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[0])(@this, riid, ppvObjectPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[0])(@this, riid, ppvObjectPtr); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int QueryInterface(ref Guid riid, void** ppvObject) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Guid* riidPtr = &riid) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[0])(@this, riidPtr, ppvObject); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[0])(@this, riidPtr, ppvObject); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[0])(@this, riidPtr, ppvObject); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int QueryInterface(ref Guid riid, ref void* ppvObject) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Guid* riidPtr = &riid) { fixed (void** ppvObjectPtr = &ppvObject) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[0])(@this, riidPtr, ppvObjectPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[0])(@this, riidPtr, ppvObjectPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[0])(@this, riidPtr, ppvObjectPtr); } #endif } } return ret; } /// <summary>To be documented.</summary> public readonly uint AddRef() { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); uint ret = default; ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, uint>)LpVtbl[1])(@this); return ret; } /// <summary>To be documented.</summary> public readonly uint Release() { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); uint ret = default; ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, uint>)LpVtbl[2])(@this); return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetPrivateData(Guid* guid, uint* pDataSize, void* pData) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guid, pDataSize, pData); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guid, pDataSize, pData); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guid, pDataSize, pData); } #endif return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetPrivateData<T0>(Guid* guid, uint* pDataSize, ref T0 pData) where T0 : unmanaged { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (void* pDataPtr = &pData) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guid, pDataSize, pDataPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guid, pDataSize, pDataPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guid, pDataSize, pDataPtr); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetPrivateData(Guid* guid, ref uint pDataSize, void* pData) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (uint* pDataSizePtr = &pDataSize) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guid, pDataSizePtr, pData); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guid, pDataSizePtr, pData); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guid, pDataSizePtr, pData); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetPrivateData<T0>(Guid* guid, ref uint pDataSize, ref T0 pData) where T0 : unmanaged { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (uint* pDataSizePtr = &pDataSize) { fixed (void* pDataPtr = &pData) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guid, pDataSizePtr, pDataPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guid, pDataSizePtr, pDataPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guid, pDataSizePtr, pDataPtr); } #endif } } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetPrivateData(ref Guid guid, uint* pDataSize, void* pData) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Guid* guidPtr = &guid) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guidPtr, pDataSize, pData); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guidPtr, pDataSize, pData); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guidPtr, pDataSize, pData); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetPrivateData<T0>(ref Guid guid, uint* pDataSize, ref T0 pData) where T0 : unmanaged { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Guid* guidPtr = &guid) { fixed (void* pDataPtr = &pData) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guidPtr, pDataSize, pDataPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guidPtr, pDataSize, pDataPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guidPtr, pDataSize, pDataPtr); } #endif } } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetPrivateData(ref Guid guid, ref uint pDataSize, void* pData) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Guid* guidPtr = &guid) { fixed (uint* pDataSizePtr = &pDataSize) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guidPtr, pDataSizePtr, pData); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guidPtr, pDataSizePtr, pData); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guidPtr, pDataSizePtr, pData); } #endif } } return ret; } /// <summary>To be documented.</summary> public readonly int GetPrivateData<T0>(ref Guid guid, ref uint pDataSize, ref T0 pData) where T0 : unmanaged { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Guid* guidPtr = &guid) { fixed (uint* pDataSizePtr = &pDataSize) { fixed (void* pDataPtr = &pData) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guidPtr, pDataSizePtr, pDataPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guidPtr, pDataSizePtr, pDataPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, uint*, void*, int>)LpVtbl[3])(@this, guidPtr, pDataSizePtr, pDataPtr); } #endif } } } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int SetPrivateData(Guid* guid, uint DataSize, void* pData) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, uint, void*, int>)LpVtbl[4])(@this, guid, DataSize, pData); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, uint, void*, int>)LpVtbl[4])(@this, guid, DataSize, pData); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, uint, void*, int>)LpVtbl[4])(@this, guid, DataSize, pData); } #endif return ret; } /// <summary>To be documented.</summary> public readonly unsafe int SetPrivateData<T0>(Guid* guid, uint DataSize, ref T0 pData) where T0 : unmanaged { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (void* pDataPtr = &pData) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, uint, void*, int>)LpVtbl[4])(@this, guid, DataSize, pDataPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, uint, void*, int>)LpVtbl[4])(@this, guid, DataSize, pDataPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, uint, void*, int>)LpVtbl[4])(@this, guid, DataSize, pDataPtr); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int SetPrivateData(ref Guid guid, uint DataSize, void* pData) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Guid* guidPtr = &guid) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, uint, void*, int>)LpVtbl[4])(@this, guidPtr, DataSize, pData); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, uint, void*, int>)LpVtbl[4])(@this, guidPtr, DataSize, pData); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, uint, void*, int>)LpVtbl[4])(@this, guidPtr, DataSize, pData); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly int SetPrivateData<T0>(ref Guid guid, uint DataSize, ref T0 pData) where T0 : unmanaged { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Guid* guidPtr = &guid) { fixed (void* pDataPtr = &pData) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, uint, void*, int>)LpVtbl[4])(@this, guidPtr, DataSize, pDataPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, uint, void*, int>)LpVtbl[4])(@this, guidPtr, DataSize, pDataPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, uint, void*, int>)LpVtbl[4])(@this, guidPtr, DataSize, pDataPtr); } #endif } } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int SetPrivateDataInterface(Guid* guid, [Flow(FlowDirection.In)] Silk.NET.Core.Native.IUnknown* pData) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, Silk.NET.Core.Native.IUnknown*, int>)LpVtbl[5])(@this, guid, pData); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, Silk.NET.Core.Native.IUnknown*, int>)LpVtbl[5])(@this, guid, pData); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, Silk.NET.Core.Native.IUnknown*, int>)LpVtbl[5])(@this, guid, pData); } #endif return ret; } /// <summary>To be documented.</summary> public readonly unsafe int SetPrivateDataInterface(Guid* guid, [Flow(FlowDirection.In)] in Silk.NET.Core.Native.IUnknown pData) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Silk.NET.Core.Native.IUnknown* pDataPtr = &pData) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, Silk.NET.Core.Native.IUnknown*, int>)LpVtbl[5])(@this, guid, pDataPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, Silk.NET.Core.Native.IUnknown*, int>)LpVtbl[5])(@this, guid, pDataPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, Silk.NET.Core.Native.IUnknown*, int>)LpVtbl[5])(@this, guid, pDataPtr); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int SetPrivateDataInterface(ref Guid guid, [Flow(FlowDirection.In)] Silk.NET.Core.Native.IUnknown* pData) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Guid* guidPtr = &guid) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, Silk.NET.Core.Native.IUnknown*, int>)LpVtbl[5])(@this, guidPtr, pData); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, Silk.NET.Core.Native.IUnknown*, int>)LpVtbl[5])(@this, guidPtr, pData); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, Silk.NET.Core.Native.IUnknown*, int>)LpVtbl[5])(@this, guidPtr, pData); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly int SetPrivateDataInterface(ref Guid guid, [Flow(FlowDirection.In)] in Silk.NET.Core.Native.IUnknown pData) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Guid* guidPtr = &guid) { fixed (Silk.NET.Core.Native.IUnknown* pDataPtr = &pData) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, Silk.NET.Core.Native.IUnknown*, int>)LpVtbl[5])(@this, guidPtr, pDataPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, Silk.NET.Core.Native.IUnknown*, int>)LpVtbl[5])(@this, guidPtr, pDataPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, Silk.NET.Core.Native.IUnknown*, int>)LpVtbl[5])(@this, guidPtr, pDataPtr); } #endif } } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int SetName(char* Name) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, char*, int>)LpVtbl[6])(@this, Name); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, char*, int>)LpVtbl[6])(@this, Name); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, char*, int>)LpVtbl[6])(@this, Name); } #endif return ret; } /// <summary>To be documented.</summary> public readonly int SetName(ref char Name) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (char* NamePtr = &Name) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, char*, int>)LpVtbl[6])(@this, NamePtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, char*, int>)LpVtbl[6])(@this, NamePtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, char*, int>)LpVtbl[6])(@this, NamePtr); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly int SetName([UnmanagedType(Silk.NET.Core.Native.UnmanagedType.LPWStr)] string Name) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; var NamePtr = (byte*) SilkMarshal.StringToPtr(Name, NativeStringEncoding.LPWStr); #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, byte*, int>)LpVtbl[6])(@this, NamePtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, byte*, int>)LpVtbl[6])(@this, NamePtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, byte*, int>)LpVtbl[6])(@this, NamePtr); } #endif SilkMarshal.Free((nint)NamePtr); return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetDevice(Guid* riid, void** ppvDevice) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[7])(@this, riid, ppvDevice); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[7])(@this, riid, ppvDevice); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[7])(@this, riid, ppvDevice); } #endif return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetDevice(Guid* riid, ref void* ppvDevice) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (void** ppvDevicePtr = &ppvDevice) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[7])(@this, riid, ppvDevicePtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[7])(@this, riid, ppvDevicePtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[7])(@this, riid, ppvDevicePtr); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetDevice(ref Guid riid, void** ppvDevice) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Guid* riidPtr = &riid) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[7])(@this, riidPtr, ppvDevice); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[7])(@this, riidPtr, ppvDevice); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[7])(@this, riidPtr, ppvDevice); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetDevice(ref Guid riid, ref void* ppvDevice) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Guid* riidPtr = &riid) { fixed (void** ppvDevicePtr = &ppvDevice) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[7])(@this, riidPtr, ppvDevicePtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[7])(@this, riidPtr, ppvDevicePtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[7])(@this, riidPtr, ppvDevicePtr); } #endif } } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int Map(uint Subresource, Range* pReadRange, void** ppData) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, uint, Range*, void**, int>)LpVtbl[8])(@this, Subresource, pReadRange, ppData); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, uint, Range*, void**, int>)LpVtbl[8])(@this, Subresource, pReadRange, ppData); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, uint, Range*, void**, int>)LpVtbl[8])(@this, Subresource, pReadRange, ppData); } #endif return ret; } /// <summary>To be documented.</summary> public readonly unsafe int Map(uint Subresource, Range* pReadRange, ref void* ppData) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (void** ppDataPtr = &ppData) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, uint, Range*, void**, int>)LpVtbl[8])(@this, Subresource, pReadRange, ppDataPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, uint, Range*, void**, int>)LpVtbl[8])(@this, Subresource, pReadRange, ppDataPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, uint, Range*, void**, int>)LpVtbl[8])(@this, Subresource, pReadRange, ppDataPtr); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int Map(uint Subresource, ref Range pReadRange, void** ppData) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Range* pReadRangePtr = &pReadRange) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, uint, Range*, void**, int>)LpVtbl[8])(@this, Subresource, pReadRangePtr, ppData); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, uint, Range*, void**, int>)LpVtbl[8])(@this, Subresource, pReadRangePtr, ppData); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, uint, Range*, void**, int>)LpVtbl[8])(@this, Subresource, pReadRangePtr, ppData); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int Map(uint Subresource, ref Range pReadRange, ref void* ppData) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Range* pReadRangePtr = &pReadRange) { fixed (void** ppDataPtr = &ppData) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, uint, Range*, void**, int>)LpVtbl[8])(@this, Subresource, pReadRangePtr, ppDataPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, uint, Range*, void**, int>)LpVtbl[8])(@this, Subresource, pReadRangePtr, ppDataPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, uint, Range*, void**, int>)LpVtbl[8])(@this, Subresource, pReadRangePtr, ppDataPtr); } #endif } } return ret; } /// <summary>To be documented.</summary> public readonly unsafe void Unmap(uint Subresource, Range* pWrittenRange) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); #if NET5_0_OR_GREATER ((delegate* unmanaged<ID3D12Resource2*, uint, Range*, void>)LpVtbl[9])(@this, Subresource, pWrittenRange); #else if (SilkMarshal.IsWinapiStdcall) { ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, uint, Range*, void>)LpVtbl[9])(@this, Subresource, pWrittenRange); } else { ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, uint, Range*, void>)LpVtbl[9])(@this, Subresource, pWrittenRange); } #endif } /// <summary>To be documented.</summary> public readonly void Unmap(uint Subresource, ref Range pWrittenRange) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); fixed (Range* pWrittenRangePtr = &pWrittenRange) { #if NET5_0_OR_GREATER ((delegate* unmanaged<ID3D12Resource2*, uint, Range*, void>)LpVtbl[9])(@this, Subresource, pWrittenRangePtr); #else if (SilkMarshal.IsWinapiStdcall) { ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, uint, Range*, void>)LpVtbl[9])(@this, Subresource, pWrittenRangePtr); } else { ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, uint, Range*, void>)LpVtbl[9])(@this, Subresource, pWrittenRangePtr); } #endif } } /// <summary>To be documented.</summary> public readonly ResourceDesc GetDesc() { ResourceDesc silkDotNetReturnFixupResult; var pSilkDotNetReturnFixupResult = &silkDotNetReturnFixupResult; var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); ResourceDesc* ret = default; #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, ResourceDesc*, ResourceDesc*>)LpVtbl[10])(@this, pSilkDotNetReturnFixupResult); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, ResourceDesc*, ResourceDesc*>)LpVtbl[10])(@this, pSilkDotNetReturnFixupResult); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, ResourceDesc*, ResourceDesc*>)LpVtbl[10])(@this, pSilkDotNetReturnFixupResult); } #endif return *ret; } /// <summary>To be documented.</summary> public readonly ulong GetGPUVirtualAddress() { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); ulong ret = default; ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, ulong>)LpVtbl[11])(@this); return ret; } /// <summary>To be documented.</summary> public readonly unsafe int WriteToSubresource(uint DstSubresource, Box* pDstBox, void* pSrcData, uint SrcRowPitch, uint SrcDepthPitch) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, uint, Box*, void*, uint, uint, int>)LpVtbl[12])(@this, DstSubresource, pDstBox, pSrcData, SrcRowPitch, SrcDepthPitch); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, uint, Box*, void*, uint, uint, int>)LpVtbl[12])(@this, DstSubresource, pDstBox, pSrcData, SrcRowPitch, SrcDepthPitch); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, uint, Box*, void*, uint, uint, int>)LpVtbl[12])(@this, DstSubresource, pDstBox, pSrcData, SrcRowPitch, SrcDepthPitch); } #endif return ret; } /// <summary>To be documented.</summary> public readonly unsafe int WriteToSubresource<T0>(uint DstSubresource, Box* pDstBox, ref T0 pSrcData, uint SrcRowPitch, uint SrcDepthPitch) where T0 : unmanaged { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (void* pSrcDataPtr = &pSrcData) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, uint, Box*, void*, uint, uint, int>)LpVtbl[12])(@this, DstSubresource, pDstBox, pSrcDataPtr, SrcRowPitch, SrcDepthPitch); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, uint, Box*, void*, uint, uint, int>)LpVtbl[12])(@this, DstSubresource, pDstBox, pSrcDataPtr, SrcRowPitch, SrcDepthPitch); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, uint, Box*, void*, uint, uint, int>)LpVtbl[12])(@this, DstSubresource, pDstBox, pSrcDataPtr, SrcRowPitch, SrcDepthPitch); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int WriteToSubresource(uint DstSubresource, ref Box pDstBox, void* pSrcData, uint SrcRowPitch, uint SrcDepthPitch) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Box* pDstBoxPtr = &pDstBox) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, uint, Box*, void*, uint, uint, int>)LpVtbl[12])(@this, DstSubresource, pDstBoxPtr, pSrcData, SrcRowPitch, SrcDepthPitch); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, uint, Box*, void*, uint, uint, int>)LpVtbl[12])(@this, DstSubresource, pDstBoxPtr, pSrcData, SrcRowPitch, SrcDepthPitch); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, uint, Box*, void*, uint, uint, int>)LpVtbl[12])(@this, DstSubresource, pDstBoxPtr, pSrcData, SrcRowPitch, SrcDepthPitch); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly int WriteToSubresource<T0>(uint DstSubresource, ref Box pDstBox, ref T0 pSrcData, uint SrcRowPitch, uint SrcDepthPitch) where T0 : unmanaged { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Box* pDstBoxPtr = &pDstBox) { fixed (void* pSrcDataPtr = &pSrcData) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, uint, Box*, void*, uint, uint, int>)LpVtbl[12])(@this, DstSubresource, pDstBoxPtr, pSrcDataPtr, SrcRowPitch, SrcDepthPitch); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, uint, Box*, void*, uint, uint, int>)LpVtbl[12])(@this, DstSubresource, pDstBoxPtr, pSrcDataPtr, SrcRowPitch, SrcDepthPitch); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, uint, Box*, void*, uint, uint, int>)LpVtbl[12])(@this, DstSubresource, pDstBoxPtr, pSrcDataPtr, SrcRowPitch, SrcDepthPitch); } #endif } } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int ReadFromSubresource(void* pDstData, uint DstRowPitch, uint DstDepthPitch, uint SrcSubresource, Box* pSrcBox) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, void*, uint, uint, uint, Box*, int>)LpVtbl[13])(@this, pDstData, DstRowPitch, DstDepthPitch, SrcSubresource, pSrcBox); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, void*, uint, uint, uint, Box*, int>)LpVtbl[13])(@this, pDstData, DstRowPitch, DstDepthPitch, SrcSubresource, pSrcBox); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, void*, uint, uint, uint, Box*, int>)LpVtbl[13])(@this, pDstData, DstRowPitch, DstDepthPitch, SrcSubresource, pSrcBox); } #endif return ret; } /// <summary>To be documented.</summary> public readonly unsafe int ReadFromSubresource(void* pDstData, uint DstRowPitch, uint DstDepthPitch, uint SrcSubresource, ref Box pSrcBox) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Box* pSrcBoxPtr = &pSrcBox) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, void*, uint, uint, uint, Box*, int>)LpVtbl[13])(@this, pDstData, DstRowPitch, DstDepthPitch, SrcSubresource, pSrcBoxPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, void*, uint, uint, uint, Box*, int>)LpVtbl[13])(@this, pDstData, DstRowPitch, DstDepthPitch, SrcSubresource, pSrcBoxPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, void*, uint, uint, uint, Box*, int>)LpVtbl[13])(@this, pDstData, DstRowPitch, DstDepthPitch, SrcSubresource, pSrcBoxPtr); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int ReadFromSubresource<T0>(ref T0 pDstData, uint DstRowPitch, uint DstDepthPitch, uint SrcSubresource, Box* pSrcBox) where T0 : unmanaged { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (void* pDstDataPtr = &pDstData) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, void*, uint, uint, uint, Box*, int>)LpVtbl[13])(@this, pDstDataPtr, DstRowPitch, DstDepthPitch, SrcSubresource, pSrcBox); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, void*, uint, uint, uint, Box*, int>)LpVtbl[13])(@this, pDstDataPtr, DstRowPitch, DstDepthPitch, SrcSubresource, pSrcBox); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, void*, uint, uint, uint, Box*, int>)LpVtbl[13])(@this, pDstDataPtr, DstRowPitch, DstDepthPitch, SrcSubresource, pSrcBox); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly int ReadFromSubresource<T0>(ref T0 pDstData, uint DstRowPitch, uint DstDepthPitch, uint SrcSubresource, ref Box pSrcBox) where T0 : unmanaged { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (void* pDstDataPtr = &pDstData) { fixed (Box* pSrcBoxPtr = &pSrcBox) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, void*, uint, uint, uint, Box*, int>)LpVtbl[13])(@this, pDstDataPtr, DstRowPitch, DstDepthPitch, SrcSubresource, pSrcBoxPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, void*, uint, uint, uint, Box*, int>)LpVtbl[13])(@this, pDstDataPtr, DstRowPitch, DstDepthPitch, SrcSubresource, pSrcBoxPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, void*, uint, uint, uint, Box*, int>)LpVtbl[13])(@this, pDstDataPtr, DstRowPitch, DstDepthPitch, SrcSubresource, pSrcBoxPtr); } #endif } } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetHeapProperties(HeapProperties* pHeapProperties, HeapFlags* pHeapFlags) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, HeapProperties*, HeapFlags*, int>)LpVtbl[14])(@this, pHeapProperties, pHeapFlags); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, HeapProperties*, HeapFlags*, int>)LpVtbl[14])(@this, pHeapProperties, pHeapFlags); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, HeapProperties*, HeapFlags*, int>)LpVtbl[14])(@this, pHeapProperties, pHeapFlags); } #endif return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetHeapProperties(HeapProperties* pHeapProperties, ref HeapFlags pHeapFlags) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (HeapFlags* pHeapFlagsPtr = &pHeapFlags) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, HeapProperties*, HeapFlags*, int>)LpVtbl[14])(@this, pHeapProperties, pHeapFlagsPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, HeapProperties*, HeapFlags*, int>)LpVtbl[14])(@this, pHeapProperties, pHeapFlagsPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, HeapProperties*, HeapFlags*, int>)LpVtbl[14])(@this, pHeapProperties, pHeapFlagsPtr); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetHeapProperties(ref HeapProperties pHeapProperties, HeapFlags* pHeapFlags) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (HeapProperties* pHeapPropertiesPtr = &pHeapProperties) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, HeapProperties*, HeapFlags*, int>)LpVtbl[14])(@this, pHeapPropertiesPtr, pHeapFlags); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, HeapProperties*, HeapFlags*, int>)LpVtbl[14])(@this, pHeapPropertiesPtr, pHeapFlags); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, HeapProperties*, HeapFlags*, int>)LpVtbl[14])(@this, pHeapPropertiesPtr, pHeapFlags); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly int GetHeapProperties(ref HeapProperties pHeapProperties, ref HeapFlags pHeapFlags) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (HeapProperties* pHeapPropertiesPtr = &pHeapProperties) { fixed (HeapFlags* pHeapFlagsPtr = &pHeapFlags) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, HeapProperties*, HeapFlags*, int>)LpVtbl[14])(@this, pHeapPropertiesPtr, pHeapFlagsPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, HeapProperties*, HeapFlags*, int>)LpVtbl[14])(@this, pHeapPropertiesPtr, pHeapFlagsPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, HeapProperties*, HeapFlags*, int>)LpVtbl[14])(@this, pHeapPropertiesPtr, pHeapFlagsPtr); } #endif } } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetProtectedResourceSession(Guid* riid, void** ppProtectedSession) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[15])(@this, riid, ppProtectedSession); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[15])(@this, riid, ppProtectedSession); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[15])(@this, riid, ppProtectedSession); } #endif return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetProtectedResourceSession(Guid* riid, ref void* ppProtectedSession) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (void** ppProtectedSessionPtr = &ppProtectedSession) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[15])(@this, riid, ppProtectedSessionPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[15])(@this, riid, ppProtectedSessionPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[15])(@this, riid, ppProtectedSessionPtr); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetProtectedResourceSession(ref Guid riid, void** ppProtectedSession) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Guid* riidPtr = &riid) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[15])(@this, riidPtr, ppProtectedSession); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[15])(@this, riidPtr, ppProtectedSession); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[15])(@this, riidPtr, ppProtectedSession); } #endif } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int GetProtectedResourceSession(ref Guid riid, ref void* ppProtectedSession) { var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Guid* riidPtr = &riid) { fixed (void** ppProtectedSessionPtr = &ppProtectedSession) { #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[15])(@this, riidPtr, ppProtectedSessionPtr); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[15])(@this, riidPtr, ppProtectedSessionPtr); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, Guid*, void**, int>)LpVtbl[15])(@this, riidPtr, ppProtectedSessionPtr); } #endif } } return ret; } /// <summary>To be documented.</summary> public readonly ResourceDesc1 GetDesc1() { ResourceDesc1 silkDotNetReturnFixupResult; var pSilkDotNetReturnFixupResult = &silkDotNetReturnFixupResult; var @this = (ID3D12Resource2*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); ResourceDesc1* ret = default; #if NET5_0_OR_GREATER ret = ((delegate* unmanaged<ID3D12Resource2*, ResourceDesc1*, ResourceDesc1*>)LpVtbl[16])(@this, pSilkDotNetReturnFixupResult); #else if (SilkMarshal.IsWinapiStdcall) { ret = ((delegate* unmanaged[Stdcall]<ID3D12Resource2*, ResourceDesc1*, ResourceDesc1*>)LpVtbl[16])(@this, pSilkDotNetReturnFixupResult); } else { ret = ((delegate* unmanaged[Cdecl]<ID3D12Resource2*, ResourceDesc1*, ResourceDesc1*>)LpVtbl[16])(@this, pSilkDotNetReturnFixupResult); } #endif return *ret; } } }
45.375397
203
0.534011
[ "MIT" ]
Ar37-rs/Silk.NET
src/Microsoft/Silk.NET.Direct3D12/Structs/ID3D12Resource2.gen.cs
57,173
C#
using System; using System.Text; using System.Collections; using System.Collections.Generic; namespace Com.Aspose.Slides.Model { public class TextItems { public List<TextItem> Items { get; set; } public ResourceUri SelfUri { get; set; } public List<ResourceUri> AlternateLinks { get; set; } public List<ResourceUri> Links { get; set; } public override string ToString() { var sb = new StringBuilder(); sb.Append("class TextItems {\n"); sb.Append(" Items: ").Append(Items).Append("\n"); sb.Append(" SelfUri: ").Append(SelfUri).Append("\n"); sb.Append(" AlternateLinks: ").Append(AlternateLinks).Append("\n"); sb.Append(" Links: ").Append(Links).Append("\n"); sb.Append("}\n"); return sb.ToString(); } } }
28.285714
74
0.632576
[ "MIT" ]
mudassirfayyaz/Aspose.Slides-for-Cloud
SDKs/Aspose.Slides-Cloud-SDK-for-.NET/src/Com/Aspose/Slides/Model/TextItems.cs
792
C#
using System.Collections.Generic; namespace ParserGS1 { /// <summary> /// Фабрика результатов сканирования, подбирает объект и инициализирует его по полученному словарю тегов /// </summary> internal class ResultFactory { /// <summary> /// Фабрика результатов сканирования, подбирает объект и инициализирует его по полученному словарю тегов /// </summary> /// <param name="StrategyResults">Массив стратегий для объектов-результатов</param> /// <param name="defaultParseType">Объект-результат используемый если другие варианты не подходят</param> public ResultFactory(IStrategyResults[] StrategyResults, DefaultResult defaultParseType) { IStrategyResults = StrategyResults; DefaultParseType = defaultParseType; CurrentParseType = null; } private IStrategyResults CurrentParseType; private DefaultResult DefaultParseType; private IStrategyResults[] IStrategyResults; public bool Create(string fullStrings, string[] codeStrings, Dictionary<string, RuleKeyAI> RuleKeys) { CurrentParseType = null; foreach (var ParseType in IStrategyResults) { if (ParseType.IsTypeResult(RuleKeys)) { CurrentParseType = ParseType; CurrentParseType.CompletingFields(fullStrings, codeStrings, RuleKeys); } } if (CurrentParseType == null) { string text = string.IsNullOrWhiteSpace(fullStrings)?"": fullStrings + "\n"; foreach (var aHandler in RuleKeys) { text = text + aHandler.Value.ToString() + "\n"; } DefaultParseType.Text = text; CurrentParseType = DefaultParseType; } else { CurrentParseType.ActionAfterCompletingFields(); } return true; } /// <summary> /// Полученный объект-результат после обработки /// </summary> public IStrategyResults Result => CurrentParseType; } }
35.754098
113
0.600183
[ "MIT" ]
ArtemBuskunov/ParserGS1-128
ParserGS1_128/ResultFactory.cs
2,490
C#
using Arc4u.Dependency; using Arc4u.Diagnostics; using Arc4u.OAuth2.Security.Principal; using Arc4u.OAuth2.Token; using Arc4u.ServiceModel; using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; namespace Arc4u.OAuth2.TokenProvider { [System.Composition.Export(CredentialTokenCacheTokenProvider.ProviderName, typeof(ICredentialTokenProvider))] public class CredentialTokenCacheTokenProvider : ICredentialTokenProvider { public const string ProviderName = "Credential"; private readonly ITokenCache TokenCache; private readonly IContainerResolve Container; private readonly ILogger Logger; [System.Composition.ImportingConstructor] public CredentialTokenCacheTokenProvider(ITokenCache tokenCache, ILogger logger, IContainerResolve container) { TokenCache = tokenCache; Logger = logger; Container = container; } public async Task<TokenInfo> GetTokenAsync(IKeyValueSettings settings, CredentialsResult credential) { var messages = GetContext(settings, out string clientId, out string authority, out string authenticationType, out string serviceApplicationId); if (String.IsNullOrWhiteSpace(credential.Upn)) messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Warning, "No Username is provided.")); if (String.IsNullOrWhiteSpace(credential.Password)) messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Warning, "No password is provided.")); messages.LogAndThrowIfNecessary(this); messages.Clear(); if (null != TokenCache) { // Get a HashCode from the password so a second call with the same upn but with a wrong password will not be impersonated due to // the lack of password check. var cacheKey = BuildKey(credential, authority, serviceApplicationId); Logger.Technical().From<CredentialTokenCacheTokenProvider>().System($"Check if the cache contains a token for {cacheKey}.").Log(); var tokenInfo = TokenCache.Get<TokenInfo>(cacheKey); var hasChanged = false; if (null != tokenInfo) { Logger.Technical().From<CredentialTokenCacheTokenProvider>().System($"Token loaded from the cache for {cacheKey}.").Log(); if (tokenInfo.ExpiresOnUtc < DateTime.UtcNow.AddMinutes(1)) { Logger.Technical().From<CredentialTokenCacheTokenProvider>().System($"Token is expired for {cacheKey}.").Log(); // We need to refresh the token. tokenInfo = await CreateBasicTokenInfoAsync(settings, credential); hasChanged = true; } } else { Logger.Technical().From<CredentialTokenCacheTokenProvider>().System($"Contact the STS to create an access token for {cacheKey}.").Log(); tokenInfo = await CreateBasicTokenInfoAsync(settings, credential); hasChanged = true; } if (hasChanged) { try { Logger.Technical().From<CredentialTokenCacheTokenProvider>().System($"Save the token in the cache for {cacheKey}, will expire at {tokenInfo.ExpiresOnUtc} Utc.").Log(); TokenCache.Put(cacheKey, tokenInfo); } catch (Exception ex) { Logger.Technical().From<CredentialTokenCacheTokenProvider>().Exception(ex).Log(); } } return tokenInfo; } // no cache, do a direct call on every calls. Logger.Technical().From<CredentialTokenCacheTokenProvider>().System($"No cache is defined. STS is called for every call.").Log(); return await CreateBasicTokenInfoAsync(settings, credential); } protected async Task<TokenInfo> CreateBasicTokenInfoAsync(IKeyValueSettings settings, CredentialsResult credential) { var basicTokenProvider = Container.Resolve<ICredentialTokenProvider>(CredentialTokenProvider.ProviderName); return await basicTokenProvider.GetTokenAsync(settings, credential); } private static string BuildKey(CredentialsResult credential, string authority, string serviceApplicationId) { return authority + "_" + serviceApplicationId + "_Password_" + credential.Upn + "_" + credential.Password.GetHashCode().ToString(); } private Messages GetContext(IKeyValueSettings settings, out string clientId, out string authority, out string authenticationType, out string serviceApplicationId) { // Check the information. var messages = new Messages(); if (null == settings) { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Error, "Settings parameter cannot be null.")); clientId = null; authority = null; authenticationType = null; serviceApplicationId = null; return messages; } // Valdate arguments. if (!settings.Values.ContainsKey(TokenKeys.AuthorityKey)) messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Error, "Authority is missing. Cannot process the request.")); if (!settings.Values.ContainsKey(TokenKeys.ClientIdKey)) messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Error, "ClientId is missing. Cannot process the request.")); if (!settings.Values.ContainsKey(TokenKeys.ServiceApplicationIdKey)) messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Error, "ApplicationId is missing. Cannot process the request.")); if (!settings.Values.ContainsKey(TokenKeys.AuthenticationTypeKey)) messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Error, "Authentication type key is missing. Cannot process the request.")); Logger.Technical().From<CredentialTokenCacheTokenProvider>().System($"Creating an authentication context for the request.").Log(); clientId = settings.Values[TokenKeys.ClientIdKey]; serviceApplicationId = settings.Values[TokenKeys.ServiceApplicationIdKey]; authority = settings.Values[TokenKeys.AuthorityKey]; authenticationType = settings.Values[TokenKeys.AuthenticationTypeKey]; Logger.Technical().From<CredentialTokenCacheTokenProvider>().System($"ClientId = {clientId}.").Log(); Logger.Technical().From<CredentialTokenCacheTokenProvider>().System($"ServiceApplicationId = {serviceApplicationId}.").Log(); Logger.Technical().From<CredentialTokenCacheTokenProvider>().System($"Authority = {authority}.").Log(); Logger.Technical().From<CredentialTokenCacheTokenProvider>().System($"Authentication type = {authenticationType}.").Log(); return messages; } } }
49.582278
191
0.623053
[ "Apache-2.0" ]
GFlisch/Arc4u
src/Arc4u.Standard.OAuth2/TokenProvider/CredentialTokenCacheTokenProvider.cs
7,836
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; namespace BrightcoveOS.NET_MAPI_Wrapper.Tests.IntegrationTests.VideoWrite { [TestFixture] public class RemoveLogoOverlayTests : VideoWriteTestBase { [Test] public void RemoveLogoOverlay_Test_Basic() { _api.RemoveLogoOverlay(1942305739001); // TODO: not sure how to verify this worked other than the lack of error } } }
22.333333
76
0.746269
[ "MIT" ]
BrightcoveOS/.NET-MAPI-Wrapper
tests/BrightcoveOS .NET-MAPI-Wrapper.Tests/IntegrationTests/VideoWrite/RemoveLogoOverlayTests.cs
471
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("AWSSDK.ElasticLoadBalancing")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Elastic Load Balancing. Elastic Load Balancing automatically distributes incoming application traffic across multiple compute instances in the cloud.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Elastic Load Balancing. Elastic Load Balancing automatically distributes incoming application traffic across multiple compute instances in the cloud.")] #elif PCL [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - Elastic Load Balancing. Elastic Load Balancing automatically distributes incoming application traffic across multiple compute instances in the cloud.")] #elif UNITY [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - Elastic Load Balancing. Elastic Load Balancing automatically distributes incoming application traffic across multiple compute instances in the cloud.")] #elif CORECLR [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (CoreCLR)- Elastic Load Balancing. Elastic Load Balancing automatically distributes incoming application traffic across multiple compute instances in the cloud.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.3.3.8")] #if WINDOWS_PHONE || UNITY [assembly: System.CLSCompliant(false)] # else [assembly: System.CLSCompliant(true)] #endif #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
49.684211
232
0.783192
[ "Apache-2.0" ]
InsiteVR/aws-sdk-net
sdk/src/Services/ElasticLoadBalancing/Properties/AssemblyInfo.cs
2,832
C#
using System; using System.Linq; using HotChocolate.Language; using HotChocolate.Types.Descriptors; using Snapshooter.Xunit; using Xunit; namespace HotChocolate.Types { public class InterfaceTypeTests : TypeTestBase { [Fact] public void InterfaceType_DynamicName() { // act var schema = Schema.Create(c => { c.RegisterType(new InterfaceType(d => d .Name(dep => dep.Name + "Foo") .DependsOn<StringType>() .Field("bar") .Type<StringType>())); c.Options.StrictValidation = false; }); // assert InterfaceType type = schema.GetType<InterfaceType>("StringFoo"); Assert.NotNull(type); } [Fact] public void InterfaceType_DynamicName_NonGeneric() { // act var schema = Schema.Create(c => { c.RegisterType(new InterfaceType(d => d .Name(dep => dep.Name + "Foo") .DependsOn(typeof(StringType)) .Field("bar") .Type<StringType>())); c.Options.StrictValidation = false; }); // assert InterfaceType type = schema.GetType<InterfaceType>("StringFoo"); Assert.NotNull(type); } [Fact] public void GenericInterfaceType_DynamicName() { // act var schema = Schema.Create(c => { c.RegisterType(new InterfaceType<IFoo>(d => d .Name(dep => dep.Name + "Foo") .DependsOn<StringType>())); c.Options.StrictValidation = false; }); // assert InterfaceType type = schema.GetType<InterfaceType>("StringFoo"); Assert.NotNull(type); } [Fact] public void GenericInterfaceType_DynamicName_NonGeneric() { // act var schema = Schema.Create(c => { c.RegisterType(new InterfaceType<IFoo>(d => d .Name(dep => dep.Name + "Foo") .DependsOn(typeof(StringType)))); c.Options.StrictValidation = false; }); // assert InterfaceType type = schema.GetType<InterfaceType>("StringFoo"); Assert.NotNull(type); } [Fact] public void InferFieldsFromClrInterface() { // arrange // act InterfaceType<IFoo> fooType = CreateType( new InterfaceType<IFoo>(), b => b.ModifyOptions(o => o.StrictValidation = false)); // assert Assert.Collection( fooType.Fields.Where(t => !t.IsIntrospectionField).OrderBy(t => t.Name), t => { Assert.Equal("bar", t.Name); Assert.IsType<BooleanType>( Assert.IsType<NonNullType>(t.Type).Type); }, t => { Assert.Equal("baz", t.Name); Assert.IsType<StringType>(t.Type); }, t => { Assert.Equal("qux", t.Name); Assert.IsType<IntType>( Assert.IsType<NonNullType>(t.Type).Type); Assert.Collection(t.Arguments, a => Assert.Equal("a", a.Name)); }); } [Fact] public void InferSchemaInterfaceTypeFromClrInterface() { // arrange && act var schema = Schema.Create(c => { c.RegisterType<IFoo>(); c.RegisterQueryType<FooImpl>(); }); // assert ObjectType type = schema.GetType<ObjectType>("FooImpl"); Assert.Collection(type.Implements, t => Assert.Equal("IFoo", t.Name)); } [Fact] public void IgnoreFieldsFromClrInterface() { // arrange // act InterfaceType<IFoo> fooType = CreateType( new InterfaceType<IFoo>(t => t.Ignore(p => p.Bar)), b => b.ModifyOptions(o => o.StrictValidation = false)); // assert Assert.Collection( fooType.Fields.Where(t => !t.IsIntrospectionField), t => { Assert.Equal("baz", t.Name); Assert.IsType<StringType>(t.Type); }, t => { Assert.Equal("qux", t.Name); Assert.IsType<IntType>( Assert.IsType<NonNullType>(t.Type).Type); Assert.Collection(t.Arguments, a => Assert.Equal("a", a.Name)); }); } [Fact] public void UnignoreFieldsFromClrInterface() { // arrange // act InterfaceType<IFoo> fooType = CreateType( new InterfaceType<IFoo>(t => { t.Ignore(p => p.Bar); t.Field(p => p.Bar).Ignore(false); }), b => b.ModifyOptions(o => o.StrictValidation = false)); // assert Assert.Collection( fooType.Fields.Where(t => !t.IsIntrospectionField), t => { Assert.Equal("bar", t.Name); Assert.IsType<BooleanType>( Assert.IsType<NonNullType>(t.Type).Type); }, t => { Assert.Equal("baz", t.Name); Assert.IsType<StringType>(t.Type); }, t => { Assert.Equal("qux", t.Name); Assert.IsType<IntType>( Assert.IsType<NonNullType>(t.Type).Type); Assert.Collection(t.Arguments, a => Assert.Equal("a", a.Name)); }); } [Fact] public void ExplicitInterfaceFieldDeclaration() { // arrange // act InterfaceType<IFoo> fooType = CreateType( new InterfaceType<IFoo>(t => t .BindFields(BindingBehavior.Explicit) .Field(p => p.Bar)), b => b.ModifyOptions(o => o.StrictValidation = false)); // assert Assert.Collection( fooType.Fields.Where(t => !t.IsIntrospectionField), t => { Assert.Equal("bar", t.Name); Assert.IsType<BooleanType>( Assert.IsType<NonNullType>(t.Type).Type); }); } [Fact] public void GenericInterfaceType_AddDirectives_NameArgs() { // arrange // act InterfaceType<IFoo> fooType = CreateType( new InterfaceType<IFoo>(d => d .Directive("foo") .Field(f => f.Bar) .Directive("foo")), b => b.AddDirectiveType<FooDirectiveType>() .ModifyOptions(o => o.StrictValidation = false)); // assert Assert.NotEmpty(fooType.Directives["foo"]); Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); } [Fact] public void GenericInterfaceType_AddDirectives_NameArgs2() { // arrange // act InterfaceType<IFoo> fooType = CreateType( new InterfaceType<IFoo>(d => d .Directive(new NameString("foo")) .Field(f => f.Bar) .Directive(new NameString("foo"))), b => b.AddDirectiveType<FooDirectiveType>() .ModifyOptions(o => o.StrictValidation = false)); // assert Assert.NotEmpty(fooType.Directives["foo"]); Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); } [Fact] public void GenericInterfaceType_AddDirectives_DirectiveNode() { // arrange // act InterfaceType<IFoo> fooType = CreateType( new InterfaceType<IFoo>(d => d .Directive(new DirectiveNode("foo")) .Field(f => f.Bar) .Directive(new DirectiveNode("foo"))), b => b.AddDirectiveType<FooDirectiveType>() .ModifyOptions(o => o.StrictValidation = false)); // assert Assert.NotEmpty(fooType.Directives["foo"]); Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); } [Fact] public void GenericInterfaceType_AddDirectives_DirectiveClassInstance() { // arrange // act InterfaceType<IFoo> fooType = CreateType( new InterfaceType<IFoo>(d => d .Directive(new FooDirective()) .Field(f => f.Bar) .Directive(new FooDirective())), b => b.AddDirectiveType<FooDirectiveType>() .ModifyOptions(o => o.StrictValidation = false)); // assert Assert.NotEmpty(fooType.Directives["foo"]); Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); } [Fact] public void GenericInterfaceType_AddDirectives_DirectiveType() { // arrange // act InterfaceType<IFoo> fooType = CreateType(new InterfaceType<IFoo>(d => d .Directive<FooDirective>() .Field(f => f.Bar) .Directive<FooDirective>()), b => b.AddDirectiveType<FooDirectiveType>() .ModifyOptions(o => o.StrictValidation = false)); // assert Assert.NotEmpty(fooType.Directives["foo"]); Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); } [Fact] public void InterfaceType_AddDirectives_NameArgs() { // arrange // act InterfaceType fooType = CreateType(new InterfaceType(d => d .Name("FooInt") .Directive("foo") .Field("id") .Type<StringType>() .Directive("foo")), b => b.AddDirectiveType<FooDirectiveType>() .ModifyOptions(o => o.StrictValidation = false)); // assert Assert.NotEmpty(fooType.Directives["foo"]); Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); } [Fact] public void InterfaceType_AddDirectives_NameArgs2() { // arrange // act InterfaceType fooType = CreateType(new InterfaceType(d => d .Name("FooInt") .Directive(new NameString("foo")) .Field("bar") .Type<StringType>() .Directive(new NameString("foo"))), b => b.AddDirectiveType<FooDirectiveType>() .ModifyOptions(o => o.StrictValidation = false)); // assert Assert.NotEmpty(fooType.Directives["foo"]); Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); } [Fact] public void InterfaceType_AddDirectives_DirectiveNode() { // arrange // act InterfaceType fooType = CreateType(new InterfaceType(d => d .Name("FooInt") .Directive(new DirectiveNode("foo")) .Field("id") .Type<StringType>() .Directive(new DirectiveNode("foo"))), b => b.AddDirectiveType<FooDirectiveType>() .ModifyOptions(o => o.StrictValidation = false)); // assert Assert.NotEmpty(fooType.Directives["foo"]); Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); } [Fact] public void InterfaceType_AddDirectives_DirectiveClassInstance() { // arrange // act InterfaceType fooType = CreateType(new InterfaceType(d => d .Name("FooInt") .Directive(new FooDirective()) .Field("id") .Type<StringType>() .Directive(new FooDirective())), b => b.AddDirectiveType<FooDirectiveType>() .ModifyOptions(o => o.StrictValidation = false)); // assert Assert.NotEmpty(fooType.Directives["foo"]); Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); } [Fact] public void InterfaceType_AddDirectives_DirectiveType() { // arrange // act InterfaceType fooType = CreateType(new InterfaceType(d => d .Name("FooInt") .Directive<FooDirective>() .Field("id") .Type<StringType>() .Directive<FooDirective>()), b => b.AddDirectiveType<FooDirectiveType>() .ModifyOptions(o => o.StrictValidation = false)); // assert Assert.NotEmpty(fooType.Directives["foo"]); Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); } [Fact] public void DoNotAllow_InputTypes_OnFields() { // arrange // act Action a = () => SchemaBuilder.New() .AddType(new InterfaceType(t => t .Name("Foo") .Field("bar") .Type<NonNullType<InputObjectType<object>>>())) .Create(); // assert Assert.Throws<SchemaException>(a) .Errors.First().Message.MatchSnapshot(); } [Fact] public void DoNotAllow_DynamicInputTypes_OnFields() { // arrange // act Action a = () => SchemaBuilder.New() .AddType(new InterfaceType(t => t .Name("Foo") .Field("bar") .Type(new NonNullType(new InputObjectType<object>())))) .Create(); // assert Assert.Throws<SchemaException>(a) .Errors.First().Message.MatchSnapshot(); } [Fact] public void Ignore_DescriptorIsNull_ArgumentNullException() { // arrange // act Action action = () => InterfaceTypeDescriptorExtensions .Ignore<IFoo>(null, t => t.Bar); // assert Assert.Throws<ArgumentNullException>(action); } [Fact] public void Ignore_ExpressionIsNull_ArgumentNullException() { // arrange InterfaceTypeDescriptor<IFoo> descriptor = InterfaceTypeDescriptor.New<IFoo>(DescriptorContext.Create()); // act Action action = () => InterfaceTypeDescriptorExtensions .Ignore(descriptor, null); // assert Assert.Throws<ArgumentNullException>(action); } [Fact] public void Ignore_Bar_Property() { // arrange // act ISchema schema = SchemaBuilder.New() .AddQueryType(c => c .Name("Query") .Field("foo") .Type<StringType>() .Resolver("bar")) .AddType(new InterfaceType<IFoo>(d => d .Ignore(t => t.Bar))) .ModifyOptions(o => o.StrictValidation = false) .Create(); // assert schema.ToString().MatchSnapshot(); } [Fact] public void Deprecate_Obsolete_Fields() { // arrange // act ISchema schema = SchemaBuilder.New() .AddQueryType(c => c .Name("Query") .Field("foo") .Type<StringType>() .Resolver("bar")) .AddType(new InterfaceType<FooObsolete>()) .ModifyOptions(o => o.StrictValidation = false) .Create(); // assert schema.ToString().MatchSnapshot(); } [Fact] public void Deprecate_Fields_With_Deprecated_Attribute() { ISchema schema = SchemaBuilder.New() .AddQueryType(c => c.Name("Query") .Field("foo") .Type<StringType>() .Resolver("bar")) .AddType(new InterfaceType<FooDeprecated>()) .ModifyOptions(o => o.StrictValidation = false) .Create(); schema.ToString().MatchSnapshot(); } public interface IFoo { bool Bar { get; } string Baz(); int Qux(string a); } public class FooImpl : IFoo { public bool Bar => throw new System.NotImplementedException(); public string Baz() { throw new System.NotImplementedException(); } public int Qux(string a) { throw new System.NotImplementedException(); } } public class FooDirectiveType : DirectiveType<FooDirective> { protected override void Configure( IDirectiveTypeDescriptor<FooDirective> descriptor) { descriptor.Name("foo"); descriptor.Location(DirectiveLocation.Interface) .Location(DirectiveLocation.FieldDefinition); } } public class FooDirective { } public class FooObsolete { [Obsolete("Baz")] public string Bar() => "foo"; } public class FooDeprecated { [GraphQLDeprecated("Use Bar2.")] public string Bar() => "foo"; public string Bar2() => "Foo 2: Electric foo-galoo"; } } }
32.533795
88
0.466173
[ "MIT" ]
Asshiah/hotchocolate
src/HotChocolate/Core/test/Types.Tests/Types/InterfaceTypeTests.cs
18,772
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; using System.IO; namespace GSStorm.RPG.Engine { /// <summary> /// Data manager in charged of game save and load. /// </summary> public class DataManager: Singleton<DataManager>, IManager { public DataManager() { } public ManagerStatus Status { get; private set; } private string filename; public IEnumerator StartLaunch() { Debug.Log("Data manager starting..."); filename = Path.Combine(Application.persistentDataPath, "game.dat"); Debug.Log(filename); // any long-running startup tasks go here, and set status to 'Initializing' until those tasks are complete Status = ManagerStatus.StarLaunching; LoadGameState(); Status = ManagerStatus.Started; yield return null; } public void SaveGameState() { // TODO: this may not work, need code refine. Dictionary<string, object> gamestate = new Dictionary<string, object>(); gamestate.Add("Demo", "Demo"); FileStream stream = File.Create(filename); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, gamestate); stream.Close(); } public void LoadGameState() { if (!File.Exists(filename)) { Debug.Log("No saved game"); return; } Dictionary<string, object> gamestate; BinaryFormatter formatter = new BinaryFormatter(); FileStream stream = File.Open(filename, FileMode.Open); gamestate = formatter.Deserialize(stream) as Dictionary<string, object>; stream.Close(); } public IEnumerator PreLaunch() { yield return null; } public IEnumerator PostLaunch() { yield return null; } } }
29.434783
118
0.597735
[ "MIT" ]
GraySchofield/rgpModelEngine
RPG Model Engine - Current/Assets/GSSTORM/Scripts/Managers/DataManager.cs
2,033
C#
/** * Copyright 2015 Canada Health Infoway, Inc. * * 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. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $ * Revision: $LastChangedRevision: 2623 $ */ /* This class was auto-generated by the message builder generator tools. */ using Ca.Infoway.Messagebuilder; namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03.Domainvalue { public interface ResponseLevel : Code { } }
37.428571
83
0.709924
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-ab-r02_04_03/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03/Domainvalue/ResponseLevel.cs
1,048
C#
using System; using System.IO; using System.Linq; using System.Threading; using Ultraviolet.Content; using Ultraviolet.Core; using Ultraviolet.Core.Messages; using Ultraviolet.Platform; namespace Ultraviolet { /// <summary> /// Represents an application running on top of the Ultraviolet Framework. /// </summary> public abstract partial class UltravioletApplication : IMessageSubscriber<UltravioletMessageID>, IUltravioletComponent, IUltravioletHost, IDisposable { /// <summary> /// Initializes the <see cref="UltravioletApplication"/> type. /// </summary> static UltravioletApplication() { var baseDir = AppContext.BaseDirectory; if (baseDir != null) Directory.SetCurrentDirectory(baseDir); } /// <summary> /// Initializes a new instance of the <see cref="UltravioletApplication"/> class. /// </summary> /// <param name="developerName">The name of the company or developer that built this application.</param> /// <param name="applicationName">The name of the application </param> protected UltravioletApplication(String developerName, String applicationName) { Contract.RequireNotEmpty(developerName, nameof(developerName)); Contract.RequireNotEmpty(applicationName, nameof(applicationName)); PreserveApplicationSettings = true; this.DeveloperName = developerName; this.ApplicationName = applicationName; InitializeApplication(); } /// <inheritdoc/> void IMessageSubscriber<UltravioletMessageID>.ReceiveMessage(UltravioletMessageID type, MessageData data) { OnReceivedMessage(type, data); } /// <summary> /// Releases resources associated with the object. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Runs the Ultraviolet application. /// </summary> public void Run() { Contract.EnsureNotDisposed(this, disposed); OnInitializing(); CreateUltravioletContext(); OnInitialized(); OnLoadingContent(); running = true; while (running) { if (IsSuspended) { timingLogic.RunOneTickSuspended(); } else { timingLogic.RunOneTick(); } Thread.Yield(); } timingLogic.Cleanup(); uv.WaitForPendingTasks(true); } /// <summary> /// Exits the application. /// </summary> public void Exit() { Contract.EnsureNotDisposed(this, disposed); if (UltravioletPlatformInfo.CurrentPlatform == UltravioletPlatform.iOS) { System.Diagnostics.Debug.WriteLine(UltravioletStrings.CannotQuitOniOS); } else { running = false; } } /// <summary> /// Gets the Ultraviolet context. /// </summary> public UltravioletContext Ultraviolet { get { Contract.EnsureNotDisposed(this, disposed); Contract.Ensure(created, UltravioletStrings.ContextMissing); return uv; } } /// <inheritdoc/> public String DeveloperName { get; } /// <inheritdoc/> public String ApplicationName { get; } /// <summary> /// Gets or sets a value indicating whether the application's primary window is synchronized /// to the vertical retrace when rendering (i.e., whether vsync is enabled). /// </summary> public Boolean SynchronizeWithVerticalRetrace { get { Contract.EnsureNotDisposed(this, disposed); if (primary == null) throw new InvalidOperationException(UltravioletStrings.NoPrimaryWindow); return primary.SynchronizeWithVerticalRetrace; } set { Contract.EnsureNotDisposed(this, disposed); if (primary == null) throw new InvalidOperationException(UltravioletStrings.NoPrimaryWindow); primary.SynchronizeWithVerticalRetrace = value; } } /// <inheritdoc/> public Boolean IsActive { get { Contract.EnsureNotDisposed(this, disposed); if (primary == null) return false; lock (stateSyncObject) return primary.Active && !suspended; } } /// <inheritdoc/> public Boolean IsSuspended { get { Contract.EnsureNotDisposed(this, disposed); lock (stateSyncObject) return suspended; } } /// <inheritdoc/> public Boolean IsFixedTimeStep { get { Contract.EnsureNotDisposed(this, disposed); return this.isFixedTimeStep; } set { Contract.EnsureNotDisposed(this, disposed); this.isFixedTimeStep = value; if (timingLogic != null) { timingLogic.IsFixedTimeStep = value; } } } /// <inheritdoc/> public TimeSpan TargetElapsedTime { get { Contract.EnsureNotDisposed(this, disposed); return this.targetElapsedTime; } set { Contract.EnsureNotDisposed(this, disposed); Contract.EnsureRange(value.TotalMilliseconds >= 0, nameof(value)); this.targetElapsedTime = value; if (timingLogic != null) { timingLogic.TargetElapsedTime = value; } } } /// <inheritdoc/> public TimeSpan InactiveSleepTime { get { Contract.EnsureNotDisposed(this, disposed); return this.inactiveSleepTime; } set { Contract.EnsureNotDisposed(this, disposed); this.inactiveSleepTime = value; if (timingLogic != null) { timingLogic.InactiveSleepTime = value; } } } /// <summary> /// Called when the application is creating its Ultraviolet context. /// </summary> /// <returns>The Ultraviolet context.</returns> protected abstract UltravioletContext OnCreatingUltravioletContext(); /// <summary> /// Releases resources associated with the object. /// </summary> /// <param name="disposing"><see langword="true"/> if the object is being disposed; <see langword="false"/> if the object is being finalized.</param> protected virtual void Dispose(Boolean disposing) { lock (stateSyncObject) { if (!disposed) { if (disposing && uv != null) { uv.Messages.Unsubscribe(this); DisposePlatformResources(); if (primary != null) { primary.Drawing -= uv_Drawing; primary = null; } uv.Dispose(); uv.Updating -= uv_Updating; uv.Shutdown -= uv_Shutdown; uv.WindowDrawing -= uv_WindowDrawing; uv.WindowDrawn -= uv_WindowDrawn; timingLogic = null; } disposed = true; } } } /// <summary> /// Called when the application is initializing. /// </summary> protected virtual void OnInitializing() { } /// <summary> /// Called after the application has been initialized. /// </summary> protected virtual void OnInitialized() { } /// <summary> /// Called when the application is loading content. /// </summary> protected virtual void OnLoadingContent() { } /// <summary> /// Called when the application state is being updated. /// </summary> /// <param name="time">Time elapsed since the last call to <see cref="UltravioletContext.Update(UltravioletTime)"/>.</param> protected virtual void OnUpdating(UltravioletTime time) { } /// <summary> /// Called when the scene is being drawn. /// </summary> /// <param name="time">Time elapsed since the last call to <see cref="UltravioletContext.Draw(UltravioletTime)"/>.</param> protected virtual void OnDrawing(UltravioletTime time) { } /// <summary> /// Called when one of the application's windows is about to be drawn. /// </summary> /// <param name="time">Time elapsed since the last call to <see cref="UltravioletContext.Draw(UltravioletTime)"/>.</param> /// <param name="window">The window that is about to be drawn.</param> protected virtual void OnWindowDrawing(UltravioletTime time, IUltravioletWindow window) { } /// <summary> /// Called after one of the application's windows has been drawn. /// </summary> /// <param name="time">Time elapsed since the last call to <see cref="UltravioletContext.Draw(UltravioletTime)"/>.</param> /// <param name="window">The window that was just drawn.</param> protected virtual void OnWindowDrawn(UltravioletTime time, IUltravioletWindow window) { } /// <summary> /// Called when the application is about to be suspended. /// </summary> /// <remarks>When implementing this method, be aware that it can potentially be called /// from a thread other than the main Ultraviolet thread.</remarks> protected internal virtual void OnSuspending() { } /// <summary> /// Called when the application has been suspended. /// </summary> /// <remarks>When implementing this method, be aware that it can potentially be called /// from a thread other than the main Ultraviolet thread.</remarks> protected internal virtual void OnSuspended() { SaveSettings(); } /// <summary> /// Called when the application is about to be resumed. /// </summary> /// <remarks>When implementing this method, be aware that it can potentially be called /// from a thread other than the main Ultraviolet thread.</remarks> protected internal virtual void OnResuming() { } /// <summary> /// Called when the application has been resumed. /// </summary> /// <remarks>When implementing this method, be aware that it can potentially be called /// from a thread other than the main Ultraviolet thread.</remarks> protected internal virtual void OnResumed() { } /// <summary> /// Called when the operating system is attempting to reclaim memory. /// </summary> /// <remarks>When implementing this method, be aware that it can potentially be called /// from a thread other than the main Ultraviolet thread.</remarks> protected internal virtual void OnReclaimingMemory() { } /// <summary> /// Called when the application is being shut down. /// </summary> protected virtual void OnShutdown() { } /// <summary> /// Occurs when the context receives a message from its queue. /// </summary> /// <param name="type">The message type.</param> /// <param name="data">The message data.</param> protected virtual void OnReceivedMessage(UltravioletMessageID type, MessageData data) { if (type == UltravioletMessages.ApplicationTerminating) { running = false; } else if (type == UltravioletMessages.ApplicationSuspending) { OnSuspending(); lock (stateSyncObject) suspended = true; } else if (type == UltravioletMessages.ApplicationSuspended) { OnSuspended(); } else if (type == UltravioletMessages.ApplicationResuming) { OnResuming(); } else if (type == UltravioletMessages.ApplicationResumed) { timingLogic?.ResetElapsed(); lock (stateSyncObject) suspended = false; OnResumed(); } else if (type == UltravioletMessages.LowMemory) { OnReclaimingMemory(); } else if (type == UltravioletMessages.Quit) { if (UltravioletPlatformInfo.CurrentPlatform == UltravioletPlatform.iOS) { System.Diagnostics.Debug.WriteLine(UltravioletStrings.CannotQuitOniOS); } else { running = false; } } } /// <summary> /// Creates the timing logic for this host process. /// </summary> protected virtual IUltravioletTimingLogic CreateTimingLogic() { var timingLogic = new UltravioletTimingLogic(this); timingLogic.IsFixedTimeStep = this.IsFixedTimeStep; timingLogic.TargetElapsedTime = this.TargetElapsedTime; timingLogic.InactiveSleepTime = this.InactiveSleepTime; return timingLogic; } /// <summary> /// Ensures that the assembly which contains the specified type is linked on platforms /// which require ahead-of-time compilation. /// </summary> /// <typeparam name="T">One of the types defined by the assembly to link.</typeparam> protected void EnsureAssemblyIsLinked<T>() { Console.WriteLine("Touching '" + typeof(T).Assembly.FullName + "' to ensure linkage..."); } /// <summary> /// Uses a file source which is appropriate to the current platform. /// </summary> /// <returns><see langword="true"/> if a platform-specific file source was used; otherwise, <see langword="false"/>.</returns> protected Boolean UsePlatformSpecificFileSource() { return false; } /// <summary> /// Sets the file system source to an archive file loaded from a manifest resource stream, /// if the specified manifest resource exists. /// </summary> /// <param name="name">The name of the manifest resource being loaded as the file system source.</param> /// <returns><see langword="true"/> if the file source was set; otherwise, <see langword="false"/>.</returns> protected Boolean SetFileSourceFromManifestIfExists(String name) { Contract.RequireNotEmpty(name, nameof(name)); var asm = GetType().Assembly; if (asm.GetManifestResourceNames().Contains(name)) { FileSystemService.Source = ContentArchive.FromArchiveFile(() => { return asm.GetManifestResourceStream(name); }); return true; } return false; } /// <summary> /// Sets the file system source to an archive file loaded from a manifest resource stream. /// </summary> /// <param name="name">The name of the manifest resource being loaded as the file system source.</param> protected void SetFileSourceFromManifest(String name) { Contract.RequireNotEmpty(name, nameof(name)); var asm = GetType().Assembly; if (!asm.GetManifestResourceNames().Contains(name)) throw new FileNotFoundException(name); FileSystemService.Source = ContentArchive.FromArchiveFile(() => { return asm.GetManifestResourceStream(name); }); } /// <summary> /// Populates the specified Ultraviolet configuration with the application's initial values. /// </summary> /// <param name="configuration">The <see cref="UltravioletConfiguration"/> to populate.</param> protected void PopulateConfiguration(UltravioletConfiguration configuration) { Contract.Require(configuration, nameof(configuration)); PopulateConfigurationFromSettings(configuration); } /// <summary> /// Gets the directory that contains the application's local configuration files. /// If the directory does not already exist, it will be created. /// </summary> /// <returns>The directory that contains the application's local configuration files.</returns> protected String GetLocalApplicationSettingsDirectory() { var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), DeveloperName, ApplicationName); Directory.CreateDirectory(path); return path; } /// <summary> /// Gets the directory that contains the application's roaming configuration files. /// If the directory does not already exist, it will be created. /// </summary> /// <returns>The directory that contains the application's roaming configuration files.</returns> protected String GetRoamingApplicationSettingsDirectory() { var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), DeveloperName, ApplicationName); Directory.CreateDirectory(path); return path; } /// <summary> /// Gets or sets a value indicating whether the application's internal framework settings /// should be preserved between instances. /// </summary> protected Boolean PreserveApplicationSettings { get; set; } /// <summary> /// Initializes the application's state. /// </summary> partial void InitializeApplication(); /// <summary> /// Initializes the application's context after it has been acquired. /// </summary> partial void InitializeContext(); /// <summary> /// Disposes any platform-specific resources. /// </summary> partial void DisposePlatformResources(); /// <summary> /// Creates the application's Ultraviolet context. /// </summary> private void CreateUltravioletContext() { LoadSettings(); uv = UltravioletContext.EnsureSuccessfulCreation(OnCreatingUltravioletContext); if (uv == null) throw new InvalidOperationException(UltravioletStrings.ContextNotCreated); ApplySettings(); this.timingLogic = CreateTimingLogic(); if (this.timingLogic == null) throw new InvalidOperationException(UltravioletStrings.InvalidTimingLogic); this.uv.Messages.Subscribe(this, UltravioletMessages.ApplicationTerminating, UltravioletMessages.ApplicationSuspending, UltravioletMessages.ApplicationSuspended, UltravioletMessages.ApplicationResuming, UltravioletMessages.ApplicationResumed, UltravioletMessages.LowMemory, UltravioletMessages.Quit); this.uv.Updating += uv_Updating; this.uv.Shutdown += uv_Shutdown; this.uv.WindowDrawing += uv_WindowDrawing; this.uv.WindowDrawn += uv_WindowDrawn; this.uv.GetPlatform().Windows.PrimaryWindowChanging += uv_PrimaryWindowChanging; this.uv.GetPlatform().Windows.PrimaryWindowChanged += uv_PrimaryWindowChanged; HookPrimaryWindowEvents(); this.created = true; InitializeContext(); } /// <summary> /// Hooks into the primary window's events. /// </summary> private void HookPrimaryWindowEvents() { if (primary != null) { primary.Drawing -= uv_Drawing; } primary = uv.GetPlatform().Windows.GetPrimary(); if (primary != null) { primary.Drawing += uv_Drawing; } } /// <summary> /// Loads the application's settings. /// </summary> partial void LoadSettings(); /// <summary> /// Saves the application's settings. /// </summary> partial void SaveSettings(); /// <summary> /// Applies the application's settings. /// </summary> partial void ApplySettings(); /// <summary> /// Populates the Ultraviolet configuration from the application settings. /// </summary> partial void PopulateConfigurationFromSettings(UltravioletConfiguration configuration); /// <summary> /// Handles the Ultraviolet window manager's PrimaryWindowChanging event. /// </summary> /// <param name="window">The primary window.</param> private void uv_PrimaryWindowChanging(IUltravioletWindow window) { SaveSettings(); } /// <summary> /// Handles the Ultraviolet window manager's PrimaryWindowChanged event. /// </summary> /// <param name="window">The primary window.</param> private void uv_PrimaryWindowChanged(IUltravioletWindow window) { HookPrimaryWindowEvents(); } /// <summary> /// Handles the Ultraviolet window's Drawing event. /// </summary> /// <param name="window">The window being drawn.</param> /// <param name="time">Time elapsed since the last call to <see cref="UltravioletContext.Draw(UltravioletTime)"/>.</param> private void uv_Drawing(IUltravioletWindow window, UltravioletTime time) { OnDrawing(time); } /// <summary> /// Handles the Ultraviolet context's Updating event. /// </summary> /// <param name="uv">The Ultraviolet context.</param> /// <param name="time">Time elapsed since the last call to <see cref="UltravioletContext.Update(UltravioletTime)"/>.</param> private void uv_Updating(UltravioletContext uv, UltravioletTime time) { OnUpdating(time); } /// <summary> /// Handles the Ultraviolet context's Shutdown event. /// </summary> /// <param name="uv">The Ultraviolet context.</param> private void uv_Shutdown(UltravioletContext uv) { OnShutdown(); } /// <summary> /// Handles the Ultraviolet context's <see cref="UltravioletContext.WindowDrawing"/> event. /// </summary> private void uv_WindowDrawing(UltravioletContext uv, UltravioletTime time, IUltravioletWindow window) { OnWindowDrawing(time, window); } /// <summary> /// Handles the Ultraviolet context's <see cref="UltravioletContext.WindowDrawn"/> event. /// </summary> private void uv_WindowDrawn(UltravioletContext uv, UltravioletTime time, IUltravioletWindow window) { OnWindowDrawn(time, window); } // Property values. private UltravioletContext uv; // State values. private readonly Object stateSyncObject = new Object(); private IUltravioletTimingLogic timingLogic; private Boolean created; private Boolean running; private Boolean suspended; private Boolean disposed; private IUltravioletWindow primary; // The application's tick state. private Boolean isFixedTimeStep = UltravioletTimingLogic.DefaultIsFixedTimeStep; private TimeSpan targetElapsedTime = UltravioletTimingLogic.DefaultTargetElapsedTime; private TimeSpan inactiveSleepTime = UltravioletTimingLogic.DefaultInactiveSleepTime; } }
33.637931
157
0.560462
[ "Apache-2.0", "MIT" ]
MicroWorldwide/ultraviolet
Source/Ultraviolet.Shims.NETCore3/UltravioletApplication.cs
25,365
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace FiMA.Data { using System; using System.Collections.Generic; public partial class ec_groups { public int issuer_id { get; set; } public string issuer_des { get; set; } } }
30.761905
85
0.5
[ "Apache-2.0" ]
zachdimitrov/FiMA_Desktop
FiMA.Data/ec_groups.cs
646
C#
/* // <copyright> // dotNetRDF is free and open source software licensed under the MIT License // ------------------------------------------------------------------------- // // Copyright (c) 2009-2020 dotNetRDF Project (http://dotnetrdf.org/) // // 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. // </copyright> */ using System; namespace VDS.RDF.JsonLd { /// <summary> /// Exception raised when the JSON-LD framing algorithm encounters an error during processing. /// </summary> public class JsonLdFramingException : Exception { /// <summary> /// The JSON-LD error code describing the error encountered. /// </summary> public JsonLdFramingErrorCode ErrorCode { get; } /// <summary> /// Create a new exception instance. /// </summary> /// <param name="errorCode">The JSON-LD error code describing the error encountered.</param> /// <param name="message">A string containing contextual information to help the user identify the root cause of the error.</param> public JsonLdFramingException(JsonLdFramingErrorCode errorCode, string message) : base(message) { ErrorCode = errorCode; } } }
43.230769
139
0.683274
[ "MIT" ]
joephayes/dotnetrdf
Libraries/dotNetRDF/JsonLd/JsonLdFramingException.cs
2,248
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable namespace Azure.IoT.Hub.Service.Models { /// <summary> Represents the Device Method Invocation Results. </summary> public partial class CloudToDeviceMethodResponse { /// <summary> Initializes a new instance of CloudToDeviceMethodResponse. </summary> internal CloudToDeviceMethodResponse() { } /// <summary> Initializes a new instance of CloudToDeviceMethodResponse. </summary> /// <param name="status"> Method invocation result status. </param> /// <param name="payload"> Method invocation result payload. </param> internal CloudToDeviceMethodResponse(int? status, object payload) { Status = status; Payload = payload; } /// <summary> Method invocation result status. </summary> public int? Status { get; } /// <summary> Method invocation result payload. </summary> public object Payload { get; } } }
33.121212
91
0.647758
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/iot/Azure.IoT.Hub.Service/src/Generated/Models/CloudToDeviceMethodResponse.cs
1,093
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("LivePhotoFrame.UWP")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LivePhotoFrame.UWP")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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")] [assembly: ComVisible(false)]
36.310345
84
0.74264
[ "MIT" ]
dsalunga/LivePhotoFrame
LivePhotoFrame/LivePhotoFrame.UWP/Properties/AssemblyInfo.cs
1,056
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Text.Json.Serialization; namespace Microsoft.Identity.Web.Test.LabInfrastructure { public class LabUser { [JsonPropertyName("objectId")] public Guid ObjectId { get; set; } [JsonPropertyName("userType")] public UserType UserType { get; set; } [JsonPropertyName("upn")] public string Upn { get; set; } [JsonPropertyName("displayname")] public string DisplayName { get; set; } [JsonPropertyName("mfa")] public MFA Mfa { get; set; } [JsonPropertyName("protectionpolicy")] public ProtectionPolicy ProtectionPolicy { get; set; } [JsonPropertyName("homedomain")] public HomeDomain HomeDomain { get; set; } [JsonPropertyName("homeupn")] public string HomeUPN { get; set; } [JsonPropertyName("b2cprovider")] public B2CIdentityProvider B2cProvider { get; set; } [JsonPropertyName("labname")] public string LabName { get; set; } public FederationProvider FederationProvider { get; set; } public string Credential { get; set; } public string TenantId { get; set; } private string _password = null; [JsonPropertyName("appid")] public string AppId { get; set; } public string GetOrFetchPassword() { if (_password == null) { _password = LabUserHelper.FetchUserPassword(LabName); } return _password; } } }
26.031746
69
0.606098
[ "MIT" ]
AzureAD/microsoft-identity-web
tests/Microsoft.Identity.Web.Test.LabInfrastructure/LabUser.cs
1,642
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Autofac; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace WebApplication { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddScoped<IProductRepository, ProductRepository>(); //var containerBuilder = new ContainerBuilder();, //containerBuilder // .RegisterType<ProductRepository>() // .As<IProductRepository>(); //containerBuilder.RegisterModule<AutofacModule>(); //containerBuilder.Populate(services); //var container = containerBuilder.Build(); //return new AutofacServiceProvider(container); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
30.609375
107
0.578356
[ "MIT" ]
polatengin/B05277
Chapter10/0-InjectingDependenciesConfiguringIoC/Startup.cs
1,961
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("15. Neighbour Wars")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("15. Neighbour Wars")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4428bd08-0258-4210-8a36-7ce08e1a2cf7")] // 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.081081
84
0.74308
[ "MIT" ]
ViktorLazarov/SoftUniPractice
TechModuleConditionalStatementsAndLoops/15. Neighbour Wars/Properties/AssemblyInfo.cs
1,412
C#
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.IO; using Accessibility; using System.Runtime.InteropServices.ComTypes; using System.Security.Policy; namespace Microsoft.Plugin.Program.Programs { class ShellLinkHelper { [Flags()] public enum SLGP_FLAGS { SLGP_SHORTPATH = 0x1, SLGP_UNCPRIORITY = 0x2, SLGP_RAWPATH = 0x4 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct WIN32_FIND_DATAW { public uint dwFileAttributes; public long ftCreationTime; public long ftLastAccessTime; public long ftLastWriteTime; public uint nFileSizeHigh; public uint nFileSizeLow; public uint dwReserved0; public uint dwReserved1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string cFileName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] public string cAlternateFileName; } [Flags()] public enum SLR_FLAGS { SLR_NO_UI = 0x1, SLR_ANY_MATCH = 0x2, SLR_UPDATE = 0x4, SLR_NOUPDATE = 0x8, SLR_NOSEARCH = 0x10, SLR_NOTRACK = 0x20, SLR_NOLINKINFO = 0x40, SLR_INVOKE_MSI = 0x80 } // Reference : http://www.pinvoke.net/default.aspx/Interfaces.IShellLinkW /// The IShellLink interface allows Shell links to be created, modified, and resolved [ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")] interface IShellLinkW { /// <summary>Retrieves the path and file name of a Shell link object</summary> void GetPath([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, ref WIN32_FIND_DATAW pfd, SLGP_FLAGS fFlags); /// <summary>Retrieves the list of item identifiers for a Shell link object</summary> void GetIDList(out IntPtr ppidl); /// <summary>Sets the pointer to an item identifier list (PIDL) for a Shell link object.</summary> void SetIDList(IntPtr pidl); /// <summary>Retrieves the description string for a Shell link object</summary> void GetDescription([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName); /// <summary>Sets the description for a Shell link object. The description can be any application-defined string</summary> void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName); /// <summary>Retrieves the name of the working directory for a Shell link object</summary> void GetWorkingDirectory([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath); /// <summary>Sets the name of the working directory for a Shell link object</summary> void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir); /// <summary>Retrieves the command-line arguments associated with a Shell link object</summary> void GetArguments([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath); /// <summary>Sets the command-line arguments for a Shell link object</summary> void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs); /// <summary>Retrieves the hot key for a Shell link object</summary> void GetHotkey(out short pwHotkey); /// <summary>Sets a hot key for a Shell link object</summary> void SetHotkey(short wHotkey); /// <summary>Retrieves the show command for a Shell link object</summary> void GetShowCmd(out int piShowCmd); /// <summary>Sets the show command for a Shell link object. The show command sets the initial show state of the window.</summary> void SetShowCmd(int iShowCmd); /// <summary>Retrieves the location (path and index) of the icon for a Shell link object</summary> void GetIconLocation([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath, int cchIconPath, out int piIcon); /// <summary>Sets the location (path and index) of the icon for a Shell link object</summary> void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon); /// <summary>Sets the relative path to the Shell link object</summary> void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved); /// <summary>Attempts to find the target of a Shell link, even if it has been moved or renamed</summary> void Resolve(ref Accessibility._RemotableHandle hwnd, SLR_FLAGS fFlags); /// <summary>Sets the path and file name of a Shell link object</summary> void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile); } [ComImport(), Guid("00021401-0000-0000-C000-000000000046")] public class ShellLink { } // To initialize the app description public String description = String.Empty; // Retrieve the target path using Shell Link public string retrieveTargetPath(string path) { var link = new ShellLink(); const int STGM_READ = 0; ((IPersistFile)link).Load(path, STGM_READ); var hwnd = new _RemotableHandle(); ((IShellLinkW)link).Resolve(ref hwnd, 0); const int MAX_PATH = 260; StringBuilder buffer = new StringBuilder(MAX_PATH); var data = new WIN32_FIND_DATAW(); ((IShellLinkW)link).GetPath(buffer, buffer.Capacity, ref data, SLGP_FLAGS.SLGP_SHORTPATH); var target = buffer.ToString(); // To set the app description if (!String.IsNullOrEmpty(target)) { buffer = new StringBuilder(MAX_PATH); ((IShellLinkW)link).GetDescription(buffer, MAX_PATH); description = buffer.ToString(); } return target; } } }
48.083333
150
0.637467
[ "MIT" ]
01DKAC/PowerToys
src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/ShellLinkHelper.cs
6,349
C#
namespace Zoombraco.Tests { using System; using System.ComponentModel.DataAnnotations; using Xunit; using Zoombraco.Extensions; public class EnumExtensionTests { public static readonly TheoryData<TestEnum, string> EnumData = new TheoryData<TestEnum, string> { {TestEnum.Value1,"I am the first value." }, {TestEnum.Value2,"I am the second value." }, {TestEnum.Value3,"Value3" }, }; [Theory] [MemberData(nameof(EnumData))] public void EnumReturnsCorrectDisplayValue(TestEnum value, string expected) { Assert.Equal(value.ToDisplay(), expected, StringComparer.OrdinalIgnoreCase); } } public enum TestEnum { [Display(Name = "I am the first value.")] Value1, [Display(Name = "I am the second value.")] Value2, Value3 } }
25.361111
103
0.601314
[ "Apache-2.0" ]
JimBobSquarePants/Zoombraco
tests/Zoombraco.Tests/EnumExtensionTests.cs
915
C#
#define COUNT_ACTIVATE_DEACTIVATE using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Orleans; using Orleans.Runtime; using Orleans.Runtime.Providers; using Orleans.Streams; using UnitTests.GrainInterfaces; namespace UnitTests.Grains { [Serializable] public class StreamLifecycleTestGrainState { // For producer and consumer // -- only need to store this because of how we run our unit tests against multiple providers public string StreamProviderName { get; set; } // For producer only. public IAsyncStream<int> Stream { get; set; } public bool IsProducer { get; set; } public int NumMessagesSent { get; set; } public int NumErrors { get; set; } // For consumer only. public HashSet<StreamSubscriptionHandle<int>> ConsumerSubscriptionHandles { get; set; } public StreamLifecycleTestGrainState() { ConsumerSubscriptionHandles = new HashSet<StreamSubscriptionHandle<int>>(); } } public class GenericArg { public string A { get; private set; } public int B { get; private set; } public GenericArg(string a, int b) { A = a; B = b; } public override bool Equals(object obj) { var item = obj as GenericArg; if (item == null) { return false; } return A.Equals(item.A) && B.Equals(item.B); } public override int GetHashCode() { return (B * 397) ^ (A != null ? A.GetHashCode() : 0); } } public class AsyncObserverArg : GenericArg { public AsyncObserverArg(string a, int b) : base(a, b) { } } public class AsyncObservableArg : GenericArg { public AsyncObservableArg(string a, int b) : base(a, b) { } } public class AsyncStreamArg : GenericArg { public AsyncStreamArg(string a, int b) : base(a, b) { } } public class StreamSubscriptionHandleArg : GenericArg { public StreamSubscriptionHandleArg(string a, int b) : base(a, b) { } } public class StreamLifecycleTestGrainBase : Grain<StreamLifecycleTestGrainState> { protected ILogger logger; protected string _lastProviderName; protected IStreamProvider _streamProvider; #if COUNT_ACTIVATE_DEACTIVATE private IActivateDeactivateWatcherGrain watcher; #endif public StreamLifecycleTestGrainBase(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}"); } protected Task RecordActivate() { #if COUNT_ACTIVATE_DEACTIVATE watcher = GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0); return watcher.RecordActivateCall(IdentityString); #else return Task.CompletedTask; #endif } protected Task RecordDeactivate() { #if COUNT_ACTIVATE_DEACTIVATE return watcher.RecordDeactivateCall(IdentityString); #else return Task.CompletedTask; #endif } protected void InitStream(StreamId streamId, string providerToUse) { if (providerToUse == null) throw new ArgumentNullException("providerToUse", "Can't have null stream provider name"); if (State.Stream != null && !State.Stream.StreamId.Equals(streamId)) { if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Stream already exists for StreamId={0} StreamProvider={1} - Resetting", State.Stream, providerToUse); // Note: in this test, we are deliberately not doing Unsubscribe consumers, just discard old stream and let auto-cleanup functions do their thing. State.ConsumerSubscriptionHandles.Clear(); State.IsProducer = false; State.NumMessagesSent = 0; State.NumErrors = 0; State.Stream = null; } if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("InitStream StreamId={0} StreamProvider={1}", streamId, providerToUse); if (providerToUse != _lastProviderName) { _streamProvider = GetStreamProvider(providerToUse); _lastProviderName = providerToUse; } IAsyncStream<int> stream = _streamProvider.GetStream<int>(streamId); State.Stream = stream; State.StreamProviderName = providerToUse; if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("InitStream returning with Stream={0} with ref type = {1}", State.Stream, State.Stream.GetType().FullName); } } [Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")] internal class StreamLifecycleConsumerGrain : StreamLifecycleTestGrainBase, IStreamLifecycleConsumerGrain { protected readonly InsideRuntimeClient runtimeClient; protected readonly IStreamProviderRuntime streamProviderRuntime; public StreamLifecycleConsumerGrain(InsideRuntimeClient runtimeClient, IStreamProviderRuntime streamProviderRuntime, ILoggerFactory loggerFactory) : base(loggerFactory) { this.runtimeClient = runtimeClient; this.streamProviderRuntime = streamProviderRuntime; } protected IDictionary<StreamSubscriptionHandle<int>, MyStreamObserver<int>> Observers { get; set; } public override async Task OnActivateAsync() { if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("OnActivateAsync"); await RecordActivate(); if (Observers == null) { Observers = new Dictionary<StreamSubscriptionHandle<int>, MyStreamObserver<int>>(); } if (State.Stream != null && State.StreamProviderName != null) { if (State.ConsumerSubscriptionHandles.Count > 0) { var handles = State.ConsumerSubscriptionHandles.ToArray(); logger.Info("ReconnectConsumerHandles SubscriptionHandles={0} Grain={1}", Utils.EnumerableToString(handles), this.AsReference<IStreamLifecycleConsumerGrain>()); foreach (var handle in handles) { var observer = new MyStreamObserver<int>(this.logger); StreamSubscriptionHandle<int> subsHandle = await handle.ResumeAsync(observer); Observers.Add(subsHandle, observer); } } } else { if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Not conected to stream yet."); } } public override async Task OnDeactivateAsync() { if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("OnDeactivateAsync"); await RecordDeactivate(); } public Task<int> GetReceivedCount() { int numReceived = Observers.Sum(o => o.Value.NumItems); if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("ReceivedCount={0}", numReceived); return Task.FromResult(numReceived); } public Task<int> GetErrorsCount() { int numErrors = Observers.Sum(o => o.Value.NumErrors); if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("ErrorsCount={0}", numErrors); return Task.FromResult(numErrors); } public Task Ping() { logger.Info("Ping"); return Task.CompletedTask; } public virtual async Task BecomeConsumer(StreamId streamId, string providerToUse) { if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("BecomeConsumer StreamId={0} StreamProvider={1} Grain={2}", streamId, providerToUse, this.AsReference<IStreamLifecycleConsumerGrain>()); InitStream(streamId, providerToUse); var observer = new MyStreamObserver<int>(logger); var subsHandle = await State.Stream.SubscribeAsync(observer); State.ConsumerSubscriptionHandles.Add(subsHandle); Observers.Add(subsHandle, observer); await WriteStateAsync(); } public virtual async Task TestBecomeConsumerSlim(StreamId streamId, string providerName) { InitStream(streamId, providerName); var observer = new MyStreamObserver<int>(logger); //var subsHandle = await State.Stream.SubscribeAsync(observer); var context = this.Data; var (myExtension, myExtensionReference) = this.streamProviderRuntime.BindExtension<StreamConsumerExtension, IStreamConsumerExtension>( () => new StreamConsumerExtension(streamProviderRuntime)); string extKey = providerName + "_" + Encoding.UTF8.GetString(State.Stream.StreamId.Namespace.ToArray()); var id = new InternalStreamId(providerName, streamId); IPubSubRendezvousGrain pubsub = GrainFactory.GetGrain<IPubSubRendezvousGrain>(id.ToString()); GuidId subscriptionId = GuidId.GetNewGuidId(); await pubsub.RegisterConsumer(subscriptionId, ((StreamImpl<int>)State.Stream).InternalStreamId, myExtensionReference); myExtension.SetObserver(subscriptionId, ((StreamImpl<int>)State.Stream), observer, null, null); } public async Task RemoveConsumer(StreamId streamId, string providerName, StreamSubscriptionHandle<int> subsHandle) { if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("RemoveConsumer StreamId={0} StreamProvider={1}", streamId, providerName); if (State.ConsumerSubscriptionHandles.Count == 0) throw new InvalidOperationException("Not a Consumer"); await subsHandle.UnsubscribeAsync(); Observers.Remove(subsHandle); State.ConsumerSubscriptionHandles.Remove(subsHandle); await WriteStateAsync(); } public async Task ClearGrain() { logger.Info("ClearGrain"); var subsHandles = State.ConsumerSubscriptionHandles.ToArray(); foreach (var handle in subsHandles) { await handle.UnsubscribeAsync(); } State.ConsumerSubscriptionHandles.Clear(); State.Stream = null; State.IsProducer = false; Observers.Clear(); await ClearStateAsync(); } } [Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")] public class StreamLifecycleProducerGrain : StreamLifecycleTestGrainBase, IStreamLifecycleProducerGrain { public StreamLifecycleProducerGrain(ILoggerFactory loggerFactory) : base(loggerFactory) { } public override async Task OnActivateAsync() { if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("OnActivateAsync"); await RecordActivate(); if (State.Stream != null && State.StreamProviderName != null) { if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Reconnected to stream {0}", State.Stream); } else { if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Not connected to stream yet."); } } public override async Task OnDeactivateAsync() { if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("OnDeactivateAsync"); await RecordDeactivate(); } public Task<int> GetSendCount() { int result = State.NumMessagesSent; if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("GetSendCount={0}", result); return Task.FromResult(result); } public Task<int> GetErrorsCount() { int result = State.NumErrors; if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("GetErrorsCount={0}", result); return Task.FromResult(result); } public Task Ping() { logger.Info("Ping"); return Task.CompletedTask; } public async Task SendItem(int item) { if (!State.IsProducer || State.Stream == null) throw new InvalidOperationException("Not a Producer"); if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("SendItem Item={0}", item); Exception error = null; try { await State.Stream.OnNextAsync(item); if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Successful SendItem " + item); State.NumMessagesSent++; } catch (Exception exc) { logger.Error(0, "Error from SendItem " + item, exc); State.NumErrors++; error = exc; } await WriteStateAsync(); // Update counts in persisted state if (error != null) { throw new AggregateException(error); } if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Finished SendItem for Item={0}", item); } public async Task BecomeProducer(StreamId streamId, string providerName) { if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("BecomeProducer StreamId={0} StreamProvider={1}", streamId, providerName); InitStream(streamId, providerName); State.IsProducer = true; // Send an initial message to ensure we are properly initialized as a Producer. await State.Stream.OnNextAsync(0); State.NumMessagesSent++; await WriteStateAsync(); if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Finished BecomeProducer for StreamId={0} StreamProvider={1}", streamId, providerName); } public async Task ClearGrain() { logger.Info("ClearGrain"); State.IsProducer = false; State.Stream = null; await ClearStateAsync(); } public async Task DoDeactivateNoClose() { if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("DoDeactivateNoClose"); State.IsProducer = false; State.Stream = null; await WriteStateAsync(); if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Calling DeactivateOnIdle"); DeactivateOnIdle(); } } [Serializable] public class MyStreamObserver<T> : IAsyncObserver<T> { internal int NumItems { get; private set; } internal int NumErrors { get; private set; } private readonly ILogger logger; internal MyStreamObserver(ILogger logger) { this.logger = logger; } public Task OnNextAsync(T item, StreamSequenceToken token) { NumItems++; if (logger != null && logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("Received OnNextAsync - Item={0} - Total Items={1} Errors={2}", item, NumItems, NumErrors); } return Task.CompletedTask; } public Task OnCompletedAsync() { if (logger != null) { logger.Info("Receive OnCompletedAsync - Total Items={0} Errors={1}", NumItems, NumErrors); } return Task.CompletedTask; } public Task OnErrorAsync(Exception ex) { NumErrors++; if (logger != null) { logger.Warn(1, "Received OnErrorAsync - Exception={0} - Total Items={1} Errors={2}", ex, NumItems, NumErrors); } return Task.CompletedTask; } } public class ClosedTypeStreamObserver : MyStreamObserver<AsyncObserverArg> { public ClosedTypeStreamObserver(ILogger logger) : base(logger) { } } public interface IClosedTypeAsyncObservable : IAsyncObservable<AsyncObservableArg> { } public interface IClosedTypeAsyncStream : IAsyncStream<AsyncStreamArg> { } internal class ClosedTypeStreamSubscriptionHandle : StreamSubscriptionHandleImpl<StreamSubscriptionHandleArg> { public ClosedTypeStreamSubscriptionHandle() : base(null, null) { /* not a subject to the creation */ } } }
36.997778
202
0.614692
[ "MIT" ]
Bin-H-CN/orleans
test/Grains/TestInternalGrains/StreamLifecycleTestGrains.cs
16,649
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; namespace Contoso.Forms.Demo { [Android.Runtime.Preserve(AllMembers = true)] public partial class AddPropertyContentPage { public event Action<Property> PropertyAdded; public AddPropertyContentPage() { InitializeComponent(); } async void AddProperty(object sender, EventArgs e) { Property addedProperty = new Property(NameEntry.Text, ValueEntry.Text); PropertyAdded.Invoke(addedProperty); await Navigation.PopModalAsync(); } async void Cancel(object sender, EventArgs e) { await Navigation.PopModalAsync(); } } }
25.290323
83
0.632653
[ "MIT" ]
AndreiShilkin/AppCenter-SDK-DotNet
Apps/Contoso.Forms.Demo/Contoso.Forms.Demo/AddPropertyContentPage.xaml.cs
784
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Mapbox.Api { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Mapbox.Api.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to API key is not set.. /// </summary> internal static string ApiKeyIsNotSet { get { return ResourceManager.GetString("ApiKeyIsNotSet", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Disposed.. /// </summary> internal static string Disposed { get { return ResourceManager.GetString("Disposed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Disposing.... /// </summary> internal static string Disposing { get { return ResourceManager.GetString("Disposing", resourceCulture); } } } }
39.912088
165
0.5837
[ "MIT" ]
panoramicdata/Mapbox.Api
Mapbox.Api/Resources.Designer.cs
3,634
C#
using System.Collections.Generic; using System.IO; using System.Linq; using Terraria.ModLoader.IO; namespace Terraria.ModLoader.Default { class MysteryTilesWorld : ModWorld { internal List<MysteryTileInfo> infos = new List<MysteryTileInfo>(); internal List<MysteryTileInfo> pendingInfos = new List<MysteryTileInfo>(); public override void Initialize() { infos.Clear(); pendingInfos.Clear(); } public override TagCompound Save() { return new TagCompound { ["list"] = infos.Select(info => info?.Save() ?? new TagCompound()).ToList() }; } public override void Load(TagCompound tag) { List<ushort> canRestore = new List<ushort>(); bool canRestoreFlag = false; foreach (var infoTag in tag.GetList<TagCompound>("list")) { if (!infoTag.ContainsKey("mod")) { infos.Add(null); canRestore.Add(0); continue; } string modName = infoTag.GetString("mod"); string name = infoTag.GetString("name"); bool frameImportant = infoTag.ContainsKey("frameX"); var info = frameImportant ? new MysteryTileInfo(modName, name, infoTag.GetShort("frameX"), infoTag.GetShort("frameY")) : new MysteryTileInfo(modName, name); infos.Add(info); int type = ModLoader.GetMod(modName)?.TileType(name) ?? 0; canRestore.Add((ushort)type); if (type != 0) canRestoreFlag = true; } if (canRestoreFlag) { RestoreTiles(canRestore); for (int k = 0; k < canRestore.Count; k++) { if (canRestore[k] > 0) { infos[k] = null; } } } if (pendingInfos.Count > 0) { ConfirmPendingInfo(); } } private void RestoreTiles(List<ushort> canRestore) { ushort mysteryType = (ushort)ModContent.GetInstance<ModLoaderMod>().TileType("MysteryTile"); for (int x = 0; x < Main.maxTilesX; x++) { for (int y = 0; y < Main.maxTilesY; y++) { if (Main.tile[x, y].type == mysteryType) { Tile tile = Main.tile[x, y]; MysteryTileFrame frame = new MysteryTileFrame(tile.frameX, tile.frameY); int frameID = frame.FrameID; if (canRestore[frameID] > 0) { MysteryTileInfo info = infos[frameID]; tile.type = canRestore[frameID]; tile.frameX = info.frameX; tile.frameY = info.frameY; } } } } } private void ConfirmPendingInfo() { List<int> truePendingID = new List<int>(); int nextID = 0; for (int k = 0; k < pendingInfos.Count; k++) { while (nextID < infos.Count && infos[nextID] != null) { nextID++; } if (nextID == infos.Count) { infos.Add(pendingInfos[k]); } else { infos[nextID] = pendingInfos[k]; } truePendingID.Add(nextID); } ushort pendingType = (ushort)ModContent.GetInstance<ModLoaderMod>().TileType("PendingMysteryTile"); ushort mysteryType = (ushort)ModContent.GetInstance<ModLoaderMod>().TileType("MysteryTile"); for (int x = 0; x < Main.maxTilesX; x++) { for (int y = 0; y < Main.maxTilesY; y++) { if (Main.tile[x, y].type == pendingType) { Tile tile = Main.tile[x, y]; MysteryTileFrame frame = new MysteryTileFrame(tile.frameX, tile.frameY); frame = new MysteryTileFrame(truePendingID[frame.FrameID]); tile.type = mysteryType; tile.frameX = frame.FrameX; tile.frameY = frame.FrameY; } } } } } }
29.81982
102
0.636556
[ "MIT" ]
Dradon-extra-fork/tStandalone
patches/tModLoader/Terraria/ModLoader/Default/MysteryTilesWorld.cs
3,312
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Threading.Tasks; using Dbosoft.IdentityServer.Models.Contexts; using Dbosoft.IdentityServer.Services; namespace Dbosoft.IdentityServer.UnitTests.Endpoints.EndSession { internal class StubBackChannelLogoutClient : IBackChannelLogoutService { public bool SendLogoutsWasCalled { get; set; } public Task SendLogoutNotificationsAsync(LogoutNotificationContext context) { SendLogoutsWasCalled = true; return Task.CompletedTask; } } }
31.363636
107
0.73913
[ "Apache-2.0" ]
dbosoft/IdentityServer
tests/IdentityServer.UnitTests/Endpoints/EndSession/StubBackChannelLogoutClient.cs
692
C#
using UnityEngine; using BaseClient = Assets.Scripts.InMaze.Multiplayer.Normal.ClientController; using Assets.Scripts.InMaze.Networking.Jsonify.Extension; using Assets.Scripts.InMaze.Networking.Jsonify; namespace Assets.Scripts.InMaze.Multiplayer.CaptureTheFlag { public class ClientController : BaseClient { private bool hasFlag; // Exactly the same as normal clientcontroller protected override void Update () { base.Update (); if (FlagHolder.Present != null) { // Not you if (FlagHolder.Present.Id != PlayerNode.present.id) { if (hasFlag) MessageBox.Show (this, "You just lost the flag"); hasFlag = false; } else { if (!hasFlag) MessageBox.Show (this, "You have gotten the flag"); hasFlag = true; } } } } }
25.258065
77
0.696041
[ "Apache-2.0" ]
myze/Unity-App
Assets/Scripts/InMaze/Multiplayer/CaptureTheFlag/ClientController.cs
785
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace BennyKok.NotionAPI.Post { [Serializable] public class Parent { public string type; public string database_id; } [Serializable] public class OptionEntry { //public string id; public string name; //public string color; } [Serializable] public class SelectProperty { //public string id; //public string name; //public string type; public OptionEntry select; } [Serializable] public class MultiSelectProperty { //public string id; //public string name; //public string type; public OptionEntry[] multi_select; } [Serializable] public class TitleProperty { //public string id; //public string name; //public string type; public Text[] title; } [Serializable] public class TextProperty { //public string id; //public string type; public Text[] rich_text; } [Serializable] public class Text { //public string type; public TextContent text; public Annotations annotations = new Annotations(); //public string plain_text; //public object href; [Serializable] public class TextContent { public string content; public object link; } [Serializable] public class Annotations { public bool bold; public bool italic; public bool strikethrough; public bool underline; public bool code; public string color = "default"; } } [Serializable] public class NumberProperty { //public string id; //public string name; //public string type; public float number; } [Serializable] public class CheckboxProperty { //public string id; //public string name; //public string type; public bool checkbox; } [Serializable] public class DateProperty { //public string id; //public string name; //public string type; public Date date; } [Serializable] public class DateRangeProperty { //public string id; //public string name; //public string type; public DateRange date; } [Serializable] public class Date { public string start; } [Serializable] public class DateRange : Date { public string end; } [Serializable] public class EmailProperty { //public string id; //public string name; //public string type; public string email; } [Serializable] public class PhoneNumberProperty { //public string id; //public string name; //public string type; public string phone_number; } [Serializable] public class UrlProperty { //public string id; //public string name; //public string type; public string url; } [Serializable] public class PersonProperty { //public string id; //public string name; //public string type; public People[] people; } [Serializable] public class People { public string @object; public string id; } }
20.125
59
0.560136
[ "MIT" ]
yotiky/unity-notion-api
Runtime/DataModel/PostProperty.cs
3,544
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the alexaforbusiness-2017-11-09.normal.json service model. */ using System; using Amazon.Runtime; namespace Amazon.AlexaForBusiness { /// <summary> /// Constants used for properties of type DeviceStatus. /// </summary> public class DeviceStatus : ConstantClass { /// <summary> /// Constant PENDING for DeviceStatus /// </summary> public static readonly DeviceStatus PENDING = new DeviceStatus("PENDING"); /// <summary> /// Constant READY for DeviceStatus /// </summary> public static readonly DeviceStatus READY = new DeviceStatus("READY"); /// <summary> /// Constant WAS_OFFLINE for DeviceStatus /// </summary> public static readonly DeviceStatus WAS_OFFLINE = new DeviceStatus("WAS_OFFLINE"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public DeviceStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static DeviceStatus FindValue(string value) { return FindValue<DeviceStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator DeviceStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type DistanceUnit. /// </summary> public class DistanceUnit : ConstantClass { /// <summary> /// Constant IMPERIAL for DistanceUnit /// </summary> public static readonly DistanceUnit IMPERIAL = new DistanceUnit("IMPERIAL"); /// <summary> /// Constant METRIC for DistanceUnit /// </summary> public static readonly DistanceUnit METRIC = new DistanceUnit("METRIC"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public DistanceUnit(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static DistanceUnit FindValue(string value) { return FindValue<DistanceUnit>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator DistanceUnit(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type EnrollmentStatus. /// </summary> public class EnrollmentStatus : ConstantClass { /// <summary> /// Constant DEREGISTERING for EnrollmentStatus /// </summary> public static readonly EnrollmentStatus DEREGISTERING = new EnrollmentStatus("DEREGISTERING"); /// <summary> /// Constant INITIALIZED for EnrollmentStatus /// </summary> public static readonly EnrollmentStatus INITIALIZED = new EnrollmentStatus("INITIALIZED"); /// <summary> /// Constant PENDING for EnrollmentStatus /// </summary> public static readonly EnrollmentStatus PENDING = new EnrollmentStatus("PENDING"); /// <summary> /// Constant REGISTERED for EnrollmentStatus /// </summary> public static readonly EnrollmentStatus REGISTERED = new EnrollmentStatus("REGISTERED"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public EnrollmentStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static EnrollmentStatus FindValue(string value) { return FindValue<EnrollmentStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator EnrollmentStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type Feature. /// </summary> public class Feature : ConstantClass { /// <summary> /// Constant ALL for Feature /// </summary> public static readonly Feature ALL = new Feature("ALL"); /// <summary> /// Constant BLUETOOTH for Feature /// </summary> public static readonly Feature BLUETOOTH = new Feature("BLUETOOTH"); /// <summary> /// Constant LISTS for Feature /// </summary> public static readonly Feature LISTS = new Feature("LISTS"); /// <summary> /// Constant NOTIFICATIONS for Feature /// </summary> public static readonly Feature NOTIFICATIONS = new Feature("NOTIFICATIONS"); /// <summary> /// Constant SKILLS for Feature /// </summary> public static readonly Feature SKILLS = new Feature("SKILLS"); /// <summary> /// Constant VOLUME for Feature /// </summary> public static readonly Feature VOLUME = new Feature("VOLUME"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public Feature(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static Feature FindValue(string value) { return FindValue<Feature>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator Feature(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type SortValue. /// </summary> public class SortValue : ConstantClass { /// <summary> /// Constant ASC for SortValue /// </summary> public static readonly SortValue ASC = new SortValue("ASC"); /// <summary> /// Constant DESC for SortValue /// </summary> public static readonly SortValue DESC = new SortValue("DESC"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public SortValue(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static SortValue FindValue(string value) { return FindValue<SortValue>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator SortValue(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type TemperatureUnit. /// </summary> public class TemperatureUnit : ConstantClass { /// <summary> /// Constant CELSIUS for TemperatureUnit /// </summary> public static readonly TemperatureUnit CELSIUS = new TemperatureUnit("CELSIUS"); /// <summary> /// Constant FAHRENHEIT for TemperatureUnit /// </summary> public static readonly TemperatureUnit FAHRENHEIT = new TemperatureUnit("FAHRENHEIT"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public TemperatureUnit(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static TemperatureUnit FindValue(string value) { return FindValue<TemperatureUnit>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator TemperatureUnit(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type WakeWord. /// </summary> public class WakeWord : ConstantClass { /// <summary> /// Constant ALEXA for WakeWord /// </summary> public static readonly WakeWord ALEXA = new WakeWord("ALEXA"); /// <summary> /// Constant AMAZON for WakeWord /// </summary> public static readonly WakeWord AMAZON = new WakeWord("AMAZON"); /// <summary> /// Constant COMPUTER for WakeWord /// </summary> public static readonly WakeWord COMPUTER = new WakeWord("COMPUTER"); /// <summary> /// Constant ECHO for WakeWord /// </summary> public static readonly WakeWord ECHO = new WakeWord("ECHO"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public WakeWord(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static WakeWord FindValue(string value) { return FindValue<WakeWord>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator WakeWord(string value) { return FindValue(value); } } }
35.63835
114
0.59511
[ "Apache-2.0" ]
Murcho/aws-sdk-net
sdk/src/Services/AlexaForBusiness/Generated/ServiceEnumerations.cs
14,683
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; namespace GraphQlClientGenerator { public class GraphQlGenerator { private const string AutoGeneratedPrefix = "// <auto-generated> This file has been auto generated. </auto-generated>"; public const string PreprocessorDirectiveDisableNewtonsoftJson = "GRAPHQL_GENERATOR_DISABLE_NEWTONSOFT_JSON"; public const string RequiredNamespaces = @"using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; #if!" + PreprocessorDirectiveDisableNewtonsoftJson + @" using Newtonsoft.Json; using Newtonsoft.Json.Linq; #endif "; private delegate void WriteDataClassPropertyBodyDelegate(ScalarFieldTypeDescription netType, string backingFieldName); private static readonly HttpClient HttpClient = new HttpClient { DefaultRequestHeaders = { UserAgent = { ProductInfoHeaderValue.Parse("GraphQlGenerator/" + typeof(GraphQlGenerator).GetTypeInfo().Assembly.GetName().Version) } } }; internal static readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), Converters = { new StringEnumConverter() } }; private readonly GraphQlGeneratorConfiguration _configuration; public GraphQlGenerator(GraphQlGeneratorConfiguration configuration = null) { _configuration = configuration ?? new GraphQlGeneratorConfiguration(); } public static async Task<GraphQlSchema> RetrieveSchema(string url, string authorization = null) { using var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new StringContent(JsonConvert.SerializeObject(new { query = IntrospectionQuery.Text }), Encoding.UTF8, "application/json") }; if (!String.IsNullOrWhiteSpace(authorization)) request.Headers.Authorization = AuthenticationHeaderValue.Parse(authorization); using var response = await HttpClient.SendAsync(request); var content = response.Content == null ? "(no content)" : await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) throw new InvalidOperationException($"Status code: {(int)response.StatusCode} ({response.StatusCode}){Environment.NewLine}content:{Environment.NewLine}{content}"); return DeserializeGraphQlSchema(content); } public static GraphQlSchema DeserializeGraphQlSchema(string content) { try { var result = JsonConvert.DeserializeObject<GraphQlResult>(content, SerializerSettings); if (result.Data?.Schema == null) throw new ArgumentException("not a GraphQL schema", nameof(content)); return result.Data.Schema; } catch (JsonReaderException exception) { throw new ArgumentException("not a GraphQL schema", nameof(content), exception); } } public string GenerateFullClientCSharpFile(GraphQlSchema schema, string @namespace) { if (String.IsNullOrWhiteSpace(@namespace)) throw new ArgumentException("namespace required", nameof(@namespace)); var builder = new StringBuilder(); builder.AppendLine(AutoGeneratedPrefix); builder.AppendLine(); builder.AppendLine(RequiredNamespaces); builder.Append("namespace "); builder.AppendLine(@namespace); builder.AppendLine("{"); using (var writer = new StringWriter(builder)) Generate(new SingleFileGenerationContext(schema, writer, indentationSize: 4)); builder.AppendLine("}"); return builder.ToString(); } public string Generate(GraphQlSchema schema) { var builder = new StringBuilder(); using var writer = new StringWriter(builder); Generate(new SingleFileGenerationContext(schema, writer)); return builder.ToString(); } public void Generate(GenerationContext context) { context.BeforeGeneration(_configuration); GenerateBaseClasses(context); GenerateEnums(context); GenerateDirectives(context); GenerateQueryBuilders(context); var referencedObjectTypes = GenerateInputObjects(context); GenerateDataClasses(context, referencedObjectTypes); context.AfterGeneration(); } private void GenerateEnums(GenerationContext context) { var enumTypes = context.Schema.Types.Where(t => t.Kind == GraphQlTypeKind.Enum && !t.Name.StartsWith("__")).ToList(); if (!enumTypes.Any()) return; context.BeforeEnumsGeneration(); enumTypes.ForEach(t => GenerateEnum(context, t)); context.AfterEnumsGeneration(); } private void GenerateQueryBuilders(GenerationContext context) { if (IsQueryBuilderGenerationDisabled(context.ObjectTypes)) return; context.BeforeQueryBuildersGeneration(); var complexTypes = context.Schema.Types.Where(t => IsComplexType(t.Kind) && !t.Name.StartsWith("__")).ToList(); var complexTypeDictionary = complexTypes.ToDictionary(t => t.Name); complexTypes.ForEach(t => GenerateQueryBuilder(context, t, complexTypeDictionary)); context.AfterQueryBuildersGeneration(); } private static void GenerateBaseClasses(GenerationContext context) { if (IsQueryBuilderGenerationDisabled(context.ObjectTypes)) return; context.BeforeBaseClassGeneration(); var indentation = GetIndentation(context.Indentation); using (var reader = new StreamReader(typeof(GraphQlGenerator).GetTypeInfo().Assembly.GetManifestResourceStream("GraphQlClientGenerator.BaseClasses.cs"))) do { var line = reader.ReadLine(); if (line == null) break; context.Writer.Write(indentation); context.Writer.WriteLine(line.Replace("GRAPHQL_GENERATOR_DISABLE_NEWTONSOFT_JSON", PreprocessorDirectiveDisableNewtonsoftJson)); } while (true); context.AfterBaseClassGeneration(); } private static bool IsQueryBuilderGenerationDisabled(GeneratedObjectType objectTypes) => !objectTypes.HasFlag(GeneratedObjectType.QueryBuilders); private static bool IsDataClassGenerationDisabled(GeneratedObjectType objectTypes) => !objectTypes.HasFlag(GeneratedObjectType.DataClasses); private static string GetIndentation(int size) => new String(' ', size); private static void FindAllReferencedObjectTypes(GraphQlSchema schema, GraphQlType type, ISet<string> objectTypes) { foreach (var member in (IEnumerable<IGraphQlMember>)type.InputFields ?? type.Fields) { var unwrappedType = member.Type.UnwrapIfNonNull(); GraphQlType memberType; switch (unwrappedType.Kind) { case GraphQlTypeKind.Object: objectTypes.Add(unwrappedType.Name); memberType = schema.Types.Single(t => t.Name == unwrappedType.Name); FindAllReferencedObjectTypes(schema, memberType, objectTypes); break; case GraphQlTypeKind.List: var itemType = unwrappedType.OfType.UnwrapIfNonNull(); if (IsComplexType(itemType.Kind)) { memberType = schema.Types.Single(t => t.Name == itemType.Name); FindAllReferencedObjectTypes(schema, memberType, objectTypes); } break; } } } private ICollection<string> GenerateInputObjects(GenerationContext context) { var referencedObjectTypes = new HashSet<string>(); if (IsDataClassGenerationDisabled(context.ObjectTypes)) return referencedObjectTypes; var schema = context.Schema; var inputObjectTypes = schema.Types.Where(t => t.Kind == GraphQlTypeKind.InputObject && !t.Name.StartsWith("__")).ToArray(); if (!inputObjectTypes.Any()) return referencedObjectTypes; context.BeforeInputClassesGeneration(); foreach (var inputObject in inputObjectTypes) { FindAllReferencedObjectTypes(schema, inputObject, referencedObjectTypes); GenerateDataClass( context, NamingHelper.ToPascalCase(inputObject.Name), inputObject.Description, "IGraphQlInputObject", () => GenerateInputDataClassBody(inputObject, inputObject.InputFields.Cast<IGraphQlMember>().ToArray(), context)); } context.AfterInputClassesGeneration(); return referencedObjectTypes; } private void GenerateDataClasses(GenerationContext context, ICollection<string> referencedObjectTypes) { if (IsDataClassGenerationDisabled(context.ObjectTypes)) return; var schema = context.Schema; var complexTypes = schema.Types.Where(t => IsComplexType(t.Kind) && !t.Name.StartsWith("__")).ToArray(); if (!complexTypes.Any()) return; var complexTypeDictionary = complexTypes.ToDictionary(t => t.Name); context.BeforeDataClassesGeneration(); foreach (var complexType in complexTypes) { var hasInputReference = referencedObjectTypes.Contains(complexType.Name); var fieldsToGenerate = GetFieldsToGenerate(complexType, complexTypeDictionary); var isInterface = complexType.Kind == GraphQlTypeKind.Interface; var csharpTypeName = complexType.Name; if (!UseCustomClassNameIfDefined(ref csharpTypeName)) csharpTypeName = NamingHelper.ToPascalCase(csharpTypeName); void GenerateBody(bool isInterfaceMember) { var writer = context.Writer; if (hasInputReference) GenerateInputDataClassBody(complexType, fieldsToGenerate, context); else if (fieldsToGenerate != null) { var generateBackingFields = _configuration.PropertyGeneration == PropertyGenerationOption.BackingField && !isInterfaceMember; if (generateBackingFields) { var indentation = GetIndentation(context.Indentation); foreach (var field in fieldsToGenerate) { writer.Write(indentation); writer.Write(" private "); writer.Write(GetDataPropertyType(complexType, field).NetTypeName); writer.Write(" "); writer.Write(GetBackingFieldName(field.Name)); writer.WriteLine(";"); } writer.WriteLine(); } foreach (var field in fieldsToGenerate) GenerateDataProperty( complexType, field, isInterfaceMember, field.IsDeprecated, field.DeprecationReason, true, (_, backingFieldName) => writer.Write(generateBackingFields ? _configuration.PropertyAccessorBodyWriter(backingFieldName, GetDataPropertyType(complexType, field)) : " { get; set; }"), context); } } var interfacesToImplement = new List<string>(); if (isInterface) { interfacesToImplement.Add(GenerateInterface(context, "I" + csharpTypeName, complexType.Description, () => GenerateBody(true))); } else if (complexType.Interfaces?.Count > 0) { var fieldNames = new HashSet<string>(fieldsToGenerate.Select(f => f.Name)); foreach (var @interface in complexType.Interfaces) { interfacesToImplement.Add("I" + @interface.Name + _configuration.ClassPostfix); foreach (var interfaceField in complexTypeDictionary[@interface.Name].Fields.Where(FilterDeprecatedFields)) if (fieldNames.Add(interfaceField.Name)) fieldsToGenerate.Add(interfaceField); } } if (hasInputReference) interfacesToImplement.Add("IGraphQlInputObject"); GenerateDataClass(context, csharpTypeName, complexType.Description, String.Join(", ", interfacesToImplement), () => GenerateBody(false)); } context.AfterDataClassesGeneration(); } private static string GetBackingFieldName(string graphQlFieldName) => "_" + NamingHelper.LowerFirst(NamingHelper.ToPascalCase(graphQlFieldName)); private static bool IsComplexType(GraphQlTypeKind graphQlTypeKind) => graphQlTypeKind == GraphQlTypeKind.Object || graphQlTypeKind == GraphQlTypeKind.Interface || graphQlTypeKind == GraphQlTypeKind.Union; private void GenerateInputDataClassBody(GraphQlType type, IEnumerable<IGraphQlMember> members, GenerationContext context) { var writer = context.Writer; var indentation = GetIndentation(context.Indentation); var fieldNameMembers = new Dictionary<string, IGraphQlMember>(); foreach (var member in members) { var fieldName = GetBackingFieldName(member.Name); fieldNameMembers.Add(fieldName, member); writer.Write(indentation); writer.Write(" private InputPropertyInfo "); writer.Write(fieldName); writer.WriteLine(";"); } writer.WriteLine(); var useCompatibleSyntax = _configuration.CSharpVersion == CSharpVersion.Compatible; foreach (var kvp in fieldNameMembers) GenerateDataProperty( type, kvp.Value, false, false, null, true, (t, _) => { writer.WriteLine(); writer.Write(indentation); writer.WriteLine(" {"); writer.Write(indentation); writer.Write(" get"); writer.Write(useCompatibleSyntax ? " { return " : " => "); writer.Write("("); writer.Write(t.NetTypeName); writer.Write(")"); writer.Write(kvp.Key); writer.Write(".Value;"); if (useCompatibleSyntax) writer.Write(" }"); writer.WriteLine(); writer.Write(indentation); writer.Write(" set"); writer.Write(useCompatibleSyntax ? " { " : " => "); writer.Write(kvp.Key); writer.Write(" = new InputPropertyInfo { Name = \""); writer.Write(kvp.Value.Name); writer.Write("\", Value = value"); if (!String.IsNullOrEmpty(t.FormatMask)) { writer.Write(", FormatMask = \""); writer.Write(t.FormatMask.Replace("\"", "\\\"")); writer.Write("\""); } writer.Write(" };"); if (useCompatibleSyntax) writer.Write(" }"); writer.WriteLine(); writer.Write(indentation); writer.WriteLine(" }"); }, context); writer.Write(indentation); writer.WriteLine(" IEnumerable<InputPropertyInfo> IGraphQlInputObject.GetPropertyValues()"); writer.Write(indentation); writer.WriteLine(" {"); foreach (var fieldName in fieldNameMembers.Keys) { writer.Write(indentation); writer.Write(" if ("); writer.Write(fieldName); writer.Write(".Name != null) yield return "); writer.Write(fieldName); writer.WriteLine(";"); } writer.Write(indentation); writer.WriteLine(" }"); } private string GenerateInterface(GenerationContext context, string interfaceName, string interfaceDescription, Action generateInterfaceBody) => GenerateFileMember(context, "interface", interfaceName, interfaceDescription, null, generateInterfaceBody); private string GenerateDataClass(GenerationContext context, string typeName, string typeDescription, string baseTypeName, Action generateClassBody) => GenerateFileMember(context, (_configuration.GeneratePartialClasses ? "partial " : null) + "class", typeName, typeDescription, baseTypeName, generateClassBody); private string GenerateFileMember(GenerationContext context, string memberType, string typeName, string typeDescription, string baseTypeName, Action generateFileMemberBody) { typeName += _configuration.ClassPostfix; ValidateClassName(typeName); context.BeforeDataClassGeneration(typeName); var writer = context.Writer; GenerateCodeComments(writer, typeDescription, context.Indentation); var indentation = GetIndentation(context.Indentation); writer.Write(indentation); writer.Write(GetMemberAccessibility()); writer.Write(" "); writer.Write(memberType); writer.Write(" "); writer.Write(typeName); if (!String.IsNullOrEmpty(baseTypeName)) { writer.Write(" : "); writer.Write(baseTypeName); } writer.WriteLine(); writer.Write(indentation); writer.WriteLine("{"); generateFileMemberBody(); writer.Write(indentation); writer.WriteLine("}"); context.AfterDataClassGeneration(typeName); return typeName; } private static IEnumerable<GraphQlField> GetFragments(GraphQlType type, IDictionary<string, GraphQlType> complexTypeDictionary) { var fragments = new List<GraphQlField>(); if (type.Kind != GraphQlTypeKind.Union && type.Kind != GraphQlTypeKind.Interface) return fragments; foreach (var possibleType in type.PossibleTypes) if (complexTypeDictionary.TryGetValue(possibleType.Name, out var consistOfType) && consistOfType.Fields != null) fragments.Add( new GraphQlField { Name = consistOfType.Name, Description = consistOfType.Description, Type = new GraphQlFieldType { Name = consistOfType.Name, Kind = consistOfType.Kind } }); return fragments; } private List<GraphQlField> GetFieldsToGenerate(GraphQlType type, IDictionary<string, GraphQlType> complexTypeDictionary) { var typeFields = type.Fields; if (type.Kind == GraphQlTypeKind.Union) { var unionFields = new List<GraphQlField>(); var unionFieldNames = new HashSet<string>(); foreach (var possibleType in type.PossibleTypes) if (complexTypeDictionary.TryGetValue(possibleType.Name, out var consistOfType) && consistOfType.Fields != null) unionFields.AddRange(consistOfType.Fields.Where(f => unionFieldNames.Add(f.Name))); typeFields = unionFields; } return typeFields?.Where(FilterDeprecatedFields).ToList(); } private string AddQuestionMarkIfNullableReferencesEnabled(string dataTypeIdentifier) => AddQuestionMarkIfNullableReferencesEnabled(_configuration, dataTypeIdentifier); internal static string AddQuestionMarkIfNullableReferencesEnabled(GraphQlGeneratorConfiguration configuration, string dataTypeIdentifier) => configuration.CSharpVersion == CSharpVersion.NewestWithNullableReferences ? dataTypeIdentifier + "?" : dataTypeIdentifier; private bool UseCustomClassNameIfDefined(ref string typeName) { if (!_configuration.CustomClassNameMapping.TryGetValue(typeName, out var customTypeName)) return false; typeName = customTypeName; return true; } private string GetMemberAccessibility() => _configuration.MemberAccessibility == MemberAccessibility.Internal ? "internal" : "public"; internal bool FilterDeprecatedFields(GraphQlField field) => !field.IsDeprecated || _configuration.IncludeDeprecatedFields; private void GenerateDataProperty( GraphQlType baseType, IGraphQlMember member, bool isInterfaceMember, bool isDeprecated, string deprecationReason, bool decorateWithJsonProperty, WriteDataClassPropertyBodyDelegate writeBody, GenerationContext context) { var propertyName = NamingHelper.ToPascalCase(member.Name); var propertyTypeDescription = GetDataPropertyType(baseType, member); var propertyTypeName = propertyTypeDescription.NetTypeName; var writer = context.Writer; GenerateCodeComments(writer, member.Description, context.Indentation + 4); var indentation = GetIndentation(context.Indentation); if (isDeprecated) { deprecationReason = String.IsNullOrWhiteSpace(deprecationReason) ? null : $"(@\"{deprecationReason.Replace("\"", "\"\"")}\")"; writer.Write(indentation); writer.WriteLine($" [Obsolete{deprecationReason}]"); } if (decorateWithJsonProperty) { decorateWithJsonProperty = _configuration.JsonPropertyGeneration == JsonPropertyGenerationOption.Always || !String.Equals( member.Name, propertyName, _configuration.JsonPropertyGeneration == JsonPropertyGenerationOption.CaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); if (_configuration.JsonPropertyGeneration == JsonPropertyGenerationOption.Never || _configuration.JsonPropertyGeneration == JsonPropertyGenerationOption.UseDefaultAlias) decorateWithJsonProperty = false; } if (!isInterfaceMember && decorateWithJsonProperty) { writer.Write(indentation); writer.Write(" #if !"); writer.WriteLine(PreprocessorDirectiveDisableNewtonsoftJson); writer.Write(indentation); writer.WriteLine($" [JsonProperty(\"{member.Name}\")]"); writer.Write(indentation); writer.WriteLine(" #endif"); } if (baseType.Kind == GraphQlTypeKind.InputObject) { writer.Write(indentation); writer.Write(" #if !"); writer.WriteLine(PreprocessorDirectiveDisableNewtonsoftJson); writer.Write(indentation); writer.WriteLine($" [JsonConverter(typeof(QueryBuilderParameterConverter<{propertyTypeName}>))]"); writer.Write(indentation); writer.WriteLine(" #endif"); propertyTypeName = AddQuestionMarkIfNullableReferencesEnabled($"QueryBuilderParameter<{propertyTypeName}>"); } writer.Write(indentation); writer.Write(" "); if (!isInterfaceMember) writer.Write("public "); writer.Write(propertyTypeName); writer.Write(" "); writer.Write(propertyName); writeBody(new ScalarFieldTypeDescription { NetTypeName = propertyTypeName, FormatMask = propertyTypeDescription.FormatMask }, GetBackingFieldName(member.Name)); writer.WriteLine(); } private ScalarFieldTypeDescription GetDataPropertyType(GraphQlType baseType, IGraphQlMember member) { var fieldType = member.Type.UnwrapIfNonNull(); switch (fieldType.Kind) { case GraphQlTypeKind.Object: case GraphQlTypeKind.Interface: case GraphQlTypeKind.Union: case GraphQlTypeKind.InputObject: var fieldTypeName = fieldType.Name; if (!UseCustomClassNameIfDefined(ref fieldTypeName)) fieldTypeName = NamingHelper.ToPascalCase(fieldTypeName); var propertyType = fieldTypeName + _configuration.ClassPostfix; return ConvertToTypeDescription(AddQuestionMarkIfNullableReferencesEnabled(propertyType)); case GraphQlTypeKind.Enum: return _configuration.CustomScalarFieldTypeMapping(baseType, member.Type, member.Name); case GraphQlTypeKind.List: var itemType = UnwrapListItemType(fieldType, out var netCollectionOpenType); var unwrappedItemType = itemType?.UnwrapIfNonNull(); if (unwrappedItemType == null) throw ListItemTypeResolutionFailedException(baseType.Name, fieldType.Name); var itemTypeName = unwrappedItemType.Name; if (!UseCustomClassNameIfDefined(ref itemTypeName)) itemTypeName = NamingHelper.ToPascalCase(itemTypeName); var netItemType = IsUnknownObjectScalar(baseType, member.Name, itemType) ? "object" : itemTypeName + _configuration.ClassPostfix; var suggestedScalarNetType = ScalarToNetType(baseType, member.Name, itemType).NetTypeName.TrimEnd('?'); if (!String.Equals(suggestedScalarNetType, "object") && !String.Equals(suggestedScalarNetType, "object?") && !suggestedScalarNetType.TrimEnd().EndsWith("System.Object") && !suggestedScalarNetType.TrimEnd().EndsWith("System.Object?")) netItemType = suggestedScalarNetType; if (itemType.Kind != GraphQlTypeKind.NonNull) netItemType = AddQuestionMarkIfNullableReferencesEnabled(netItemType); var netCollectionType = String.Format(netCollectionOpenType, netItemType); return ConvertToTypeDescription(AddQuestionMarkIfNullableReferencesEnabled(netCollectionType)); case GraphQlTypeKind.Scalar: return fieldType.Name switch { GraphQlTypeBase.GraphQlTypeScalarInteger => GetIntegerNetType(baseType, member.Type, member.Name), GraphQlTypeBase.GraphQlTypeScalarString => GetCustomScalarType(baseType, member.Type, member.Name), GraphQlTypeBase.GraphQlTypeScalarFloat => GetFloatNetType(baseType, member.Type, member.Name), GraphQlTypeBase.GraphQlTypeScalarBoolean => ConvertToTypeDescription(GetBooleanNetType(baseType, member.Type, member.Name)), GraphQlTypeBase.GraphQlTypeScalarId => GetIdNetType(baseType, member.Type, member.Name), _ => GetCustomScalarType(baseType, member.Type, member.Name) }; default: return ConvertToTypeDescription(AddQuestionMarkIfNullableReferencesEnabled("string")); } } private string GetBooleanNetType(GraphQlType baseType, GraphQlTypeBase valueType, string valueName) => _configuration.BooleanTypeMapping switch { BooleanTypeMapping.Boolean => "bool?", BooleanTypeMapping.Custom => _configuration.CustomScalarFieldTypeMapping(baseType, valueType, valueName).NetTypeName, _ => throw new InvalidOperationException($"'{_configuration.BooleanTypeMapping}' not supported") }; private ScalarFieldTypeDescription GetFloatNetType(GraphQlType baseType, GraphQlTypeBase valueType, string valueName) => _configuration.FloatTypeMapping switch { FloatTypeMapping.Decimal => ConvertToTypeDescription("decimal?"), FloatTypeMapping.Float => ConvertToTypeDescription("float?"), FloatTypeMapping.Double => ConvertToTypeDescription("double?"), FloatTypeMapping.Custom => _configuration.CustomScalarFieldTypeMapping(baseType, valueType, valueName), _ => throw new InvalidOperationException($"'{_configuration.FloatTypeMapping}' not supported") }; private ScalarFieldTypeDescription GetIntegerNetType(GraphQlType baseType, GraphQlTypeBase valueType, string valueName) => _configuration.IntegerTypeMapping switch { IntegerTypeMapping.Int32 => ConvertToTypeDescription("int?"), IntegerTypeMapping.Int16 => ConvertToTypeDescription("short?"), IntegerTypeMapping.Int64 => ConvertToTypeDescription("long?"), IntegerTypeMapping.Custom => _configuration.CustomScalarFieldTypeMapping(baseType, valueType, valueName), _ => throw new InvalidOperationException($"'{_configuration.IntegerTypeMapping}' not supported") }; private ScalarFieldTypeDescription GetIdNetType(GraphQlType baseType, GraphQlTypeBase valueType, string valueName) => _configuration.IdTypeMapping switch { IdTypeMapping.String => ConvertToTypeDescription(AddQuestionMarkIfNullableReferencesEnabled("string")), IdTypeMapping.Guid => ConvertToTypeDescription("Guid?"), IdTypeMapping.Object => ConvertToTypeDescription(AddQuestionMarkIfNullableReferencesEnabled("object")), IdTypeMapping.Custom => _configuration.CustomScalarFieldTypeMapping(baseType, valueType, valueName), _ => throw new InvalidOperationException($"'{_configuration.IdTypeMapping}' not supported") }; private static InvalidOperationException ListItemTypeResolutionFailedException(string typeName, string fieldName) => FieldTypeResolutionFailedException(typeName, fieldName, "list item type was not resolved; nested collections too deep"); private static InvalidOperationException FieldTypeResolutionFailedException(string typeName, string fieldName, string reason) => new InvalidOperationException($"field type resolution failed - type: {typeName}; field: {fieldName}{(reason == null ? null : "; reason: " + reason)}"); private void GenerateQueryBuilder(GenerationContext context, GraphQlType type, IDictionary<string, GraphQlType> complexTypeDictionary) { var schema = context.Schema; var typeName = type.Name; var useCustomName = UseCustomClassNameIfDefined(ref typeName); var className = (useCustomName ? typeName : NamingHelper.ToPascalCase(typeName)) + "QueryBuilder" + _configuration.ClassPostfix; ValidateClassName(className); context.BeforeQueryBuilderGeneration(className); var writer = context.Writer; var indentation = GetIndentation(context.Indentation); writer.Write(indentation); writer.Write(GetMemberAccessibility()); writer.Write(" "); if (_configuration.GeneratePartialClasses) writer.Write("partial "); writer.Write("class "); writer.Write(className); writer.WriteLine($" : GraphQlQueryBuilder<{className}>"); writer.Write(indentation); writer.WriteLine("{"); writer.Write(indentation); writer.Write(" private static readonly FieldMetadata[] AllFieldMetadata ="); var fields = type.Kind == GraphQlTypeKind.Union ? null : GetFieldsToGenerate(type, complexTypeDictionary); if (fields == null) { writer.WriteLine(" new FieldMetadata[0];"); writer.WriteLine(); } else { writer.WriteLine(); var fieldMetadataIndentation = indentation; if (_configuration.CSharpVersion == CSharpVersion.Compatible) { writer.Write(indentation); writer.WriteLine(" new []"); fieldMetadataIndentation = indentation + " "; } writer.Write(fieldMetadataIndentation); writer.WriteLine(" {"); for (var i = 0; i < fields.Count; i++) { var comma = i == fields.Count - 1 ? null : ","; var field = fields[i]; var fieldType = field.Type.UnwrapIfNonNull(); var isList = fieldType.Kind == GraphQlTypeKind.List; var treatUnknownObjectAsComplex = IsUnknownObjectScalar(type, field.Name, fieldType) && !_configuration.TreatUnknownObjectAsScalar; var isComplex = isList || treatUnknownObjectAsComplex || IsComplexType(fieldType.Kind); writer.Write(fieldMetadataIndentation); writer.Write(" new FieldMetadata { Name = \""); writer.Write(field.Name); writer.Write('"'); var csharpPropertyName = NamingHelper.ToPascalCase(field.Name); if (_configuration.JsonPropertyGeneration == JsonPropertyGenerationOption.UseDefaultAlias && !String.Equals(field.Name, csharpPropertyName, StringComparison.OrdinalIgnoreCase)) { writer.Write(", DefaultAlias = \""); writer.Write(NamingHelper.LowerFirst(csharpPropertyName)); writer.Write('"'); } if (isComplex) { writer.Write(", IsComplex = true"); if (isList) { var itemType = UnwrapListItemType(fieldType, out _)?.UnwrapIfNonNull(); fieldType = itemType ?? throw ListItemTypeResolutionFailedException(type.Name, field.Name); } if (fieldType.Kind != GraphQlTypeKind.Scalar && fieldType.Kind != GraphQlTypeKind.Enum && fieldType.Kind != GraphQlTypeKind.List) { var fieldTypeName = fieldType.Name; if (fieldTypeName == null) throw FieldTypeResolutionFailedException(type.Name, field.Name, null); if (!UseCustomClassNameIfDefined(ref fieldTypeName)) fieldTypeName = NamingHelper.ToPascalCase(fieldTypeName); writer.Write($", QueryBuilderType = typeof({fieldTypeName}QueryBuilder{_configuration.ClassPostfix})"); } } writer.WriteLine($" }}{comma}"); } writer.Write(fieldMetadataIndentation); writer.WriteLine(" };"); writer.WriteLine(); } GraphQlDirectiveLocation directiveLocation; if (type.Name == schema.QueryType?.Name) directiveLocation = GraphQlDirectiveLocation.Query; else if (type.Name == schema.MutationType?.Name) directiveLocation = GraphQlDirectiveLocation.Mutation; else if (type.Name == schema.SubscriptionType?.Name) directiveLocation = GraphQlDirectiveLocation.Subscription; else directiveLocation = GraphQlDirectiveLocation.Field; var hasQueryPrefix = directiveLocation != GraphQlDirectiveLocation.Field; WriteOverrideProperty("protected", "string", "TypeName", $"\"{type.Name}\"", indentation, writer); WriteOverrideProperty("public", "IReadOnlyList<FieldMetadata>", "AllFields", "AllFieldMetadata", indentation, writer); string ReturnPrefix(bool requiresFullBody) => requiresFullBody ? indentation + " return " : String.Empty; var useCompatibleSyntax = _configuration.CSharpVersion == CSharpVersion.Compatible; var stringDataType = AddQuestionMarkIfNullableReferencesEnabled("string"); if (hasQueryPrefix) { writer.Write(indentation); writer.Write(" public "); writer.Write(className); writer.Write("("); writer.Write(stringDataType); writer.Write(" operationName = null) : base(\""); writer.Write(directiveLocation.ToString().ToLowerInvariant()); writer.WriteLine("\", operationName)"); writer.Write(indentation); writer.WriteLine(" {"); writer.Write(indentation); writer.WriteLine(" }"); writer.WriteLine(); writer.Write(indentation); writer.Write($" public {className} WithParameter<T>(GraphQlQueryParameter<T> parameter)"); WriteQueryBuilderMethodBody( useCompatibleSyntax, indentation, writer, () => writer.WriteLine($"{ReturnPrefix(useCompatibleSyntax)}WithParameterInternal(parameter);")); writer.WriteLine(); } var fragments = GetFragments(type, complexTypeDictionary); fields ??= new List<GraphQlField>(); var firstFragmentIndex = fields.Count; fields.AddRange(fragments); for (var i = 0; i < fields.Count; i++) { var field = fields[i]; var fieldType = field.Type.UnwrapIfNonNull(); if (fieldType.Kind == GraphQlTypeKind.List) fieldType = fieldType.OfType; fieldType = fieldType.UnwrapIfNonNull(); var isFragment = i >= firstFragmentIndex; static bool IsCompatibleArgument(GraphQlFieldType argumentType) { argumentType = argumentType.UnwrapIfNonNull(); return argumentType.Kind switch { GraphQlTypeKind.Scalar => true, GraphQlTypeKind.Enum => true, GraphQlTypeKind.InputObject => true, GraphQlTypeKind.List => IsCompatibleArgument(argumentType.OfType), _ => false }; } var argumentDefinitions = field.Args?.Where(a => IsCompatibleArgument(a.Type)).Select(a => BuildMethodParameterDefinition(type, a)).ToArray() ?? new QueryBuilderParameterDefinition[0]; var methodParameters = String.Join( ", ", argumentDefinitions .OrderByDescending(d => d.Argument.Type.Kind == GraphQlTypeKind.NonNull) .Select(d => d.NetParameterDefinitionClause)); var requiresFullBody = useCompatibleSyntax || argumentDefinitions.Any(); var returnPrefix = ReturnPrefix(requiresFullBody); var csharpPropertyName = NamingHelper.ToPascalCase(field.Name); void WriteAliasParameter() { writer.Write(stringDataType); writer.Write(" alias = "); if (_configuration.JsonPropertyGeneration == JsonPropertyGenerationOption.UseDefaultAlias && !String.Equals(field.Name, csharpPropertyName, StringComparison.OrdinalIgnoreCase)) { writer.Write('"'); writer.Write(NamingHelper.LowerFirst(csharpPropertyName)); writer.Write('"'); } else writer.Write("null"); } if (fieldType.Kind == GraphQlTypeKind.Scalar || fieldType.Kind == GraphQlTypeKind.Enum || fieldType.Kind == GraphQlTypeKind.List) { writer.Write(indentation); writer.Write(" public "); writer.Write(className); writer.Write(" With"); writer.Write(csharpPropertyName); writer.Write("("); writer.Write(methodParameters); if (!String.IsNullOrEmpty(methodParameters)) writer.Write(", "); WriteAliasParameter(); var fieldDirectiveParameterNameList = WriteDirectiveParameterList(schema, GraphQlDirectiveLocation.Field, writer); writer.Write(")"); WriteQueryBuilderMethodBody( requiresFullBody, indentation, writer, () => { AppendArgumentDictionary(indentation, writer, argumentDefinitions); writer.Write(returnPrefix); writer.Write("WithScalarField(\""); writer.Write(field.Name); writer.Write("\", alias, "); writer.Write(fieldDirectiveParameterNameList); if (argumentDefinitions.Length > 0) writer.Write(", args"); writer.WriteLine(");"); }); } else { var fieldTypeName = fieldType.Name; if (String.IsNullOrEmpty(fieldTypeName)) throw FieldTypeResolutionFailedException(type.Name, field.Name, null); if (!UseCustomClassNameIfDefined(ref fieldTypeName)) fieldTypeName = NamingHelper.ToPascalCase(fieldTypeName); var builderParameterName = NamingHelper.LowerFirst(fieldTypeName); writer.Write(indentation); writer.Write($" public {className} With{csharpPropertyName}{(isFragment ? "Fragment" : null)}({fieldTypeName}QueryBuilder{_configuration.ClassPostfix} {builderParameterName}QueryBuilder"); if (argumentDefinitions.Length > 0) { writer.Write(", "); writer.Write(methodParameters); } if (!isFragment) { writer.Write(", "); WriteAliasParameter(); } var fieldDirectiveParameterNameList = WriteDirectiveParameterList(schema, GraphQlDirectiveLocation.Field, writer); writer.Write(")"); WriteQueryBuilderMethodBody( requiresFullBody, indentation, writer, () => { AppendArgumentDictionary(indentation, writer, argumentDefinitions); writer.Write(returnPrefix); writer.Write("With"); if (isFragment) writer.Write("Fragment("); else { writer.Write("ObjectField(\""); writer.Write(field.Name); writer.Write("\", alias, "); } writer.Write(builderParameterName); writer.Write("QueryBuilder"); writer.Write(", "); writer.Write(fieldDirectiveParameterNameList); if (argumentDefinitions.Length > 0) writer.Write(", args"); writer.WriteLine(");"); }); } if (!isFragment) { writer.WriteLine(); writer.Write(indentation); writer.Write($" public {className} Except{csharpPropertyName}()"); WriteQueryBuilderMethodBody( useCompatibleSyntax, indentation, writer, () => writer.WriteLine($"{ReturnPrefix(useCompatibleSyntax)}ExceptField(\"{field.Name}\");")); } if (i < fields.Count - 1) writer.WriteLine(); } writer.Write(indentation); writer.WriteLine("}"); context.AfterQueryBuilderGeneration(className); } private GraphQlFieldType UnwrapListItemType(GraphQlFieldType type, out string netCollectionOpenType) { var levels = 0; var nullableSymbols = new List<string> { String.Empty }; while (true) { levels++; var unwrappedType = type.OfType?.UnwrapIfNonNull(); if (unwrappedType == null) { netCollectionOpenType = null; return null; } if (unwrappedType.Kind != GraphQlTypeKind.List) { type = type.OfType; break; } nullableSymbols.Add(type.OfType.Kind == GraphQlTypeKind.NonNull ? String.Empty : AddQuestionMarkIfNullableReferencesEnabled(String.Empty)); type = unwrappedType; } nullableSymbols.Reverse(); netCollectionOpenType = levels == 1 ? "ICollection<{0}>" : String.Concat(Enumerable.Repeat("IList<", levels).Concat(new[] { "{0}" }).Concat(nullableSymbols.Select(s => ">" + s))); return type; } private string WriteDirectiveParameterList(GraphQlSchema schema, GraphQlDirectiveLocation directiveLocation, TextWriter writer) { var directiveParameterNames = new List<string>(); foreach (var directive in schema.Directives.Where(d => d.Locations.Contains(directiveLocation))) { var csharpDirectiveName = NamingHelper.ToPascalCase(directive.Name); var directiveClassName = csharpDirectiveName + "Directive"; var parameterName = NamingHelper.LowerFirst(csharpDirectiveName); directiveParameterNames.Add(parameterName); writer.Write(", "); writer.Write(AddQuestionMarkIfNullableReferencesEnabled(directiveClassName)); writer.Write(" "); writer.Write(parameterName); writer.Write(" = null"); } return directiveParameterNames.Any() ? "new " + AddQuestionMarkIfNullableReferencesEnabled("GraphQlDirective") + "[] { " + String.Join(", ", directiveParameterNames) + " }" : "null"; } private static void WriteQueryBuilderMethodBody(bool requiresFullBody, string indentation, TextWriter writer, Action writeBody) { if (requiresFullBody) { writer.WriteLine(); writer.Write(indentation); writer.WriteLine(" {"); } else writer.Write(" => "); writeBody(); if (requiresFullBody) { writer.Write(indentation); writer.WriteLine(" }"); } } private void WriteOverrideProperty(string accessibility, string propertyType, string propertyName, string propertyValue, string indentation, TextWriter writer) { writer.Write(indentation); writer.Write(" "); writer.Write(accessibility); writer.Write(" override "); writer.Write(propertyType); writer.Write(" "); writer.Write(propertyName); writer.Write(" { get"); if (_configuration.CSharpVersion == CSharpVersion.Compatible) { writer.Write(" { return "); writer.Write(propertyValue); writer.WriteLine("; } } "); } else { writer.Write("; } = "); writer.Write(propertyValue); writer.WriteLine(";"); } writer.WriteLine(); } private QueryBuilderParameterDefinition BuildMethodParameterDefinition(GraphQlType baseType, GraphQlArgument argument) { var argumentType = argument.Type; var isArgumentNotNull = argumentType.Kind == GraphQlTypeKind.NonNull; var isTypeNotNull = isArgumentNotNull; var unwrappedType = argumentType.UnwrapIfNonNull(); var isCollection = unwrappedType.Kind == GraphQlTypeKind.List; if (isCollection) { isTypeNotNull = unwrappedType.OfType.Kind == GraphQlTypeKind.NonNull; argumentType = unwrappedType.OfType; unwrappedType = argumentType.UnwrapIfNonNull(); } var argumentTypeDescription = unwrappedType.Kind == GraphQlTypeKind.Enum ? ConvertToTypeDescription(NamingHelper.ToPascalCase(unwrappedType.Name) + "?") : ScalarToNetType(baseType, argument.Name, argumentType); var argumentNetType = argumentTypeDescription.NetTypeName; if (isTypeNotNull) argumentNetType = argumentNetType.TrimEnd('?'); var isInputObject = unwrappedType.Kind == GraphQlTypeKind.InputObject; if (isInputObject) { argumentNetType = unwrappedType.Name; if (!UseCustomClassNameIfDefined(ref argumentNetType)) argumentNetType = NamingHelper.ToPascalCase(argumentNetType); argumentNetType += _configuration.ClassPostfix; if (!isTypeNotNull) argumentNetType = AddQuestionMarkIfNullableReferencesEnabled(argumentNetType); } argumentNetType = isCollection ? $"QueryBuilderParameter<IEnumerable<{argumentNetType}>>" : $"QueryBuilderParameter<{argumentNetType}>"; if (!isArgumentNotNull) argumentNetType = AddQuestionMarkIfNullableReferencesEnabled(argumentNetType); var netParameterName = NamingHelper.ToValidCSharpName(NamingHelper.LowerFirst(NamingHelper.ToPascalCase(argument.Name))); var argumentDefinition = $"{argumentNetType} {netParameterName}"; if (!isArgumentNotNull) argumentDefinition += " = null"; return new QueryBuilderParameterDefinition { Argument = argument, NetParameterName = netParameterName, NetParameterDefinitionClause = argumentDefinition, FormatMask = argumentTypeDescription.FormatMask }; } private static void ValidateClassName(string className) { if (!CSharpHelper.IsValidIdentifier(className)) throw new InvalidOperationException($"Resulting class name '{className}' is not valid. "); } private static void AppendArgumentDictionary(string indentation, TextWriter writer, ICollection<QueryBuilderParameterDefinition> argumentDefinitions) { if (argumentDefinitions.Count == 0) return; writer.Write(indentation); writer.WriteLine(" var args = new List<QueryBuilderArgumentInfo>();"); static void WriteAddKeyValuePair(TextWriter writer, QueryBuilderParameterDefinition argumentDefinition) { var argument = argumentDefinition.Argument; writer.Write("args.Add(new QueryBuilderArgumentInfo { ArgumentName = \""); writer.Write(argument.Name); writer.Write("\", ArgumentValue = "); writer.Write(argumentDefinition.NetParameterName); if (!String.IsNullOrEmpty(argumentDefinition.FormatMask)) { writer.Write(", FormatMask = \""); writer.Write(argumentDefinition.FormatMask.Replace("\"", "\\\"")); writer.Write("\""); } writer.WriteLine("} );"); } foreach (var argumentDefinition in argumentDefinitions) { writer.Write(indentation); if (argumentDefinition.Argument.Type.Kind == GraphQlTypeKind.NonNull) { writer.Write(" "); WriteAddKeyValuePair(writer, argumentDefinition); } else { writer.Write(" if ("); writer.Write(argumentDefinition.NetParameterName); writer.WriteLine(" != null)"); writer.Write(indentation); writer.Write(" "); WriteAddKeyValuePair(writer, argumentDefinition); writer.WriteLine(); } } } private void GenerateEnum(GenerationContext context, GraphQlType type) { var enumName = NamingHelper.ToPascalCase(type.Name); context.BeforeEnumGeneration(enumName); var writer = context.Writer; GenerateCodeComments(writer, type.Description, context.Indentation); var indentation = GetIndentation(context.Indentation); writer.Write(indentation); writer.Write("public enum "); writer.WriteLine(enumName); writer.Write(indentation); writer.WriteLine("{"); var enumValues = type.EnumValues.ToList(); for (var i = 0; i < enumValues.Count; i++) { var enumValue = enumValues[i]; GenerateCodeComments(writer, enumValue.Description, context.Indentation + 4); writer.Write(indentation); writer.Write(" "); var netIdentifier = NamingHelper.ToCSharpEnumName(enumValue.Name); if (netIdentifier != enumValue.Name) writer.Write($"[EnumMember(Value = \"{enumValue.Name}\")] "); writer.Write(netIdentifier); if (i < enumValues.Count - 1) writer.Write(","); writer.WriteLine(); } writer.Write(indentation); writer.WriteLine("}"); context.AfterEnumGeneration(enumName); } private static readonly HashSet<GraphQlDirectiveLocation> SupportedDirectiveLocations = new HashSet<GraphQlDirectiveLocation> { GraphQlDirectiveLocation.Object, GraphQlDirectiveLocation.Field, GraphQlDirectiveLocation.Query, GraphQlDirectiveLocation.Mutation, GraphQlDirectiveLocation.Subscription }; private void GenerateDirectives(GenerationContext context) { if (IsQueryBuilderGenerationDisabled(context.ObjectTypes)) return; var queryBuilderDirectives = context.Schema.Directives.Where(t => SupportedDirectiveLocations.Overlaps(t.Locations)).ToList(); if (!queryBuilderDirectives.Any()) return; context.BeforeDirectivesGeneration(); queryBuilderDirectives.ForEach(d => GenerateDirective(context, d)); context.AfterDirectivesGeneration(); } private void GenerateDirective(GenerationContext context, GraphQlDirective directive) { var directiveName = NamingHelper.ToPascalCase(directive.Name) + "Directive"; context.BeforeDirectiveGeneration(directiveName); var writer = context.Writer; GenerateCodeComments(writer, directive.Description, context.Indentation); var orderedArgumentDefinitions = directive.Args.OrderByDescending(a => a.Type.Kind == GraphQlTypeKind.NonNull).Select(a => BuildMethodParameterDefinition(null, a)).ToArray(); var argumentList = String.Join(", ", orderedArgumentDefinitions.Select(d => d.NetParameterDefinitionClause)); var indentation = GetIndentation(context.Indentation); writer.Write(indentation); writer.Write("public class "); writer.Write(directiveName); writer.WriteLine(" : GraphQlDirective"); writer.Write(indentation); writer.WriteLine("{"); writer.Write(indentation); writer.Write(" public "); writer.Write(directiveName); writer.Write("("); writer.Write(argumentList); writer.Write(") : base(\""); writer.Write(directive.Name); writer.WriteLine("\")"); writer.Write(indentation); writer.WriteLine(" {"); foreach (var definition in orderedArgumentDefinitions) { writer.Write(indentation); writer.Write(" AddArgument(\""); writer.Write(definition.Argument.Name); writer.Write("\", "); writer.Write(NamingHelper.ToValidCSharpName(definition.Argument.Name)); writer.WriteLine(");"); } writer.Write(indentation); writer.WriteLine(" }"); writer.Write(indentation); writer.WriteLine("}"); context.AfterDirectiveGeneration(directiveName); } private void GenerateCodeComments(TextWriter writer, string description, int indentationSize) { if (String.IsNullOrWhiteSpace(description)) return; var indentation = GetIndentation(indentationSize); if (_configuration.CommentGeneration.HasFlag(CommentGenerationOption.CodeSummary)) { writer.Write(indentation); writer.WriteLine("/// <summary>"); writer.Write(indentation); writer.WriteLine("/// " + String.Join(Environment.NewLine + indentation + "/// ", description.Split('\n').Select(l => l.Trim()))); writer.Write(indentation); writer.WriteLine("/// </summary>"); } if (_configuration.CommentGeneration.HasFlag(CommentGenerationOption.DescriptionAttribute)) { writer.Write(indentation); writer.WriteLine($"[Description(@\"{description.Replace("\"", "\"\"")}\")]"); } } private bool IsUnknownObjectScalar(GraphQlType baseType, string valueName, GraphQlFieldType fieldType) { if (fieldType.UnwrapIfNonNull().Kind != GraphQlTypeKind.Scalar) return false; var netType = ScalarToNetType(baseType, valueName, fieldType).NetTypeName; return netType == "object" || netType.TrimEnd().EndsWith("System.Object") || netType == "object?" || netType.TrimEnd().EndsWith("System.Object?"); } private ScalarFieldTypeDescription ScalarToNetType(GraphQlType baseType, string valueName, GraphQlFieldType valueType) => valueType.UnwrapIfNonNull().Name switch { GraphQlTypeBase.GraphQlTypeScalarInteger => GetIntegerNetType(baseType, valueType, valueName), GraphQlTypeBase.GraphQlTypeScalarString => GetCustomScalarType(baseType, valueType, valueName), GraphQlTypeBase.GraphQlTypeScalarFloat => GetFloatNetType(baseType, valueType, valueName), GraphQlTypeBase.GraphQlTypeScalarBoolean => ConvertToTypeDescription(GetBooleanNetType(baseType, valueType, valueName)), GraphQlTypeBase.GraphQlTypeScalarId => GetIdNetType(baseType, valueType, valueName), _ => GetCustomScalarType(baseType, valueType, valueName) }; private ScalarFieldTypeDescription GetCustomScalarType(GraphQlType baseType, GraphQlTypeBase valueType, string valueName) { if (_configuration.CustomScalarFieldTypeMapping == null) throw new InvalidOperationException($"'{nameof(_configuration.CustomScalarFieldTypeMapping)}' missing"); var typeDescription = _configuration.CustomScalarFieldTypeMapping(baseType, valueType, valueName); if (String.IsNullOrWhiteSpace(typeDescription.NetTypeName)) throw new InvalidOperationException($".NET type for '{baseType.Name}.{valueName}' ({valueType.Name}) cannot be resolved. Please check {nameof(_configuration)}.{nameof(_configuration.CustomScalarFieldTypeMapping)} implementation. "); if (typeDescription.FormatMask != null && String.IsNullOrWhiteSpace(typeDescription.FormatMask)) throw new InvalidOperationException("invalid format mask"); return typeDescription; } private static ScalarFieldTypeDescription ConvertToTypeDescription(string netTypeName) => new ScalarFieldTypeDescription { NetTypeName = netTypeName }; private struct QueryBuilderParameterDefinition { public GraphQlArgument Argument; public string NetParameterName; public string NetParameterDefinitionClause; public string FormatMask; } } }
45.469111
249
0.556035
[ "MIT" ]
Serge-Eng/GraphQlClientGenerator
src/GraphQlClientGenerator/GraphQlGenerator.cs
66,976
C#
namespace EconProject.CurrencyWebService { public class ServiceSettings { public string ExchangeRateApiUrl { get; set; } public ServiceSettings() { } } }
15.461538
54
0.60199
[ "Apache-2.0" ]
Vasar007/EconProject
CurrencyWebService/ServiceSettings.cs
203
C#
using NetStack.Serialization; public struct ServerGrantedIdCommand : ICommand, IServerCommand { public System.UInt16 Id; public void Serialize(BitBuffer bitBuffer) { bitBuffer.AddUShort(1); bitBuffer.AddUShort(Id); } public void Deserialize(BitBuffer bitBuffer) { Id = bitBuffer.ReadUShort(); } }
18.647059
63
0.750789
[ "MIT" ]
RomanZhu/Entitas-Sync-Framework
Assets/Sources/Generated/Command/Server/GrantedIdCommand.cs
317
C#
// MonoGame - Copyright (C) The MonoGame Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using System; namespace MonoGame.Tests.Components { class PixelDeltaFrameComparer : IFrameComparer { private static int[] GreyScale(FramePixelData pixelData, int newWidth, int newHeight) { var resized = new int[newWidth * newHeight]; var stepX = pixelData.Width / (float)newWidth; var stepY = pixelData.Height / (float)newHeight; for (var y = 0; y < newHeight; y++) { for (var x = 0; x < newWidth; x++) { // We use a simple nearest neighbor sample as any blending // would only serve to increase the differences between the images. var sx = (int)(x * stepX); var sy = (int)(y * stepY); var si = sx + (sy * pixelData.Width); var scolor = pixelData.Data[si]; // Convert to a greyscale value which removes small // color differences that the eye cannot spot. var grayScale = (int)((scolor.R * 0.3) + (scolor.G * 0.59) + (scolor.B * 0.11)); var di = x + (y * newWidth); resized[di] = grayScale; } } return resized; } public float Compare(FramePixelData image, FramePixelData referenceImage) { // Conver the images down to a common sized greyscale image. var width = Math.Min(image.Width, referenceImage.Width); var height = Math.Min(image.Height, referenceImage.Height); var img = GreyScale(image, width, height); var imgRef = GreyScale(referenceImage, width, height); // Find the differences between the greyscale images. var absDiff = new int[width * height]; for (var i = 0; i < absDiff.Length; i++) absDiff[i] = Math.Abs(img[i] - imgRef[i]); // Find all the differences over the threshold. const int threshold = 3; var diffPixels = 0; for (var i = 0; i < absDiff.Length; i++) { if (absDiff[i] > threshold) diffPixels++; } // Calculate the difference percentage. var diff = diffPixels / (float)absDiff.Length; return 1.0f - diff; } } }
36.521127
100
0.527189
[ "MIT" ]
06needhamt/MonoGame
Test/Framework/Components/PixelDeltaFrameComparer.cs
2,595
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Threading; using osu.Framework.Allocation; using osu.Framework.Extensions.PolygonExtensions; using osu.Framework.Graphics.Primitives; using osu.Framework.Layout; using osu.Framework.Threading; namespace osu.Framework.Graphics.Containers { /// <summary> /// A container which asynchronously loads specified content. /// Has the ability to delay the loading until it has been visible on-screen for a specified duration. /// In order to benefit from delayed load, we must be inside a <see cref="ScrollContainer{T}"/>. /// </summary> public class DelayedLoadWrapper : CompositeDrawable { [Resolved] protected Game Game { get; private set; } private readonly Func<Drawable> createFunc; /// <summary> /// Creates a <see cref="Container"/> that will asynchronously load the given <see cref="Drawable"/> with a delay. /// </summary> /// <remarks>If <see cref="timeBeforeLoad"/> is set to 0, the loading process will begin on the next Update call.</remarks> /// <param name="content">The <see cref="Drawable"/> to be loaded.</param> /// <param name="timeBeforeLoad">The delay in milliseconds before loading can begin.</param> public DelayedLoadWrapper(Drawable content, double timeBeforeLoad = 500) : this(timeBeforeLoad) { Content = content ?? throw new ArgumentNullException(nameof(content), $@"{nameof(DelayedLoadWrapper)} required non-null {nameof(content)}."); } /// <summary> /// Creates a <see cref="Container"/> that will asynchronously load the given <see cref="Drawable"/> with a delay. /// This constructor is preferred due to avoiding construction of the loadable content until a load is actually triggered. /// </summary> /// <remarks>If <see cref="timeBeforeLoad"/> is set to 0, the loading process will begin on the next Update call.</remarks> /// <param name="createFunc">A function which created future content.</param> /// <param name="timeBeforeLoad">The delay in milliseconds before loading can begin.</param> public DelayedLoadWrapper(Func<Drawable> createFunc, double timeBeforeLoad = 500) : this(timeBeforeLoad) { this.createFunc = createFunc; } private DelayedLoadWrapper(double timeBeforeLoad) { this.timeBeforeLoad = timeBeforeLoad; AddLayout(optimisingContainerCache); AddLayout(isIntersectingCache); } private Drawable content; public Drawable Content { get => content; protected set { if (content == value) return; content = value; if (content == null) return; AutoSizeAxes = Axes.None; RelativeSizeAxes = Axes.None; RelativeSizeAxes = content.RelativeSizeAxes; AutoSizeAxes = (content as CompositeDrawable)?.AutoSizeAxes ?? AutoSizeAxes; } } /// <summary> /// The amount of time on-screen in milliseconds before we begin a load of children. /// </summary> private readonly double timeBeforeLoad; private double timeVisible; protected virtual bool ShouldLoadContent => timeVisible > timeBeforeLoad; private CancellationTokenSource cancellationTokenSource; private ScheduledDelegate scheduledAddition; protected override void Update() { base.Update(); // This code can be expensive, so only run if we haven't yet loaded. if (DelayedLoadCompleted || DelayedLoadTriggered) return; if (!IsIntersecting) timeVisible = 0; else timeVisible += Time.Elapsed; if (ShouldLoadContent) BeginDelayedLoad(); } protected void BeginDelayedLoad() { if (DelayedLoadTriggered || DelayedLoadCompleted) throw new InvalidOperationException("Load has already started!"); Content ??= createFunc(); DelayedLoadTriggered = true; DelayedLoadStarted?.Invoke(Content); cancellationTokenSource = new CancellationTokenSource(); // The callback is run on the game's scheduler since DelayedLoadUnloadWrapper needs to unload when no updates are being received. LoadComponentAsync(Content, EndDelayedLoad, scheduler: Game.Scheduler, cancellation: cancellationTokenSource.Token); } protected virtual void EndDelayedLoad(Drawable content) { timeVisible = 0; // This code is running on the game's scheduler, while this wrapper may have been async disposed, so the addition is scheduled locally to prevent adding to disposed wrappers. scheduledAddition = Schedule(() => { AddInternal(content); DelayedLoadCompleted = true; DelayedLoadComplete?.Invoke(content); }); } internal override void UnbindAllBindables() { base.UnbindAllBindables(); CancelTasks(); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); CancelTasks(); } protected virtual void CancelTasks() { isIntersectingCache.Invalidate(); cancellationTokenSource?.Cancel(); cancellationTokenSource = null; scheduledAddition?.Cancel(); scheduledAddition = null; } /// <summary> /// Fired when delayed async load has started. /// </summary> public event Action<Drawable> DelayedLoadStarted; /// <summary> /// Fired when delayed async load completes. Should be used to perform transitions. /// </summary> public event Action<Drawable> DelayedLoadComplete; /// <summary> /// True if the load task for our content has been started. /// Will remain true even after load is completed. /// </summary> protected bool DelayedLoadTriggered; /// <summary> /// True if the content has been added to the drawable hierarchy. /// </summary> public bool DelayedLoadCompleted { get; protected set; } private readonly LayoutValue optimisingContainerCache = new LayoutValue(Invalidation.Parent); private readonly LayoutValue isIntersectingCache = new LayoutValue(Invalidation.All); private ScheduledDelegate isIntersectingResetDelegate; protected bool IsIntersecting { get; private set; } internal IOnScreenOptimisingContainer OptimisingContainer { get; private set; } internal IOnScreenOptimisingContainer FindParentOptimisingContainer() => FindClosestParent<IOnScreenOptimisingContainer>(); protected override bool OnInvalidate(Invalidation invalidation, InvalidationSource source) { bool result = base.OnInvalidate(invalidation, source); // For every invalidation, we schedule a reset of IsIntersecting to the game. // This is done since UpdateSubTreeMasking() may not be invoked in the current frame, as a result of presence/masking changes anywhere in our super-tree. // It is important that this is scheduled such that it occurs on the NEXT frame, in order to give this wrapper a chance to load its contents. // For example, if a parent invalidated this wrapper every frame, IsIntersecting would be false by the time Update() is run and may only become true at the very end of the frame. // The scheduled delegate will be cancelled if this wrapper has its UpdateSubTreeMasking() invoked, as more accurate intersections can be computed there instead. if (isIntersectingResetDelegate == null) { isIntersectingResetDelegate = Game?.Scheduler.AddDelayed(wrapper => wrapper.IsIntersecting = false, this, 0); result = true; } return result; } public override bool UpdateSubTreeMasking(Drawable source, RectangleF maskingBounds) { bool result = base.UpdateSubTreeMasking(source, maskingBounds); // We can accurately compute intersections - the scheduled reset is no longer required. isIntersectingResetDelegate?.Cancel(); isIntersectingResetDelegate = null; if (!isIntersectingCache.IsValid) { if (!optimisingContainerCache.IsValid) { OptimisingContainer = FindParentOptimisingContainer(); optimisingContainerCache.Validate(); } // The first condition is an intersection against the hierarchy, including any parents that may be masking this wrapper. // It is the same calculation as Drawable.IsMaskedAway, however IsMaskedAway is optimised out for some CompositeDrawables (which this wrapper is). // The second condition is an exact intersection against the optimising container, which further optimises rotated AABBs where the wrapper content is not visible. IsIntersecting = maskingBounds.IntersectsWith(ScreenSpaceDrawQuad.AABBFloat) && OptimisingContainer?.ScreenSpaceDrawQuad.Intersects(ScreenSpaceDrawQuad) != false; isIntersectingCache.Validate(); } return result; } /// <summary> /// A container which acts as a masking parent for on-screen delayed load optimisations. /// </summary> internal interface IOnScreenOptimisingContainer : IDrawable { } } }
41.947581
191
0.620494
[ "MIT" ]
Pizzabelly/osu-framework
osu.Framework/Graphics/Containers/DelayedLoadWrapper.cs
10,158
C#
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Globalization; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Converters { /// <summary> /// Converts a <see cref="DateTime"/> to and from the ISO 8601 date format (e.g. <c>"2008-04-12T12:53Z"</c>). /// </summary> public class IsoDateTimeConverter : DateTimeConverterBase { private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind; private string? _dateTimeFormat; private CultureInfo? _culture; /// <summary> /// Gets or sets the date time styles used when converting a date to and from JSON. /// </summary> /// <value>The date time styles used when converting a date to and from JSON.</value> public DateTimeStyles DateTimeStyles { get => _dateTimeStyles; set => _dateTimeStyles = value; } /// <summary> /// Gets or sets the date time format used when converting a date to and from JSON. /// </summary> /// <value>The date time format used when converting a date to and from JSON.</value> public string? DateTimeFormat { get => _dateTimeFormat ?? string.Empty; set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value; } /// <summary> /// Gets or sets the culture used when converting a date to and from JSON. /// </summary> /// <value>The culture used when converting a date to and from JSON.</value> public CultureInfo Culture { get => _culture ?? CultureInfo.CurrentCulture; set => _culture = value; } /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param> /// <param name="value">The value.</param> /// <param name="serializer">The calling serializer.</param> public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { string text; if (value is DateTime dateTime) { if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal) { dateTime = dateTime.ToUniversalTime(); } text = dateTime.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture); } #if HAVE_DATE_TIME_OFFSET else if (value is DateTimeOffset dateTimeOffset) { if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal) { dateTimeOffset = dateTimeOffset.ToUniversalTime(); } text = dateTimeOffset.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture); } #endif else { throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value)!)); } writer.WriteValue(text); } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { bool nullable = ReflectionUtils.IsNullableType(objectType); if (reader.TokenType == JsonToken.Null) { if (!nullable) { throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); } return null; } #if HAVE_DATE_TIME_OFFSET Type t = (nullable) ? Nullable.GetUnderlyingType(objectType) : objectType; #endif if (reader.TokenType == JsonToken.Date) { #if HAVE_DATE_TIME_OFFSET if (t == typeof(DateTimeOffset)) { return (reader.Value is DateTimeOffset) ? reader.Value : new DateTimeOffset((DateTime)reader.Value!); } // converter is expected to return a DateTime if (reader.Value is DateTimeOffset offset) { return offset.DateTime; } #endif return reader.Value; } if (reader.TokenType != JsonToken.String) { throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } string? dateText = reader.Value?.ToString(); if (string.IsNullOrEmpty(dateText) && nullable) { return null; } #if HAVE_DATE_TIME_OFFSET if (t == typeof(DateTimeOffset)) { if (!string.IsNullOrEmpty(_dateTimeFormat)) { return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles); } else { return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles); } } #endif if (!string.IsNullOrEmpty(_dateTimeFormat)) { return DateTime.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles); } else { return DateTime.Parse(dateText, Culture, _dateTimeStyles); } } } }
39.107692
221
0.601495
[ "MIT" ]
SeppPenner/Newtonsoft.Json
Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs
7,628
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace HelloTabs { [Activity (Label = "Activity3")] public class Activity3 : Activity { protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); TextView textview = new TextView (this); textview.Text = "This is the activity under tab 2"; SetContentView (textview); } } }
21.206897
63
0.634146
[ "Apache-2.0" ]
Dmitiry-hub/monodroid-samples
PlatformFeatures/ICS_Samples/HelloTabs/HelloTabs/Activity3.cs
615
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using dosymep.Bim4Everyone; namespace PlatformSettings.SharedParams { public abstract class RevitParams { public string Name { get; set; } public string KeyName { get; set; } public string ConfigFileName { get; set; } public abstract RevitParamsConfig GetConfig(); public string GetConfigPath() { string sharedParamsPath = pyRevitLabs.PyRevit.PyRevitConfigs.GetConfigFile().GetValue("PlatformSettings", KeyName); return string.IsNullOrEmpty(sharedParamsPath) ? null : new System.IO.FileInfo(sharedParamsPath.Trim('\"')).FullName; } public void SaveSettings(RevitParamsConfig revitParamsConfig, string configPath) { if(!string.IsNullOrEmpty(configPath)) { revitParamsConfig.Save(configPath); pyRevitLabs.PyRevit.PyRevitConfigs.GetConfigFile().SetValue("PlatformSettings", KeyName, $"\"{configPath}\""); } } } }
36.133333
128
0.682657
[ "MIT" ]
dosymep/RevitPlugins
PlatformSettings/SharedParams/RevitParams.cs
1,086
C#
using System; using Eto.Forms; using Eto.Drawing; using Eto.Designer; namespace Eto.Addin.Shared { public class ProjectWizardPageView : BasePageView { Label HeadingLabel(string text) { return new Label { Text = text, VerticalAlignment = VerticalAlignment.Center, TextAlignment = TextAlignment.Right }; } public ProjectWizardPageView(ProjectWizardPageModel model) { var radioSpacing = Platform.IsGtk ? Size.Empty : new Size(2, 2); var content = new DynamicLayout { Spacing = new Size(10, 10) }; if (model.SupportsAppName) { var nameBox = new TextBox(); nameBox.TextBinding.BindDataContext((ProjectWizardPageModel m) => m.AppName); Application.Instance.AsyncInvoke(nameBox.Focus); var nameValid = new Label { TextColor = Global.Theme.ErrorForeground }; nameValid.BindDataContext(c => c.Visible, (ProjectWizardPageModel m) => m.AppNameInvalid); nameValid.BindDataContext(c => c.Text, (ProjectWizardPageModel m) => m.AppNameValidationText); content.BeginHorizontal(); content.Add(HeadingLabel((model.IsLibrary ? "Library" : "App") + " Name:")); content.AddColumn(nameBox, nameValid); content.EndHorizontal(); } else if (!string.IsNullOrEmpty(model.AppName)) { var label = new Label { Text = model.AppName, VerticalAlignment = VerticalAlignment.Center }; content.AddRow(HeadingLabel((model.IsLibrary ? "Library" : "App") + " Name:"), label); } if (model.SupportsFramework) { var frameworkDropDown = new DropDown(); frameworkDropDown.BindDataContext(c => c.DataStore, (ProjectWizardPageModel m) => m.SupportedFrameworks); frameworkDropDown.ItemTextBinding = Binding.Property((ProjectWizardPageModel.FrameworkInfo i) => i.Text); frameworkDropDown.ItemKeyBinding = Binding.Property((ProjectWizardPageModel.FrameworkInfo i) => i.Value); frameworkDropDown.SelectedValueBinding.BindDataContext((ProjectWizardPageModel m) => m.SelectedFramework); /* var frameworkCheckBoxes = new CheckBoxList(); frameworkCheckBoxes.BindDataContext(c => c.DataStore, (ProjectWizardPageModel m) => m.SupportedFrameworks); frameworkCheckBoxes.ItemTextBinding = Binding.Property((ProjectWizardPageModel.FrameworkInfo i) => i.Text); frameworkCheckBoxes.ItemKeyBinding = Binding.Property((ProjectWizardPageModel.FrameworkInfo i) => i.Value); frameworkCheckBoxes.SelectedValuesBinding.BindDataContext((ProjectWizardPageModel m) => m.SelectedFrameworks); */ content.AddRow(HeadingLabel("Framework:"), frameworkDropDown); } if (model.SupportsCombined) { var platformTypeList = new RadioButtonList { Orientation = Orientation.Vertical, Spacing = radioSpacing, Items = { new ListItem { Text = "Separate projects for each platform", Key = "separate" }, new ListItem { Text = "Single Windows, Linux, and Mac desktop project", Key = "combined" } } }; platformTypeList.BindDataContext(c => c.Visible, (ProjectWizardPageModel m) => m.AllowCombined); platformTypeList.SelectedKeyBinding .Convert(v => v == "combined", v => v ? "combined" : "separate") .BindDataContext((ProjectWizardPageModel m) => m.Combined); var heading = HeadingLabel("Launcher:"); heading.BindDataContext(c => c.Visible, (ProjectWizardPageModel m) => m.AllowCombined); content.AddRow(heading, platformTypeList); } if (model.SupportsXamMac) { var cb = new CheckBox { Text = "Include Xamarin.Mac project", ToolTip = "This enables you to bundle mono with your app so your users don't have to install it separately. You can only compile this on a Mac" }; cb.CheckedBinding.BindDataContext((ProjectWizardPageModel m) => m.IncludeXamMac); content.AddRow(HeadingLabel(string.Empty), cb); } /* * eventually select platforms to include? * var platformCheckBoxes = new DynamicLayout(); platformCheckBoxes.BeginHorizontal(); platformCheckBoxes.Add(new CheckBox { Text = "Gtk2" }); platformCheckBoxes.Add(new CheckBox { Text = "Gtk3" }); platformCheckBoxes.EndBeginHorizontal(); platformCheckBoxes.Add(new CheckBox { Text = "WinForms" }); platformCheckBoxes.Add(new CheckBox { Text = "Wpf" }); platformCheckBoxes.Add(new CheckBox { Text = "Direct2D" }); platformCheckBoxes.EndBeginHorizontal(); platformCheckBoxes.Add(new CheckBox { Text = "Mac" }); platformCheckBoxes.Add(new CheckBox { Text = "XamMac" }); platformCheckBoxes.Add(new CheckBox { Text = "XamMac2" }); platformCheckBoxes.EndHorizontal(); content.Rows.Add(new TableRow(new Label { Text = "Platforms:", TextAlignment = TextAlignment.Right }, platformCheckBoxes)); /**/ if (model.SupportsProjectType) { var sharedCodeList = new RadioButtonList { Orientation = Orientation.Vertical, Spacing = radioSpacing, }; if (model.SupportsPCL) { sharedCodeList.Items.Add(new ListItem { Text = "Portable Class Library", Key = "pcl" }); sharedCodeList.SelectedKeyBinding.Convert(v => v == "pcl", v => v ? "pcl" : sharedCodeList.SelectedKey).BindDataContext((ProjectWizardPageModel m) => m.UsePCL); } if (model.SupportsNetStandard) { sharedCodeList.Items.Add(new ListItem { Text = ".NET Standard", Key = "netstandard" }); sharedCodeList.SelectedKeyBinding.Convert(v => v == "netstandard", v => v ? "netstandard" : sharedCodeList.SelectedKey).BindDataContext((ProjectWizardPageModel m) => m.UseNetStandard); } if (model.SupportsSAL) { sharedCodeList.Items.Add(new ListItem { Text = "Shared Project", Key = "sal" }); sharedCodeList.SelectedKeyBinding.Convert(v => v == "sal", v => v ? "sal" : sharedCodeList.SelectedKey).BindDataContext((ProjectWizardPageModel m) => m.UseSAL); } sharedCodeList.Items.Add(new ListItem { Text = "Full .NET", Key = "net" }); sharedCodeList.SelectedKeyBinding.Convert(v => v == "net", v => v ? "net" : sharedCodeList.SelectedKey).BindDataContext((ProjectWizardPageModel m) => m.UseNET); content.AddRow(new Label { Text = model.IsLibrary ? "Type:" : "Shared Code:", TextAlignment = TextAlignment.Right }, sharedCodeList); } if (model.SupportsPanelType) { var panelTypeList = new RadioButtonList { Orientation = Orientation.Horizontal, Spacing = radioSpacing, }; panelTypeList.Items.Add(new ListItem { Text = "Code", Key = "code" }); panelTypeList.SelectedKeyBinding.BindDataContext((ProjectWizardPageModel m) => m.Mode); if (model.SupportsXeto) { panelTypeList.Items.Add(new ListItem { Text = "Xaml", Key = "xaml" }); } if (model.SupportsJeto) { panelTypeList.Items.Add(new ListItem { Text = "Json", Key = "json" }); } if (model.SupportsCodePreview) { panelTypeList.Items.Add(new ListItem { Text = "Code Preview", Key = "preview" }); } content.AddRow(HeadingLabel("Form:"), panelTypeList); } if (model.SupportsBase) { var baseTypeList = new RadioButtonList { Orientation = Orientation.Horizontal, Spacing = radioSpacing, }; baseTypeList.Items.Add(new ListItem { Text = "Panel", Key = "Panel" }); baseTypeList.Items.Add(new ListItem { Text = "Dialog", Key = "Dialog" }); baseTypeList.Items.Add(new ListItem { Text = "Form", Key = "Form" }); baseTypeList.SelectedKeyBinding.BindDataContext((ProjectWizardPageModel m) => m.Base); content.AddRow(HeadingLabel("Base:"), baseTypeList); } #if DEBUG //var showColorsButton = new Button { Text = "Show all themed colors" }; //showColorsButton.Click += (sender, e) => new ThemedColorsDialog().ShowModal(this); //content.AddRow(new Panel(), showColorsButton); #endif var informationLabel = new Label(); informationLabel.TextBinding.BindDataContext((ProjectWizardPageModel m) => m.Information); Information = informationLabel; Content = content; DataContext = model; } } }
39.02439
189
0.69225
[ "BSD-3-Clause" ]
AkiSakurai/Eto
src/Addins/Eto.Addin.Shared/ProjectWizardPageView.cs
8,000
C#
using AO.Models.Enums; using System.Data; using System.Threading.Tasks; namespace Dapper.Repository { public partial class Repository<TUser, TModel, TKey> { protected virtual string SqlGet { get; } protected virtual CommandType SqlGetCommandType => CommandType.Text; protected virtual string SqlDelete { get; } protected virtual CommandType SqlDeleteCommandType => CommandType.Text; protected virtual string SqlGetWhere { get; } protected virtual CommandType SqlGetWhereCommandType => CommandType.Text; protected virtual object SqlIdParameter(TKey id) => new { id }; protected virtual object SqlIdDeleteParameter(TKey id) => null; /// <summary> /// override this to populate "navigation properties" of your model row /// </summary> protected async virtual Task GetRelatedAsync(IDbConnection connection, TModel model, IDbTransaction txn = null) => await Task.CompletedTask; /// <summary> /// override this to implement a permission check on a GetAsync, GetWhereAsync, or MergeAsync /// </summary> protected async virtual Task<(bool result, string message)> AllowGetAsync(IDbConnection connection, TModel model, IDbTransaction txn = null) { await Task.CompletedTask; return (true, null); } /// <summary> /// override this to check user's delete permission on a model /// </summary> protected async virtual Task<(bool result, string message)> AllowDeleteAsync(IDbConnection connection, TModel model, IDbTransaction txn = null) { await Task.CompletedTask; return (true, null); } /// <summary> /// override this to validate a model prior to saving /// </summary> protected async virtual Task<(bool result, string message)> ValidateAsync(IDbConnection connection, SaveAction action, TModel model, IDbTransaction txn = null) { await Task.CompletedTask; return (true, null); } protected async virtual Task BeforeSaveAsync(IDbConnection connection, SaveAction action, TModel model, IDbTransaction txn = null) => await Task.CompletedTask; protected async virtual Task AfterSaveAsync(IDbConnection connection, SaveAction action, TModel model, IDbTransaction txn = null) => await Task.CompletedTask; protected async virtual Task BeforeDeleteAsync(IDbConnection connection, TModel model, IDbTransaction txn = null) => await Task.CompletedTask; protected async virtual Task AfterDeleteAsync(IDbConnection connection, TModel model, IDbTransaction txn = null) => await Task.CompletedTask; protected virtual void SetIdentity(TKey id, TModel model) => model.Id = id; } }
41.691176
167
0.683598
[ "MIT" ]
adamfoneil/Dapper.Repository
Dapper.Repository/Repository_virtuals.cs
2,837
C#
namespace Nodsoft.Wargaming.Api.Common.Data.Responses; public record ResponseMeta { public int? Count { get; init; } }
20.166667
55
0.760331
[ "MIT" ]
Nodsoft/Wargaming.Api
Nodsoft.Wargaming.Api.Common/Data/Responses/ResponseMeta.cs
123
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.VisualStudio.Shell.Interop; using System; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Security.AccessControl; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using Package = Microsoft.VisualStudio.Shell.Package; using ThreadHelper = Microsoft.VisualStudio.Shell.ThreadHelper; namespace Microsoft.VisualStudio.BlazorExtension { /// <summary> /// The counterpart to VSForWindowsRebuildService.cs in the Blazor.Server project. /// Listens for named pipe connections and rebuilds projects on request. /// </summary> internal class AutoRebuildService { private const int _protocolVersion = 1; private readonly BuildEventsWatcher _buildEventsWatcher; private readonly string _pipeName; public AutoRebuildService(BuildEventsWatcher buildEventsWatcher) { _buildEventsWatcher = buildEventsWatcher ?? throw new ArgumentNullException(nameof(buildEventsWatcher)); _pipeName = $"BlazorAutoRebuild\\{Process.GetCurrentProcess().Id}"; } public void Listen() { AddBuildServiceNamedPipeServer(); } private void AddBuildServiceNamedPipeServer() { Task.Factory.StartNew(async () => { try { var identity = WindowsIdentity.GetCurrent(); var identifier = identity.Owner; var security = new PipeSecurity(); // Restrict access to just this account. var rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow); security.AddAccessRule(rule); security.SetOwner(identifier); // And our current elevation level var principal = new WindowsPrincipal(identity); var isServerElevated = principal.IsInRole(WindowsBuiltInRole.Administrator); using (var serverPipe = new NamedPipeServerStream( _pipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.WriteThrough, 0x10000, // 64k input buffer 0x10000, // 64k output buffer security, HandleInheritability.None)) { // As soon as we receive a connection, spin up another background // listener to wait for the next connection await serverPipe.WaitForConnectionAsync(); AddBuildServiceNamedPipeServer(); await HandleRequestAsync(serverPipe, isServerElevated); } } catch (Exception ex) { await AttemptLogErrorAsync( $"Error in Blazor AutoRebuildService:\n{ex.Message}\n{ex.StackTrace}"); } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } private async Task HandleRequestAsync(NamedPipeServerStream stream, bool isServerElevated) { // Protocol: // 1. Send a "protocol version" number to the client // 2. Receive the project path from the client // If it is the special string "abort", gracefully disconnect and end // This is to allow for mismatches between server and client protocol version // 3. Receive the "if not built since" timestamp from the client // 4. Perform the build, then send back the success/failure result flag // Keep in sync with VSForWindowsRebuildService.cs in the Blazor.Server project // In the future we may extend this to getting back build error details await stream.WriteIntAsync(_protocolVersion); var projectPath = await stream.ReadStringAsync(); // We can't do the security check for elevation until we read from the stream. if (isServerElevated != IsClientElevated(stream)) { return; } if (projectPath.Equals("abort", StringComparison.Ordinal)) { return; } var allowExistingBuildsSince = await stream.ReadDateTimeAsync(); var buildResult = await _buildEventsWatcher.PerformBuildAsync(projectPath, allowExistingBuildsSince); await stream.WriteBoolAsync(buildResult); } private async Task AttemptLogErrorAsync(string message) { if (!ThreadHelper.CheckAccess()) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); } var outputWindow = (IVsOutputWindow)Package.GetGlobalService(typeof(SVsOutputWindow)); if (outputWindow != null) { outputWindow.GetPane(VSConstants.OutputWindowPaneGuid.BuildOutputPane_guid, out var pane); if (pane != null) { pane.OutputString(message); pane.Activate(); } } } private bool? IsClientElevated(NamedPipeServerStream stream) { bool? isClientElevated = null; stream.RunAsClient(() => { var identity = WindowsIdentity.GetCurrent(ifImpersonating: true); var principal = new WindowsPrincipal(identity); isClientElevated = principal.IsInRole(WindowsBuiltInRole.Administrator); }); return isClientElevated; } } }
41.790541
152
0.593856
[ "Apache-2.0" ]
0xced/AspNetCore
src/Components/blazor/tooling/Microsoft.VisualStudio.BlazorExtension/AutoRebuild/AutoRebuildService.cs
6,187
C#
using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace homework_5_bsa2018.PL.Migrations { public partial class InitialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Flights", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Number = table.Column<string>(nullable: true), StartPoint = table.Column<string>(nullable: true), StartTime = table.Column<DateTime>(nullable: false), FinishPoint = table.Column<string>(nullable: true), FinishTime = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Flights", x => x.Id); }); migrationBuilder.CreateTable( name: "Pilots", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), FirstName = table.Column<string>(nullable: true), LastName = table.Column<string>(nullable: true), Experience = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Pilots", x => x.Id); }); migrationBuilder.CreateTable( name: "PlaneTypes", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Model = table.Column<string>(nullable: true), Places = table.Column<int>(nullable: false), Carrying = table.Column<double>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_PlaneTypes", x => x.Id); }); migrationBuilder.CreateTable( name: "Tickets", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Price = table.Column<double>(nullable: false), FlightNumber = table.Column<string>(nullable: true), FlightId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Tickets", x => x.Id); table.ForeignKey( name: "FK_Tickets_Flights_FlightId", column: x => x.FlightId, principalTable: "Flights", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Crews", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), PilotId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Crews", x => x.Id); table.ForeignKey( name: "FK_Crews_Pilots_PilotId", column: x => x.PilotId, principalTable: "Pilots", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Planes", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true), TypePlaneId = table.Column<int>(nullable: true), Created = table.Column<DateTime>(nullable: false), LifeTime = table.Column<TimeSpan>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Planes", x => x.Id); table.ForeignKey( name: "FK_Planes_PlaneTypes_TypePlaneId", column: x => x.TypePlaneId, principalTable: "PlaneTypes", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Stewardesses", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), FirstName = table.Column<string>(nullable: true), LastName = table.Column<string>(nullable: true), DateOfBirth = table.Column<DateTime>(nullable: false), CrewId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Stewardesses", x => x.Id); table.ForeignKey( name: "FK_Stewardesses_Crews_CrewId", column: x => x.CrewId, principalTable: "Crews", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Departures", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), FlightNumber = table.Column<string>(nullable: true), DepartureTime = table.Column<DateTime>(nullable: false), CrewId = table.Column<int>(nullable: true), PlaneId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Departures", x => x.Id); table.ForeignKey( name: "FK_Departures_Crews_CrewId", column: x => x.CrewId, principalTable: "Crews", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Departures_Planes_PlaneId", column: x => x.PlaneId, principalTable: "Planes", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_Crews_PilotId", table: "Crews", column: "PilotId"); migrationBuilder.CreateIndex( name: "IX_Departures_CrewId", table: "Departures", column: "CrewId"); migrationBuilder.CreateIndex( name: "IX_Departures_PlaneId", table: "Departures", column: "PlaneId"); migrationBuilder.CreateIndex( name: "IX_Planes_TypePlaneId", table: "Planes", column: "TypePlaneId"); migrationBuilder.CreateIndex( name: "IX_Stewardesses_CrewId", table: "Stewardesses", column: "CrewId"); migrationBuilder.CreateIndex( name: "IX_Tickets_FlightId", table: "Tickets", column: "FlightId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Departures"); migrationBuilder.DropTable( name: "Stewardesses"); migrationBuilder.DropTable( name: "Tickets"); migrationBuilder.DropTable( name: "Planes"); migrationBuilder.DropTable( name: "Crews"); migrationBuilder.DropTable( name: "Flights"); migrationBuilder.DropTable( name: "PlaneTypes"); migrationBuilder.DropTable( name: "Pilots"); } } }
41.41048
122
0.48318
[ "Apache-2.0" ]
oleksiitymchenko/Academy_2018_Tasks-async-await-
homework_5_bsa2018.DAL/Migrations/20180714142532_InitialCreate.cs
9,485
C#
using System; using System.IO; using System.Threading.Tasks; using Plugin.Media.Abstractions; using CoreGraphics; using AssetsLibrary; using Foundation; using UIKit; using NSAction = global::System.Action; using System.Globalization; using ImageIO; using MobileCoreServices; using System.Drawing; namespace Plugin.Media { internal class MediaPickerDelegate : UIImagePickerControllerDelegate { internal MediaPickerDelegate(UIViewController viewController, UIImagePickerControllerSourceType sourceType, StoreCameraMediaOptions options) { this.viewController = viewController; source = sourceType; this.options = options ?? new StoreCameraMediaOptions(); if (viewController != null) { UIDevice.CurrentDevice.BeginGeneratingDeviceOrientationNotifications(); observer = NSNotificationCenter.DefaultCenter.AddObserver(UIDevice.OrientationDidChangeNotification, DidRotate); } } public UIPopoverController Popover { get; set; } public UIView View => viewController.View; public Task<MediaFile> Task => tcs.Task; public override async void FinishedPickingMedia(UIImagePickerController picker, NSDictionary info) { RemoveOrientationChangeObserverAndNotifications(); MediaFile mediaFile; switch ((NSString)info[UIImagePickerController.MediaType]) { case MediaImplementation.TypeImage: mediaFile = await GetPictureMediaFile(info); break; case MediaImplementation.TypeMovie: mediaFile = await GetMovieMediaFile(info); break; default: throw new NotSupportedException(); } if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { UIApplication.SharedApplication.SetStatusBarStyle(MediaImplementation.StatusBarStyle, false); } Dismiss(picker, () => { if (mediaFile == null) tcs.SetException(new FileNotFoundException()); else tcs.TrySetResult(mediaFile); }); } public override void Canceled(UIImagePickerController picker) { RemoveOrientationChangeObserverAndNotifications(); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { UIApplication.SharedApplication.SetStatusBarStyle(MediaImplementation.StatusBarStyle, false); } Dismiss(picker, () => { tcs.SetResult(null); }); } public void DisplayPopover(bool hideFirst = false) { if (Popover == null) return; var swidth = UIScreen.MainScreen.Bounds.Width; var sheight = UIScreen.MainScreen.Bounds.Height; nfloat width = 400; nfloat height = 300; if (orientation == null) { if (IsValidInterfaceOrientation(UIDevice.CurrentDevice.Orientation)) orientation = UIDevice.CurrentDevice.Orientation; else orientation = GetDeviceOrientation(viewController.InterfaceOrientation); } double x, y; if (orientation == UIDeviceOrientation.LandscapeLeft || orientation == UIDeviceOrientation.LandscapeRight) { x = (Math.Max(swidth, sheight) - width) / 2; y = (Math.Min(swidth, sheight) - height) / 2; } else { x = (Math.Min(swidth, sheight) - width) / 2; y = (Math.Max(swidth, sheight) - height) / 2; } if (hideFirst && Popover.PopoverVisible) Popover.Dismiss(animated: false); Popover.PresentFromRect(new CGRect(x, y, width, height), View, 0, animated: true); } private UIDeviceOrientation? orientation; private NSObject observer; private readonly UIViewController viewController; private readonly UIImagePickerControllerSourceType source; private TaskCompletionSource<MediaFile> tcs = new TaskCompletionSource<MediaFile>(); private readonly StoreCameraMediaOptions options; private bool IsCaptured => source == UIImagePickerControllerSourceType.Camera; private void Dismiss(UIImagePickerController picker, NSAction onDismiss) { if (viewController == null) { onDismiss(); tcs = new TaskCompletionSource<MediaFile>(); } else { if (Popover != null) { Popover.Dismiss(animated: true); try { Popover.Dispose(); } catch { } Popover = null; onDismiss(); } else { picker.DismissViewController(true, onDismiss); try { picker.Dispose(); } catch { } } } } private void RemoveOrientationChangeObserverAndNotifications() { if (viewController != null) { UIDevice.CurrentDevice.EndGeneratingDeviceOrientationNotifications(); NSNotificationCenter.DefaultCenter.RemoveObserver(observer); observer.Dispose(); } } private void DidRotate(NSNotification notice) { var device = (UIDevice)notice.Object; if (!IsValidInterfaceOrientation(device.Orientation) || Popover == null) return; if (orientation.HasValue && IsSameOrientationKind(orientation.Value, device.Orientation)) return; if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0)) { if (!GetShouldRotate6(device.Orientation)) return; } else if (!GetShouldRotate(device.Orientation)) return; var co = orientation; orientation = device.Orientation; if (co == null) return; DisplayPopover(hideFirst: true); } private bool GetShouldRotate(UIDeviceOrientation orientation) { var iorientation = UIInterfaceOrientation.Portrait; switch (orientation) { case UIDeviceOrientation.LandscapeLeft: iorientation = UIInterfaceOrientation.LandscapeLeft; break; case UIDeviceOrientation.LandscapeRight: iorientation = UIInterfaceOrientation.LandscapeRight; break; case UIDeviceOrientation.Portrait: iorientation = UIInterfaceOrientation.Portrait; break; case UIDeviceOrientation.PortraitUpsideDown: iorientation = UIInterfaceOrientation.PortraitUpsideDown; break; default: return false; } return viewController.ShouldAutorotateToInterfaceOrientation(iorientation); } private bool GetShouldRotate6(UIDeviceOrientation orientation) { if (!viewController.ShouldAutorotate()) return false; UIInterfaceOrientationMask mask = UIInterfaceOrientationMask.Portrait; switch (orientation) { case UIDeviceOrientation.LandscapeLeft: mask = UIInterfaceOrientationMask.LandscapeLeft; break; case UIDeviceOrientation.LandscapeRight: mask = UIInterfaceOrientationMask.LandscapeRight; break; case UIDeviceOrientation.Portrait: mask = UIInterfaceOrientationMask.Portrait; break; case UIDeviceOrientation.PortraitUpsideDown: mask = UIInterfaceOrientationMask.PortraitUpsideDown; break; default: return false; } return viewController.GetSupportedInterfaceOrientations().HasFlag(mask); } private async Task<MediaFile> GetPictureMediaFile(NSDictionary info) { var image = (UIImage)info[UIImagePickerController.EditedImage] ?? (UIImage)info[UIImagePickerController.OriginalImage]; if (image == null) return null; var path = GetOutputPath(MediaImplementation.TypeImage, options.Directory ?? ((IsCaptured) ? string.Empty : "temp"), options.Name); var cgImage = image.CGImage; var percent = 1.0f; float newHeight = image.CGImage.Height; float newWidth = image.CGImage.Width; if (options.PhotoSize != PhotoSize.Full) { try { switch (options.PhotoSize) { case PhotoSize.Large: percent = .75f; break; case PhotoSize.Medium: percent = .5f; break; case PhotoSize.Small: percent = .25f; break; case PhotoSize.Custom: percent = (float)options.CustomPhotoSize / 100f; break; } if (options.PhotoSize == PhotoSize.MaxWidthHeight && options.MaxWidthHeight.HasValue) { var max = Math.Max(image.CGImage.Width, image.CGImage.Height); if (max > options.MaxWidthHeight.Value) { percent = (float)options.MaxWidthHeight.Value / (float)max; } } if (percent < 1.0f) { //begin resizing image image = image.ResizeImageWithAspectRatio(percent); } } catch (Exception ex) { Console.WriteLine($"Unable to compress image: {ex}"); } } NSDictionary meta = null; try { if (options.SaveMetaData) { if (source == UIImagePickerControllerSourceType.Camera) { meta = info[UIImagePickerController.MediaMetadata] as NSDictionary; if (meta != null && meta.ContainsKey(ImageIO.CGImageProperties.Orientation)) { var newMeta = new NSMutableDictionary(); newMeta.SetValuesForKeysWithDictionary(meta); var newTiffDict = new NSMutableDictionary(); newTiffDict.SetValuesForKeysWithDictionary(meta[ImageIO.CGImageProperties.TIFFDictionary] as NSDictionary); newTiffDict.SetValueForKey(meta[ImageIO.CGImageProperties.Orientation], ImageIO.CGImageProperties.TIFFOrientation); newMeta[ImageIO.CGImageProperties.TIFFDictionary] = newTiffDict; meta = newMeta; } var location = options.Location; if (meta != null && location != null) { meta = SetGpsLocation(meta, location); } } else { meta = PhotoLibraryAccess.GetPhotoLibraryMetadata(info[UIImagePickerController.ReferenceUrl] as NSUrl); } } } catch (Exception ex) { Console.WriteLine($"Unable to get metadata: {ex}"); } //iOS quality is 0.0-1.0 var quality = (options.CompressionQuality / 100f); var savedImage = false; if (meta != null) savedImage = SaveImageWithMetadata(image, quality, meta, path); if (!savedImage) { var finalQuality = quality; var imageData = image.AsJPEG(finalQuality); //continue to move down quality , rare instances while (imageData == null && finalQuality > 0) { finalQuality -= 0.05f; imageData = image.AsJPEG(finalQuality); } if (imageData == null) throw new NullReferenceException("Unable to convert image to jpeg, please ensure file exists or lower quality level"); imageData.Save(path, true); imageData.Dispose(); } string aPath = null; if (source != UIImagePickerControllerSourceType.Camera) { //try to get the album path's url var url = (NSUrl)info[UIImagePickerController.ReferenceUrl]; aPath = url?.AbsoluteString; } else { if (options.SaveToAlbum) { try { var library = new ALAssetsLibrary(); var albumSave = await library.WriteImageToSavedPhotosAlbumAsync(cgImage, meta); aPath = albumSave.AbsoluteString; } catch (Exception ex) { Console.WriteLine("unable to save to album:" + ex); } } } Func<Stream> getStreamForExternalStorage = () => { if (options.RotateImage) return RotateImage(image, options.CompressionQuality); else return File.OpenRead(path); }; return new MediaFile(path, () => File.OpenRead(path), streamGetterForExternalStorage: () => getStreamForExternalStorage(), albumPath: aPath); } private static NSDictionary SetGpsLocation(NSDictionary meta, Location location) { var newMeta = new NSMutableDictionary(); newMeta.SetValuesForKeysWithDictionary(meta); var newGpsDict = new NSMutableDictionary(); newGpsDict.SetValueForKey(new NSNumber(Math.Abs(location.Latitude)), ImageIO.CGImageProperties.GPSLatitude); newGpsDict.SetValueForKey(new NSString(location.Latitude > 0 ? "N" : "S"), ImageIO.CGImageProperties.GPSLatitudeRef); newGpsDict.SetValueForKey(new NSNumber(Math.Abs(location.Longitude)), ImageIO.CGImageProperties.GPSLongitude); newGpsDict.SetValueForKey(new NSString(location.Longitude > 0 ? "E" : "W"), ImageIO.CGImageProperties.GPSLongitudeRef); newGpsDict.SetValueForKey(new NSNumber(location.Altitude), ImageIO.CGImageProperties.GPSAltitude); newGpsDict.SetValueForKey(new NSNumber(0), ImageIO.CGImageProperties.GPSAltitudeRef); newGpsDict.SetValueForKey(new NSNumber(location.Speed), ImageIO.CGImageProperties.GPSSpeed); newGpsDict.SetValueForKey(new NSString("K"), ImageIO.CGImageProperties.GPSSpeedRef); newGpsDict.SetValueForKey(new NSNumber(location.Direction), ImageIO.CGImageProperties.GPSImgDirection); newGpsDict.SetValueForKey(new NSString("T"), ImageIO.CGImageProperties.GPSImgDirectionRef); newGpsDict.SetValueForKey(new NSString(location.Timestamp.ToString("hh:mm:ss")), ImageIO.CGImageProperties.GPSTimeStamp); newGpsDict.SetValueForKey(new NSString(location.Timestamp.ToString("yyyy:MM:dd")), ImageIO.CGImageProperties.GPSDateStamp); newMeta[ImageIO.CGImageProperties.GPSDictionary] = newGpsDict; return newMeta; } private bool SaveImageWithMetadata(UIImage image, float quality, NSDictionary meta, string path) { try { var finalQuality = quality; var imageData = image.AsJPEG(finalQuality); //continue to move down quality , rare instances while (imageData == null && finalQuality > 0) { finalQuality -= 0.05f; imageData = image.AsJPEG(finalQuality); } if (imageData == null) throw new NullReferenceException("Unable to convert image to jpeg, please ensure file exists or lower quality level"); var dataProvider = new CGDataProvider(imageData); var cgImageFromJpeg = CGImage.FromJPEG(dataProvider, null, false, CGColorRenderingIntent.Default); var imageWithExif = new NSMutableData(); var destination = CGImageDestination.Create(imageWithExif, UTType.JPEG, 1); var cgImageMetadata = new CGMutableImageMetadata(); var destinationOptions = new CGImageDestinationOptions(); if (meta.ContainsKey(ImageIO.CGImageProperties.Orientation)) destinationOptions.Dictionary[ImageIO.CGImageProperties.Orientation] = meta[ImageIO.CGImageProperties.Orientation]; if (meta.ContainsKey(ImageIO.CGImageProperties.DPIWidth)) destinationOptions.Dictionary[ImageIO.CGImageProperties.DPIWidth] = meta[ImageIO.CGImageProperties.DPIWidth]; if (meta.ContainsKey(ImageIO.CGImageProperties.DPIHeight)) destinationOptions.Dictionary[ImageIO.CGImageProperties.DPIHeight] = meta[ImageIO.CGImageProperties.DPIHeight]; if (meta.ContainsKey(ImageIO.CGImageProperties.ExifDictionary)) { destinationOptions.ExifDictionary = new CGImagePropertiesExif(meta[ImageIO.CGImageProperties.ExifDictionary] as NSDictionary); } if (meta.ContainsKey(ImageIO.CGImageProperties.TIFFDictionary)) { destinationOptions.TiffDictionary = new CGImagePropertiesTiff(meta[ImageIO.CGImageProperties.TIFFDictionary] as NSDictionary); } if (meta.ContainsKey(ImageIO.CGImageProperties.GPSDictionary)) { destinationOptions.GpsDictionary = new CGImagePropertiesGps(meta[ImageIO.CGImageProperties.GPSDictionary] as NSDictionary); } if (meta.ContainsKey(ImageIO.CGImageProperties.JFIFDictionary)) { destinationOptions.JfifDictionary = new CGImagePropertiesJfif(meta[ImageIO.CGImageProperties.JFIFDictionary] as NSDictionary); } if (meta.ContainsKey(ImageIO.CGImageProperties.IPTCDictionary)) { destinationOptions.IptcDictionary = new CGImagePropertiesIptc(meta[ImageIO.CGImageProperties.IPTCDictionary] as NSDictionary); } destination.AddImageAndMetadata(cgImageFromJpeg, cgImageMetadata, destinationOptions); var success = destination.Close(); if (success) { imageWithExif.Save(path, true); } return success; } catch (Exception ex) { Console.WriteLine($"Unable to save image with metadata: {ex}"); } return false; } private async Task<MediaFile> GetMovieMediaFile(NSDictionary info) { var url = (NSUrl)info[UIImagePickerController.MediaURL]; var path = GetOutputPath(MediaImplementation.TypeMovie, options.Directory ?? ((IsCaptured) ? string.Empty : "temp"), options.Name ?? Path.GetFileName(url.Path)); File.Move(url.Path, path); string aPath = null; if (source != UIImagePickerControllerSourceType.Camera) { //try to get the album path's url var url2 = (NSUrl)info[UIImagePickerController.ReferenceUrl]; aPath = url2?.AbsoluteString; } else { if (options.SaveToAlbum) { try { var library = new ALAssetsLibrary(); var albumSave = await library.WriteVideoToSavedPhotosAlbumAsync(new NSUrl(path)); aPath = albumSave.AbsoluteString; } catch (Exception ex) { Console.WriteLine("unable to save to album:" + ex); } } } return new MediaFile(path, () => File.OpenRead(path), albumPath: aPath); } private static string GetUniquePath(string type, string path, string name) { var isPhoto = (type == MediaImplementation.TypeImage); var ext = Path.GetExtension(name); if (ext == string.Empty) ext = ((isPhoto) ? ".jpg" : ".mp4"); name = Path.GetFileNameWithoutExtension(name); var nname = name + ext; var i = 1; while (File.Exists(Path.Combine(path, nname))) nname = name + "_" + (i++) + ext; return Path.Combine(path, nname); } private static string GetOutputPath(string type, string path, string name) { path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), path); Directory.CreateDirectory(path); if (string.IsNullOrWhiteSpace(name)) { var timestamp = DateTime.Now.ToString("yyyMMdd_HHmmss", CultureInfo.InvariantCulture); if (type == MediaImplementation.TypeImage) name = "IMG_" + timestamp + ".jpg"; else name = "VID_" + timestamp + ".mp4"; } return Path.Combine(path, GetUniquePath(type, path, name)); } private static bool IsValidInterfaceOrientation(UIDeviceOrientation self) { return (self != UIDeviceOrientation.FaceUp && self != UIDeviceOrientation.FaceDown && self != UIDeviceOrientation.Unknown); } private static bool IsSameOrientationKind(UIDeviceOrientation o1, UIDeviceOrientation o2) { if (o1 == UIDeviceOrientation.FaceDown || o1 == UIDeviceOrientation.FaceUp) return (o2 == UIDeviceOrientation.FaceDown || o2 == UIDeviceOrientation.FaceUp); if (o1 == UIDeviceOrientation.LandscapeLeft || o1 == UIDeviceOrientation.LandscapeRight) return (o2 == UIDeviceOrientation.LandscapeLeft || o2 == UIDeviceOrientation.LandscapeRight); if (o1 == UIDeviceOrientation.Portrait || o1 == UIDeviceOrientation.PortraitUpsideDown) return (o2 == UIDeviceOrientation.Portrait || o2 == UIDeviceOrientation.PortraitUpsideDown); return false; } private static UIDeviceOrientation GetDeviceOrientation(UIInterfaceOrientation self) { switch (self) { case UIInterfaceOrientation.LandscapeLeft: return UIDeviceOrientation.LandscapeLeft; case UIInterfaceOrientation.LandscapeRight: return UIDeviceOrientation.LandscapeRight; case UIInterfaceOrientation.Portrait: return UIDeviceOrientation.Portrait; case UIInterfaceOrientation.PortraitUpsideDown: return UIDeviceOrientation.PortraitUpsideDown; default: throw new InvalidOperationException(); } } public static Stream RotateImage(UIImage image, int compressionQuality) { UIImage imageToReturn = null; if (image.Orientation == UIImageOrientation.Up) { imageToReturn = image; } else { CGAffineTransform transform = CGAffineTransform.MakeIdentity(); switch (image.Orientation) { case UIImageOrientation.Down: case UIImageOrientation.DownMirrored: transform.Rotate((float)Math.PI); transform.Translate(image.Size.Width, image.Size.Height); break; case UIImageOrientation.Left: case UIImageOrientation.LeftMirrored: transform.Rotate((float)Math.PI / 2); transform.Translate(image.Size.Width, 0); break; case UIImageOrientation.Right: case UIImageOrientation.RightMirrored: transform.Rotate(-(float)Math.PI / 2); transform.Translate(0, image.Size.Height); break; case UIImageOrientation.Up: case UIImageOrientation.UpMirrored: break; } switch (image.Orientation) { case UIImageOrientation.UpMirrored: case UIImageOrientation.DownMirrored: transform.Translate(image.Size.Width, 0); transform.Scale(-1, 1); break; case UIImageOrientation.LeftMirrored: case UIImageOrientation.RightMirrored: transform.Translate(image.Size.Height, 0); transform.Scale(-1, 1); break; case UIImageOrientation.Up: case UIImageOrientation.Down: case UIImageOrientation.Left: case UIImageOrientation.Right: break; } using (var context = new CGBitmapContext(IntPtr.Zero, (int)image.Size.Width, (int)image.Size.Height, image.CGImage.BitsPerComponent, image.CGImage.BytesPerRow, image.CGImage.ColorSpace, image.CGImage.BitmapInfo)) { context.ConcatCTM(transform); switch (image.Orientation) { case UIImageOrientation.Left: case UIImageOrientation.LeftMirrored: case UIImageOrientation.Right: case UIImageOrientation.RightMirrored: context.DrawImage(new RectangleF(PointF.Empty, new SizeF((float)image.Size.Height, (float)image.Size.Width)), image.CGImage); break; default: context.DrawImage(new RectangleF(PointF.Empty, new SizeF((float)image.Size.Width, (float)image.Size.Height)), image.CGImage); break; } using (var imageRef = context.ToImage()) { imageToReturn = new UIImage(imageRef, 1, UIImageOrientation.Up); } } } var finalQuality = compressionQuality / 100f; var imageData = imageToReturn.AsJPEG(finalQuality); //continue to move down quality , rare instances while (imageData == null && finalQuality > 0) { finalQuality -= 0.05f; imageData = imageToReturn.AsJPEG(finalQuality); } if (imageData == null) throw new NullReferenceException("Unable to convert image to jpeg, please ensure file exists or lower quality level"); var stream = new MemoryStream(); imageData.AsStream().CopyTo(stream); imageData.Dispose(); return stream; } } }
29.833109
144
0.707615
[ "MIT" ]
AndreiMisiukevich/MediaPlugin
src/Media.Plugin/iOS/MediaPickerDelegate.cs
22,166
C#
// <auto-generated /> namespace Derby.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.1.1-30610")] public sealed partial class SomethingSomethingPack : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(SomethingSomethingPack)); string IMigrationMetadata.Id { get { return "201410241923485_SomethingSomethingPack"; } } string IMigrationMetadata.Source { get { return Resources.GetString("Source"); } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
28.933333
105
0.637097
[ "MIT" ]
tmeers/Derby
Derby/Migrations/201410241923485_SomethingSomethingPack.Designer.cs
868
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.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.Windows.Forms.TestUtilities; using Xunit; using static Interop; namespace System.Windows.Forms.Tests { using Point = System.Drawing.Point; using Size = System.Drawing.Size; public class MonthCalendarTests : IClassFixture<ThreadExceptionFixture> { [WinFormsFact] public void MonthCalendar_Ctor_Default() { using var control = new SubMonthCalendar(); Assert.Null(control.AccessibleDefaultActionDescription); Assert.Null(control.AccessibleDescription); Assert.Null(control.AccessibleName); Assert.Equal(AccessibleRole.Default, control.AccessibleRole); Assert.False(control.AllowDrop); Assert.Equal(AnchorStyles.Top | AnchorStyles.Left, control.Anchor); Assert.Empty(control.AnnuallyBoldedDates); Assert.Same(control.AnnuallyBoldedDates, control.AnnuallyBoldedDates); Assert.False(control.AutoSize); Assert.Equal(SystemColors.Window, control.BackColor); Assert.Null(control.BackgroundImage); Assert.Equal(ImageLayout.Tile, control.BackgroundImageLayout); Assert.Null(control.BindingContext); Assert.Empty(control.BoldedDates); Assert.Same(control.BoldedDates, control.BoldedDates); Assert.True(control.Bottom > 0); Assert.Equal(0, control.Bounds.X); Assert.Equal(0, control.Bounds.Y); Assert.True(control.Bounds.Width > 0); Assert.True(control.Bounds.Height > 0); Assert.Equal(new Size(1, 1), control.CalendarDimensions); Assert.False(control.CanEnableIme); Assert.False(control.CanFocus); Assert.True(control.CanRaiseEvents); Assert.True(control.CanSelect); Assert.False(control.Capture); Assert.True(control.CausesValidation); Assert.True(control.ClientSize.Width > 0); Assert.True(control.ClientSize.Height > 0); Assert.Equal(0, control.ClientRectangle.X); Assert.Equal(0, control.ClientRectangle.Y); Assert.True(control.ClientRectangle.Width > 0); Assert.True(control.ClientRectangle.Height > 0); Assert.Null(control.Container); Assert.False(control.ContainsFocus); Assert.Null(control.ContextMenuStrip); Assert.Empty(control.Controls); Assert.Same(control.Controls, control.Controls); Assert.False(control.Created); Assert.Same(Cursors.Default, control.Cursor); Assert.Same(Cursors.Default, control.DefaultCursor); Assert.Equal(ImeMode.Disable, control.DefaultImeMode); Assert.Equal(new Padding(9), control.DefaultMargin); Assert.Equal(Size.Empty, control.DefaultMaximumSize); Assert.Equal(Size.Empty, control.DefaultMinimumSize); Assert.Equal(Padding.Empty, control.DefaultPadding); Assert.True(control.DefaultSize.Width > 0); Assert.True(control.DefaultSize.Height > 0); Assert.False(control.DesignMode); Assert.Equal(0, control.DisplayRectangle.X); Assert.Equal(0, control.DisplayRectangle.Y); Assert.True(control.DisplayRectangle.Width > 0); Assert.True(control.DisplayRectangle.Height > 0); Assert.Equal(DockStyle.None, control.Dock); Assert.False(control.DoubleBuffered); Assert.True(control.Enabled); Assert.NotNull(control.Events); Assert.Same(control.Events, control.Events); Assert.Equal(Day.Default, control.FirstDayOfWeek); Assert.False(control.Focused); Assert.Equal(Control.DefaultFont, control.Font); Assert.Equal(control.Font.Height, control.FontHeight); Assert.Equal(SystemColors.WindowText, control.ForeColor); Assert.False(control.HasChildren); Assert.True(control.Height > 0); Assert.Equal(ImeMode.Disable, control.ImeMode); Assert.Equal(ImeMode.Disable, control.ImeModeBase); Assert.False(control.IsAccessible); Assert.False(control.IsMirrored); Assert.NotNull(control.LayoutEngine); Assert.Same(control.LayoutEngine, control.LayoutEngine); Assert.Equal(0, control.Left); Assert.Equal(Point.Empty, control.Location); Assert.Equal(new Padding(9), control.Margin); Assert.Equal(new DateTime(9998, 12, 31), control.MaxDate); Assert.Equal(Size.Empty, control.MaximumSize); Assert.Equal(7, control.MaxSelectionCount); Assert.Equal(new DateTime(1753, 1, 1), control.MinDate); Assert.Equal(Size.Empty, control.MinimumSize); Assert.Empty(control.MonthlyBoldedDates); Assert.Same(control.MonthlyBoldedDates, control.MonthlyBoldedDates); Assert.Equal(Padding.Empty, control.Padding); Assert.Null(control.Parent); Assert.True(control.PreferredSize.Width > 0); Assert.True(control.PreferredSize.Height > 0); Assert.Equal("Microsoft\u00AE .NET", control.ProductName); Assert.False(control.RecreatingHandle); Assert.Null(control.Region); Assert.False(control.ResizeRedraw); Assert.True(control.Right > 0); Assert.Equal(RightToLeft.No, control.RightToLeft); Assert.False(control.RightToLeftLayout); Assert.Equal(0, control.ScrollChange); Assert.Equal(DateTime.Now.Date, control.SelectionEnd); Assert.Equal(DateTime.Now.Date, control.SelectionRange.Start); Assert.Equal(DateTime.Now.Date, control.SelectionRange.End); Assert.NotSame(control.SelectionRange, control.SelectionRange); Assert.Equal(DateTime.Now.Date, control.SelectionStart); Assert.True(control.ShowFocusCues); Assert.True(control.ShowKeyboardCues); Assert.True(control.ShowToday); Assert.True(control.ShowTodayCircle); Assert.False(control.ShowWeekNumbers); Assert.Equal(new Size(176, 153), control.SingleMonthSize); Assert.Null(control.Site); Assert.True(control.Size.Width > 0); Assert.True(control.Size.Height > 0); Assert.Equal(0, control.TabIndex); Assert.True(control.TabStop); Assert.Empty(control.Text); Assert.Equal(SystemColors.ActiveCaption, control.TitleBackColor); Assert.Equal(SystemColors.ActiveCaptionText, control.TitleForeColor); Assert.Equal(DateTime.Now.Date, control.TodayDate); Assert.False(control.TodayDateSet); Assert.Equal(0, control.Top); Assert.Null(control.TopLevelControl); Assert.Equal(SystemColors.GrayText, control.TrailingForeColor); Assert.False(control.UseWaitCursor); Assert.True(control.Visible); Assert.True(control.Width > 0); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void MonthCalendar_CreateParams_GetDefault_ReturnsExpected() { using var control = new SubMonthCalendar(); CreateParams createParams = control.CreateParams; Assert.Null(createParams.Caption); Assert.Equal("SysMonthCal32", createParams.ClassName); Assert.Equal(0x8, createParams.ClassStyle); Assert.Equal(0, createParams.ExStyle); Assert.Equal(control.Height, createParams.Height); Assert.Equal(IntPtr.Zero, createParams.Parent); Assert.Null(createParams.Param); Assert.Equal(0x56010003, createParams.Style); Assert.Equal(control.Width, createParams.Width); Assert.Equal(0, createParams.X); Assert.Equal(0, createParams.Y); Assert.Same(createParams, control.CreateParams); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> AnnuallyBoldedDates_Set_TestData() { yield return new object[] { null, Array.Empty<DateTime>() }; yield return new object[] { Array.Empty<DateTime>(), Array.Empty<DateTime>() }; yield return new object[] { new DateTime[] { new DateTime(2019, 01, 1), new DateTime(2019, 01, 20) }, new DateTime[] { new DateTime(2019, 01, 1), new DateTime(2019, 01, 20) } }; yield return new object[] { new DateTime[] { new DateTime(2017, 01, 1), new DateTime(2018, 01, 20) }, new DateTime[] { new DateTime(2017, 01, 1), new DateTime(2018, 01, 20) } }; yield return new object[] { new DateTime[] { new DateTime(2019, 01, 1), new DateTime(2019, 01, 1), new DateTime(2018, 01, 1) }, new DateTime[] { new DateTime(2019, 01, 1), new DateTime(2019, 01, 1), new DateTime(2018, 01, 1) } }; yield return new object[] { new DateTime[] { DateTime.MinValue, DateTime.MaxValue }, new DateTime[] { DateTime.MinValue, DateTime.MaxValue } }; var everyMonth = new DateTime[] { new DateTime(2019, 01, 1), new DateTime(2019, 02, 2), new DateTime(2019, 03, 3), new DateTime(2019, 04, 4), new DateTime(2019, 05, 5), new DateTime(2019, 06, 6), new DateTime(2019, 07, 7), new DateTime(2019, 08, 8), new DateTime(2019, 09, 9), new DateTime(2019, 10, 10), new DateTime(2019, 11, 11), new DateTime(2019, 12, 12), }; yield return new object[] { everyMonth, everyMonth }; } [WinFormsTheory] [MemberData(nameof(AnnuallyBoldedDates_Set_TestData))] public void MonthCalendar_AnnuallyBoldedDates_Set_GetReturnsExpected(DateTime[] value, DateTime[] expected) { using var calendar = new MonthCalendar { AnnuallyBoldedDates = value }; Assert.Equal(expected, calendar.AnnuallyBoldedDates); Assert.NotSame(value, calendar.AnnuallyBoldedDates); if (value?.Length > 0) { Assert.NotSame(calendar.AnnuallyBoldedDates, calendar.AnnuallyBoldedDates); } else { Assert.Same(calendar.AnnuallyBoldedDates, calendar.AnnuallyBoldedDates); } Assert.False(calendar.IsHandleCreated); // Set same. calendar.AnnuallyBoldedDates = value; Assert.Equal(expected, calendar.AnnuallyBoldedDates); Assert.NotSame(value, calendar.AnnuallyBoldedDates); if (value?.Length > 0) { Assert.NotSame(calendar.AnnuallyBoldedDates, calendar.AnnuallyBoldedDates); } else { Assert.Same(calendar.AnnuallyBoldedDates, calendar.AnnuallyBoldedDates); } Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(AnnuallyBoldedDates_Set_TestData))] public void MonthCalendar_AnnuallyBoldedDates_SetWithHandle_GetReturnsExpected(DateTime[] value, DateTime[] expected) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.AnnuallyBoldedDates = value; Assert.Equal(expected, calendar.AnnuallyBoldedDates); Assert.NotSame(value, calendar.AnnuallyBoldedDates); if (value?.Length > 0) { Assert.NotSame(calendar.AnnuallyBoldedDates, calendar.AnnuallyBoldedDates); } else { Assert.Same(calendar.AnnuallyBoldedDates, calendar.AnnuallyBoldedDates); } Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. calendar.AnnuallyBoldedDates = value; Assert.Equal(expected, calendar.AnnuallyBoldedDates); Assert.NotSame(value, calendar.AnnuallyBoldedDates); if (value?.Length > 0) { Assert.NotSame(calendar.AnnuallyBoldedDates, calendar.AnnuallyBoldedDates); } else { Assert.Same(calendar.AnnuallyBoldedDates, calendar.AnnuallyBoldedDates); } Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } public static IEnumerable<object[]> BackColor_Set_TestData() { yield return new object[] { Color.Empty, SystemColors.Window }; yield return new object[] { Color.Red, Color.Red }; } [WinFormsTheory] [MemberData(nameof(BackColor_Set_TestData))] public void MonthCalendar_BackColor_Set_GetReturnsExpected(Color value, Color expected) { using var control = new MonthCalendar { BackColor = value }; Assert.Equal(expected, control.BackColor); Assert.False(control.IsHandleCreated); // Set same. control.BackColor = value; Assert.Equal(expected, control.BackColor); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> BackColor_SetWithHandle_TestData() { yield return new object[] { Color.Empty, SystemColors.Window, 0 }; yield return new object[] { Color.Red, Color.Red, 1 }; } [WinFormsTheory] [MemberData(nameof(BackColor_SetWithHandle_TestData))] public void MonthCalendar_BackColor_SetWithHandle_GetReturnsExpected(Color value, Color expected, int expectedInvalidatedCallCount) { using var control = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.BackColor = value; Assert.Equal(expected, control.BackColor); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.BackColor = value; Assert.Equal(expected, control.BackColor); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_BackColor_SetWithHandler_CallsBackColorChanged() { using var control = new MonthCalendar(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); callCount++; }; control.BackColorChanged += handler; // Set different. control.BackColor = Color.Red; Assert.Equal(Color.Red, control.BackColor); Assert.Equal(1, callCount); // Set same. control.BackColor = Color.Red; Assert.Equal(Color.Red, control.BackColor); Assert.Equal(1, callCount); // Set different. control.BackColor = Color.Empty; Assert.Equal(SystemColors.Window, control.BackColor); Assert.Equal(2, callCount); // Remove handler. control.BackColorChanged -= handler; control.BackColor = Color.Red; Assert.Equal(Color.Red, control.BackColor); Assert.Equal(2, callCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelperEx), nameof(CommonTestHelperEx.GetImageTheoryData))] public void MonthCalendar_BackgroundImage_Set_GetReturnsExpected(Image value) { using var control = new MonthCalendar { BackgroundImage = value }; Assert.Same(value, control.BackgroundImage); Assert.False(control.IsHandleCreated); // Set same. control.BackgroundImage = value; Assert.Same(value, control.BackgroundImage); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void MonthCalendar_BackgroundImage_SetWithHandler_CallsBackgroundImageChanged() { using var control = new MonthCalendar(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); callCount++; }; control.BackgroundImageChanged += handler; // Set different. using var image1 = new Bitmap(10, 10); control.BackgroundImage = image1; Assert.Same(image1, control.BackgroundImage); Assert.Equal(1, callCount); // Set same. control.BackgroundImage = image1; Assert.Same(image1, control.BackgroundImage); Assert.Equal(1, callCount); // Set different. using var image2 = new Bitmap(10, 10); control.BackgroundImage = image2; Assert.Same(image2, control.BackgroundImage); Assert.Equal(2, callCount); // Set null. control.BackgroundImage = null; Assert.Null(control.BackgroundImage); Assert.Equal(3, callCount); // Remove handler. control.BackgroundImageChanged -= handler; control.BackgroundImage = image1; Assert.Same(image1, control.BackgroundImage); Assert.Equal(3, callCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(ImageLayout))] public void MonthCalendar_BackgroundImageLayout_Set_GetReturnsExpected(ImageLayout value) { using var control = new SubMonthCalendar { BackgroundImageLayout = value }; Assert.Equal(value, control.BackgroundImageLayout); Assert.False(control.DoubleBuffered); Assert.False(control.IsHandleCreated); // Set same. control.BackgroundImageLayout = value; Assert.Equal(value, control.BackgroundImageLayout); Assert.False(control.DoubleBuffered); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void MonthCalendar_BackgroundImageLayout_SetWithHandler_CallsBackgroundImageLayoutChanged() { using var control = new MonthCalendar(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); callCount++; }; control.BackgroundImageLayoutChanged += handler; // Set different. control.BackgroundImageLayout = ImageLayout.Center; Assert.Equal(ImageLayout.Center, control.BackgroundImageLayout); Assert.Equal(1, callCount); // Set same. control.BackgroundImageLayout = ImageLayout.Center; Assert.Equal(ImageLayout.Center, control.BackgroundImageLayout); Assert.Equal(1, callCount); // Set different. control.BackgroundImageLayout = ImageLayout.Stretch; Assert.Equal(ImageLayout.Stretch, control.BackgroundImageLayout); Assert.Equal(2, callCount); // Remove handler. control.BackgroundImageLayoutChanged -= handler; control.BackgroundImageLayout = ImageLayout.Center; Assert.Equal(ImageLayout.Center, control.BackgroundImageLayout); Assert.Equal(2, callCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(ImageLayout))] public void MonthCalendar_BackgroundImageLayout_SetInvalid_ThrowsInvalidEnumArgumentException(ImageLayout value) { using var control = new MonthCalendar(); Assert.Throws<InvalidEnumArgumentException>("value", () => control.BackgroundImageLayout = value); } public static IEnumerable<object[]> BoldedDates_Set_TestData() { yield return new object[] { null, Array.Empty<DateTime>() }; yield return new object[] { Array.Empty<DateTime>(), Array.Empty<DateTime>() }; yield return new object[] { new DateTime[] { new DateTime(2019, 01, 1), new DateTime(2019, 01, 20) }, new DateTime[] { new DateTime(2019, 01, 1), new DateTime(2019, 01, 20) } }; yield return new object[] { new DateTime[] { new DateTime(2017, 01, 1), new DateTime(2018, 01, 20) }, new DateTime[] { new DateTime(2017, 01, 1), new DateTime(2018, 01, 20) } }; yield return new object[] { new DateTime[] { new DateTime(2019, 01, 1), new DateTime(2019, 01, 1), new DateTime(2018, 01, 1) }, new DateTime[] { new DateTime(2019, 01, 1), new DateTime(2019, 01, 1), new DateTime(2018, 01, 1) } }; yield return new object[] { new DateTime[] { DateTime.MinValue, DateTime.MaxValue }, new DateTime[] { DateTime.MinValue, DateTime.MaxValue } }; var everyMonth = new DateTime[] { new DateTime(2019, 01, 1), new DateTime(2019, 02, 2), new DateTime(2019, 03, 3), new DateTime(2019, 04, 4), new DateTime(2019, 05, 5), new DateTime(2019, 06, 6), new DateTime(2019, 07, 7), new DateTime(2019, 08, 8), new DateTime(2019, 09, 9), new DateTime(2019, 10, 10), new DateTime(2019, 11, 11), new DateTime(2019, 12, 12), }; yield return new object[] { everyMonth, everyMonth }; } [WinFormsTheory] [MemberData(nameof(BoldedDates_Set_TestData))] public void MonthCalendar_BoldedDates_Set_GetReturnsExpected(DateTime[] value, DateTime[] expected) { using var calendar = new MonthCalendar { BoldedDates = value }; Assert.Equal(expected, calendar.BoldedDates); Assert.NotSame(value, calendar.BoldedDates); if (value?.Length > 0) { Assert.NotSame(calendar.BoldedDates, calendar.BoldedDates); } else { Assert.Same(calendar.BoldedDates, calendar.BoldedDates); } Assert.False(calendar.IsHandleCreated); // Set same. calendar.BoldedDates = value; Assert.Equal(expected, calendar.BoldedDates); Assert.NotSame(value, calendar.BoldedDates); if (value?.Length > 0) { Assert.NotSame(calendar.BoldedDates, calendar.BoldedDates); } else { Assert.Same(calendar.BoldedDates, calendar.BoldedDates); } Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(BoldedDates_Set_TestData))] public void MonthCalendar_BoldedDates_SetWithHandle_GetReturnsExpected(DateTime[] value, DateTime[] expected) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.BoldedDates = value; Assert.Equal(expected, calendar.BoldedDates); Assert.NotSame(value, calendar.BoldedDates); if (value?.Length > 0) { Assert.NotSame(calendar.BoldedDates, calendar.BoldedDates); } else { Assert.Same(calendar.BoldedDates, calendar.BoldedDates); } Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. calendar.BoldedDates = value; Assert.Equal(expected, calendar.BoldedDates); Assert.NotSame(value, calendar.BoldedDates); if (value?.Length > 0) { Assert.NotSame(calendar.BoldedDates, calendar.BoldedDates); } else { Assert.Same(calendar.BoldedDates, calendar.BoldedDates); } Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } public static IEnumerable<object[]> CalendarDimensions_Set_TestData() { yield return new object[] { new Size(1, 1), new Size(1, 1) }; yield return new object[] { new Size(1, 2), new Size(1, 2) }; yield return new object[] { new Size(2, 1), new Size(2, 1) }; yield return new object[] { new Size(2, 3), new Size(2, 3) }; yield return new object[] { new Size(3, 4), new Size(3, 4) }; yield return new object[] { new Size(3, 5), new Size(3, 4) }; yield return new object[] { new Size(3, 10), new Size(3, 4) }; yield return new object[] { new Size(5, 3), new Size(4, 3) }; yield return new object[] { new Size(10, 3), new Size(4, 3) }; } [WinFormsTheory] [MemberData(nameof(CalendarDimensions_Set_TestData))] public void MonthCalendar_CalendarDimensions_Set_GetReturnsExpected(Size value, Size expected) { using var calendar = new MonthCalendar { CalendarDimensions = value }; Assert.Equal(expected, calendar.CalendarDimensions); Assert.False(calendar.IsHandleCreated); // Set same. calendar.CalendarDimensions = value; Assert.Equal(expected, calendar.CalendarDimensions); Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [InlineData(1, 12)] [InlineData(12, 1)] public void MonthCalendar_CalendarDimensions_SetAreaOfTwelve_GetReturnsExpected(int width, int height) { var value = new Size(width, height); using var calendar = new MonthCalendar { CalendarDimensions = value }; Assert.True(calendar.CalendarDimensions.Width > 0 && calendar.CalendarDimensions.Width <= 12); Assert.True(calendar.CalendarDimensions.Height > 0 && calendar.CalendarDimensions.Height <= 12); Assert.False(calendar.IsHandleCreated); // Set same. var previousCalendarDimensions = calendar.CalendarDimensions; calendar.CalendarDimensions = value; Assert.True(calendar.CalendarDimensions.Width > 0 && calendar.CalendarDimensions.Width <= 12); Assert.True(calendar.CalendarDimensions.Height > 0 && calendar.CalendarDimensions.Height <= 12); Assert.Equal(previousCalendarDimensions, calendar.CalendarDimensions); Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(CalendarDimensions_Set_TestData))] public void MonthCalendar_CalendarDimensions_SetWithHandle_GetReturnsExpected(Size value, Size expected) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.CalendarDimensions = value; Assert.Equal(expected, calendar.CalendarDimensions); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. calendar.CalendarDimensions = value; Assert.Equal(expected, calendar.CalendarDimensions); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [InlineData(1, 12)] [InlineData(12, 1)] public void MonthCalendar_CalendarDimensions_SetWithHandleAreaOfTwelve_GetReturnsExpected(int width, int height) { var value = new Size(width, height); using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.CalendarDimensions = value; Assert.True(calendar.CalendarDimensions.Width > 0 && calendar.CalendarDimensions.Width <= 12); Assert.True(calendar.CalendarDimensions.Height > 0 && calendar.CalendarDimensions.Height <= 12); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. var previousCalendarDimensions = calendar.CalendarDimensions; calendar.CalendarDimensions = value; Assert.True(calendar.CalendarDimensions.Width > 0 && calendar.CalendarDimensions.Width <= 12); Assert.True(calendar.CalendarDimensions.Height > 0 && calendar.CalendarDimensions.Height <= 12); Assert.Equal(previousCalendarDimensions, calendar.CalendarDimensions); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [InlineData(0)] [InlineData(-1)] public void MonthCalendar_CalendarDimensions_SetNegativeX_ThrowsArgumentOutOfRangeException(int x) { using var calendar = new MonthCalendar(); Assert.Throws<ArgumentOutOfRangeException>("x", () => calendar.CalendarDimensions = new Size(x, 1)); } [WinFormsTheory] [InlineData(0)] [InlineData(-1)] public void MonthCalendar_CalendarDimensions_SetNegativeY_ThrowsArgumentOutOfRangeException(int y) { using var calendar = new MonthCalendar(); Assert.Throws<ArgumentOutOfRangeException>("y", () => calendar.CalendarDimensions = new Size(1, y)); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))] public void MonthCalendar_DoubleBuffered_Set_GetReturnsExpected(bool value) { using var control = new SubMonthCalendar { DoubleBuffered = value }; Assert.Equal(value, control.DoubleBuffered); Assert.Equal(value, control.GetStyle(ControlStyles.OptimizedDoubleBuffer)); Assert.False(control.IsHandleCreated); // Set same. control.DoubleBuffered = value; Assert.Equal(value, control.DoubleBuffered); Assert.Equal(value, control.GetStyle(ControlStyles.OptimizedDoubleBuffer)); Assert.False(control.IsHandleCreated); // Set different. control.DoubleBuffered = !value; Assert.Equal(!value, control.DoubleBuffered); Assert.Equal(!value, control.GetStyle(ControlStyles.OptimizedDoubleBuffer)); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))] public void MonthCalendar_DoubleBuffered_SetWithHandle_GetReturnsExpected(bool value) { using var control = new SubMonthCalendar(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.DoubleBuffered = value; Assert.Equal(value, control.DoubleBuffered); Assert.Equal(value, control.GetStyle(ControlStyles.OptimizedDoubleBuffer)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.DoubleBuffered = value; Assert.Equal(value, control.DoubleBuffered); Assert.Equal(value, control.GetStyle(ControlStyles.OptimizedDoubleBuffer)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set different. control.DoubleBuffered = !value; Assert.Equal(!value, control.DoubleBuffered); Assert.Equal(!value, control.GetStyle(ControlStyles.OptimizedDoubleBuffer)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(Day))] public void MonthCalendar_FirstDayOfWeek_Set_GetReturnsExpected(Day value) { using var calendar = new MonthCalendar { FirstDayOfWeek = value }; Assert.Equal(value, calendar.FirstDayOfWeek); Assert.False(calendar.IsHandleCreated); // Set same. calendar.FirstDayOfWeek = value; Assert.Equal(value, calendar.FirstDayOfWeek); Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(Day))] public void MonthCalendar_FirstDayOfWeek_SetWithCustomOldValue_GetReturnsExpected(Day value) { using var calendar = new MonthCalendar { FirstDayOfWeek = Day.Monday }; calendar.FirstDayOfWeek = value; Assert.Equal(value, calendar.FirstDayOfWeek); Assert.False(calendar.IsHandleCreated); // Set same. calendar.FirstDayOfWeek = value; Assert.Equal(value, calendar.FirstDayOfWeek); Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(Day))] public void MonthCalendar_FirstDayOfWeek_SetWithHandle_GetReturnsExpected(Day value) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.FirstDayOfWeek = value; Assert.Equal(value, calendar.FirstDayOfWeek); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. calendar.FirstDayOfWeek = value; Assert.Equal(value, calendar.FirstDayOfWeek); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [InlineData(Day.Default, 1)] [InlineData(Day.Monday, 0)] [InlineData(Day.Tuesday, 0)] [InlineData(Day.Wednesday, 0)] [InlineData(Day.Thursday, 0)] [InlineData(Day.Friday, 0)] [InlineData(Day.Saturday, 0)] [InlineData(Day.Sunday, 0)] public void MonthCalendar_FirstDayOfWeek_SetWithHandleWithCustomOldValue_GetReturnsExpected(Day value, int expectedCreatedCallCount) { using var calendar = new MonthCalendar { FirstDayOfWeek = Day.Monday }; Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.FirstDayOfWeek = value; Assert.Equal(value, calendar.FirstDayOfWeek); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); // Set same. calendar.FirstDayOfWeek = value; Assert.Equal(value, calendar.FirstDayOfWeek); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(Day))] public void MonthCalendar_FirstDayOfWeek_SetInvalidValue_ThrowsInvalidEnumArgumentException(Day value) { using var calendar = new MonthCalendar(); Assert.Throws<InvalidEnumArgumentException>("FirstDayOfWeek", () => calendar.FirstDayOfWeek = value); } public static IEnumerable<object[]> ForeColor_Set_TestData() { yield return new object[] { Color.Empty, SystemColors.WindowText }; yield return new object[] { Color.FromArgb(254, 1, 2, 3), Color.FromArgb(254, 1, 2, 3) }; yield return new object[] { Color.White, Color.White }; yield return new object[] { Color.Black, Color.Black }; yield return new object[] { Color.Red, Color.Red }; } [WinFormsTheory] [MemberData(nameof(ForeColor_Set_TestData))] public void MonthCalendar_ForeColor_Set_GetReturnsExpected(Color value, Color expected) { using var control = new MonthCalendar { ForeColor = value }; Assert.Equal(expected, control.ForeColor); Assert.False(control.IsHandleCreated); // Set same. control.ForeColor = value; Assert.Equal(expected, control.ForeColor); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> ForeColor_SetWithHandle_TestData() { yield return new object[] { Color.Empty, SystemColors.WindowText, 0 }; yield return new object[] { Color.FromArgb(254, 1, 2, 3), Color.FromArgb(254, 1, 2, 3), 1 }; yield return new object[] { Color.White, Color.White, 1 }; yield return new object[] { Color.Black, Color.Black, 1 }; yield return new object[] { Color.Red, Color.Red, 1 }; } [WinFormsTheory] [MemberData(nameof(ForeColor_SetWithHandle_TestData))] public void MonthCalendar_ForeColor_SetWithHandle_GetReturnsExpected(Color value, Color expected, int expectedInvalidatedCallCount) { using var control = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.ForeColor = value; Assert.Equal(expected, control.ForeColor); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.ForeColor = value; Assert.Equal(expected, control.ForeColor); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_ForeColor_SetWithHandler_CallsForeColorChanged() { using var control = new MonthCalendar(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); callCount++; }; control.ForeColorChanged += handler; // Set different. control.ForeColor = Color.Red; Assert.Equal(Color.Red, control.ForeColor); Assert.Equal(1, callCount); // Set same. control.ForeColor = Color.Red; Assert.Equal(Color.Red, control.ForeColor); Assert.Equal(1, callCount); // Set different. control.ForeColor = Color.Empty; Assert.Equal(SystemColors.WindowText, control.ForeColor); Assert.Equal(2, callCount); // Remove handler. control.ForeColorChanged -= handler; control.ForeColor = Color.Red; Assert.Equal(Color.Red, control.ForeColor); Assert.Equal(2, callCount); } [WinFormsFact] public void MonthCalendar_Handle_GetWithSelectionRange_Success() { var lower = new DateTime(2019, 1, 30, 3, 4, 5, 6); var upper = new DateTime(2019, 2, 3, 4, 5, 6, 7); using var control = new SubMonthCalendar { SelectionRange = new SelectionRange(lower, upper) }; Assert.NotEqual(IntPtr.Zero, control.Handle); Span<Kernel32.SYSTEMTIME> range = stackalloc Kernel32.SYSTEMTIME[2]; Assert.Equal((IntPtr)1, User32.SendMessageW(control.Handle, (User32.WM)ComCtl32.MCM.GETSELRANGE, IntPtr.Zero, ref range[0])); Assert.Equal(2019, range[0].wYear); Assert.Equal(1, range[0].wMonth); Assert.Equal(30, range[0].wDay); Assert.Equal(3, range[0].wDayOfWeek); Assert.True(range[0].wHour >= 0); Assert.True(range[0].wMinute >= 0); Assert.True(range[0].wSecond >= 0); Assert.True(range[0].wMilliseconds >= 0); Assert.Equal(2019, range[1].wYear); Assert.Equal(2, range[1].wMonth); Assert.Equal(3, range[1].wDay); Assert.Equal(0, range[1].wDayOfWeek); Assert.True(range[1].wHour >= 0); Assert.True(range[1].wMinute >= 0); Assert.True(range[1].wSecond >= 0); Assert.True(range[1].wMilliseconds >= 0); } [WinFormsFact] public void MonthCalendar_Handle_GetWithMaxSelectionCount_Success() { using var control = new SubMonthCalendar { MaxSelectionCount = 10 }; Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Equal((IntPtr)10, User32.SendMessageW(control.Handle, (User32.WM)ComCtl32.MCM.GETMAXSELCOUNT, IntPtr.Zero, IntPtr.Zero)); } [WinFormsFact] public void MonthCalendar_Handle_GetWithTodayDate_Success() { using var control = new SubMonthCalendar { TodayDate = new DateTime(2019, 1, 30, 3, 4, 5, 6) }; Assert.NotEqual(IntPtr.Zero, control.Handle); Kernel32.SYSTEMTIME date = default; Assert.Equal((IntPtr)1, User32.SendMessageW(control.Handle, (User32.WM)ComCtl32.MCM.GETTODAY, IntPtr.Zero, ref date)); Assert.Equal(2019, date.wYear); Assert.Equal(1, date.wMonth); Assert.Equal(30, date.wDay); Assert.Equal(3, date.wDayOfWeek); Assert.Equal(0, date.wHour); Assert.Equal(0, date.wMinute); Assert.Equal(0, date.wSecond); Assert.Equal(0, date.wMilliseconds); } [WinFormsFact] public void MonthCalendar_Handle_GetWithForeColor_Success() { using var control = new SubMonthCalendar { ForeColor = Color.FromArgb(0x12, 0x34, 0x56, 0x78) }; Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Equal((IntPtr)0x785634, User32.SendMessageW(control.Handle, (User32.WM)ComCtl32.MCM.GETCOLOR, (IntPtr)ComCtl32.MCSC.TEXT, IntPtr.Zero)); } [WinFormsFact] public void MonthCalendar_Handle_GetWithBackColor_Success() { using var control = new SubMonthCalendar { BackColor = Color.FromArgb(0xFF, 0x12, 0x34, 0x56) }; Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Equal((IntPtr)0x563412, User32.SendMessageW(control.Handle, (User32.WM)ComCtl32.MCM.GETCOLOR, (IntPtr)ComCtl32.MCSC.MONTHBK, IntPtr.Zero)); } [WinFormsFact] public void MonthCalendar_Handle_GetWithTitleBackColor_Success() { using var control = new SubMonthCalendar { TitleBackColor = Color.FromArgb(0x12, 0x34, 0x56, 0x78) }; Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Equal((IntPtr)0x785634, User32.SendMessageW(control.Handle, (User32.WM)ComCtl32.MCM.GETCOLOR, (IntPtr)ComCtl32.MCSC.TITLEBK, IntPtr.Zero)); } [WinFormsFact] public void MonthCalendar_Handle_GetWithTitleForeColor_Success() { using var control = new SubMonthCalendar { TitleForeColor = Color.FromArgb(0x12, 0x34, 0x56, 0x78) }; Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Equal((IntPtr)0x785634, User32.SendMessageW(control.Handle, (User32.WM)ComCtl32.MCM.GETCOLOR, (IntPtr)ComCtl32.MCSC.TITLETEXT, IntPtr.Zero)); } [WinFormsFact] public void MonthCalendar_Handle_GetWithTrailingForeColor_Success() { using var control = new SubMonthCalendar { TrailingForeColor = Color.FromArgb(0x12, 0x34, 0x56, 0x78) }; Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Equal((IntPtr)0x785634, User32.SendMessageW(control.Handle, (User32.WM)ComCtl32.MCM.GETCOLOR, (IntPtr)ComCtl32.MCSC.TRAILINGTEXT, IntPtr.Zero)); } [WinFormsFact] public void MonthCalendar_Handle_GetWithDefaultFirstDayOfWeek_Success() { using var control = new SubMonthCalendar { FirstDayOfWeek = Day.Default }; Assert.NotEqual(IntPtr.Zero, control.Handle); int expected = (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 6; while (expected > 6) { expected -= 7; } Assert.Equal((IntPtr)expected, User32.SendMessageW(control.Handle, (User32.WM)ComCtl32.MCM.GETFIRSTDAYOFWEEK, IntPtr.Zero, IntPtr.Zero)); } [WinFormsFact] public void MonthCalendar_Handle_GetWithFirstDayOfWeek_Success() { using var control = new SubMonthCalendar { FirstDayOfWeek = Day.Tuesday }; Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Equal((IntPtr)0x10001, User32.SendMessageW(control.Handle, (User32.WM)ComCtl32.MCM.GETFIRSTDAYOFWEEK, IntPtr.Zero, IntPtr.Zero)); } [WinFormsFact] public void MonthCalendar_Handle_GetWithRange_Success() { using var control = new SubMonthCalendar { MinDate = new DateTime(2019, 1, 2, 3, 4, 5, 6), MaxDate = new DateTime(2020, 2, 3, 4, 5, 6, 7) }; Assert.NotEqual(IntPtr.Zero, control.Handle); Span<Kernel32.SYSTEMTIME> range = stackalloc Kernel32.SYSTEMTIME[2]; Assert.Equal((IntPtr)3, User32.SendMessageW(control.Handle, (User32.WM)ComCtl32.MCM.GETRANGE, IntPtr.Zero, ref range[0])); Assert.Equal(2019, range[0].wYear); Assert.Equal(1, range[0].wMonth); Assert.Equal(2, range[0].wDay); Assert.Equal(3, range[0].wDayOfWeek); Assert.Equal(3, range[0].wHour); Assert.Equal(4, range[0].wMinute); Assert.Equal(5, range[0].wSecond); Assert.Equal(0, range[0].wMilliseconds); Assert.Equal(2020, range[1].wYear); Assert.Equal(2, range[1].wMonth); Assert.Equal(3, range[1].wDay); Assert.Equal(1, range[1].wDayOfWeek); Assert.Equal(4, range[1].wHour); Assert.Equal(5, range[1].wMinute); Assert.Equal(6, range[1].wSecond); Assert.Equal(0, range[1].wMilliseconds); } [WinFormsFact] public void MonthCalendar_Handle_GetWithScrollChange_Success() { using var control = new SubMonthCalendar { ScrollChange = 10 }; Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Equal((IntPtr)10, User32.SendMessageW(control.Handle, (User32.WM)ComCtl32.MCM.GETMONTHDELTA, IntPtr.Zero, IntPtr.Zero)); } public static IEnumerable<object[]> ImeMode_Set_TestData() { yield return new object[] { ImeMode.Inherit, ImeMode.NoControl }; yield return new object[] { ImeMode.NoControl, ImeMode.NoControl }; yield return new object[] { ImeMode.On, ImeMode.On }; yield return new object[] { ImeMode.Off, ImeMode.Off }; yield return new object[] { ImeMode.Disable, ImeMode.Disable }; yield return new object[] { ImeMode.Hiragana, ImeMode.Hiragana }; yield return new object[] { ImeMode.Katakana, ImeMode.Katakana }; yield return new object[] { ImeMode.KatakanaHalf, ImeMode.KatakanaHalf }; yield return new object[] { ImeMode.AlphaFull, ImeMode.AlphaFull }; yield return new object[] { ImeMode.Alpha, ImeMode.Alpha }; yield return new object[] { ImeMode.HangulFull, ImeMode.HangulFull }; yield return new object[] { ImeMode.Hangul, ImeMode.Hangul }; yield return new object[] { ImeMode.Close, ImeMode.Close }; yield return new object[] { ImeMode.OnHalf, ImeMode.On }; } [WinFormsTheory] [MemberData(nameof(ImeMode_Set_TestData))] public void MonthCalendar_ImeMode_Set_GetReturnsExpected(ImeMode value, ImeMode expected) { using var control = new MonthCalendar { ImeMode = value }; Assert.Equal(expected, control.ImeMode); Assert.False(control.IsHandleCreated); // Set same. control.ImeMode = value; Assert.Equal(expected, control.ImeMode); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(ImeMode_Set_TestData))] public void MonthCalendar_ImeMode_SetWithHandle_GetReturnsExpected(ImeMode value, ImeMode expected) { using var control = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.ImeMode = value; Assert.Equal(expected, control.ImeMode); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.ImeMode = value; Assert.Equal(expected, control.ImeMode); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_ImeMode_SetWithHandler_CallsImeModeChanged() { using var control = new MonthCalendar(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); callCount++; }; control.ImeModeChanged += handler; // Set different. control.ImeMode = ImeMode.On; Assert.Equal(ImeMode.On, control.ImeMode); Assert.Equal(0, callCount); // Set same. control.ImeMode = ImeMode.On; Assert.Equal(ImeMode.On, control.ImeMode); Assert.Equal(0, callCount); // Set different. control.ImeMode = ImeMode.Off; Assert.Equal(ImeMode.Off, control.ImeMode); Assert.Equal(0, callCount); // Remove handler. control.ImeModeChanged -= handler; control.ImeMode = ImeMode.Off; Assert.Equal(ImeMode.Off, control.ImeMode); Assert.Equal(0, callCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(ImeMode))] public void MonthCalendar_ImeMode_SetInvalid_ThrowsInvalidEnumArgumentException(ImeMode value) { using var control = new MonthCalendar(); Assert.Throws<InvalidEnumArgumentException>("value", () => control.ImeMode = value); } public static IEnumerable<object[]> MaxDate_Set_TestData() { yield return new object[] { new DateTime(1753, 1, 1), new DateTime(1753, 1, 1), new DateTime(1753, 1, 1) }; yield return new object[] { new DateTime(2019, 1, 29), new DateTime(2019, 1, 29), new DateTime(2019, 1, 29) }; yield return new object[] { new DateTime(9998, 12, 31), new DateTime(9998, 12, 31), DateTime.Now.Date }; yield return new object[] { new DateTime(9999, 1, 1), new DateTime(9998, 12, 31), DateTime.Now.Date }; yield return new object[] { DateTime.MaxValue, new DateTime(9998, 12, 31), DateTime.Now.Date }; } [WinFormsTheory] [MemberData(nameof(MaxDate_Set_TestData))] public void MonthCalendar_MaxDate_Set_GetReturnsExpected(DateTime value, DateTime expected, DateTime expectedSelection) { using var calendar = new MonthCalendar { MaxDate = value }; Assert.Equal(expected, calendar.MaxDate); Assert.Equal(expectedSelection, calendar.SelectionStart); Assert.Equal(expectedSelection, calendar.SelectionEnd); Assert.False(calendar.IsHandleCreated); // Set same. calendar.MaxDate = value; Assert.Equal(expected, calendar.MaxDate); Assert.Equal(expectedSelection, calendar.SelectionStart); Assert.Equal(expectedSelection, calendar.SelectionEnd); Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(MaxDate_Set_TestData))] public void MonthCalendar_MaxDate_SetWithHandle_GetReturnsExpected(DateTime value, DateTime expected, DateTime expectedSelection) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.MaxDate = value; Assert.Equal(expected, calendar.MaxDate); Assert.Equal(expectedSelection, calendar.SelectionStart); Assert.Equal(expectedSelection, calendar.SelectionEnd); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. calendar.MaxDate = value; Assert.Equal(expected, calendar.MaxDate); Assert.Equal(expectedSelection, calendar.SelectionStart); Assert.Equal(expectedSelection, calendar.SelectionEnd); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_MaxDate_SetLessThanMinDate_ThrowsArgumentOutOfRangeException() { using var calendar = new MonthCalendar(); Assert.Throws<ArgumentOutOfRangeException>("value", () => calendar.MaxDate = calendar.MinDate.AddTicks(-1)); } public static IEnumerable<object[]> MaxSelectionCount_Set_TestData() { yield return new object[] { 1 }; yield return new object[] { 2 }; yield return new object[] { 7 }; yield return new object[] { 8 }; yield return new object[] { int.MaxValue }; } [WinFormsTheory] [MemberData(nameof(MaxSelectionCount_Set_TestData))] public void MonthCalendar_MaxSelectionCount_Set_GetReturnsExpected(int value) { using var calendar = new MonthCalendar { MaxSelectionCount = value }; Assert.Equal(value, calendar.MaxSelectionCount); Assert.False(calendar.IsHandleCreated); // Set same. calendar.MaxSelectionCount = value; Assert.Equal(value, calendar.MaxSelectionCount); Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(MaxSelectionCount_Set_TestData))] public void MonthCalendar_MaxSelectionCount_SetWithHandle_GetReturnsExpected(int value) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.MaxSelectionCount = value; Assert.Equal(value, calendar.MaxSelectionCount); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. calendar.MaxSelectionCount = value; Assert.Equal(value, calendar.MaxSelectionCount); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [InlineData(0)] [InlineData(-1)] public void MonthCalendar_MaxSelectionCount_SetLessThanOne_ThrowsArgumentOutOfRangeException(int value) { using var calendar = new MonthCalendar(); Assert.Throws<ArgumentOutOfRangeException>("value", () => calendar.MaxSelectionCount = value); } public static IEnumerable<object[]> MinDate_Set_TestData() { yield return new object[] { DateTime.MinValue, new DateTime(1753, 1, 1), DateTime.Now.Date }; yield return new object[] { new DateTime(1753, 1, 1), new DateTime(1753, 1, 1), DateTime.Now.Date }; yield return new object[] { new DateTime(2019, 1, 29), new DateTime(2019, 1, 29), DateTime.Now.Date }; yield return new object[] { new DateTime(9998, 12, 31), new DateTime(9998, 12, 31), new DateTime(9998, 12, 31) }; } [WinFormsTheory] [MemberData(nameof(MinDate_Set_TestData))] public void MonthCalendar_MinDate_Set_GetReturnsExpected(DateTime value, DateTime expected, DateTime expectedSelection) { using var calendar = new MonthCalendar { MinDate = value }; Assert.Equal(expected, calendar.MinDate); Assert.Equal(expectedSelection, calendar.SelectionStart); Assert.Equal(expectedSelection, calendar.SelectionEnd); Assert.False(calendar.IsHandleCreated); // Set same. calendar.MinDate = value; Assert.Equal(expected, calendar.MinDate); Assert.Equal(expectedSelection, calendar.SelectionStart); Assert.Equal(expectedSelection, calendar.SelectionEnd); Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(MinDate_Set_TestData))] public void MonthCalendar_MinDate_SetWithHandle_GetReturnsExpected(DateTime value, DateTime expected, DateTime expectedSelection) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.MinDate = value; Assert.Equal(expected, calendar.MinDate); Assert.Equal(expectedSelection, calendar.SelectionStart); Assert.Equal(expectedSelection, calendar.SelectionEnd); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. calendar.MinDate = value; Assert.Equal(expected, calendar.MinDate); Assert.Equal(expectedSelection, calendar.SelectionStart); Assert.Equal(expectedSelection, calendar.SelectionEnd); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_MinDate_SetLessThanMaxDate_ThrowsArgumentOutOfRangeException() { using var calendar = new MonthCalendar(); Assert.Throws<ArgumentOutOfRangeException>("value", () => calendar.MinDate = calendar.MaxDate.AddTicks(1)); } [WinFormsFact] public void MonthCalendar_MinDate_SetLessThanMinDate_ThrowsArgumentOutOfRangeException() { using var calendar = new MonthCalendar(); Assert.Throws<ArgumentOutOfRangeException>("value", () => calendar.MinDate = calendar.MinDate.AddTicks(-1)); } public static IEnumerable<object[]> MonthlyBoldedDates_Set_TestData() { yield return new object[] { null, Array.Empty<DateTime>() }; yield return new object[] { Array.Empty<DateTime>(), Array.Empty<DateTime>() }; yield return new object[] { new DateTime[] { new DateTime(2019, 01, 1), new DateTime(2019, 01, 20) }, new DateTime[] { new DateTime(2019, 01, 1), new DateTime(2019, 01, 20) } }; yield return new object[] { new DateTime[] { new DateTime(2017, 01, 1), new DateTime(2018, 01, 20) }, new DateTime[] { new DateTime(2017, 01, 1), new DateTime(2018, 01, 20) } }; yield return new object[] { new DateTime[] { new DateTime(2019, 01, 1), new DateTime(2019, 01, 1), new DateTime(2018, 01, 1) }, new DateTime[] { new DateTime(2019, 01, 1), new DateTime(2019, 01, 1), new DateTime(2018, 01, 1) } }; yield return new object[] { new DateTime[] { DateTime.MinValue, DateTime.MaxValue }, new DateTime[] { DateTime.MinValue, DateTime.MaxValue } }; var everyMonth = new DateTime[] { new DateTime(2019, 01, 1), new DateTime(2019, 02, 2), new DateTime(2019, 03, 3), new DateTime(2019, 04, 4), new DateTime(2019, 05, 5), new DateTime(2019, 06, 6), new DateTime(2019, 07, 7), new DateTime(2019, 08, 8), new DateTime(2019, 09, 9), new DateTime(2019, 10, 10), new DateTime(2019, 11, 11), new DateTime(2019, 12, 12), }; yield return new object[] { everyMonth, everyMonth }; } [WinFormsTheory] [MemberData(nameof(MonthlyBoldedDates_Set_TestData))] public void MonthCalendar_MonthlyBoldedDates_Set_GetReturnsExpected(DateTime[] value, DateTime[] expected) { using var calendar = new MonthCalendar { MonthlyBoldedDates = value }; Assert.Equal(expected, calendar.MonthlyBoldedDates); Assert.NotSame(value, calendar.MonthlyBoldedDates); if (value?.Length > 0) { Assert.NotSame(calendar.MonthlyBoldedDates, calendar.MonthlyBoldedDates); } else { Assert.Same(calendar.MonthlyBoldedDates, calendar.MonthlyBoldedDates); } Assert.False(calendar.IsHandleCreated); // Set same. calendar.MonthlyBoldedDates = value; Assert.Equal(expected, calendar.MonthlyBoldedDates); Assert.NotSame(value, calendar.MonthlyBoldedDates); if (value?.Length > 0) { Assert.NotSame(calendar.MonthlyBoldedDates, calendar.MonthlyBoldedDates); } else { Assert.Same(calendar.MonthlyBoldedDates, calendar.MonthlyBoldedDates); } Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(MonthlyBoldedDates_Set_TestData))] public void MonthCalendar_MonthlyBoldedDates_SetWithHandle_GetReturnsExpected(DateTime[] value, DateTime[] expected) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.MonthlyBoldedDates = value; Assert.Equal(expected, calendar.MonthlyBoldedDates); Assert.NotSame(value, calendar.MonthlyBoldedDates); if (value?.Length > 0) { Assert.NotSame(calendar.MonthlyBoldedDates, calendar.MonthlyBoldedDates); } else { Assert.Same(calendar.MonthlyBoldedDates, calendar.MonthlyBoldedDates); } Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. calendar.MonthlyBoldedDates = value; Assert.Equal(expected, calendar.MonthlyBoldedDates); Assert.NotSame(value, calendar.MonthlyBoldedDates); if (value?.Length > 0) { Assert.NotSame(calendar.MonthlyBoldedDates, calendar.MonthlyBoldedDates); } else { Assert.Same(calendar.MonthlyBoldedDates, calendar.MonthlyBoldedDates); } Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelperEx), nameof(CommonTestHelperEx.GetPaddingNormalizedTheoryData))] public void MonthCalendar_Padding_Set_GetReturnsExpected(Padding value, Padding expected) { using var control = new MonthCalendar { Padding = value }; Assert.Equal(expected, control.Padding); Assert.False(control.IsHandleCreated); // Set same. control.Padding = value; Assert.Equal(expected, control.Padding); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelperEx), nameof(CommonTestHelperEx.GetPaddingNormalizedTheoryData))] public void MonthCalendar_Padding_SetWithHandle_GetReturnsExpected(Padding value, Padding expected) { using var control = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.Padding = value; Assert.Equal(expected, control.Padding); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.Padding = value; Assert.Equal(expected, control.Padding); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_Padding_SetWithHandler_CallsPaddingChanged() { using var control = new MonthCalendar(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Equal(control, sender); Assert.Equal(EventArgs.Empty, e); callCount++; }; control.PaddingChanged += handler; // Set different. var padding1 = new Padding(1); control.Padding = padding1; Assert.Equal(padding1, control.Padding); Assert.Equal(1, callCount); // Set same. control.Padding = padding1; Assert.Equal(padding1, control.Padding); Assert.Equal(1, callCount); // Set different. var padding2 = new Padding(2); control.Padding = padding2; Assert.Equal(padding2, control.Padding); Assert.Equal(2, callCount); // Remove handler. control.PaddingChanged -= handler; control.Padding = padding1; Assert.Equal(padding1, control.Padding); Assert.Equal(2, callCount); } [WinFormsTheory] [InlineData(RightToLeft.Yes, true, 1)] [InlineData(RightToLeft.Yes, false, 0)] [InlineData(RightToLeft.No, true, 1)] [InlineData(RightToLeft.No, false, 0)] [InlineData(RightToLeft.Inherit, true, 1)] [InlineData(RightToLeft.Inherit, false, 0)] public void MonthCalendar_RightToLeftLayout_Set_GetReturnsExpected(RightToLeft rightToLeft, bool value, int expectedLayoutCallCount) { using var control = new MonthCalendar { RightToLeft = rightToLeft }; int layoutCallCount = 0; control.Layout += (sender, e) => { Assert.Same(control, sender); Assert.Same(control, e.AffectedControl); Assert.Equal("RightToLeftLayout", e.AffectedProperty); layoutCallCount++; }; control.RightToLeftLayout = value; Assert.Equal(value, control.RightToLeftLayout); Assert.Equal(expectedLayoutCallCount, layoutCallCount); Assert.False(control.IsHandleCreated); // Set same. control.RightToLeftLayout = value; Assert.Equal(value, control.RightToLeftLayout); Assert.Equal(expectedLayoutCallCount, layoutCallCount); Assert.False(control.IsHandleCreated); // Set different. control.RightToLeftLayout = !value; Assert.Equal(!value, control.RightToLeftLayout); Assert.Equal(expectedLayoutCallCount + 1, layoutCallCount); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(RightToLeft.Yes, true, 1, 1, 2)] [InlineData(RightToLeft.Yes, false, 0, 0, 1)] [InlineData(RightToLeft.No, true, 1, 0, 0)] [InlineData(RightToLeft.No, false, 0, 0, 0)] [InlineData(RightToLeft.Inherit, true, 1, 0, 0)] [InlineData(RightToLeft.Inherit, false, 0, 0, 0)] public void MonthCalendar_RightToLeftLayout_SetWithHandle_GetReturnsExpected(RightToLeft rightToLeft, bool value, int expectedLayoutCallCount, int expectedCreatedCallCount1, int expectedCreatedCallCount2) { using var control = new MonthCalendar { RightToLeft = rightToLeft }; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; int layoutCallCount = 0; control.Layout += (sender, e) => { Assert.Same(control, sender); Assert.Same(control, e.AffectedControl); Assert.Equal("RightToLeftLayout", e.AffectedProperty); layoutCallCount++; }; control.RightToLeftLayout = value; Assert.Equal(value, control.RightToLeftLayout); Assert.Equal(expectedLayoutCallCount, layoutCallCount); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount1, createdCallCount); // Set same. control.RightToLeftLayout = value; Assert.Equal(value, control.RightToLeftLayout); Assert.Equal(expectedLayoutCallCount, layoutCallCount); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount1, createdCallCount); // Set different. control.RightToLeftLayout = !value; Assert.Equal(!value, control.RightToLeftLayout); Assert.Equal(expectedLayoutCallCount + 1, layoutCallCount); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount2, createdCallCount); } [WinFormsFact] public void MonthCalendar_RightToLeftLayout_SetWithHandler_CallsRightToLeftLayoutChanged() { using var control = new MonthCalendar { RightToLeftLayout = true }; int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); callCount++; }; control.RightToLeftLayoutChanged += handler; // Set different. control.RightToLeftLayout = false; Assert.False(control.RightToLeftLayout); Assert.Equal(1, callCount); // Set same. control.RightToLeftLayout = false; Assert.False(control.RightToLeftLayout); Assert.Equal(1, callCount); // Set different. control.RightToLeftLayout = true; Assert.True(control.RightToLeftLayout); Assert.Equal(2, callCount); // Remove handler. control.RightToLeftLayoutChanged -= handler; control.RightToLeftLayout = false; Assert.False(control.RightToLeftLayout); Assert.Equal(2, callCount); } [WinFormsFact] public void MonthCalendar_RightToLeftLayout_SetWithHandlerInDisposing_DoesNotRightToLeftLayoutChanged() { using var control = new MonthCalendar { RightToLeft = RightToLeft.Yes }; Assert.NotEqual(IntPtr.Zero, control.Handle); int callCount = 0; control.RightToLeftLayoutChanged += (sender, e) => callCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; int disposedCallCount = 0; control.Disposed += (sender, e) => { control.RightToLeftLayout = true; Assert.True(control.RightToLeftLayout); Assert.Equal(0, callCount); Assert.Equal(0, createdCallCount); disposedCallCount++; }; control.Dispose(); Assert.Equal(1, disposedCallCount); } public static IEnumerable<object[]> ScrollChange_Set_TestData() { yield return new object[] { 0 }; yield return new object[] { 1 }; yield return new object[] { 2 }; yield return new object[] { 20000 }; } [WinFormsTheory] [MemberData(nameof(ScrollChange_Set_TestData))] public void MonthCalendar_ScrollChange_Set_GetReturnsExpected(int value) { using var calendar = new MonthCalendar { ScrollChange = value }; Assert.Equal(value, calendar.ScrollChange); Assert.False(calendar.IsHandleCreated); // Set same. calendar.ScrollChange = value; Assert.Equal(value, calendar.ScrollChange); Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(ScrollChange_Set_TestData))] public void MonthCalendar_ScrollChange_SetWithHandle_GetReturnsExpected(int value) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.ScrollChange = value; Assert.Equal(value, calendar.ScrollChange); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. calendar.ScrollChange = value; Assert.Equal(value, calendar.ScrollChange); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [InlineData(-1)] [InlineData(200001)] public void MonthCalendar_ScrollChange_SetInvalid_ThrowsArgumentOutOfRangeException(int value) { using var calendar = new MonthCalendar(); Assert.Throws<ArgumentOutOfRangeException>("value", () => calendar.ScrollChange = value); } public static IEnumerable<object[]> SelectionStart_Set_TestData() { yield return new object[] { DateTime.MinValue, new DateTime(1, 1, 7) }; yield return new object[] { new DateTime(1753, 1, 1), new DateTime(1753, 1, 7) }; yield return new object[] { new DateTime(1753, 1, 1).AddHours(1), new DateTime(1753, 1, 7).AddHours(1) }; yield return new object[] { new DateTime(2019, 1, 29), new DateTime(2019, 2, 4) }; yield return new object[] { DateTime.Now.Date.AddDays(-1), DateTime.Now.Date }; yield return new object[] { DateTime.Now.Date, DateTime.Now.Date }; yield return new object[] { new DateTime(9998, 12, 31), new DateTime(9998, 12, 31) }; yield return new object[] { DateTime.MaxValue, DateTime.MaxValue }; } [WinFormsTheory] [MemberData(nameof(SelectionStart_Set_TestData))] public void MonthCalendar_SelectionStart_Set_GetReturnsExpected(DateTime value, DateTime expectedSelectionEnd) { using var calendar = new MonthCalendar { SelectionStart = value }; Assert.Equal(value, calendar.SelectionStart); Assert.Equal(expectedSelectionEnd, calendar.SelectionEnd); Assert.False(calendar.IsHandleCreated); // Set same. calendar.SelectionStart = value; Assert.Equal(value, calendar.SelectionStart); Assert.Equal(expectedSelectionEnd, calendar.SelectionEnd); Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(SelectionStart_Set_TestData))] public void MonthCalendar_SelectionStart_SetWithHandle_GetReturnsExpected(DateTime value, DateTime expectedSelectionEnd) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.SelectionStart = value; Assert.Equal(value, calendar.SelectionStart); Assert.Equal(expectedSelectionEnd, calendar.SelectionEnd); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. calendar.SelectionStart = value; Assert.Equal(value, calendar.SelectionStart); Assert.Equal(expectedSelectionEnd, calendar.SelectionEnd); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_SelectionStart_SetLessThanMinDate_ThrowsArgumentOutOfRangeException() { using var calendar = new MonthCalendar(); calendar.SelectionStart = calendar.MinDate.AddTicks(-1); Assert.Equal(calendar.MinDate.AddTicks(-1), calendar.SelectionStart); calendar.MinDate = new DateTime(2019, 10, 3); Assert.Throws<ArgumentOutOfRangeException>("value", () => calendar.SelectionStart = calendar.MinDate.AddTicks(-1)); } [WinFormsFact] public void MonthCalendar_SelectionStart_SetGreaterThanMaxDate_ThrowsArgumentOutOfRangeException() { using var calendar = new MonthCalendar(); calendar.SelectionStart = calendar.MaxDate.AddTicks(1); Assert.Equal(calendar.MaxDate.AddTicks(1), calendar.SelectionStart); calendar.MaxDate = new DateTime(2019, 9, 3); Assert.Throws<ArgumentOutOfRangeException>("value", () => calendar.SelectionStart = calendar.MaxDate.AddTicks(1)); } public static IEnumerable<object[]> SelectionEnd_Set_TestData() { yield return new object[] { new DateTime(1753, 1, 1), new DateTime(1753, 1, 1) }; yield return new object[] { new DateTime(1753, 1, 1).AddHours(1), new DateTime(1753, 1, 1).AddHours(1) }; yield return new object[] { new DateTime(2019, 1, 29), new DateTime(2019, 1, 29) }; yield return new object[] { DateTime.Now.Date.AddDays(1), DateTime.Now.Date }; yield return new object[] { DateTime.Now.Date, DateTime.Now.Date }; yield return new object[] { new DateTime(9998, 12, 31), new DateTime(9998, 12, 25) }; } [WinFormsTheory] [MemberData(nameof(SelectionEnd_Set_TestData))] public void MonthCalendar_SelectionEnd_Set_GetReturnsExpected(DateTime value, DateTime expectedSelectionStart) { using var calendar = new MonthCalendar { SelectionEnd = value }; Assert.Equal(value, calendar.SelectionEnd); Assert.Equal(expectedSelectionStart, calendar.SelectionStart); Assert.False(calendar.IsHandleCreated); // Set same. calendar.SelectionEnd = value; Assert.Equal(value, calendar.SelectionEnd); Assert.Equal(expectedSelectionStart, calendar.SelectionStart); Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(SelectionEnd_Set_TestData))] public void MonthCalendar_SelectionEnd_SetWithHandle_GetReturnsExpected(DateTime value, DateTime expectedSelectionStart) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.SelectionEnd = value; Assert.Equal(value, calendar.SelectionEnd); Assert.Equal(expectedSelectionStart, calendar.SelectionStart); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. calendar.SelectionEnd = value; Assert.Equal(value, calendar.SelectionEnd); Assert.Equal(expectedSelectionStart, calendar.SelectionStart); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_SelectionEnd_SetLessThanMinDate_ThrowsArgumentOutOfRangeException() { using var calendar = new MonthCalendar(); Assert.Throws<ArgumentOutOfRangeException>("value", () => calendar.SelectionEnd = calendar.MinDate.AddTicks(-1)); calendar.MinDate = new DateTime(2019, 10, 3); Assert.Throws<ArgumentOutOfRangeException>("value", () => calendar.SelectionEnd = calendar.MinDate.AddTicks(-1)); } [WinFormsFact] public void MonthCalendar_SelectionEnd_SetGreaterThanMaxDate_ThrowsArgumentOutOfRangeException() { using var calendar = new MonthCalendar(); Assert.Throws<ArgumentOutOfRangeException>("value", () => calendar.SelectionEnd = calendar.MaxDate.AddTicks(1)); calendar.MaxDate = new DateTime(2019, 9, 3); Assert.Throws<ArgumentOutOfRangeException>("value", () => calendar.SelectionEnd = calendar.MaxDate.AddTicks(1)); } public static IEnumerable<object[]> SelectionRange_Set_TestData() { yield return new object[] { new SelectionRange(DateTime.MinValue, DateTime.MinValue), DateTime.MinValue, DateTime.MinValue }; yield return new object[] { new SelectionRange(new DateTime(1753, 1, 1).AddTicks(-1), new DateTime(1753, 1, 1).AddTicks(-1)), new DateTime(1752, 12, 31), new DateTime(1752, 12, 31) }; yield return new object[] { new SelectionRange(new DateTime(1753, 1, 1), new DateTime(1753, 1, 1)), new DateTime(1753, 1, 1), new DateTime(1753, 1, 1) }; yield return new object[] { new SelectionRange(new DateTime(1753, 1, 1), new DateTime(1753, 1, 2)), new DateTime(1753, 1, 1), new DateTime(1753, 1, 2) }; yield return new object[] { new SelectionRange(new DateTime(2019, 9, 1), new DateTime(2019, 9, 1)), new DateTime(2019, 9, 1), new DateTime(2019, 9, 1) }; yield return new object[] { new SelectionRange(new DateTime(2019, 9, 1), new DateTime(2019, 9, 2)), new DateTime(2019, 9, 1), new DateTime(2019, 9, 2) }; yield return new object[] { new SelectionRange(new DateTime(2019, 9, 1).AddHours(1), new DateTime(2019, 9, 2).AddHours(1)), new DateTime(2019, 9, 1), new DateTime(2019, 9, 2) }; yield return new object[] { new SelectionRange(new DateTime(2019, 9, 2), new DateTime(2019, 9, 1)), new DateTime(2019, 9, 1), new DateTime(2019, 9, 2) }; yield return new object[] { new SelectionRange(new DateTime(2019, 9, 1), new DateTime(2019, 9, 7)), new DateTime(2019, 9, 1), new DateTime(2019, 9, 7) }; yield return new object[] { new SelectionRange(new DateTime(2019, 9, 1), new DateTime(2019, 9, 8)), new DateTime(2019, 9, 1), new DateTime(2019, 9, 7) }; yield return new object[] { new SelectionRange(DateTime.Now.Date, DateTime.Now.Date), DateTime.Now.Date, DateTime.Now.Date }; yield return new object[] { new SelectionRange(DateTime.Now.Date, DateTime.Now.Date.AddDays(1)), DateTime.Now.Date, DateTime.Now.Date.AddDays(1) }; yield return new object[] { new SelectionRange(DateTime.Now.Date.AddHours(1), DateTime.Now.Date.AddHours(1)), DateTime.Now.Date, DateTime.Now.Date }; yield return new object[] { new SelectionRange(DateTime.Now.Date.AddDays(1), DateTime.Now.Date), DateTime.Now.Date, DateTime.Now.Date.AddDays(1) }; yield return new object[] { new SelectionRange(DateTime.Now.Date, DateTime.Now.Date.AddDays(6)), DateTime.Now.Date, DateTime.Now.Date.AddDays(6) }; yield return new object[] { new SelectionRange(DateTime.Now.Date, DateTime.Now.Date.AddDays(7)), DateTime.Now.Date.AddDays(1), DateTime.Now.Date.AddDays(7) }; yield return new object[] { new SelectionRange(new DateTime(9998, 12, 30), new DateTime(9998, 12, 31)), new DateTime(9998, 12, 30), new DateTime(9998, 12, 31) }; yield return new object[] { new SelectionRange(new DateTime(9998, 12, 31), new DateTime(9998, 12, 31)), new DateTime(9998, 12, 31), new DateTime(9998, 12, 31) }; yield return new object[] { new SelectionRange(new DateTime(9998, 12, 31).AddTicks(1), new DateTime(9998, 12, 31).AddTicks(1)), new DateTime(9998, 12, 31), new DateTime(9998, 12, 31) }; yield return new object[] { new SelectionRange(DateTime.MaxValue, DateTime.MaxValue), DateTime.MaxValue.Date, DateTime.MaxValue.Date }; } [WinFormsTheory] [MemberData(nameof(SelectionRange_Set_TestData))] public void MonthCalendar_SelectionRange_Set_GetReturnsExpected(SelectionRange value, DateTime expectedSelectionStart, DateTime expectedSelectionEnd) { using var calendar = new MonthCalendar { SelectionRange = value }; Assert.Equal(expectedSelectionStart, calendar.SelectionRange.Start); Assert.Equal(expectedSelectionEnd, calendar.SelectionRange.End); Assert.Equal(expectedSelectionStart, calendar.SelectionStart); Assert.Equal(expectedSelectionEnd, calendar.SelectionEnd); Assert.NotSame(value, calendar.SelectionRange); Assert.False(calendar.IsHandleCreated); // Set same. calendar.SelectionRange = new SelectionRange(expectedSelectionStart, expectedSelectionEnd); Assert.Equal(expectedSelectionStart, calendar.SelectionRange.Start); Assert.Equal(expectedSelectionEnd, calendar.SelectionRange.End); Assert.Equal(expectedSelectionStart, calendar.SelectionStart); Assert.Equal(expectedSelectionEnd, calendar.SelectionEnd); Assert.NotSame(value, calendar.SelectionRange); Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(SelectionRange_Set_TestData))] public void MonthCalendar_SelectionRange_SetWithHandle_GetReturnsExpected(SelectionRange value, DateTime expectedSelectionStart, DateTime expectedSelectionEnd) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.SelectionRange = value; Assert.Equal(expectedSelectionStart, calendar.SelectionRange.Start); Assert.Equal(expectedSelectionEnd, calendar.SelectionRange.End); Assert.Equal(expectedSelectionStart, calendar.SelectionStart); Assert.Equal(expectedSelectionEnd, calendar.SelectionEnd); Assert.NotSame(value, calendar.SelectionRange); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. calendar.SelectionRange = new SelectionRange(expectedSelectionStart, expectedSelectionEnd); Assert.Equal(expectedSelectionStart, calendar.SelectionRange.Start); Assert.Equal(expectedSelectionEnd, calendar.SelectionRange.End); Assert.Equal(expectedSelectionStart, calendar.SelectionStart); Assert.Equal(expectedSelectionEnd, calendar.SelectionEnd); Assert.NotSame(value, calendar.SelectionRange); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_SelectionRange_SetLessThanMinDate_ThrowsArgumentOutOfRangeException() { using var calendar = new MonthCalendar(); calendar.SelectionRange = new SelectionRange(calendar.MinDate.AddTicks(-1), calendar.MinDate); Assert.Equal(calendar.MinDate.AddTicks(-1).Date, calendar.SelectionStart); Assert.Equal(calendar.MinDate, calendar.SelectionEnd); calendar.SelectionRange = new SelectionRange(calendar.MinDate, calendar.MinDate.AddTicks(-1)); Assert.Equal(calendar.MinDate.AddTicks(-1).Date, calendar.SelectionStart); Assert.Equal(calendar.MinDate, calendar.SelectionEnd); calendar.MinDate = new DateTime(2019, 10, 3); Assert.Throws<ArgumentOutOfRangeException>("date1", () => calendar.SelectionRange = new SelectionRange(calendar.MinDate.AddTicks(-1), calendar.MinDate)); Assert.Throws<ArgumentOutOfRangeException>("date1", () => calendar.SelectionRange = new SelectionRange(calendar.MinDate, calendar.MinDate.AddTicks(-1))); } [WinFormsFact] public void MonthCalendar_SelectionRange_SetGreaterThanMaxDate_ThrowsArgumentOutOfRangeException() { using var calendar = new MonthCalendar(); calendar.SelectionRange = new SelectionRange(calendar.MaxDate.AddTicks(1), calendar.MaxDate); Assert.Equal(calendar.MaxDate, calendar.SelectionStart); Assert.Equal(calendar.MaxDate.AddTicks(1).Date, calendar.SelectionEnd); calendar.SelectionRange = new SelectionRange(calendar.MaxDate, calendar.MaxDate.AddTicks(1)); Assert.Equal(calendar.MaxDate, calendar.SelectionStart); Assert.Equal(calendar.MaxDate.AddTicks(1).Date, calendar.SelectionEnd); calendar.MaxDate = new DateTime(2019, 9, 3); Assert.Throws<ArgumentOutOfRangeException>("date2", () => calendar.SelectionRange = new SelectionRange(calendar.MaxDate.AddDays(1), calendar.MaxDate)); Assert.Throws<ArgumentOutOfRangeException>("date2", () => calendar.SelectionRange = new SelectionRange(calendar.MaxDate, calendar.MaxDate.AddDays(1))); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))] public void MonthCalendar_ShowToday_Set_GetReturnsExpected(bool value) { using var control = new SubMonthCalendar { ShowToday = value }; Assert.Equal(value, control.ShowToday); Assert.False(control.IsHandleCreated); // Set same. control.ShowToday = value; Assert.Equal(value, control.ShowToday); Assert.False(control.IsHandleCreated); // Set different. control.ShowToday = !value; Assert.Equal(!value, control.ShowToday); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(true, 0)] [InlineData(false, 1)] public void MonthCalendar_ShowToday_SetWithHandle_GetReturnsExpected(bool value, int expectedStyleChangedCallCount) { using var control = new SubMonthCalendar(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.ShowToday = value; Assert.Equal(value, control.ShowToday); Assert.True(control.IsHandleCreated); Assert.Equal(expectedStyleChangedCallCount, invalidatedCallCount); Assert.Equal(expectedStyleChangedCallCount, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.ShowToday = value; Assert.Equal(value, control.ShowToday); Assert.True(control.IsHandleCreated); Assert.Equal(expectedStyleChangedCallCount, invalidatedCallCount); Assert.Equal(expectedStyleChangedCallCount, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set different. control.ShowToday = !value; Assert.Equal(!value, control.ShowToday); Assert.True(control.IsHandleCreated); Assert.Equal(expectedStyleChangedCallCount + 1, invalidatedCallCount); Assert.Equal(expectedStyleChangedCallCount + 1, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_CreateAccessibilityInstance_Invoke_ReturnsExpected() { using var control = new SubMonthCalendar(); Control.ControlAccessibleObject instance = Assert.IsAssignableFrom<Control.ControlAccessibleObject>(control.CreateAccessibilityInstance()); Assert.NotNull(instance); Assert.Same(control, instance.Owner); Assert.Equal(AccessibleRole.Table, instance.Role); Assert.NotSame(control.CreateAccessibilityInstance(), instance); Assert.NotSame(control.AccessibilityObject, instance); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))] public void MonthCalendar_ShowTodayCircle_Set_GetReturnsExpected(bool value) { using var control = new SubMonthCalendar { ShowTodayCircle = value }; Assert.Equal(value, control.ShowTodayCircle); Assert.False(control.IsHandleCreated); // Set same. control.ShowTodayCircle = value; Assert.Equal(value, control.ShowTodayCircle); Assert.False(control.IsHandleCreated); // Set different. control.ShowTodayCircle = !value; Assert.Equal(!value, control.ShowTodayCircle); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(true, 0)] [InlineData(false, 1)] public void MonthCalendar_ShowTodayCircle_SetWithHandle_GetReturnsExpected(bool value, int expectedStyleChangedCallCount) { using var control = new SubMonthCalendar(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.ShowTodayCircle = value; Assert.Equal(value, control.ShowTodayCircle); Assert.True(control.IsHandleCreated); Assert.Equal(expectedStyleChangedCallCount, invalidatedCallCount); Assert.Equal(expectedStyleChangedCallCount, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.ShowTodayCircle = value; Assert.Equal(value, control.ShowTodayCircle); Assert.True(control.IsHandleCreated); Assert.Equal(expectedStyleChangedCallCount, invalidatedCallCount); Assert.Equal(expectedStyleChangedCallCount, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set different. control.ShowTodayCircle = !value; Assert.Equal(!value, control.ShowTodayCircle); Assert.True(control.IsHandleCreated); Assert.Equal(expectedStyleChangedCallCount + 1, invalidatedCallCount); Assert.Equal(expectedStyleChangedCallCount + 1, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))] public void MonthCalendar_ShowWeekNumbers_Set_GetReturnsExpected(bool value) { using var control = new SubMonthCalendar { ShowWeekNumbers = value }; Assert.Equal(value, control.ShowWeekNumbers); Assert.False(control.IsHandleCreated); // Set same. control.ShowWeekNumbers = value; Assert.Equal(value, control.ShowWeekNumbers); Assert.False(control.IsHandleCreated); // Set different. control.ShowWeekNumbers = !value; Assert.Equal(!value, control.ShowWeekNumbers); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(true, 1)] [InlineData(false, 0)] public void MonthCalendar_ShowWeekNumbers_SetWithHandle_GetReturnsExpected(bool value, int expectedStyleChangedCallCount) { using var control = new SubMonthCalendar(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.ShowWeekNumbers = value; Assert.Equal(value, control.ShowWeekNumbers); Assert.True(control.IsHandleCreated); Assert.Equal(expectedStyleChangedCallCount, invalidatedCallCount); Assert.Equal(expectedStyleChangedCallCount, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.ShowWeekNumbers = value; Assert.Equal(value, control.ShowWeekNumbers); Assert.True(control.IsHandleCreated); Assert.Equal(expectedStyleChangedCallCount, invalidatedCallCount); Assert.Equal(expectedStyleChangedCallCount, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set different. control.ShowWeekNumbers = !value; Assert.Equal(!value, control.ShowWeekNumbers); Assert.True(control.IsHandleCreated); Assert.Equal(expectedStyleChangedCallCount + 1, invalidatedCallCount); Assert.Equal(expectedStyleChangedCallCount + 1, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_SingleMonthSize_GetWithHandle_ReturnsExpected() { using var control = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; Size size = control.SingleMonthSize; Assert.True(size.Width >= 169); Assert.True(size.Height >= 153); Assert.Equal(size, control.SingleMonthSize); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } public static IEnumerable<object[]> SingleMonthSize_GetCustomGetMinReqRect_TestData() { yield return new object[] { new RECT(0, 0, 0, 0), Size.Empty }; yield return new object[] { new RECT(1, 2, 3, 4), new Size(3, 4) }; yield return new object[] { new RECT(1, 2, 1, 6), new Size(1, 6) }; yield return new object[] { new RECT(1, 2, 6, 1), new Size(6, 1) }; yield return new object[] { new RECT(1, 2, 6, 6), new Size(6, 6) }; yield return new object[] { new RECT(1, 2, 30, 40), new Size(30, 40) }; } [WinFormsTheory] [MemberData(nameof(SingleMonthSize_GetCustomGetMinReqRect_TestData))] public void MonthCalendar_SingleMonthSize_GetCustomGetMinReqRect_ReturnsExpected(object getMinReqRectResult, Size expected) { using var control = new CustomGetMinReqRectMonthCalendar { GetMinReqRectResult = (RECT)getMinReqRectResult }; Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Equal(expected, control.SingleMonthSize); } private class CustomGetMinReqRectMonthCalendar : MonthCalendar { public RECT GetMinReqRectResult { get; set; } protected unsafe override void WndProc(ref Message m) { if (m.Msg == (int)ComCtl32.MCM.GETMINREQRECT) { RECT* pRect = (RECT*)m.LParam; *pRect = GetMinReqRectResult; m.Result = (IntPtr)1; return; } base.WndProc(ref m); } } [WinFormsFact] public void MonthCalendar_SingleMonthSize_GetInvalidGetMinReqRect_ThrowsInvalidOperationException() { using var control = new InvalidGetMinReqRectMonthCalendar(); Assert.NotEqual(IntPtr.Zero, control.Handle); control.MakeInvalid = true; Assert.Throws<InvalidOperationException>(() => control.SingleMonthSize); } private class InvalidGetMinReqRectMonthCalendar : MonthCalendar { public bool MakeInvalid { get; set; } protected override void WndProc(ref Message m) { if (MakeInvalid && m.Msg == (int)ComCtl32.MCM.GETMINREQRECT) { m.Result = IntPtr.Zero; return; } base.WndProc(ref m); } } public static IEnumerable<object[]> Size_Set_TestData() { yield return new object[] { new Size(1, 2) }; yield return new object[] { new Size(0, 0) }; yield return new object[] { new Size(-1, -2) }; yield return new object[] { new Size(-1, 2) }; yield return new object[] { new Size(1, -2) }; } [WinFormsTheory] [MemberData(nameof(Size_Set_TestData))] public void MonthCalendar_Size_Set_GetReturnsExpected(Size value) { using var control = new MonthCalendar(); Size size = control.ClientSize; control.Size = value; Assert.Equal(size, control.ClientSize); Assert.Equal(new Rectangle(Point.Empty, size), control.ClientRectangle); Assert.Equal(new Rectangle(Point.Empty, size), control.DisplayRectangle); Assert.Equal(size, control.Size); Assert.Equal(new Rectangle(Point.Empty, size), control.Bounds); Assert.False(control.IsHandleCreated); // Set same. control.Size = value; Assert.Equal(size, control.ClientSize); Assert.Equal(new Rectangle(Point.Empty, size), control.ClientRectangle); Assert.Equal(new Rectangle(Point.Empty, size), control.DisplayRectangle); Assert.Equal(size, control.Size); Assert.Equal(new Rectangle(Point.Empty, size), control.Bounds); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(Size_Set_TestData))] public void MonthCalendar_Size_SetWithHandle_GetReturnsExpected(Size value) { using var control = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, control.Handle); Size size = control.Size; int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.Size = value; Assert.Equal(size, control.ClientSize); Assert.Equal(new Rectangle(Point.Empty, size), control.ClientRectangle); Assert.Equal(new Rectangle(Point.Empty, size), control.DisplayRectangle); Assert.Equal(size, control.Size); Assert.Equal(new Rectangle(Point.Empty, size), control.Bounds); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.Size = value; Assert.Equal(size, control.ClientSize); Assert.Equal(new Rectangle(Point.Empty, size), control.ClientRectangle); Assert.Equal(new Rectangle(Point.Empty, size), control.DisplayRectangle); Assert.Equal(size, control.Size); Assert.Equal(new Rectangle(Point.Empty, size), control.Bounds); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_Size_SetWithHandler_CallsSizeChanged() { using var control = new MonthCalendar(); Size size = control.Size; int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); callCount++; }; int clientSizeChangedCallCount = 0; EventHandler clientSizeChangedHandler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); clientSizeChangedCallCount++; }; control.SizeChanged += handler; control.ClientSizeChanged += clientSizeChangedHandler; control.Size = new Size(10, 10); Assert.Equal(size, control.Size); Assert.Equal(0, callCount); Assert.Equal(0, clientSizeChangedCallCount); // Set same. control.Size = new Size(10, 10); Assert.Equal(size, control.Size); Assert.Equal(0, callCount); Assert.Equal(0, clientSizeChangedCallCount); // Set different. control.Size = new Size(11, 11); Assert.Equal(size, control.Size); Assert.Equal(0, callCount); Assert.Equal(0, clientSizeChangedCallCount); // Remove handler. control.SizeChanged -= handler; control.ClientSizeChanged -= clientSizeChangedHandler; control.Size = new Size(10, 10); Assert.Equal(size, control.Size); Assert.Equal(0, callCount); Assert.Equal(0, clientSizeChangedCallCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))] public void MonthCalendar_Text_Set_GetReturnsExpected(string value, string expected) { using var control = new MonthCalendar { Text = value }; Assert.Equal(expected, control.Text); Assert.False(control.IsHandleCreated); // Set same. control.Text = value; Assert.Equal(expected, control.Text); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))] public void MonthCalendar_Text_SetWithHandle_GetReturnsExpected(string value, string expected) { using var control = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.Text = value; Assert.Equal(expected, control.Text); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.Text = value; Assert.Equal(expected, control.Text); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_Text_SetWithHandler_CallsTextChanged() { using var control = new MonthCalendar(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Equal(EventArgs.Empty, e); callCount++; }; control.TextChanged += handler; // Set different. control.Text = "text"; Assert.Equal("text", control.Text); Assert.Equal(1, callCount); // Set same. control.Text = "text"; Assert.Equal("text", control.Text); Assert.Equal(1, callCount); // Set different. control.Text = null; Assert.Empty(control.Text); Assert.Equal(2, callCount); // Remove handler. control.TextChanged -= handler; control.Text = "text"; Assert.Equal("text", control.Text); Assert.Equal(2, callCount); } public static IEnumerable<object[]> TitleBackColor_Set_TestData() { yield return new object[] { Color.Red }; yield return new object[] { Color.FromArgb(254, 1, 2, 3) }; } [WinFormsTheory] [MemberData(nameof(TitleBackColor_Set_TestData))] public void MonthCalendar_TitleBackColor_Set_GetReturnsExpected(Color value) { using var calendar = new MonthCalendar { TitleBackColor = value }; Assert.Equal(value, calendar.TitleBackColor); Assert.False(calendar.IsHandleCreated); // Call again. calendar.TitleBackColor = value; Assert.Equal(value, calendar.TitleBackColor); Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(TitleBackColor_Set_TestData))] public void MonthCalendar_TitleBackColor_SetWithHandle_GetReturnsExpected(Color value) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.TitleBackColor = value; Assert.Equal(value, calendar.TitleBackColor); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Call again. calendar.TitleBackColor = value; Assert.Equal(value, calendar.TitleBackColor); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_TitleBackColor_SetEmpty_ThrowsArgumentException() { using var calendar = new MonthCalendar(); Assert.Throws<ArgumentException>("value", () => calendar.TitleBackColor = Color.Empty); } public static IEnumerable<object[]> TitleForeColor_Set_TestData() { yield return new object[] { Color.Red }; yield return new object[] { Color.FromArgb(254, 1, 2, 3) }; } [WinFormsTheory] [MemberData(nameof(TitleForeColor_Set_TestData))] public void MonthCalendar_TitleForeColor_Set_GetReturnsExpected(Color value) { using var calendar = new MonthCalendar { TitleForeColor = value }; Assert.Equal(value, calendar.TitleForeColor); Assert.False(calendar.IsHandleCreated); // Call again. calendar.TitleForeColor = value; Assert.Equal(value, calendar.TitleForeColor); Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(TitleForeColor_Set_TestData))] public void MonthCalendar_TitleForeColor_SetWithHandle_GetReturnsExpected(Color value) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.TitleForeColor = value; Assert.Equal(value, calendar.TitleForeColor); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Call again. calendar.TitleForeColor = value; Assert.Equal(value, calendar.TitleForeColor); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_TitleForeColor_SetEmpty_ThrowsArgumentException() { using var calendar = new MonthCalendar(); Assert.Throws<ArgumentException>("value", () => calendar.TitleForeColor = Color.Empty); } [WinFormsFact] public void MonthCalendar_TodayDate_GetWithHandle_ReturnsExpected() { using var control = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Equal(DateTime.Now.Date, control.TodayDate); Assert.False(control.TodayDateSet); } public static IEnumerable<object[]> TodayDate_Set_TestData() { yield return new object[] { DateTime.MinValue }; yield return new object[] { new DateTime(1753, 1, 1).AddTicks(-1) }; yield return new object[] { new DateTime(1753, 1, 1) }; yield return new object[] { new DateTime(2019, 9, 1) }; yield return new object[] { new DateTime(2019, 9, 1).AddHours(1) }; yield return new object[] { DateTime.Now.Date }; yield return new object[] { DateTime.Now.Date.AddHours(1) }; yield return new object[] { new DateTime(9998, 12, 31) }; yield return new object[] { new DateTime(9998, 12, 31).AddTicks(1) }; yield return new object[] { DateTime.MaxValue }; } [WinFormsTheory] [MemberData(nameof(TodayDate_Set_TestData))] public void MonthCalendar_TodayDate_Set_GetReturnsExpected(DateTime value) { using var calendar = new MonthCalendar { TodayDate = value }; Assert.Equal(value.Date, calendar.TodayDate); Assert.True(calendar.TodayDateSet); Assert.False(calendar.IsHandleCreated); // Call again. calendar.TodayDate = value; Assert.Equal(value.Date, calendar.TodayDate); Assert.True(calendar.TodayDateSet); Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(TodayDate_Set_TestData))] public void MonthCalendar_TodayDate_SetWithHandle_GetReturnsExpected(DateTime value) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.TodayDate = value; Assert.Equal(value.Date, calendar.TodayDate); Assert.True(calendar.TodayDateSet); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Call again. calendar.TodayDate = value; Assert.Equal(value.Date, calendar.TodayDate); Assert.True(calendar.TodayDateSet); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_TodayDate_SetLessThanMinDate_ThrowsArgumentOutOfRangeException() { using var calendar = new MonthCalendar(); calendar.TodayDate = calendar.MinDate.AddTicks(-1); Assert.Equal(calendar.MinDate.AddTicks(-1).Date, calendar.TodayDate); calendar.MinDate = new DateTime(2019, 10, 3); Assert.Throws<ArgumentOutOfRangeException>("value", () => calendar.TodayDate = calendar.MinDate.AddTicks(-1)); } [WinFormsFact] public void MonthCalendar_TodayDate_SetGreaterThanMaxDate_ThrowsArgumentOutOfRangeException() { using var calendar = new MonthCalendar(); calendar.TodayDate = calendar.MaxDate.AddTicks(1); Assert.Equal(calendar.MaxDate.AddTicks(1).Date, calendar.TodayDate); calendar.MaxDate = new DateTime(2019, 9, 3); Assert.Throws<ArgumentOutOfRangeException>("value", () => calendar.TodayDate = calendar.MaxDate.AddDays(1)); } public static IEnumerable<object[]> TrailingForeColor_Set_TestData() { yield return new object[] { Color.Red }; yield return new object[] { Color.FromArgb(254, 1, 2, 3) }; } [WinFormsTheory] [MemberData(nameof(TrailingForeColor_Set_TestData))] public void MonthCalendar_TrailingForeColor_Set_GetReturnsExpected(Color value) { using var calendar = new MonthCalendar { TrailingForeColor = value }; Assert.Equal(value, calendar.TrailingForeColor); Assert.False(calendar.IsHandleCreated); // Call again. calendar.TrailingForeColor = value; Assert.Equal(value, calendar.TrailingForeColor); Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(TrailingForeColor_Set_TestData))] public void MonthCalendar_TrailingForeColor_SetWithHandle_GetReturnsExpected(Color value) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.TrailingForeColor = value; Assert.Equal(value, calendar.TrailingForeColor); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Call again. calendar.TrailingForeColor = value; Assert.Equal(value, calendar.TrailingForeColor); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_TrailingForeColor_SetEmpty_ThrowsArgumentException() { using var calendar = new MonthCalendar(); Assert.Throws<ArgumentException>("value", () => calendar.TrailingForeColor = Color.Empty); } [WinFormsFact] public void MonthCalendar_AddAnnuallyBoldedDate_Invoke_AddsToAnnuallyBoldedDates() { using var calendar = new MonthCalendar(); calendar.AddAnnuallyBoldedDate(new DateTime(2019, 10, 3)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3) }, calendar.AnnuallyBoldedDates); Assert.False(calendar.IsHandleCreated); // Different day. calendar.AddAnnuallyBoldedDate(new DateTime(2019, 10, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5) }, calendar.AnnuallyBoldedDates); Assert.False(calendar.IsHandleCreated); // Different month. calendar.AddAnnuallyBoldedDate(new DateTime(2019, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5) }, calendar.AnnuallyBoldedDates); Assert.False(calendar.IsHandleCreated); // Different year. calendar.AddAnnuallyBoldedDate(new DateTime(2018, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5) }, calendar.AnnuallyBoldedDates); Assert.False(calendar.IsHandleCreated); // Duplicate. calendar.AddAnnuallyBoldedDate(new DateTime(2018, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5), new DateTime(2018, 09, 5) }, calendar.AnnuallyBoldedDates); Assert.False(calendar.IsHandleCreated); // MinValue. calendar.AddAnnuallyBoldedDate(DateTime.MinValue); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5), new DateTime(2018, 09, 5), DateTime.MinValue }, calendar.AnnuallyBoldedDates); Assert.False(calendar.IsHandleCreated); // MaxValue. calendar.AddAnnuallyBoldedDate(DateTime.MaxValue); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5), new DateTime(2018, 09, 5), DateTime.MinValue, DateTime.MaxValue }, calendar.AnnuallyBoldedDates); Assert.False(calendar.IsHandleCreated); } [WinFormsFact] public void MonthCalendar_AddAnnuallyBoldedDate_InvokeWithHandle_AddsToAnnuallyBoldedDates() { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.AddAnnuallyBoldedDate(new DateTime(2019, 10, 3)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3) }, calendar.AnnuallyBoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Different day. calendar.AddAnnuallyBoldedDate(new DateTime(2019, 10, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5) }, calendar.AnnuallyBoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Different month. calendar.AddAnnuallyBoldedDate(new DateTime(2019, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5) }, calendar.AnnuallyBoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Different year. calendar.AddAnnuallyBoldedDate(new DateTime(2018, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5) }, calendar.AnnuallyBoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Duplicate. calendar.AddAnnuallyBoldedDate(new DateTime(2018, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5), new DateTime(2018, 09, 5) }, calendar.AnnuallyBoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // MinValue. calendar.AddAnnuallyBoldedDate(DateTime.MinValue); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5), new DateTime(2018, 09, 5), DateTime.MinValue }, calendar.AnnuallyBoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // MaxValue. calendar.AddAnnuallyBoldedDate(DateTime.MaxValue); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5), new DateTime(2018, 09, 5), DateTime.MinValue, DateTime.MaxValue }, calendar.AnnuallyBoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_AddBoldedDate_Invoke_AddsToBoldedDates() { using var calendar = new MonthCalendar(); calendar.AddBoldedDate(new DateTime(2019, 10, 3)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3) }, calendar.BoldedDates); Assert.False(calendar.IsHandleCreated); // Different day. calendar.AddBoldedDate(new DateTime(2019, 10, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5) }, calendar.BoldedDates); Assert.False(calendar.IsHandleCreated); // Different month. calendar.AddBoldedDate(new DateTime(2019, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5) }, calendar.BoldedDates); Assert.False(calendar.IsHandleCreated); // Different year. calendar.AddBoldedDate(new DateTime(2018, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5) }, calendar.BoldedDates); Assert.False(calendar.IsHandleCreated); // Duplicate. calendar.AddBoldedDate(new DateTime(2018, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5) }, calendar.BoldedDates); Assert.False(calendar.IsHandleCreated); // MinValue. calendar.AddBoldedDate(DateTime.MinValue); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5), DateTime.MinValue }, calendar.BoldedDates); Assert.False(calendar.IsHandleCreated); // MaxValue. calendar.AddBoldedDate(DateTime.MaxValue); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5), DateTime.MinValue, DateTime.MaxValue }, calendar.BoldedDates); Assert.False(calendar.IsHandleCreated); } [WinFormsFact] public void MonthCalendar_AddBoldedDate_InvokeWithHandle_AddsToBoldedDates() { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.AddBoldedDate(new DateTime(2019, 10, 3)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3) }, calendar.BoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Different day. calendar.AddBoldedDate(new DateTime(2019, 10, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5) }, calendar.BoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Different month. calendar.AddBoldedDate(new DateTime(2019, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5) }, calendar.BoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Different year. calendar.AddBoldedDate(new DateTime(2018, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5) }, calendar.BoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Duplicate. calendar.AddBoldedDate(new DateTime(2018, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5) }, calendar.BoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // MinValue. calendar.AddBoldedDate(DateTime.MinValue); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5), DateTime.MinValue }, calendar.BoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // MaxValue. calendar.AddBoldedDate(DateTime.MaxValue); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5), DateTime.MinValue, DateTime.MaxValue }, calendar.BoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_AddMonthlyBoldedDate_Invoke_AddsToMonthlyBoldedDates() { using var calendar = new MonthCalendar(); calendar.AddMonthlyBoldedDate(new DateTime(2019, 10, 3)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3) }, calendar.MonthlyBoldedDates); Assert.False(calendar.IsHandleCreated); // Different day. calendar.AddMonthlyBoldedDate(new DateTime(2019, 10, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5) }, calendar.MonthlyBoldedDates); Assert.False(calendar.IsHandleCreated); // Different month. calendar.AddMonthlyBoldedDate(new DateTime(2019, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5) }, calendar.MonthlyBoldedDates); Assert.False(calendar.IsHandleCreated); // Different year. calendar.AddMonthlyBoldedDate(new DateTime(2018, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5) }, calendar.MonthlyBoldedDates); Assert.False(calendar.IsHandleCreated); // Duplicate. calendar.AddMonthlyBoldedDate(new DateTime(2018, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5), new DateTime(2018, 09, 5) }, calendar.MonthlyBoldedDates); Assert.False(calendar.IsHandleCreated); // MinValue. calendar.AddMonthlyBoldedDate(DateTime.MinValue); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5), new DateTime(2018, 09, 5), DateTime.MinValue }, calendar.MonthlyBoldedDates); Assert.False(calendar.IsHandleCreated); // MaxValue. calendar.AddMonthlyBoldedDate(DateTime.MaxValue); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5), new DateTime(2018, 09, 5), DateTime.MinValue, DateTime.MaxValue }, calendar.MonthlyBoldedDates); Assert.False(calendar.IsHandleCreated); } [WinFormsFact] public void MonthCalendar_AddMonthlyBoldedDate_InvokeWithHandle_AddsToMonthlyBoldedDates() { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.AddMonthlyBoldedDate(new DateTime(2019, 10, 3)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3) }, calendar.MonthlyBoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Different day. calendar.AddMonthlyBoldedDate(new DateTime(2019, 10, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5) }, calendar.MonthlyBoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Different month. calendar.AddMonthlyBoldedDate(new DateTime(2019, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5) }, calendar.MonthlyBoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Different year. calendar.AddMonthlyBoldedDate(new DateTime(2018, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5) }, calendar.MonthlyBoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Duplicate. calendar.AddMonthlyBoldedDate(new DateTime(2018, 09, 5)); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5), new DateTime(2018, 09, 5) }, calendar.MonthlyBoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // MinValue. calendar.AddMonthlyBoldedDate(DateTime.MinValue); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5), new DateTime(2018, 09, 5), DateTime.MinValue }, calendar.MonthlyBoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // MaxValue. calendar.AddMonthlyBoldedDate(DateTime.MaxValue); Assert.Equal(new DateTime[] { new DateTime(2019, 10, 3), new DateTime(2019, 10, 5), new DateTime(2019, 09, 5), new DateTime(2018, 09, 5), new DateTime(2018, 09, 5), DateTime.MinValue, DateTime.MaxValue }, calendar.MonthlyBoldedDates); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_CreateHandle_Invoke_Success() { using var control = new SubMonthCalendar(); control.CreateHandle(); Assert.True(control.Created); Assert.True(control.IsHandleCreated); Assert.NotEqual(IntPtr.Zero, control.Handle); } [WinFormsFact] public void MonthCalendar_GetAutoSizeMode_Invoke_ReturnsExpected() { using var control = new SubMonthCalendar(); Assert.Equal(AutoSizeMode.GrowOnly, control.GetAutoSizeMode()); } [WinFormsTheory] [InlineData(ControlStyles.ContainerControl, false)] [InlineData(ControlStyles.UserPaint, false)] [InlineData(ControlStyles.Opaque, false)] [InlineData(ControlStyles.ResizeRedraw, false)] [InlineData(ControlStyles.FixedWidth, false)] [InlineData(ControlStyles.FixedHeight, false)] [InlineData(ControlStyles.StandardClick, false)] [InlineData(ControlStyles.Selectable, true)] [InlineData(ControlStyles.UserMouse, false)] [InlineData(ControlStyles.SupportsTransparentBackColor, false)] [InlineData(ControlStyles.StandardDoubleClick, true)] [InlineData(ControlStyles.AllPaintingInWmPaint, true)] [InlineData(ControlStyles.CacheText, false)] [InlineData(ControlStyles.EnableNotifyMessage, false)] [InlineData(ControlStyles.DoubleBuffer, false)] [InlineData(ControlStyles.OptimizedDoubleBuffer, false)] [InlineData(ControlStyles.UseTextForAccessibility, true)] [InlineData((ControlStyles)0, true)] [InlineData((ControlStyles)int.MaxValue, false)] [InlineData((ControlStyles)(-1), false)] public void MonthCalendar_GetStyle_Invoke_ReturnsExpected(ControlStyles flag, bool expected) { using var control = new SubMonthCalendar(); Assert.Equal(expected, control.GetStyle(flag)); // Call again to test caching. Assert.Equal(expected, control.GetStyle(flag)); } [WinFormsFact] public void MonthCalendar_GetTopLevel_Invoke_ReturnsExpected() { using var control = new SubMonthCalendar(); Assert.False(control.GetTopLevel()); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEventArgsTheoryData))] public void MonthCalendar_OnBackColorChanged_Invoke_CallsBackColorChanged(EventArgs eventArgs) { using var control = new SubMonthCalendar(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.BackColorChanged += handler; control.OnBackColorChanged(eventArgs); Assert.Equal(1, callCount); Assert.False(control.IsHandleCreated); // Remove handler. control.BackColorChanged -= handler; control.OnBackColorChanged(eventArgs); Assert.Equal(1, callCount); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEventArgsTheoryData))] public void MonthCalendar_OnBackColorChanged_InvokeWithHandle_CallsBackColorChanged(EventArgs eventArgs) { using var control = new SubMonthCalendar(); Assert.NotEqual(IntPtr.Zero, control.Handle); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; int invalidatedCallCount = 0; InvalidateEventHandler invalidatedHandler = (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; EventHandler styleChangedHandler = (sender, e) => styleChangedCallCount++; int createdCallCount = 0; EventHandler createdHandler = (sender, e) => createdCallCount++; // Call with handler. control.BackColorChanged += handler; control.Invalidated += invalidatedHandler; control.StyleChanged += styleChangedHandler; control.HandleCreated += createdHandler; control.OnBackColorChanged(eventArgs); Assert.Equal(1, callCount); Assert.Equal(1, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); Assert.True(control.IsHandleCreated); // Remove handler. control.BackColorChanged -= handler; control.Invalidated -= invalidatedHandler; control.StyleChanged -= styleChangedHandler; control.HandleCreated -= createdHandler; control.OnBackColorChanged(eventArgs); Assert.Equal(1, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); Assert.True(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEventArgsTheoryData))] public void MonthCalendar_OnClick_Invoke_CallsClick(EventArgs eventArgs) { using var control = new SubMonthCalendar(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.Click += handler; control.OnClick(eventArgs); Assert.Equal(1, callCount); // Remove handler. control.Click -= handler; control.OnClick(eventArgs); Assert.Equal(1, callCount); } public static IEnumerable<object[]> DateRangeEventArgs_TestData() { yield return new object[] { null }; yield return new object[] { new DateRangeEventArgs(DateTime.Now, DateTime.Now) }; } [WinFormsTheory] [MemberData(nameof(DateRangeEventArgs_TestData))] public void MonthCalendar_Calendar_OnDateChanged_Invoke_CallsDateChanged(DateRangeEventArgs eventArgs) { using var calendar = new SubMonthCalendar(); int callCount = 0; DateRangeEventHandler handler = (sender, e) => { Assert.Same(calendar, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. calendar.DateChanged += handler; calendar.OnDateChanged(eventArgs); Assert.Equal(1, callCount); // Remove handler. calendar.DateChanged -= handler; calendar.OnDateChanged(eventArgs); Assert.Equal(1, callCount); } [WinFormsTheory] [MemberData(nameof(DateRangeEventArgs_TestData))] public void MonthCalendar_Calendar_OnDateSelected_Invoke_CallsDateSelected(DateRangeEventArgs eventArgs) { using var calendar = new SubMonthCalendar(); int callCount = 0; DateRangeEventHandler handler = (sender, e) => { Assert.Same(calendar, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. calendar.DateSelected += handler; calendar.OnDateSelected(eventArgs); Assert.Equal(1, callCount); // Remove handler. calendar.DateSelected -= handler; calendar.OnDateSelected(eventArgs); Assert.Equal(1, callCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEventArgsTheoryData))] public void MonthControl_OnDoubleClick_Invoke_CallsDoubleClick(EventArgs eventArgs) { using var control = new SubMonthCalendar(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.DoubleClick += handler; control.OnDoubleClick(eventArgs); Assert.Equal(1, callCount); // Remove handler. control.DoubleClick -= handler; control.OnDoubleClick(eventArgs); Assert.Equal(1, callCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEventArgsTheoryData))] public void MonthCalendar_OnForeColorChanged_Invoke_CallsForeColorChanged(EventArgs eventArgs) { using var control = new SubMonthCalendar(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.ForeColorChanged += handler; control.OnForeColorChanged(eventArgs); Assert.Equal(1, callCount); Assert.False(control.IsHandleCreated); // Remove handler. control.ForeColorChanged -= handler; control.OnForeColorChanged(eventArgs); Assert.Equal(1, callCount); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEventArgsTheoryData))] public void MonthCalendar_OnForeColorChanged_InvokeWithHandle_CallsForeColorChanged(EventArgs eventArgs) { using var control = new SubMonthCalendar(); Assert.NotEqual(IntPtr.Zero, control.Handle); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; int invalidatedCallCount = 0; InvalidateEventHandler invalidatedHandler = (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; EventHandler styleChangedHandler = (sender, e) => styleChangedCallCount++; int createdCallCount = 0; EventHandler createdHandler = (sender, e) => createdCallCount++; // Call with handler. control.ForeColorChanged += handler; control.Invalidated += invalidatedHandler; control.StyleChanged += styleChangedHandler; control.HandleCreated += createdHandler; control.OnForeColorChanged(eventArgs); Assert.Equal(1, callCount); Assert.Equal(1, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); Assert.True(control.IsHandleCreated); // Remove handler. control.ForeColorChanged -= handler; control.Invalidated -= invalidatedHandler; control.StyleChanged -= styleChangedHandler; control.HandleCreated -= createdHandler; control.OnForeColorChanged(eventArgs); Assert.Equal(1, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); Assert.True(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEventArgsTheoryData))] public void MonthCalendar_OnHandleCreated_Invoke_CallsHandleCreated(EventArgs eventArgs) { using var control = new SubMonthCalendar(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.HandleCreated += handler; control.OnHandleCreated(eventArgs); Assert.Equal(1, callCount); Assert.False(control.IsHandleCreated); // Remove handler. control.HandleCreated -= handler; control.OnHandleCreated(eventArgs); Assert.Equal(1, callCount); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEventArgsTheoryData))] public void MonthCalendar_OnHandleCreated_InvokeWithHandle_CallsHandleCreated(EventArgs eventArgs) { using var control = new SubMonthCalendar(); Assert.NotEqual(IntPtr.Zero, control.Handle); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.HandleCreated += handler; control.OnHandleCreated(eventArgs); Assert.Equal(1, callCount); Assert.True(control.IsHandleCreated); // Remove handler. control.HandleCreated -= handler; control.OnHandleCreated(eventArgs); Assert.Equal(1, callCount); Assert.True(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEventArgsTheoryData))] public void MonthCalendar_OnHandleDestroyed_Invoke_CallsHandleDestroyed(EventArgs eventArgs) { using var control = new SubMonthCalendar(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.HandleDestroyed += handler; control.OnHandleDestroyed(eventArgs); Assert.Equal(1, callCount); Assert.False(control.IsHandleCreated); // Remove handler. control.HandleDestroyed -= handler; control.OnHandleDestroyed(eventArgs); Assert.Equal(1, callCount); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEventArgsTheoryData))] public void MonthCalendar_OnHandleDestroyed_InvokeWithHandle_CallsHandleDestroyed(EventArgs eventArgs) { using var control = new SubMonthCalendar(); Assert.NotEqual(IntPtr.Zero, control.Handle); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.HandleDestroyed += handler; control.OnHandleDestroyed(eventArgs); Assert.Equal(1, callCount); Assert.True(control.IsHandleCreated); // Remove handler. control.HandleDestroyed -= handler; control.OnHandleDestroyed(eventArgs); Assert.Equal(1, callCount); Assert.True(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelperEx), nameof(CommonTestHelperEx.GetMouseEventArgsTheoryData))] public void MonthCalendar_OnMouseClick_Invoke_CallsMouseClick(MouseEventArgs eventArgs) { using var control = new SubMonthCalendar(); int callCount = 0; MouseEventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.MouseClick += handler; control.OnMouseClick(eventArgs); Assert.Equal(1, callCount); // Remove handler. control.MouseClick -= handler; control.OnMouseClick(eventArgs); Assert.Equal(1, callCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelperEx), nameof(CommonTestHelperEx.GetMouseEventArgsTheoryData))] public void MonthCalendar_OnMouseDoubleClick_Invoke_CallsMouseDoubleClick(MouseEventArgs eventArgs) { using var control = new SubMonthCalendar(); int callCount = 0; MouseEventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.MouseDoubleClick += handler; control.OnMouseDoubleClick(eventArgs); Assert.Equal(1, callCount); // Remove handler. control.MouseDoubleClick -= handler; control.OnMouseDoubleClick(eventArgs); Assert.Equal(1, callCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelperEx), nameof(CommonTestHelperEx.GetPaintEventArgsTheoryData))] public void MonthCalendar_OnPaint_Invoke_CallsPaint(PaintEventArgs eventArgs) { using var control = new SubMonthCalendar(); int callCount = 0; PaintEventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.Paint += handler; control.OnPaint(eventArgs); Assert.Equal(1, callCount); // Remove handler. control.Paint -= handler; control.OnPaint(eventArgs); Assert.Equal(1, callCount); } public static IEnumerable<object[]> OnRightToLeftLayoutChanged_TestData() { yield return new object[] { RightToLeft.Yes, null }; yield return new object[] { RightToLeft.Yes, new EventArgs() }; yield return new object[] { RightToLeft.No, null }; yield return new object[] { RightToLeft.No, new EventArgs() }; yield return new object[] { RightToLeft.Inherit, null }; yield return new object[] { RightToLeft.Inherit, new EventArgs() }; } [WinFormsTheory] [MemberData(nameof(OnRightToLeftLayoutChanged_TestData))] public void MonthCalendar_OnRightToLeftLayoutChanged_Invoke_CallsRightToLeftLayoutChanged(RightToLeft rightToLeft, EventArgs eventArgs) { using var control = new SubMonthCalendar { RightToLeft = rightToLeft }; int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.RightToLeftLayoutChanged += handler; control.OnRightToLeftLayoutChanged(eventArgs); Assert.Equal(1, callCount); Assert.False(control.IsHandleCreated); // Remove handler. control.RightToLeftLayoutChanged -= handler; control.OnRightToLeftLayoutChanged(eventArgs); Assert.Equal(1, callCount); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> OnRightToLeftLayoutChanged_WithHandle_TestData() { yield return new object[] { RightToLeft.Yes, null, 1 }; yield return new object[] { RightToLeft.Yes, new EventArgs(), 1 }; yield return new object[] { RightToLeft.No, null, 0 }; yield return new object[] { RightToLeft.No, new EventArgs(), 0 }; yield return new object[] { RightToLeft.Inherit, null, 0 }; yield return new object[] { RightToLeft.Inherit, new EventArgs(), 0 }; } [WinFormsTheory] [MemberData(nameof(OnRightToLeftLayoutChanged_WithHandle_TestData))] public void MonthCalendar_OnRightToLeftLayoutChanged_InvokeWithHandle_CallsRightToLeftLayoutChanged(RightToLeft rightToLeft, EventArgs eventArgs, int expectedCreatedCallCount) { using var control = new SubMonthCalendar { RightToLeft = rightToLeft }; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.RightToLeftLayoutChanged += handler; control.OnRightToLeftLayoutChanged(eventArgs); Assert.Equal(1, callCount); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); // Remove handler. control.RightToLeftLayoutChanged -= handler; control.OnRightToLeftLayoutChanged(eventArgs); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount * 2, createdCallCount); } [WinFormsFact] public void MonthCalendar_OnRightToLeftLayoutChanged_InvokeInDisposing_DoesNotCallRightToLeftLayoutChanged() { using var control = new SubMonthCalendar { RightToLeft = RightToLeft.Yes }; Assert.NotEqual(IntPtr.Zero, control.Handle); int callCount = 0; control.RightToLeftLayoutChanged += (sender, e) => callCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; int disposedCallCount = 0; control.Disposed += (sender, e) => { control.OnRightToLeftLayoutChanged(EventArgs.Empty); Assert.Equal(0, callCount); Assert.Equal(0, createdCallCount); disposedCallCount++; }; control.Dispose(); Assert.Equal(1, disposedCallCount); } [WinFormsFact] public void MonthCalendar_RecreateHandle_InvokeWithHandle_Success() { using var control = new SubMonthCalendar(); IntPtr handle1 = control.Handle; Assert.NotEqual(IntPtr.Zero, handle1); Assert.True(control.IsHandleCreated); control.RecreateHandle(); IntPtr handle2 = control.Handle; Assert.NotEqual(IntPtr.Zero, handle2); Assert.NotEqual(handle1, handle2); Assert.True(control.IsHandleCreated); // Invoke again. control.RecreateHandle(); IntPtr handle3 = control.Handle; Assert.NotEqual(IntPtr.Zero, handle3); Assert.NotEqual(handle2, handle3); Assert.True(control.IsHandleCreated); } [WinFormsFact] public void MonthCalendar_RecreateHandle_InvokeWithoutHandle_Nop() { using var control = new SubMonthCalendar(); control.RecreateHandle(); Assert.False(control.IsHandleCreated); // Invoke again. control.RecreateHandle(); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(1, 2)] [InlineData(0, 0)] [InlineData(-1, -2)] public void MonthControl_RescaleConstantsForDpi_Invoke_Nop(int deviceDpiOld, int deviceDpiNew) { using var control = new SubMonthCalendar(); control.RescaleConstantsForDpi(deviceDpiOld, deviceDpiNew); Assert.False(control.IsHandleCreated); // Call again. control.RescaleConstantsForDpi(deviceDpiOld, deviceDpiNew); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> SetDate_TestData() { yield return new object[] { DateTime.MinValue }; yield return new object[] { new DateTime(1753, 1, 1).AddTicks(-1) }; yield return new object[] { new DateTime(1753, 1, 1) }; yield return new object[] { new DateTime(2019, 9, 1) }; yield return new object[] { new DateTime(2019, 9, 1).AddHours(1) }; yield return new object[] { DateTime.Now.Date }; yield return new object[] { DateTime.Now.Date.AddHours(1) }; yield return new object[] { new DateTime(9998, 12, 31) }; yield return new object[] { new DateTime(9998, 12, 31).AddTicks(1) }; yield return new object[] { DateTime.MaxValue }; } [WinFormsTheory] [MemberData(nameof(SetDate_TestData))] public void MonthCalendar_SetDate_Invoke_GetReturnsExpected(DateTime date) { using var calendar = new MonthCalendar(); calendar.SetDate(date); Assert.Equal(date.Date, calendar.SelectionRange.Start); Assert.Equal(date.Date, calendar.SelectionRange.End); Assert.Equal(date, calendar.SelectionStart); Assert.Equal(date, calendar.SelectionEnd); Assert.False(calendar.IsHandleCreated); // Call again. calendar.SetDate(date); Assert.Equal(date.Date, calendar.SelectionRange.Start); Assert.Equal(date.Date, calendar.SelectionRange.End); Assert.Equal(date, calendar.SelectionStart); Assert.Equal(date, calendar.SelectionEnd); Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(SetDate_TestData))] public void MonthCalendar_SetDate_InvokeWithHandle_GetReturnsExpected(DateTime date) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.SetDate(date); Assert.Equal(date.Date, calendar.SelectionRange.Start); Assert.Equal(date.Date, calendar.SelectionRange.End); Assert.Equal(date, calendar.SelectionStart); Assert.Equal(date, calendar.SelectionEnd); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Call again. calendar.SetDate(date); Assert.Equal(date.Date, calendar.SelectionRange.Start); Assert.Equal(date.Date, calendar.SelectionRange.End); Assert.Equal(date, calendar.SelectionStart); Assert.Equal(date, calendar.SelectionEnd); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_SetDate_DateLessThanMinDate_ThrowsArgumentOutOfRangeException() { using var calendar = new MonthCalendar(); calendar.SetDate(calendar.MinDate.AddTicks(-1)); Assert.Equal(calendar.MinDate.AddTicks(-1), calendar.SelectionStart); Assert.Equal(calendar.MinDate.AddTicks(-1), calendar.SelectionEnd); calendar.MinDate = new DateTime(2019, 10, 3); Assert.Throws<ArgumentOutOfRangeException>("date", () => calendar.SetDate(calendar.MinDate.AddTicks(-1))); } [WinFormsFact] public void MonthCalendar_SetDate_DateGreaterThanMaxDate_ThrowsArgumentOutOfRangeException() { using var calendar = new MonthCalendar(); calendar.SetDate(calendar.MaxDate.AddTicks(1)); Assert.Equal(calendar.MaxDate.AddTicks(1), calendar.SelectionStart); Assert.Equal(calendar.MaxDate.AddTicks(1), calendar.SelectionEnd); calendar.MaxDate = new DateTime(2019, 9, 3); Assert.Throws<ArgumentOutOfRangeException>("date", () => calendar.SetDate(calendar.MaxDate.AddDays(1))); } public static IEnumerable<object[]> SetSelectionRange_TestData() { yield return new object[] { DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue }; yield return new object[] { new DateTime(1753, 1, 1).AddTicks(-1), new DateTime(1753, 1, 1).AddTicks(-1), new DateTime(1753, 1, 1).AddTicks(-1), new DateTime(1753, 1, 1).AddTicks(-1) }; yield return new object[] { new DateTime(1753, 1, 1), new DateTime(1753, 1, 1), new DateTime(1753, 1, 1), new DateTime(1753, 1, 1) }; yield return new object[] { new DateTime(1753, 1, 1), new DateTime(1753, 1, 2), new DateTime(1753, 1, 1), new DateTime(1753, 1, 2) }; yield return new object[] { new DateTime(2019, 9, 1), new DateTime(2019, 9, 1), new DateTime(2019, 9, 1), new DateTime(2019, 9, 1) }; yield return new object[] { new DateTime(2019, 9, 1), new DateTime(2019, 9, 2), new DateTime(2019, 9, 1), new DateTime(2019, 9, 2) }; yield return new object[] { new DateTime(2019, 9, 1).AddHours(1), new DateTime(2019, 9, 2).AddHours(1), new DateTime(2019, 9, 1).AddHours(1), new DateTime(2019, 9, 2).AddHours(1) }; yield return new object[] { new DateTime(2019, 9, 2), new DateTime(2019, 9, 1), new DateTime(2019, 9, 2), new DateTime(2019, 9, 2) }; yield return new object[] { new DateTime(2019, 9, 1), new DateTime(2019, 9, 7), new DateTime(2019, 9, 1), new DateTime(2019, 9, 7) }; yield return new object[] { new DateTime(2019, 9, 1), new DateTime(2019, 9, 8), new DateTime(2019, 9, 1), new DateTime(2019, 9, 7) }; yield return new object[] { DateTime.Now.Date, DateTime.Now.Date, DateTime.Now.Date, DateTime.Now.Date }; yield return new object[] { DateTime.Now.Date, DateTime.Now.Date.AddDays(1), DateTime.Now.Date, DateTime.Now.Date.AddDays(1) }; yield return new object[] { DateTime.Now.Date.AddHours(1), DateTime.Now.Date.AddHours(1), DateTime.Now.Date.AddHours(1), DateTime.Now.Date.AddHours(1) }; yield return new object[] { DateTime.Now.Date.AddDays(1), DateTime.Now.Date, DateTime.Now.Date.AddDays(1), DateTime.Now.Date.AddDays(1) }; yield return new object[] { DateTime.Now.Date, DateTime.Now.Date.AddDays(6), DateTime.Now.Date, DateTime.Now.Date.AddDays(6) }; yield return new object[] { DateTime.Now.Date, DateTime.Now.Date.AddDays(7), DateTime.Now.Date.AddDays(1), DateTime.Now.Date.AddDays(7) }; yield return new object[] { new DateTime(9998, 12, 30), new DateTime(9998, 12, 31), new DateTime(9998, 12, 30), new DateTime(9998, 12, 31) }; yield return new object[] { new DateTime(9998, 12, 31), new DateTime(9998, 12, 31), new DateTime(9998, 12, 31), new DateTime(9998, 12, 31) }; yield return new object[] { new DateTime(9998, 12, 31).AddTicks(1), new DateTime(9998, 12, 31).AddTicks(1), new DateTime(9998, 12, 31).AddTicks(1), new DateTime(9998, 12, 31).AddTicks(1) }; yield return new object[] { DateTime.MaxValue, DateTime.MaxValue, DateTime.MaxValue, DateTime.MaxValue }; } [WinFormsTheory] [MemberData(nameof(SetSelectionRange_TestData))] public void MonthCalendar_SetSelectionRange_Invoke_GetReturnsExpected(DateTime date1, DateTime date2, DateTime expectedSelectionStart, DateTime expectedSelectionEnd) { using var calendar = new MonthCalendar(); calendar.SetSelectionRange(date1, date2); Assert.Equal(expectedSelectionStart.Date, calendar.SelectionRange.Start); Assert.Equal(expectedSelectionEnd.Date, calendar.SelectionRange.End); Assert.Equal(expectedSelectionStart, calendar.SelectionStart); Assert.Equal(expectedSelectionEnd, calendar.SelectionEnd); Assert.False(calendar.IsHandleCreated); // Call again. calendar.SetSelectionRange(expectedSelectionStart, expectedSelectionEnd); Assert.Equal(expectedSelectionStart.Date, calendar.SelectionRange.Start); Assert.Equal(expectedSelectionEnd.Date, calendar.SelectionRange.End); Assert.Equal(expectedSelectionStart, calendar.SelectionStart); Assert.Equal(expectedSelectionEnd, calendar.SelectionEnd); Assert.False(calendar.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(SetSelectionRange_TestData))] public void MonthCalendar_SetSelectionRange_InvokeWithHandle_GetReturnsExpected(DateTime date1, DateTime date2, DateTime expectedSelectionStart, DateTime expectedSelectionEnd) { using var calendar = new MonthCalendar(); Assert.NotEqual(IntPtr.Zero, calendar.Handle); int invalidatedCallCount = 0; calendar.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; calendar.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; calendar.HandleCreated += (sender, e) => createdCallCount++; calendar.SetSelectionRange(date1, date2); Assert.Equal(expectedSelectionStart.Date, calendar.SelectionRange.Start); Assert.Equal(expectedSelectionEnd.Date, calendar.SelectionRange.End); Assert.Equal(expectedSelectionStart, calendar.SelectionStart); Assert.Equal(expectedSelectionEnd, calendar.SelectionEnd); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Call again. calendar.SetSelectionRange(expectedSelectionStart, expectedSelectionEnd); Assert.Equal(expectedSelectionStart.Date, calendar.SelectionRange.Start); Assert.Equal(expectedSelectionEnd.Date, calendar.SelectionRange.End); Assert.Equal(expectedSelectionStart, calendar.SelectionStart); Assert.Equal(expectedSelectionEnd, calendar.SelectionEnd); Assert.True(calendar.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void MonthCalendar_SetSelectionRange_DateLessThanMinDate_ThrowsArgumentOutOfRangeException() { using var calendar = new MonthCalendar(); calendar.SetSelectionRange(calendar.MinDate.AddTicks(-1), calendar.MinDate); Assert.Equal(calendar.MinDate.AddTicks(-1), calendar.SelectionStart); Assert.Equal(calendar.MinDate, calendar.SelectionEnd); calendar.SetSelectionRange(calendar.MinDate, calendar.MinDate.AddTicks(-1)); Assert.Equal(calendar.MinDate, calendar.SelectionStart); Assert.Equal(calendar.MinDate, calendar.SelectionEnd); calendar.MinDate = new DateTime(2019, 10, 3); Assert.Throws<ArgumentOutOfRangeException>("date1", () => calendar.SetSelectionRange(calendar.MinDate.AddTicks(-1), calendar.MinDate)); Assert.Throws<ArgumentOutOfRangeException>("date2", () => calendar.SetSelectionRange(calendar.MinDate, calendar.MinDate.AddTicks(-1))); } [WinFormsFact] public void MonthCalendar_SetSelectionRange_DateGreaterThanMaxDate_ThrowsArgumentOutOfRangeException() { using var calendar = new MonthCalendar(); calendar.SetSelectionRange(calendar.MaxDate.AddTicks(1), calendar.MaxDate); Assert.Equal(calendar.MaxDate.AddTicks(1), calendar.SelectionStart); Assert.Equal(calendar.MaxDate.AddTicks(1), calendar.SelectionEnd); calendar.SetSelectionRange(calendar.MaxDate, calendar.MaxDate.AddTicks(1)); Assert.Equal(calendar.MaxDate, calendar.SelectionStart); Assert.Equal(calendar.MaxDate.AddTicks(1), calendar.SelectionEnd); calendar.MaxDate = new DateTime(2019, 9, 3); Assert.Throws<ArgumentOutOfRangeException>("date1", () => calendar.SetSelectionRange(calendar.MaxDate.AddDays(1), calendar.MaxDate)); Assert.Throws<ArgumentOutOfRangeException>("date2", () => calendar.SetSelectionRange(calendar.MaxDate, calendar.MaxDate.AddDays(1))); } private class SubMonthCalendar : MonthCalendar { public new bool CanEnableIme => base.CanEnableIme; public new bool CanRaiseEvents => base.CanRaiseEvents; public new CreateParams CreateParams => base.CreateParams; public new Cursor DefaultCursor => base.DefaultCursor; public new ImeMode DefaultImeMode => base.DefaultImeMode; public new Padding DefaultMargin => base.DefaultMargin; public new Size DefaultMaximumSize => base.DefaultMaximumSize; public new Size DefaultMinimumSize => base.DefaultMinimumSize; public new Padding DefaultPadding => base.DefaultPadding; public new Size DefaultSize => base.DefaultSize; public new bool DesignMode => base.DesignMode; public new bool DoubleBuffered { get => base.DoubleBuffered; set => base.DoubleBuffered = value; } public new EventHandlerList Events => base.Events; public new int FontHeight { get => base.FontHeight; set => base.FontHeight = value; } public new ImeMode ImeModeBase { get => base.ImeModeBase; set => base.ImeModeBase = value; } public new bool ResizeRedraw { get => base.ResizeRedraw; set => base.ResizeRedraw = value; } public new bool ShowFocusCues => base.ShowFocusCues; public new bool ShowKeyboardCues => base.ShowKeyboardCues; public new AccessibleObject CreateAccessibilityInstance() => base.CreateAccessibilityInstance(); public new void CreateHandle() => base.CreateHandle(); public new AutoSizeMode GetAutoSizeMode() => base.GetAutoSizeMode(); public new bool GetStyle(ControlStyles flag) => base.GetStyle(flag); public new bool GetTopLevel() => base.GetTopLevel(); public new void OnBackColorChanged(EventArgs e) => base.OnBackColorChanged(e); public new void OnClick(EventArgs e) => base.OnClick(e); public new void OnDateChanged(DateRangeEventArgs e) => base.OnDateChanged(e); public new void OnDateSelected(DateRangeEventArgs e) => base.OnDateSelected(e); public new void OnDoubleClick(EventArgs e) => base.OnDoubleClick(e); public new void OnFontChanged(EventArgs e) => base.OnFontChanged(e); public new void OnForeColorChanged(EventArgs e) => base.OnForeColorChanged(e); public new void OnHandleCreated(EventArgs e) => base.OnHandleCreated(e); public new void OnHandleDestroyed(EventArgs e) => base.OnHandleDestroyed(e); public new void OnMouseClick(MouseEventArgs e) => base.OnMouseClick(e); public new void OnMouseDoubleClick(MouseEventArgs e) => base.OnMouseDoubleClick(e); public new void OnPaint(PaintEventArgs e) => base.OnPaint(e); public new void OnRightToLeftLayoutChanged(EventArgs e) => base.OnRightToLeftLayoutChanged(e); public new void RecreateHandle() => base.RecreateHandle(); public new void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) => base.RescaleConstantsForDpi(deviceDpiOld, deviceDpiNew); public new void SetStyle(ControlStyles flag, bool value) => base.SetStyle(flag, value); } } }
45.69554
247
0.614842
[ "MIT" ]
abdullah1133/winforms
src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/MonthCalendarTests.cs
194,665
C#
using Orchard.Environment.Extensions; using Orchard.Layouts.Framework.Display; using Orchard.Layouts.Framework.Drivers; using Orchard.Layouts.ViewModels; using MarkdownElement = Orchard.Layouts.Elements.Markdown; namespace Orchard.Layouts.Drivers { [OrchardFeature("Orchard.Layouts.Markdown")] public class MarkdownElementDriver : ElementDriver<MarkdownElement> { protected override EditorResult OnBuildEditor(MarkdownElement element, ElementEditorContext context) { var viewModel = new MarkdownEditorViewModel { Text = element.Content }; var editor = context.ShapeFactory.EditorTemplate(TemplateName: "Elements.Markdown", Model: viewModel); if (context.Updater != null) { context.Updater.TryUpdateModel(viewModel, context.Prefix, null, null); element.Content = viewModel.Text; } return Editor(context, editor); } protected override void OnDisplaying(MarkdownElement element, ElementDisplayingContext context) { context.ElementShape.ProcessedContent = ToHtml(element.Content); } private string ToHtml(string markdown) { return new MarkdownSharp.Markdown().Transform(markdown); } } }
39.545455
114
0.681992
[ "BSD-3-Clause" ]
BilalHasanKhan/Orchard
src/Orchard.Web/Modules/Orchard.Layouts/Drivers/MarkdownElementDriver.cs
1,307
C#
namespace ThirdPartyLibraries.Repository.Template { public sealed class LibraryReadMeDependencyContext { public string Name { get; set; } public string Version { get; set; } public string LocalHRef { get; set; } } }
23.090909
54
0.65748
[ "MIT" ]
max-ieremenko/ThirdPartyLibraries
Sources/ThirdPartyLibraries.Repository/Template/LibraryReadMeDependencyContext.cs
256
C#
using System; using System.Collections.Generic; using System.Text; namespace Google.Maps { internal static class Constants { public const int SIZE_WIDTH_MIN = 1; public const int SIZE_HEIGHT_MIN = 1; public const int SIZE_WIDTH_MAX = 4096; public const int SIZE_HEIGHT_MAX = 4096; public const int ZOOM_LEVEL_MIN = 0; public const string PATH_ENCODED_PREFIX = "enc:"; public const string PIPE_URL_ENCODED = "%7C"; public const string expectedColors = "black, brown, green, purple, yellow, blue, gray, orange, red, white"; //pasted straight from the website. private static string[] S_ExpectedNamedColors; public static bool IsExpectedNamedColor(string value) { if(value == null) return false; return (Contains(S_ExpectedNamedColors, value, true)); } private static int[] S_ExpectedScaleValues; public static bool IsExpectedScaleValue(int value, bool throwIfOutOfRange) { if(Contains(S_ExpectedScaleValues, value) == true) return true; if(throwIfOutOfRange) throw new ArgumentOutOfRangeException("Scale value can only be " + ListValues(S_ExpectedScaleValues)); else return false; } static Constants() { S_ExpectedNamedColors = expectedColors.Replace(", ", ",").Split(','); //since we paste straight from the website, we remove spaces, and convert to an array. S_ExpectedScaleValues = new int[] { 1, 2, 4 }; } #region Pre-Framework v3.0 support private static bool Contains(string[] array, string value, bool ignoreCase) { //TODO: rewrite for speed somehow for(int i = 0; i < array.Length; i++) { if(string.Compare(array[i], value, ignoreCase) == 0) return true; } return false; } private static bool Contains(int[] array, int value) { //TODO: rewrite for speed somehow for(int i = 0; i < array.Length; i++) { if(array[i] == value) return true; } return false; } private static string ListValues(int[] array) { //TODO: rewrite for speed somehow System.Text.StringBuilder sb = new StringBuilder(); for(int i = 0; i < array.Length; i++) { if(sb.Length > 0) sb.Append(","); sb.Append(array[i]); } return sb.ToString(); } internal static void CheckHeadingRange(short value, string parameterName) { const string HEADING_PARAMETER_RANGE = "Heading value must be greater or equal to 0 and less than or equal to 360"; if(value < 0) throw new ArgumentOutOfRangeException(parameterName, HEADING_PARAMETER_RANGE); if(value > 360) throw new ArgumentOutOfRangeException(parameterName, HEADING_PARAMETER_RANGE); } internal static void CheckPitchRange(short value, string parameterName) { const string PITCH_PARAMETER_RANGE = "Pitch value must be greater or equal to -90 and less than or equal to 90."; if(value < -90 || value > 90) throw new ArgumentOutOfRangeException(PITCH_PARAMETER_RANGE, parameterName); } internal static void CheckFieldOfViewRange(short value, string parameterName) { const string FIELD_OF_VIEW_PARAMETER_RANGE = "Field of view value must be greater or equal to 1 and less than or equal to 120."; if (value < 1 || value > 120) throw new ArgumentOutOfRangeException(FIELD_OF_VIEW_PARAMETER_RANGE, parameterName); } #endregion } }
33.158416
161
0.696626
[ "Apache-2.0" ]
AlexSkarbo/gmaps-api-net
src/Google.Maps/Constants.cs
3,351
C#
using J2N.Collections.Generic.Extensions; using System.Collections.Generic; namespace Lucene.Net.Codecs.Lucene46 { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using ChecksumIndexInput = Lucene.Net.Store.ChecksumIndexInput; using CorruptIndexException = Lucene.Net.Index.CorruptIndexException; using DocValuesType = Lucene.Net.Index.DocValuesType; using Directory = Lucene.Net.Store.Directory; using FieldInfo = Lucene.Net.Index.FieldInfo; using FieldInfos = Lucene.Net.Index.FieldInfos; using IndexFileNames = Lucene.Net.Index.IndexFileNames; using IndexInput = Lucene.Net.Store.IndexInput; using IndexOptions = Lucene.Net.Index.IndexOptions; using IOContext = Lucene.Net.Store.IOContext; using IOUtils = Lucene.Net.Util.IOUtils; /// <summary> /// Lucene 4.6 FieldInfos reader. /// <para/> /// @lucene.experimental /// </summary> /// <seealso cref="Lucene46FieldInfosFormat"/> internal sealed class Lucene46FieldInfosReader : FieldInfosReader { /// <summary> /// Sole constructor. </summary> public Lucene46FieldInfosReader() { } public override FieldInfos Read(Directory directory, string segmentName, string segmentSuffix, IOContext context) { string fileName = IndexFileNames.SegmentFileName(segmentName, segmentSuffix, Lucene46FieldInfosFormat.EXTENSION); ChecksumIndexInput input = directory.OpenChecksumInput(fileName, context); bool success = false; try { int codecVersion = CodecUtil.CheckHeader(input, Lucene46FieldInfosFormat.CODEC_NAME, Lucene46FieldInfosFormat.FORMAT_START, Lucene46FieldInfosFormat.FORMAT_CURRENT); int size = input.ReadVInt32(); //read in the size FieldInfo[] infos = new FieldInfo[size]; for (int i = 0; i < size; i++) { string name = input.ReadString(); int fieldNumber = input.ReadVInt32(); byte bits = input.ReadByte(); bool isIndexed = (bits & Lucene46FieldInfosFormat.IS_INDEXED) != 0; bool storeTermVector = (bits & Lucene46FieldInfosFormat.STORE_TERMVECTOR) != 0; bool omitNorms = (bits & Lucene46FieldInfosFormat.OMIT_NORMS) != 0; bool storePayloads = (bits & Lucene46FieldInfosFormat.STORE_PAYLOADS) != 0; IndexOptions indexOptions; if (!isIndexed) { indexOptions = IndexOptions.NONE; } else if ((bits & Lucene46FieldInfosFormat.OMIT_TERM_FREQ_AND_POSITIONS) != 0) { indexOptions = IndexOptions.DOCS_ONLY; } else if ((bits & Lucene46FieldInfosFormat.OMIT_POSITIONS) != 0) { indexOptions = IndexOptions.DOCS_AND_FREQS; } else if ((bits & Lucene46FieldInfosFormat.STORE_OFFSETS_IN_POSTINGS) != 0) { indexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS; } else { indexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS; } // DV Types are packed in one byte byte val = input.ReadByte(); DocValuesType docValuesType = GetDocValuesType(input, (sbyte)(val & 0x0F)); DocValuesType normsType = GetDocValuesType(input, (sbyte)(((int)((uint)val >> 4)) & 0x0F)); long dvGen = input.ReadInt64(); IDictionary<string, string> attributes = input.ReadStringStringMap(); infos[i] = new FieldInfo(name, isIndexed, fieldNumber, storeTermVector, omitNorms, storePayloads, indexOptions, docValuesType, normsType, attributes.AsReadOnly()); infos[i].DocValuesGen = dvGen; } if (codecVersion >= Lucene46FieldInfosFormat.FORMAT_CHECKSUM) { CodecUtil.CheckFooter(input); } else { #pragma warning disable 612, 618 CodecUtil.CheckEOF(input); #pragma warning restore 612, 618 } FieldInfos fieldInfos = new FieldInfos(infos); success = true; return fieldInfos; } finally { if (success) { input.Dispose(); } else { IOUtils.DisposeWhileHandlingException(input); } } } private static DocValuesType GetDocValuesType(IndexInput input, sbyte b) { if (b == 0) { return DocValuesType.NONE; } else if (b == 1) { return DocValuesType.NUMERIC; } else if (b == 2) { return DocValuesType.BINARY; } else if (b == 3) { return DocValuesType.SORTED; } else if (b == 4) { return DocValuesType.SORTED_SET; } else { throw new CorruptIndexException("invalid docvalues byte: " + b + " (resource=" + input + ")"); } } } }
41.151899
183
0.55629
[ "Apache-2.0" ]
Ref12/lucenenet
src/Lucene.Net/Codecs/Lucene46/Lucene46FieldInfosReader.cs
6,502
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.UI.Xaml.Media.Animation { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] #endif public partial class DiscretePointKeyFrame : global::Windows.UI.Xaml.Media.Animation.PointKeyFrame { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public DiscretePointKeyFrame() : base() { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Media.Animation.DiscretePointKeyFrame", "DiscretePointKeyFrame.DiscretePointKeyFrame()"); } #endif // Forced skipping of method Windows.UI.Xaml.Media.Animation.DiscretePointKeyFrame.DiscretePointKeyFrame() } }
39.95
183
0.773467
[ "Apache-2.0" ]
AlexTrepanier/Uno
src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Media.Animation/DiscretePointKeyFrame.cs
799
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Microsoft.CognitiveServices.ContentModerator { public class ModeratorHelper { public enum ImageFormat { bmp, jpeg, gif, tiff, png, unknown } public static ImageFormat GetImageFormat(Stream stream) { // see http://www.mikekunz.com/image_file_header.html var bmp = Encoding.ASCII.GetBytes("BM"); // BMP var gif = Encoding.ASCII.GetBytes("GIF"); // GIF var png = new byte[] { 137, 80, 78, 71 }; // PNG var tiff = new byte[] { 73, 73, 42 }; // TIFF var tiff2 = new byte[] { 77, 77, 42 }; // TIFF var jpeg = new byte[] { 255, 216, 255, 224 }; // jpeg var jpeg2 = new byte[] { 255, 216, 255, 225 }; // jpeg canon var buffer = new byte[4]; stream.Read(buffer, 0, buffer.Length); if (bmp.SequenceEqual(buffer.Take(bmp.Length))) return ImageFormat.bmp; if (gif.SequenceEqual(buffer.Take(gif.Length))) return ImageFormat.gif; if (png.SequenceEqual(buffer.Take(png.Length))) return ImageFormat.png; if (tiff.SequenceEqual(buffer.Take(tiff.Length))) return ImageFormat.tiff; if (tiff2.SequenceEqual(buffer.Take(tiff2.Length))) return ImageFormat.tiff; if (jpeg.SequenceEqual(buffer.Take(jpeg.Length))) return ImageFormat.jpeg; if (jpeg2.SequenceEqual(buffer.Take(jpeg2.Length))) return ImageFormat.jpeg; return ImageFormat.unknown; } public static string GetEnumDescription(Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes != null && attributes.Length > 0) return attributes[0].Description; else return value.ToString(); } } }
31.486842
100
0.556623
[ "MIT" ]
AdonisJ99/Microsoft.CognitiveServices.ContentModerator-Windows
ContentModeratorSDK/ModeratorHelper.cs
2,395
C#