content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
//------------------------------------------------------------------------------ // <copyright file="XmlSchemaAttribute.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">Microsoft</owner> //------------------------------------------------------------------------------ using System.Collections; using System.ComponentModel; using System.Xml.Serialization; namespace System.Xml.Schema { /// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlSchemaAttribute : XmlSchemaAnnotated { string defaultValue; string fixedValue; string name; XmlSchemaForm form = XmlSchemaForm.None; XmlSchemaUse use = XmlSchemaUse.None; XmlQualifiedName refName = XmlQualifiedName.Empty; XmlQualifiedName typeName = XmlQualifiedName.Empty; XmlQualifiedName qualifiedName = XmlQualifiedName.Empty; XmlSchemaSimpleType type; XmlSchemaSimpleType attributeType; SchemaAttDef attDef; /// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.DefaultValue"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("default")] [DefaultValue(null)] public string DefaultValue { get { return defaultValue; } set { defaultValue = value; } } /// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.FixedValue"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("fixed")] [DefaultValue(null)] public string FixedValue { get { return fixedValue; } set { fixedValue = value; } } /// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.Form"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("form"), DefaultValue(XmlSchemaForm.None)] public XmlSchemaForm Form { get { return form; } set { form = value; } } /// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.Name"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("name")] public string Name { get { return name; } set { name = value; } } /// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.RefName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("ref")] public XmlQualifiedName RefName { get { return refName; } set { refName = (value == null ? XmlQualifiedName.Empty : value); } } /// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.SchemaTypeName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("type")] public XmlQualifiedName SchemaTypeName { get { return typeName; } set { typeName = (value == null ? XmlQualifiedName.Empty : value); } } /// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.SchemaType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlElement("simpleType")] public XmlSchemaSimpleType SchemaType { get { return type; } set { type = value; } } /// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.Use"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("use"), DefaultValue(XmlSchemaUse.None)] public XmlSchemaUse Use { get { return use; } set { use = value; } } /// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.QualifiedName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlQualifiedName QualifiedName { get { return qualifiedName; } } /// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.AttributeType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] [Obsolete("This property has been deprecated. Please use AttributeSchemaType property that returns a strongly typed attribute type. http://go.microsoft.com/fwlink/?linkid=14202")] public object AttributeType { get { if (attributeType == null) return null; if (attributeType.QualifiedName.Namespace == XmlReservedNs.NsXs) { return attributeType.Datatype; } return attributeType; } } /// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.AttributeSchemaType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaSimpleType AttributeSchemaType { get { return attributeType; } } internal XmlReader Validate(XmlReader reader, XmlResolver resolver, XmlSchemaSet schemaSet, ValidationEventHandler valEventHandler) { if (schemaSet != null) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ValidationType = ValidationType.Schema; readerSettings.Schemas = schemaSet; readerSettings.ValidationEventHandler += valEventHandler; return new XsdValidatingReader(reader, resolver, readerSettings, this); } return null; } [XmlIgnore] internal XmlSchemaDatatype Datatype { get { if (attributeType != null) { return attributeType.Datatype; } return null; } } internal void SetQualifiedName(XmlQualifiedName value) { qualifiedName = value; } internal void SetAttributeType(XmlSchemaSimpleType value) { attributeType = value; } internal SchemaAttDef AttDef { get { return attDef; } set { attDef = value; } } internal bool HasDefault { get { return defaultValue != null; } } [XmlIgnore] internal override string NameAttribute { get { return Name; } set { Name = value; } } internal override XmlSchemaObject Clone() { XmlSchemaAttribute newAtt = (XmlSchemaAttribute)MemberwiseClone(); //Deep clone the QNames as these will be updated on chameleon includes newAtt.refName = this.refName.Clone(); newAtt.typeName = this.typeName.Clone(); newAtt.qualifiedName = this.qualifiedName.Clone(); return newAtt; } } }
36.817308
187
0.541264
[ "MIT" ]
Abdalla-rabie/referencesource
System.Xml/System/Xml/Schema/XmlSchemaAttribute.cs
7,658
C#
/* // <copyright> // dotNetRDF is free and open source software licensed under the MIT License // ------------------------------------------------------------------------- // // Copyright (c) 2009-2021 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; using System.Collections.Generic; using System.Linq; using System.Text; using VDS.RDF.Nodes; using VDS.RDF.Parsing; using VDS.RDF.Query.Expressions; using VDS.RDF.Query.Expressions.Primary; namespace VDS.RDF.Query.Aggregates.XPath { /// <summary> /// Represents the XPath fn:string-join() aggregate. /// </summary> public class StringJoinAggregate : BaseAggregate { /// <summary> /// Separator Expression. /// </summary> protected ISparqlExpression _sep; private bool _customSep = true; /// <summary> /// Creates a new XPath String Join aggregate which uses no separator. /// </summary> /// <param name="expr">Expression.</param> public StringJoinAggregate(ISparqlExpression expr) : this(expr, new ConstantTerm(new LiteralNode(null, String.Empty))) { _customSep = false; } /// <summary> /// Creates a new XPath String Join aggregate. /// </summary> /// <param name="expr">Expression.</param> /// <param name="sep">Separator Expression.</param> public StringJoinAggregate(ISparqlExpression expr, ISparqlExpression sep) : base(expr) { _sep = sep; } /// <summary> /// Applies the Aggregate in the given Context over the given Binding IDs. /// </summary> /// <param name="context">Evaluation Context.</param> /// <param name="bindingIDs">Binding IDs.</param> /// <returns></returns> public override IValuedNode Apply(SparqlEvaluationContext context, IEnumerable<int> bindingIDs) { List<int> ids = bindingIDs.ToList(); StringBuilder output = new StringBuilder(); HashSet<String> values = new HashSet<string>(); for (int i = 0; i < ids.Count; i++) { try { String temp = ValueInternal(context, ids[i]); // Apply DISTINCT modifer if required if (_distinct) { if (values.Contains(temp)) { continue; } else { values.Add(temp); } } output.Append(temp); } catch (RdfQueryException) { output.Append(String.Empty); } // Append Separator if required if (i < ids.Count - 1) { String sep = GetSeparator(context, ids[i]); output.Append(sep); } } return new StringNode(null, output.ToString(), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString)); } /// <summary> /// Gets the value of a member of the Group for concatenating as part of the result for the Group. /// </summary> /// <param name="context">Evaluation Context.</param> /// <param name="bindingID">Binding ID.</param> /// <returns></returns> protected virtual String ValueInternal(SparqlEvaluationContext context, int bindingID) { IValuedNode temp = _expr.Evaluate(context, bindingID); if (temp == null) throw new RdfQueryException("Cannot do an XPath string-join on a null"); if (temp.NodeType == NodeType.Literal) { ILiteralNode l = (ILiteralNode)temp; if (l.DataType != null) { if (l.DataType.AbsoluteUri.Equals(XmlSpecsHelper.XmlSchemaDataTypeString)) { return temp.AsString(); } else { throw new RdfQueryException("Cannot do an XPath string-join on a Literal which is not typed as a String"); } } else { return temp.AsString(); } } else { throw new RdfQueryException("Cannot do an XPath string-join on a non-Literal Node"); } } /// <summary> /// Gets the separator to use in the concatenation. /// </summary> /// <param name="context">Evaluation Context.</param> /// <param name="bindingID">Binding ID.</param> /// <returns></returns> private String GetSeparator(SparqlEvaluationContext context, int bindingID) { INode temp = _sep.Evaluate(context, bindingID); if (temp == null) { return String.Empty; } else if (temp.NodeType == NodeType.Literal) { ILiteralNode l = (ILiteralNode)temp; if (l.DataType != null) { if (l.DataType.AbsoluteUri.Equals(XmlSpecsHelper.XmlSchemaDataTypeString)) { return l.Value; } else { throw new RdfQueryException("Cannot evaluate an XPath string-join since the separator expression returns a typed Literal which is not a String"); } } else { return l.Value; } } else { throw new RdfQueryException("Cannot evaluate an XPath string-join since the separator expression does not return a Literal"); } } /// <summary> /// Gets the String representation of the function. /// </summary> /// <returns></returns> public override string ToString() { StringBuilder output = new StringBuilder(); output.Append('<'); output.Append(XPathFunctionFactory.XPathFunctionsNamespace); output.Append(XPathFunctionFactory.StringJoin); output.Append(">("); if (_distinct) output.Append("DISTINCT "); output.Append(_expr.ToString()); if (_customSep) { output.Append(_sep.ToString()); } output.Append(')'); return output.ToString(); } /// <summary> /// Gets the Functor of the Expression. /// </summary> public override string Functor { get { return XPathFunctionFactory.XPathFunctionsNamespace + XPathFunctionFactory.StringJoin; } } } }
36.714286
169
0.529426
[ "MIT" ]
BME-MIT-IET/iet-hf2021-gitgud
Libraries/dotNetRDF/Query/Aggregates/XPath/StringJoin.cs
8,224
C#
using System; using Microsoft.AspNetCore.Mvc; namespace UTMAPP.Controllers { [ApiController] [Produces("application/json")] [Route("/")] public class MainController : ControllerBase { [HttpGet] public IActionResult GetApiInfo() { return Ok(new { Version = "1.0.0", nameof = "Calculate values", SwaggerSchema = "/swagger" }); } } }
20.521739
48
0.512712
[ "MIT" ]
vitaliemiron/utm-equation
be/UTMAPP/Controllers/MainController.cs
472
C#
using Microsoft.Web.WebView2.Core; namespace WebView2.DOM { // https://github.com/chromium/chromium/blob/master/third_party/blink/renderer/core/svg/svg_mask_element.idl public partial class SVGMaskElement : SVGElement { protected internal SVGMaskElement(CoreWebView2 coreWebView, string referenceId) : base(coreWebView, referenceId) { } public SVGAnimatedEnumeration<SVGUnitType> maskUnits => Get<SVGAnimatedEnumeration<SVGUnitType>>(); public SVGAnimatedEnumeration<SVGUnitType> maskContentUnits => Get<SVGAnimatedEnumeration<SVGUnitType>>(); public SVGAnimatedLength x => Get<SVGAnimatedLength>(); public SVGAnimatedLength y => Get<SVGAnimatedLength>(); public SVGAnimatedLength width => Get<SVGAnimatedLength>(); public SVGAnimatedLength height => Get<SVGAnimatedLength>(); } public partial class SVGMaskElement : SVGTests { public SVGStringList requiredExtensions => Get<SVGStringList>(); public SVGStringList systemLanguage => Get<SVGStringList>(); } }
31.53125
109
0.773043
[ "MIT" ]
R2D221/WebView2.DOM
WebView2.DOM/SVG/Elements/SVGMaskElement.cs
1,011
C#
using Geek.Server.Logic.Bag; using Geek.Server.Proto; using NLog; using System; using System.Threading.Tasks; namespace Geek.Server.Logic.Role { public class RoleCompAgent : StateComponentAgent<RoleComp, RoleState> { private static readonly Logger LOGGER = LogManager.GetCurrentClassLogger(); class RoleEH : EventListener<RoleCompAgent> { protected override async Task HandleEvent(RoleCompAgent agent, Event evt) { switch (evt.EventId) { case (int)EventID.OnDisconnected: await agent.OnDisconnected(); break; case (int)EventID.OnMsgReceived: await agent.OnMsgReceived(); break; } } public override Task InitListener(long entityId) { GED.AddListener<RoleEH>(entityId, EventID.OnDisconnected); GED.AddListener<RoleEH>(entityId, EventID.OnMsgReceived); return Task.CompletedTask; } } public Task<bool> IsOnline() { return Task.FromResult(true); } public Task OnDisconnected() { return Task.CompletedTask; } public Task OnMsgReceived() { //可以用于心跳处理 return Task.CompletedTask; } public Task OnCreate(ReqLogin reqLogin, long roleId) { State.CreateTime = DateTime.Now; State.Level = 1; State.VipLevel = 1; State.RoleId = roleId; State.RoleName = new System.Random().Next(1000, 10000).ToString();//随机给一个 return Task.CompletedTask; } public async Task OnLogin(ReqLogin reqLogin, bool isNewRole, long roleId) { if (isNewRole) { await OnCreate(reqLogin, roleId); var bagComp = await GetCompAgent<BagCompAgent>(); await bagComp.Init(); } State.LoginTime = DateTime.Now; } public Task OnLoginOut() { State.OfflineTime = DateTime.Now; return Task.CompletedTask; } [MethodOption.ThreadSafe] public virtual Task<ResLogin> BuildLoginMsg() { var res = new ResLogin() { Code = 0, UserInfo = new UserInfo() { CreateTime = State.CreateTime.Ticks, Level = State.Level, RoleId = State.RoleId, RoleName = State.RoleName, VipLevel = State.VipLevel } }; return Task.FromResult(res); } public static Task<bool> IsRoleOnline(long entityId) { throw new NotImplementedException(); } /// <summary> 通知客户端消息 </summary> [MethodOption.NotAwait] public virtual async Task NotifyClient(IMessage msg) { if (await IsOnline()) { var session = SessionManager.Get(EntityId); if (session != null) { SessionUtils.WriteAndFlush(session.Channel, msg); } } } /// <summary> /// 此接口是 /// </summary> /// <param name="msg"></param> /// <param name="uniId"></param> /// <returns></returns> [MethodOption.NotAwait] public virtual async Task NotifyClient(MSG msg, int uniId = 0) { if (await IsOnline()) { var session = SessionManager.Get(EntityId); if (session != null) { if (msg.MsgId > 0) await NotifyClient(msg.msg); if (msg.UniId < 0 || uniId < 0) return; var errInfo = msg.Info; ResErrorCode res = new ResErrorCode { UniId = msg.UniId, ErrCode = (int)errInfo.Code, Desc = errInfo.Desc, }; await NotifyClient(res); } } } } }
29.172185
85
0.472645
[ "MIT" ]
ErQing/GeekServer
GeekServer.Hotfix/Logic/Role/RoleCompAgent.cs
4,455
C#
using CyberCAT.Core.Classes.Mapping; namespace CyberCAT.Core.Classes.DumpedClasses { [RealName("gameIAttack")] public class GameIAttack : IScriptable { } }
17.3
45
0.716763
[ "MIT" ]
Deweh/CyberCAT
CyberCAT.Core/Classes/DumpedClasses/GameIAttack.cs
173
C#
namespace EasyBrush.Views { partial class QuestionnaireForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(QuestionnaireForm)); this.pictureBox1 = new System.Windows.Forms.PictureBox(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // pictureBox1 // this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(12, 12); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(221, 214); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; // // QuestionnaireForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(252, 246); this.Controls.Add(this.pictureBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "QuestionnaireForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "调查反馈"; ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.PictureBox pictureBox1; } }
40.208955
149
0.604677
[ "MIT" ]
yuzhengyang/EasyBrush
EasyBrush/EasyBrush/Views/QuestionnaireForm.Designer.cs
2,704
C#
using System.Collections.Generic; using DotNetify; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTests { [TestClass] public class BaseVMCRUDExtensionTest { public class TestObject { public int Id { get; set; } public string Name { get; set; } } private class TestVM : BaseVM { public List<TestObject> Sequence { get { return Get<List<TestObject>>(); } set { Set(value); } } public TestVM() { Sequence = new List<TestObject> { new TestObject { Id = 1, Name = "One" }, new TestObject { Id = 2, Name = "" }, new TestObject { Id = 3, Name = "Three" } }; } } [TestMethod] public void BaseVM_CRUD() { var vm = new TestVM(); vm.AddList(() => vm.Sequence, new TestObject { Id = 4, Name = "Four" }); Assert.IsNotNull(vm.ChangedProperties); Assert.IsTrue(vm.ChangedProperties.ContainsKey("Sequence_add")); Assert.IsNotNull(vm.ChangedProperties["Sequence_add"] as TestObject); Assert.AreEqual(4, (vm.ChangedProperties["Sequence_add"] as TestObject).Id); Assert.AreEqual("Four", (vm.ChangedProperties["Sequence_add"] as TestObject).Name); vm.UpdateList(() => vm.Sequence, new TestObject { Id = 2, Name = "Two" }); Assert.IsNotNull(vm.ChangedProperties); Assert.IsTrue(vm.ChangedProperties.ContainsKey("Sequence_update")); Assert.IsNotNull(vm.ChangedProperties["Sequence_update"] as TestObject); Assert.AreEqual(2, (vm.ChangedProperties["Sequence_update"] as TestObject).Id); Assert.AreEqual("Two", (vm.ChangedProperties["Sequence_update"] as TestObject).Name); vm.RemoveList(() => vm.Sequence, 3); Assert.IsNotNull(vm.ChangedProperties); Assert.IsTrue(vm.ChangedProperties.ContainsKey("Sequence_remove")); Assert.AreEqual(3, vm.ChangedProperties["Sequence_remove"]); } } }
35.542373
94
0.59752
[ "Apache-2.0" ]
BajakiGabesz/dotNetify
UnitTests/BaseVMCRUDExtensionTest.cs
2,099
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class AppController : MonoBehaviour { public GameObject configPanel; public GameObject buttonsControl; void Start() { } public void CloseApp(){ Application.Quit(); } public void HabilitarImpresionMensaje(){ buttonsControl.GetComponent<ButtonJoystick>().setImprimeMensaje(configPanel.transform.Find("Logs").GetComponent<Toggle>().isOn); } }
19.296296
136
0.696737
[ "MIT" ]
probots-ml/control-universal-ml
Assets/Scripts/AppController.cs
523
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.Web.V20201201.Inputs { /// <summary> /// Description of a backup schedule. Describes how often should be the backup performed and what should be the retention policy. /// </summary> public sealed class BackupScheduleArgs : Pulumi.ResourceArgs { /// <summary> /// How often the backup should be executed (e.g. for weekly backup, this should be set to 7 and FrequencyUnit should be set to Day) /// </summary> [Input("frequencyInterval", required: true)] public Input<int> FrequencyInterval { get; set; } = null!; /// <summary> /// The unit of time for how often the backup should be executed (e.g. for weekly backup, this should be set to Day and FrequencyInterval should be set to 7) /// </summary> [Input("frequencyUnit", required: true)] public Input<Pulumi.AzureNative.Web.V20201201.FrequencyUnit> FrequencyUnit { get; set; } = null!; /// <summary> /// True if the retention policy should always keep at least one backup in the storage account, regardless how old it is; false otherwise. /// </summary> [Input("keepAtLeastOneBackup", required: true)] public Input<bool> KeepAtLeastOneBackup { get; set; } = null!; /// <summary> /// After how many days backups should be deleted. /// </summary> [Input("retentionPeriodInDays", required: true)] public Input<int> RetentionPeriodInDays { get; set; } = null!; /// <summary> /// When the schedule should start working. /// </summary> [Input("startTime")] public Input<string>? StartTime { get; set; } public BackupScheduleArgs() { FrequencyInterval = 7; FrequencyUnit = Pulumi.AzureNative.Web.V20201201.FrequencyUnit.Day; KeepAtLeastOneBackup = true; RetentionPeriodInDays = 30; } } }
39.684211
165
0.640584
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Web/V20201201/Inputs/BackupScheduleArgs.cs
2,262
C#
using GitHub.Unity; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace UnitTests { static class ProcessManagerExtensions { static NPath defaultGitPath = "git".ToNPath(); public static async Task<IEnumerable<GitBranch>> GetGitBranches(this ProcessManager processManager, NPath workingDirectory, NPath? gitPath = null) { var processor = new BranchListOutputProcessor(); NPath path = gitPath ?? defaultGitPath; var results = await new ProcessTaskWithListOutput<GitBranch>(CancellationToken.None, processor) .Configure(processManager, path, "branch -vv", workingDirectory, false) .Start() .Task; return results; } public static async Task<List<GitLogEntry>> GetGitLogEntries(this ProcessManager processManager, NPath workingDirectory, IEnvironment environment, IFileSystem filesystem, IProcessEnvironment gitEnvironment, int? logCount = null, NPath? gitPath = null) { var gitStatusEntryFactory = new GitObjectFactory(environment); var processor = new LogEntryOutputProcessor(gitStatusEntryFactory); var logNameStatus = @"log --pretty=format:""%H%n%P%n%aN%n%aE%n%aI%n%cN%n%cE%n%cI%n%B---GHUBODYEND---"" --name-status"; if (logCount.HasValue) { logNameStatus = logNameStatus + " -" + logCount.Value; } NPath path = gitPath ?? defaultGitPath; var results = await new ProcessTaskWithListOutput<GitLogEntry>(CancellationToken.None, processor) .Configure(processManager, path, logNameStatus, workingDirectory, false) .Start() .Task; return results; } public static async Task<GitStatus> GetGitStatus(this ProcessManager processManager, NPath workingDirectory, IEnvironment environment, IFileSystem filesystem, IProcessEnvironment gitEnvironment, NPath? gitPath = null) { var gitStatusEntryFactory = new GitObjectFactory(environment); var processor = new StatusOutputProcessor(gitStatusEntryFactory); NPath path = gitPath ?? defaultGitPath; var results = await new ProcessTask<GitStatus>(CancellationToken.None, processor) .Configure(processManager, path, "status -b -u --porcelain", workingDirectory, false) .Start() .Task; return results; } public static async Task<List<GitRemote>> GetGitRemoteEntries(this ProcessManager processManager, NPath workingDirectory, NPath? gitPath = null) { var processor = new RemoteListOutputProcessor(); NPath path = gitPath ?? defaultGitPath; var results = await new ProcessTaskWithListOutput<GitRemote>(CancellationToken.None, processor) .Configure(processManager, path, "remote -v", workingDirectory, false) .Start() .Task; return results; } public static async Task<string> GetGitCreds(this ProcessManager processManager, NPath workingDirectory, IEnvironment environment, IFileSystem filesystem, IProcessEnvironment gitEnvironment, NPath? gitPath = null) { var processor = new FirstNonNullLineOutputProcessor(); NPath path = gitPath ?? defaultGitPath; var task = new ProcessTask<string>(CancellationToken.None, processor) .Configure(processManager, path, "credential-wincred get", workingDirectory, true); task.OnStartProcess += p => { p.StandardInput.WriteLine("protocol=https"); p.StandardInput.WriteLine("host=github.com"); p.StandardInput.Close(); }; return await task.StartAsAsync(); } } }
37.636364
130
0.617633
[ "MIT" ]
Frozenfire92/Unity
src/tests/UnitTests/ProcessManagerExtensions.cs
4,140
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: Microsoft.Extensions.Configuration.UserSecrets.UserSecretsIdAttribute("eaeb2415-563c-44a5-af31-c86e7ab16157")] [assembly: System.Reflection.AssemblyCompanyAttribute("P1")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("P1")] [assembly: System.Reflection.AssemblyTitleAttribute("P1")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
43.12
121
0.663265
[ "MIT" ]
090820-dotnet-uta/ChristopherKeller_p1
P1_WIP/P1/obj/Debug/netcoreapp3.1/P1.AssemblyInfo.cs
1,078
C#
using Microsoft.AspNetCore.Mvc; namespace MithrilShards.WebApi { [ApiController] [Produces("application/json")] [Route("[area]/[controller]/[action]")] public abstract class MithrilControllerBase : ControllerBase { } }
23.3
67
0.729614
[ "MIT" ]
MithrilMan/MithrilShards
src/MithrilShards.WebApi/MithrilControllerBase.cs
235
C#
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using FlatMate.Module.Common.Extensions; using FlatMate.Module.Common.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using prayzzz.Common.Attributes; namespace FlatMate.Module.Offers.Tasks { [Inject(typeof(ScheduledTask))] public class DeleteOldProductsTask : ScheduledTask { private readonly OffersDbContext _context; private readonly ILogger<DeleteOldProductsTask> _logger; public DeleteOldProductsTask(OffersDbContext context, ILogger<DeleteOldProductsTask> logger) { _context = context; _logger = logger; } /// <summary> /// Every Sunday 12:00 UTC /// </summary> public override string Schedule => "0 12 * * 0"; public override async Task ExecuteAsync(CancellationToken cancellationToken) { var date = DateTime.Now.AddMonths(-12).ToString("yyyy-MM-dd"); var dtos = _context.OldProductDtos.FromSqlRaw(@" SELECT product.Id as ProductId, offer.id as OfferId FROM Offers.Product product JOIN Offers.Offer offer on offer.ProductId = product.Id WHERE (SELECT COUNT(*) FROM Offers.Offer WHERE ProductId = product.Id AND [To] > ${0}) = 0 AND NOT EXISTS (SELECT * FROM Offers.ProductFavorite pf WHERE pf.ProductId = product.Id) ", date).AsNoTracking(); var offerIds = dtos.Select(x => x.OfferId).Distinct().ToList(); var productIds = dtos.Select(x => x.ProductId).Distinct().ToList(); _logger.LogInformation($"Found {productIds.Count} Products with no Offers since {date}"); var offers = _context.Offers.Where(o => offerIds.Contains(o.Id)); _context.Offers.RemoveRange(offers); var priceHistory = _context.PriceHistories.Where(ph => productIds.Contains(ph.ProductId)); _context.PriceHistories.RemoveRange(priceHistory); var products = _context.Products.Where(ph => productIds.Contains(ph.Id)); _context.Products.RemoveRange(products); using (var _ = _logger.LogInformationTimed("Old Products removed")) { await _context.SaveChangesAsync(cancellationToken); } } } public class OldProductDto { public int OfferId { get; set; } public int ProductId { get; set; } } }
36.056338
103
0.634766
[ "MIT" ]
prayzzz/FlatMate-v2
src/FlatMate.Module.Offers/Tasks/DeleteOldProductsTask.cs
2,560
C#
using System.Data.Entity.ModelConfiguration; using SmartStore.Core.Domain.Catalog; namespace SmartStore.Data.Mapping.Catalog { public partial class CategoryMap : EntityTypeConfiguration<Category> { public CategoryMap() { this.ToTable("Category"); this.HasKey(c => c.Id); this.Property(c => c.Name).IsRequired().HasMaxLength(400); this.Property(c => c.FullName).HasMaxLength(400); this.Property(c => c.BottomDescription).IsMaxLength(); this.Property(c => c.Description).IsMaxLength(); this.Property(c => c.MetaKeywords).HasMaxLength(400); this.Property(c => c.MetaTitle).HasMaxLength(400); this.Property(c => c.PageSizeOptions).HasMaxLength(200).IsOptional(); this.Property(c => c.Alias).HasMaxLength(100); this.HasOptional(p => p.Picture) .WithMany() .HasForeignKey(p => p.PictureId) .WillCascadeOnDelete(false); } } }
35.037037
72
0.658562
[ "MIT" ]
jenmcquade/csharp-snippets
SmartStoreNET-3.x/src/Libraries/SmartStore.Data/Mapping/Catalog/CategoryMap.cs
946
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Ads.GoogleAds.V8.Services.Snippets { using Google.Ads.GoogleAds.V8.Resources; using Google.Ads.GoogleAds.V8.Services; public sealed partial class GeneratedAdGroupBidModifierServiceClientStandaloneSnippets { /// <summary>Snippet for GetAdGroupBidModifier</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void GetAdGroupBidModifier() { // Create client AdGroupBidModifierServiceClient adGroupBidModifierServiceClient = AdGroupBidModifierServiceClient.Create(); // Initialize request argument(s) string resourceName = "customers/[CUSTOMER_ID]/adGroupBidModifiers/[AD_GROUP_ID]~[CRITERION_ID]"; // Make the request AdGroupBidModifier response = adGroupBidModifierServiceClient.GetAdGroupBidModifier(resourceName); } } }
41.325
119
0.714459
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/ads/googleads/v8/googleads-csharp/Google.Ads.GoogleAds.V8.Services.StandaloneSnippets/AdGroupBidModifierServiceClient.GetAdGroupBidModifierSnippet.g.cs
1,653
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="OxyRectTests.cs" company="OxyPlot"> // Copyright (c) 2014 OxyPlot contributors // </copyright> // <summary> // Provides unit tests for the <see cref="OxyRect" /> class and it's extensions. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace OxyPlot.Tests { using NUnit.Framework; /// <summary> /// Unit tests for <see cref="OxyRect" />. /// </summary> [TestFixture] public class OxyRectTests { /// <summary> /// Tests the Equals method. /// </summary> [Test] public void Equals() { Assert.That(new OxyRect(1, 2, 3, 4).Equals(new OxyRect(1, 2, 3, 4)), Is.True); Assert.That(new OxyRect(1, 2, 3, 4).Equals(new OxyRect()), Is.False); } /// <summary> /// Tests the Inflate method. /// </summary> [Test] public void Inflate() { Assert.That(new OxyRect(1, 2, 3, 4).Inflate(0.1, 0.2), Is.EqualTo(new OxyRect(0.9, 1.8, 3.2, 4.4))); Assert.That(new OxyRect(10, 20, 30, 40).Inflate(new OxyThickness(1, 2, 3, 4)), Is.EqualTo(new OxyRect(9, 18, 34, 46))); } /// <summary> /// Tests the Deflate method. /// </summary> [Test] public void Deflate() { Assert.That(new OxyRect(10, 20, 30, 40).Deflate(new OxyThickness(1, 2, 3, 4)), Is.EqualTo(new OxyRect(11, 22, 26, 34))); } /// <summary> /// Tests the Offset method. /// </summary> [Test] public void Offset() { Assert.That(new OxyRect(1, 2, 3, 4).Offset(0.1, 0.2), Is.EqualTo(new OxyRect(1.1, 2.2, 3, 4))); } } }
33.068966
132
0.452555
[ "MIT" ]
GeertvanHorrik/oxyplot
Source/OxyPlot.Tests/Foundation/OxyRectTests.cs
1,920
C#
using Adyen.CloudApiSerialization; using Newtonsoft.Json; using System.Runtime.Serialization; namespace Adyen.Model.Nexo { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)] public partial class RepeatedResponseMessageBody : IMessagePayload { [System.Xml.Serialization.XmlElementAttribute("CardAcquisitionResponse", typeof(CardAcquisitionResponse), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] [System.Xml.Serialization.XmlElementAttribute("CardReaderAPDUResponse", typeof(CardReaderAPDUResponse), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] [System.Xml.Serialization.XmlElementAttribute("LoyaltyResponse", typeof(LoyaltyResponse), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] [System.Xml.Serialization.XmlElementAttribute("PaymentResponse", typeof(PaymentResponse), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] [System.Xml.Serialization.XmlElementAttribute("ReversalResponse", typeof(ReversalResponse), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] [System.Xml.Serialization.XmlElementAttribute("StoredValueResponse", typeof(StoredValueResponse), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] public dynamic MessagePayload; } }
66.5
166
0.782581
[ "MIT" ]
Ganesh-Chavan/adyen-dotnet-api-library
Adyen/Model/Nexo/RepeatedResponseMessageBody.cs
1,598
C#
// Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Hazelcast.Client.Connection; using Hazelcast.Client.Protocol; using Hazelcast.Core; using Hazelcast.Logging; using Hazelcast.Util; #pragma warning disable CS1591 namespace Hazelcast.Client.Spi { internal class ClientListenerService : IClientListenerService, IConnectionListener, IDisposable { private const int DefaultEventThreadCount = 3; private const int DefaultEventQueueCapacity = 1000000; private readonly HazelcastClient _client; private static readonly ILogger Logger = Logging.Logger.GetLogger(typeof(ClientSmartInvocationService)); private readonly StripedTaskScheduler _registrationScheduler; private readonly StripedTaskScheduler _eventExecutor; private readonly ClientConnectionManager _connectionManager; private Timer _connectionReopener; private readonly ConcurrentDictionary<ClientConnection, ICollection<ListenerRegistration>> _failedRegistrations; private readonly ConcurrentDictionary<string, ListenerRegistration> _registrations; private readonly ConcurrentDictionary<long, DistributedEventHandler> _eventHandlers; public bool IsSmart { get; private set; } public ClientListenerService(HazelcastClient client) { _client = client; _connectionManager = client.GetConnectionManager(); var eventTreadCount = EnvironmentUtil.ReadInt("hazelcast.client.event.thread.count") ?? DefaultEventThreadCount; var eventQueueCapacity = EnvironmentUtil.ReadInt("hazelcast.client.event.queue.capacity") ?? DefaultEventQueueCapacity; _eventExecutor = new StripedTaskScheduler(eventTreadCount, eventQueueCapacity, client.GetName() + ".event"); _registrationScheduler = new StripedTaskScheduler(1, eventQueueCapacity, client.GetName() + ".eventRegistration"); _registrations = new ConcurrentDictionary<string, ListenerRegistration>(); _eventHandlers = new ConcurrentDictionary<long, DistributedEventHandler>(); _failedRegistrations = new ConcurrentDictionary<ClientConnection, ICollection<ListenerRegistration>>(); IsSmart = client.GetClientConfig().GetNetworkConfig().IsSmartRouting(); } public string RegisterListener(IClientMessage registrationMessage, DecodeRegisterResponse responseDecoder, EncodeDeregisterRequest encodeDeregisterRequest, DistributedEventHandler eventHandler) { //This method should not be called from registrationExecutor Debug.Assert(Thread.CurrentThread.Name == null || !Thread.CurrentThread.Name.Contains("eventRegistration")); TrySyncConnectToAllConnections(); var registrationTask = new Task<string>(() => { var userRegistrationId = Guid.NewGuid().ToString(); var listenerRegistration = new ListenerRegistration(userRegistrationId, registrationMessage, responseDecoder, encodeDeregisterRequest, eventHandler); _registrations.TryAdd(userRegistrationId, listenerRegistration); var connections = _connectionManager.ActiveConnections; foreach (var connection in connections) { try { RegisterListenerOnConnection(listenerRegistration, connection); } catch (Exception e) { if (connection.Live) { DeregisterListenerInternal(userRegistrationId); throw new HazelcastException("Listener cannot be added ", e); } } } return userRegistrationId; }); try { registrationTask.Start(_registrationScheduler); return registrationTask.Result; } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } } public bool DeregisterListener(string userRegistrationId) { //This method should not be called from registrationExecutor Debug.Assert(Thread.CurrentThread.Name == null || !Thread.CurrentThread.Name.Contains("eventRegistration")); try { return Task<bool>.Factory.StartNew(() => DeregisterListenerInternal(userRegistrationId), Task<bool>.Factory.CancellationToken, Task<bool>.Factory.CreationOptions, _registrationScheduler).Result; } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } } private bool DeregisterListenerInternal(string userRegistrationId) { //This method should not be called from registrationExecutor Debug.Assert(Thread.CurrentThread.Name == null || !Thread.CurrentThread.Name.Contains("eventRegistration")); ListenerRegistration listenerRegistration; if (!_registrations.TryGetValue(userRegistrationId, out listenerRegistration)) { return false; } var successful = true; foreach (var connectionRegistration in listenerRegistration.ConnectionRegistrations.Values) { var connection = connectionRegistration.ClientConnection; try { var serverRegistrationId = connectionRegistration.ServerRegistrationId; var request = listenerRegistration.EncodeDeregisterRequest(serverRegistrationId); var future = ((ClientInvocationService) _client.GetInvocationService()).InvokeOnConnection(request, connection); ThreadUtil.GetResult(future); DistributedEventHandler removed; _eventHandlers.TryRemove(connectionRegistration.CorrelationId, out removed); EventRegistration reg; listenerRegistration.ConnectionRegistrations.TryRemove(connection, out reg); } catch (Exception e) { if (connection.Live) { successful = false; Logger.Warning( string.Format("Deregistration of listener with ID {0} has failed to address {1}", userRegistrationId, connection.GetLocalSocketAddress()), e); } } } if (successful) { _registrations.TryRemove(userRegistrationId, out listenerRegistration); } return successful; } private void RegisterListenerOnConnection(ListenerRegistration listenerRegistration, ClientConnection connection) { //This method should only be called from registrationExecutor Debug.Assert(Thread.CurrentThread.Name != null && Thread.CurrentThread.Name.Contains("eventRegistration")); if (listenerRegistration.ConnectionRegistrations.ContainsKey(connection)) { return; } var future = ((ClientInvocationService) _client.GetInvocationService()).InvokeListenerOnConnection( listenerRegistration.RegistrationRequest, listenerRegistration.EventHandler, connection); IClientMessage clientMessage; try { clientMessage = ThreadUtil.GetResult(future); } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } var serverRegistrationId = listenerRegistration.DecodeRegisterResponse(clientMessage); var correlationId = listenerRegistration.RegistrationRequest.GetCorrelationId(); var registration = new EventRegistration(serverRegistrationId, correlationId, connection); Debug.Assert(listenerRegistration.ConnectionRegistrations != null, "registrationMap should be created!"); listenerRegistration.ConnectionRegistrations[connection] = registration; } public bool AddEventHandler(long correlationId, DistributedEventHandler eventHandler) { return _eventHandlers.TryAdd(correlationId, eventHandler); } public bool RemoveEventHandler(long correlationId) { DistributedEventHandler removed; return _eventHandlers.TryRemove(correlationId, out removed); } internal void TrySyncConnectToAllConnections() { if (!IsSmart) return; long timeLeftMillis = ((ClientInvocationService) _client.GetInvocationService()).InvocationTimeoutMillis; do { // Define the cancellation token. using (var source = new CancellationTokenSource()) { var token = source.Token; var clientClusterService = _client.GetClientClusterService(); var tasks = clientClusterService.GetMemberList().Select(member => Task.Factory.StartNew(() => { try { _connectionManager.GetOrConnectAsync(member.GetAddress()).Wait(token); } catch (Exception) { // if an exception occur cancel the process source.Cancel(); } }, token)).ToArray(); var start = Clock.CurrentTimeMillis(); try { if (Task.WaitAll(tasks, (int) timeLeftMillis, token)) { //All succeed return; } } catch (Exception) { //waitAll did not completed } timeLeftMillis -= Clock.CurrentTimeMillis() - start; } } while (_client.GetLifecycleService().IsRunning() && timeLeftMillis > 0); throw new TimeoutException("Registering listeners is timed out."); } private void RegisterListenerFromInternal(ListenerRegistration listenerRegistration, ClientConnection connection) { //This method should only be called from registrationExecutor Debug.Assert(Thread.CurrentThread.Name != null && Thread.CurrentThread.Name.Contains("eventRegistration")); try { RegisterListenerOnConnection(listenerRegistration, connection); } catch (IOException) { ICollection<ListenerRegistration> failedRegsToConnection; if (!_failedRegistrations.TryGetValue(connection, out failedRegsToConnection)) { failedRegsToConnection = new HashSet<ListenerRegistration>(); _failedRegistrations[connection] = failedRegsToConnection; } failedRegsToConnection.Add(listenerRegistration); } catch (Exception e) { Logger.Warning(string.Format("Listener {0} can not be added to a new connection: {1}, reason: {2}", listenerRegistration, connection, e.Message)); } } public void HandleResponseMessage(IClientMessage message) { var partitionId = message.GetPartitionId(); Task.Factory.StartNew(o => { var correlationId = message.GetCorrelationId(); DistributedEventHandler eventHandler; if (!_eventHandlers.TryGetValue(correlationId, out eventHandler)) { Logger.Warning(string.Format("No eventHandler for correlationId: {0} , event: {1} .", correlationId, message)); return; } eventHandler(message); }, partitionId, Task.Factory.CancellationToken, Task.Factory.CreationOptions, _eventExecutor); } public void ConnectionAdded(ClientConnection connection) { //This method should not be called from registrationExecutor Debug.Assert(Thread.CurrentThread.Name == null || !Thread.CurrentThread.Name.Contains("eventRegistration")); SubmitToRegistrationScheduler(() => { foreach (var listenerRegistration in _registrations.Values) { RegisterListenerFromInternal(listenerRegistration, connection); } }); } public void ConnectionRemoved(ClientConnection connection) { //This method should not be called from registrationExecutor Debug.Assert(Thread.CurrentThread.Name == null || !Thread.CurrentThread.Name.Contains("eventRegistration")); SubmitToRegistrationScheduler(() => { ICollection<ListenerRegistration> removed; _failedRegistrations.TryRemove(connection, out removed); foreach (var listenerRegistration in _registrations.Values) { EventRegistration registration; if (listenerRegistration.ConnectionRegistrations.TryRemove(connection, out registration)) { RemoveEventHandler(registration.CorrelationId); } } }); } public void Start() { _connectionManager.AddConnectionListener(this); if (IsSmart) { _connectionReopener = new Timer(ReOpenAllConnectionsIfNotOpen, null, 1000, 1000); } } public void Dispose() { if (_connectionReopener != null) { _connectionReopener.Dispose(); } _registrationScheduler.Dispose(); _eventExecutor.Dispose(); } private void SubmitToRegistrationScheduler(Action action) { Task.Factory.StartNew(action, Task.Factory.CancellationToken, Task.Factory.CreationOptions, _registrationScheduler); } private void ReOpenAllConnectionsIfNotOpen(object state) { var clientClusterService = _client.GetClientClusterService(); var memberList = clientClusterService.GetMemberList(); foreach (var member in memberList) { try { _connectionManager.GetOrConnectAsync(member.GetAddress()); } catch (IOException) { return; } } } } }
42.710106
130
0.594308
[ "Apache-2.0" ]
asimarslan/hazelcast-csharp-client
Hazelcast.Net/Hazelcast.Client.Spi/ClientListenerService.cs
16,061
C#
#pragma checksum "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\NumericRangeValidatorPage.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "6d43d3bde11a25b5d8a122bb4f4725154d5b3ad4" // <auto-generated/> #pragma warning disable 1591 namespace RadzenBlazorDemos.Pages { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #nullable restore #line 1 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\_Imports.razor" using System.Net.Http; #line default #line hidden #nullable disable #nullable restore #line 2 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\_Imports.razor" using Microsoft.AspNetCore.Components.Forms; #line default #line hidden #nullable disable #nullable restore #line 3 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\_Imports.razor" using Microsoft.AspNetCore.Components.Routing; #line default #line hidden #nullable disable #nullable restore #line 4 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\_Imports.razor" using Microsoft.AspNetCore.Components.Web; #line default #line hidden #nullable disable #nullable restore #line 5 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\_Imports.razor" using Microsoft.AspNetCore.Components.Authorization; #line default #line hidden #nullable disable #nullable restore #line 6 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\_Imports.razor" using Microsoft.JSInterop; #line default #line hidden #nullable disable #nullable restore #line 3 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\_Imports.razor" using Radzen.Blazor; #line default #line hidden #nullable disable #nullable restore #line 4 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\_Imports.razor" using RadzenBlazorDemos; #line default #line hidden #nullable disable #nullable restore #line 5 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\_Imports.razor" using RadzenBlazorDemos.Shared; #line default #line hidden #nullable disable #nullable restore #line 2 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\NumericRangeValidatorPage.razor" using Radzen; #line default #line hidden #nullable disable #nullable restore #line 3 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\NumericRangeValidatorPage.razor" using System.Text.Json; #line default #line hidden #nullable disable [Microsoft.AspNetCore.Components.LayoutAttribute(typeof(MainLayout))] [Microsoft.AspNetCore.Components.RouteAttribute("/numericrangevalidator")] public partial class NumericRangeValidatorPage : Microsoft.AspNetCore.Components.ComponentBase { #pragma warning disable 1998 protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) { __builder.OpenComponent<RadzenBlazorDemos.Shared.RadzenExample>(0); __builder.AddAttribute(1, "Name", "NumericRangeValidator"); __builder.AddAttribute(2, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment)((__builder2) => { __builder2.OpenElement(3, "div"); __builder2.AddAttribute(4, "class", "row"); __builder2.OpenElement(5, "div"); __builder2.AddAttribute(6, "class", "col-xl-6"); __builder2.OpenElement(7, "div"); __builder2.AddAttribute(8, "class", "row"); __builder2.OpenElement(9, "div"); __builder2.AddAttribute(10, "class", "col"); __builder2.OpenComponent<Radzen.Blazor.RadzenTemplateForm<Model>>(11); __builder2.AddAttribute(12, "Data", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Model>( #nullable restore #line 10 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\NumericRangeValidatorPage.razor" model #line default #line hidden #nullable disable )); __builder2.AddAttribute(13, "Submit", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.EventCallback<Model>>(Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Model>(this, #nullable restore #line 10 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\NumericRangeValidatorPage.razor" OnSubmit #line default #line hidden #nullable disable ))); __builder2.AddAttribute(14, "InvalidSubmit", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.EventCallback<Radzen.FormInvalidSubmitEventArgs>>(Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Radzen.FormInvalidSubmitEventArgs>(this, #nullable restore #line 10 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\NumericRangeValidatorPage.razor" OnInvalidSubmit #line default #line hidden #nullable disable ))); __builder2.AddAttribute(15, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment<Microsoft.AspNetCore.Components.Forms.EditContext>)((context) => (__builder3) => { __builder3.OpenComponent<Radzen.Blazor.RadzenFieldset>(16); __builder3.AddAttribute(17, "Text", "Bid info"); __builder3.AddAttribute(18, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment)((__builder4) => { __builder4.OpenElement(19, "div"); __builder4.AddAttribute(20, "class", "row"); __builder4.AddAttribute(21, "style", "margin-bottom: 48px"); __builder4.OpenElement(22, "div"); __builder4.AddAttribute(23, "class", "col-md-4 align-right"); __builder4.OpenComponent<Radzen.Blazor.RadzenLabel>(24); __builder4.AddAttribute(25, "Text", "Quantity"); __builder4.CloseComponent(); __builder4.AddMarkupContent(26, "\r\n "); __builder4.AddMarkupContent(27, "<small style=\"display: block\">(1-10 items)</small>"); __builder4.CloseElement(); __builder4.AddMarkupContent(28, "\r\n "); __builder4.OpenElement(29, "div"); __builder4.AddAttribute(30, "class", "col"); __Blazor.RadzenBlazorDemos.Pages.NumericRangeValidatorPage.TypeInference.CreateRadzenNumeric_0(__builder4, 31, 32, "display: block", 33, "Quantity", 34, Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.ChangeEventArgs>(this, #nullable restore #line 18 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\NumericRangeValidatorPage.razor" OnInput #line default #line hidden #nullable disable ), 35, #nullable restore #line 18 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\NumericRangeValidatorPage.razor" model.Quantity #line default #line hidden #nullable disable , 36, Microsoft.AspNetCore.Components.EventCallback.Factory.Create(this, Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.CreateInferredEventCallback(this, __value => model.Quantity = __value, model.Quantity)), 37, () => model.Quantity); __builder4.AddMarkupContent(38, "\r\n "); __builder4.OpenComponent<Radzen.Blazor.RadzenNumericRangeValidator>(39); __builder4.AddAttribute(40, "Component", "Quantity"); __builder4.AddAttribute(41, "Min", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<dynamic>( #nullable restore #line 19 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\NumericRangeValidatorPage.razor" 1 #line default #line hidden #nullable disable )); __builder4.AddAttribute(42, "Max", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<dynamic>( #nullable restore #line 19 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\NumericRangeValidatorPage.razor" 10 #line default #line hidden #nullable disable )); __builder4.AddAttribute(43, "Text", "Quantity should be between 1 and 10"); __builder4.AddAttribute(44, "Popup", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Boolean>( #nullable restore #line 19 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\NumericRangeValidatorPage.razor" popup #line default #line hidden #nullable disable )); __builder4.AddAttribute(45, "Style", "position: absolute"); __builder4.CloseComponent(); __builder4.CloseElement(); __builder4.CloseElement(); __builder4.AddMarkupContent(46, "\r\n "); __builder4.OpenComponent<Radzen.Blazor.RadzenButton>(47); __builder4.AddAttribute(48, "ButtonType", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Radzen.ButtonType>( #nullable restore #line 22 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\NumericRangeValidatorPage.razor" ButtonType.Submit #line default #line hidden #nullable disable )); __builder4.AddAttribute(49, "Text", "Submit"); __builder4.CloseComponent(); } )); __builder3.CloseComponent(); } )); __builder2.CloseComponent(); __builder2.CloseElement(); __builder2.AddMarkupContent(50, "\r\n "); __builder2.OpenElement(51, "div"); __builder2.AddAttribute(52, "class", "col"); __builder2.OpenElement(53, "label"); __builder2.AddMarkupContent(54, "\r\n Display validators as popup\r\n "); __Blazor.RadzenBlazorDemos.Pages.NumericRangeValidatorPage.TypeInference.CreateRadzenCheckBox_1(__builder2, 55, 56, #nullable restore #line 29 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\NumericRangeValidatorPage.razor" popup #line default #line hidden #nullable disable , 57, Microsoft.AspNetCore.Components.EventCallback.Factory.Create(this, Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.CreateInferredEventCallback(this, __value => popup = __value, popup)), 58, () => popup); __builder2.CloseElement(); __builder2.CloseElement(); __builder2.CloseElement(); __builder2.CloseElement(); __builder2.AddMarkupContent(59, "\r\n "); __builder2.OpenElement(60, "div"); __builder2.AddAttribute(61, "class", "col-xl-6"); __builder2.OpenComponent<RadzenBlazorDemos.Shared.EventConsole>(62); __builder2.AddComponentReferenceCapture(63, (__value) => { #nullable restore #line 35 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\NumericRangeValidatorPage.razor" console = (RadzenBlazorDemos.Shared.EventConsole)__value; #line default #line hidden #nullable disable } ); __builder2.CloseComponent(); __builder2.CloseElement(); __builder2.CloseElement(); } )); __builder.CloseComponent(); } #pragma warning restore 1998 #nullable restore #line 40 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\NumericRangeValidatorPage.razor" class Model { public decimal Quantity { get; set; } } bool popup; Model model = new Model(); EventConsole console; void OnInput(ChangeEventArgs args) { Log("oninput", args.Value.ToString()); } void Log(string eventName, string value) { console.Log($"{eventName}: {value}"); } void OnSubmit(Model model) { Log("Submit", JsonSerializer.Serialize(model, new JsonSerializerOptions() { WriteIndented = true })); } void OnInvalidSubmit(FormInvalidSubmitEventArgs args) { Log("InvalidSubmit", JsonSerializer.Serialize(args, new JsonSerializerOptions() { WriteIndented = true })); } #line default #line hidden #nullable disable } } namespace __Blazor.RadzenBlazorDemos.Pages.NumericRangeValidatorPage { #line hidden internal static class TypeInference { public static void CreateRadzenNumeric_0<TValue>(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder, int seq, int __seq0, System.Object __arg0, int __seq1, global::System.String __arg1, int __seq2, global::System.Object __arg2, int __seq3, TValue __arg3, int __seq4, global::Microsoft.AspNetCore.Components.EventCallback<TValue> __arg4, int __seq5, global::System.Linq.Expressions.Expression<global::System.Func<TValue>> __arg5) { __builder.OpenComponent<global::Radzen.Blazor.RadzenNumeric<TValue>>(seq); __builder.AddAttribute(__seq0, "style", __arg0); __builder.AddAttribute(__seq1, "Name", __arg1); __builder.AddAttribute(__seq2, "oninput", __arg2); __builder.AddAttribute(__seq3, "Value", __arg3); __builder.AddAttribute(__seq4, "ValueChanged", __arg4); __builder.AddAttribute(__seq5, "ValueExpression", __arg5); __builder.CloseComponent(); } public static void CreateRadzenCheckBox_1<TValue>(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder, int seq, int __seq0, TValue __arg0, int __seq1, global::Microsoft.AspNetCore.Components.EventCallback<TValue> __arg1, int __seq2, global::System.Linq.Expressions.Expression<global::System.Func<TValue>> __arg2) { __builder.OpenComponent<global::Radzen.Blazor.RadzenCheckBox<TValue>>(seq); __builder.AddAttribute(__seq0, "Value", __arg0); __builder.AddAttribute(__seq1, "ValueChanged", __arg1); __builder.AddAttribute(__seq2, "ValueExpression", __arg2); __builder.CloseComponent(); } } } #pragma warning restore 1591
45.90303
463
0.634473
[ "MIT" ]
longvutam/vtl-nvp
RadzenBlazorDemos/obj/Debug/net5.0/Razor/Pages/NumericRangeValidatorPage.razor.g.cs
15,148
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; using System.IO; namespace BackupRotator { public class Config { private const string CONFIG_FILE_NAME = "config.xml"; private static bool s_isInitialized = false; private static Config s_instance; public static Config Instance { get { if(!s_isInitialized) { s_instance = new Config(); s_isInitialized = true; } return s_instance; } set { s_instance = value; } } public static bool Load() { bool result = false; try { XmlSerializer xs = new XmlSerializer(typeof(Config)); using (FileStream fs = new FileStream(CONFIG_FILE_NAME, FileMode.Open)) { Config theConfig = (Config)xs.Deserialize(fs); s_instance = theConfig; s_isInitialized = true; } result = true; } catch(Exception e) { // Nothing to do } return result; } public static bool Save() { bool result = false; try { XmlSerializer xs = new XmlSerializer(typeof(Config)); using (FileStream fs = new FileStream(CONFIG_FILE_NAME, FileMode.OpenOrCreate)) { xs.Serialize(fs, s_instance); } result = true; } catch(Exception e) { // Nothing to do } return result; } public int NumberOfBackups { get; set; } public int BackupInterval { get; set; } } }
24.988235
96
0.44209
[ "MIT" ]
ExempliG/BackupRotator
BackupRotator/Config.cs
2,126
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AsyncAwaitBestPractices; using AsyncAwaitBestPractices.MVVM; using Autofac; using GitTrends.Mobile.Common; using GitTrends.Mobile.Common.Constants; using GitTrends.Shared; using Shiny; using Xamarin.CommunityToolkit.Markup; using Xamarin.Essentials.Interfaces; using Xamarin.Forms; using static Xamarin.CommunityToolkit.Markup.GridRowsColumns; namespace GitTrends { public class RepositoryPage : BaseContentPage<RepositoryViewModel>, ISearchPage { readonly WeakEventManager<string> _searchTextChangedEventManager = new(); readonly RefreshView _refreshView; readonly FirstRunService _firstRunService; readonly GitHubUserService _gitHubUserService; readonly DeepLinkingService _deepLinkingService; public RepositoryPage(IMainThread mainThread, FirstRunService firstRunService, IAnalyticsService analyticsService, GitHubUserService gitHubUserService, DeepLinkingService deepLinkingService, RepositoryViewModel repositoryViewModel, MobileSortingService mobileSortingService) : base(repositoryViewModel, analyticsService, mainThread) { _firstRunService = firstRunService; _gitHubUserService = gitHubUserService; _deepLinkingService = deepLinkingService; //Workaround for CollectionView.SelectionChanged firing when SwipeView is swiped BaseRepositoryDataTemplate.Tapped += HandleRepositoryDataTemplateTapped; SearchBarTextChanged += HandleSearchBarTextChanged; RepositoryViewModel.PullToRefreshFailed += HandlePullToRefreshFailed; LanguageService.PreferredLanguageChanged += HandlePreferredLanguageChanged; this.SetBinding(TitleProperty, nameof(RepositoryViewModel.TitleText)); ToolbarItems.Add(new ToolbarItem { Text = PageTitles.SettingsPage, IconImageSource = Device.RuntimePlatform is Device.iOS ? "Settings" : null, Order = Device.RuntimePlatform is Device.Android ? ToolbarItemOrder.Secondary : ToolbarItemOrder.Default, AutomationId = RepositoryPageAutomationIds.SettingsButton, Command = new AsyncCommand(ExecuteSetttingsToolbarItemCommand) }); ToolbarItems.Add(new ToolbarItem { Text = RepositoryPageConstants.SortToolbarItemText, Priority = 1, IconImageSource = Device.RuntimePlatform is Device.iOS ? "Sort" : null, Order = Device.RuntimePlatform is Device.Android ? ToolbarItemOrder.Secondary : ToolbarItemOrder.Default, AutomationId = RepositoryPageAutomationIds.SortButton, Command = new AsyncCommand(ExecuteSortToolbarItemCommand) }); Content = new Grid { RowDefinitions = Rows.Define( (Row.CollectionView, Star), (Row.Information, InformationButton.Diameter)), ColumnDefinitions = Columns.Define( (Column.CollectionView, Star), (Column.Information, InformationButton.Diameter)), Children = { //Work around to prevent iOS Navigation Bar from collapsing new BoxView { HeightRequest = 0.1 } .RowSpan(All<Row>()).ColumnSpan(All<Column>()), new RefreshView { AutomationId = RepositoryPageAutomationIds.RefreshView, Content = new CollectionView { ItemTemplate = new RepositoryDataTemplateSelector(mobileSortingService, repositoryViewModel), BackgroundColor = Color.Transparent, AutomationId = RepositoryPageAutomationIds.CollectionView, //Work around for https://github.com/xamarin/Xamarin.Forms/issues/9879 Header = Device.RuntimePlatform is Device.Android ? new BoxView { HeightRequest = BaseRepositoryDataTemplate.BottomPadding } : null, Footer = Device.RuntimePlatform is Device.Android ? new BoxView { HeightRequest = BaseRepositoryDataTemplate.TopPadding } : null, EmptyView = new EmptyDataView("EmptyRepositoriesList", RepositoryPageAutomationIds.EmptyDataView) .Bind<EmptyDataView, bool, bool>(IsVisibleProperty, nameof(RepositoryViewModel.IsRefreshing), convert: isRefreshing => !isRefreshing) .Bind(EmptyDataView.TitleProperty, nameof(RepositoryViewModel.EmptyDataViewTitle)) .Bind(EmptyDataView.DescriptionProperty, nameof(RepositoryViewModel.EmptyDataViewDescription)) }.Bind(CollectionView.ItemsSourceProperty, nameof(RepositoryViewModel.VisibleRepositoryList)) }.RowSpan(All<Row>()).ColumnSpan(All<Column>()).Assign(out _refreshView) .Bind(RefreshView.IsRefreshingProperty, nameof(RepositoryViewModel.IsRefreshing)) .Bind(RefreshView.CommandProperty, nameof(RepositoryViewModel.PullToRefreshCommand)) .DynamicResource(RefreshView.RefreshColorProperty, nameof(BaseTheme.PullToRefreshColor)), new InformationButton(mobileSortingService, mainThread, analyticsService).Row(Row.Information).Column(Column.Information) } }; } enum Row { CollectionView, Information } enum Column { CollectionView, Information } public event EventHandler<string> SearchBarTextChanged { add => _searchTextChangedEventManager.AddEventHandler(value); remove => _searchTextChangedEventManager.RemoveEventHandler(value); } protected override async void OnAppearing() { base.OnAppearing(); var token = await _gitHubUserService.GetGitHubToken(); if (!_firstRunService.IsFirstRun && shouldShowWelcomePage(Navigation, token.AccessToken)) { await NavigateToWelcomePage(); } else if (!_firstRunService.IsFirstRun && isUserValid(token.AccessToken, _gitHubUserService.Alias) && _refreshView.Content is CollectionView collectionView && collectionView.ItemsSource.IsNullOrEmpty()) { _refreshView.IsRefreshing = true; } bool shouldShowWelcomePage(in INavigation navigation, in string accessToken) { return !navigation.ModalStack.Any() && _gitHubUserService.Alias != DemoUserConstants.Alias && !isUserValid(accessToken, _gitHubUserService.Alias); } static bool isUserValid(in string accessToken, in string alias) => !string.IsNullOrWhiteSpace(accessToken) || !string.IsNullOrWhiteSpace(alias); } async void HandleRepositoryDataTemplateTapped(object sender, EventArgs e) { var view = (View)sender; var repository = (Repository)view.BindingContext; AnalyticsService.Track("Repository Tapped", new Dictionary<string, string> { { nameof(Repository) + nameof(Repository.OwnerLogin), repository.OwnerLogin }, { nameof(Repository) + nameof(Repository.Name), repository.Name } }); await NavigateToTrendsPage(repository); } async Task NavigateToWelcomePage() { var welcomePage = ContainerService.Container.Resolve<WelcomePage>(); //Allow RepositoryPage to appear briefly before loading await Task.Delay(TimeSpan.FromMilliseconds(250)); await MainThread.InvokeOnMainThreadAsync(() => Navigation.PushModalAsync(welcomePage)); } Task NavigateToSettingsPage() { var settingsPage = ContainerService.Container.Resolve<SettingsPage>(); return MainThread.InvokeOnMainThreadAsync(() => Navigation.PushAsync(settingsPage)); } Task NavigateToTrendsPage(in Repository repository) { var trendsCarouselPage = ContainerService.Container.Resolve<TrendsCarouselPage>(new TypedParameter(typeof(Repository), repository)); return MainThread.InvokeOnMainThreadAsync(() => Navigation.PushAsync(trendsCarouselPage)); } Task ExecuteSetttingsToolbarItemCommand() { AnalyticsService.Track("Settings Button Tapped"); return NavigateToSettingsPage(); } async Task ExecuteSortToolbarItemCommand() { var sortingOptions = MobileSortingService.SortingOptionsDictionary.Values; string? selection = await DisplayActionSheet(SortingConstants.ActionSheetTitle, SortingConstants.CancelText, null, sortingOptions.ToArray()); if (!string.IsNullOrWhiteSpace(selection) && selection != SortingConstants.CancelText) ViewModel.SortRepositoriesCommand.Execute(MobileSortingService.SortingOptionsDictionary.First(x => x.Value == selection).Key); } async void HandlePullToRefreshFailed(object sender, PullToRefreshFailedEventArgs eventArgs) => await MainThread.InvokeOnMainThreadAsync(async () => { if (Application.Current is App && !Application.Current.MainPage.Navigation.ModalStack.Any() && Application.Current.MainPage.Navigation.NavigationStack.Last() is RepositoryPage) { switch (eventArgs) { case MaximumApiRequestsReachedEventArgs: var isAccepted = await DisplayAlert(eventArgs.Title, eventArgs.Message, eventArgs.Accept, eventArgs.Cancel); if (isAccepted) await _deepLinkingService.OpenBrowser(GitHubConstants.GitHubRateLimitingDocs); break; case AbuseLimitPullToRefreshEventArgs when _gitHubUserService.GitHubApiAbuseLimitCount <= 1: var isAlertAccepted = await DisplayAlert(eventArgs.Title, eventArgs.Message, eventArgs.Accept, eventArgs.Cancel); if (isAlertAccepted) await _deepLinkingService.OpenBrowser(GitHubConstants.GitHubApiAbuseDocs); break; case AbuseLimitPullToRefreshEventArgs: // Don't display error message when GitHubUserService.GitHubApiAbuseLimitCount > 1 break; case LoginExpiredPullToRefreshEventArgs: await DisplayAlert(eventArgs.Title, eventArgs.Message, eventArgs.Cancel); await NavigateToWelcomePage(); break; case ErrorPullToRefreshEventArgs: await DisplayAlert(eventArgs.Title, eventArgs.Message, eventArgs.Cancel); break; default: throw new NotSupportedException(); } } }); void HandlePreferredLanguageChanged(object sender, string? e) { var sortItem = ToolbarItems.First(x => x.AutomationId is RepositoryPageAutomationIds.SortButton); var settingsItem = ToolbarItems.First(x => x.AutomationId is RepositoryPageAutomationIds.SettingsButton); sortItem.Text = RepositoryPageConstants.SortToolbarItemText; settingsItem.Text = PageTitles.SettingsPage; } void HandleSearchBarTextChanged(object sender, string searchBarText) => ViewModel.FilterRepositoriesCommand.Execute(searchBarText); void ISearchPage.OnSearchBarTextChanged(in string text) => _searchTextChangedEventManager.RaiseEvent(this, text, nameof(SearchBarTextChanged)); } }
41.370079
161
0.748953
[ "MIT" ]
Tiamat-Tech/GitTrends
GitTrends/Pages/RepositoryPage.cs
10,510
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AwePayingManaCostViewer.cs" company="nGratis"> // The MIT License (MIT) // // Copyright (c) 2014 - 2021 Cahya Ong // // 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> // <author>Cahya Ong - cahya.ong@gmail.com</author> // <creation_timestamp>Monday, 7 January 2019 8:12:55 AM UTC</creation_timestamp> // -------------------------------------------------------------------------------------------------------------------- namespace nGratis.AI.Kvasir.Client { using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Shapes; using nGratis.AI.Kvasir.Contract; using nGratis.Cop.Olympus.Contract; using nGratis.Cop.Olympus.Wpf; [TemplatePart(Name = "PART_ContentPanel", Type = typeof(Panel))] internal class AwePayingManaCostViewer : Control { public static readonly DependencyProperty PayingManaCostProperty = DependencyProperty.Register( nameof(AwePayingManaCostViewer.PayingManaCost), typeof(DefinedBlob.PayingManaCost), typeof(AwePayingManaCostViewer), new PropertyMetadata(null, AwePayingManaCostViewer.OnPayingManaCostChanged)); private static readonly IEnumerable<Mana> ColorManas = Enum .GetValues(typeof(Mana)) .Cast<Mana>() .Where(mana => mana != Mana.Unknown) .Where(mana => mana != Mana.Colorless) .ToArray(); private readonly IThemeManager _themeManager; private Panel _contentPanel; public AwePayingManaCostViewer() : this(ThemeManager.Instance) { } internal AwePayingManaCostViewer(IThemeManager themeManager) { Guard .Require(themeManager, nameof(themeManager)) .Is.Not.Null(); this._themeManager = themeManager; } public DefinedBlob.PayingManaCost PayingManaCost { get => (DefinedBlob.PayingManaCost)this.GetValue(AwePayingManaCostViewer.PayingManaCostProperty); set => this.SetValue(AwePayingManaCostViewer.PayingManaCostProperty, value); } public override void OnApplyTemplate() { base.OnApplyTemplate(); this._contentPanel = (Panel)this.Template.FindName("PART_ContentPanel", this); this.AddColorlessShape("?"); } private static void OnPayingManaCostChanged(DependencyObject container, DependencyPropertyChangedEventArgs args) { if (!(container is AwePayingManaCostViewer viewer)) { return; } viewer._contentPanel.Children.Clear(); if (!(args.NewValue is DefinedBlob.PayingManaCost payingManaCost)) { viewer.AddColorlessShape("?"); return; } viewer.AddColorlessShape(payingManaCost[Mana.Colorless].ToString()); AwePayingManaCostViewer .ColorManas .Select(mana => new { Mana = mana, Amount = payingManaCost[mana] }) .Where(anon => anon.Amount > 0) .ForEach(anon => viewer.AddColorShapes(anon.Mana, anon.Amount)); } private void AddColorlessShape(string value) { var primaryBrush = this._themeManager.FindBrush("Cop.Brush.Shade1"); var secondaryBrush = this._themeManager.FindBrush("Cop.Brush.Shade6"); var shape = new Grid { Children = { new Ellipse { Width = 16, Height = 16, Fill = secondaryBrush, Stroke = secondaryBrush }, new TextBlock { Text = !string.IsNullOrEmpty(value) ? value : "?", Foreground = primaryBrush, FontSize = 12, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center } }, Margin = new Thickness(0, 0, 2, 0) }; this._contentPanel.Children.Add(shape); } private void AddColorShapes(Mana mana, ushort count) { Guard .Require(mana, nameof(mana)) .Is.Not.Default(); var primaryBrush = this._themeManager.FindBrush($"AI.Brush.Mana.{mana}.Primary"); var secondaryBrush = this._themeManager.FindBrush($"AI.Brush.Mana.{mana}.Secondary"); Enumerable .Range(0, count) .Select(_ => new Ellipse { Width = 16, Height = 16, Fill = primaryBrush, Stroke = secondaryBrush, StrokeThickness = 1, Margin = new Thickness(0, 0, 2, 0) }) .ForEach(shape => this._contentPanel.Children.Add(shape)); } } }
37.531792
120
0.561066
[ "MIT" ]
cahyaong/ai.kvasir
Source/Kvasir.Client/Controls/AweManaCostViewer.cs
6,495
C#
using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using YUTPLAT.Services.Interface; using YUTPLAT.ViewModel; namespace YUTPLAT.Validadores { public class ValidarIndicador : ValidationAttribute { public ValidarIndicador() { } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { IndicadorViewModel indicadorViewModel = (IndicadorViewModel)value; if ((indicadorViewModel != null && indicadorViewModel.MetaAceptableViewModel != null) || indicadorViewModel.Id > 0) { IMedicionService medicionService = DependencyResolver.Current.GetService<IMedicionService>(); EscalaGraficosViewModel escalas = medicionService.ObtenerEscalasGrafico(indicadorViewModel); decimal[] escalaValores = escalas.EscalaValores; if (escalaValores[0] <= escalaValores[1] && escalaValores[1] <= escalaValores[2] && escalaValores[2] <= escalaValores[3] && escalaValores[3] <= escalaValores[4] && escalaValores[4] <= escalaValores[5]) { return null; } else { return new ValidationResult("Verifique que los rangos de las metas sean correctos."); } } else { return null; } } } }
34
127
0.575163
[ "MIT" ]
ballesta1234/Y-U-T-P-L-A-T
YUTPLAT/Validadores/ValidarIndicador.cs
1,532
C#
using System; using System.Linq; using System.Reflection; using McMorph.Tools; using McMorph.Files; namespace McMorph.Recipes { public class RecipeParser { public static Recipe Parse(PathName filepath) { var lines = new Lines(filepath.ReadAllLines()); var recipe = new Recipe(); Action<string> setter = (_) => {}; Action<Tag> context = RootContext; void RootContext(Tag tag) { switch (tag.ToString().ToLowerInvariant()) { case "title": setter = value => recipe.Title = value; break; case "description": setter = value => recipe.Description.Add(value); break; case "home": setter = value => recipe.Home.Add(value); break; case "name": setter = value => recipe.Name = value; break; case "version": setter = value => recipe.Version = value; break; case "upstream": setter = value => { if (recipe.Upstream != null) { throw new ArgumentException("already set", nameof(recipe.Upstream)); } recipe.Upstream = value; }; break; case "assets": setter = value => recipe.Assets.Add(value); break; case "deps": { setter = value => recipe.Deps.AddRange(value.Split(' ', StringSplitOptions.RemoveEmptyEntries)); break; } case "class": { setter = value => { var options = string.Join(", ", value.Split(' ', '|').Where(s => !string.IsNullOrWhiteSpace(s))); var add = (RecipeClass)Enum.Parse(typeof(RecipeClass), options, true); recipe.Class = recipe.Class | add; }; break; } case "build.bash": { recipe.Build = new BuildBash(); context = BuildBashContext; break; } default: Errors.Throw($"{filepath}({tag.LineNo}): unknown tag [{tag}]"); break; } } void BuildBashContext (Tag tag) { var text = tag.ToString().ToLowerInvariant(); switch (text) { case ".settings": setter = value => recipe.Build.Settings.Add(value); break; case ".configure": setter = value => recipe.Build.Configure.Add(value); break; case ".make": setter = value => recipe.Build.Make.Add(value); break; case ".install": setter = value => recipe.Build.Make.Add(value); break; default: if (text.StartsWith(".")) { Errors.Throw($"{filepath}({tag.LineNo}): unknown tag [{tag}]"); } context = RootContext; RootContext(tag); break; } } foreach (var token in lines) { if (token is Tag tag) { context(tag); } else if (token is Value val) { setter(val.Text); } else { var err = (ErrTok)token; Errors.Throw($"{filepath}({token.LineNo}): {err.Message}"); } } recipe.Upstream = recipe.Upstream.Replace("@[Name]", recipe.Name).Replace("@[Version]", recipe.Version); return recipe; } } }
35.398496
125
0.359176
[ "MIT" ]
knutjelitto/McMorph
McMorph.Morph/Recipes/Parsing/RecipeParser.cs
4,708
C#
using System; namespace Lenoard.AspNetCore.Identity.UnitTests { /// <summary> /// Entity type for a user's token /// </summary> public class TestUserToken : TestUserToken<string> { } /// <summary> /// Entity type for a user's token /// </summary> /// <typeparam name="TKey"></typeparam> public class TestUserToken<TKey> where TKey : IEquatable<TKey> { /// <summary> /// The login provider for the login (i.e. facebook, google) /// </summary> public virtual string LoginProvider { get; set; } /// <summary> /// Key representing the login for the provider /// </summary> public virtual string TokenName { get; set; } /// <summary> /// Display name for the login /// </summary> public virtual string TokenValue { get; set; } /// <summary> /// User Id for the user who owns this login /// </summary> public virtual TKey UserId { get; set; } } }
28.945946
73
0.537815
[ "MIT" ]
edwardmeng/Lenoard.AspNetCore
test/Model/TestUserToken.cs
1,073
C#
using Microsoft.Extensions.FileProviders; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace XWidget.SwaggerUI { internal class ManifestResourceFileInfo : IFileInfo { public Stream Stream { get; set; } public bool Exists => true; public long Length => Stream.Length; public string PhysicalPath => null; public string Name { get; set; } public DateTimeOffset LastModified => DateTimeOffset.UtcNow; public bool IsDirectory => false; public Stream CreateReadStream() { Stream.Seek(0, SeekOrigin.Begin); return Stream; } } }
24.142857
68
0.653846
[ "MIT" ]
XuPeiYao/XWidget.SwaggerUI
XWidget.SwaggerUI/ManifestResourceFileInfo.cs
678
C#
using HarmonyLib; using Multiplayer.Common; using RimWorld; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using Verse; namespace Multiplayer.Client { [HarmonyPatch(typeof(Designator))] [HarmonyPatch(nameof(Designator.Finalize))] [HarmonyPatch(new[] { typeof(bool) })] public static class DesignatorFinalizePatch { static bool Prefix(bool somethingSucceeded) { if (Multiplayer.Client == null) return true; return !somethingSucceeded || Multiplayer.ExecutingCmds; } } public static class DesignatorPatches { public static bool DesignateSingleCell(Designator __instance, IntVec3 __0) { if (!Multiplayer.ShouldSync) return true; Designator designator = __instance; Map map = Find.CurrentMap; LoggingByteWriter writer = new LoggingByteWriter(); writer.LogNode("Designate single cell: " + designator.GetType()); WriteData(writer, DesignatorMode.SingleCell, designator); Sync.WriteSync(writer, __0); Multiplayer.Client.SendCommand(CommandType.Designator, map.uniqueID, writer.ToArray()); Multiplayer.PacketLog.nodes.Add(writer.current); return false; } public static bool DesignateMultiCell(Designator __instance, IEnumerable<IntVec3> __0) { if (!Multiplayer.ShouldSync) return true; // No cells implies Finalize(false), which currently doesn't cause side effects if (__0.Count() == 0) return true; Designator designator = __instance; Map map = Find.CurrentMap; LoggingByteWriter writer = new LoggingByteWriter(); writer.LogNode("Designate multi cell: " + designator.GetType()); IntVec3[] cellArray = __0.ToArray(); WriteData(writer, DesignatorMode.MultiCell, designator); Sync.WriteSync(writer, cellArray); Multiplayer.Client.SendCommand(CommandType.Designator, map.uniqueID, writer.ToArray()); Multiplayer.PacketLog.nodes.Add(writer.current); return false; } public static bool DesignateThing(Designator __instance, Thing __0) { if (!Multiplayer.ShouldSync) return true; Designator designator = __instance; Map map = Find.CurrentMap; LoggingByteWriter writer = new LoggingByteWriter(); writer.LogNode("Designate thing: " + __0 + " " + designator.GetType()); WriteData(writer, DesignatorMode.Thing, designator); Sync.WriteSync(writer, __0); Multiplayer.Client.SendCommand(CommandType.Designator, map.uniqueID, writer.ToArray()); Multiplayer.PacketLog.nodes.Add(writer.current); MoteMaker.ThrowMetaPuffs(__0); return false; } // DesignateFinalizer ignores unimplemented Designate* methods public static Exception DesignateFinalizer(Exception __exception) { if (__exception is NotImplementedException) { return null; } return __exception; } private static void WriteData(ByteWriter data, DesignatorMode mode, Designator designator) { Sync.WriteSync(data, mode); Sync.WriteSyncObject(data, designator, designator.GetType()); // These affect the Global context and shouldn't be SyncWorkers // Read at MapAsyncTimeComp.SetDesignatorState if (designator is Designator_AreaAllowed) Sync.WriteSync(data, Designator_AreaAllowed.SelectedArea); if (designator is Designator_Install install) Sync.WriteSync(data, install.MiniToInstallOrBuildingToReinstall); if (designator is Designator_Zone) Sync.WriteSync(data, Find.Selector.SelectedZone); } } [HarmonyPatch(typeof(Designator_Install))] [HarmonyPatch(nameof(Designator_Install.MiniToInstallOrBuildingToReinstall), MethodType.Getter)] public static class DesignatorInstallPatch { public static Thing thingToInstall; static void Postfix(ref Thing __result) { if (thingToInstall != null) __result = thingToInstall; } } }
33.421053
100
0.64162
[ "MIT" ]
Cameron-Friel/Multiplayer
Source/Client/Designators.cs
4,447
C#
using PKISharp.WACS.Plugins.Base.Options; using PKISharp.WACS.Plugins.Interfaces; using PKISharp.WACS.Services; using System; using System.Threading.Tasks; namespace PKISharp.WACS.Plugins.Base.Factories.Null { /// <summary> /// Null implementation /// </summary> internal class NullTargetFactory : ITargetPluginOptionsFactory, INull { Type IPluginOptionsFactory.InstanceType => typeof(object); Type IPluginOptionsFactory.OptionsType => typeof(object); (bool, string?) IPluginOptionsFactory.Disabled => (false, null); bool IPluginOptionsFactory.Match(string name) => false; Task<TargetPluginOptions?> IPluginOptionsFactory<TargetPluginOptions>.Aquire(IInputService inputService, RunLevel runLevel) => Task.FromResult<TargetPluginOptions?>(default); Task<TargetPluginOptions?> IPluginOptionsFactory<TargetPluginOptions>.Default() => Task.FromResult<TargetPluginOptions?>(default); string IPluginOptionsFactory.Name => "None"; string? IPluginOptionsFactory.Description => null; int IPluginOptionsFactory.Order => int.MaxValue; } }
45.04
182
0.742451
[ "Apache-2.0" ]
AbstractionsAs/win-acme
src/main.lib/Plugins/Base/OptionsFactories/Null/NullTargetOptionsFactory.cs
1,128
C#
namespace DecTest { using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; [TestFixture] public class Recorder : Base { public class PrimitivesRecordable : Dec.IRecordable { public int intValue; public float floatValue; public bool boolValue; public string stringValue; public Type typeValue; public void Record(Dec.Recorder record) { record.Record(ref intValue, "intValue"); record.Record(ref floatValue, "floatValue"); record.Record(ref boolValue, "boolValue"); record.Record(ref stringValue, "stringValue"); record.Record(ref typeValue, "typeValue"); } } [Test] public void Primitives([Values] RecorderMode mode) { Dec.Config.TestParameters = new Dec.Config.UnitTestParameters { }; var parser = new Dec.Parser(); parser.Finish(); var primitives = new PrimitivesRecordable(); primitives.intValue = 42; primitives.floatValue = 0.1234f; primitives.boolValue = true; primitives.stringValue = "<This is a test string value with some XML-sensitive characters.>"; primitives.typeValue = typeof(Dec.Dec); var deserialized = DoRecorderRoundTrip(primitives, mode); Assert.AreEqual(primitives.intValue, deserialized.intValue); Assert.AreEqual(primitives.floatValue, deserialized.floatValue); Assert.AreEqual(primitives.boolValue, deserialized.boolValue); Assert.AreEqual(primitives.stringValue, deserialized.stringValue); Assert.AreEqual(primitives.typeValue, typeof(Dec.Dec)); } public class EnumRecordable : Dec.IRecordable { public enum Enum { Alpha, Beta, Gamma, } public Enum alph; public Enum bet; public Enum gam; public void Record(Dec.Recorder record) { record.Record(ref alph, "alph"); record.Record(ref bet, "bet"); record.Record(ref gam, "gam"); } } [Test] public void Enum([Values] RecorderMode mode) { Dec.Config.TestParameters = new Dec.Config.UnitTestParameters { }; var parser = new Dec.Parser(); parser.Finish(); var enums = new EnumRecordable(); enums.alph = EnumRecordable.Enum.Alpha; enums.bet = EnumRecordable.Enum.Beta; enums.gam = EnumRecordable.Enum.Gamma; var deserialized = DoRecorderRoundTrip(enums, mode, testSerializedResult: serialized => { Assert.IsTrue(serialized.Contains("Alpha")); Assert.IsTrue(serialized.Contains("Beta")); Assert.IsTrue(serialized.Contains("Gamma")); Assert.IsFalse(serialized.Contains("__value")); }); Assert.AreEqual(enums.alph, deserialized.alph); Assert.AreEqual(enums.bet, deserialized.bet); Assert.AreEqual(enums.gam, deserialized.gam); } [Test] public void Parserless([Values] RecorderMode mode) { var primitives = new PrimitivesRecordable(); primitives.intValue = 42; primitives.floatValue = 0.1234f; primitives.boolValue = true; primitives.stringValue = "<This is a test string value with some XML-sensitive characters.>"; primitives.typeValue = typeof(Dec.Dec); var deserialized = DoRecorderRoundTrip(primitives, mode); Assert.AreEqual(primitives.intValue, deserialized.intValue); Assert.AreEqual(primitives.floatValue, deserialized.floatValue); Assert.AreEqual(primitives.boolValue, deserialized.boolValue); Assert.AreEqual(primitives.stringValue, deserialized.stringValue); Assert.AreEqual(primitives.typeValue, typeof(Dec.Dec)); } [Dec.StaticReferences] public static class StaticReferenceDecs { static StaticReferenceDecs() { Dec.StaticReferencesAttribute.Initialized(); } public static StubDec TestDecA; public static StubDec TestDecB; } public class DecRecordable : Dec.IRecordable { public StubDec a; public StubDec b; public StubDec empty; public StubDec forceEmpty = StaticReferenceDecs.TestDecA; public void Record(Dec.Recorder record) { record.Record(ref a, "a"); record.Record(ref b, "b"); record.Record(ref empty, "empty"); record.Record(ref forceEmpty, "forceEmpty"); } } [Test] public void Decs([Values] RecorderMode mode) { Dec.Config.TestParameters = new Dec.Config.UnitTestParameters { explicitTypes = new Type[] { typeof(StubDec) }, explicitStaticRefs = new Type[] { typeof(StaticReferenceDecs) } }; var parser = new Dec.Parser(); parser.AddString(@" <Decs> <StubDec decName=""TestDecA"" /> <StubDec decName=""TestDecB"" /> </Decs>"); parser.Finish(); var decs = new DecRecordable(); decs.a = StaticReferenceDecs.TestDecA; decs.b = StaticReferenceDecs.TestDecB; // leave empty empty, of course decs.forceEmpty = null; var deserialized = DoRecorderRoundTrip(decs, mode); Assert.AreEqual(decs.a, deserialized.a); Assert.AreEqual(decs.b, deserialized.b); Assert.AreEqual(decs.empty, deserialized.empty); Assert.AreEqual(decs.forceEmpty, deserialized.forceEmpty); } [Test] public void DecsRemoved([ValuesExcept(RecorderMode.Validation)] RecorderMode mode) { Dec.Config.TestParameters = new Dec.Config.UnitTestParameters { explicitTypes = new Type[] { typeof(StubDec) }, explicitStaticRefs = new Type[] { typeof(StaticReferenceDecs) } }; var parser = new Dec.Parser(); parser.AddString(@" <Decs> <StubDec decName=""TestDecA"" /> <StubDec decName=""TestDecB"" /> </Decs>"); parser.Finish(); var decs = new DecRecordable(); decs.a = StaticReferenceDecs.TestDecA; decs.b = StaticReferenceDecs.TestDecB; Dec.Database.Delete(StaticReferenceDecs.TestDecA); var deserialized = DoRecorderRoundTrip(decs, mode, expectWriteErrors: true, expectReadErrors: true); Assert.IsNull(deserialized.a); Assert.AreEqual(decs.b, deserialized.b); } public class ContainersRecordable : Dec.IRecordable { public List<int> intList = new List<int>(); public Dictionary<string, string> stringDict = new Dictionary<string, string>(); public int[] intArray; public void Record(Dec.Recorder record) { record.Record(ref intList, "intList"); record.Record(ref stringDict, "stringDict"); record.Record(ref intArray, "intArray"); } } [Test] public void Containers([Values] RecorderMode mode) { Dec.Config.TestParameters = new Dec.Config.UnitTestParameters { }; var parser = new Dec.Parser(); parser.Finish(); var containers = new ContainersRecordable(); containers.intList.Add(42); containers.intList.Add(1234); containers.intList.Add(-105); containers.stringDict["Key"] = "Value"; containers.stringDict["Info"] = "Data"; containers.intArray = new int[] { 10, 11, 12, 13, 15, 16, 18, 20, 22, 24, 27, 30, 33, 36, 39, 43, 47, 51, 56, 62, 68, 75, 82, 91 }; var deserialized = DoRecorderRoundTrip(containers, mode); Assert.AreEqual(containers.intList, deserialized.intList); Assert.AreEqual(containers.stringDict, deserialized.stringDict); Assert.AreEqual(containers.intArray, deserialized.intArray); } public class ContainersNestedRecordable : Dec.IRecordable { public List<List<int>> intLL = new List<List<int>>(); public void Record(Dec.Recorder record) { record.Record(ref intLL, "intLL"); } } [Test] public void ContainersNested([Values] RecorderMode mode) { Dec.Config.TestParameters = new Dec.Config.UnitTestParameters { }; var parser = new Dec.Parser(); parser.Finish(); var nested = new ContainersNestedRecordable(); nested.intLL.Add(new List<int>()); nested.intLL.Add(null); nested.intLL.Add(new List<int>()); nested.intLL.Add(new List<int>()); nested.intLL[0].Add(42); nested.intLL[0].Add(95); nested.intLL[2].Add(203); var deserialized = DoRecorderRoundTrip(nested, mode); Assert.AreEqual(nested.intLL, deserialized.intLL); } public class Unparseable { } public class MisparseRecordable : Dec.IRecordable { // amusingly, if this is "null", it works fine, because it just says "well it's null I'll mark as a null, done" // I'm not sure I want to guarantee that behavior but I'm also not gonna make it an error, at least for now public Unparseable unparseable = new Unparseable(); public void Record(Dec.Recorder record) { record.Record(ref unparseable, "unparseable"); } } [Test] public void Misparse([ValuesExcept(RecorderMode.Validation)] RecorderMode mode) { Dec.Config.TestParameters = new Dec.Config.UnitTestParameters { }; var parser = new Dec.Parser(); parser.Finish(); var misparse = new MisparseRecordable(); var deserialized = DoRecorderRoundTrip(misparse, mode, expectWriteErrors: true, expectReadErrors: true); Assert.IsNotNull(deserialized); // should just leave this alone Assert.IsNotNull(deserialized.unparseable); } public class RecursiveSquaredRecorder : Dec.IRecordable { public RecursiveSquaredRecorder left; public RecursiveSquaredRecorder right; public void Record(Dec.Recorder record) { record.Record(ref left, "left"); record.Record(ref right, "right"); } } [Test] public void RecursiveSquared([Values] RecorderMode mode) { Dec.Config.TestParameters = new Dec.Config.UnitTestParameters { }; var parser = new Dec.Parser(); parser.Finish(); var root = new RecursiveSquaredRecorder(); var a = new RecursiveSquaredRecorder(); var b = new RecursiveSquaredRecorder(); var c = new RecursiveSquaredRecorder(); root.left = a; root.right = a; a.left = b; a.right = b; b.left = c; b.right = c; c.left = a; c.right = a; var deserialized = DoRecorderRoundTrip(root, mode); Assert.AreSame(deserialized.left, deserialized.right); Assert.AreSame(deserialized.left.left, deserialized.right.right); Assert.AreSame(deserialized.left.left.left, deserialized.right.right.right); Assert.AreSame(deserialized.left.left.left.left, deserialized.right.right.right.right); Assert.AreSame(deserialized.left, deserialized.right.right.right.right); Assert.AreNotSame(deserialized, deserialized.left); Assert.AreNotSame(deserialized, deserialized.left.left); Assert.AreNotSame(deserialized, deserialized.left.left.left); Assert.AreNotSame(deserialized, deserialized.left.left.left.left); Assert.AreNotSame(deserialized.left, deserialized.left.left); Assert.AreNotSame(deserialized.left, deserialized.left.left.left); Assert.AreNotSame(deserialized.left.left, deserialized.left.left.left); } [Test] public void RecursiveSquaredRoot([Values] RecorderMode mode) { Dec.Config.TestParameters = new Dec.Config.UnitTestParameters { }; var parser = new Dec.Parser(); parser.Finish(); var root = new RecursiveSquaredRecorder(); var a = new RecursiveSquaredRecorder(); var b = new RecursiveSquaredRecorder(); var c = new RecursiveSquaredRecorder(); root.left = a; root.right = a; a.left = b; a.right = b; b.left = c; b.right = c; c.left = root; c.right = root; var deserialized = DoRecorderRoundTrip(root, mode); Assert.AreSame(deserialized.left, deserialized.right); Assert.AreSame(deserialized.left.left, deserialized.right.right); Assert.AreSame(deserialized.left.left.left, deserialized.right.right.right); Assert.AreSame(deserialized.left.left.left.left, deserialized.right.right.right.right); Assert.AreSame(deserialized, deserialized.right.right.right.right); Assert.AreNotSame(deserialized, deserialized.left); Assert.AreNotSame(deserialized, deserialized.left.left); Assert.AreNotSame(deserialized, deserialized.left.left.left); Assert.AreNotSame(deserialized.left, deserialized.left.left); Assert.AreNotSame(deserialized.left, deserialized.left.left.left); Assert.AreNotSame(deserialized.left, deserialized.left.left.left.left); Assert.AreNotSame(deserialized.left.left, deserialized.left.left.left); Assert.AreNotSame(deserialized.left.left.left, deserialized.left.left.left.left); Assert.AreNotSame(deserialized.left.left.left, deserialized.left.left.left.left); } [Test] public void RootPrimitive([Values] RecorderMode mode) { Dec.Config.TestParameters = new Dec.Config.UnitTestParameters { }; var parser = new Dec.Parser(); parser.Finish(); int value = 4; // gonna be honest, this feels kind of like overkill var deserialized = DoRecorderRoundTrip(value, mode); Assert.AreEqual(value, deserialized); } public class BaseRecordable : Dec.IRecordable { public int baseVal = 0; public virtual void Record(Dec.Recorder record) { record.Record(ref baseVal, "baseVal"); } } public class DerivedRecordable : BaseRecordable { public int derivedVal = 0; public override void Record(Dec.Recorder record) { base.Record(record); record.Record(ref derivedVal, "derivedVal"); } } public class DerivedBareRecordable : BaseRecordable { } public class RecordableContainer : Dec.IRecordable { public BaseRecordable baseContainer; public void Record(Dec.Recorder record) { record.Record(ref baseContainer, "baseContainer"); } } [Test] public void DerivedRecordables([Values] RecorderMode mode) { Dec.Config.TestParameters = new Dec.Config.UnitTestParameters { }; var parser = new Dec.Parser(); parser.Finish(); var root = new RecordableContainer(); root.baseContainer = new DerivedRecordable(); root.baseContainer.baseVal = 42; (root.baseContainer as DerivedRecordable).derivedVal = 81; var deserialized = DoRecorderRoundTrip(root, mode); Assert.AreEqual(typeof(DerivedRecordable), deserialized.baseContainer.GetType()); Assert.AreEqual(42, deserialized.baseContainer.baseVal); Assert.AreEqual(81, (root.baseContainer as DerivedRecordable).derivedVal); } [Test] public void DerivedBareRecordables([Values] RecorderMode mode) { Dec.Config.TestParameters = new Dec.Config.UnitTestParameters { }; var parser = new Dec.Parser(); parser.Finish(); var root = new RecordableContainer(); root.baseContainer = new DerivedBareRecordable(); root.baseContainer.baseVal = 42; var deserialized = DoRecorderRoundTrip(root, mode); Assert.AreEqual(typeof(DerivedBareRecordable), deserialized.baseContainer.GetType()); Assert.AreEqual(42, deserialized.baseContainer.baseVal); } public class MultiRecordRec : Dec.IRecordable { public int x; public int y; public void Record(Dec.Recorder record) { record.Record(ref x, "x"); record.Record(ref y, "x"); // oops! } } [Test] public void MultiRecord([ValuesExcept(RecorderMode.Validation)] RecorderMode mode) { var mr = new MultiRecordRec(); mr.x = 3; mr.y = 5; var deserialized = DoRecorderRoundTrip(mr, mode, expectWriteErrors: true); Assert.AreEqual(mr.x, deserialized.x); // y's value is left undefined } public class PrimitivesContainer : Dec.IRecordable { public PrimitivesRecordable recordable; public void Record(Dec.Recorder record) { record.Record(ref recordable, "recordable"); } } [Test] public void Pretty([Values(RecorderMode.Bare, RecorderMode.Pretty)] RecorderMode mode) { var item = new StubRecordable(); var output = Dec.Recorder.Write(item, pretty: mode == RecorderMode.Pretty); Assert.AreEqual(mode == RecorderMode.Pretty, output.Contains("\n")); } public class RecordablePrivate : Dec.IRecordable { internal RecordablePrivate() { } public void Record(Dec.Recorder record) { } } [Test] public void Private([Values] RecorderMode mode) { var item = new RecordablePrivate(); var output = DoRecorderRoundTrip(item, mode, expectReadErrors: true); Assert.IsNull(output); } [Test] public void PrivateRef() { // Turn it into null. string serialized = @" <Record> <recordFormatVersion>1</recordFormatVersion> <refs> <Ref id=""ref00000"" class=""DecTest.Recorder.RecordablePrivate"" /> </refs> <data> <recordable ref=""ref00000"" /> </data> </Record>"; StubRecordable deserialized = null; ExpectErrors(() => deserialized = Dec.Recorder.Read<StubRecordable>(serialized)); Assert.IsNotNull(deserialized); } public class RecordableParameter : Dec.IRecordable { public RecordableParameter(int x) { } public void Record(Dec.Recorder record) { } } [Test] public void Parameter([Values] RecorderMode mode) { var item = new RecordableParameter(3); var output = DoRecorderRoundTrip(item, mode, expectReadErrors: true); Assert.IsNull(output); } [Test] public void ParameterRef() { // Turn it into null. string serialized = @" <Record> <recordFormatVersion>1</recordFormatVersion> <refs> <Ref id=""ref00000"" class=""DecTest.Recorder.RecordableParameter"" /> </refs> <data> <recordable ref=""ref00000"" /> </data> </Record>"; StubRecordable deserialized = null; ExpectErrors(() => deserialized = Dec.Recorder.Read<StubRecordable>(serialized)); Assert.IsNotNull(deserialized); } public class IntContainerClass : Dec.IRecordable { public int value; public void Record(Dec.Recorder record) { record.Record(ref value, "value"); } } public struct IntContainerStruct : Dec.IRecordable { public int value; public void Record(Dec.Recorder record) { record.Record(ref value, "value"); } } public class ObjectRefsRecordable : Dec.IRecordable { public object intRef; public object enumRef; public object stringRef; public object typeRef; public object nullRef; public object classRef; public object structRef; public object arrayRef; public object listRef; public object dictRef; public object hashRef; public void Record(Dec.Recorder record) { record.Record(ref intRef, "intRef"); record.Record(ref enumRef, "enumRef"); record.Record(ref stringRef, "stringRef"); record.Record(ref typeRef, "typeRef"); record.Record(ref nullRef, "nullRef"); record.Record(ref classRef, "classRef"); record.Record(ref structRef, "structRef"); record.Record(ref arrayRef, "arrayRef"); record.Record(ref listRef, "listRef"); record.Record(ref dictRef, "dictRef"); record.Record(ref hashRef, "hashRef"); } } [Test] public void ObjectRefs([Values] RecorderMode mode) { var obj = new ObjectRefsRecordable(); obj.intRef = 42; obj.enumRef = GenericEnum.Gamma; obj.stringRef = "Hello, I am a string"; obj.typeRef = typeof(Recorder); obj.nullRef = null; // redundant, obviously obj.classRef = new IntContainerClass() { value = 10 }; obj.structRef = new IntContainerStruct() { value = -10 }; obj.arrayRef = new int[] { 1, 1, 2, 3, 5, 8, 11 }; obj.listRef = new List<int>() { 2, 3, 5, 7, 11, 13, 17 }; obj.dictRef = new Dictionary<int, string>() { { 1, "one" }, { 2, "two" }, { 4, "four" }, { 8, "eight" } }; obj.hashRef = new HashSet<int>() { 1, 6, 21, 107 }; var deserialized = DoRecorderRoundTrip(obj, mode); Assert.AreEqual(obj.intRef, deserialized.intRef); Assert.AreEqual(obj.enumRef, deserialized.enumRef); Assert.AreEqual(obj.stringRef, deserialized.stringRef); Assert.AreEqual(obj.typeRef, deserialized.typeRef); Assert.AreEqual(obj.nullRef, deserialized.nullRef); Assert.AreEqual(obj.classRef.GetType(), deserialized.classRef.GetType()); Assert.AreEqual(((IntContainerClass)obj.classRef).value, ((IntContainerClass)deserialized.classRef).value); Assert.AreEqual(obj.structRef.GetType(), deserialized.structRef.GetType()); Assert.AreEqual(((IntContainerStruct)obj.structRef).value, ((IntContainerStruct)deserialized.structRef).value); Assert.AreEqual(obj.arrayRef, deserialized.arrayRef); Assert.AreEqual(obj.listRef, deserialized.listRef); Assert.AreEqual(obj.dictRef, deserialized.dictRef); Assert.AreEqual(obj.hashRef, deserialized.hashRef); } public class StringEmptyNullRecordable : Dec.IRecordable { public string stringContains; public string stringEmpty; public string stringNull; public void Record(Dec.Recorder record) { record.Record(ref stringContains, "stringContains"); record.Record(ref stringEmpty, "stringEmpty"); record.Record(ref stringNull, "stringNull"); } } [Test] public void StringEmptyNull([Values] RecorderMode mode) { var senr = new StringEmptyNullRecordable(); senr.stringContains = "Contains"; senr.stringEmpty = ""; senr.stringNull = null; var deserialized = DoRecorderRoundTrip(senr, mode); Assert.AreEqual(senr.stringContains, deserialized.stringContains); Assert.AreEqual(senr.stringEmpty, deserialized.stringEmpty); Assert.AreEqual(senr.stringNull, deserialized.stringNull); } public class ListAsThisRecordable : Dec.IRecordable { public List<int> data; public void Record(Dec.Recorder recorder) { recorder.RecordAsThis(ref data); } } [Test] public void AsThis([ValuesExcept(RecorderMode.Validation)] RecorderMode mode) { var lat = new ListAsThisRecordable(); lat.data = new List<int>() { 1, 1, 2, 3, 5, 8, 13, 21 }; var deserialized = DoRecorderRoundTrip(lat, mode); Assert.AreEqual(lat.data, deserialized.data); } public class ListAsThisMultiRecordable : Dec.IRecordable { public List<int> data; public int data2; public void Record(Dec.Recorder recorder) { recorder.RecordAsThis(ref data); recorder.RecordAsThis(ref data2); } } [Test] public void AsThisMulti([ValuesExcept(RecorderMode.Validation)] RecorderMode mode) { var lat = new ListAsThisMultiRecordable(); lat.data = new List<int>() { 1, 1, 2, 3, 5, 8, 13, 21 }; lat.data2 = 19; var deserialized = DoRecorderRoundTrip(lat, mode, expectReadErrors: true, expectWriteErrors: true); Assert.AreEqual(lat.data, deserialized.data); } public class ListAsThisPreRecordable : Dec.IRecordable { public List<int> data; public int data2; public void Record(Dec.Recorder recorder) { recorder.Record(ref data, "data"); recorder.RecordAsThis(ref data2); } } [Test] public void AsThisPre([ValuesExcept(RecorderMode.Validation)] RecorderMode mode) { var lat = new ListAsThisPreRecordable(); lat.data = new List<int>() { 1, 1, 2, 3, 5, 8, 13, 21 }; lat.data2 = 19; var deserialized = DoRecorderRoundTrip(lat, mode, expectReadErrors: true, expectWriteErrors: true); Assert.AreEqual(lat.data, deserialized.data); } public class ListAsThisPostRecordable : Dec.IRecordable { public List<int> data; public int data2; public void Record(Dec.Recorder recorder) { recorder.RecordAsThis(ref data); recorder.Record(ref data2, "data2"); } } [Test] public void AsThisPost([ValuesExcept(RecorderMode.Validation)] RecorderMode mode) { var lat = new ListAsThisPostRecordable(); lat.data = new List<int>() { 1, 1, 2, 3, 5, 8, 13, 21 }; lat.data2 = 19; var deserialized = DoRecorderRoundTrip(lat, mode, expectReadErrors: true, expectWriteErrors: true); Assert.AreEqual(lat.data, deserialized.data); } public class BaseType : Dec.IRecordable { public void Record(Dec.Recorder recorder) { } } public class DerivedType : BaseType { } [Test] public void PolymorphicRoot([Values] RecorderMode mode) { BaseType root = new DerivedType(); var deserialized = DoRecorderRoundTrip(root, mode); Assert.AreEqual(root.GetType(), deserialized.GetType()); } } }
34.131855
190
0.566203
[ "MIT", "Unlicense" ]
zorbathut/dec
test/unit/Recorder.cs
29,251
C#
// Copyright (c) 2020 Yann Crumeyrolle. All rights reserved. // Licensed under the MIT license. See LICENSE in the project root for license information. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if !NETSTANDARD2_0 && !NET461 && !NETCOREAPP2_1 using System.Runtime.Intrinsics; #endif namespace JsonWebToken { /// <summary> /// Provides AES decryption. /// </summary> public abstract class AesDecryptor : IDisposable { /// <summary> /// Try to decrypt the <paramref name="ciphertext"/>. /// </summary> /// <param name="ciphertext">The ciphertext to decrypt.</param> /// <param name="nonce">The nonce used to encrypt.</param> /// <param name="plaintext">The resulting plaintext.</param> /// <param name="bytesWritten">The bytes written in the <paramref name="plaintext"/>.</param> /// <returns></returns> public abstract bool TryDecrypt(ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> nonce, Span<byte> plaintext, out int bytesWritten); /// <inheritdoc /> public abstract void Dispose(); /// <summary> /// Decrypt a <paramref name="ciphertext"/>. /// </summary> /// <param name="ciphertext"></param> /// <param name="plaintext"></param> public abstract void DecryptBlock(ref byte ciphertext, ref byte plaintext); #if !NETSTANDARD2_0 && !NET461 && !NETCOREAPP2_1 /// <summary> /// Gets the padding mask used to validate the padding of the ciphertext. The padding value MUST be between 0 and 16 included. /// </summary> /// <param name="padding"></param> /// <returns></returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] protected static Vector128<byte> GetPaddingMask(byte padding) { ref Vector128<byte> tmp = ref Unsafe.As<byte, Vector128<byte>>(ref MemoryMarshal.GetReference(PaddingMask)); return Unsafe.Add(ref tmp, (IntPtr)padding); } private static ReadOnlySpan<byte> PaddingMask => new byte[17 * 16] { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x02, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x03,0x03, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x04,0x04,0x04, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x05,0x05,0x05,0x05,0x05, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x06,0x06,0x06,0x06,0x06,0x06, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x07,0x07,0x07,0x07,0x07,0x07, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x09,0x09,0x09,0x09,0x09,0x09,0x09,0x09,0x09, 0x00,0x00,0x00,0x00,0x00,0x00,0x0A,0x0A,0x0A,0x0A,0x0A,0x0A,0x0A,0x0A,0x0A,0x0A, 0x00,0x00,0x00,0x00,0x00,0x0B,0x0B,0x0B,0x0B,0x0B,0x0B,0x0B,0x0B,0x0B,0x0B,0x0B, 0x00,0x00,0x00,0x00,0x0C,0x0C,0x0C,0x0C,0x0C,0x0C,0x0C,0x0C,0x0C,0x0C,0x0C,0x0C, 0x00,0x00,0x00,0x0D,0x0D,0x0D,0x0D,0x0D,0x0D,0x0D,0x0D,0x0D,0x0D,0x0D,0x0D,0x0D, 0x00,0x00,0x0E,0x0E,0x0E,0x0E,0x0E,0x0E,0x0E,0x0E,0x0E,0x0E,0x0E,0x0E,0x0E,0x0E, 0x00,0x0F,0x0F,0x0F,0x0F,0x0F,0x0F,0x0F,0x0F,0x0F,0x0F,0x0F,0x0F,0x0F,0x0F,0x0F, 0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10 }; #endif } }
50.648649
141
0.658751
[ "MIT" ]
MortalFlesh/Jwt
src/JsonWebToken/Cryptography/AesDecryptor.cs
3,750
C#
// // (C) Copyright 2003-2019 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // namespace Revit.SDK.Samples.CurtainSystem.CS.UI { partial class CurtainForm { /// <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.createCSButton = new System.Windows.Forms.Button(); this.cgCheckedListBox = new System.Windows.Forms.CheckedListBox(); this.addCGButton = new System.Windows.Forms.Button(); this.cgLabel = new System.Windows.Forms.Label(); this.removeCGButton = new System.Windows.Forms.Button(); this.facesLabel = new System.Windows.Forms.Label(); this.facesCheckedListBox = new System.Windows.Forms.CheckedListBox(); this.exitButton = new System.Windows.Forms.Button(); this.statusStrip = new System.Windows.Forms.StatusStrip(); this.operationStatusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.deleteCSButton = new System.Windows.Forms.Button(); this.csListBox = new System.Windows.Forms.CheckedListBox(); this.mainPanel = new System.Windows.Forms.Panel(); this.csLabel = new System.Windows.Forms.Label(); this.statusStrip.SuspendLayout(); this.mainPanel.SuspendLayout(); this.SuspendLayout(); // // createCSButton // this.createCSButton.Image = global::Revit.SDK.Samples.CurtainSystem.CS.Properties.Resources._new; this.createCSButton.Location = new System.Drawing.Point(16, 192); this.createCSButton.Margin = new System.Windows.Forms.Padding(4); this.createCSButton.Name = "createCSButton"; this.createCSButton.Size = new System.Drawing.Size(32, 30); this.createCSButton.TabIndex = 2; this.createCSButton.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.createCSButton.UseVisualStyleBackColor = true; this.createCSButton.Click += new System.EventHandler(this.createCSButton_Click); // // cgCheckedListBox // this.cgCheckedListBox.CheckOnClick = true; this.cgCheckedListBox.FormattingEnabled = true; this.cgCheckedListBox.Location = new System.Drawing.Point(454, 27); this.cgCheckedListBox.Margin = new System.Windows.Forms.Padding(4, 3, 4, 4); this.cgCheckedListBox.Name = "cgCheckedListBox"; this.cgCheckedListBox.Size = new System.Drawing.Size(144, 157); this.cgCheckedListBox.TabIndex = 7; this.cgCheckedListBox.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.cgCheckedListBox_ItemCheck); // // addCGButton // this.addCGButton.Location = new System.Drawing.Point(348, 67); this.addCGButton.Margin = new System.Windows.Forms.Padding(4); this.addCGButton.Name = "addCGButton"; this.addCGButton.Size = new System.Drawing.Size(98, 32); this.addCGButton.TabIndex = 5; this.addCGButton.Text = "&Add >>"; this.addCGButton.UseVisualStyleBackColor = true; this.addCGButton.Click += new System.EventHandler(this.addCGButton_Click); // // cgLabel // this.cgLabel.AutoSize = true; this.cgLabel.Location = new System.Drawing.Point(451, 7); this.cgLabel.Margin = new System.Windows.Forms.Padding(4, 7, 4, 0); this.cgLabel.Name = "cgLabel"; this.cgLabel.Size = new System.Drawing.Size(95, 17); this.cgLabel.TabIndex = 8; this.cgLabel.Text = "Curtain Grids:"; // // removeCGButton // this.removeCGButton.Location = new System.Drawing.Point(348, 107); this.removeCGButton.Margin = new System.Windows.Forms.Padding(4); this.removeCGButton.Name = "removeCGButton"; this.removeCGButton.Size = new System.Drawing.Size(98, 32); this.removeCGButton.TabIndex = 6; this.removeCGButton.Text = "<< &Remove"; this.removeCGButton.UseVisualStyleBackColor = true; this.removeCGButton.Click += new System.EventHandler(this.removeCGButton_Click); // // facesLabel // this.facesLabel.AutoSize = true; this.facesLabel.Location = new System.Drawing.Point(193, 7); this.facesLabel.Margin = new System.Windows.Forms.Padding(4, 7, 4, 0); this.facesLabel.Name = "facesLabel"; this.facesLabel.Size = new System.Drawing.Size(123, 17); this.facesLabel.TabIndex = 0; this.facesLabel.Text = "Uncovered Faces:"; // // facesCheckedListBox // this.facesCheckedListBox.CheckOnClick = true; this.facesCheckedListBox.FormattingEnabled = true; this.facesCheckedListBox.Location = new System.Drawing.Point(196, 27); this.facesCheckedListBox.Margin = new System.Windows.Forms.Padding(4, 3, 4, 4); this.facesCheckedListBox.Name = "facesCheckedListBox"; this.facesCheckedListBox.Size = new System.Drawing.Size(144, 157); this.facesCheckedListBox.TabIndex = 4; this.facesCheckedListBox.SelectedIndexChanged += new System.EventHandler(this.facesCheckedListBox_SelectedIndexChanged); // // exitButton // this.exitButton.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.exitButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.exitButton.Location = new System.Drawing.Point(510, 241); this.exitButton.Margin = new System.Windows.Forms.Padding(7); this.exitButton.Name = "exitButton"; this.exitButton.Size = new System.Drawing.Size(88, 28); this.exitButton.TabIndex = 8; this.exitButton.Text = "&Close"; this.exitButton.UseVisualStyleBackColor = true; // // statusStrip // this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.operationStatusLabel}); this.statusStrip.Location = new System.Drawing.Point(0, 276); this.statusStrip.Name = "statusStrip"; this.statusStrip.Padding = new System.Windows.Forms.Padding(1, 0, 19, 0); this.statusStrip.Size = new System.Drawing.Size(614, 22); this.statusStrip.SizingGrip = false; this.statusStrip.Stretch = false; this.statusStrip.TabIndex = 12; // // operationStatusLabel // this.operationStatusLabel.Name = "operationStatusLabel"; this.operationStatusLabel.Size = new System.Drawing.Size(0, 17); // // deleteCSButton // this.deleteCSButton.Image = global::Revit.SDK.Samples.CurtainSystem.CS.Properties.Resources.delete; this.deleteCSButton.Location = new System.Drawing.Point(56, 192); this.deleteCSButton.Margin = new System.Windows.Forms.Padding(4); this.deleteCSButton.Name = "deleteCSButton"; this.deleteCSButton.Size = new System.Drawing.Size(32, 30); this.deleteCSButton.TabIndex = 3; this.deleteCSButton.UseVisualStyleBackColor = true; this.deleteCSButton.Click += new System.EventHandler(this.deleteCSButton_Click); // // csListBox // this.csListBox.FormattingEnabled = true; this.csListBox.Location = new System.Drawing.Point(16, 27); this.csListBox.Margin = new System.Windows.Forms.Padding(7, 3, 7, 4); this.csListBox.Name = "csListBox"; this.csListBox.Size = new System.Drawing.Size(169, 157); this.csListBox.TabIndex = 1; this.csListBox.SelectedIndexChanged += new System.EventHandler(this.csListBox_SelectedIndexChanged); // // mainPanel // this.mainPanel.Controls.Add(this.csListBox); this.mainPanel.Controls.Add(this.deleteCSButton); this.mainPanel.Controls.Add(this.statusStrip); this.mainPanel.Controls.Add(this.exitButton); this.mainPanel.Controls.Add(this.facesCheckedListBox); this.mainPanel.Controls.Add(this.facesLabel); this.mainPanel.Controls.Add(this.removeCGButton); this.mainPanel.Controls.Add(this.cgLabel); this.mainPanel.Controls.Add(this.addCGButton); this.mainPanel.Controls.Add(this.csLabel); this.mainPanel.Controls.Add(this.cgCheckedListBox); this.mainPanel.Controls.Add(this.createCSButton); this.mainPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.mainPanel.Location = new System.Drawing.Point(0, 0); this.mainPanel.Margin = new System.Windows.Forms.Padding(4); this.mainPanel.Name = "mainPanel"; this.mainPanel.Size = new System.Drawing.Size(614, 298); this.mainPanel.TabIndex = 0; this.mainPanel.Paint += new System.Windows.Forms.PaintEventHandler(this.mainPanel_Paint); // // csLabel // this.csLabel.AutoSize = true; this.csLabel.Location = new System.Drawing.Point(13, 7); this.csLabel.Margin = new System.Windows.Forms.Padding(4, 7, 4, 0); this.csLabel.Name = "csLabel"; this.csLabel.Size = new System.Drawing.Size(114, 17); this.csLabel.TabIndex = 0; this.csLabel.Text = "Curtain Systems:"; this.csLabel.Click += new System.EventHandler(this.csLabel_Click); // // CurtainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.exitButton; this.ClientSize = new System.Drawing.Size(614, 298); this.Controls.Add(this.mainPanel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Margin = new System.Windows.Forms.Padding(4); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "CurtainForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Curtain System"; this.statusStrip.ResumeLayout(false); this.statusStrip.PerformLayout(); this.mainPanel.ResumeLayout(false); this.mainPanel.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button createCSButton; private System.Windows.Forms.CheckedListBox cgCheckedListBox; private System.Windows.Forms.Button addCGButton; private System.Windows.Forms.Label cgLabel; private System.Windows.Forms.Button removeCGButton; private System.Windows.Forms.Label facesLabel; private System.Windows.Forms.CheckedListBox facesCheckedListBox; private System.Windows.Forms.Button exitButton; private System.Windows.Forms.StatusStrip statusStrip; private System.Windows.Forms.ToolStripStatusLabel operationStatusLabel; private System.Windows.Forms.Button deleteCSButton; private System.Windows.Forms.CheckedListBox csListBox; private System.Windows.Forms.Panel mainPanel; private System.Windows.Forms.Label csLabel; } }
51.0625
133
0.615235
[ "MIT" ]
xin1627/RevitSdkSamples
SDK/Samples/CurtainSystem/CS/UI/CurtainForm.Designer.cs
13,889
C#
// // Unit tests for NSBundle // // Authors: // Sebastien Pouliot <sebastien@xamarin.com> // // Copyright 2012-2013 Xamarin Inc. All rights reserved. // using System; using System.Net; #if XAMCORE_2_0 using Foundation; #if MONOMAC using AppKit; #else using UIKit; #endif using ObjCRuntime; #else using MonoTouch.Foundation; using MonoTouch.ObjCRuntime; using MonoTouch.UIKit; #endif using NUnit.Framework; namespace MonoTouchFixtures.Foundation { [TestFixture] [Preserve (AllMembers = true)] public class BundleTest { NSBundle main = NSBundle.MainBundle; [Test] public void LocalizedString2 () { string s = main.LocalizedString (null, "comment"); Assert.That (s, Is.Empty, "key"); s = main.LocalizedString ("key", null); Assert.That (s, Is.EqualTo ("key"), "comment"); s = main.LocalizedString (null, null); Assert.That (s, Is.Empty, "all-null"); } [Test] public void LocalizedString3 () { string s = main.LocalizedString (null, "value", "table"); Assert.That (s, Is.EqualTo ("value"), "key"); s = NSBundle.MainBundle.LocalizedString ("key", null, "table"); Assert.That (s, Is.EqualTo ("key"), "value"); s = NSBundle.MainBundle.LocalizedString (null, "value", null); Assert.That (s, Is.EqualTo ("value"), "comment"); s = main.LocalizedString (null, null, null); Assert.That (s, Is.Empty, "all-null"); } [Test] public void LocalizedString4 () { string s = main.LocalizedString (null, "value", "table", "comment"); Assert.That (s, Is.EqualTo ("value"), "key"); s = NSBundle.MainBundle.LocalizedString ("key", null, "table", "comment"); Assert.That (s, Is.EqualTo ("key"), "value"); s = NSBundle.MainBundle.LocalizedString ("key", "value", null, "comment"); Assert.That (s, Is.EqualTo ("value"), "table"); s = NSBundle.MainBundle.LocalizedString ("key", "value", "table", null); Assert.That (s, Is.EqualTo ("value"), "comment"); s = main.LocalizedString (null, null, null, null); Assert.That (s, Is.Empty, "all-null"); } // http://developer.apple.com/library/ios/#documentation/uikit/reference/NSBundle_UIKitAdditions/Introduction/Introduction.html #if false // Disabling for now due to Xcode 9 does not support nibs if deployment target == 6.0 #if !__WATCHOS__ [Test] public void LoadNibWithOptions () { #if MONOMAC NSArray objects; Assert.NotNull (main.LoadNibNamed ("EmptyNib", main, out objects)); #else Assert.NotNull (main.LoadNib ("EmptyNib", main, null)); #endif } #endif // !__WATCHOS__ #endif #if false // some selectors are only in AppKit but we included them in MonoTouch (and this match Apple documentation) // https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSBundle_AppKitAdditions/Reference/Reference.html // I guess no one ever used them since they don't work... // commented (selectors removed from MT bindings) - can be re-enabled to test newer iOS releases [Test] [ExpectedException (typeof (MonoTouchException))] public void PathForImageResource () { main.PathForImageResource ("basn3p08.png"); } [Test] [ExpectedException (typeof (MonoTouchException))] public void PathForSoundResource () { main.PathForSoundResource ("basn3p08.png"); } [Test] [ExpectedException (typeof (MonoTouchException))] public void LoadNib () { NSBundle.LoadNib (String.Empty, main); } #endif [Test] public void Localizations () { string [] locz = main.Localizations; Assert.That (locz.Length, Is.GreaterThanOrEqualTo (0), "Length"); } [Test] public void PreferredLocalizations () { string [] locz = main.PreferredLocalizations; Assert.That (locz.Length, Is.GreaterThanOrEqualTo (1), "Length"); Assert.That (locz, Contains.Item ("Base"), "Base"); } [Test] public void AppStoreReceiptURL () { if (!TestRuntime.CheckXcodeVersion (5, 0)) Assert.Inconclusive ("Requires iOS7 or later"); // on iOS8 device this now ends with "/StoreKit/sandboxReceipt" // instead of "/StokeKit/receipt" Assert.That (main.AppStoreReceiptUrl.AbsoluteString, Is.StringEnding ("eceipt"), "AppStoreReceiptUrl"); } #if !XAMCORE_4_0 [Test] public void LocalizedString () { // null values are fine var l2 = main.LocalizedString (null, null); Assert.That (l2.Length, Is.EqualTo (0), "null,null"); var l3 = main.LocalizedString (null, null, null); Assert.That (l3.Length, Is.EqualTo (0), "null,null,null"); var l4 = main.LocalizedString (null, null, null, null); Assert.That (l4.Length, Is.EqualTo (0), "null,null,null,null"); // NoKey does not exists so the same string is returned l2 = main.LocalizedString ("NoKey", null); Assert.That (l2, Is.EqualTo ("NoKey"), "string,null"); l3 = main.LocalizedString ("NoKey", null, null); Assert.That (l3, Is.EqualTo ("NoKey"), "string,null,null"); l4 = main.LocalizedString ("NoKey", null, null, null); Assert.That (l4, Is.EqualTo ("NoKey"), "string,null,null,null"); // TestKey exists (Localizable.strings) and returns TestValue l2 = main.LocalizedString ("TestKey", null); Assert.That (l2, Is.EqualTo ("TestValue"), "string,null-2"); l3 = main.LocalizedString ("TestKey", null, null); Assert.That (l3, Is.EqualTo ("TestValue"), "string,null,null-2"); l4 = main.LocalizedString ("TestKey", null, null, null); Assert.That (l4, Is.EqualTo ("TestValue"), "string,null,null,null-2"); } #endif [Test] public void GetLocalizedString () { // null values are fine using (var l = main.GetLocalizedString (null, null, null)) Assert.That (l.Length, Is.EqualTo (0), "null,null,null"); // NoKey does not exists so the same string is returned using (var l = main.GetLocalizedString ("NoKey", null, null)) Assert.That (l.ToString (), Is.EqualTo ("NoKey"), "string,null,null"); using (var key = new NSString ("NoKey")) using (var l = main.GetLocalizedString (key, null, null)) Assert.That (l.ToString (), Is.EqualTo ("NoKey"), "NString,null,null"); // TestKey exists (Localizable.strings) and returns TestValue using (var l = main.GetLocalizedString ("TestKey", null, null)) Assert.That (l.ToString (), Is.EqualTo ("TestValue"), "string,null,null-2"); using (var key = new NSString ("TestKey")) using (var l = main.GetLocalizedString (key, null, null)) Assert.That (l.ToString (), Is.EqualTo ("TestValue"), "NString,null,null-2"); } } }
31.461165
148
0.67721
[ "BSD-3-Clause" ]
1975781737/xamarin-macios
tests/monotouch-test/Foundation/BundleTest.cs
6,481
C#
/* Dieser Code Anteil wurde geschrieben von: Name: Kamga Vorname : Nicodeme */ 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.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 System.Data.SQLite; namespace Hotel_Management_WPF { /// <summary> /// Interaktionslogik für Report2.xaml /// </summary> public partial class Report2 : Page { public Report2() { InitializeComponent(); } internal void Show() { throw new NotImplementedException(); } string dbConnectionString = @"Data Source =Hotel_DB.db;Version=3;"; private void Button_Click(object sender, RoutedEventArgs e) { SQLiteConnection sqliteCon = new SQLiteConnection(dbConnectionString); try { sqliteCon.Open(); if (datapic1.Text == "" || datapic2.Text == "") //|| textbox3.Text == "" || textbox4.Text == "" || cmb1.Text =="") { MessageBox.Show("Bitte Datum ausfüllen "); } else { //string Query = " SELECT Buchung_nummer fROM Buchen"; //string Query = " SELECT Buchung_nummer, Name , Vorname, Geburtsdatum , type , Preis_zimmer from Buchung,Kunden,Zimmer WHERE Buchung.Kunden_id = Kunden.Kunden_id And Buchung.Zimmer_id = Zimmer.Zimmer_id "; //string Query = " SELECT Buchung_nummer, Name , Vorname, Geburtsdatum , type , Preis_zimmer from Buchung,Kunden,Zimmer WHERE Von between '" +datapicke1.ToString()+ "' AND Bis'" + datapik2.ToString() + "' And Buchung.Kunden_id = Kunden.Kunden_id And Buchung.Zimmer_id = Zimmer.Zimmer_id And Buchung.Zimmer_id = Zimmer.Zimmer_id"; string Query = " SELECT Buchung_nummer,Name , Vorname, Von, Bis, Datum , Preis FROM Buchung ,Kunden WHERE Von between '" + datapic1.ToString() + "'and '" + datapic2.ToString() + "' And Buchung.Kunden_id = Kunden.Kunden_id "; //string Query = "SELECT * FROM Buchung JOIN Kunden , Zimmer ON Buchung.Kunden_id = Kunden.Kunden_id And Buchung.Zimmer_id = Zimmer.Zimmer_id WHERE Buchung_nummer = @Buchungsnummer"; //string Query = " SELECT Buchung_nummer from Buchung"; SQLiteCommand CreateCommand = new SQLiteCommand(Query, sqliteCon); SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(CreateCommand); Zimmer_verwalten ds = new Zimmer_verwalten(); SQLiteDataReader reader; reader = CreateCommand.ExecuteReader(); dataGrid.ItemsSource = reader; //sqliteCon.Close(); //DataTable dt = new DataTable(); //dataAdapter.Fill(dt); //dataGrid.DataSource = dt; } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } }
41.259259
349
0.598145
[ "MIT" ]
iliassh1/hotel-management-system-desktop
Hotel_Management_WPF/Hotel_Management_WPF/Report2.xaml.cs
3,346
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System.Collections.Generic; using System.Globalization; using System.IO; using FluentAssertions; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Writers; using Xunit; namespace Microsoft.OpenApi.Tests.Models { [Collection("DefaultSettings")] public class OpenApiTagTests { public static OpenApiTag BasicTag = new OpenApiTag(); public static OpenApiTag AdvancedTag = new OpenApiTag { Name = "pet", Description = "Pets operations", ExternalDocs = OpenApiExternalDocsTests.AdvanceExDocs, Extensions = new Dictionary<string, IOpenApiExtension> { {"x-tag-extension", new OpenApiNull()} } }; public static OpenApiTag ReferencedTag = new OpenApiTag { Name = "pet", Description = "Pets operations", ExternalDocs = OpenApiExternalDocsTests.AdvanceExDocs, Extensions = new Dictionary<string, IOpenApiExtension> { {"x-tag-extension", new OpenApiNull()} }, Reference = new OpenApiReference { Type = ReferenceType.Tag, Id = "pet" } }; [Fact] public void SerializeBasicTagAsV3JsonWithoutReferenceWorks() { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiJsonWriter(outputStringWriter); var expected = "{ }"; // Act BasicTag.SerializeAsV3WithoutReference(writer); writer.Flush(); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual = actual.MakeLineBreaksEnvironmentNeutral(); expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } [Fact] public void SerializeBasicTagAsV2JsonWithoutReferenceWorks() { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiJsonWriter(outputStringWriter); var expected = "{ }"; // Act BasicTag.SerializeAsV2WithoutReference(writer); writer.Flush(); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual = actual.MakeLineBreaksEnvironmentNeutral(); expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } [Fact] public void SerializeBasicTagAsV3YamlWithoutReferenceWorks() { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiYamlWriter(outputStringWriter); var expected = "{ }"; // Act BasicTag.SerializeAsV3WithoutReference(writer); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual = actual.MakeLineBreaksEnvironmentNeutral(); expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } [Fact] public void SerializeBasicTagAsV2YamlWithoutReferenceWorks() { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiYamlWriter(outputStringWriter); var expected = "{ }"; // Act BasicTag.SerializeAsV2WithoutReference(writer); writer.Flush(); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual = actual.MakeLineBreaksEnvironmentNeutral(); expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } [Fact] public void SerializeAdvancedTagAsV3JsonWithoutReferenceWorks() { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiJsonWriter(outputStringWriter); var expected = @"{ ""name"": ""pet"", ""description"": ""Pets operations"", ""externalDocs"": { ""description"": ""Find more info here"", ""url"": ""https://example.com"" }, ""x-tag-extension"": null }"; // Act AdvancedTag.SerializeAsV3WithoutReference(writer); writer.Flush(); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual = actual.MakeLineBreaksEnvironmentNeutral(); expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } [Fact] public void SerializeAdvancedTagAsV2JsonWithoutReferenceWorks() { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiJsonWriter(outputStringWriter); var expected = @"{ ""name"": ""pet"", ""description"": ""Pets operations"", ""externalDocs"": { ""description"": ""Find more info here"", ""url"": ""https://example.com"" }, ""x-tag-extension"": null }"; // Act AdvancedTag.SerializeAsV2WithoutReference(writer); writer.Flush(); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual = actual.MakeLineBreaksEnvironmentNeutral(); expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } [Fact] public void SerializeAdvancedTagAsV3YamlWithoutReferenceWorks() { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiYamlWriter(outputStringWriter); var expected = @"name: pet description: Pets operations externalDocs: description: Find more info here url: https://example.com x-tag-extension: "; // Act AdvancedTag.SerializeAsV3WithoutReference(writer); writer.Flush(); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual = actual.MakeLineBreaksEnvironmentNeutral(); expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } [Fact] public void SerializeAdvancedTagAsV2YamlWithoutReferenceWorks() { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiYamlWriter(outputStringWriter); var expected = @"name: pet description: Pets operations externalDocs: description: Find more info here url: https://example.com x-tag-extension: "; // Act AdvancedTag.SerializeAsV2WithoutReference(writer); writer.Flush(); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual = actual.MakeLineBreaksEnvironmentNeutral(); expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } [Fact] public void SerializeAdvancedTagAsV3JsonWorks() { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiJsonWriter(outputStringWriter); var expected = @"""pet"""; // Act AdvancedTag.SerializeAsV3(writer); writer.Flush(); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual = actual.MakeLineBreaksEnvironmentNeutral(); expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } [Fact] public void SerializeAdvancedTagAsV2JsonWorks() { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiJsonWriter(outputStringWriter); var expected = @"""pet"""; // Act AdvancedTag.SerializeAsV2(writer); writer.Flush(); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual = actual.MakeLineBreaksEnvironmentNeutral(); expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } [Fact] public void SerializeAdvancedTagAsV3YamlWorks() { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiYamlWriter(outputStringWriter); var expected = @" pet"; // Act AdvancedTag.SerializeAsV3(writer); writer.Flush(); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual = actual.MakeLineBreaksEnvironmentNeutral(); expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } [Fact] public void SerializeAdvancedTagAsV2YamlWorks() { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiYamlWriter(outputStringWriter); var expected = @" pet"; // Act AdvancedTag.SerializeAsV2(writer); writer.Flush(); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual = actual.MakeLineBreaksEnvironmentNeutral(); expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } [Fact] public void SerializeReferencedTagAsV3JsonWorks() { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiJsonWriter(outputStringWriter); var expected = @"""pet"""; // Act ReferencedTag.SerializeAsV3(writer); writer.Flush(); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual = actual.MakeLineBreaksEnvironmentNeutral(); expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } [Fact] public void SerializeReferencedTagAsV2JsonWorks() { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiJsonWriter(outputStringWriter); var expected = @"""pet"""; // Act ReferencedTag.SerializeAsV2(writer); writer.Flush(); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual = actual.MakeLineBreaksEnvironmentNeutral(); expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } [Fact] public void SerializeReferencedTagAsV3YamlWorks() { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiYamlWriter(outputStringWriter); var expected = @" pet"; // Act ReferencedTag.SerializeAsV3(writer); writer.Flush(); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual = actual.MakeLineBreaksEnvironmentNeutral(); expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } [Fact] public void SerializeReferencedTagAsV2YamlWorks() { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); var writer = new OpenApiYamlWriter(outputStringWriter); var expected = @" pet"; // Act ReferencedTag.SerializeAsV2(writer); writer.Flush(); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual = actual.MakeLineBreaksEnvironmentNeutral(); expected = expected.MakeLineBreaksEnvironmentNeutral(); actual.Should().Be(expected); } } }
33.607692
84
0.593729
[ "MIT" ]
CenterEdge/OpenAPI.NET
test/Microsoft.OpenApi.Tests/Models/OpenApiTagTests.cs
13,109
C#
namespace CH3.LawOfDemeter { /// <summary> /// Data connection object /// </summary> public class Connection { /// <summary> /// Opens a connection to the data source. /// </summary> public void Open() { // ... implementation ... } } }
20
50
0.475
[ "MIT" ]
PacktPublishing/Clean-Code-in-C-
CH03/LawOfDemeter/Connection.cs
322
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SuperSocket.Common; using SuperSocket.SocketBase; using SuperSocket.SocketBase.Command; using SuperSocket.SocketBase.Protocol; namespace SuperSocket.QuickStart.CustomProtocol { class MyRequestFilter : RequestFilterBase<BinaryRequestInfo> { private readonly MyDataRequestFilter m_PreparedDataReader = new MyDataRequestFilter(); private MyDataRequestFilter GetMyCommandDataReader(string commandName, int dataLength) { m_PreparedDataReader.Initialize(commandName, dataLength, this); return m_PreparedDataReader; } public override BinaryRequestInfo Filter(IAppSession<BinaryRequestInfo> session, byte[] readBuffer, int offset, int length, bool toBeCopied, out int left) { left = 0; int leftLength = 10 - this.BufferSegments.Count; if (length < leftLength) { AddArraySegment(readBuffer, offset, length, toBeCopied); NextRequestFilter = this; return null; } AddArraySegment(readBuffer, offset, leftLength, toBeCopied); string commandName = BufferSegments.Decode(Encoding.ASCII, 0, 4); int commandDataLength = Convert.ToInt32(BufferSegments.Decode(Encoding.ASCII, 5, 4).TrimStart('0')); if (length > leftLength) { int leftDataLength = length - leftLength; if (leftDataLength >= commandDataLength) { byte[] commandData = readBuffer.CloneRange(offset + leftLength, commandDataLength); BufferSegments.ClearSegements(); NextRequestFilter = this; var requestInfo = new BinaryRequestInfo(commandName, commandData); //The next requestInfo is comming if (leftDataLength > commandDataLength) left = leftDataLength - commandDataLength; return requestInfo; } else// if (leftDataLength < commandDataLength) { //Clear previous cached header data BufferSegments.ClearSegements(); //Save left data part AddArraySegment(readBuffer, offset + leftLength, length - leftLength, toBeCopied); NextRequestFilter = GetMyCommandDataReader(commandName, commandDataLength); return null; } } else { NextRequestFilter = GetMyCommandDataReader(commandName, commandDataLength); return null; } } } }
38.824324
163
0.581622
[ "BSD-3-Clause" ]
3rdandUrban-dev/Nuxleus
src/external/SuperSocket/mainline/QuickStart/CustomProtocol/MyRequestFilter.cs
2,875
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace generic_api_1.Controllers { [Produces("application/json")] [Route("api/[controller]")] [ApiController] public class Controller1 : ControllerBase { // GET api/values [HttpGet("Metodo1")] [ProducesResponseType(201)] [ProducesResponseType(400)] [ProducesResponseType(500)] [ProducesResponseType(200)] public ActionResult<IEnumerable<string>> Get() { return new string[] { "Hola mundo desde Metodo 1." }; } // GET api/values/5 [HttpGet("Metodo2/{id}")] [ProducesResponseType(201)] [ProducesResponseType(400)] [ProducesResponseType(500)] [ProducesResponseType(200)] public ActionResult<string> Get(int id) { return "El ID enviado es: "+id+" y corresponde al Metodo 2."; } } }
26.473684
73
0.61332
[ "MIT" ]
pablodiloreto/api-demos
netcore_2_2/generic_api_1/Controllers/Controller1.cs
1,008
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace GSAKWrapper.UIControls.ActionBuilder { public class ActionIsOwner : ActionImplementationYesNo { public const string STR_NAME = "IsOwner"; public ActionIsOwner() : base(STR_NAME, "IsOwner") { } } }
21.7
58
0.693548
[ "MIT" ]
GlobalcachingEU/GSAKWrapper
GSAKWrapper/UIControls/ActionBuilder/ActionIsOwner.cs
436
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.dcdn.Model.V20180115; namespace Aliyun.Acs.dcdn.Transform.V20180115 { public class DeleteDcdnSpecificStagingConfigResponseUnmarshaller { public static DeleteDcdnSpecificStagingConfigResponse Unmarshall(UnmarshallerContext context) { DeleteDcdnSpecificStagingConfigResponse deleteDcdnSpecificStagingConfigResponse = new DeleteDcdnSpecificStagingConfigResponse(); deleteDcdnSpecificStagingConfigResponse.HttpResponse = context.HttpResponse; deleteDcdnSpecificStagingConfigResponse.RequestId = context.StringValue("DeleteDcdnSpecificStagingConfig.RequestId"); return deleteDcdnSpecificStagingConfigResponse; } } }
39.575
132
0.780796
[ "Apache-2.0" ]
chys0404/aliyun-openapi-net-sdk
aliyun-net-sdk-dcdn/Dcdn/Transform/V20180115/DeleteDcdnSpecificStagingConfigResponseUnmarshaller.cs
1,583
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MatrixOperations")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MatrixOperations")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("731e4efd-507b-4cae-8ee5-e35959a33b77")] // 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")]
37.805556
84
0.745775
[ "MIT" ]
rvats/TWIAlgorithms
MatrixOperations/Properties/AssemblyInfo.cs
1,364
C#
using System.Threading.Tasks; using Nest; using Tests.Framework; namespace Tests.Indices.Monitoring.IndicesSegments { public class SegmentsUrlTests { [U] public async Task Urls() { await UrlTester.GET($"/_segments") .Fluent(c => c.Segments(Nest.Indices.All)) .Request(c => c.Segments(new SegmentsRequest())) .FluentAsync(c => c.SegmentsAsync(Nest.Indices.All)) .RequestAsync(c => c.SegmentsAsync(new SegmentsRequest())) ; var index = "index1,index2"; await UrlTester.GET($"/{index}/_segments") .Fluent(c => c.Segments(index)) .Request(c => c.Segments(new SegmentsRequest(index))) .FluentAsync(c => c.SegmentsAsync(index)) .RequestAsync(c => c.SegmentsAsync(new SegmentsRequest(index))) ; } } }
26.964286
67
0.682119
[ "Apache-2.0" ]
lukapor/NEST
src/Tests/Indices/Monitoring/IndicesSegments/SegmentsUrlTests.cs
757
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using WebGAC.Core; namespace WebGACForVS { public partial class ConfigureWebGAC : Form { private readonly WebGAC.Core.WebGAC mGac; public ConfigureWebGAC(WebGAC.Core.WebGAC pGac) { InitializeComponent(); mGac = pGac; } private void cancelButton_Click(object sender, EventArgs e) { Close(); } private void okButton_Click(object sender, EventArgs e) { mGac.Config.LocalStore = localStoreTextBox.Text; List<string> newRepos = new List<string>(); foreach (string repo in repositoriesListBox.Items) { newRepos.Add(repo); } mGac.Config.Repositories = newRepos.ToArray(); mGac.SaveUserConfig(); Close(); } private void ConfigureWebGAC_Load(object sender, EventArgs e) { this.localStoreTextBox.Text = mGac.Config.LocalStore; // Populate the repositories foreach (AuthenticatedRepository repository in mGac.Config.AllRepositories) { repositoriesListBox.Items.Add(repository.Url); } // Force an update on the controls repositoriesListBox_SelectedIndexChanged(sender, e); } private void removeButton_Click(object sender, EventArgs e) { repositoriesListBox.Items.RemoveAt(repositoriesListBox.SelectedIndex); } private void repositoriesListBox_SelectedIndexChanged(object sender, EventArgs e) { if (repositoriesListBox.SelectedIndex == -1) { // Disable the remove, move up, move down buttons removeButton.Enabled = false; moveUpButton.Enabled = false; moveDownButton.Enabled = false; } else { removeButton.Enabled = true; moveUpButton.Enabled = repositoriesListBox.SelectedIndex != 0; moveDownButton.Enabled = repositoriesListBox.SelectedIndex < repositoriesListBox.Items.Count - 1; } } private void browseLocalStoreButton_Click(object sender, EventArgs e) { browseLocalStoreDialog.SelectedPath = localStoreTextBox.Text; if (browseLocalStoreDialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { localStoreTextBox.Text = browseLocalStoreDialog.SelectedPath; } } private void addButton_Click(object sender, EventArgs e) { AddRepositoryDialog addDialog = new AddRepositoryDialog(mGac); if (addDialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { repositoriesListBox.Items.Add(addDialog.RepositoryUrl); // Force an update on the controls repositoriesListBox_SelectedIndexChanged(sender, e); } } private void moveUpButton_Click(object sender, EventArgs e) { int pos = repositoriesListBox.SelectedIndex; object curItem = repositoriesListBox.Items[pos]; repositoriesListBox.Items.RemoveAt(pos); repositoriesListBox.Items.Insert(pos-1, curItem); repositoriesListBox.SelectedIndex = pos - 1; } private void moveDownButton_Click(object sender, EventArgs e) { int pos = repositoriesListBox.SelectedIndex; object curItem = repositoriesListBox.Items[pos]; repositoriesListBox.Items.RemoveAt(pos); repositoriesListBox.Items.Insert(pos + 1, curItem); repositoriesListBox.SelectedIndex = pos + 1; } } }
33.941748
106
0.688501
[ "Unlicense" ]
paulj/webgac
WebGACForVS/ConfigureWebGAC.cs
3,496
C#
using System; using System.Net.Http; using System.Net.Http.Json; using System.Threading.Tasks; using FluentAssertions; using FluentUtils.MediatR.Pagination; using FluentUtils.MediatR.Samples; using Microsoft.AspNetCore.Mvc.Testing; using Xunit; namespace FluentUtils.MediatR.UnitTests; public class MediatorApiControllerFacts : IClassFixture<WebApplicationFactory<Program>> { private readonly WebApplicationFactory<Program> _factory; public MediatorApiControllerFacts(WebApplicationFactory<Program> factory) { _factory = factory; } [Fact] public async Task GivenOffsetIsZero_WhenGettingWeatherForecasts_ThenReturnCorrectLinks() { // Arrange HttpClient client = _factory.CreateClient(); Links expected = new() { Self = new Uri("/WeatherForecast?Limit=10&Offset=0", UriKind.Relative), Next = new Uri("/WeatherForecast?Limit=10&Offset=10", UriKind.Relative) }; // Act var response = await client.GetFromJsonAsync<PaginatedResponse<WeatherForecast>>("WeatherForecast?offset=0&limit=10"); // Assert response.Should().NotBeNull(); response!.Links.Should().BeEquivalentTo(expected); } [Fact] public async Task GivenOffsetGreaterThanLimit_WhenGettingWeatherForecasts_ThenReturnCorrectLinks() { // Arrange HttpClient client = _factory.CreateClient(); Links expected = new() { Self = new Uri("/WeatherForecast?Limit=10&Offset=10", UriKind.Relative), Next = new Uri("/WeatherForecast?Limit=10&Offset=20", UriKind.Relative), Previous = new Uri("/WeatherForecast?Limit=10&Offset=0", UriKind.Relative) }; // Act var response = await client.GetFromJsonAsync<PaginatedResponse<WeatherForecast>>("WeatherForecast?offset=10&limit=10"); // Assert response.Should().NotBeNull(); response!.Links.Should().BeEquivalentTo(expected); } [Fact] public async Task GivenOffsetGreaterThanTotal_WhenGettingWeatherForecasts_ThenReturnCorrectLinks() { // Arrange HttpClient client = _factory.CreateClient(); Links expected = new() { Self = new Uri("/WeatherForecast?Limit=10&Offset=40", UriKind.Relative), Previous = new Uri("/WeatherForecast?Limit=10&Offset=20", UriKind.Relative) }; // Act var response = await client.GetFromJsonAsync<PaginatedResponse<WeatherForecast>>("WeatherForecast?offset=40&limit=10"); // Assert response.Should().NotBeNull(); response!.Links.Should().BeEquivalentTo(expected); } [Fact] public async Task GivenLimitLessThanZero_WhenGettingWeatherForecasts_ThenLimitShouldBeMinValue() { // Arrange HttpClient client = _factory.CreateClient(); Links expected = new() { Self = new Uri("/WeatherForecast?Limit=10&Offset=0", UriKind.Relative), Next = new Uri("/WeatherForecast?Limit=10&Offset=10", UriKind.Relative) }; // Act var response = await client.GetFromJsonAsync<PaginatedResponse<WeatherForecast>>("WeatherForecast?offset=0&limit=-10"); // Assert response.Should().NotBeNull(); response!.Links.Should().BeEquivalentTo(expected); } [Fact] public async Task GivenLimitGreaterThanOneHundred_WhenGettingWeatherForecasts_ThenLimitShouldBeMaxValue() { // Arrange HttpClient client = _factory.CreateClient(); Links expected = new() { Self = new Uri("/WeatherForecast?Limit=100&Offset=0", UriKind.Relative) }; // Act var response = await client.GetFromJsonAsync<PaginatedResponse<WeatherForecast>>("WeatherForecast?offset=0&limit=200"); // Assert response.Should().NotBeNull(); response!.Links.Should().BeEquivalentTo(expected); } }
35.163793
128
0.648198
[ "MIT" ]
draekien/Draekien.FluentUtils
tests/FluentUtils.MediatR.UnitTests/MediatorApiControllerFacts.cs
4,079
C#
/* * Created on 25-Jan-2006 */ using Lucene.Net.Analysis; using Lucene.Net.Index; using Lucene.Net.Search; using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; namespace Lucene.Net.Queries.Mlt { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// A simple wrapper for <see cref="MoreLikeThis"/> for use in scenarios where a <see cref="Query"/> object is required eg /// in custom QueryParser extensions. At query.Rewrite() time the reader is used to construct the /// actual <see cref="MoreLikeThis"/> object and obtain the real <see cref="Query"/> object. /// </summary> public class MoreLikeThisQuery : Query { private string likeText; private string[] moreLikeFields; private Analyzer analyzer; private readonly string fieldName; private float percentTermsToMatch = 0.3f; private int minTermFrequency = 1; private int maxQueryTerms = 5; private ISet<string> stopWords = null; private int minDocFreq = -1; /// <param name="moreLikeFields"> fields used for similarity measure </param> public MoreLikeThisQuery(string likeText, string[] moreLikeFields, Analyzer analyzer, string fieldName) { this.LikeText = likeText; this.MoreLikeFields = moreLikeFields; this.Analyzer = analyzer; this.fieldName = fieldName; } public override Query Rewrite(IndexReader reader) { var mlt = new MoreLikeThis(reader) { FieldNames = moreLikeFields, Analyzer = analyzer, MinTermFreq = minTermFrequency }; if (MinDocFreq >= 0) { mlt.MinDocFreq = minDocFreq; } mlt.MaxQueryTerms = maxQueryTerms; mlt.StopWords = stopWords; var bq = (BooleanQuery)mlt.Like(new StringReader(likeText), fieldName); var clauses = bq.GetClauses(); //make at least half the terms match bq.MinimumNumberShouldMatch = (int)(clauses.Length * percentTermsToMatch); return bq; } /// <summary> /// <see cref="Query.ToString(string)"/> /// </summary> public override string ToString(string field) { return "like:" + LikeText; } public virtual float PercentTermsToMatch { get { return percentTermsToMatch; } set { percentTermsToMatch = value; } } public virtual Analyzer Analyzer { get { return analyzer; } set { analyzer = value; } } public virtual string LikeText { get { return likeText; } set { likeText = value; } } public virtual int MaxQueryTerms { get { return maxQueryTerms; } set { maxQueryTerms = value; } } public virtual int MinTermFrequency { get { return minTermFrequency; } set { minTermFrequency = value; } } [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public virtual string[] MoreLikeFields { get { return moreLikeFields; } set { moreLikeFields = value; } } public virtual ISet<string> StopWords { get { return stopWords; } set { stopWords = value; } } public virtual int MinDocFreq { get { return minDocFreq; } set { minDocFreq = value; } } public override int GetHashCode() { const int prime = 31; int result = base.GetHashCode(); result = prime * result + ((analyzer == null) ? 0 : analyzer.GetHashCode()); result = prime * result + ((fieldName == null) ? 0 : fieldName.GetHashCode()); result = prime * result + ((likeText == null) ? 0 : likeText.GetHashCode()); result = prime * result + maxQueryTerms; result = prime * result + minDocFreq; result = prime * result + minTermFrequency; result = prime * result + Arrays.GetHashCode(moreLikeFields); result = prime * result + Number.SingleToInt32Bits(percentTermsToMatch); // LUCENENET: wrap in Equatable to compare set contents result = prime * result + ((stopWords == null) ? 0 : Equatable.Wrap(stopWords).GetHashCode()); return result; } public override bool Equals(object obj) { if (this == obj) { return true; } if (!base.Equals(obj)) { return false; } if (this.GetType() != obj.GetType()) { return false; } var other = (MoreLikeThisQuery)obj; if (analyzer == null) { if (other.analyzer != null) { return false; } } else if (!analyzer.Equals(other.analyzer)) { return false; } if (fieldName == null) { if (other.fieldName != null) { return false; } } else if (!fieldName.Equals(other.fieldName, StringComparison.Ordinal)) { return false; } if (likeText == null) { if (other.likeText != null) { return false; } } else if (!likeText.Equals(other.likeText, StringComparison.Ordinal)) { return false; } if (maxQueryTerms != other.maxQueryTerms) { return false; } if (minDocFreq != other.minDocFreq) { return false; } if (minTermFrequency != other.minTermFrequency) { return false; } if (!Arrays.Equals(moreLikeFields, other.moreLikeFields)) { return false; } if (Number.SingleToInt32Bits(percentTermsToMatch) != Number.SingleToInt32Bits(other.percentTermsToMatch)) { return false; } if (stopWords == null) { if (other.stopWords != null) { return false; } } // LUCENENET: wrap in Equatable to compare set contents else if (!Equatable.Wrap(stopWords).Equals(other.stopWords)) { return false; } return true; } } }
33.289916
135
0.529976
[ "Apache-2.0" ]
DiogenesPolanco/lucenenet
src/Lucene.Net.Queries/Mlt/MoreLikeThisQuery.cs
7,925
C#
using AzureFromTheTrenches.Commanding.Abstractions; using FunctionMonkey.Tests.Integration.Common.Commands.Model; namespace FunctionMonkey.Tests.Integration.Common.Commands { public class HttpPostCommandWithSecurityProperty : ICommand<SimpleResponse> { [SecurityProperty] public int Value { get; set; } public string Message { get; set; } } }
29.230769
79
0.744737
[ "MIT" ]
AKomyshan/FunctionMonkey
Tests/FunctionMonkey.Tests.Integration.Common/Commands/HttpPostCommandWithSecurityProperty.cs
380
C#
using System; using System.Reflection; namespace LambdicSql.SQLite.MultiplatformCompatibe { static class ReflectionAdapter { internal static bool IsAssignableFromEx(this Type type, Type target) => type.GetTypeInfo().IsAssignableFrom(target.GetTypeInfo()); public static Type[] GetGenericArgumentsEx(this Type type) => type.GenericTypeArguments; } }
26.933333
76
0.707921
[ "MIT" ]
Codeer-Software/LambdicSql.SQLite
Project/LambdicSql.SQLite.PCL/MultiplatformCompatibe/ReflectionAdapter.cs
406
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Ejercicio7 : MonoBehaviour { //7. Realizá un programa que al ingresar por Inspector tres números enteros num1, num2 y num3, muestre el valor del mayor de todos. //En caso de igualdad entre los tres imprimir "Los números son iguales". Test1: num1 = 12, num2 = 4, num3= 7.Resultado esperado: //El mayor número es num1 Test2: num1 = 2, num2 = 65, num3= 8.Resultado esperado: El mayor número es num2. Test3: num1 = 3, num2 = 10, num3= 28. Resultado esperado: //El mayor número es num3 Test4: num1 = 5, num2 = 5, num3= 5. Resultado esperado: Los números son iguales // Start is called before the first frame update public int num1, num2, num3; void Start() { if (num1 > num2 && num1 > num3) { Debug.Log("El numero más grande es el num1" + " (" + num1 + "). "); } if (num2 > num1 && num2 > num3) { Debug.Log("El numero más grande es el num2" + " (" + num2 + "). "); } if (num3 > num1 && num3 > num2) { Debug.Log("El numero más grande es el num3" + " (" + num3 + "). "); } if (num1 == num2 && num2 == num3) { Debug.Log("Los números son iguales"); } } // Update is called once per frame void Update() { } }
33.452381
168
0.572242
[ "MIT" ]
NicoUmansky/GuiaDeProgramacion1
Assets/Scripts/Ejercicio7.cs
1,418
C#
using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; namespace Fungus { [CommandInfo("UI", "Set Interactable", "Set the interactable sate of selectable objects.")] public class SetInteractable : Command { [Tooltip("List of objects to be affected by the command")] public List<GameObject> targetObjects = new List<GameObject>(); [Tooltip("Controls if the selectable UI object be interactable or not")] public BooleanData interactableState = new BooleanData(true); public override void OnEnter() { if (targetObjects.Count == 0) { Continue(); return; } foreach (GameObject targetObject in targetObjects) { foreach (Selectable selectable in targetObject.GetComponents<Selectable>()) { selectable.interactable = interactableState.Value; } } Continue(); } public override string GetSummary() { if (targetObjects.Count == 0) { return "Error: No targetObjects selected"; } else if (targetObjects.Count == 1) { if (targetObjects[0] == null) { return "Error: No targetObjects selected"; } return targetObjects[0].name + " = " + interactableState.Value; } string objectList = ""; foreach (GameObject gameObject in targetObjects) { if (gameObject == null) { continue; } if (objectList == "") { objectList += gameObject.name; } else { objectList += ", " + gameObject.name; } } return objectList + " = " + interactableState.Value; } public override Color GetButtonColor() { return new Color32(180, 250, 250, 255); } public override void OnCommandAdded(Block parentBlock) { targetObjects.Add(null); } public override bool IsReorderableArray(string propertyName) { if (propertyName == "targetObjects") { return true; } return false; } } }
20.333333
79
0.640369
[ "MIT" ]
FeniXb3/In-Progress
Assets/Fungus/UI/Scripts/Commands/SetInteractable.cs
1,954
C#
using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using LiteDB.Engine; using Xunit; using LiteDB.Async; using LiteDB; namespace Tests.LiteDB.Async { public class Transactions_Tests { [Fact] public async Task Transaction_Write_Lock_Timeout() { var data1 = DataGen.Person(1, 100).ToArray(); var data2 = DataGen.Person(101, 200).ToArray(); using (var db = new LiteDatabase("filename=:memory:")) using (var asyncDb = new LiteDatabaseAsync(db, false)) { // small timeout await asyncDb.PragmaAsync(Pragmas.TIMEOUT, 1); var asyncPerson = asyncDb.GetCollection<Person>(); var person = db.GetCollection<Person>(); // init person collection with 100 document await asyncPerson.InsertAsync(data1); var taskASemaphore = new SemaphoreSlim(0, 1); var taskBSemaphore = new SemaphoreSlim(0, 1); // task A will open transaction and will insert +100 documents // but will commit only 2s later var ta = Task.Run(async () => { await asyncDb.BeginTransAsync(); await asyncPerson.InsertAsync(data2); taskBSemaphore.Release(); taskASemaphore.Wait(); var count = await asyncPerson.CountAsync(); count.Should().Be(data1.Length + data2.Length); await asyncDb.CommitAsync(); }); // task B will try delete all documents but will be locked during 1 second var tb = Task.Run(() => { taskBSemaphore.Wait(); db.BeginTrans(); person .Invoking(personCol => personCol.DeleteMany("1 = 1")) .Should() .Throw<LiteException>() .Where(ex => ex.ErrorCode == LiteException.LOCK_TIMEOUT); taskASemaphore.Release(); }); await Task.WhenAll(ta, tb); } } [Fact] public async Task Transaction_Avoid_Dirty_Read() { var data1 = DataGen.Person(1, 100).ToArray(); var data2 = DataGen.Person(101, 200).ToArray(); using (var db = new LiteDatabase(new MemoryStream())) using (var asyncDb = new LiteDatabaseAsync(db, false)) { var asyncPerson = asyncDb.GetCollection<Person>(); var person = db.GetCollection<Person>(); // init person collection with 100 document await asyncPerson.InsertAsync(data1); var taskASemaphore = new SemaphoreSlim(0, 1); var taskBSemaphore = new SemaphoreSlim(0, 1); // task A will open transaction and will insert +100 documents // but will commit only 1s later - this plus +100 document must be visible only inside task A var ta = Task.Run(async () => { await asyncDb.BeginTransAsync(); await asyncPerson.InsertAsync(data2); taskBSemaphore.Release(); await taskASemaphore.WaitAsync(); var count = await asyncPerson.CountAsync(); count.Should().Be(data1.Length + data2.Length); await asyncDb.CommitAsync(); taskBSemaphore.Release(); }); // task B will not open transaction and will wait 250ms before and count collection - // at this time, task A already insert +100 document but here I can't see (are not committed yet) // after task A finish, I can see now all 200 documents var tb = Task.Run(() => { taskBSemaphore.Wait(); var count = person.Count(); // read 100 documents count.Should().Be(data1.Length); taskASemaphore.Release(); taskBSemaphore.Wait(); // read 200 documents count = person.Count(); count.Should().Be(data1.Length + data2.Length); }); await Task.WhenAll(ta, tb); } } [Fact] public async Task Transaction_Read_Version() { var data1 = DataGen.Person(1, 100).ToArray(); var data2 = DataGen.Person(101, 200).ToArray(); using (var db = new LiteDatabase(new MemoryStream())) using (var asyncDb = new LiteDatabaseAsync(db, false)) { var asyncPerson = asyncDb.GetCollection<Person>(); var person = db.GetCollection<Person>(); // init person collection with 100 document await asyncPerson.InsertAsync(data1); var taskASemaphore = new SemaphoreSlim(0, 1); var taskBSemaphore = new SemaphoreSlim(0, 1); // task A will insert more 100 documents but will commit only 1s later var ta = Task.Run(async () => { await asyncDb.BeginTransAsync(); await asyncPerson.InsertAsync(data2); taskBSemaphore.Release(); taskASemaphore.Wait(); await asyncDb.CommitAsync(); taskBSemaphore.Release(); }); // task B will open transaction too and will count 100 original documents only // but now, will wait task A finish - but is in transaction and must see only initial version var tb = Task.Run(() => { db.BeginTrans(); taskBSemaphore.Wait(); var count = person.Count(); // read 100 documents count.Should().Be(data1.Length); taskASemaphore.Release(); taskBSemaphore.Wait(); // keep reading 100 documents because i'm still in same transaction count = person.Count(); count.Should().Be(data1.Length); }); await Task.WhenAll(ta, tb); } } [Fact] public async Task Test_Transaction_States() { var data0 = DataGen.Person(1, 10).ToArray(); var data1 = DataGen.Person(11, 20).ToArray(); using (var db = new LiteDatabaseAsync(new MemoryStream())) { var person = db.GetCollection<Person>(); // first time transaction will be opened (await db.BeginTransAsync()).Should().BeTrue(); // but in second type transaction will be same (await db.BeginTransAsync()).Should().BeFalse(); await person.InsertAsync(data0); // must commit transaction (await db.CommitAsync()).Should().BeTrue(); // no transaction to commit (await db.CommitAsync()).Should().BeFalse(); // no transaction to rollback; (await db.RollbackAsync()).Should().BeFalse(); (await db.BeginTransAsync()).Should().BeTrue(); // no page was changed but ok, let's rollback anyway (await db.RollbackAsync()).Should().BeTrue(); // auto-commit await person.InsertAsync(data1); (await person.CountAsync()).Should().Be(20); } } } }
34.068376
113
0.504014
[ "Apache-2.0" ]
devinSpitz/litedb-async
litedbasynctest/engine/Transaction_Tests.cs
7,972
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Web; namespace LogDataConversionServiceApplication.Logfiles { public class TextLog : ILogFile { private List<Char> Seperators = new List<Char> { '\t' }; public TextLog(string[] log) { this.Data = log; } private string[] Data; public string Parser { get; set; } public List<string[]> GetData() { List<string> DataList = Data.ToList<string>(); DataList.RemoveAt(0); // Remove the headers. List<string[]> ToReturn = new List<string[]>(); foreach(string Line in DataList) { string[] ArrLine = Line.Split(Seperators.ToArray()); ToReturn.Add(ArrLine); } return ToReturn; } public List<string> GetHeaders() { string Headers = Data[0]; return Headers.Split(Seperators.ToArray()).ToList<string>(); // Split the headers by the seperators, and put it to a list } } }
22.023256
124
0.682154
[ "MIT" ]
alex855k/WelfareProject
LogDataConversionServiceApplication/LogDataConversionServiceApplication/Logfiles/TextLog.cs
949
C#
using System; using System.Xml.Serialization; namespace Niue.Alipay.Domain { /// <summary> /// AlipayMarketingVoucherConfirmModel Data Structure. /// </summary> [Serializable] public class AlipayMarketingVoucherConfirmModel : AopObject { /// <summary> /// 用于决定在用户确认领券后是否重定向。可枚举:true表示需要重定向,false表示不需要重定向,不区分大小写 /// </summary> [XmlElement("need_redirect")] public bool NeedRedirect { get; set; } /// <summary> /// 外部业务单号。用作幂等控制。同一个template_id、user_id、out_biz_no返回相同的发券码 /// </summary> [XmlElement("out_biz_no")] public string OutBizNo { get; set; } /// <summary> /// 重定向地址,用于接收支付宝返回的领取码 /// </summary> [XmlElement("redirect_uri")] public string RedirectUri { get; set; } /// <summary> /// 券模板ID /// </summary> [XmlElement("template_id")] public string TemplateId { get; set; } /// <summary> /// 指定用户确认页面的主题名称。目前提供5套主题,分别为:red, blue, yellow, green, orange /// </summary> [XmlElement("theme")] public string Theme { get; set; } /// <summary> /// 支付宝用户ID /// </summary> [XmlElement("user_id")] public string UserId { get; set; } } }
26.612245
71
0.559049
[ "MIT" ]
P79N6A/abp-ant-design-pro-vue
Niue.Alipay/Domain/AlipayMarketingVoucherConfirmModel.cs
1,556
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; namespace RestaurantReviews.DataAccess.Model { public partial class RestaurantReviewsDbContext : DbContext { public RestaurantReviewsDbContext() { } public RestaurantReviewsDbContext(DbContextOptions<RestaurantReviewsDbContext> options) : base(options) { // Database.EnsureCreated(); } public virtual DbSet<Restaurant> Restaurant { get; set; } public virtual DbSet<Review> Review { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Restaurant>(entity => { entity.Property(e => e.Name) .IsRequired() .HasMaxLength(128); }); modelBuilder.Entity<Review>(entity => { entity.HasIndex(e => e.RestaurantId); entity.Property(e => e.ReviewerName) .IsRequired() .HasMaxLength(128); entity.Property(e => e.Text) .IsRequired() .HasMaxLength(2048); entity.HasOne(d => d.Restaurant) .WithMany(p => p.Review) .HasForeignKey(d => d.RestaurantId); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } }
28.851852
95
0.550706
[ "MIT" ]
2002-feb24-net/nick-project1
RestaurantReviews.DataAccess/Model/RestaurantReviewsDbContext.cs
1,560
C#
// <auto-generated/> #pragma warning disable 1591 #pragma warning disable 0414 #pragma warning disable 0649 #pragma warning disable 0169 namespace Authentication.Pages.DepotUI { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #nullable restore #line 1 "C:\Users\HP\Desktop\Wave-Project-Management-Real-Estate\_Imports.razor" using System.Net.Http; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\HP\Desktop\Wave-Project-Management-Real-Estate\_Imports.razor" using Microsoft.AspNetCore.Authorization; #line default #line hidden #nullable disable #nullable restore #line 3 "C:\Users\HP\Desktop\Wave-Project-Management-Real-Estate\_Imports.razor" using Microsoft.AspNetCore.Components.Authorization; #line default #line hidden #nullable disable #nullable restore #line 4 "C:\Users\HP\Desktop\Wave-Project-Management-Real-Estate\_Imports.razor" using Microsoft.AspNetCore.Components.Forms; #line default #line hidden #nullable disable #nullable restore #line 5 "C:\Users\HP\Desktop\Wave-Project-Management-Real-Estate\_Imports.razor" using Microsoft.AspNetCore.Components.Routing; #line default #line hidden #nullable disable #nullable restore #line 6 "C:\Users\HP\Desktop\Wave-Project-Management-Real-Estate\_Imports.razor" using Microsoft.AspNetCore.Components.Web; #line default #line hidden #nullable disable #nullable restore #line 7 "C:\Users\HP\Desktop\Wave-Project-Management-Real-Estate\_Imports.razor" using Microsoft.AspNetCore.Components.Web.Virtualization; #line default #line hidden #nullable disable #nullable restore #line 8 "C:\Users\HP\Desktop\Wave-Project-Management-Real-Estate\_Imports.razor" using Microsoft.JSInterop; #line default #line hidden #nullable disable #nullable restore #line 9 "C:\Users\HP\Desktop\Wave-Project-Management-Real-Estate\_Imports.razor" using Authentication; #line default #line hidden #nullable disable #nullable restore #line 10 "C:\Users\HP\Desktop\Wave-Project-Management-Real-Estate\_Imports.razor" using Authentication.Shared; #line default #line hidden #nullable disable #nullable restore #line 11 "C:\Users\HP\Desktop\Wave-Project-Management-Real-Estate\_Imports.razor" using Blazored.Toast; #line default #line hidden #nullable disable #nullable restore #line 12 "C:\Users\HP\Desktop\Wave-Project-Management-Real-Estate\_Imports.razor" using Blazored.Toast.Services; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\HP\Desktop\Wave-Project-Management-Real-Estate\Pages\DepotUI\DeleteDepot.razor" using Authentication.Data; #line default #line hidden #nullable disable [Microsoft.AspNetCore.Components.RouteAttribute("/DeleteDepot/{CurrentID}")] public partial class DeleteDepot : Microsoft.AspNetCore.Components.ComponentBase { #pragma warning disable 1998 protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) { } #pragma warning restore 1998 #nullable restore #line 42 "C:\Users\HP\Desktop\Wave-Project-Management-Real-Estate\Pages\DepotUI\DeleteDepot.razor" [Parameter] public string CurrentID { get; set; } Depot objDep = new Depot(); protected override async Task OnInitializedAsync() { objDep = await Task.Run(() => objDepService.GetDepotById(Convert.ToInt32(CurrentID))); } protected void DeleteDepInfo() { if (objDepService.DeleteDepot(objDep) == "success") NavigationManager.NavigateTo("ViewDepots"); else NavigationManager.NavigateTo("InvalidOperation"); } void Cancel() { NavigationManager.NavigateTo("ViewDepots"); } #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Components.InjectAttribute] private NavigationManager NavigationManager { get; set; } [global::Microsoft.AspNetCore.Components.InjectAttribute] private DepotService objDepService { get; set; } } } #pragma warning restore 1591
28.557823
123
0.754645
[ "MIT" ]
CatalinCaldararu/Blazor-Real-Estate-Project-Management
obj/Release/net5.0/RazorDeclaration/Pages/DepotUI/DeleteDepot.razor.g.cs
4,198
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("Zoo_Animals_Client")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Zoo_Animals_Client")] [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("3c501e50-1c40-4262-8a20-d88679b692a3")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.888889
84
0.753666
[ "MIT" ]
vetuha/ZooAnimals
Zoo Animals Client/Zoo Animals Client/Properties/AssemblyInfo.cs
1,367
C#
// Instance generated by TankLibHelper.InstanceBuilder // ReSharper disable All namespace TankLib.STU.Types { [STUAttribute(0x29D0D734)] public class STU_29D0D734 : STUUXGeometry { } }
22
54
0.747475
[ "MIT" ]
Mike111177/OWLib
TankLib/STU/Types/STU_29D0D734.cs
198
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace ProtocolGateway.Host.Common { using System; using System.Diagnostics.Contracts; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using DotNetty.Buffers; using DotNetty.Common.Utilities; using DotNetty.Codecs.Mqtt; using DotNetty.Common.Concurrency; using DotNetty.Handlers.Tls; using DotNetty.Transport.Bootstrapping; using DotNetty.Transport.Channels; using DotNetty.Transport.Channels.Sockets; using Microsoft.Azure.Devices.Client; using Microsoft.Azure.Devices.ProtocolGateway; using Microsoft.Azure.Devices.ProtocolGateway.Identity; using Microsoft.Azure.Devices.ProtocolGateway.Instrumentation; using Microsoft.Azure.Devices.ProtocolGateway.IotHubClient; using Microsoft.Azure.Devices.ProtocolGateway.Mqtt; using Microsoft.Azure.Devices.ProtocolGateway.Mqtt.Persistence; using Message = Microsoft.Azure.Devices.ProtocolGateway.Messaging.Message; using Microsoft.Azure.Devices.ProtocolGateway.Http; using DotNetty.Codecs.Http; public class Bootstrapper { const int MqttsPort = 8883; const int ListenBacklogSize = 2000; // connections allowed pending accept const int MaxConcurrentAccepts = 200; // Maximum number of concurrent connections to accept and start TLS handshake with const int DefaultConnectionPoolSize = 400; // IoT Hub default connection pool size static readonly TimeSpan DefaultConnectionIdleTimeout = TimeSpan.FromSeconds(210); // IoT Hub default connection idle timeout readonly TaskCompletionSource closeCompletionSource; readonly ISettingsProvider settingsProvider; readonly Settings settings; readonly ISessionStatePersistenceProvider sessionStateManager; readonly IQos2StatePersistenceProvider qos2StateProvider; readonly IDeviceIdentityProvider authProvider; X509Certificate2 tlsCertificate; IEventLoopGroup parentEventLoopGroup; IEventLoopGroup eventLoopGroup; IChannel serverChannel; readonly IotHubClientSettings iotHubClientSettings; public Bootstrapper(ISettingsProvider settingsProvider, ISessionStatePersistenceProvider sessionStateManager, IQos2StatePersistenceProvider qos2StateProvider) { Contract.Requires(settingsProvider != null); Contract.Requires(sessionStateManager != null); this.closeCompletionSource = new TaskCompletionSource(); this.settingsProvider = settingsProvider; this.settings = new Settings(this.settingsProvider); this.iotHubClientSettings = new IotHubClientSettings(this.settingsProvider); this.sessionStateManager = sessionStateManager; this.qos2StateProvider = qos2StateProvider; this.authProvider = new SasTokenDeviceIdentityProvider(); } public Task CloseCompletion => this.closeCompletionSource.Task; public async Task RunAsync(X509Certificate2 certificate, int threadCount, CancellationToken cancellationToken) { Contract.Requires(certificate != null); Contract.Requires(threadCount > 0); try { BootstrapperEventSource.Log.Info("Starting", null); //PerformanceCounters.ConnectionsEstablishedTotal.RawValue = 0; //PerformanceCounters.ConnectionsCurrent.RawValue = 0; //PerformanceCounters.TotalCommandsReceived.RawValue = 0; //PerformanceCounters.TotalMethodsInvoked.RawValue = 0; this.tlsCertificate = certificate; this.parentEventLoopGroup = new MultithreadEventLoopGroup(1); this.eventLoopGroup = new MultithreadEventLoopGroup(threadCount); ServerBootstrap bootstrap = this.SetupBootstrap(); BootstrapperEventSource.Log.Info($"Initializing TLS endpoint on port {8084} with certificate {this.tlsCertificate.Thumbprint}.", null); this.serverChannel = await bootstrap.BindAsync(IPAddress.Any, 8084); this.serverChannel.CloseCompletion.LinkOutcome(this.closeCompletionSource); cancellationToken.Register(this.CloseAsync); BootstrapperEventSource.Log.Info("Started", null); } catch (Exception ex) { BootstrapperEventSource.Log.Error("Failed to start", ex); this.CloseAsync(); } } async void CloseAsync() { try { BootstrapperEventSource.Log.Info("Stopping", null); if (this.serverChannel != null) { await this.serverChannel.CloseAsync(); } if (this.eventLoopGroup != null) { await this.eventLoopGroup.ShutdownGracefullyAsync(); } BootstrapperEventSource.Log.Info("Stopped", null); } catch (Exception ex) { BootstrapperEventSource.Log.Warning("Failed to stop cleanly", ex); } finally { this.closeCompletionSource.TryComplete(); } } ServerBootstrap SetupBootstrap() { // pull/customize configuration int maxInboundMessageSize = this.settingsProvider.GetIntegerSetting("MaxInboundMessageSize", 256 * 1024); int connectionPoolSize = this.settingsProvider.GetIntegerSetting("IotHubClient.ConnectionPoolSize", DefaultConnectionPoolSize); TimeSpan connectionIdleTimeout = this.settingsProvider.GetTimeSpanSetting("IotHubClient.ConnectionIdleTimeout", DefaultConnectionIdleTimeout); string connectionString = this.iotHubClientSettings.IotHubConnectionString; // setup message processing logic var telemetryProcessing = TopicHandling.CompileParserFromUriTemplates(new[] { "devices/{deviceId}/messages/events" }); var commandProcessing = TopicHandling.CompileFormatterFromUriTemplate("devices/{deviceId}/messages/devicebound"); MessagingBridgeFactoryFunc bridgeFactory = IotHubBridge.PrepareFactory(connectionString, connectionPoolSize, connectionIdleTimeout, this.iotHubClientSettings, bridge => { bridge.RegisterRoute(topic => true, new TelemetrySender(bridge, telemetryProcessing)); // handle all incoming messages with TelemetrySender bridge.RegisterSource(new CommandReceiver(bridge, PooledByteBufferAllocator.Default, commandProcessing)); // handle device command queue bridge.RegisterSource(new MethodHandler("SendMessageToDevice", bridge, (request, dispatcher) => DispatchCommands(bridge.DeviceId, request, dispatcher))); // register }); var acceptLimiter = new AcceptLimiter(MaxConcurrentAccepts); return new ServerBootstrap() .Group(this.parentEventLoopGroup, this.eventLoopGroup) .Option(ChannelOption.SoBacklog, 8192) .Channel<TcpServerSocketChannel>() .ChildHandler(new ActionChannelInitializer<IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; //if (tlsCertificate != null) //{ // pipeline.AddLast(TlsHandler.Server(tlsCertificate)); //} pipeline.AddLast("encoder", new HttpResponseEncoder()); pipeline.AddLast("decoder", new HttpRequestDecoder(4096, 8192, 8192, false)); pipeline.AddLast("handler", new HttpHandler(authProvider, bridgeFactory)); })); //return new ServerBootstrap() // .Group(this.parentEventLoopGroup, this.eventLoopGroup) // .Option(ChannelOption.SoBacklog, ListenBacklogSize) // .Option(ChannelOption.AutoRead, false) // .ChildOption(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default) // .ChildOption(ChannelOption.AutoRead, false) // .Channel<TcpServerSocketChannel>() // .Handler(acceptLimiter) //.ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel => //{ // channel.Pipeline.AddLast( // TlsHandler.Server(this.tlsCertificate), // new AcceptLimiterTlsReleaseHandler(acceptLimiter), // MqttEncoder.Instance, // new MqttDecoder(true, maxInboundMessageSize), // new MqttAdapter( // this.settings, // this.sessionStateManager, // this.authProvider, // this.qos2StateProvider, // bridgeFactory)); //})); } static async Task<MethodResponse> DispatchCommands(string deviceId, MethodRequest request, IMessageDispatcher dispatcher) { PerformanceCounters.TotalMethodsInvoked.Increment(); PerformanceCounters.MethodsInvokedPerSecond.Increment(); try { // deserialize request payload and further process it before sending or // just pass it through to message.Payload using Unpooled.WrappedBuffer(request.Data) var message = new Message { Id = Guid.NewGuid().ToString(), CreatedTimeUtc = DateTime.UtcNow, Address = "devices/" + deviceId + "/messages/commands", Properties = { { "extra", "property" } }, Payload = Unpooled.WrappedBuffer(request.Data) }; var outcome = await dispatcher.SendAsync(message); switch (outcome) { case SendMessageOutcome.Completed: return new MethodResponse(200); case SendMessageOutcome.Rejected: return new MethodResponse(Encoding.UTF8.GetBytes("{\"message\":\"Could not dispatch the call. Device is not subscribed.\"}"), 404); default: return new MethodResponse(Encoding.UTF8.GetBytes("{\"message\":\"Unexpected outcome.\"}"), 500); } } catch (Exception ex) { CommonEventSource.Log.Error("Received malformed method request: " + request.DataAsJson, ex, null, deviceId); return new MethodResponse(Encoding.UTF8.GetBytes($"{{\"message\":\"error sending message: {ex.ToString()}\"}}"), 500); } } } }
49.259912
185
0.630299
[ "MIT" ]
GinterP/azure-iot-protocol-gateway
host/ProtocolGateway.Host.Common/Bootstrapper.cs
11,182
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure.Core.Tests; using Azure.Messaging.EventHubs.Consumer; using Azure.Messaging.EventHubs.Diagnostics; using Azure.Messaging.EventHubs.Primitives; using Azure.Messaging.EventHubs.Tests; using Moq; using NUnit.Framework; namespace Azure.Messaging.EventHubs.Processor.Tests { /// <summary> /// The suite of tests for validating the diagnostics instrumentation /// of the client library. These tests are not constrained to a specific /// class or functional area. /// </summary> /// /// <remarks> /// Every instrumented operation will trigger diagnostics activities as /// long as they are being listened to, making it possible for other /// tests to interfere with these. For this reason, these tests are /// marked as non-parallelizable. /// </remarks> /// [NonParallelizable] public class DiagnosticsTests { /// <summary>The name of the diagnostics source being tested.</summary> private const string DiagnosticSourceName = "Azure.Messaging.EventHubs"; /// <summary> /// Verifies diagnostics functionality of the <see cref="EventProcessorClient.UpdateCheckpointAsync" /> /// method. /// </summary> /// [Test] [Ignore("Unstable test. (Tracked by: #10067)")] public async Task UpdateCheckpointAsyncCreatesScope() { using ClientDiagnosticListener listener = new ClientDiagnosticListener(DiagnosticSourceName); var eventHubName = "SomeName"; var endpoint = new Uri("amqp://some.endpoint.com/path"); Func<EventHubConnection> fakeFactory = () => new MockConnection(endpoint, eventHubName); var context = new MockPartitionContext("partition"); var data = new MockEventData(new byte[0], sequenceNumber: 0, offset: 0); var storageManager = new Mock<StorageManager>(); var eventProcessor = new Mock<EventProcessorClient>(Mock.Of<StorageManager>(), "cg", endpoint.Host, eventHubName, fakeFactory, null, null); // UpdateCheckpointAsync does not invoke the handlers, but we are setting them here in case // this fact changes in the future. eventProcessor.Object.ProcessEventAsync += eventArgs => Task.CompletedTask; eventProcessor.Object.ProcessErrorAsync += eventArgs => Task.CompletedTask; await eventProcessor.Object.UpdateCheckpointAsync(data, context, default); ClientDiagnosticListener.ProducedDiagnosticScope scope = listener.Scopes.Single(); Assert.That(scope.Name, Is.EqualTo(DiagnosticProperty.EventProcessorCheckpointActivityName)); } /// <summary> /// Verifies diagnostics functionality of the <see cref="EventProcessorClient.RunPartitionProcessingAsync" /> /// method. /// </summary> /// [Test] [Ignore("Unstable test. (Tracked by: #10067)")] public async Task RunPartitionProcessingAsyncCreatesScopeForEventProcessing() { string fullyQualifiedNamespace = "namespace"; string eventHubName = "eventHub"; var mockStorage = new MockCheckPointStorage(); var mockConsumer = new Mock<EventHubConsumerClient>("cg", Mock.Of<EventHubConnection>(), default); var mockProcessor = new Mock<EventProcessorClient>(mockStorage, "cg", fullyQualifiedNamespace, eventHubName, Mock.Of<Func<EventHubConnection>>(), default, default) { CallBase = true }; using ClientDiagnosticListener listener = new ClientDiagnosticListener(DiagnosticSourceName); var completionSource = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); var processEventCalls = 0; mockConsumer .Setup(consumer => consumer.ReadEventsFromPartitionAsync( It.IsAny<string>(), It.IsAny<EventPosition>(), It.IsAny<ReadEventOptions>(), It.IsAny<CancellationToken>())) .Returns<string, EventPosition, ReadEventOptions, CancellationToken>((partitionId, position, options, token) => { async IAsyncEnumerable<PartitionEvent> mockPartitionEventEnumerable() { var context = new MockPartitionContext(partitionId); yield return new PartitionEvent(context, new EventData(Array.Empty<byte>()) { Properties = { { DiagnosticProperty.DiagnosticIdAttribute, "id" } } }); yield return new PartitionEvent(context, new EventData(Array.Empty<byte>()) { Properties = { { DiagnosticProperty.DiagnosticIdAttribute, "id2" } } }); while (!completionSource.Task.IsCompleted && !token.IsCancellationRequested) { await Task.Delay(TimeSpan.FromSeconds(1)); yield return new PartitionEvent(); } yield break; }; return mockPartitionEventEnumerable(); }); mockProcessor .Setup(processor => processor.CreateConsumer( It.IsAny<string>(), It.IsAny<EventHubConnection>(), It.IsAny<EventHubConsumerClientOptions>())) .Returns(mockConsumer.Object); mockProcessor.Object.ProcessEventAsync += eventArgs => { if (++processEventCalls == 2) { completionSource.SetResult(null); } return Task.CompletedTask; }; // RunPartitionProcessingAsync does not invoke the error handler, but we are setting it here in case // this fact changes in the future. mockProcessor.Object.ProcessErrorAsync += eventArgs => Task.CompletedTask; // Start processing and wait for the consumer to be invoked. Set a cancellation for backup to ensure // that the test completes deterministically. using var cancellationSource = new CancellationTokenSource(); cancellationSource.CancelAfter(TimeSpan.FromSeconds(15)); using var partitionProcessingTask = Task.Run(() => mockProcessor.Object.RunPartitionProcessingAsync("pid", default, cancellationSource.Token)); await Task.WhenAny(Task.Delay(-1, cancellationSource.Token), completionSource.Task); await Task.WhenAny(Task.Delay(-1, cancellationSource.Token), partitionProcessingTask); // Validate that cancellation did not take place. Assert.That(cancellationSource.IsCancellationRequested, Is.False, "The processor should have stopped without cancellation."); // Validate diagnostics functionality. Assert.That(listener.Scopes.Select(s => s.Name), Has.All.EqualTo(DiagnosticProperty.EventProcessorProcessingActivityName)); Assert.That(listener.Scopes.SelectMany(s => s.Links), Has.One.EqualTo("id")); Assert.That(listener.Scopes.SelectMany(s => s.Links), Has.One.EqualTo("id2")); var expectedTags = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>(DiagnosticProperty.KindAttribute, DiagnosticProperty.ConsumerKind), new KeyValuePair<string, string>(DiagnosticProperty.EventHubAttribute, eventHubName), new KeyValuePair<string, string>(DiagnosticProperty.EndpointAttribute, fullyQualifiedNamespace) }; foreach (var scope in listener.Scopes) { Assert.That(expectedTags, Is.SubsetOf(scope.Activity.Tags.ToList())); } } /// <summary> /// Verifies diagnostics functionality of the <see cref="EventProcessorClient.RunPartitionProcessingAsync" /> /// method. /// </summary> /// [Test] public async Task RunPartitionProcessingAsyncAddsAttributesToLinkedActivities() { string fullyQualifiedNamespace = "namespace"; string eventHubName = "eventHub"; var mockStorage = new MockCheckPointStorage(); var mockConsumer = new Mock<EventHubConsumerClient>("cg", Mock.Of<EventHubConnection>(), default); var mockProcessor = new Mock<EventProcessorClient>(mockStorage, "cg", fullyQualifiedNamespace, eventHubName, Mock.Of<Func<EventHubConnection>>(), default, default) { CallBase = true }; var enqueuedTime = DateTimeOffset.UtcNow; using ClientDiagnosticListener listener = new ClientDiagnosticListener(DiagnosticSourceName); var completionSource = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); var processEventCalled = false; mockConsumer .Setup(consumer => consumer.ReadEventsFromPartitionAsync( It.IsAny<string>(), It.IsAny<EventPosition>(), It.IsAny<ReadEventOptions>(), It.IsAny<CancellationToken>())) .Returns<string, EventPosition, ReadEventOptions, CancellationToken>((partitionId, position, options, token) => { async IAsyncEnumerable<PartitionEvent> mockPartitionEventEnumerable() { var context = new MockPartitionContext(partitionId); yield return new PartitionEvent(context, new MockEventData(Array.Empty<byte>(), enqueuedTime: enqueuedTime) { Properties = { { DiagnosticProperty.DiagnosticIdAttribute, "id" } } }); while (!completionSource.Task.IsCompleted && !token.IsCancellationRequested) { await Task.Delay(TimeSpan.FromSeconds(1)); yield return new PartitionEvent(); } yield break; }; return mockPartitionEventEnumerable(); }); mockProcessor .Setup(processor => processor.CreateConsumer( It.IsAny<string>(), It.IsAny<EventHubConnection>(), It.IsAny<EventHubConsumerClientOptions>())) .Returns(mockConsumer.Object); mockProcessor.Object.ProcessEventAsync += eventArgs => { if (!processEventCalled) { processEventCalled = true; completionSource.SetResult(null); } return Task.CompletedTask; }; // RunPartitionProcessingAsync does not invoke the error handler, but we are setting it here in case // this fact changes in the future. mockProcessor.Object.ProcessErrorAsync += eventArgs => Task.CompletedTask; // Start processing and wait for the consumer to be invoked. Set a cancellation for backup to ensure // that the test completes deterministically. using var cancellationSource = new CancellationTokenSource(); cancellationSource.CancelAfter(TimeSpan.FromSeconds(15)); using var partitionProcessingTask = Task.Run(() => mockProcessor.Object.RunPartitionProcessingAsync("pid", default, cancellationSource.Token)); await Task.WhenAny(Task.Delay(-1, cancellationSource.Token), completionSource.Task); await Task.WhenAny(Task.Delay(-1, cancellationSource.Token), partitionProcessingTask); // Validate that cancellation did not take place. Assert.That(cancellationSource.IsCancellationRequested, Is.False, "The processor should have stopped without cancellation."); // Validate diagnostics functionality. var processingScope = listener.Scopes.Single(s => s.Name == DiagnosticProperty.EventProcessorProcessingActivityName); var linkedActivity = processingScope.LinkedActivities.Single(a => a.ParentId == "id"); var expectedTags = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>(DiagnosticProperty.EnqueuedTimeAttribute, enqueuedTime.ToUnixTimeSeconds().ToString()) }; Assert.That(linkedActivity.Tags, Is.EquivalentTo(expectedTags)); } private class MockConnection : EventHubConnection { private const string MockConnectionString = "Endpoint=value.com;SharedAccessKeyName=[value];SharedAccessKey=[value];"; public Uri ServiceEndpoint; public MockConnection(Uri serviceEndpoint, string eventHubName) : base(MockConnectionString, eventHubName) { ServiceEndpoint = serviceEndpoint; } } private class MockPartitionContext : PartitionContext { public MockPartitionContext(string partitionId) : base(partitionId) { } } } }
46.881944
205
0.625907
[ "MIT" ]
ctstone/azure-sdk-for-net
sdk/eventhub/Azure.Messaging.EventHubs.Processor/tests/Diagnostics/DiagnosticsTests.cs
13,504
C#
using Newtonsoft.Json; namespace BetfairNG.Data { public class AccountFundsResponse { [JsonProperty(PropertyName = "availableToBetBalance")] public double AvailableToBetBalance { get; set; } [JsonProperty(PropertyName = "discountRate")] public double DiscountRate { get; set; } [JsonProperty(PropertyName = "exposure")] public double Exposure { get; set; } [JsonProperty(PropertyName = "exposureLimit")] public double ExposureLimit { get; set; } [JsonProperty(PropertyName = "pointsBalance")] public double PointsBalance { get; set; } [JsonProperty(PropertyName = "retainedCommission")] public double RetainedCommission { get; set; } } }
30.08
62
0.656915
[ "MIT" ]
k-s-s/betfairng
Data/AccountFundsResponse.cs
754
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _04.Count_Symbols { class Program { static void Main(string[] args) { string text = Console.ReadLine(); SortedDictionary<char, int> result = new SortedDictionary<char, int>(); for (int i = 0; i < text.Length; i++) { char currentSymbol = text[i]; if (!result.ContainsKey(currentSymbol)) { result[currentSymbol] = 0; } result[currentSymbol]++; } foreach (var kvp in result) { Console.WriteLine($"{kvp.Key}: {kvp.Value} time/s"); } } } }
24.294118
83
0.490315
[ "MIT" ]
stoianov00/C-Advanced
C# Advanced/02.Sets and Dictionaries/04.Count Symbols/Count Symbols.cs
828
C#
using System; using System.Collections; using System.Data; using NUnit.Framework; using g = CodeGenerator; namespace CodeGeneratorTest { [TestFixture] public class SqlDatabaseLoaderTest : BaseTest { [Test] public void TestLoadDatabase() { g.Sql.Database db = dbLoader.Database; Assert.AreEqual(4, db.TablesHash.Count); Assert.IsTrue(db.TablesHash.Contains("test_Record1")); Assert.IsTrue(db.TablesHash.Contains("test_Record1Cat")); Assert.IsTrue(db.TablesHash.Contains("test_Record1Record2")); Assert.IsTrue(db.TablesHash.Contains("test_Record2")); } [Test] public void TestPrimaryKeyConstraints() { g.Sql.Database db = dbLoader.Database; g.Sql.Table t = db.GetTable("test_Record1"); g.Sql.PrimaryKeyConstraint pk = t.PrimaryKey; Assert.AreEqual("Id", pk.Field.Name); Assert.IsTrue(pk.IsUnary); Assert.IsNull(pk.Field2); t = db.GetTable("test_Record1Cat"); pk = t.PrimaryKey; Assert.AreEqual("Id", pk.Field.Name); Assert.IsTrue(pk.IsUnary); Assert.IsNull(pk.Field2); t = db.GetTable("test_Record1Record2"); pk = t.PrimaryKey; Assert.AreEqual("Record1Id", pk.Field.Name); Assert.IsFalse(pk.IsUnary); Assert.AreEqual("Record2Id", pk.Field2.Name); t = db.GetTable("test_Record2"); pk = t.PrimaryKey; Assert.AreEqual("Id", pk.Field.Name); Assert.IsTrue(pk.IsUnary); Assert.IsNull(pk.Field2); } [Test] public void TestForeignKeyConstraints() { g.Sql.Database db = dbLoader.Database; g.Sql.Table t = db.GetTable("test_Record1Record2"); Hashtable fkeys = new Hashtable(); foreach (g.Sql.Constraint c in t.Constraints) { g.Sql.ForeignKeyConstraint temp = c as g.Sql.ForeignKeyConstraint; if (temp != null) fkeys.Add(temp.Field.Name, temp); } Assert.AreEqual(2, fkeys.Count); g.Sql.ForeignKeyConstraint fk = (g.Sql.ForeignKeyConstraint)fkeys["Record1Id"]; Assert.AreEqual(fk.Field.Name, "Record1Id"); Assert.AreEqual(fk.RefTableName, "test_Record1"); Assert.AreEqual(fk.RefFieldName, "Id"); fk = (g.Sql.ForeignKeyConstraint)fkeys["Record2Id"]; Assert.AreEqual(fk.Field.Name, "Record2Id"); Assert.AreEqual(fk.RefTableName, "test_Record2"); Assert.AreEqual(fk.RefFieldName, "Id"); } [Test] public void TestUniqueConstraints() { g.Sql.Database db = dbLoader.Database; g.Sql.Table t = db.GetTable("test_Record1"); g.Sql.UniqueConstraint uq = null; foreach (g.Sql.Constraint c in t.Constraints) { g.Sql.UniqueConstraint temp = c as g.Sql.UniqueConstraint; if (temp != null && c.Field.Name == "A4") uq = temp; } Assert.IsNotNull(uq); } [Test] public void TestGetTables() { DataTable tables = dbLoader.GetTables(); g.Sql.Table t1 = new g.Sql.Table(tables.Rows[0][0].ToString(), null, false); g.Sql.Table t2 = new g.Sql.Table(tables.Rows[1][0].ToString(), null, false); g.Sql.Table t3 = new g.Sql.Table(tables.Rows[2][0].ToString(), null, false); g.Sql.Table t4 = new g.Sql.Table(tables.Rows[3][0].ToString(), null, false); Assert.AreEqual(4, tables.Rows.Count); Assert.AreEqual("test_Record1", t1.Name); Assert.AreEqual("test_Record1Cat", t2.Name); Assert.AreEqual("test_Record1Record2", t3.Name); Assert.AreEqual("test_Record2", t4.Name); } [Test] public void TestGetColumns() { DataTable tables = dbLoader.GetTables(); g.Sql.Table t1 = new g.Sql.Table(tables.Rows[0][0].ToString(), null, false); g.Sql.Table t2 = new g.Sql.Table(tables.Rows[1][0].ToString(), null, false); g.Sql.Table t3 = new g.Sql.Table(tables.Rows[2][0].ToString(), null, false); g.Sql.Table t4 = new g.Sql.Table(tables.Rows[3][0].ToString(), null, false); DataTable columns1 = dbLoader.GetColumns(t1.Name); DataTable columns2 = dbLoader.GetColumns(t2.Name); DataTable columns3 = dbLoader.GetColumns(t3.Name); DataTable columns4 = dbLoader.GetColumns(t4.Name); Assert.AreEqual(26, columns1.Rows.Count); Assert.AreEqual(1, columns2.Rows.Count); Assert.AreEqual(2, columns3.Rows.Count); Assert.AreEqual(1, columns4.Rows.Count); } //this test tests whether the datarow is read correctly - i.e. NOT the correctness of the // sql.tablefield properties, but whether they are initialized corrrectlky based on the datarow data [Test] public void TestMakeField() { DataTable tables = dbLoader.GetTables(); g.Sql.Table t1 = new g.Sql.Table(tables.Rows[0][0].ToString(), null, false); DataTable columns = dbLoader.GetColumns(t1.Name); g.Sql.TableField f = dbLoader.MakeField(columns.Rows[0], t1); Assert.AreEqual("Id", f.Name); Assert.IsTrue(f.IsIdentity); Assert.AreEqual("int", f.Datatype); f = dbLoader.MakeField(columns.Rows[1], t1); Assert.AreEqual("Record1CatId", f.Name); Assert.AreEqual("int", f.Datatype); f = dbLoader.MakeField(columns.Rows[2], t1); Assert.AreEqual("A1", f.Name); Assert.AreEqual("bigint", f.Datatype); f = dbLoader.MakeField(columns.Rows[3], t1); Assert.AreEqual("A2", f.Name); Assert.AreEqual("binary", f.Datatype); Assert.AreEqual(8, f.Length); f = dbLoader.MakeField(columns.Rows[4], t1); Assert.AreEqual("A3", f.Name); Assert.AreEqual("bit", f.Datatype); f = dbLoader.MakeField(columns.Rows[5], t1); Assert.AreEqual("A4", f.Name); Assert.AreEqual("char", f.Datatype); Assert.AreEqual(3, f.Length); f = dbLoader.MakeField(columns.Rows[6], t1); Assert.AreEqual("A5", f.Name); Assert.AreEqual("datetime", f.Datatype); f = dbLoader.MakeField(columns.Rows[7], t1); Assert.AreEqual("A6", f.Name); Assert.AreEqual("decimal", f.Datatype); Assert.AreEqual(5, f.Precision); Assert.AreEqual(2, f.Scale); f = dbLoader.MakeField(columns.Rows[8], t1); Assert.AreEqual("A7", f.Name); Assert.AreEqual("float", f.Datatype); f = dbLoader.MakeField(columns.Rows[9], t1); Assert.AreEqual("A8", f.Name); Assert.AreEqual("image", f.Datatype); f = dbLoader.MakeField(columns.Rows[10], t1); Assert.AreEqual("A9", f.Name); Assert.AreEqual("int", f.Datatype); f = dbLoader.MakeField(columns.Rows[11], t1); Assert.AreEqual("A10", f.Name); Assert.AreEqual("money", f.Datatype); f = dbLoader.MakeField(columns.Rows[12], t1); Assert.AreEqual("A11", f.Name); Assert.AreEqual("nchar", f.Datatype); Assert.AreEqual(3, f.Length); f = dbLoader.MakeField(columns.Rows[13], t1); Assert.AreEqual("A12", f.Name); Assert.AreEqual("ntext", f.Datatype); f = dbLoader.MakeField(columns.Rows[14], t1); Assert.AreEqual("A13", f.Name); Assert.AreEqual("numeric", f.Datatype); Assert.AreEqual(4, f.Precision); Assert.AreEqual(3, f.Scale); f = dbLoader.MakeField(columns.Rows[15], t1); Assert.AreEqual("A14", f.Name); Assert.AreEqual("nvarchar", f.Datatype); Assert.AreEqual(3, f.Length); f = dbLoader.MakeField(columns.Rows[16], t1); Assert.AreEqual("A15", f.Name); Assert.AreEqual("real", f.Datatype); f = dbLoader.MakeField(columns.Rows[17], t1); Assert.AreEqual("A16", f.Name); Assert.AreEqual("smalldatetime", f.Datatype); f = dbLoader.MakeField(columns.Rows[18], t1); Assert.AreEqual("A17", f.Name); Assert.AreEqual("smallint", f.Datatype); f = dbLoader.MakeField(columns.Rows[19], t1); Assert.AreEqual("A18", f.Name); Assert.AreEqual("smallmoney", f.Datatype); f = dbLoader.MakeField(columns.Rows[20], t1); Assert.AreEqual("A19", f.Name); Assert.AreEqual("text", f.Datatype); f = dbLoader.MakeField(columns.Rows[21], t1); Assert.AreEqual("A20", f.Name); Assert.AreEqual("timestamp", f.Datatype); f = dbLoader.MakeField(columns.Rows[22], t1); Assert.AreEqual("A21", f.Name); Assert.AreEqual("tinyint", f.Datatype); f = dbLoader.MakeField(columns.Rows[23], t1); Assert.AreEqual("A22", f.Name); Assert.AreEqual("uniqueidentifier", f.Datatype); f = dbLoader.MakeField(columns.Rows[24], t1); Assert.AreEqual("A23", f.Name); Assert.AreEqual("varbinary", f.Datatype); Assert.AreEqual(8, f.Length); f = dbLoader.MakeField(columns.Rows[25], t1); Assert.AreEqual("A24", f.Name); Assert.AreEqual("varchar", f.Datatype); Assert.AreEqual(3, f.Length); } [SetUp] public void SetUp() { string setupFile = @"C:\development\vs\CodeGenerator\CodeGeneratorTest\mics\dbTestEnvSetup.txt"; string teardownFile = @"C:\development\vs\CodeGenerator\CodeGeneratorTest\mics\dbTestEnvTearDown.txt"; envBuilder = new Sql.DbEnvironmentBuilder(Connection, setupFile, teardownFile); envBuilder.Setup(); dbLoader = new CodeGenerator.SqlDatabaseLoader(Connection, true); } [TearDown] public void TearDown() { envBuilder.TearDown(); } private Sql.DbEnvironmentBuilder envBuilder; private g.SqlDatabaseLoader dbLoader; } }
38.100358
114
0.56698
[ "MIT" ]
ic4f/codegenerator
CodeGeneratorTest/SqlDatabaseLoaderTest.cs
10,630
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.Vulkan.Video { [NativeName("Name", "StdVideoEncodeH265SliceHeaderFlags")] public unsafe partial struct StdVideoEncodeH265SliceHeaderFlags { public StdVideoEncodeH265SliceHeaderFlags ( uint? firstSliceSegmentInPicFlag = null, uint? noOutputOfPriorPicsFlag = null, uint? dependentSliceSegmentFlag = null, uint? shortTermRefPicSetSpsFlag = null, uint? sliceTemporalMvpEnableFlag = null, uint? sliceSaoLumaFlag = null, uint? sliceSaoChromaFlag = null, uint? numRefIdxActiveOverrideFlag = null, uint? mvdL1ZeroFlag = null, uint? cabacInitFlag = null, uint? sliceDeblockingFilterDisableFlag = null, uint? collocatedFromL0Flag = null, uint? sliceLoopFilterAcrossSlicesEnabledFlag = null, uint? bLastSliceInPic = null, ushort? lumaWeightL0Flag = null, ushort? chromaWeightL0Flag = null, ushort? lumaWeightL1Flag = null, ushort? chromaWeightL1Flag = null ) : this() { if (firstSliceSegmentInPicFlag is not null) { FirstSliceSegmentInPicFlag = firstSliceSegmentInPicFlag.Value; } if (noOutputOfPriorPicsFlag is not null) { NoOutputOfPriorPicsFlag = noOutputOfPriorPicsFlag.Value; } if (dependentSliceSegmentFlag is not null) { DependentSliceSegmentFlag = dependentSliceSegmentFlag.Value; } if (shortTermRefPicSetSpsFlag is not null) { ShortTermRefPicSetSpsFlag = shortTermRefPicSetSpsFlag.Value; } if (sliceTemporalMvpEnableFlag is not null) { SliceTemporalMvpEnableFlag = sliceTemporalMvpEnableFlag.Value; } if (sliceSaoLumaFlag is not null) { SliceSaoLumaFlag = sliceSaoLumaFlag.Value; } if (sliceSaoChromaFlag is not null) { SliceSaoChromaFlag = sliceSaoChromaFlag.Value; } if (numRefIdxActiveOverrideFlag is not null) { NumRefIdxActiveOverrideFlag = numRefIdxActiveOverrideFlag.Value; } if (mvdL1ZeroFlag is not null) { MvdL1ZeroFlag = mvdL1ZeroFlag.Value; } if (cabacInitFlag is not null) { CabacInitFlag = cabacInitFlag.Value; } if (sliceDeblockingFilterDisableFlag is not null) { SliceDeblockingFilterDisableFlag = sliceDeblockingFilterDisableFlag.Value; } if (collocatedFromL0Flag is not null) { CollocatedFromL0Flag = collocatedFromL0Flag.Value; } if (sliceLoopFilterAcrossSlicesEnabledFlag is not null) { SliceLoopFilterAcrossSlicesEnabledFlag = sliceLoopFilterAcrossSlicesEnabledFlag.Value; } if (bLastSliceInPic is not null) { BLastSliceInPic = bLastSliceInPic.Value; } if (lumaWeightL0Flag is not null) { LumaWeightL0Flag = lumaWeightL0Flag.Value; } if (chromaWeightL0Flag is not null) { ChromaWeightL0Flag = chromaWeightL0Flag.Value; } if (lumaWeightL1Flag is not null) { LumaWeightL1Flag = lumaWeightL1Flag.Value; } if (chromaWeightL1Flag is not null) { ChromaWeightL1Flag = chromaWeightL1Flag.Value; } } private uint _bitfield1; public uint FirstSliceSegmentInPicFlag { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (uint)(_bitfield1 & 0x1u); [MethodImpl(MethodImplOptions.AggressiveInlining)] set => _bitfield1 = (uint)((uint)(_bitfield1 & ~0x1u) | (uint)((uint)(value) & 0x1u)); } public uint NoOutputOfPriorPicsFlag { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (uint)((_bitfield1 >> 1) & 0x1u); [MethodImpl(MethodImplOptions.AggressiveInlining)] set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 1)) | (uint)(((uint)(value) & 0x1u) << 1)); } public uint DependentSliceSegmentFlag { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (uint)((_bitfield1 >> 2) & 0x1u); [MethodImpl(MethodImplOptions.AggressiveInlining)] set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 2)) | (uint)(((uint)(value) & 0x1u) << 2)); } public uint ShortTermRefPicSetSpsFlag { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (uint)((_bitfield1 >> 3) & 0x1u); [MethodImpl(MethodImplOptions.AggressiveInlining)] set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 3)) | (uint)(((uint)(value) & 0x1u) << 3)); } public uint SliceTemporalMvpEnableFlag { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (uint)((_bitfield1 >> 4) & 0x1u); [MethodImpl(MethodImplOptions.AggressiveInlining)] set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 4)) | (uint)(((uint)(value) & 0x1u) << 4)); } public uint SliceSaoLumaFlag { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (uint)((_bitfield1 >> 5) & 0x1u); [MethodImpl(MethodImplOptions.AggressiveInlining)] set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 5)) | (uint)(((uint)(value) & 0x1u) << 5)); } public uint SliceSaoChromaFlag { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (uint)((_bitfield1 >> 6) & 0x1u); [MethodImpl(MethodImplOptions.AggressiveInlining)] set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 6)) | (uint)(((uint)(value) & 0x1u) << 6)); } public uint NumRefIdxActiveOverrideFlag { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (uint)((_bitfield1 >> 7) & 0x1u); [MethodImpl(MethodImplOptions.AggressiveInlining)] set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 7)) | (uint)(((uint)(value) & 0x1u) << 7)); } public uint MvdL1ZeroFlag { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (uint)((_bitfield1 >> 8) & 0x1u); [MethodImpl(MethodImplOptions.AggressiveInlining)] set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 8)) | (uint)(((uint)(value) & 0x1u) << 8)); } public uint CabacInitFlag { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (uint)((_bitfield1 >> 9) & 0x1u); [MethodImpl(MethodImplOptions.AggressiveInlining)] set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 9)) | (uint)(((uint)(value) & 0x1u) << 9)); } public uint SliceDeblockingFilterDisableFlag { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (uint)((_bitfield1 >> 10) & 0x1u); [MethodImpl(MethodImplOptions.AggressiveInlining)] set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 10)) | (uint)(((uint)(value) & 0x1u) << 10)); } public uint CollocatedFromL0Flag { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (uint)((_bitfield1 >> 11) & 0x1u); [MethodImpl(MethodImplOptions.AggressiveInlining)] set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 11)) | (uint)(((uint)(value) & 0x1u) << 11)); } public uint SliceLoopFilterAcrossSlicesEnabledFlag { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (uint)((_bitfield1 >> 12) & 0x1u); [MethodImpl(MethodImplOptions.AggressiveInlining)] set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 12)) | (uint)(((uint)(value) & 0x1u) << 12)); } public uint BLastSliceInPic { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (uint)((_bitfield1 >> 13) & 0x1u); [MethodImpl(MethodImplOptions.AggressiveInlining)] set => _bitfield1 = (uint)((uint)(_bitfield1 & ~(0x1u << 13)) | (uint)(((uint)(value) & 0x1u) << 13)); } [NativeName("Type", "uint16_t")] [NativeName("Type.Name", "uint16_t")] [NativeName("Name", "luma_weight_l0_flag")] public ushort LumaWeightL0Flag; [NativeName("Type", "uint16_t")] [NativeName("Type.Name", "uint16_t")] [NativeName("Name", "chroma_weight_l0_flag")] public ushort ChromaWeightL0Flag; [NativeName("Type", "uint16_t")] [NativeName("Type.Name", "uint16_t")] [NativeName("Name", "luma_weight_l1_flag")] public ushort LumaWeightL1Flag; [NativeName("Type", "uint16_t")] [NativeName("Type.Name", "uint16_t")] [NativeName("Name", "chroma_weight_l1_flag")] public ushort ChromaWeightL1Flag; } }
36.98893
114
0.573125
[ "MIT" ]
Zellcore/Silk.NET
src/Vulkan/Silk.NET.Vulkan/Video/Structs/StdVideoEncodeH265SliceHeaderFlags.gen.cs
10,024
C#
using Microsoft.Xna.Framework.Content.Pipeline; using MonoGame.Extended.Content.Pipeline.Json; namespace MonoGame.Extended.Content.Pipeline.SpriteFactory { [ContentProcessor(DisplayName = "Sprite Factory Processor - MonoGame.Extended")] public class SpriteFactoryContentProcessor : JsonContentProcessor { public SpriteFactoryContentProcessor() { ContentType = "MonoGame.Extended MonoGame.Extended.Animations.SpriteFactory.SpriteFactoryFileReader, MonoGame.Extended.Animations"; } } }
35.866667
143
0.760223
[ "MIT" ]
Apostolique/MonoGame.Extended
src/dotnet/MonoGame.Extended.Content.Pipeline/SpriteFactory/SpriteFactoryContentProcessor.cs
540
C#
using System; using System.Collections.Generic; using System.IO; using System.Text.Json; using System.Threading.Tasks; using SmartTaskbar.Core.Helpers; namespace SmartTaskbar.Core.Settings { public static class SettingsHelper { private static readonly string SettingPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "SmartTaskbar", "SmartTaskbar.json"); internal static async Task SaveSettingsAsync(UserSettings userSettings) { DirectoryBuilder(); var options = new JsonSerializerOptions { WriteIndented = true }; using var stream = new FileStream(SettingPath, FileMode.OpenOrCreate); await JsonSerializer.SerializeAsync(stream, userSettings, options); } internal static async Task<UserSettings> ReadSettingsAsync() { DirectoryBuilder(); using var fs = new FileStream(SettingPath, FileMode.OpenOrCreate); var settings = await JsonSerializer.DeserializeAsync<UserSettings>(fs); return settings.UpdateSettings(); } private static void DirectoryBuilder() => Directory.CreateDirectory(Path.GetDirectoryName(SettingPath) ?? throw new InvalidOperationException()); private static UserSettings UpdateSettings(this UserSettings settings) => new UserSettings { IconStyle = settings?.IconStyle ?? IconStyle.Auto, ModeType = settings?.ModeType ?? AutoModeType.AutoHideApiMode, ResetState = settings?.ResetState ?? new TaskbarState { HideTaskbarCompletely = false, IsAutoHide = !AutoHide.NotAutoHide(), IconSize = ButtonSize.GetIconSize(), TransparentMode = TransparentModeType.Disable }, ReadyState = settings?.ReadyState ?? new TaskbarState { HideTaskbarCompletely = false, IsAutoHide = false, IconSize = Constant.IconLarge, TransparentMode = TransparentModeType.Disable }, TargetState = settings?.TargetState ?? new TaskbarState { HideTaskbarCompletely = false, IsAutoHide = true, IconSize = Constant.IconLarge, TransparentMode = TransparentModeType.Disable }, Blacklist = settings?.Blacklist ?? new HashSet<string>(), Whitelist = settings?.Whitelist ?? new HashSet<string>(), //DisableOnTabletMode = settings?.DisableOnTabletMode ?? true, IconCentered = settings?.IconCentered ?? false, Language = settings?.Language ?? Language.Auto }; } }
39.6
115
0.588215
[ "MIT" ]
nonomal/SmartTaskbar
SmartTaskbar.Core/Settings/SettingsHelper.cs
2,972
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 Ctf4e.Server.Resources.Views { 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", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class AdminUsers_Edit { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal AdminUsers_Edit() { } /// <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("Ctf4e.Server.Resources.Views.AdminUsers.Edit", typeof(AdminUsers_Edit).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 Cancel. /// </summary> internal static string Form_Cancel { get { return ResourceManager.GetString("Form:Cancel", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Name. /// </summary> internal static string Form_DisplayName { get { return ResourceManager.GetString("Form:DisplayName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Group creation code. /// </summary> internal static string Form_GroupFindingCode { get { return ResourceManager.GetString("Form:GroupFindingCode", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Group. /// </summary> internal static string Form_GroupId { get { return ResourceManager.GetString("Form:GroupId", resourceCulture); } } /// <summary> /// Looks up a localized string similar to (none). /// </summary> internal static string Form_GroupId_None { get { return ResourceManager.GetString("Form:GroupId:None", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Admin permissions. /// </summary> internal static string Form_IsAdmin { get { return ResourceManager.GetString("Form:IsAdmin", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Tutor permissions. /// </summary> internal static string Form_IsTutor { get { return ResourceManager.GetString("Form:IsTutor", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Moodle account. /// </summary> internal static string Form_MoodleName { get { return ResourceManager.GetString("Form:MoodleName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Save changes. /// </summary> internal static string Form_Submit { get { return ResourceManager.GetString("Form:Submit", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Edit user. /// </summary> internal static string Title { get { return ResourceManager.GetString("Title", resourceCulture); } } } }
37.363636
195
0.56187
[ "MIT" ]
JanWichelmann/ctf4e
src/Ctf4e.Server/Resources/Views/AdminUsers.Edit.Designer.cs
5,756
C#
#region Using directives using SimpleFramework.Xml; using System; #endregion namespace SimpleFramework.Xml.Core { public class NamespaceDefaultTest : ValidationTestCase { private const String SOURCE = "<a xmlns:x='http://domain/x' xmlns='http://domain/z'>\n"+ " <y:b xmlns:y='http://domain/y'>\n"+ " <c xmlns='http://domain/c'>\n"+ " <d xmlns='http://domain/z'>d</d>\n"+ " </c>\n"+ " </y:b>\n"+ "</a>\n"; [Root] [NamespaceList] [Namespace(Prefix="x", Reference="http://domain/x")] [Namespace(Prefix="z", Reference="http://domain/z")})] [Namespace(Reference="http://domain/z")] private static class A { [Element] [Namespace(Prefix="y", Reference="http://domain/y")] private B b; } [Root] private static class B { [Element] [Namespace(Reference="http://domain/c")] private C c; } [Root] private static class C{ [Element] [Namespace(Reference="http://domain/z")] private String d; } public void TestScope() { Persister persister = new Persister(); StringWriter writer = new StringWriter(); A example = persister.read(A.class, SOURCE); AssertEquals(example.b.c.d, "d"); assertElementHasNamespace(SOURCE, "/a", "http://domain/z"); assertElementHasNamespace(SOURCE, "/a/b", "http://domain/y"); assertElementHasNamespace(SOURCE, "/a/b/c", "http://domain/c"); assertElementHasNamespace(SOURCE, "/a/b/c/d", "http://domain/z"); persister.write(example, writer); String text = writer.toString(); System.out.println(text); assertElementHasNamespace(text, "/a", "http://domain/z"); assertElementHasNamespace(text, "/a/b", "http://domain/y"); assertElementHasNamespace(text, "/a/b/c", "http://domain/c"); assertElementHasNamespace(text, "/a/b/c/d", "http://domain/z"); assertElementHasAttribute(text, "/a", "xmlns", "http://domain/z"); assertElementDoesNotHaveAttribute(text, "/a", "xmlns:z", "http://domain/z"); assertElementHasAttribute(text, "/a", "xmlns:x", "http://domain/x"); assertElementHasAttribute(text, "/a/b", "xmlns:y", "http://domain/y"); assertElementHasAttribute(text, "/a/b/c", "xmlns", "http://domain/c"); assertElementHasAttribute(text, "/a/b/c/d", "xmlns", "http://domain/z"); } } }
40.870968
85
0.571429
[ "Apache-2.0" ]
AMCON-GmbH/simplexml
port/src/main/Xml/Core/NamespaceDefaultTest.cs
2,534
C#
using System; using System.Linq; using Microsoft.EntityFrameworkCore; using DatabaseFirstLINQ.Models; using System.Collections.Generic; namespace DatabaseFirstLINQ { class Problems { private ECommerceContext _context; public Problems() { _context = new ECommerceContext(); } public void RunLINQQueries() { ProblemOne(); ProblemTwo(); ProblemThree(); ProblemFour(); ProblemFive(); ProblemSix(); ProblemSeven(); ProblemEight(); ProblemNine(); ProblemTen(); ProblemEleven(); ProblemTwelve(); ProblemThirteen(); ProblemFourteen(); ProblemFifteen(); ProblemSixteen(); ProblemSeventeen(); ProblemEighteen(); ProblemNineteen(); ProblemTwenty(); } // <><><><><><><><> R Actions (Read) <><><><><><><><><> private void ProblemOne() { // Write a LINQ query that returns the number of users in the Users table. // HINT: .ToList().Count int count = _context.Users.ToList().Count; Console.WriteLine(count); } private void ProblemTwo() { // Write a LINQ query that retrieves the users from the User tables then print each user's email to the console. var users = _context.Users; foreach (User user in users) { Console.WriteLine(user.Email); } } private void ProblemThree() { // Write a LINQ query that gets each product where the products price is greater than $150. // Then print the name and price of each product from the above query to the console. var products = _context.Products.Where(p => p.Price > 150m); foreach (var product in products) { Console.WriteLine(product.Name + " " + product.Price); } } private void ProblemFour() { // Write a LINQ query that gets each product that contains an "s" in the products name. // Then print the name of each product from the above query to the console. var products = _context.Products; foreach (var product in products) if (product.Name.Contains("s")) { Console.WriteLine(product.Name); } } private void ProblemFive() { // Write a LINQ query that gets all of the users who registered BEFORE 2016 // Then print each user's email and registration date to the console. DateTime endDate = new DateTime(2016, 01, 01); var registeredBefore = _context.Users.Where(y => y.RegistrationDate < endDate).ToList(); foreach (User user in registeredBefore) { Console.WriteLine(user.RegistrationDate); } } private void ProblemSix() { // Write a LINQ query that gets all of the users who registered AFTER 2016 and BEFORE 2018 // Then print each user's email and registration date to the console. DateTime endDate = new DateTime(2016, 01, 01); DateTime endDateTwo = new DateTime(2018, 01, 01); var registeredBefore = _context.Users.Where(y => y.RegistrationDate > endDate && y.RegistrationDate < endDateTwo).ToList(); foreach (User user in registeredBefore) { Console.WriteLine(user.RegistrationDate + " " + user.Email); } } // <><><><><><><><> R Actions (Read) with Foreign Keys <><><><><><><><><> private void ProblemSeven() { // Write a LINQ query that retreives all of the users who are assigned to the role of Customer. // Then print the users email and role name to the console. var customerUsers = _context.UserRoles.Include(ur => ur.Role).Include(ur => ur.User).Where(ur => ur.Role.RoleName == "Customer"); foreach (UserRole userRole in customerUsers) { Console.WriteLine($"Email: {userRole.User.Email} Role: {userRole.Role.RoleName}"); } } private void ProblemEight() { // Write a LINQ query that retreives all of the products in the shopping cart of the user who has the email "afton@gmail.com". // Then print the product's name, price, and quantity to the console. var boughtProducts = _context.ShoppingCarts.Include(sc => sc.Product).Include(sc => sc.User).Where(sc => sc.User.Email == "afton@gmail.com"); foreach (ShoppingCart scRow in boughtProducts) { Console.WriteLine($"Product Name:{scRow.Product.Name} Product Price:{scRow.Product.Price} Product Quantity:{scRow.Quantity}"); } } private void ProblemNine() { // Write a LINQ query that retreives all of the products in the shopping cart of the user who has the email "oda@gmail.com" and returns the sum of all of the products prices. // HINT: End of query will be: .Select(sc => sc.Product.Price).Sum(); // Then print the total of the shopping cart to the console. var boughtProduct = _context.ShoppingCarts.Include(sc => sc.Product).Include(sc => sc.User).Where(sc => sc.User.Email == "afton@gmail.com").Select(sc => sc.Product.Price).Sum(); Console.WriteLine($"The sum is: {boughtProduct}"); } private void ProblemTen() { // Write a LINQ query that retreives all of the products in the shopping cart of users who have the role of "Employee". // Then print the user's email as well as the product's name, price, and quantity to the console. // [34, 21, 65] var employeeUsers = _context.UserRoles.Include(ur => ur.Role).Include(ur => ur.User).Where(ur => ur.Role.RoleName == "Employee").Select(ur => ur.UserId); var shoppingCart = _context.ShoppingCarts.Include(sc => sc.Product).Include(sc => sc.User).Where(sc => employeeUsers.Contains(sc.UserId)); foreach (ShoppingCart scRow in shoppingCart) { Console.WriteLine($"Email {scRow.User.Email} Product Name: {scRow.Product.Name} Price: {scRow.Product.Price} Quantity: {scRow.Quantity}"); } } // <><><><><><><><> CUD (Create, Update, Delete) Actions <><><><><><><><><> // <><> C Actions (Create) <><> private void ProblemEleven() { // Create a new User object and add that user to the Users table using LINQ. User newUser = new User() { Email = "david@gmail.com", Password = "DavidsPass123" }; _context.Users.Add(newUser); _context.SaveChanges(); } private void ProblemTwelve() { // Create a new Product object and add that product to the Products table using LINQ. Product newProduct = new Product() { Name = "Salt & Vinegar Kettle Potato Chips", Description = "Crunchy, perfectly fried potato chips with a hint of Sea Salt and Vinegar flavor", Price = 19.99m }; _context.Products.Add(newProduct); _context.SaveChanges(); } private void ProblemThirteen() { // Add the role of "Customer" to the user we just created in the UserRoles junction table using LINQ. var roleId = _context.Roles.Where(r => r.RoleName == "Customer").Select(r => r.Id).SingleOrDefault(); var userId = _context.Users.Where(u => u.Email == "david@gmail.com").Select(u => u.Id).FirstOrDefault(); UserRole newUserRole = new UserRole() { UserId = userId, RoleId = roleId }; _context.UserRoles.Add(newUserRole); _context.SaveChanges(); } private void ProblemFourteen() { // Add the product you create to the user we created in the ShoppingCart junction table using LINQ. var userId = _context.Users.Where(u => u.Email == "david@gmail.com").Select(u => u.Id).FirstOrDefault(); var addProduct = _context.Products.Where(p => p.Name == "Salt & Vinegar Kettle Potato Chips").Select(_context => _context.Id).FirstOrDefault(); ShoppingCart thisCart = new ShoppingCart() { ProductId = userId, UserId = addProduct }; _context.ShoppingCarts.Add(thisCart); _context.SaveChanges(); } // <><> U Actions (Update) <><> private void ProblemFifteen() { // Update the email of the user we created to "mike@gmail.com" var user = _context.Users.Where(u => u.Email == "david@gmail.com").FirstOrDefault(); user.Email = "mike@gmail.com"; _context.Users.Update(user); _context.SaveChanges(); } private void ProblemSixteen() { // Update the price of the product you created to something different using LINQ. var product = _context.Products.Where(p => p.Name == "Salt & Vinegar Kettle Potato Chips").FirstOrDefault(); product.Price = 4.99m; _context.Products.Update(product); _context.SaveChanges(); } private void ProblemSeventeen() { // Change the role of the user we created to "Employee" // HINT: You need to delete the existing role relationship and then create a new UserRole object and add it to the UserRoles table // See problem eighteen as an example of removing a role relationship var userRole = _context.UserRoles.Where(ur => ur.User.Email == "mike@gmail.com").FirstOrDefault(); _context.UserRoles.Remove(userRole); UserRole newUserRole = new UserRole() { UserId = _context.Users.Where(u => u.Email == "mike@gmail.com").Select(u => u.Id).FirstOrDefault(), RoleId = _context.Roles.Where(r => r.RoleName == "Employee").Select(r => r.Id).FirstOrDefault() }; _context.UserRoles.Add(newUserRole); _context.SaveChanges(); } // <><> D Actions (Delete) <><> private void ProblemEighteen() { // Delete the role relationship from the user who has the email "oda@gmail.com" using LINQ. var userRole = _context.UserRoles.Where(ur => ur.User.Email == "oda@gmail.com").FirstOrDefault(); _context.UserRoles.Remove(userRole); _context.SaveChanges(); } private void ProblemNineteen() { // Delete all of the product relationships to the user with the email "oda@gmail.com" in the ShoppingCart table using LINQ. // HINT: Loop var shoppingCartProducts = _context.ShoppingCarts.Where(sc => sc.User.Email == "oda@gmail.com"); foreach (ShoppingCart userProductRelationship in shoppingCartProducts) { _context.ShoppingCarts.Remove(userProductRelationship); } _context.SaveChanges(); } private void ProblemTwenty() { // Delete the user with the email "oda@gmail.com" from the Users table using LINQ. var deletedUser = _context.Users.Where(ur => ur.Email == "oda@gmail.com").FirstOrDefault(); _context.Users.Remove(deletedUser); _context.SaveChanges(); } // <><><><><><><><> BONUS PROBLEMS <><><><><><><><><> private void BonusOne() { // Prompt the user to enter in an email and password through the console. // Take the email and password and check if the there is a person that matches that combination. // Print "Signed In!" to the console if they exists and the values match otherwise print "Invalid Email or Password.". } private void BonusTwo() { // Write a query that finds the total of every users shopping cart products using LINQ. // Display the total of each users shopping cart as well as the total of the toals to the console. } // BIG ONE private void BonusThree() { // 1. Create functionality for a user to sign in via the console // 2. If the user succesfully signs in // a. Give them a menu where they perform the following actions within the console // View the products in their shopping cart // View all products in the Products table // Add a product to the shopping cart (incrementing quantity if that product is already in their shopping cart) // Remove a product from their shopping cart // 3. If the user does not succesfully sing in // a. Display "Invalid Email or Password" // b. Re-prompt the user for credentials } } }
40.008902
189
0.568716
[ "MIT" ]
EbonyRiddick/LINQ-Ecommerce-Project
DatabaseFirstLINQ/Problems.cs
13,485
C#
 namespace Raiding.Models { public class Paladin : BaseHero { private const int POWER = 100; public Paladin(string name) : base(name) { this.Power = POWER; } public override string CastAbility() { return $"{this.GetType().Name} - {this.Name} healed for {this.Power}"; } } }
21.055556
82
0.511873
[ "MIT" ]
tonchevaAleksandra/C-Sharp-OOP
Polymorphism/Raiding/Models/Paladin.cs
381
C#
using NWheels.Composition.Model; using NWheels.Composition.Model.Impl; using NWheels.Composition.Model.Impl.Metadata; using NWheels.DevOps.Model.Impl.Parsers; namespace NWheels.DevOps.Model { [ModelParser(typeof(EnvironmentParser))] public abstract class AnyEnvironment : ICanInclude<AnyDeployment>, ICanInclude<TechnologyAdaptedComponent> { } public abstract class Environment<TConfig> : AnyEnvironment { protected Environment(string name, string role, TConfig config) { this.Name = name; this.Role = role; this.Config = config; } public string Name { get; } public string Role { get; } public TConfig Config { get; } } }
27.333333
110
0.668022
[ "MIT" ]
nwheels-io/NWheels
source/NWheels.DevOps.Model/Environment.cs
738
C#
using System; using System.Collections.Generic; #nullable disable namespace Sopra.Lab.App4.ConsoleApp4.Models { public partial class Orders_Qry { public int OrderID { get; set; } public string CustomerID { get; set; } public int? EmployeeID { get; set; } public DateTime? OrderDate { get; set; } public DateTime? RequiredDate { get; set; } public DateTime? ShippedDate { get; set; } public int? ShipVia { get; set; } public decimal? Freight { get; set; } public string ShipName { get; set; } public string ShipAddress { get; set; } public string ShipCity { get; set; } public string ShipRegion { get; set; } public string ShipPostalCode { get; set; } public string ShipCountry { get; set; } public string CompanyName { get; set; } public string Address { get; set; } public string City { get; set; } public string Region { get; set; } public string PostalCode { get; set; } public string Country { get; set; } } }
34.03125
51
0.605142
[ "Unlicense" ]
vPlata98/Labs
Sopra.Lab.App4.ConsoleApp4/Models/Orders_Qry.cs
1,091
C#
using System.Reactive; using System.Reactive.Subjects; using JetBrains.Annotations; namespace Sholo.HomeAssistant.Mqtt.Entities.DeviceTrigger { [PublicAPI] public interface IDeviceTrigger : IEntity { ISubject<Unit> TriggerSubject { get; } void Trigger(); } }
20.857143
57
0.712329
[ "MIT" ]
scottt732/Sholo.HomeAssistant
Source/Sholo.HomeAssistant.Mqtt/Entities/DeviceTrigger/IDeviceTrigger.cs
292
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; /// <summary> /// System.MathF.Min(System.Single, System.Single) /// </summary> public class MathFMin8 { public static int Main(string[] args) { MathFMin8 min8 = new MathFMin8(); TestLibrary.TestFramework.BeginTestCase("Testing System.MathF.Min(System.Single,System.Single)..."); if (min8.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Verify the return value of min function..."); try { float var1 = TestLibrary.Generator.GetSingle(-55); float var2 = TestLibrary.Generator.GetSingle(-55); if (var1 < var2 && !float.IsNaN(var1) && !float.IsNaN(var2)) { if (MathF.Min(var1, var2) != var1) { TestLibrary.TestFramework.LogError("001", "The return value should be var1!"); retVal = false; } } else if (!float.IsNaN(var1) && !float.IsNaN(var2)) { if (MathF.Min(var1, var2) != var2) { TestLibrary.TestFramework.LogError("002", "The return value should be var2!"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Verify the min value of float.NaN and float.NegativeInfinity..."); try { float var1 = float.NaN; float var2 = float.NegativeInfinity; if (!float.IsNaN(MathF.Min(var1, var2))) { TestLibrary.TestFramework.LogError("004", "The return value should be float.NaN!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("005", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } }
29.441176
125
0.541459
[ "MIT" ]
AaronRobinsonMSFT/coreclr
tests/src/CoreMangLib/cti/system/mathf/mathfmin.cs
3,003
C#
// nVLC // // Author: Roman Ginzburg // // nVLC is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // nVLC 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 General Public License for more details. // // ======================================================================== using System; using System.Runtime.InteropServices; using System.Collections.Generic; using Nequeo.Media.Vlc; using Nequeo.Media.Vlc.Enums; using Nequeo.Media.Vlc.Exceptions; using Nequeo.Media.Vlc.Structures; namespace Nequeo.Media.Vlc.Media { internal class MediaFromFile : BasicMedia, IMediaFromFile { public MediaFromFile(IntPtr hMediaLib) : base(hMediaLib) { } public override string Input { get { return m_path; } set { m_path = value; m_hMedia = LibVlcMethods.libvlc_media_new_path(m_hMediaLib, m_path.ToUtf8()); } } public string GetMetaData(MetaDataType dataType) { IntPtr pData = LibVlcMethods.libvlc_media_get_meta(m_hMedia, (libvlc_meta_t)dataType); return Marshal.PtrToStringAnsi(pData); } public void SetMetaData(MetaDataType dataType, string argument) { LibVlcMethods.libvlc_media_set_meta(m_hMedia, (libvlc_meta_t)dataType, argument.ToUtf8()); } public void SaveMetaData() { LibVlcMethods.libvlc_media_save_meta(m_hMedia); } public long Duration { get { return LibVlcMethods.libvlc_media_get_duration(m_hMedia); } } [Obsolete] public MediaTrackInfo[] TracksInfo { get { IntPtr pTr = IntPtr.Zero; int num = LibVlcMethods.libvlc_media_get_tracks_info(m_hMedia, out pTr); if (num == 0 || pTr == IntPtr.Zero) { throw new LibVlcException(); } int size = Marshal.SizeOf(typeof(libvlc_media_track_info_t)); libvlc_media_track_info_t[] tracks = new libvlc_media_track_info_t[num]; for (int i = 0; i < num; i++) { tracks[i] = (libvlc_media_track_info_t)Marshal.PtrToStructure(pTr, typeof(libvlc_media_track_info_t)); pTr = new IntPtr(pTr.ToInt64() + size); } MediaTrackInfo[] mtis = new MediaTrackInfo[num]; for (int i = 0; i < num; i++) { mtis[i] = tracks[i].ToMediaInfo(); } return mtis; } } } }
29.895238
122
0.546671
[ "MIT" ]
drazenzadravec/projects
Media/Player/Nequeo.Media.Vlc/Nequeo.Media.Vlc/Media/MediaFromFile.cs
3,141
C#
using System; namespace R5T.D0101.T001 { /// <summary> /// IProjectRepositoryFileContext definition. /// </summary> public static class Documentation { } }
15.083333
49
0.635359
[ "MIT" ]
SafetyCone/R5T.D0101
source/R5T.D0101.I001.T001/Code/Documentation.cs
181
C#
/** * Copyright 2013 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: gng $ * Last modified: $LastChangedDate: 2015-11-19 18:20:12 -0500 (Fri, 30 Jan 2015) $ * Revision: $LastChangedRevision: 9755 $ */ using System; using System.Collections.Generic; using Ca.Infoway.Messagebuilder; using Ca.Infoway.Messagebuilder.Datatype; using Ca.Infoway.Messagebuilder.Lang; using Ca.Infoway.Messagebuilder.Platform; using ILOG.J2CsMapping.Text; namespace Ca.Infoway.Messagebuilder.Marshalling.HL7 { public class IiValidationUtils { public static readonly string II = "II"; public static readonly string II_TOKEN = "II.TOKEN"; public static readonly string II_BUS = "II.BUS"; public static readonly string II_PUBLIC = "II.PUBLIC"; public static readonly string II_OID = "II.OID"; public static readonly string II_VER = "II.VER"; public static readonly string II_BUS_AND_VER = "II.BUS_AND_VER"; public static readonly string II_BUSVER = "II.BUSVER"; public static readonly string II_PUBLICVER = "II.PUBLICVER"; public static readonly ICollection<string> concreteIiTypes = new HashSet<string>(); static IiValidationUtils() { concreteIiTypes.Add(II_TOKEN); concreteIiTypes.Add(II_BUS); concreteIiTypes.Add(II_PUBLIC); concreteIiTypes.Add(II_OID); concreteIiTypes.Add(II_VER); concreteIiTypes.Add(II_BUSVER); concreteIiTypes.Add(II_PUBLICVER); } private const int EXTENSION_MAX_LENGTH = 20; private const int ROOT_MAX_LENGTH = 200; private const int ROOT_MAX_LENGTH_CERX = 100; public virtual bool IsOid(string root) { return IsOid(root, false); } public virtual bool IsOid(string root, bool isR2) { if (StringUtils.IsBlank(root) || !root.Contains(".")) { return false; } else { if (isR2 && !(root[0] == '0' || root[0] == '1' || root[0] == '2')) { return false; } else { bool oid = true; while (root.Contains(".")) { string prefix = StringUtils.SubstringBefore(root, "."); oid &= (StringUtils.IsNotBlank(prefix) && StringUtils.IsNumeric(prefix)); root = StringUtils.SubstringAfter(root, "."); } if (StringUtils.IsBlank(root)) { oid = false; } else { oid &= StringUtils.IsNumeric(root); } return oid; } } } public virtual bool IsUuid(string root) { // avoid trying to create a UUID - if not a uuid, the call is expensive (especially for .NET) if (root == null || !(root.Length == 36 || root.Length == 32)) { return false; } try { UUID.FromString(root); return true; } catch (Exception) { return false; } } public virtual bool IsRuid(string root) { bool result = StringUtils.IsBlank(root) ? false : char.IsLetter(root[0]); for (int i = 0; result && i < root.Length; i++) { char ch = root[i]; result &= (char.IsLetterOrDigit(ch) || ch == '-'); } return result; } public virtual int GetMaxRootLength(StandardDataType type, VersionNumber version) { return SpecificationVersion.IsVersion(type, version, Hl7BaseVersion.CERX) ? ROOT_MAX_LENGTH_CERX : ROOT_MAX_LENGTH; } public virtual bool IsRootLengthInvalid(string root, StandardDataType type, VersionNumber version) { return StringUtils.Length(root) > GetMaxRootLength(type, version); } public virtual int GetMaxExtensionLength() { return EXTENSION_MAX_LENGTH; } public virtual bool IsExtensionLengthInvalid(string extension) { return StringUtils.Length(extension) > GetMaxExtensionLength(); } public virtual bool IsCerxOrMr2007(VersionNumber version, StandardDataType type) { return SpecificationVersion.IsVersion(type, version, Hl7BaseVersion.MR2007) || SpecificationVersion.IsVersion(type, version , Hl7BaseVersion.CERX); } public virtual bool IsSpecializationTypeRequired(VersionNumber version, string type, bool isCda) { StandardDataType standardDataType = StandardDataType.GetByTypeName(type); // AB does not treat II as abstract; for CeRx, II is concrete; Newfoundland is excepted to allow our legacy tests to pass return IsIiBusAndVer(type) || (IsII(type) && !(isCda || SpecificationVersion.IsVersion(standardDataType, version, Hl7BaseVersion .CERX) || "NEWFOUNDLAND".Equals(version == null ? null : version.VersionLiteral) || SpecificationVersion.IsExactVersion( SpecificationVersion.V02R02_AB, version))); } public virtual bool IsIiBusAndVer(string type) { return StandardDataType.II_BUS_AND_VER.Type.Equals(type); } public virtual bool IsIiBusOrIiVer(string type) { return StandardDataType.II_BUS.Type.Equals(type) || StandardDataType.II_VER.Type.Equals(type); } public virtual bool IsII(string type) { return StandardDataType.II.Type.Equals(type); } public virtual string GetInvalidOrMissingSpecializationTypeErrorMessage(string type) { string invalidOrMissing = StringUtils.IsBlank(type) ? "Missing" : "Invalid"; return invalidOrMissing + " specializationType" + (StringUtils.IsBlank(type) ? string.Empty : (" (" + type + ")")) + ". Field being left as II without a specializationType."; } public virtual string GetInvalidSpecializationTypeForBusAndVerErrorMessage(string specializationType, string type) { return "Specialization type must be II.BUS or II.VER; " + type + " will be assumed. Invalid specialization type " + specializationType; } public virtual string GetMissingAttributeErrorMessage(string type, string attributeName, string attributeValue) { return System.String.Format("Data type " + type + " requires the attribute {0}=\"{1}\"", attributeName, XmlStringEscape.Escape (attributeValue)); } public virtual string GetIncorrectAttributeValueErrorMessage(string type, string attributeName, string attributeValue) { return System.String.Format("Data type " + type + " expected the attribute {0}=\"{1}\"", attributeName, XmlStringEscape.Escape (attributeValue)); } public virtual string GetRootMustBeUuidErrorMessage(string root) { return "root '" + root + "' should be a UUID."; } public virtual string GetRootMustBeUuidRuidOidErrorMessage(string root) { return "root '" + root + "' must conform to be either a UUID, RUID, or OID."; } public virtual string GetInvalidRootLengthErrorMessage(string root, StandardDataType type, VersionNumber version) { return "root '" + root + "' exceeds maximum allowed length of " + GetMaxRootLength(type, version) + "."; } public virtual string GetInvalidExtensionLengthErrorMessage(string extension) { return "extension '" + extension + "' exceeds maximum allowed length of " + GetMaxExtensionLength() + "."; } public virtual string GetRootMustBeAnOidErrorMessage(string root) { return "The oid, \"" + root + "\" does not appear to be a valid oid"; } public virtual string GetShouldNotProvideSpecializationTypeErrorMessage(string typeFromContext) { return "A specializationType should not be specified for non-abstract type: " + typeFromContext; } } }
32.497942
178
0.690769
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-core/Main/Ca/Infoway/Messagebuilder/Marshalling/HL7/IiValidationUtils.cs
7,897
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.TimeSeriesInsights { /// <summary> /// An event source that receives its data from an Azure EventHub. /// API Version: 2020-05-15. /// </summary> [AzureNativeResourceType("azure-native:timeseriesinsights:EventHubEventSource")] public partial class EventHubEventSource : Pulumi.CustomResource { /// <summary> /// The name of the event hub's consumer group that holds the partitions from which events will be read. /// </summary> [Output("consumerGroupName")] public Output<string> ConsumerGroupName { get; private set; } = null!; /// <summary> /// The time the resource was created. /// </summary> [Output("creationTime")] public Output<string> CreationTime { get; private set; } = null!; /// <summary> /// The name of the event hub. /// </summary> [Output("eventHubName")] public Output<string> EventHubName { get; private set; } = null!; /// <summary> /// The resource id of the event source in Azure Resource Manager. /// </summary> [Output("eventSourceResourceId")] public Output<string> EventSourceResourceId { get; private set; } = null!; /// <summary> /// The name of the SAS key that grants the Time Series Insights service access to the event hub. The shared access policies for this key must grant 'Listen' permissions to the event hub. /// </summary> [Output("keyName")] public Output<string> KeyName { get; private set; } = null!; /// <summary> /// The kind of the event source. /// Expected value is 'Microsoft.EventHub'. /// </summary> [Output("kind")] public Output<string> Kind { get; private set; } = null!; /// <summary> /// An object that represents the local timestamp property. It contains the format of local timestamp that needs to be used and the corresponding timezone offset information. If a value isn't specified for localTimestamp, or if null, then the local timestamp will not be ingressed with the events. /// </summary> [Output("localTimestamp")] public Output<Outputs.LocalTimestampResponse?> LocalTimestamp { get; private set; } = null!; /// <summary> /// Resource location /// </summary> [Output("location")] public Output<string> Location { get; private set; } = null!; /// <summary> /// Resource name /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Provisioning state of the resource. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// The name of the service bus that contains the event hub. /// </summary> [Output("serviceBusNamespace")] public Output<string> ServiceBusNamespace { get; private set; } = null!; /// <summary> /// Resource tags /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// ISO8601 UTC datetime with seconds precision (milliseconds are optional), specifying the date and time that will be the starting point for Events to be consumed. /// </summary> [Output("time")] public Output<string?> Time { get; private set; } = null!; /// <summary> /// The event property that will be used as the event source's timestamp. If a value isn't specified for timestampPropertyName, or if null or empty-string is specified, the event creation time will be used. /// </summary> [Output("timestampPropertyName")] public Output<string?> TimestampPropertyName { get; private set; } = null!; /// <summary> /// Resource type /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a EventHubEventSource resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public EventHubEventSource(string name, EventHubEventSourceArgs args, CustomResourceOptions? options = null) : base("azure-native:timeseriesinsights:EventHubEventSource", name, MakeArgs(args), MakeResourceOptions(options, "")) { } private EventHubEventSource(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:timeseriesinsights:EventHubEventSource", name, null, MakeResourceOptions(options, id)) { } private static EventHubEventSourceArgs MakeArgs(EventHubEventSourceArgs args) { args ??= new EventHubEventSourceArgs(); args.Kind = "Microsoft.EventHub"; return args; } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:timeseriesinsights:EventHubEventSource"}, new Pulumi.Alias { Type = "azure-native:timeseriesinsights/v20170228preview:EventHubEventSource"}, new Pulumi.Alias { Type = "azure-nextgen:timeseriesinsights/v20170228preview:EventHubEventSource"}, new Pulumi.Alias { Type = "azure-native:timeseriesinsights/v20171115:EventHubEventSource"}, new Pulumi.Alias { Type = "azure-nextgen:timeseriesinsights/v20171115:EventHubEventSource"}, new Pulumi.Alias { Type = "azure-native:timeseriesinsights/v20180815preview:EventHubEventSource"}, new Pulumi.Alias { Type = "azure-nextgen:timeseriesinsights/v20180815preview:EventHubEventSource"}, new Pulumi.Alias { Type = "azure-native:timeseriesinsights/v20200515:EventHubEventSource"}, new Pulumi.Alias { Type = "azure-nextgen:timeseriesinsights/v20200515:EventHubEventSource"}, new Pulumi.Alias { Type = "azure-native:timeseriesinsights/v20210630preview:EventHubEventSource"}, new Pulumi.Alias { Type = "azure-nextgen:timeseriesinsights/v20210630preview:EventHubEventSource"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing EventHubEventSource resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static EventHubEventSource Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new EventHubEventSource(name, id, options); } } public sealed class EventHubEventSourceArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the event hub's consumer group that holds the partitions from which events will be read. /// </summary> [Input("consumerGroupName", required: true)] public Input<string> ConsumerGroupName { get; set; } = null!; /// <summary> /// The name of the Time Series Insights environment associated with the specified resource group. /// </summary> [Input("environmentName", required: true)] public Input<string> EnvironmentName { get; set; } = null!; /// <summary> /// The name of the event hub. /// </summary> [Input("eventHubName", required: true)] public Input<string> EventHubName { get; set; } = null!; /// <summary> /// Name of the event source. /// </summary> [Input("eventSourceName")] public Input<string>? EventSourceName { get; set; } /// <summary> /// The resource id of the event source in Azure Resource Manager. /// </summary> [Input("eventSourceResourceId", required: true)] public Input<string> EventSourceResourceId { get; set; } = null!; /// <summary> /// The name of the SAS key that grants the Time Series Insights service access to the event hub. The shared access policies for this key must grant 'Listen' permissions to the event hub. /// </summary> [Input("keyName", required: true)] public Input<string> KeyName { get; set; } = null!; /// <summary> /// The kind of the event source. /// Expected value is 'Microsoft.EventHub'. /// </summary> [Input("kind", required: true)] public Input<string> Kind { get; set; } = null!; /// <summary> /// An object that represents the local timestamp property. It contains the format of local timestamp that needs to be used and the corresponding timezone offset information. If a value isn't specified for localTimestamp, or if null, then the local timestamp will not be ingressed with the events. /// </summary> [Input("localTimestamp")] public Input<Inputs.LocalTimestampArgs>? LocalTimestamp { get; set; } /// <summary> /// The location of the resource. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// Name of an Azure Resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the service bus that contains the event hub. /// </summary> [Input("serviceBusNamespace", required: true)] public Input<string> ServiceBusNamespace { get; set; } = null!; /// <summary> /// The value of the shared access key that grants the Time Series Insights service read access to the event hub. This property is not shown in event source responses. /// </summary> [Input("sharedAccessKey", required: true)] public Input<string> SharedAccessKey { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Key-value pairs of additional properties for the resource. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } /// <summary> /// ISO8601 UTC datetime with seconds precision (milliseconds are optional), specifying the date and time that will be the starting point for Events to be consumed. /// </summary> [Input("time")] public Input<string>? Time { get; set; } /// <summary> /// The event property that will be used as the event source's timestamp. If a value isn't specified for timestampPropertyName, or if null or empty-string is specified, the event creation time will be used. /// </summary> [Input("timestampPropertyName")] public Input<string>? TimestampPropertyName { get; set; } /// <summary> /// The type of the ingressStartAt, It can be "EarliestAvailable", "EventSourceCreationTime", "CustomEnqueuedTime". /// </summary> [Input("type")] public InputUnion<string, Pulumi.AzureNative.TimeSeriesInsights.IngressStartAtType>? Type { get; set; } public EventHubEventSourceArgs() { } } }
45.088028
305
0.617025
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/TimeSeriesInsights/EventHubEventSource.cs
12,805
C#
using System; using Xunit; namespace CreditCardApplications.Tests { public class CreditCardApplicationEvaluatorShould { [Fact] public void AcceptHighIncomeApplications() { var sut = new CreditCardApplicationEvaluator(null); var application = new CreditCardApplication { GrossAnnualIncome = 100_000 }; CreditCardApplicationDecision decision = sut.Evaluate(application); Assert.Equal(CreditCardApplicationDecision.AutoAccepted, decision); } [Fact] public void ReferYoungApplications() { var sut = new CreditCardApplicationEvaluator(null); var application = new CreditCardApplication { Age = 19 }; CreditCardApplicationDecision decision = sut.Evaluate(application); Assert.Equal(CreditCardApplicationDecision.ReferredToHuman, decision); } // other evaluator test conditions } }
27.542857
88
0.665975
[ "MIT" ]
svetlimladenov/WorkDemos
UnitTests/02/demos/after/03NewDependency/CreditCardApplications.Tests/CreditCardApplicationEvaluatorShould.cs
964
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq.Expressions; using AutoMapper.Configuration; using AutoMapper.Mappers.Internal; namespace AutoMapper.Mappers { using static Expression; using static CollectionMapperExpressionFactory; public class EnumerableMapper : EnumerableMapperBase { public override bool IsMatch(TypePair context) => (context.DestinationType.IsInterface() && context.DestinationType.IsEnumerableType() || context.DestinationType.IsListType()) && context.SourceType.IsEnumerableType(); public override Expression MapExpression(IConfigurationProvider configurationProvider, ProfileMap profileMap, PropertyMap propertyMap, Expression sourceExpression, Expression destExpression, Expression contextExpression) { if(destExpression.Type.IsInterface()) { var listType = typeof(IList<>).MakeGenericType(ElementTypeHelper.GetElementType(destExpression.Type)); destExpression = Convert(destExpression, listType); } return MapCollectionExpression(configurationProvider, profileMap, propertyMap, sourceExpression, destExpression, contextExpression, typeof(List<>), MapItemExpr); } } }
46.766667
228
0.682823
[ "MIT" ]
FeiYanLeung/AutoMapper
src/AutoMapper/Mappers/EnumerableMapper.cs
1,403
C#
namespace CodeFragments; public class FileChangeDemo { public static void Exection() { string path = @"c:/"; // Create a new FileSystemWatcher and set its properties. FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = path; /* Watch for changes in LastAccess and LastWrite times, and the renaming of files or directories. */ watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Only watch text files. watcher.Filter = "*.txt"; // Add event handlers. watcher.Changed += new FileSystemEventHandler(OnChanged); watcher.Created += new FileSystemEventHandler(OnChanged); watcher.Deleted += new FileSystemEventHandler(OnChanged); watcher.Renamed += new RenamedEventHandler(OnRenamed); // Begin watching. watcher.EnableRaisingEvents = true; // Subdirectorie. watcher.IncludeSubdirectories = true; } // Define the event handlers. private static void OnChanged(object source, FileSystemEventArgs e) { // Specify what is done when a file is changed, created, or deleted. Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType); } private static void OnRenamed(object source, RenamedEventArgs e) { // Specify what is done when a file is renamed. Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath); } }
36.093023
81
0.654639
[ "Apache-2.0" ]
futugyou/CodeFragments
CodeFragments/FileChangeDemo.cs
1,552
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Room : MonoBehaviour { public int Width; public int Height; public int X; public int Y; private bool updatedDoors = false; public bool cleared = false; public Room(int x, int y) { X = x; Y = y; } public Door leftDoor; public Door rightDoor; public Door topDoor; public Door bottomDoor; public List<Door> doors = new List<Door>(); // Start is called before the first frame update void Start() { if(RoomController.instance == null) { Debug.Log("You pressed play in the wrong scene!"); return; } Door[] ds = GetComponentsInChildren<Door>(); foreach(Door d in ds) { doors.Add(d); switch (d.doorType) { case Door.DoorType.right: rightDoor = d; break; case Door.DoorType.left: leftDoor = d; break; case Door.DoorType.top: topDoor = d; break; case Door.DoorType.bottom: bottomDoor = d; break; } } RoomController.instance.RegisterRoom(this); } void Update() { if(name.Contains("End") && !updatedDoors) { RemoveUnconnectedDoors(); updatedDoors = true; } } public void RemoveUnconnectedDoors() { foreach(Door door in doors) { switch (door.doorType) { case Door.DoorType.right: if(GetRight() == null) { door.gameObject.SetActive(false); } break; case Door.DoorType.left: if (GetLeft() == null) { door.gameObject.SetActive(false); } break; case Door.DoorType.top: if (GetTop() == null) { door.gameObject.SetActive(false); } break; case Door.DoorType.bottom: if (GetBottom() == null) { door.gameObject.SetActive(false); } break; } } } public Room GetRight() { if (RoomController.instance.DoesRoomExist(X + 1, Y)) { return RoomController.instance.FindRoom(X + 1, Y); } return null; } public Room GetLeft() { if (RoomController.instance.DoesRoomExist(X - 1, Y)) { return RoomController.instance.FindRoom(X - 1, Y); } return null; } public Room GetTop() { if (RoomController.instance.DoesRoomExist(X, Y + 1)) { return RoomController.instance.FindRoom(X, Y + 1); } return null; } public Room GetBottom() { if (RoomController.instance.DoesRoomExist(X, Y - 1)) { return RoomController.instance.FindRoom(X, Y - 1); } return null; } void OnDrawGizmos() { Gizmos.color = Color.red; Gizmos.DrawWireCube(transform.position, new Vector3(Width, Height, 0)); } public Vector3 GetRoomCentre() { return new Vector3(X * Width, Y * Height); } private void OnTriggerEnter2D(Collider2D other) { //Debug.Log("PlayerEntered"); if(other.tag == "Player") { Debug.Log("Triggered!"); RoomController.instance.OnPlayerEnterRoom(this); } } }
23.853659
79
0.464724
[ "Apache-2.0" ]
tcarausu/Game-Project---6th-Semester
Assets/Scripts/DungeonGenerator/Room.cs
3,912
C#
using System.Collections.Generic; using Content.Server.Atmos; using Content.Server.Body.Systems; using Content.Shared.Atmos; using Content.Shared.Chemistry.Components; using Robust.Shared.Analyzers; using Robust.Shared.GameObjects; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; namespace Content.Server.Body.Components; [RegisterComponent, Friend(typeof(LungSystem))] public sealed class LungComponent : Component { [DataField("air")] public GasMixture Air { get; set; } = new() { Volume = 6, Temperature = Atmospherics.NormalBodyTemperature }; [ViewVariables] public Solution LungSolution = default!; }
26.576923
56
0.756874
[ "MIT" ]
Alainx277/space-station-14
Content.Server/Body/Components/LungComponent.cs
693
C#
using System.Collections.Generic; using NSubstitute; using NUnit.Framework; using Regseed.Common.Builder; using Regseed.Common.Random; using Regseed.Common.Ranges; using Regseed.Expressions; namespace Regseed.Test.Expressions { [TestFixture] internal class UnionExpressionTest : UnionExpression { private IStringBuilder _stringBuilder; [SetUp] public void SetUp() { _stringBuilder = Substitute.For<IStringBuilder>(); _stringBuilder.GenerateString().Returns("Claudia"); _randomGenerator = Substitute.For<IRandomGenerator>(); _expression = Substitute.For<IExpression>(); _expression.ToStringBuilder().Returns(_stringBuilder); } private IRandomGenerator _randomGenerator; private IExpression _expression; public UnionExpressionTest() : base(null, null) { } public UnionExpressionTest(List<IExpression> expressions, IRandomGenerator random) : base(expressions, random) { } [Test] public void GetInverse_CallsGetComplementOnEachUnionElement() { var expression1 = Substitute.For<IExpression>(); var expression2 = Substitute.For<IExpression>(); var unionExpressions = new List<IExpression> {expression1, expression2}; var union = new UnionExpressionTest(unionExpressions, _randomGenerator); union.GetInverse(); expression1.Received(1).GetInverse(); expression2.Received(1).GetInverse(); } [Test] public void GetInverse_ReturnValueHasSameRepeatIntegerIntervalAsOriginal() { var repeatRange = new IntegerInterval(); repeatRange.TrySetValue(1, 2); var union = new UnionExpressionTest(new List<IExpression>(), _randomGenerator) {RepeatRange = repeatRange}; var result = union.GetInverse().RepeatRange; Assert.AreEqual(repeatRange, result); } [Test] public void GetInverse_ReturnValueHasTypeUnionExpression() { var union = new UnionExpressionTest(new List<IExpression>(), _randomGenerator); var result = union.GetInverse(); Assert.IsInstanceOf<IntersectionExpression>(result); } [Test] public void ToSingleRegexString_ReturnsEmptyString_WhenUnionIsEmpty() { var union = new UnionExpressionTest(new List<IExpression>(), _randomGenerator); var result = union.ToSingleStringBuilder().GenerateString(); Assert.AreEqual(string.Empty, result); } [Test] public void ToSingleRegexString_ReturnsRandomUnionElement_WhenUnionContainsAtLeastTwoElements() { _randomGenerator.GetNextInteger(Arg.Any<int>(), Arg.Any<int>()).Returns(2); var unionExpressions = new List<IExpression> { Substitute.For<IExpression>(), Substitute.For<IExpression>(), _expression, Substitute.For<IExpression>() }; var union = new UnionExpressionTest(unionExpressions, _randomGenerator); var result = union.ToSingleStringBuilder().GenerateString(); Assert.AreEqual("Claudia", result); _expression.Received(1).ToStringBuilder(); _randomGenerator.Received(1).GetNextInteger(Arg.Any<int>(), Arg.Any<int>()); } [Test] public void ToSingleRegexString_ReturnsStringValueOfFirstUnionElement_WhenUnionContainsOneElement() { var union = new UnionExpressionTest(new List<IExpression> {_expression}, _randomGenerator); var result = union.ToSingleStringBuilder().GenerateString(); Assert.AreEqual("Claudia", result); _expression.Received(1).ToStringBuilder(); } [Test] public void Clone_ReturnsNewConcatenationInstanceWithSameValues() { var expression = Substitute.For<IExpression>(); var union = new UnionExpression(new List<IExpression>{expression}, _random) { RepeatRange = new IntegerInterval() }; union.RepeatRange.TrySetValue(1, 3); var result = union.Clone(); Assert.AreNotEqual(union, result); Assert.AreEqual(union.RepeatRange.Start, result.RepeatRange.Start); Assert.AreEqual(union.RepeatRange.End, result.RepeatRange.End); expression.Received(1).Clone(); } [Test] public void Expand_ReturnsListContainingFourStringBuilder_WhenUnionContainsTwoInitialIntersectionExpressionsReturningTwoStringBuildersEachOnExpand() { var intersect1 = Substitute.For<IExpression>(); intersect1.Expand() .Returns(new List<IStringBuilder> {Substitute.For<IStringBuilder>(), Substitute.For<IStringBuilder>()}); var intersect2 = Substitute.For<IExpression>(); intersect2.Expand() .Returns(new List<IStringBuilder> {Substitute.For<IStringBuilder>(), Substitute.For<IStringBuilder>()}); var expression = new UnionExpression(new List<IExpression>{intersect1, intersect2}, _random); var result = expression.Expand(); Assert.AreEqual(4, result.Count); } } }
36.879195
156
0.630755
[ "Apache-2.0" ]
JanZsch/RegSeed
src/Regseed.Test/Expressions/UnionExpressionTest.cs
5,495
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 s3control-2018-08-20.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.S3Control.Model { /// <summary> /// This is the response object from the GetAccessPoint operation. /// </summary> public partial class GetAccessPointResponse : AmazonWebServiceResponse { private string _bucket; private DateTime? _creationDate; private string _name; private NetworkOrigin _networkOrigin; private PublicAccessBlockConfiguration _publicAccessBlockConfiguration; private VpcConfiguration _vpcConfiguration; /// <summary> /// Gets and sets the property Bucket. /// <para> /// The name of the bucket associated with the specified access point. /// </para> /// </summary> [AWSProperty(Min=3, Max=255)] public string Bucket { get { return this._bucket; } set { this._bucket = value; } } // Check to see if Bucket property is set internal bool IsSetBucket() { return this._bucket != null; } /// <summary> /// Gets and sets the property CreationDate. /// <para> /// The date and time when the specified access point was created. /// </para> /// </summary> public DateTime CreationDate { get { return this._creationDate.GetValueOrDefault(); } set { this._creationDate = value; } } // Check to see if CreationDate property is set internal bool IsSetCreationDate() { return this._creationDate.HasValue; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the specified access point. /// </para> /// </summary> [AWSProperty(Min=3, Max=50)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property NetworkOrigin. /// <para> /// Indicates whether this access point allows access from the public internet. If <code>VpcConfiguration</code> /// is specified for this access point, then <code>NetworkOrigin</code> is <code>VPC</code>, /// and the access point doesn't allow access from the public internet. Otherwise, <code>NetworkOrigin</code> /// is <code>Internet</code>, and the access point allows access from the public internet, /// subject to the access point and bucket access policies. /// </para> /// </summary> public NetworkOrigin NetworkOrigin { get { return this._networkOrigin; } set { this._networkOrigin = value; } } // Check to see if NetworkOrigin property is set internal bool IsSetNetworkOrigin() { return this._networkOrigin != null; } /// <summary> /// Gets and sets the property PublicAccessBlockConfiguration. /// </summary> public PublicAccessBlockConfiguration PublicAccessBlockConfiguration { get { return this._publicAccessBlockConfiguration; } set { this._publicAccessBlockConfiguration = value; } } // Check to see if PublicAccessBlockConfiguration property is set internal bool IsSetPublicAccessBlockConfiguration() { return this._publicAccessBlockConfiguration != null; } /// <summary> /// Gets and sets the property VpcConfiguration. /// <para> /// Contains the virtual private cloud (VPC) configuration for the specified access point. /// </para> /// </summary> public VpcConfiguration VpcConfiguration { get { return this._vpcConfiguration; } set { this._vpcConfiguration = value; } } // Check to see if VpcConfiguration property is set internal bool IsSetVpcConfiguration() { return this._vpcConfiguration != null; } } }
33.071429
120
0.606715
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/S3Control/Generated/Model/GetAccessPointResponse.cs
5,093
C#
using UnityEngine; using TMPro; using NonStandard.Ui; using NonStandard.Data.Parse; using UnityEngine.UI; using System.Collections.Generic; using System; using System.Reflection; using NonStandard.Data; using NonStandard.Utility.UnityEditor; using NonStandard.Extension; using NonStandard.Process; namespace NonStandard.GameUi.DataSheet { public class ColumnHeaderEditor : MonoBehaviour { public ModalConfirmation confirmRemoveUi; public GameObject columnHeaderObject; private ColumnHeader cHeader; public UnityDataSheet uds; public int column; public Type expectedValueType; [System.Serializable] public struct ValidColumnEntry { public string name; public GameObject uiField; } public List<ValidColumnEntry> columnTypes = new List<ValidColumnEntry>(); public Color errorColor = new Color(1,.75f,.75f); // compiles Token. errors make the field pink, and display the error popup. if valid, refresh valueType dropdown public TMP_InputField scriptValue; public UiHoverPopup popup; public TMP_InputField columnLabel; // TODO pick option from validColumnTypes public TMP_Dropdown fieldType; // TODO another scripted value. should also use error popup public TMP_InputField defaultValue; // TODO generate based on scriptValue. if type is ambiguous, offer [string, number, integer, Token] public TMP_Dropdown valueType; // change cHeader.columnSetting.data.width, refresh rows public TMP_InputField columnWidth; // ignore erroneous values. move column and refresh on change. public TMP_InputField columnIndex; // TODO confirm dialog. if confirmed, remove from UnityDataSheet and update everything public Button trashColumn; public void Start() { popup.defaultColor = scriptValue.GetComponent<Image>().color; } public void ClearInputTextBoxListeners() { TMP_InputField elementUiInputField = fieldType.GetComponentInChildren<TMP_InputField>(); if (elementUiInputField != null) { //elementUiInputField.onValueChanged.RemoveAllListeners(); // not enough to remove all listeners apparently. elementUiInputField.onValueChanged = new TMP_InputField.OnChangeEvent(); //Show.Log("unbind from "+elementUiInputField.name); } scriptValue.onValueChanged.RemoveAllListeners(); columnLabel.onValueChanged.RemoveAllListeners(); columnWidth.onValueChanged.RemoveAllListeners(); columnIndex.onValueChanged.RemoveAllListeners(); defaultValue.onValueChanged.RemoveAllListeners(); trashColumn.onClick.RemoveAllListeners(); } public void SetColumnHeader(ColumnHeader columnHeader, UnityDataSheet uds, int column) { // unregister listeners before values change, since values are about to change. ClearInputTextBoxListeners(); this.uds = uds; this.column = column; cHeader = columnHeader; TokenErrorLog errLog = new TokenErrorLog(); // setup script value Token t = cHeader.columnSetting.fieldToken; //string textA = t.GetAsSmallText(); //string textB = t.Stringify(); //string textC = t.StringifySmall(); //string textD = t.ToString(); string text = t.GetAsBasicToken(); //Show.Log("A: "+textA+"\nB:" + textB + "\nC:" + textC + "\nD:" + textD + "\nE:" + text); scriptValue.text = text; EventBind.On(scriptValue.onValueChanged, this, OnScriptValueEdit); // implicitly setup value types dropdown OnScriptValueEdit(text); // setup column label object labelText = cHeader.columnSetting.data.label.Resolve(errLog, uds.data); if (errLog.HasError()) { popup.Set("err", defaultValue.gameObject, errLog.GetErrorString()+Proc.Now); return; } columnLabel.text = labelText.StringifySmall(); EventBind.On(columnLabel.onValueChanged, this, OnLabelEdit); // setup column width columnWidth.text = cHeader.columnSetting.data.widthOfColumn.ToString(); EventBind.On(columnWidth.onValueChanged, this, OnColumnWidthEdit); // setup column index columnIndex.text = column.ToString(); EventBind.On(columnIndex.onValueChanged, this, OnIndexEdit); // setup column type List<ModalConfirmation.Entry> entries = columnTypes.ConvertAll(c => { string dropdownLabel; if(c.uiField != null && !string.IsNullOrEmpty(c.name)) { dropdownLabel = "/*" + c.name + "*/ " + c.uiField.name; } else { dropdownLabel = c.name; } return new ModalConfirmation.Entry(dropdownLabel, null); }); t = cHeader.columnSetting.data.columnUi; string fieldTypeText = t.ToString();//cHeader.columnSetting.data.columnUi.GetAsBasicToken();//ResolveString(errLog, null); int currentIndex = columnTypes.FindIndex(c=> fieldTypeText.StartsWith(c.uiField.name)) + 1; //Show.Log(currentIndex+" field " + fieldTypeText); DropDownEvent.PopulateDropdown(fieldType, entries, this, SetFieldType, currentIndex, true); if (currentIndex == 0) { DropDownEvent.SetCustomValue(fieldType.gameObject, fieldTypeText); } TMP_InputField elementUiInputField = fieldType.GetComponentInChildren<TMP_InputField>(); if (elementUiInputField != null) { elementUiInputField.onValueChanged.RemoveAllListeners(); //Show.Log("bind to "+elementUiInputField.name); EventBind.On(elementUiInputField.onValueChanged, this, OnSetFieldTypeText); } // setup default value object defVal = cHeader.columnSetting.defaultValue; if (defVal != null) { defaultValue.text = defVal.ToString(); } else { defaultValue.text = ""; } EventBind.On(defaultValue.onValueChanged, this, OnSetDefaultValue); // setup column destroy option EventBind.On(trashColumn.onClick, this, ColumnRemove); popup.Hide(); } public void OnSetFieldTypeText(string text) { //Show.Log("fieldTypeGettingSet? " + this.fieldType.itemText.text+ " " + text); if (!gameObject.activeInHierarchy) { return; } if (SetFieldTypeText(text)) { uds.RefreshRowAndColumnUi(); } } public bool SetFieldTypeText(string text) { Tokenizer tokenizer = Tokenizer.Tokenize(text); if (tokenizer.HasError()) { popup.Set("err", defaultValue.gameObject, tokenizer.GetErrorString() + Proc.Now); return false; } Token t = Token.None; List<Token> tokens = Data.Parse.SyntaxTree.FindSubstantiveTerms(tokenizer.Tokens); // ignore comments! switch (tokens.Count) { case 0: break; case 1: t = tokens[0]; break; default: t = Tokenizer.GetMasterToken(tokens, text); break; } //Show.Log("SetFieldTypeText " + text+" -> "+t.GetAsBasicToken()+"\n"+tokenizer.GetMasterToken().Resolve(tokenizer, null).Stringify()); cHeader.columnSetting.data.columnUi = t; popup.Hide(); return true; } public void OnSetDefaultValue(string text) { object value = null; Tokenizer tokenizer = new Tokenizer(); CodeConvert.TryParseType(expectedValueType, text, ref value, null, tokenizer); // parse errors if (tokenizer.HasError()) { popup.Set("err", defaultValue.gameObject, tokenizer.GetErrorString()); return; } cHeader.columnSetting.defaultValue = value; popup.Hide(); } public void SetFieldType(int index) { // initial value is for custom text if (index == 0) { if (!SetFieldTypeText(UiText.GetText(fieldType.gameObject))) { return; } } else if (index >= 1 && columnTypes[index-1].uiField != null) { cHeader.columnSetting.data.columnUi = new Token(columnTypes[index-1].uiField.name); } uds.RefreshRowAndColumnUi(); } public void OnLabelEdit(string text) { Tokenizer tokenizer = Tokenizer.Tokenize(text); if (tokenizer.HasError()) { popup.Set("err", defaultValue.gameObject, tokenizer.GetErrorString()); return; } Token token = Token.None; switch (tokenizer.Tokens.Count) { case 0: break; case 1: token = tokenizer.Tokens[0]; break; default: token = new Token(text); break; } cHeader.columnSetting.data.label = token; object result = token.Resolve(tokenizer, uds.data); if (tokenizer.HasError()) { popup.Set("err", defaultValue.gameObject, tokenizer.GetErrorString()); return; } string resultText = result?.ToString() ?? ""; UiText.SetText(cHeader.gameObject, resultText); popup.Hide(); } public void OnColumnWidthEdit(string text) { float oldWidth = cHeader.columnSetting.data.widthOfColumn; if (float.TryParse(text, out float newWidth)) { if (newWidth > 0 && newWidth < 2048) { uds.ResizeColumnWidth(column, oldWidth, newWidth); } else { popup.Set("err", columnWidth.gameObject, "invalid width: " + newWidth + ". Requirement: 0 < value < 2048"); return; } } popup.Hide(); } public void OnIndexEdit(string text) { int oldIndex = cHeader.transform.GetSiblingIndex(); if (oldIndex != column) { popup.Set("err", columnIndex.gameObject, "WOAH PROBLEM! column " + column + " is not the same as childIndex " + oldIndex); return; } int max = uds.GetMaximumUserColumn(); if (int.TryParse(text, out int newIndex)) { if (newIndex > 0 && newIndex < max) { uds.MoveColumn(oldIndex, newIndex); column = newIndex; } else { popup.Set("err", columnIndex.gameObject,"invalid index: " + newIndex + ". Requirement: 0 < index < " + max); return; } } popup.Hide(); } public void OnScriptValueEdit(string fieldScript) { Tokenizer tokenizer = new Tokenizer(); tokenizer.Tokenize(fieldScript); GameObject go = scriptValue.gameObject; // parse errors if (tokenizer.HasError()) { popup.Set("err", go, tokenizer.GetErrorString()); return; } // just one token if (tokenizer.Tokens.Count > 1) { popup.Set("err", go, "too many tokens: should only be one value"); return; } // try to set the field based on field script if(!ProcessFieldScript(tokenizer)) return; // refresh column values uds.RefreshColumnText(column, tokenizer); // failed to set values if (tokenizer.HasError()) { popup.Set("err", go, tokenizer.GetErrorString()); return; } // success! popup.Hide(); } private bool ProcessFieldScript(Tokenizer tokenizer) { if (tokenizer.Tokens.Count == 0) { expectedValueType = null; cHeader.columnSetting.editPath = null; return false; } object value = cHeader.columnSetting.SetFieldToken(tokenizer.Tokens[0], tokenizer); // update the expected edit type SetExpectedEditType(value); // valid variable path if (tokenizer.HasError()) { popup.Set("err", scriptValue.gameObject, tokenizer.GetErrorString()); return false; } popup.Hide(); return true; } public void SetExpectedEditType(object sampleValue) { Type sampleValueType = GetEditType(); if (sampleValueType == null) { // set to read only expectedValueType = null; DropDownEvent.PopulateDropdown(valueType, new string[] { "read only" }, this, null, 0, false); } else { if (sampleValueType != expectedValueType) { // set to specific type if (sampleValueType == typeof(object)) { sampleValueType = sampleValue.GetType(); int defaultChoice = -1; if (defaultChoice < 0 && CodeConvert.IsIntegral(sampleValueType)) { defaultChoice = defaultValueTypes.FindIndex(kvp=>kvp.Key == typeof(long)); } if (defaultChoice < 0 && CodeConvert.IsNumeric(sampleValueType)) { defaultChoice = defaultValueTypes.FindIndex(kvp => kvp.Key == typeof(double)); } if (defaultChoice < 0) {// && sampleValueType == typeof(string)) { defaultChoice = defaultValueTypes.FindIndex(kvp => kvp.Key == typeof(string)); } List<string> options = defaultValueTypes.ConvertAll(kvp => kvp.Value); DropDownEvent.PopulateDropdown(valueType, options, this, SetEditType, defaultChoice, true); cHeader.columnSetting.type = defaultValueTypes[defaultChoice].Key; } else { DropDownEvent.PopulateDropdown(valueType, new string[] { sampleValueType.ToString() }, this, null, 0, false); cHeader.columnSetting.type = sampleValueType; } expectedValueType = sampleValueType; } } } public Type GetEditType() { List<object> editPath = cHeader.columnSetting.editPath; if (editPath == null || editPath.Count == 0) { return null; } else { object lastPathComponent = editPath[editPath.Count - 1]; switch (lastPathComponent) { case FieldInfo fi: return fi.FieldType; case PropertyInfo pi: return pi.PropertyType; case string s: return typeof(object); } } return null; } private void SetEditType(int index) { cHeader.columnSetting.type = defaultValueTypes[index].Key; } private static List<KeyValuePair<Type, string>> defaultValueTypes = new List<KeyValuePair<Type, string>> { new KeyValuePair<Type, string>(typeof(object), "unknown"), new KeyValuePair<Type, string>(typeof(string), "string"), new KeyValuePair<Type, string>(typeof(double),"number"), new KeyValuePair<Type, string>(typeof(long),"integer"), new KeyValuePair<Type, string>(typeof(Token), "script"), new KeyValuePair<Type, string>(null, "read only"), }; public void ColumnRemove() { ModalConfirmation ui = confirmRemoveUi; if (ui == null) { ui = Global.GetComponent<ModalConfirmation>(); } DataSheetUnityColumnData.ColumnSetting cS = uds.GetColumn(column); ui.OkCancel("Are you sure you want to delete column \"" + cS.data.label + "\"?", () => { uds.RemoveColumn(column); Close(); }); uds.RefreshUi(); } public void Close() { ClearInputTextBoxListeners(); gameObject.SetActive(false); } } }
41.468944
138
0.710327
[ "Unlicense" ]
mvaganov/NonStandardDataSheet
Scripts/NonStandardUnity/DataSheet/ColumnHeaderEditor.cs
13,355
C#
 using WASApiBassNet.Components.AudioCapture; using WPFUtilities.ComponentModel; namespace WindowsAudioSession.UI.FFT { /// <summary> /// fft view model /// </summary> public interface IFFTViewModel : IModelBase, IValidableModel, IAudioPlugin { /// <summary> /// bar count /// </summary> int BarCount { get; set; } /// <summary> /// bar width percent /// </summary> int BarWidthPercent { get; set; } } }
19.88
78
0.577465
[ "MIT" ]
franck-gaspoz/WindowsAudioSessionSample
WindowsAudioSession/UI/FFT/IFFTViewModel.cs
499
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; namespace Azure.Security.Attestation.Models { public partial class TpmAttestationRequest : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Optional.IsDefined(InternalData)) { writer.WritePropertyName("data"); writer.WriteStringValue(InternalData); } writer.WriteEndObject(); } } }
24.259259
70
0.636641
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/attestation/Azure.Security.Attestation/src/Generated/Models/TpmAttestationRequest.Serialization.cs
655
C#
/* Copyright 2018 [andriniaina](https://github.com/andriniaina/Farmhash.Sharp.HashObject/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Farmhash.Sharp { public class HashObject { /* static void Main() { } */ static Func<System.Reflection.PropertyInfo, bool> ACCEPT_ALL = p => true; static Dictionary<Tuple<Type, int>, List<Func<object, IEnumerable<byte>>>> functionCache = new Dictionary<Tuple<Type, int>, List<Func<object, IEnumerable<byte>>>>(); public static ulong Hash64<T>(T o) { return Hash64(o, ACCEPT_ALL); } public static ulong Hash64<T>(T o, Func<System.Reflection.PropertyInfo, bool> propertyFilter) { List<Func<object, IEnumerable<byte>>> functions = GetCachedCompiledHashFunctions<T>(propertyFilter); var bytes = functions.SelectMany(f => f(o)).ToArray(); return Farmhash.Hash64(bytes, bytes.Length); } public static uint Hash32<T>(T o, Func<System.Reflection.PropertyInfo, bool> propertyFilter) { List<Func<object, IEnumerable<byte>>> functions = GetCachedCompiledHashFunctions<T>(propertyFilter); var bytes = functions.SelectMany(f => f(o)).ToArray(); return Farmhash.Hash32(bytes, bytes.Length); } public static int HashS32<T>(T o, Func<System.Reflection.PropertyInfo, bool> propertyFilter) { List<Func<object, IEnumerable<byte>>> functions = GetCachedCompiledHashFunctions<T>(propertyFilter); var bytes = functions.SelectMany(f => f(o)).ToArray(); var uhash = Farmhash.Hash32(bytes, bytes.Length); var hash = BitConverter.ToInt32(BitConverter.GetBytes(uhash), 0); return hash; } private static List<Func<object, IEnumerable<byte>>> GetCachedCompiledHashFunctions<T>(Func<System.Reflection.PropertyInfo, bool> propertyFilter) { var cacheKey = Tuple.Create(typeof(T), propertyFilter.GetHashCode()); List<Func<object, IEnumerable<byte>>> functions; if (!functionCache.TryGetValue(cacheKey, out functions)) { lock (functionCache) if (!functionCache.TryGetValue(cacheKey, out functions)) { functions = BuildHashFunctionsWrapped<T>(propertyFilter).Select(f => f.Compile()).ToList(); if (functions.Count == 0) throw new NotSupportedException("no hash function found"); functionCache.Add(cacheKey, functions); } } return functions; } internal static ulong Hash64_NoCache_forBenchmarks<T>(T o) { IEnumerable<Func<object, IEnumerable<byte>>> functions; functions = BuildHashFunctionsWrapped<T>(ACCEPT_ALL).Select(f => f.Compile()).ToList(); var bytes = functions.SelectMany(f => f(o)).ToArray(); return Farmhash.Hash64(bytes, bytes.Length); } private static IEnumerable<Expression<Func<object, IEnumerable<byte>>>> BuildHashFunctionsWrapped<T>(Func<System.Reflection.PropertyInfo, bool> propertyFilter) { var t = typeof(T); var xExpr = Expression.Parameter(typeof(object), "x"); var xExprCasted = Expression.Convert(xExpr, t); var castedVariableExpr = Expression.Variable(t, "castedVariable"); var assignement = Expression.Assign(castedVariableExpr, xExprCasted); foreach (var expr in BuildHashLambdas(t, propertyFilter)) { var block = Expression.Block(new ParameterExpression[] { castedVariableExpr }, assignement, Expression.Invoke(expr, castedVariableExpr)); var xx = Expression.Lambda<Func<object, IEnumerable<byte>>>(block, xExpr); yield return xx; } } private static IEnumerable<LambdaExpression> BuildHashLambdas(Type t, Func<System.Reflection.PropertyInfo, bool> propertyFilter) { var xInputParameter = Expression.Parameter(t, "input"); LambdaExpression extractBytesExpr = null; if (t == typeof(bool)) { extractBytesExpr = BoolToBytesExpr; } else if (t == typeof(byte)) { extractBytesExpr = ByteToBytesExpr; } else if (t == typeof(sbyte)) { extractBytesExpr = SByteToBytesExpr; } else if (t == typeof(short)) { extractBytesExpr = ShortToBytesExpr; } else if (t == typeof(ushort)) { extractBytesExpr = UShortToBytesExpr; } else if (t == typeof(int)) { extractBytesExpr = Int32ToBytesExpr; } else if (t == typeof(uint)) { extractBytesExpr = UInt32ToBytesExpr; } else if (t == typeof(long)) { extractBytesExpr = Int64ToBytesExpr; } else if (t == typeof(ulong)) { extractBytesExpr = UInt64ToBytesExpr; } else if (t == typeof(float)) { extractBytesExpr = FloatToBytesExpr; } else if (t == typeof(double)) { extractBytesExpr = DoubleToBytesExpr; } else if (t == typeof(decimal)) { extractBytesExpr = DecimalToBytesExpr; } else if (t == typeof(char)) { extractBytesExpr = CharToBytesExpr; } else if (t == typeof(string)) { extractBytesExpr = StringToBytesExpr; } else if (t == typeof(DateTime)) { extractBytesExpr = DateTimeToBytesExpr; } else if (t.IsEnum) { var xExprCasted = Expression.Convert(xInputParameter, typeof(IConvertible)); var castedVariableExpr = Expression.Variable(typeof(IConvertible), "castedVariable"); var assignement = Expression.Assign(castedVariableExpr, xExprCasted); var block = Expression.Block(new ParameterExpression[] { castedVariableExpr }, assignement, Expression.Invoke(IConvertibleToBytesExpr, castedVariableExpr)); extractBytesExpr = Expression.Lambda(block, xInputParameter); } else if (IsGenericIDict(t) || t.GetInterfaces().Any(IsGenericIDict)) { var pExprKeys = Expression.Property(xInputParameter, "Keys"); var pExprValues = Expression.Property(xInputParameter, "Values"); var subexprKeys = BuildHashLambdas(t.GetProperty("Keys").PropertyType, propertyFilter); foreach (var e in subexprKeys) { yield return Expression.Lambda(Expression.Invoke(e, pExprKeys), xInputParameter); } var subexprValues = BuildHashLambdas(t.GetProperty("Values").PropertyType, propertyFilter); foreach (var e in subexprValues) { yield return Expression.Lambda(Expression.Invoke(e, pExprValues), xInputParameter); } yield break;// throw new NotImplementedException(); } else if (t.IsGenericType && typeof(IEnumerable).IsAssignableFrom(t.GetGenericTypeDefinition())) { Type underlyingType = t.GetGenericArguments()[0]; var subexpr = BuildHashLambdas(underlyingType, propertyFilter); foreach (var e in subexpr) { var pBoxedUnderlyingObject = Expression.Parameter(typeof(object), "boxedUnderlyingObject"); var xExprCasted = Expression.Convert(pBoxedUnderlyingObject, underlyingType); var castedVariableExpr = Expression.Variable(underlyingType, "castedVariable"); var assignement = Expression.Assign(castedVariableExpr, xExprCasted); var block = Expression.Block(new ParameterExpression[] { castedVariableExpr }, assignement, Expression.Invoke(e, castedVariableExpr)); var xxxxx = Expression.Lambda<Func<object, IEnumerable<byte>>>(block, pBoxedUnderlyingObject); var converter = xxxxx.Compile(); var f = GetIEnumerableToBytes(converter); yield return f; } yield break; } else if (typeof(object).IsAssignableFrom(t)) { foreach (var pInfo in t.GetProperties().Where(propertyFilter)) { Expression pExpr = Expression.Property(xInputParameter, pInfo); var subexpr = BuildHashLambdas(pInfo.PropertyType, propertyFilter); foreach (var e in subexpr) { /* var xxInputParameter = Expression.Parameter(t, "xx"); var xxxxx = Expression.Lambda(Expression.Invoke(e, pExpr), xInputParameter); yield return xxxxx; */ var xxInputParameter = Expression.Parameter(t, "xx"); var ifNotNull = Expression.Invoke(e, pExpr); var ifNull = Expression.Constant(new byte[0], typeof(IEnumerable<byte>)); var xxxxx = Expression.Condition(Expression.Equal(xInputParameter, NULL), ifNull, ifNotNull); yield return Expression.Lambda(xxxxx, xInputParameter); } } yield break; } else { throw new NotImplementedException($"type {t} is not supported"); } yield return extractBytesExpr; } private static bool IsGenericIDict(Type t) { return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IDictionary<,>); } private static Expression<Func<IEnumerable, IEnumerable<byte>>> GetIEnumerableToBytes(Func<object, IEnumerable<byte>> converter) { Expression<Func<System.Collections.IEnumerable, IEnumerable<byte>>> expr = d => GetBytes(d, converter); return expr; } private static IEnumerable<byte> GetBytes(IEnumerable d, Func<object, IEnumerable<byte>> f) { foreach (var item in d) { foreach (var b in f(item)) { yield return b; } } } private static IEnumerable<byte> GetDecimalBytes(decimal d) { foreach (var i in Decimal.GetBits(d)) foreach (var b in BitConverter.GetBytes(i)) yield return b; } static readonly ConstantExpression NULL = Expression.Constant(null, typeof(object)); static readonly Expression<Func<DateTime, IEnumerable<byte>>> DateTimeToBytesExpr = i => BitConverter.GetBytes(i.Ticks); static readonly Expression<Func<IConvertible, IEnumerable<byte>>> IConvertibleToBytesExpr = i => BitConverter.GetBytes(Convert.ToInt64(i)); static readonly Expression<Func<bool, IEnumerable<byte>>> BoolToBytesExpr = i => BitConverter.GetBytes(i); static readonly Expression<Func<byte, IEnumerable<byte>>> ByteToBytesExpr = i => BitConverter.GetBytes(i); static readonly Expression<Func<sbyte, IEnumerable<byte>>> SByteToBytesExpr = i => BitConverter.GetBytes(i); static readonly Expression<Func<short, IEnumerable<byte>>> ShortToBytesExpr = i => BitConverter.GetBytes(i); static readonly Expression<Func<ushort, IEnumerable<byte>>> UShortToBytesExpr = i => BitConverter.GetBytes(i); static readonly Expression<Func<int, IEnumerable<byte>>> Int32ToBytesExpr = i => BitConverter.GetBytes(i); static readonly Expression<Func<uint, IEnumerable<byte>>> UInt32ToBytesExpr = i => BitConverter.GetBytes(i); static readonly Expression<Func<long, IEnumerable<byte>>> Int64ToBytesExpr = i => BitConverter.GetBytes(i); static readonly Expression<Func<ulong, IEnumerable<byte>>> UInt64ToBytesExpr = i => BitConverter.GetBytes(i); static readonly Expression<Func<char, IEnumerable<byte>>> CharToBytesExpr = c => BitConverter.GetBytes(c); static readonly Expression<Func<double, IEnumerable<byte>>> DoubleToBytesExpr = s => BitConverter.GetBytes(s); static readonly Expression<Func<decimal, IEnumerable<byte>>> DecimalToBytesExpr = d => GetDecimalBytes(d); static readonly Expression<Func<float, IEnumerable<byte>>> FloatToBytesExpr = s => BitConverter.GetBytes(s); static readonly Expression<Func<string, IEnumerable<byte>>> StringToBytesExpr = s => s == null ? new byte[0] : Encoding.UTF8.GetBytes(s); } }
50.802817
460
0.604242
[ "Unlicense" ]
andriniaina/Farmhash.Sharp.HashObject
Farmhash.Sharp.HashObject/HashObject.cs
14,430
C#
using System; namespace SCHOTT.Core.Extensions { /// <summary> /// A class of double extensions. /// </summary> public static class DoubleExtensions { private const double DoubleTolerance = 0.001; /// <summary> /// Checks if a double is within a tolerance of an integer value. /// </summary> /// <param name="numberToTest">The double to test.</param> /// <param name="testValue">The integer to compare against.</param> /// <returns>True if testValue is within tolerance of numberToTest.</returns> public static bool EqualsInt(this double numberToTest, int testValue) { return Math.Abs(numberToTest - testValue) < DoubleTolerance; } /// <summary> /// Checks if a double is within a tolerance of an bool value. /// </summary> /// <param name="numberToTest">The double to test.</param> /// <param name="testValue">The bool to compare against.</param> /// <returns>True if testValue is within tolerance of numberToTest.</returns> public static bool EqualsBool(this double numberToTest, bool testValue) { return Math.Abs(numberToTest - (testValue ? 1 : 0)) < DoubleTolerance; } /// <summary> /// Checks if a double is within a tolerance of an double value. /// </summary> /// <param name="numberToTest">The double to test.</param> /// <param name="testValue">The double to compare against.</param> /// <returns>True if testValue is within tolerance of numberToTest.</returns> public static bool EqualsDouble(this double numberToTest, double testValue) { return Math.Abs(numberToTest - testValue) < DoubleTolerance; } } }
39.23913
85
0.61662
[ "MIT" ]
SCHOTTNorthAmerica/SCHOTT.Core
SCHOTT/Core/Extensions/Numbers.cs
1,807
C#
/* Copyright 2019 Pitney Bowes Inc. Licensed under the MIT License(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the README file or at https://opensource.org/licenses/MIT 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. 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. */ namespace PitneyBowes.Developer.ShippingApi.Rules { /// <summary> /// Country class - downloaded and cached. /// </summary> public class Country { /// <summary> /// Gets or sets the country code. /// </summary> /// <value>The country code.</value> virtual public string CountryCode { get; set; } /// <summary> /// Gets or sets the name of the country. /// </summary> /// <value>The name of the country.</value> virtual public string CountryName { get; set; } } }
44.444444
120
0.70625
[ "MIT-0", "MIT" ]
PitneyBowes/pitneybowes-shipping-api-csharp
src/rules/Country.cs
1,602
C#
// // Authors: // Rafael Mizrahi <rafim@mainsoft.com> // Erez Lotan <erezl@mainsoft.com> // Vladimir Krasnov <vladimirk@mainsoft.com> // // // Copyright (c) 2002-2005 Mainsoft Corporation. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Collections; namespace GHTTests.System_Web_dll.System_Web_UI_WebControls { public class WebControl_TableStyle_CellSpacing : GHTWebControlBase { #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion //Overrides GHTWebControlBase.InitTypes //This method initializes the types that will be contained in the TypesToTest array. //This only controls that TableStyle is relevant for, will be tested. protected override void InitTypes() { base.m_derivedTypes = new ArrayList(); base.m_derivedTypes.Add(typeof(RadioButtonList)); base.m_derivedTypes.Add(typeof(CheckBoxList)); base.m_derivedTypes.Add(typeof(DataGrid)); base.m_derivedTypes.Add(typeof(DataList)); base.m_derivedTypes.Add(typeof(Table)); } private void Page_Load(object sender, System.EventArgs e) { HtmlForm frm = (HtmlForm)FindControl("Form1"); GHTTestBegin(frm); foreach (Type currentType in TypesToTest) { GHTHeader(currentType.ToString()); Test(currentType); } GHTTestEnd(); } private void Test(Type ctrlType) { TableStyle style1; try { this.GHTSubTestBegin(ctrlType, "Legal value."); style1 = (TableStyle) this.TestedControl.ControlStyle; style1.CellSpacing = 10; } catch (Exception exception7) { // ProjectData.SetProjectError(exception7); Exception exception1 = exception7; this.GHTSubTestUnexpectedExceptionCaught(exception1); // ProjectData.ClearProjectError(); } this.GHTSubTestEnd(); try { this.GHTSubTestBegin(ctrlType, "Zero."); style1 = (TableStyle) this.TestedControl.ControlStyle; style1.CellSpacing = 0; } catch (Exception exception8) { // ProjectData.SetProjectError(exception8); Exception exception2 = exception8; this.GHTSubTestUnexpectedExceptionCaught(exception2); // ProjectData.ClearProjectError(); } this.GHTSubTestEnd(); try { this.GHTSubTestBegin(ctrlType, "-1."); style1 = (TableStyle) this.TestedControl.ControlStyle; style1.CellSpacing = -1; } catch (Exception exception9) { // ProjectData.SetProjectError(exception9); Exception exception3 = exception9; this.GHTSubTestUnexpectedExceptionCaught(exception3); // ProjectData.ClearProjectError(); } this.GHTSubTestEnd(); try { this.GHTSubTestBegin(ctrlType, "check that default is -1."); style1 = (TableStyle) this.TestedControl.ControlStyle; this.GHTSubTestAddResult(style1.CellSpacing.ToString()); } catch (Exception exception10) { // ProjectData.SetProjectError(exception10); Exception exception4 = exception10; this.GHTSubTestUnexpectedExceptionCaught(exception4); // ProjectData.ClearProjectError(); } this.GHTSubTestEnd(); try { this.GHTSubTestBegin(ctrlType, "Throws an exception if set to less then -1."); style1 = (TableStyle) this.TestedControl.ControlStyle; style1.CellSpacing = -2; this.GHTSubTestExpectedExceptionNotCaught("ArgumentOutOfRangeException"); } catch (ArgumentOutOfRangeException exception11) { // ProjectData.SetProjectError(exception11); ArgumentOutOfRangeException exception5 = exception11; this.GHTSubTestExpectedExceptionCaught(exception5); // ProjectData.ClearProjectError(); } catch (Exception exception12) { // ProjectData.SetProjectError(exception12); Exception exception6 = exception12; this.GHTSubTestUnexpectedExceptionCaught(exception6); // ProjectData.ClearProjectError(); } this.GHTSubTestEnd(); } } }
31.538012
86
0.724828
[ "Apache-2.0" ]
121468615/mono
mcs/class/System.Web/Test/mainsoft/MainsoftWebApp/System_Web_UI_WebControls/WebControl/WebControl_TableStyle_CellSpacing.aspx.cs
5,393
C#
namespace Titan.Assets { // TODO: this should be generated by the source generator, but it mess up the IDE coloring so I've disabled it. public enum AssetTypes { VertexShader, PixelShader, Texture, Model, Material, Atlas, Font, Count } }
20.125
115
0.565217
[ "MIT" ]
Golle/Titan
src/Titan.Assets/AssetTypes.cs
322
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 ISTC.FourthStage.Database.EF.DatabaseFirst2 { using System; using System.Collections.Generic; public partial class LinkedinEducation { public int Id { get; set; } public string Name { get; set; } public string Time { get; set; } public int LinkedinProfileId { get; set; } public string Title { get; set; } public virtual LinkedinProfile LinkedinProfile { get; set; } } }
33.961538
85
0.537939
[ "MIT" ]
VanHakobyan/ISTC_Coding_School
ISTC.FourthStage.Database/ISTC.FourthStage.Database.EF.DatabaseFirst2/LinkedinEducation.cs
883
C#
// Copyright (C) 2014 dot42 // // Original filename: Android.Location.cs // // 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. #pragma warning disable 1717 namespace Android.Location { /// <summary> /// <para>Used for receiving notifications from the LocationManager when the location has changed. These methods are called if the LocationListener has been registered with the location manager service using the LocationManager#requestLocationUpdates(String, long, float, LocationListener) method.</para><para> <h3>Developer Guides</h3></para><para> </para><para>For more information about identifying user location, read the developer guide.</para><para> </para> /// </summary> /// <java-name> /// android/location/LocationListener /// </java-name> [Dot42.DexImport("android/location/LocationListener", AccessFlags = 1537)] public partial interface ILocationListener /* scope: __dot42__ */ { /// <summary> /// <para>Called when the location has changed.</para><para>There are no restrictions on the use of the supplied Location object.</para><para></para> /// </summary> /// <java-name> /// onLocationChanged /// </java-name> [Dot42.DexImport("onLocationChanged", "(Landroid/location/Location;)V", AccessFlags = 1025)] void OnLocationChanged(global::Android.Location.Location location) /* MethodBuilder.Create */ ; /// <summary> /// <para>Called when the provider status changes. This method is called when a provider is unable to fetch a location or if the provider has recently become available after a period of unavailability.</para><para></para><para>A number of common key/value pairs for the extras Bundle are listed below. Providers that use any of the keys on this list must provide the corresponding value as described below.</para><para><ul><li><para>satellites - the number of satellites used to derive the fix </para></li></ul></para> /// </summary> /// <java-name> /// onStatusChanged /// </java-name> [Dot42.DexImport("onStatusChanged", "(Ljava/lang/String;ILandroid/os/Bundle;)V", AccessFlags = 1025)] void OnStatusChanged(string provider, int status, global::Android.Os.Bundle extras) /* MethodBuilder.Create */ ; /// <summary> /// <para>Called when the provider is enabled by the user.</para><para></para> /// </summary> /// <java-name> /// onProviderEnabled /// </java-name> [Dot42.DexImport("onProviderEnabled", "(Ljava/lang/String;)V", AccessFlags = 1025)] void OnProviderEnabled(string provider) /* MethodBuilder.Create */ ; /// <summary> /// <para>Called when the provider is disabled by the user. If requestLocationUpdates is called on an already disabled provider, this method is called immediately.</para><para></para> /// </summary> /// <java-name> /// onProviderDisabled /// </java-name> [Dot42.DexImport("onProviderDisabled", "(Ljava/lang/String;)V", AccessFlags = 1025)] void OnProviderDisabled(string provider) /* MethodBuilder.Create */ ; } /// <summary> /// <para>A class indicating the application criteria for selecting a location provider. Providers maybe ordered according to accuracy, power usage, ability to report altitude, speed, and bearing, and monetary cost. </para> /// </summary> /// <java-name> /// android/location/Criteria /// </java-name> [Dot42.DexImport("android/location/Criteria", AccessFlags = 33)] public partial class Criteria : global::Android.Os.IParcelable /* scope: __dot42__ */ { /// <summary> /// <para>A constant indicating that the application does not choose to place requirement on a particular feature. </para> /// </summary> /// <java-name> /// NO_REQUIREMENT /// </java-name> [Dot42.DexImport("NO_REQUIREMENT", "I", AccessFlags = 25)] public const int NO_REQUIREMENT = 0; /// <summary> /// <para>A constant indicating a low power requirement. </para> /// </summary> /// <java-name> /// POWER_LOW /// </java-name> [Dot42.DexImport("POWER_LOW", "I", AccessFlags = 25)] public const int POWER_LOW = 1; /// <summary> /// <para>A constant indicating a medium power requirement. </para> /// </summary> /// <java-name> /// POWER_MEDIUM /// </java-name> [Dot42.DexImport("POWER_MEDIUM", "I", AccessFlags = 25)] public const int POWER_MEDIUM = 2; /// <summary> /// <para>A constant indicating a high power requirement. </para> /// </summary> /// <java-name> /// POWER_HIGH /// </java-name> [Dot42.DexImport("POWER_HIGH", "I", AccessFlags = 25)] public const int POWER_HIGH = 3; /// <summary> /// <para>A constant indicating a finer location accuracy requirement </para> /// </summary> /// <java-name> /// ACCURACY_FINE /// </java-name> [Dot42.DexImport("ACCURACY_FINE", "I", AccessFlags = 25)] public const int ACCURACY_FINE = 1; /// <summary> /// <para>A constant indicating an approximate accuracy requirement </para> /// </summary> /// <java-name> /// ACCURACY_COARSE /// </java-name> [Dot42.DexImport("ACCURACY_COARSE", "I", AccessFlags = 25)] public const int ACCURACY_COARSE = 2; /// <summary> /// <para>A constant indicating a low location accuracy requirement<ul><li><para>may be used for horizontal, altitude, speed or bearing accuracy. For horizontal and vertical position this corresponds roughly to an accuracy of greater than 500 meters. </para></li></ul></para> /// </summary> /// <java-name> /// ACCURACY_LOW /// </java-name> [Dot42.DexImport("ACCURACY_LOW", "I", AccessFlags = 25)] public const int ACCURACY_LOW = 1; /// <summary> /// <para>A constant indicating a medium accuracy requirement<ul><li><para>currently used only for horizontal accuracy. For horizontal position this corresponds roughly to to an accuracy of between 100 and 500 meters. </para></li></ul></para> /// </summary> /// <java-name> /// ACCURACY_MEDIUM /// </java-name> [Dot42.DexImport("ACCURACY_MEDIUM", "I", AccessFlags = 25)] public const int ACCURACY_MEDIUM = 2; /// <summary> /// <para>a constant indicating a high accuracy requirement<ul><li><para>may be used for horizontal, altitude, speed or bearing accuracy. For horizontal and vertical position this corresponds roughly to an accuracy of less than 100 meters. </para></li></ul></para> /// </summary> /// <java-name> /// ACCURACY_HIGH /// </java-name> [Dot42.DexImport("ACCURACY_HIGH", "I", AccessFlags = 25)] public const int ACCURACY_HIGH = 3; /// <java-name> /// CREATOR /// </java-name> [Dot42.DexImport("CREATOR", "Landroid/os/Parcelable$Creator;", AccessFlags = 25)] public static readonly global::Android.Os.IParcelable_ICreator<global::Android.Location.Criteria> CREATOR; /// <summary> /// <para>Constructs a new Criteria object. The new object will have no requirements on accuracy, power, or response time; will not require altitude, speed, or bearing; and will not allow monetary cost. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public Criteria() /* MethodBuilder.Create */ { } /// <summary> /// <para>Constructs a new Criteria object that is a copy of the given criteria. </para> /// </summary> [Dot42.DexImport("<init>", "(Landroid/location/Criteria;)V", AccessFlags = 1)] public Criteria(global::Android.Location.Criteria criteria) /* MethodBuilder.Create */ { } /// <summary> /// <para>Indicates the desired horizontal accuracy (latitude and longitude). Accuracy may be ACCURACY_LOW, ACCURACY_MEDIUM, ACCURACY_HIGH or NO_REQUIREMENT. More accurate location may consume more power and may take longer.</para><para></para> /// </summary> /// <java-name> /// setHorizontalAccuracy /// </java-name> [Dot42.DexImport("setHorizontalAccuracy", "(I)V", AccessFlags = 1)] public virtual void SetHorizontalAccuracy(int accuracy) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns a constant indicating the desired horizontal accuracy (latitude and longitude). Accuracy may be ACCURACY_LOW, ACCURACY_MEDIUM, ACCURACY_HIGH or NO_REQUIREMENT. </para> /// </summary> /// <java-name> /// getHorizontalAccuracy /// </java-name> [Dot42.DexImport("getHorizontalAccuracy", "()I", AccessFlags = 1)] public virtual int GetHorizontalAccuracy() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Indicates the desired vertical accuracy (altitude). Accuracy may be ACCURACY_LOW, ACCURACY_MEDIUM, ACCURACY_HIGH or NO_REQUIREMENT. More accurate location may consume more power and may take longer.</para><para></para> /// </summary> /// <java-name> /// setVerticalAccuracy /// </java-name> [Dot42.DexImport("setVerticalAccuracy", "(I)V", AccessFlags = 1)] public virtual void SetVerticalAccuracy(int accuracy) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns a constant indicating the desired vertical accuracy (altitude). Accuracy may be ACCURACY_LOW, ACCURACY_HIGH, or NO_REQUIREMENT. </para> /// </summary> /// <java-name> /// getVerticalAccuracy /// </java-name> [Dot42.DexImport("getVerticalAccuracy", "()I", AccessFlags = 1)] public virtual int GetVerticalAccuracy() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Indicates the desired speed accuracy. Accuracy may be ACCURACY_LOW, ACCURACY_HIGH, or NO_REQUIREMENT. More accurate location may consume more power and may take longer.</para><para></para> /// </summary> /// <java-name> /// setSpeedAccuracy /// </java-name> [Dot42.DexImport("setSpeedAccuracy", "(I)V", AccessFlags = 1)] public virtual void SetSpeedAccuracy(int accuracy) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns a constant indicating the desired speed accuracy Accuracy may be ACCURACY_LOW, ACCURACY_HIGH, or NO_REQUIREMENT. </para> /// </summary> /// <java-name> /// getSpeedAccuracy /// </java-name> [Dot42.DexImport("getSpeedAccuracy", "()I", AccessFlags = 1)] public virtual int GetSpeedAccuracy() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Indicates the desired bearing accuracy. Accuracy may be ACCURACY_LOW, ACCURACY_HIGH, or NO_REQUIREMENT. More accurate location may consume more power and may take longer.</para><para></para> /// </summary> /// <java-name> /// setBearingAccuracy /// </java-name> [Dot42.DexImport("setBearingAccuracy", "(I)V", AccessFlags = 1)] public virtual void SetBearingAccuracy(int accuracy) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns a constant indicating the desired bearing accuracy. Accuracy may be ACCURACY_LOW, ACCURACY_HIGH, or NO_REQUIREMENT. </para> /// </summary> /// <java-name> /// getBearingAccuracy /// </java-name> [Dot42.DexImport("getBearingAccuracy", "()I", AccessFlags = 1)] public virtual int GetBearingAccuracy() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Indicates the desired accuracy for latitude and longitude. Accuracy may be ACCURACY_FINE if desired location is fine, else it can be ACCURACY_COARSE. More accurate location may consume more power and may take longer.</para><para></para> /// </summary> /// <java-name> /// setAccuracy /// </java-name> [Dot42.DexImport("setAccuracy", "(I)V", AccessFlags = 1)] public virtual void SetAccuracy(int accuracy) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns a constant indicating desired accuracy of location Accuracy may be ACCURACY_FINE if desired location is fine, else it can be ACCURACY_COARSE. </para> /// </summary> /// <java-name> /// getAccuracy /// </java-name> [Dot42.DexImport("getAccuracy", "()I", AccessFlags = 1)] public virtual int GetAccuracy() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Indicates the desired maximum power level. The level parameter must be one of NO_REQUIREMENT, POWER_LOW, POWER_MEDIUM, or POWER_HIGH. </para> /// </summary> /// <java-name> /// setPowerRequirement /// </java-name> [Dot42.DexImport("setPowerRequirement", "(I)V", AccessFlags = 1)] public virtual void SetPowerRequirement(int level) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns a constant indicating the desired power requirement. The returned </para> /// </summary> /// <java-name> /// getPowerRequirement /// </java-name> [Dot42.DexImport("getPowerRequirement", "()I", AccessFlags = 1)] public virtual int GetPowerRequirement() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Indicates whether the provider is allowed to incur monetary cost. </para> /// </summary> /// <java-name> /// setCostAllowed /// </java-name> [Dot42.DexImport("setCostAllowed", "(Z)V", AccessFlags = 1)] public virtual void SetCostAllowed(bool costAllowed) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns whether the provider is allowed to incur monetary cost. </para> /// </summary> /// <java-name> /// isCostAllowed /// </java-name> [Dot42.DexImport("isCostAllowed", "()Z", AccessFlags = 1)] public virtual bool IsCostAllowed() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Indicates whether the provider must provide altitude information. Not all fixes are guaranteed to contain such information. </para> /// </summary> /// <java-name> /// setAltitudeRequired /// </java-name> [Dot42.DexImport("setAltitudeRequired", "(Z)V", AccessFlags = 1)] public virtual void SetAltitudeRequired(bool altitudeRequired) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns whether the provider must provide altitude information. Not all fixes are guaranteed to contain such information. </para> /// </summary> /// <java-name> /// isAltitudeRequired /// </java-name> [Dot42.DexImport("isAltitudeRequired", "()Z", AccessFlags = 1)] public virtual bool IsAltitudeRequired() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Indicates whether the provider must provide speed information. Not all fixes are guaranteed to contain such information. </para> /// </summary> /// <java-name> /// setSpeedRequired /// </java-name> [Dot42.DexImport("setSpeedRequired", "(Z)V", AccessFlags = 1)] public virtual void SetSpeedRequired(bool speedRequired) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns whether the provider must provide speed information. Not all fixes are guaranteed to contain such information. </para> /// </summary> /// <java-name> /// isSpeedRequired /// </java-name> [Dot42.DexImport("isSpeedRequired", "()Z", AccessFlags = 1)] public virtual bool IsSpeedRequired() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Indicates whether the provider must provide bearing information. Not all fixes are guaranteed to contain such information. </para> /// </summary> /// <java-name> /// setBearingRequired /// </java-name> [Dot42.DexImport("setBearingRequired", "(Z)V", AccessFlags = 1)] public virtual void SetBearingRequired(bool bearingRequired) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns whether the provider must provide bearing information. Not all fixes are guaranteed to contain such information. </para> /// </summary> /// <java-name> /// isBearingRequired /// </java-name> [Dot42.DexImport("isBearingRequired", "()Z", AccessFlags = 1)] public virtual bool IsBearingRequired() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Describe the kinds of special objects contained in this Parcelable's marshalled representation.</para><para></para> /// </summary> /// <returns> /// <para>a bitmask indicating the set of special object types marshalled by the Parcelable. </para> /// </returns> /// <java-name> /// describeContents /// </java-name> [Dot42.DexImport("describeContents", "()I", AccessFlags = 1)] public virtual int DescribeContents() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Flatten this object in to a Parcel.</para><para></para> /// </summary> /// <java-name> /// writeToParcel /// </java-name> [Dot42.DexImport("writeToParcel", "(Landroid/os/Parcel;I)V", AccessFlags = 1)] public virtual void WriteToParcel(global::Android.Os.Parcel dest, int flags) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns a constant indicating the desired horizontal accuracy (latitude and longitude). Accuracy may be ACCURACY_LOW, ACCURACY_MEDIUM, ACCURACY_HIGH or NO_REQUIREMENT. </para> /// </summary> /// <java-name> /// getHorizontalAccuracy /// </java-name> public int HorizontalAccuracy { [Dot42.DexImport("getHorizontalAccuracy", "()I", AccessFlags = 1)] get{ return GetHorizontalAccuracy(); } [Dot42.DexImport("setHorizontalAccuracy", "(I)V", AccessFlags = 1)] set{ SetHorizontalAccuracy(value); } } /// <summary> /// <para>Returns a constant indicating the desired vertical accuracy (altitude). Accuracy may be ACCURACY_LOW, ACCURACY_HIGH, or NO_REQUIREMENT. </para> /// </summary> /// <java-name> /// getVerticalAccuracy /// </java-name> public int VerticalAccuracy { [Dot42.DexImport("getVerticalAccuracy", "()I", AccessFlags = 1)] get{ return GetVerticalAccuracy(); } [Dot42.DexImport("setVerticalAccuracy", "(I)V", AccessFlags = 1)] set{ SetVerticalAccuracy(value); } } /// <summary> /// <para>Returns a constant indicating the desired speed accuracy Accuracy may be ACCURACY_LOW, ACCURACY_HIGH, or NO_REQUIREMENT. </para> /// </summary> /// <java-name> /// getSpeedAccuracy /// </java-name> public int SpeedAccuracy { [Dot42.DexImport("getSpeedAccuracy", "()I", AccessFlags = 1)] get{ return GetSpeedAccuracy(); } [Dot42.DexImport("setSpeedAccuracy", "(I)V", AccessFlags = 1)] set{ SetSpeedAccuracy(value); } } /// <summary> /// <para>Returns a constant indicating the desired bearing accuracy. Accuracy may be ACCURACY_LOW, ACCURACY_HIGH, or NO_REQUIREMENT. </para> /// </summary> /// <java-name> /// getBearingAccuracy /// </java-name> public int BearingAccuracy { [Dot42.DexImport("getBearingAccuracy", "()I", AccessFlags = 1)] get{ return GetBearingAccuracy(); } [Dot42.DexImport("setBearingAccuracy", "(I)V", AccessFlags = 1)] set{ SetBearingAccuracy(value); } } /// <summary> /// <para>Returns a constant indicating desired accuracy of location Accuracy may be ACCURACY_FINE if desired location is fine, else it can be ACCURACY_COARSE. </para> /// </summary> /// <java-name> /// getAccuracy /// </java-name> public int Accuracy { [Dot42.DexImport("getAccuracy", "()I", AccessFlags = 1)] get{ return GetAccuracy(); } [Dot42.DexImport("setAccuracy", "(I)V", AccessFlags = 1)] set{ SetAccuracy(value); } } /// <summary> /// <para>Returns a constant indicating the desired power requirement. The returned </para> /// </summary> /// <java-name> /// getPowerRequirement /// </java-name> public int PowerRequirement { [Dot42.DexImport("getPowerRequirement", "()I", AccessFlags = 1)] get{ return GetPowerRequirement(); } [Dot42.DexImport("setPowerRequirement", "(I)V", AccessFlags = 1)] set{ SetPowerRequirement(value); } } } /// <summary> /// <para>This class represents the current state of a GPS satellite. This class is used in conjunction with the GpsStatus class. </para> /// </summary> /// <java-name> /// android/location/GpsSatellite /// </java-name> [Dot42.DexImport("android/location/GpsSatellite", AccessFlags = 49)] public sealed partial class GpsSatellite /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal GpsSatellite() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the PRN (pseudo-random number) for the satellite.</para><para></para> /// </summary> /// <returns> /// <para>PRN number </para> /// </returns> /// <java-name> /// getPrn /// </java-name> [Dot42.DexImport("getPrn", "()I", AccessFlags = 1)] public int GetPrn() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Returns the signal to noise ratio for the satellite.</para><para></para> /// </summary> /// <returns> /// <para>the signal to noise ratio </para> /// </returns> /// <java-name> /// getSnr /// </java-name> [Dot42.DexImport("getSnr", "()F", AccessFlags = 1)] public float GetSnr() /* MethodBuilder.Create */ { return default(float); } /// <summary> /// <para>Returns the elevation of the satellite in degrees. The elevation can vary between 0 and 90.</para><para></para> /// </summary> /// <returns> /// <para>the elevation in degrees </para> /// </returns> /// <java-name> /// getElevation /// </java-name> [Dot42.DexImport("getElevation", "()F", AccessFlags = 1)] public float GetElevation() /* MethodBuilder.Create */ { return default(float); } /// <summary> /// <para>Returns the azimuth of the satellite in degrees. The azimuth can vary between 0 and 360.</para><para></para> /// </summary> /// <returns> /// <para>the azimuth in degrees </para> /// </returns> /// <java-name> /// getAzimuth /// </java-name> [Dot42.DexImport("getAzimuth", "()F", AccessFlags = 1)] public float GetAzimuth() /* MethodBuilder.Create */ { return default(float); } /// <summary> /// <para>Returns true if the GPS engine has ephemeris data for the satellite.</para><para></para> /// </summary> /// <returns> /// <para>true if the satellite has ephemeris data </para> /// </returns> /// <java-name> /// hasEphemeris /// </java-name> [Dot42.DexImport("hasEphemeris", "()Z", AccessFlags = 1)] public bool HasEphemeris() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns true if the GPS engine has almanac data for the satellite.</para><para></para> /// </summary> /// <returns> /// <para>true if the satellite has almanac data </para> /// </returns> /// <java-name> /// hasAlmanac /// </java-name> [Dot42.DexImport("hasAlmanac", "()Z", AccessFlags = 1)] public bool HasAlmanac() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns true if the satellite was used by the GPS engine when calculating the most recent GPS fix.</para><para></para> /// </summary> /// <returns> /// <para>true if the satellite was used to compute the most recent fix. </para> /// </returns> /// <java-name> /// usedInFix /// </java-name> [Dot42.DexImport("usedInFix", "()Z", AccessFlags = 1)] public bool UsedInFix() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns the PRN (pseudo-random number) for the satellite.</para><para></para> /// </summary> /// <returns> /// <para>PRN number </para> /// </returns> /// <java-name> /// getPrn /// </java-name> public int Prn { [Dot42.DexImport("getPrn", "()I", AccessFlags = 1)] get{ return GetPrn(); } } /// <summary> /// <para>Returns the signal to noise ratio for the satellite.</para><para></para> /// </summary> /// <returns> /// <para>the signal to noise ratio </para> /// </returns> /// <java-name> /// getSnr /// </java-name> public float Snr { [Dot42.DexImport("getSnr", "()F", AccessFlags = 1)] get{ return GetSnr(); } } /// <summary> /// <para>Returns the elevation of the satellite in degrees. The elevation can vary between 0 and 90.</para><para></para> /// </summary> /// <returns> /// <para>the elevation in degrees </para> /// </returns> /// <java-name> /// getElevation /// </java-name> public float Elevation { [Dot42.DexImport("getElevation", "()F", AccessFlags = 1)] get{ return GetElevation(); } } /// <summary> /// <para>Returns the azimuth of the satellite in degrees. The azimuth can vary between 0 and 360.</para><para></para> /// </summary> /// <returns> /// <para>the azimuth in degrees </para> /// </returns> /// <java-name> /// getAzimuth /// </java-name> public float Azimuth { [Dot42.DexImport("getAzimuth", "()F", AccessFlags = 1)] get{ return GetAzimuth(); } } } /// <summary> /// <para>A class representing an Address, i.e, a set of Strings describing a location.</para><para>The addres format is a simplified version of xAL (eXtensible Address Language) </para> /// </summary> /// <java-name> /// android/location/Address /// </java-name> [Dot42.DexImport("android/location/Address", AccessFlags = 33)] public partial class Address : global::Android.Os.IParcelable /* scope: __dot42__ */ { /// <java-name> /// CREATOR /// </java-name> [Dot42.DexImport("CREATOR", "Landroid/os/Parcelable$Creator;", AccessFlags = 25)] public static readonly global::Android.Os.IParcelable_ICreator<global::Android.Location.Address> CREATOR; /// <summary> /// <para>Constructs a new Address object set to the given Locale and with all other fields initialized to null or false. </para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/util/Locale;)V", AccessFlags = 1)] public Address(global::Java.Util.Locale locale) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the Locale associated with this address. </para> /// </summary> /// <java-name> /// getLocale /// </java-name> [Dot42.DexImport("getLocale", "()Ljava/util/Locale;", AccessFlags = 1)] public virtual global::Java.Util.Locale GetLocale() /* MethodBuilder.Create */ { return default(global::Java.Util.Locale); } /// <summary> /// <para>Returns the largest index currently in use to specify an address line. If no address lines are specified, -1 is returned. </para> /// </summary> /// <java-name> /// getMaxAddressLineIndex /// </java-name> [Dot42.DexImport("getMaxAddressLineIndex", "()I", AccessFlags = 1)] public virtual int GetMaxAddressLineIndex() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Returns a line of the address numbered by the given index (starting at 0), or null if no such line is present.</para><para></para> /// </summary> /// <java-name> /// getAddressLine /// </java-name> [Dot42.DexImport("getAddressLine", "(I)Ljava/lang/String;", AccessFlags = 1)] public virtual string GetAddressLine(int index) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the line of the address numbered by index (starting at 0) to the given String, which may be null.</para><para></para> /// </summary> /// <java-name> /// setAddressLine /// </java-name> [Dot42.DexImport("setAddressLine", "(ILjava/lang/String;)V", AccessFlags = 1)] public virtual void SetAddressLine(int index, string line) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the feature name of the address, for example, "Golden Gate Bridge", or null if it is unknown </para> /// </summary> /// <java-name> /// getFeatureName /// </java-name> [Dot42.DexImport("getFeatureName", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetFeatureName() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the feature name of the address to the given String, which may be null </para> /// </summary> /// <java-name> /// setFeatureName /// </java-name> [Dot42.DexImport("setFeatureName", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetFeatureName(string featureName) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the administrative area name of the address, for example, "CA", or null if it is unknown </para> /// </summary> /// <java-name> /// getAdminArea /// </java-name> [Dot42.DexImport("getAdminArea", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetAdminArea() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the administrative area name of the address to the given String, which may be null </para> /// </summary> /// <java-name> /// setAdminArea /// </java-name> [Dot42.DexImport("setAdminArea", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetAdminArea(string adminArea) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the sub-administrative area name of the address, for example, "Santa Clara County", or null if it is unknown </para> /// </summary> /// <java-name> /// getSubAdminArea /// </java-name> [Dot42.DexImport("getSubAdminArea", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetSubAdminArea() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the sub-administrative area name of the address to the given String, which may be null </para> /// </summary> /// <java-name> /// setSubAdminArea /// </java-name> [Dot42.DexImport("setSubAdminArea", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetSubAdminArea(string subAdminArea) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the locality of the address, for example "Mountain View", or null if it is unknown. </para> /// </summary> /// <java-name> /// getLocality /// </java-name> [Dot42.DexImport("getLocality", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetLocality() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the locality of the address to the given String, which may be null. </para> /// </summary> /// <java-name> /// setLocality /// </java-name> [Dot42.DexImport("setLocality", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetLocality(string locality) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the sub-locality of the address, or null if it is unknown. For example, this may correspond to the neighborhood of the locality. </para> /// </summary> /// <java-name> /// getSubLocality /// </java-name> [Dot42.DexImport("getSubLocality", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetSubLocality() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the sub-locality of the address to the given String, which may be null. </para> /// </summary> /// <java-name> /// setSubLocality /// </java-name> [Dot42.DexImport("setSubLocality", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetSubLocality(string sublocality) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the thoroughfare name of the address, for example, "1600 Ampitheater Parkway", which may be null </para> /// </summary> /// <java-name> /// getThoroughfare /// </java-name> [Dot42.DexImport("getThoroughfare", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetThoroughfare() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the thoroughfare name of the address, which may be null. </para> /// </summary> /// <java-name> /// setThoroughfare /// </java-name> [Dot42.DexImport("setThoroughfare", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetThoroughfare(string thoroughfare) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the sub-thoroughfare name of the address, which may be null. This may correspond to the street number of the address. </para> /// </summary> /// <java-name> /// getSubThoroughfare /// </java-name> [Dot42.DexImport("getSubThoroughfare", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetSubThoroughfare() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the sub-thoroughfare name of the address, which may be null. </para> /// </summary> /// <java-name> /// setSubThoroughfare /// </java-name> [Dot42.DexImport("setSubThoroughfare", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetSubThoroughfare(string subthoroughfare) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the premises of the address, or null if it is unknown. </para> /// </summary> /// <java-name> /// getPremises /// </java-name> [Dot42.DexImport("getPremises", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetPremises() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the premises of the address to the given String, which may be null. </para> /// </summary> /// <java-name> /// setPremises /// </java-name> [Dot42.DexImport("setPremises", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetPremises(string premises) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the postal code of the address, for example "94110", or null if it is unknown. </para> /// </summary> /// <java-name> /// getPostalCode /// </java-name> [Dot42.DexImport("getPostalCode", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetPostalCode() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the postal code of the address to the given String, which may be null. </para> /// </summary> /// <java-name> /// setPostalCode /// </java-name> [Dot42.DexImport("setPostalCode", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetPostalCode(string postalCode) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the country code of the address, for example "US", or null if it is unknown. </para> /// </summary> /// <java-name> /// getCountryCode /// </java-name> [Dot42.DexImport("getCountryCode", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetCountryCode() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the country code of the address to the given String, which may be null. </para> /// </summary> /// <java-name> /// setCountryCode /// </java-name> [Dot42.DexImport("setCountryCode", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetCountryCode(string countryCode) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the localized country name of the address, for example "Iceland", or null if it is unknown. </para> /// </summary> /// <java-name> /// getCountryName /// </java-name> [Dot42.DexImport("getCountryName", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetCountryName() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the country name of the address to the given String, which may be null. </para> /// </summary> /// <java-name> /// setCountryName /// </java-name> [Dot42.DexImport("setCountryName", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetCountryName(string countryName) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns true if a latitude has been assigned to this Address, false otherwise. </para> /// </summary> /// <java-name> /// hasLatitude /// </java-name> [Dot42.DexImport("hasLatitude", "()Z", AccessFlags = 1)] public virtual bool HasLatitude() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns the latitude of the address if known.</para><para></para> /// </summary> /// <java-name> /// getLatitude /// </java-name> [Dot42.DexImport("getLatitude", "()D", AccessFlags = 1)] public virtual double GetLatitude() /* MethodBuilder.Create */ { return default(double); } /// <summary> /// <para>Sets the latitude associated with this address. </para> /// </summary> /// <java-name> /// setLatitude /// </java-name> [Dot42.DexImport("setLatitude", "(D)V", AccessFlags = 1)] public virtual void SetLatitude(double latitude) /* MethodBuilder.Create */ { } /// <summary> /// <para>Removes any latitude associated with this address. </para> /// </summary> /// <java-name> /// clearLatitude /// </java-name> [Dot42.DexImport("clearLatitude", "()V", AccessFlags = 1)] public virtual void ClearLatitude() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns true if a longitude has been assigned to this Address, false otherwise. </para> /// </summary> /// <java-name> /// hasLongitude /// </java-name> [Dot42.DexImport("hasLongitude", "()Z", AccessFlags = 1)] public virtual bool HasLongitude() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns the longitude of the address if known.</para><para></para> /// </summary> /// <java-name> /// getLongitude /// </java-name> [Dot42.DexImport("getLongitude", "()D", AccessFlags = 1)] public virtual double GetLongitude() /* MethodBuilder.Create */ { return default(double); } /// <summary> /// <para>Sets the longitude associated with this address. </para> /// </summary> /// <java-name> /// setLongitude /// </java-name> [Dot42.DexImport("setLongitude", "(D)V", AccessFlags = 1)] public virtual void SetLongitude(double longitude) /* MethodBuilder.Create */ { } /// <summary> /// <para>Removes any longitude associated with this address. </para> /// </summary> /// <java-name> /// clearLongitude /// </java-name> [Dot42.DexImport("clearLongitude", "()V", AccessFlags = 1)] public virtual void ClearLongitude() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the phone number of the address if known, or null if it is unknown.</para><para></para> /// </summary> /// <java-name> /// getPhone /// </java-name> [Dot42.DexImport("getPhone", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetPhone() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the phone number associated with this address. </para> /// </summary> /// <java-name> /// setPhone /// </java-name> [Dot42.DexImport("setPhone", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetPhone(string phone) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the public URL for the address if known, or null if it is unknown. </para> /// </summary> /// <java-name> /// getUrl /// </java-name> [Dot42.DexImport("getUrl", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetUrl() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the public URL associated with this address. </para> /// </summary> /// <java-name> /// setUrl /// </java-name> [Dot42.DexImport("setUrl", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetUrl(string Url) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns additional provider-specific information about the address as a Bundle. The keys and values are determined by the provider. If no additional information is available, null is returned. </para> /// </summary> /// <java-name> /// getExtras /// </java-name> [Dot42.DexImport("getExtras", "()Landroid/os/Bundle;", AccessFlags = 1)] public virtual global::Android.Os.Bundle GetExtras() /* MethodBuilder.Create */ { return default(global::Android.Os.Bundle); } /// <summary> /// <para>Sets the extra information associated with this fix to the given Bundle. </para> /// </summary> /// <java-name> /// setExtras /// </java-name> [Dot42.DexImport("setExtras", "(Landroid/os/Bundle;)V", AccessFlags = 1)] public virtual void SetExtras(global::Android.Os.Bundle extras) /* MethodBuilder.Create */ { } /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Describe the kinds of special objects contained in this Parcelable's marshalled representation.</para><para></para> /// </summary> /// <returns> /// <para>a bitmask indicating the set of special object types marshalled by the Parcelable. </para> /// </returns> /// <java-name> /// describeContents /// </java-name> [Dot42.DexImport("describeContents", "()I", AccessFlags = 1)] public virtual int DescribeContents() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Flatten this object in to a Parcel.</para><para></para> /// </summary> /// <java-name> /// writeToParcel /// </java-name> [Dot42.DexImport("writeToParcel", "(Landroid/os/Parcel;I)V", AccessFlags = 1)] public virtual void WriteToParcel(global::Android.Os.Parcel dest, int flags) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal Address() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns the Locale associated with this address. </para> /// </summary> /// <java-name> /// getLocale /// </java-name> public global::Java.Util.Locale Locale { [Dot42.DexImport("getLocale", "()Ljava/util/Locale;", AccessFlags = 1)] get{ return GetLocale(); } } /// <summary> /// <para>Returns the largest index currently in use to specify an address line. If no address lines are specified, -1 is returned. </para> /// </summary> /// <java-name> /// getMaxAddressLineIndex /// </java-name> public int MaxAddressLineIndex { [Dot42.DexImport("getMaxAddressLineIndex", "()I", AccessFlags = 1)] get{ return GetMaxAddressLineIndex(); } } /// <summary> /// <para>Returns the feature name of the address, for example, "Golden Gate Bridge", or null if it is unknown </para> /// </summary> /// <java-name> /// getFeatureName /// </java-name> public string FeatureName { [Dot42.DexImport("getFeatureName", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetFeatureName(); } [Dot42.DexImport("setFeatureName", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetFeatureName(value); } } /// <summary> /// <para>Returns the administrative area name of the address, for example, "CA", or null if it is unknown </para> /// </summary> /// <java-name> /// getAdminArea /// </java-name> public string AdminArea { [Dot42.DexImport("getAdminArea", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetAdminArea(); } [Dot42.DexImport("setAdminArea", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetAdminArea(value); } } /// <summary> /// <para>Returns the sub-administrative area name of the address, for example, "Santa Clara County", or null if it is unknown </para> /// </summary> /// <java-name> /// getSubAdminArea /// </java-name> public string SubAdminArea { [Dot42.DexImport("getSubAdminArea", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetSubAdminArea(); } [Dot42.DexImport("setSubAdminArea", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetSubAdminArea(value); } } /// <summary> /// <para>Returns the locality of the address, for example "Mountain View", or null if it is unknown. </para> /// </summary> /// <java-name> /// getLocality /// </java-name> public string Locality { [Dot42.DexImport("getLocality", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetLocality(); } [Dot42.DexImport("setLocality", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetLocality(value); } } /// <summary> /// <para>Returns the sub-locality of the address, or null if it is unknown. For example, this may correspond to the neighborhood of the locality. </para> /// </summary> /// <java-name> /// getSubLocality /// </java-name> public string SubLocality { [Dot42.DexImport("getSubLocality", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetSubLocality(); } [Dot42.DexImport("setSubLocality", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetSubLocality(value); } } /// <summary> /// <para>Returns the thoroughfare name of the address, for example, "1600 Ampitheater Parkway", which may be null </para> /// </summary> /// <java-name> /// getThoroughfare /// </java-name> public string Thoroughfare { [Dot42.DexImport("getThoroughfare", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetThoroughfare(); } [Dot42.DexImport("setThoroughfare", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetThoroughfare(value); } } /// <summary> /// <para>Returns the sub-thoroughfare name of the address, which may be null. This may correspond to the street number of the address. </para> /// </summary> /// <java-name> /// getSubThoroughfare /// </java-name> public string SubThoroughfare { [Dot42.DexImport("getSubThoroughfare", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetSubThoroughfare(); } [Dot42.DexImport("setSubThoroughfare", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetSubThoroughfare(value); } } /// <summary> /// <para>Returns the premises of the address, or null if it is unknown. </para> /// </summary> /// <java-name> /// getPremises /// </java-name> public string Premises { [Dot42.DexImport("getPremises", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetPremises(); } [Dot42.DexImport("setPremises", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetPremises(value); } } /// <summary> /// <para>Returns the postal code of the address, for example "94110", or null if it is unknown. </para> /// </summary> /// <java-name> /// getPostalCode /// </java-name> public string PostalCode { [Dot42.DexImport("getPostalCode", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetPostalCode(); } [Dot42.DexImport("setPostalCode", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetPostalCode(value); } } /// <summary> /// <para>Returns the country code of the address, for example "US", or null if it is unknown. </para> /// </summary> /// <java-name> /// getCountryCode /// </java-name> public string CountryCode { [Dot42.DexImport("getCountryCode", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetCountryCode(); } [Dot42.DexImport("setCountryCode", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetCountryCode(value); } } /// <summary> /// <para>Returns the localized country name of the address, for example "Iceland", or null if it is unknown. </para> /// </summary> /// <java-name> /// getCountryName /// </java-name> public string CountryName { [Dot42.DexImport("getCountryName", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetCountryName(); } [Dot42.DexImport("setCountryName", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetCountryName(value); } } /// <summary> /// <para>Returns the latitude of the address if known.</para><para></para> /// </summary> /// <java-name> /// getLatitude /// </java-name> public double Latitude { [Dot42.DexImport("getLatitude", "()D", AccessFlags = 1)] get{ return GetLatitude(); } [Dot42.DexImport("setLatitude", "(D)V", AccessFlags = 1)] set{ SetLatitude(value); } } /// <summary> /// <para>Returns the longitude of the address if known.</para><para></para> /// </summary> /// <java-name> /// getLongitude /// </java-name> public double Longitude { [Dot42.DexImport("getLongitude", "()D", AccessFlags = 1)] get{ return GetLongitude(); } [Dot42.DexImport("setLongitude", "(D)V", AccessFlags = 1)] set{ SetLongitude(value); } } /// <summary> /// <para>Returns the phone number of the address if known, or null if it is unknown.</para><para></para> /// </summary> /// <java-name> /// getPhone /// </java-name> public string Phone { [Dot42.DexImport("getPhone", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetPhone(); } [Dot42.DexImport("setPhone", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetPhone(value); } } /// <summary> /// <para>Returns the public URL for the address if known, or null if it is unknown. </para> /// </summary> /// <java-name> /// getUrl /// </java-name> public string Url { [Dot42.DexImport("getUrl", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetUrl(); } [Dot42.DexImport("setUrl", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetUrl(value); } } /// <summary> /// <para>Returns additional provider-specific information about the address as a Bundle. The keys and values are determined by the provider. If no additional information is available, null is returned. </para> /// </summary> /// <java-name> /// getExtras /// </java-name> public global::Android.Os.Bundle Extras { [Dot42.DexImport("getExtras", "()Landroid/os/Bundle;", AccessFlags = 1)] get{ return GetExtras(); } [Dot42.DexImport("setExtras", "(Landroid/os/Bundle;)V", AccessFlags = 1)] set{ SetExtras(value); } } } /// <summary> /// <para>A class for handling geocoding and reverse geocoding. Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate. Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a (partial) address. The amount of detail in a reverse geocoded location description may vary, for example one might contain the full street address of the closest building, while another might contain only a city name and postal code.</para><para>The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform. Use the isPresent() method to determine whether a Geocoder implementation exists. </para> /// </summary> /// <java-name> /// android/location/Geocoder /// </java-name> [Dot42.DexImport("android/location/Geocoder", AccessFlags = 49)] public sealed partial class Geocoder /* scope: __dot42__ */ { /// <summary> /// <para>Constructs a Geocoder whose responses will be localized for the given Locale.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Landroid/content/Context;Ljava/util/Locale;)V", AccessFlags = 1)] public Geocoder(global::Android.Content.Context context, global::Java.Util.Locale locale) /* MethodBuilder.Create */ { } /// <summary> /// <para>Constructs a Geocoder whose responses will be localized for the default system Locale.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Landroid/content/Context;)V", AccessFlags = 1)] public Geocoder(global::Android.Content.Context context) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns true if the Geocoder methods getFromLocation and getFromLocationName are implemented. Lack of network connectivity may still cause these methods to return null or empty lists. </para> /// </summary> /// <java-name> /// isPresent /// </java-name> [Dot42.DexImport("isPresent", "()Z", AccessFlags = 9)] public static bool IsPresent() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns an array of Addresses that are known to describe the area immediately surrounding the given latitude and longitude. The returned addresses will be localized for the locale provided to this class's constructor.</para><para>The returned values may be obtained by means of a network lookup. The results are a best guess and are not guaranteed to be meaningful or correct. It may be useful to call this method from a thread separate from your primary UI thread.</para><para></para> /// </summary> /// <returns> /// <para>a list of Address objects. Returns null or empty list if no matches were found or there is no backend service available.</para> /// </returns> /// <java-name> /// getFromLocation /// </java-name> [Dot42.DexImport("getFromLocation", "(DDI)Ljava/util/List;", AccessFlags = 1, Signature = "(DDI)Ljava/util/List<Landroid/location/Address;>;")] public global::Java.Util.IList<global::Android.Location.Address> GetFromLocation(double latitude, double longitude, int maxResults) /* MethodBuilder.Create */ { return default(global::Java.Util.IList<global::Android.Location.Address>); } /// <summary> /// <para>Returns an array of Addresses that are known to describe the named location, which may be a place name such as "Dalvik, Iceland", an address such as "1600 Amphitheatre Parkway, Mountain View, CA", an airport code such as "SFO", etc.. The returned addresses will be localized for the locale provided to this class's constructor.</para><para>The query will block and returned values will be obtained by means of a network lookup. The results are a best guess and are not guaranteed to be meaningful or correct. It may be useful to call this method from a thread separate from your primary UI thread.</para><para></para> /// </summary> /// <returns> /// <para>a list of Address objects. Returns null or empty list if no matches were found or there is no backend service available.</para> /// </returns> /// <java-name> /// getFromLocationName /// </java-name> [Dot42.DexImport("getFromLocationName", "(Ljava/lang/String;I)Ljava/util/List;", AccessFlags = 1, Signature = "(Ljava/lang/String;I)Ljava/util/List<Landroid/location/Address;>;")] public global::Java.Util.IList<global::Android.Location.Address> GetFromLocationName(string locationName, int maxResults) /* MethodBuilder.Create */ { return default(global::Java.Util.IList<global::Android.Location.Address>); } /// <summary> /// <para>Returns an array of Addresses that are known to describe the named location, which may be a place name such as "Dalvik, Iceland", an address such as "1600 Amphitheatre Parkway, Mountain View, CA", an airport code such as "SFO", etc.. The returned addresses will be localized for the locale provided to this class's constructor.</para><para>You may specify a bounding box for the search results by including the Latitude and Longitude of the Lower Left point and Upper Right point of the box.</para><para>The query will block and returned values will be obtained by means of a network lookup. The results are a best guess and are not guaranteed to be meaningful or correct. It may be useful to call this method from a thread separate from your primary UI thread.</para><para></para> /// </summary> /// <returns> /// <para>a list of Address objects. Returns null or empty list if no matches were found or there is no backend service available.</para> /// </returns> /// <java-name> /// getFromLocationName /// </java-name> [Dot42.DexImport("getFromLocationName", "(Ljava/lang/String;IDDDD)Ljava/util/List;", AccessFlags = 1, Signature = "(Ljava/lang/String;IDDDD)Ljava/util/List<Landroid/location/Address;>;")] public global::Java.Util.IList<global::Android.Location.Address> GetFromLocationName(string locationName, int maxResults, double lowerLeftLatitude, double lowerLeftLongitude, double upperRightLatitude, double upperRightLongitude) /* MethodBuilder.Create */ { return default(global::Java.Util.IList<global::Android.Location.Address>); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal Geocoder() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>This class represents the current state of the GPS engine. This class is used in conjunction with the Listener interface. </para> /// </summary> /// <java-name> /// android/location/GpsStatus /// </java-name> [Dot42.DexImport("android/location/GpsStatus", AccessFlags = 49)] public sealed partial class GpsStatus /* scope: __dot42__ */ { /// <summary> /// <para>Event sent when the GPS system has started. </para> /// </summary> /// <java-name> /// GPS_EVENT_STARTED /// </java-name> [Dot42.DexImport("GPS_EVENT_STARTED", "I", AccessFlags = 25)] public const int GPS_EVENT_STARTED = 1; /// <summary> /// <para>Event sent when the GPS system has stopped. </para> /// </summary> /// <java-name> /// GPS_EVENT_STOPPED /// </java-name> [Dot42.DexImport("GPS_EVENT_STOPPED", "I", AccessFlags = 25)] public const int GPS_EVENT_STOPPED = 2; /// <summary> /// <para>Event sent when the GPS system has received its first fix since starting. Call getTimeToFirstFix() to find the time from start to first fix. </para> /// </summary> /// <java-name> /// GPS_EVENT_FIRST_FIX /// </java-name> [Dot42.DexImport("GPS_EVENT_FIRST_FIX", "I", AccessFlags = 25)] public const int GPS_EVENT_FIRST_FIX = 3; /// <summary> /// <para>Event sent periodically to report GPS satellite status. Call getSatellites() to retrieve the status for each satellite. </para> /// </summary> /// <java-name> /// GPS_EVENT_SATELLITE_STATUS /// </java-name> [Dot42.DexImport("GPS_EVENT_SATELLITE_STATUS", "I", AccessFlags = 25)] public const int GPS_EVENT_SATELLITE_STATUS = 4; [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal GpsStatus() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the time required to receive the first fix since the most recent restart of the GPS engine.</para><para></para> /// </summary> /// <returns> /// <para>time to first fix in milliseconds </para> /// </returns> /// <java-name> /// getTimeToFirstFix /// </java-name> [Dot42.DexImport("getTimeToFirstFix", "()I", AccessFlags = 1)] public int GetTimeToFirstFix() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Returns an array of GpsSatellite objects, which represent the current state of the GPS engine.</para><para></para> /// </summary> /// <returns> /// <para>the list of satellites </para> /// </returns> /// <java-name> /// getSatellites /// </java-name> [Dot42.DexImport("getSatellites", "()Ljava/lang/Iterable;", AccessFlags = 1, Signature = "()Ljava/lang/Iterable<Landroid/location/GpsSatellite;>;")] public global::Java.Lang.IIterable<global::Android.Location.GpsSatellite> GetSatellites() /* MethodBuilder.Create */ { return default(global::Java.Lang.IIterable<global::Android.Location.GpsSatellite>); } /// <summary> /// <para>Returns the maximum number of satellites that can be in the satellite list that can be returned by getSatellites().</para><para></para> /// </summary> /// <returns> /// <para>the maximum number of satellites </para> /// </returns> /// <java-name> /// getMaxSatellites /// </java-name> [Dot42.DexImport("getMaxSatellites", "()I", AccessFlags = 1)] public int GetMaxSatellites() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Returns the time required to receive the first fix since the most recent restart of the GPS engine.</para><para></para> /// </summary> /// <returns> /// <para>time to first fix in milliseconds </para> /// </returns> /// <java-name> /// getTimeToFirstFix /// </java-name> public int TimeToFirstFix { [Dot42.DexImport("getTimeToFirstFix", "()I", AccessFlags = 1)] get{ return GetTimeToFirstFix(); } } /// <summary> /// <para>Returns an array of GpsSatellite objects, which represent the current state of the GPS engine.</para><para></para> /// </summary> /// <returns> /// <para>the list of satellites </para> /// </returns> /// <java-name> /// getSatellites /// </java-name> public global::Java.Lang.IIterable<global::Android.Location.GpsSatellite> Satellites { [Dot42.DexImport("getSatellites", "()Ljava/lang/Iterable;", AccessFlags = 1, Signature = "()Ljava/lang/Iterable<Landroid/location/GpsSatellite;>;")] get{ return GetSatellites(); } } /// <summary> /// <para>Returns the maximum number of satellites that can be in the satellite list that can be returned by getSatellites().</para><para></para> /// </summary> /// <returns> /// <para>the maximum number of satellites </para> /// </returns> /// <java-name> /// getMaxSatellites /// </java-name> public int MaxSatellites { [Dot42.DexImport("getMaxSatellites", "()I", AccessFlags = 1)] get{ return GetMaxSatellites(); } } /// <summary> /// <para>Used for receiving NMEA sentences from the GPS. NMEA 0183 is a standard for communicating with marine electronic devices and is a common method for receiving data from a GPS, typically over a serial port. See for more details. You can implement this interface and call LocationManager#addNmeaListener to receive NMEA data from the GPS engine. </para> /// </summary> /// <java-name> /// android/location/GpsStatus$NmeaListener /// </java-name> [Dot42.DexImport("android/location/GpsStatus$NmeaListener", AccessFlags = 1545)] public partial interface INmeaListener /* scope: __dot42__ */ { /// <java-name> /// onNmeaReceived /// </java-name> [Dot42.DexImport("onNmeaReceived", "(JLjava/lang/String;)V", AccessFlags = 1025)] void OnNmeaReceived(long timestamp, string nmea) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Used for receiving notifications when GPS status has changed. </para> /// </summary> /// <java-name> /// android/location/GpsStatus$Listener /// </java-name> [Dot42.DexImport("android/location/GpsStatus$Listener", AccessFlags = 1545)] public partial interface IListener /* scope: __dot42__ */ { /// <summary> /// <para>Called to report changes in the GPS status. The event number is one of: <ul><li><para>GpsStatus#GPS_EVENT_STARTED </para></li><li><para>GpsStatus#GPS_EVENT_STOPPED </para></li><li><para>GpsStatus#GPS_EVENT_FIRST_FIX </para></li><li><para>GpsStatus#GPS_EVENT_SATELLITE_STATUS </para></li></ul></para><para>When this method is called, the client should call LocationManager#getGpsStatus to get additional status information.</para><para></para> /// </summary> /// <java-name> /// onGpsStatusChanged /// </java-name> [Dot42.DexImport("onGpsStatusChanged", "(I)V", AccessFlags = 1025)] void OnGpsStatusChanged(int @event) /* MethodBuilder.Create */ ; } } /// <summary> /// <para>This class provides access to the system location services. These services allow applications to obtain periodic updates of the device's geographical location, or to fire an application-specified Intent when the device enters the proximity of a given geographical location.</para><para>You do not instantiate this class directly; instead, retrieve it through Context.getSystemService(Context.LOCATION_SERVICE).</para><para>Unless noted, all Location API methods require the android.Manifest.permission#ACCESS_COARSE_LOCATION or android.Manifest.permission#ACCESS_FINE_LOCATION permissions. If your application only has the coarse permission then it will not have access to the GPS or passive location providers. Other providers will still return location results, but the update rate will be throttled and the exact location will be obfuscated to a coarse level of accuracy. </para> /// </summary> /// <java-name> /// android/location/LocationManager /// </java-name> [Dot42.DexImport("android/location/LocationManager", AccessFlags = 33)] public partial class LocationManager /* scope: __dot42__ */ { /// <summary> /// <para>Name of the network location provider. </para><para>This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. </para> /// </summary> /// <java-name> /// NETWORK_PROVIDER /// </java-name> [Dot42.DexImport("NETWORK_PROVIDER", "Ljava/lang/String;", AccessFlags = 25)] public const string NETWORK_PROVIDER = "network"; /// <summary> /// <para>Name of the GPS location provider.</para><para>This provider determines location using satellites. Depending on conditions, this provider may take a while to return a location fix. Requires the permission android.Manifest.permission#ACCESS_FINE_LOCATION.</para><para>The extras Bundle for the GPS location provider can contain the following key/value pairs: <ul><li><para>satellites - the number of satellites used to derive the fix </para></li></ul></para> /// </summary> /// <java-name> /// GPS_PROVIDER /// </java-name> [Dot42.DexImport("GPS_PROVIDER", "Ljava/lang/String;", AccessFlags = 25)] public const string GPS_PROVIDER = "gps"; /// <summary> /// <para>A special location provider for receiving locations without actually initiating a location fix.</para><para>This provider can be used to passively receive location updates when other applications or services request them without actually requesting the locations yourself. This provider will return locations generated by other providers. You can query the Location#getProvider() method to determine the origin of the location update. Requires the permission android.Manifest.permission#ACCESS_FINE_LOCATION, although if the GPS is not enabled this provider might only return coarse fixes. </para> /// </summary> /// <java-name> /// PASSIVE_PROVIDER /// </java-name> [Dot42.DexImport("PASSIVE_PROVIDER", "Ljava/lang/String;", AccessFlags = 25)] public const string PASSIVE_PROVIDER = "passive"; /// <summary> /// <para>Key used for the Bundle extra holding a boolean indicating whether a proximity alert is entering (true) or exiting (false).. </para> /// </summary> /// <java-name> /// KEY_PROXIMITY_ENTERING /// </java-name> [Dot42.DexImport("KEY_PROXIMITY_ENTERING", "Ljava/lang/String;", AccessFlags = 25)] public const string KEY_PROXIMITY_ENTERING = "entering"; /// <summary> /// <para>Key used for a Bundle extra holding an Integer status value when a status change is broadcast using a PendingIntent. </para> /// </summary> /// <java-name> /// KEY_STATUS_CHANGED /// </java-name> [Dot42.DexImport("KEY_STATUS_CHANGED", "Ljava/lang/String;", AccessFlags = 25)] public const string KEY_STATUS_CHANGED = "status"; /// <summary> /// <para>Key used for a Bundle extra holding an Boolean status value when a provider enabled/disabled event is broadcast using a PendingIntent. </para> /// </summary> /// <java-name> /// KEY_PROVIDER_ENABLED /// </java-name> [Dot42.DexImport("KEY_PROVIDER_ENABLED", "Ljava/lang/String;", AccessFlags = 25)] public const string KEY_PROVIDER_ENABLED = "providerEnabled"; /// <summary> /// <para>Key used for a Bundle extra holding a Location value when a location change is broadcast using a PendingIntent. </para> /// </summary> /// <java-name> /// KEY_LOCATION_CHANGED /// </java-name> [Dot42.DexImport("KEY_LOCATION_CHANGED", "Ljava/lang/String;", AccessFlags = 25)] public const string KEY_LOCATION_CHANGED = "location"; /// <summary> /// <para>Broadcast intent action when the configured location providers change. </para> /// </summary> /// <java-name> /// PROVIDERS_CHANGED_ACTION /// </java-name> [Dot42.DexImport("PROVIDERS_CHANGED_ACTION", "Ljava/lang/String;", AccessFlags = 25)] public const string PROVIDERS_CHANGED_ACTION = "android.location.PROVIDERS_CHANGED"; [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal LocationManager() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns a list of the names of all known location providers. </para><para>All providers are returned, including ones that are not permitted to be accessed by the calling activity or are currently disabled.</para><para></para> /// </summary> /// <returns> /// <para>list of Strings containing names of the provider </para> /// </returns> /// <java-name> /// getAllProviders /// </java-name> [Dot42.DexImport("getAllProviders", "()Ljava/util/List;", AccessFlags = 1, Signature = "()Ljava/util/List<Ljava/lang/String;>;")] public virtual global::Java.Util.IList<string> GetAllProviders() /* MethodBuilder.Create */ { return default(global::Java.Util.IList<string>); } /// <summary> /// <para>Returns a list of the names of location providers.</para><para></para> /// </summary> /// <returns> /// <para>list of Strings containing names of the providers </para> /// </returns> /// <java-name> /// getProviders /// </java-name> [Dot42.DexImport("getProviders", "(Z)Ljava/util/List;", AccessFlags = 1, Signature = "(Z)Ljava/util/List<Ljava/lang/String;>;")] public virtual global::Java.Util.IList<string> GetProviders(bool enabledOnly) /* MethodBuilder.Create */ { return default(global::Java.Util.IList<string>); } /// <summary> /// <para>Returns the information associated with the location provider of the given name, or null if no provider exists by that name.</para><para></para> /// </summary> /// <returns> /// <para>a LocationProvider, or null</para> /// </returns> /// <java-name> /// getProvider /// </java-name> [Dot42.DexImport("getProvider", "(Ljava/lang/String;)Landroid/location/LocationProvider;", AccessFlags = 1)] public virtual global::Android.Location.LocationProvider GetProvider(string name) /* MethodBuilder.Create */ { return default(global::Android.Location.LocationProvider); } /// <summary> /// <para>Returns a list of the names of LocationProviders that satisfy the given criteria, or null if none do. Only providers that are permitted to be accessed by the calling activity will be returned.</para><para></para> /// </summary> /// <returns> /// <para>list of Strings containing names of the providers </para> /// </returns> /// <java-name> /// getProviders /// </java-name> [Dot42.DexImport("getProviders", "(Landroid/location/Criteria;Z)Ljava/util/List;", AccessFlags = 1, Signature = "(Landroid/location/Criteria;Z)Ljava/util/List<Ljava/lang/String;>;")] public virtual global::Java.Util.IList<string> GetProviders(global::Android.Location.Criteria criteria, bool enabledOnly) /* MethodBuilder.Create */ { return default(global::Java.Util.IList<string>); } /// <summary> /// <para>Returns the name of the provider that best meets the given criteria. Only providers that are permitted to be accessed by the calling activity will be returned. If several providers meet the criteria, the one with the best accuracy is returned. If no provider meets the criteria, the criteria are loosened in the following sequence:</para><para><ul><li><para>power requirement </para></li><li><para>accuracy </para></li><li><para>bearing </para></li><li><para>speed </para></li><li><para>altitude </para></li></ul></para><para>Note that the requirement on monetary cost is not removed in this process.</para><para></para> /// </summary> /// <returns> /// <para>name of the provider that best matches the requirements </para> /// </returns> /// <java-name> /// getBestProvider /// </java-name> [Dot42.DexImport("getBestProvider", "(Landroid/location/Criteria;Z)Ljava/lang/String;", AccessFlags = 1)] public virtual string GetBestProvider(global::Android.Location.Criteria criteria, bool enabledOnly) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// requestLocationUpdates /// </java-name> [Dot42.DexImport("requestLocationUpdates", "(Ljava/lang/String;JFLandroid/location/LocationListener;)V", AccessFlags = 1)] public virtual void RequestLocationUpdates(string request, long listener, float looper, global::Android.Location.ILocationListener intent) /* MethodBuilder.Create */ { } /// <java-name> /// requestLocationUpdates /// </java-name> [Dot42.DexImport("requestLocationUpdates", "(Ljava/lang/String;JFLandroid/location/LocationListener;Landroid/os/Looper;)V", AccessFlags = 1)] public virtual void RequestLocationUpdates(string @string, long int64, float single, global::Android.Location.ILocationListener locationListener, global::Android.Os.Looper looper) /* MethodBuilder.Create */ { } /// <java-name> /// requestLocationUpdates /// </java-name> [Dot42.DexImport("requestLocationUpdates", "(JFLandroid/location/Criteria;Landroid/location/LocationListener;Landroid/os/Loop" + "er;)V", AccessFlags = 1)] public virtual void RequestLocationUpdates(long int64, float single, global::Android.Location.Criteria criteria, global::Android.Location.ILocationListener locationListener, global::Android.Os.Looper looper) /* MethodBuilder.Create */ { } /// <java-name> /// requestLocationUpdates /// </java-name> [Dot42.DexImport("requestLocationUpdates", "(Ljava/lang/String;JFLandroid/app/PendingIntent;)V", AccessFlags = 1)] public virtual void RequestLocationUpdates(string request, long listener, float looper, global::Android.App.PendingIntent intent) /* MethodBuilder.Create */ { } /// <java-name> /// requestLocationUpdates /// </java-name> [Dot42.DexImport("requestLocationUpdates", "(JFLandroid/location/Criteria;Landroid/app/PendingIntent;)V", AccessFlags = 1)] public virtual void RequestLocationUpdates(long request, float listener, global::Android.Location.Criteria looper, global::Android.App.PendingIntent intent) /* MethodBuilder.Create */ { } /// <summary> /// <para>Register for a single location update using a Criteria and a callback.</para><para>See requestLocationUpdates(long, float, Criteria, PendingIntent) for more detail on how to use this method.</para><para></para> /// </summary> /// <java-name> /// requestSingleUpdate /// </java-name> [Dot42.DexImport("requestSingleUpdate", "(Ljava/lang/String;Landroid/location/LocationListener;Landroid/os/Looper;)V", AccessFlags = 1)] public virtual void RequestSingleUpdate(string criteria, global::Android.Location.ILocationListener listener, global::Android.Os.Looper looper) /* MethodBuilder.Create */ { } /// <summary> /// <para>Register for a single location update using a Criteria and a callback.</para><para>See requestLocationUpdates(long, float, Criteria, PendingIntent) for more detail on how to use this method.</para><para></para> /// </summary> /// <java-name> /// requestSingleUpdate /// </java-name> [Dot42.DexImport("requestSingleUpdate", "(Landroid/location/Criteria;Landroid/location/LocationListener;Landroid/os/Looper" + ";)V", AccessFlags = 1)] public virtual void RequestSingleUpdate(global::Android.Location.Criteria criteria, global::Android.Location.ILocationListener listener, global::Android.Os.Looper looper) /* MethodBuilder.Create */ { } /// <summary> /// <para>Register for a single location update using a Criteria and pending intent.</para><para>See requestLocationUpdates(long, float, Criteria, PendingIntent) for more detail on how to use this method.</para><para></para> /// </summary> /// <java-name> /// requestSingleUpdate /// </java-name> [Dot42.DexImport("requestSingleUpdate", "(Ljava/lang/String;Landroid/app/PendingIntent;)V", AccessFlags = 1)] public virtual void RequestSingleUpdate(string criteria, global::Android.App.PendingIntent intent) /* MethodBuilder.Create */ { } /// <summary> /// <para>Register for a single location update using a Criteria and pending intent.</para><para>See requestLocationUpdates(long, float, Criteria, PendingIntent) for more detail on how to use this method.</para><para></para> /// </summary> /// <java-name> /// requestSingleUpdate /// </java-name> [Dot42.DexImport("requestSingleUpdate", "(Landroid/location/Criteria;Landroid/app/PendingIntent;)V", AccessFlags = 1)] public virtual void RequestSingleUpdate(global::Android.Location.Criteria criteria, global::Android.App.PendingIntent intent) /* MethodBuilder.Create */ { } /// <summary> /// <para>Removes all location updates for the specified LocationListener.</para><para>Following this call, updates will no longer occur for this listener.</para><para></para> /// </summary> /// <java-name> /// removeUpdates /// </java-name> [Dot42.DexImport("removeUpdates", "(Landroid/location/LocationListener;)V", AccessFlags = 1)] public virtual void RemoveUpdates(global::Android.Location.ILocationListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Removes all location updates for the specified LocationListener.</para><para>Following this call, updates will no longer occur for this listener.</para><para></para> /// </summary> /// <java-name> /// removeUpdates /// </java-name> [Dot42.DexImport("removeUpdates", "(Landroid/app/PendingIntent;)V", AccessFlags = 1)] public virtual void RemoveUpdates(global::Android.App.PendingIntent listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Set a proximity alert for the location given by the position (latitude, longitude) and the given radius.</para><para>When the device detects that it has entered or exited the area surrounding the location, the given PendingIntent will be used to create an Intent to be fired.</para><para>The fired Intent will have a boolean extra added with key KEY_PROXIMITY_ENTERING. If the value is true, the device is entering the proximity region; if false, it is exiting.</para><para>Due to the approximate nature of position estimation, if the device passes through the given area briefly, it is possible that no Intent will be fired. Similarly, an Intent could be fired if the device passes very close to the given area but does not actually enter it.</para><para>After the number of milliseconds given by the expiration parameter, the location manager will delete this proximity alert and no longer monitor it. A value of -1 indicates that there should be no expiration time.</para><para>Internally, this method uses both NETWORK_PROVIDER and GPS_PROVIDER.</para><para>Before API version 17, this method could be used with android.Manifest.permission#ACCESS_FINE_LOCATION or android.Manifest.permission#ACCESS_COARSE_LOCATION. From API version 17 and onwards, this method requires android.Manifest.permission#ACCESS_FINE_LOCATION permission.</para><para></para> /// </summary> /// <java-name> /// addProximityAlert /// </java-name> [Dot42.DexImport("addProximityAlert", "(DDFJLandroid/app/PendingIntent;)V", AccessFlags = 1)] public virtual void AddProximityAlert(double latitude, double longitude, float radius, long expiration, global::Android.App.PendingIntent intent) /* MethodBuilder.Create */ { } /// <summary> /// <para>Removes the proximity alert with the given PendingIntent.</para><para>Before API version 17, this method could be used with android.Manifest.permission#ACCESS_FINE_LOCATION or android.Manifest.permission#ACCESS_COARSE_LOCATION. From API version 17 and onwards, this method requires android.Manifest.permission#ACCESS_FINE_LOCATION permission.</para><para></para> /// </summary> /// <java-name> /// removeProximityAlert /// </java-name> [Dot42.DexImport("removeProximityAlert", "(Landroid/app/PendingIntent;)V", AccessFlags = 1)] public virtual void RemoveProximityAlert(global::Android.App.PendingIntent intent) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the current enabled/disabled status of the given provider.</para><para>If the user has enabled this provider in the Settings menu, true is returned otherwise false is returned</para><para></para> /// </summary> /// <returns> /// <para>true if the provider is enabled</para> /// </returns> /// <java-name> /// isProviderEnabled /// </java-name> [Dot42.DexImport("isProviderEnabled", "(Ljava/lang/String;)Z", AccessFlags = 1)] public virtual bool IsProviderEnabled(string provider) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns a Location indicating the data from the last known location fix obtained from the given provider.</para><para>This can be done without starting the provider. Note that this location could be out-of-date, for example if the device was turned off and moved to another location.</para><para>If the provider is currently disabled, null is returned.</para><para></para> /// </summary> /// <returns> /// <para>the last known location for the provider, or null</para> /// </returns> /// <java-name> /// getLastKnownLocation /// </java-name> [Dot42.DexImport("getLastKnownLocation", "(Ljava/lang/String;)Landroid/location/Location;", AccessFlags = 1)] public virtual global::Android.Location.Location GetLastKnownLocation(string provider) /* MethodBuilder.Create */ { return default(global::Android.Location.Location); } /// <summary> /// <para>Creates a mock location provider and adds it to the set of active providers.</para><para></para> /// </summary> /// <java-name> /// addTestProvider /// </java-name> [Dot42.DexImport("addTestProvider", "(Ljava/lang/String;ZZZZZZZII)V", AccessFlags = 1)] public virtual void AddTestProvider(string name, bool requiresNetwork, bool requiresSatellite, bool requiresCell, bool hasMonetaryCost, bool supportsAltitude, bool supportsSpeed, bool supportsBearing, int powerRequirement, int accuracy) /* MethodBuilder.Create */ { } /// <summary> /// <para>Removes the mock location provider with the given name.</para><para></para> /// </summary> /// <java-name> /// removeTestProvider /// </java-name> [Dot42.DexImport("removeTestProvider", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void RemoveTestProvider(string provider) /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets a mock location for the given provider. </para><para>This location will be used in place of any actual location from the provider. The location object must have a minimum number of fields set to be considered a valid LocationProvider Location, as per documentation on Location class.</para><para></para> /// </summary> /// <java-name> /// setTestProviderLocation /// </java-name> [Dot42.DexImport("setTestProviderLocation", "(Ljava/lang/String;Landroid/location/Location;)V", AccessFlags = 1)] public virtual void SetTestProviderLocation(string provider, global::Android.Location.Location loc) /* MethodBuilder.Create */ { } /// <summary> /// <para>Removes any mock location associated with the given provider.</para><para></para> /// </summary> /// <java-name> /// clearTestProviderLocation /// </java-name> [Dot42.DexImport("clearTestProviderLocation", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void ClearTestProviderLocation(string provider) /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets a mock enabled value for the given provider. This value will be used in place of any actual value from the provider.</para><para></para> /// </summary> /// <java-name> /// setTestProviderEnabled /// </java-name> [Dot42.DexImport("setTestProviderEnabled", "(Ljava/lang/String;Z)V", AccessFlags = 1)] public virtual void SetTestProviderEnabled(string provider, bool enabled) /* MethodBuilder.Create */ { } /// <summary> /// <para>Removes any mock enabled value associated with the given provider.</para><para></para> /// </summary> /// <java-name> /// clearTestProviderEnabled /// </java-name> [Dot42.DexImport("clearTestProviderEnabled", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void ClearTestProviderEnabled(string provider) /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets mock status values for the given provider. These values will be used in place of any actual values from the provider.</para><para></para> /// </summary> /// <java-name> /// setTestProviderStatus /// </java-name> [Dot42.DexImport("setTestProviderStatus", "(Ljava/lang/String;ILandroid/os/Bundle;J)V", AccessFlags = 1)] public virtual void SetTestProviderStatus(string provider, int status, global::Android.Os.Bundle extras, long updateTime) /* MethodBuilder.Create */ { } /// <summary> /// <para>Removes any mock status values associated with the given provider.</para><para></para> /// </summary> /// <java-name> /// clearTestProviderStatus /// </java-name> [Dot42.DexImport("clearTestProviderStatus", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void ClearTestProviderStatus(string provider) /* MethodBuilder.Create */ { } /// <summary> /// <para>Adds a GPS status listener.</para><para></para> /// </summary> /// <returns> /// <para>true if the listener was successfully added</para> /// </returns> /// <java-name> /// addGpsStatusListener /// </java-name> [Dot42.DexImport("addGpsStatusListener", "(Landroid/location/GpsStatus$Listener;)Z", AccessFlags = 1)] public virtual bool AddGpsStatusListener(global::Android.Location.GpsStatus.IListener listener) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Removes a GPS status listener.</para><para></para> /// </summary> /// <java-name> /// removeGpsStatusListener /// </java-name> [Dot42.DexImport("removeGpsStatusListener", "(Landroid/location/GpsStatus$Listener;)V", AccessFlags = 1)] public virtual void RemoveGpsStatusListener(global::Android.Location.GpsStatus.IListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Adds an NMEA listener.</para><para></para> /// </summary> /// <returns> /// <para>true if the listener was successfully added</para> /// </returns> /// <java-name> /// addNmeaListener /// </java-name> [Dot42.DexImport("addNmeaListener", "(Landroid/location/GpsStatus$NmeaListener;)Z", AccessFlags = 1)] public virtual bool AddNmeaListener(global::Android.Location.GpsStatus.INmeaListener listener) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Removes an NMEA listener.</para><para></para> /// </summary> /// <java-name> /// removeNmeaListener /// </java-name> [Dot42.DexImport("removeNmeaListener", "(Landroid/location/GpsStatus$NmeaListener;)V", AccessFlags = 1)] public virtual void RemoveNmeaListener(global::Android.Location.GpsStatus.INmeaListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Retrieves information about the current status of the GPS engine. This should only be called from the GpsStatus.Listener#onGpsStatusChanged callback to ensure that the data is copied atomically.</para><para>The caller may either pass in a GpsStatus object to set with the latest status information, or pass null to create a new GpsStatus object.</para><para></para> /// </summary> /// <returns> /// <para>status object containing updated GPS status. </para> /// </returns> /// <java-name> /// getGpsStatus /// </java-name> [Dot42.DexImport("getGpsStatus", "(Landroid/location/GpsStatus;)Landroid/location/GpsStatus;", AccessFlags = 1)] public virtual global::Android.Location.GpsStatus GetGpsStatus(global::Android.Location.GpsStatus status) /* MethodBuilder.Create */ { return default(global::Android.Location.GpsStatus); } /// <summary> /// <para>Sends additional commands to a location provider. Can be used to support provider specific extensions to the Location Manager API</para><para></para> /// </summary> /// <returns> /// <para>true if the command succeeds. </para> /// </returns> /// <java-name> /// sendExtraCommand /// </java-name> [Dot42.DexImport("sendExtraCommand", "(Ljava/lang/String;Ljava/lang/String;Landroid/os/Bundle;)Z", AccessFlags = 1)] public virtual bool SendExtraCommand(string provider, string command, global::Android.Os.Bundle extras) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns a list of the names of all known location providers. </para><para>All providers are returned, including ones that are not permitted to be accessed by the calling activity or are currently disabled.</para><para></para> /// </summary> /// <returns> /// <para>list of Strings containing names of the provider </para> /// </returns> /// <java-name> /// getAllProviders /// </java-name> public global::Java.Util.IList<string> AllProviders { [Dot42.DexImport("getAllProviders", "()Ljava/util/List;", AccessFlags = 1, Signature = "()Ljava/util/List<Ljava/lang/String;>;")] get{ return GetAllProviders(); } } } /// <summary> /// <para>A data class representing a geographic location.</para><para>A location can consist of a latitude, longitude, timestamp, and other information such as bearing, altitude and velocity.</para><para>All locations generated by the LocationManager are guaranteed to have a valid latitude, longitude, and timestamp (both UTC time and elapsed real-time since boot), all other parameters are optional. </para> /// </summary> /// <java-name> /// android/location/Location /// </java-name> [Dot42.DexImport("android/location/Location", AccessFlags = 33)] public partial class Location : global::Android.Os.IParcelable /* scope: __dot42__ */ { /// <summary> /// <para>Constant used to specify formatting of a latitude or longitude in the form "[+-]DDD.DDDDD where D indicates degrees. </para> /// </summary> /// <java-name> /// FORMAT_DEGREES /// </java-name> [Dot42.DexImport("FORMAT_DEGREES", "I", AccessFlags = 25)] public const int FORMAT_DEGREES = 0; /// <summary> /// <para>Constant used to specify formatting of a latitude or longitude in the form "[+-]DDD:MM.MMMMM" where D indicates degrees and M indicates minutes of arc (1 minute = 1/60th of a degree). </para> /// </summary> /// <java-name> /// FORMAT_MINUTES /// </java-name> [Dot42.DexImport("FORMAT_MINUTES", "I", AccessFlags = 25)] public const int FORMAT_MINUTES = 1; /// <summary> /// <para>Constant used to specify formatting of a latitude or longitude in the form "DDD:MM:SS.SSSSS" where D indicates degrees, M indicates minutes of arc, and S indicates seconds of arc (1 minute = 1/60th of a degree, 1 second = 1/3600th of a degree). </para> /// </summary> /// <java-name> /// FORMAT_SECONDS /// </java-name> [Dot42.DexImport("FORMAT_SECONDS", "I", AccessFlags = 25)] public const int FORMAT_SECONDS = 2; /// <java-name> /// CREATOR /// </java-name> [Dot42.DexImport("CREATOR", "Landroid/os/Parcelable$Creator;", AccessFlags = 25)] public static readonly global::Android.Os.IParcelable_ICreator<global::Android.Location.Location> CREATOR; /// <summary> /// <para>Construct a new Location object that is copied from an existing one. </para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public Location(string l) /* MethodBuilder.Create */ { } /// <summary> /// <para>Construct a new Location object that is copied from an existing one. </para> /// </summary> [Dot42.DexImport("<init>", "(Landroid/location/Location;)V", AccessFlags = 1)] public Location(global::Android.Location.Location l) /* MethodBuilder.Create */ { } /// <java-name> /// dump /// </java-name> [Dot42.DexImport("dump", "(Landroid/util/Printer;Ljava/lang/String;)V", AccessFlags = 1)] public virtual void Dump(global::Android.Util.IPrinter pw, string prefix) /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets the contents of the location to the values from the given location. </para> /// </summary> /// <java-name> /// set /// </java-name> [Dot42.DexImport("set", "(Landroid/location/Location;)V", AccessFlags = 1)] public virtual void Set(global::Android.Location.Location l) /* MethodBuilder.Create */ { } /// <summary> /// <para>Clears the contents of the location. </para> /// </summary> /// <java-name> /// reset /// </java-name> [Dot42.DexImport("reset", "()V", AccessFlags = 1)] public virtual void Reset() /* MethodBuilder.Create */ { } /// <summary> /// <para>Converts a coordinate to a String representation. The outputType may be one of FORMAT_DEGREES, FORMAT_MINUTES, or FORMAT_SECONDS. The coordinate must be a valid double between -180.0 and 180.0.</para><para></para> /// </summary> /// <java-name> /// convert /// </java-name> [Dot42.DexImport("convert", "(DI)Ljava/lang/String;", AccessFlags = 9)] public static string Convert(double coordinate, int outputType) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Converts a String in one of the formats described by FORMAT_DEGREES, FORMAT_MINUTES, or FORMAT_SECONDS into a double.</para><para></para> /// </summary> /// <java-name> /// convert /// </java-name> [Dot42.DexImport("convert", "(Ljava/lang/String;)D", AccessFlags = 9)] public static double Convert(string coordinate) /* MethodBuilder.Create */ { return default(double); } /// <summary> /// <para>Computes the approximate distance in meters between two locations, and optionally the initial and final bearings of the shortest path between them. Distance and bearing are defined using the WGS84 ellipsoid.</para><para>The computed distance is stored in results[0]. If results has length 2 or greater, the initial bearing is stored in results[1]. If results has length 3 or greater, the final bearing is stored in results[2].</para><para></para> /// </summary> /// <java-name> /// distanceBetween /// </java-name> [Dot42.DexImport("distanceBetween", "(DDDD[F)V", AccessFlags = 9)] public static void DistanceBetween(double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the approximate distance in meters between this location and the given location. Distance is defined using the WGS84 ellipsoid.</para><para></para> /// </summary> /// <returns> /// <para>the approximate distance in meters </para> /// </returns> /// <java-name> /// distanceTo /// </java-name> [Dot42.DexImport("distanceTo", "(Landroid/location/Location;)F", AccessFlags = 1)] public virtual float DistanceTo(global::Android.Location.Location dest) /* MethodBuilder.Create */ { return default(float); } /// <summary> /// <para>Returns the approximate initial bearing in degrees East of true North when traveling along the shortest path between this location and the given location. The shortest path is defined using the WGS84 ellipsoid. Locations that are (nearly) antipodal may produce meaningless results.</para><para></para> /// </summary> /// <returns> /// <para>the initial bearing in degrees </para> /// </returns> /// <java-name> /// bearingTo /// </java-name> [Dot42.DexImport("bearingTo", "(Landroid/location/Location;)F", AccessFlags = 1)] public virtual float BearingTo(global::Android.Location.Location dest) /* MethodBuilder.Create */ { return default(float); } /// <summary> /// <para>Returns the name of the provider that generated this fix.</para><para></para> /// </summary> /// <returns> /// <para>the provider, or null if it has not been set </para> /// </returns> /// <java-name> /// getProvider /// </java-name> [Dot42.DexImport("getProvider", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetProvider() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the name of the provider that generated this fix. </para> /// </summary> /// <java-name> /// setProvider /// </java-name> [Dot42.DexImport("setProvider", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetProvider(string provider) /* MethodBuilder.Create */ { } /// <summary> /// <para>Return the UTC time of this fix, in milliseconds since January 1, 1970.</para><para>Note that the UTC time on a device is not monotonic: it can jump forwards or backwards unpredictably. So always use getElapsedRealtimeNanos when calculating time deltas.</para><para>On the other hand, getTime is useful for presenting a human readable time to the user, or for carefully comparing location fixes across reboot or across devices.</para><para>All locations generated by the LocationManager are guaranteed to have a valid UTC time, however remember that the system time may have changed since the location was generated.</para><para></para> /// </summary> /// <returns> /// <para>time of fix, in milliseconds since January 1, 1970. </para> /// </returns> /// <java-name> /// getTime /// </java-name> [Dot42.DexImport("getTime", "()J", AccessFlags = 1)] public virtual long GetTime() /* MethodBuilder.Create */ { return default(long); } /// <summary> /// <para>Set the UTC time of this fix, in milliseconds since January 1, 1970.</para><para></para> /// </summary> /// <java-name> /// setTime /// </java-name> [Dot42.DexImport("setTime", "(J)V", AccessFlags = 1)] public virtual void SetTime(long time) /* MethodBuilder.Create */ { } /// <summary> /// <para>Get the latitude, in degrees.</para><para>All locations generated by the LocationManager will have a valid latitude. </para> /// </summary> /// <java-name> /// getLatitude /// </java-name> [Dot42.DexImport("getLatitude", "()D", AccessFlags = 1)] public virtual double GetLatitude() /* MethodBuilder.Create */ { return default(double); } /// <summary> /// <para>Set the latitude, in degrees. </para> /// </summary> /// <java-name> /// setLatitude /// </java-name> [Dot42.DexImport("setLatitude", "(D)V", AccessFlags = 1)] public virtual void SetLatitude(double latitude) /* MethodBuilder.Create */ { } /// <summary> /// <para>Get the longitude, in degrees.</para><para>All locations generated by the LocationManager will have a valid longitude. </para> /// </summary> /// <java-name> /// getLongitude /// </java-name> [Dot42.DexImport("getLongitude", "()D", AccessFlags = 1)] public virtual double GetLongitude() /* MethodBuilder.Create */ { return default(double); } /// <summary> /// <para>Set the longitude, in degrees. </para> /// </summary> /// <java-name> /// setLongitude /// </java-name> [Dot42.DexImport("setLongitude", "(D)V", AccessFlags = 1)] public virtual void SetLongitude(double longitude) /* MethodBuilder.Create */ { } /// <summary> /// <para>True if this location has an altitude. </para> /// </summary> /// <java-name> /// hasAltitude /// </java-name> [Dot42.DexImport("hasAltitude", "()Z", AccessFlags = 1)] public virtual bool HasAltitude() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Get the altitude if available, in meters above sea level.</para><para>If this location does not have an altitude then 0.0 is returned. </para> /// </summary> /// <java-name> /// getAltitude /// </java-name> [Dot42.DexImport("getAltitude", "()D", AccessFlags = 1)] public virtual double GetAltitude() /* MethodBuilder.Create */ { return default(double); } /// <summary> /// <para>Set the altitude, in meters above sea level.</para><para>Following this call hasAltitude will return true. </para> /// </summary> /// <java-name> /// setAltitude /// </java-name> [Dot42.DexImport("setAltitude", "(D)V", AccessFlags = 1)] public virtual void SetAltitude(double altitude) /* MethodBuilder.Create */ { } /// <summary> /// <para>Remove the altitude from this location.</para><para>Following this call hasAltitude will return false, and getAltitude will return 0.0. </para> /// </summary> /// <java-name> /// removeAltitude /// </java-name> [Dot42.DexImport("removeAltitude", "()V", AccessFlags = 1)] public virtual void RemoveAltitude() /* MethodBuilder.Create */ { } /// <summary> /// <para>True if this location has a speed. </para> /// </summary> /// <java-name> /// hasSpeed /// </java-name> [Dot42.DexImport("hasSpeed", "()Z", AccessFlags = 1)] public virtual bool HasSpeed() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Get the speed if it is available, in meters/second over ground.</para><para>If this location does not have a speed then 0.0 is returned. </para> /// </summary> /// <java-name> /// getSpeed /// </java-name> [Dot42.DexImport("getSpeed", "()F", AccessFlags = 1)] public virtual float GetSpeed() /* MethodBuilder.Create */ { return default(float); } /// <summary> /// <para>Set the speed, in meters/second over ground.</para><para>Following this call hasSpeed will return true. </para> /// </summary> /// <java-name> /// setSpeed /// </java-name> [Dot42.DexImport("setSpeed", "(F)V", AccessFlags = 1)] public virtual void SetSpeed(float speed) /* MethodBuilder.Create */ { } /// <summary> /// <para>Remove the speed from this location.</para><para>Following this call hasSpeed will return false, and getSpeed will return 0.0. </para> /// </summary> /// <java-name> /// removeSpeed /// </java-name> [Dot42.DexImport("removeSpeed", "()V", AccessFlags = 1)] public virtual void RemoveSpeed() /* MethodBuilder.Create */ { } /// <summary> /// <para>True if this location has a bearing. </para> /// </summary> /// <java-name> /// hasBearing /// </java-name> [Dot42.DexImport("hasBearing", "()Z", AccessFlags = 1)] public virtual bool HasBearing() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Get the bearing, in degrees.</para><para>Bearing is the horizontal direction of travel of this device, and is not related to the device orientation. It is guaranteed to be in the range (0.0, 360.0] if the device has a bearing.</para><para>If this location does not have a bearing then 0.0 is returned. </para> /// </summary> /// <java-name> /// getBearing /// </java-name> [Dot42.DexImport("getBearing", "()F", AccessFlags = 1)] public virtual float GetBearing() /* MethodBuilder.Create */ { return default(float); } /// <summary> /// <para>Set the bearing, in degrees.</para><para>Bearing is the horizontal direction of travel of this device, and is not related to the device orientation.</para><para>The input will be wrapped into the range (0.0, 360.0]. </para> /// </summary> /// <java-name> /// setBearing /// </java-name> [Dot42.DexImport("setBearing", "(F)V", AccessFlags = 1)] public virtual void SetBearing(float bearing) /* MethodBuilder.Create */ { } /// <summary> /// <para>Remove the bearing from this location.</para><para>Following this call hasBearing will return false, and getBearing will return 0.0. </para> /// </summary> /// <java-name> /// removeBearing /// </java-name> [Dot42.DexImport("removeBearing", "()V", AccessFlags = 1)] public virtual void RemoveBearing() /* MethodBuilder.Create */ { } /// <summary> /// <para>True if this location has an accuracy.</para><para>All locations generated by the LocationManager have an accuracy. </para> /// </summary> /// <java-name> /// hasAccuracy /// </java-name> [Dot42.DexImport("hasAccuracy", "()Z", AccessFlags = 1)] public virtual bool HasAccuracy() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Get the estimated accuracy of this location, in meters.</para><para>We define accuracy as the radius of 68% confidence. In other words, if you draw a circle centered at this location's latitude and longitude, and with a radius equal to the accuracy, then there is a 68% probability that the true location is inside the circle.</para><para>In statistical terms, it is assumed that location errors are random with a normal distribution, so the 68% confidence circle represents one standard deviation. Note that in practice, location errors do not always follow such a simple distribution.</para><para>This accuracy estimation is only concerned with horizontal accuracy, and does not indicate the accuracy of bearing, velocity or altitude if those are included in this Location.</para><para>If this location does not have an accuracy, then 0.0 is returned. All locations generated by the LocationManager include an accuracy. </para> /// </summary> /// <java-name> /// getAccuracy /// </java-name> [Dot42.DexImport("getAccuracy", "()F", AccessFlags = 1)] public virtual float GetAccuracy() /* MethodBuilder.Create */ { return default(float); } /// <summary> /// <para>Set the estimated accuracy of this location, meters.</para><para>See getAccuracy for the definition of accuracy.</para><para>Following this call hasAccuracy will return true. </para> /// </summary> /// <java-name> /// setAccuracy /// </java-name> [Dot42.DexImport("setAccuracy", "(F)V", AccessFlags = 1)] public virtual void SetAccuracy(float accuracy) /* MethodBuilder.Create */ { } /// <summary> /// <para>Remove the accuracy from this location.</para><para>Following this call hasAccuracy will return false, and getAccuracy will return 0.0. </para> /// </summary> /// <java-name> /// removeAccuracy /// </java-name> [Dot42.DexImport("removeAccuracy", "()V", AccessFlags = 1)] public virtual void RemoveAccuracy() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns additional provider-specific information about the location fix as a Bundle. The keys and values are determined by the provider. If no additional information is available, null is returned.</para><para>A number of common key/value pairs are listed below. Providers that use any of the keys on this list must provide the corresponding value as described below.</para><para><ul><li><para>satellites - the number of satellites used to derive the fix </para></li></ul></para> /// </summary> /// <java-name> /// getExtras /// </java-name> [Dot42.DexImport("getExtras", "()Landroid/os/Bundle;", AccessFlags = 1)] public virtual global::Android.Os.Bundle GetExtras() /* MethodBuilder.Create */ { return default(global::Android.Os.Bundle); } /// <summary> /// <para>Sets the extra information associated with this fix to the given Bundle. </para> /// </summary> /// <java-name> /// setExtras /// </java-name> [Dot42.DexImport("setExtras", "(Landroid/os/Bundle;)V", AccessFlags = 1)] public virtual void SetExtras(global::Android.Os.Bundle extras) /* MethodBuilder.Create */ { } /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Describe the kinds of special objects contained in this Parcelable's marshalled representation.</para><para></para> /// </summary> /// <returns> /// <para>a bitmask indicating the set of special object types marshalled by the Parcelable. </para> /// </returns> /// <java-name> /// describeContents /// </java-name> [Dot42.DexImport("describeContents", "()I", AccessFlags = 1)] public virtual int DescribeContents() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Flatten this object in to a Parcel.</para><para></para> /// </summary> /// <java-name> /// writeToParcel /// </java-name> [Dot42.DexImport("writeToParcel", "(Landroid/os/Parcel;I)V", AccessFlags = 1)] public virtual void WriteToParcel(global::Android.Os.Parcel dest, int flags) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal Location() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns the name of the provider that generated this fix.</para><para></para> /// </summary> /// <returns> /// <para>the provider, or null if it has not been set </para> /// </returns> /// <java-name> /// getProvider /// </java-name> public string Provider { [Dot42.DexImport("getProvider", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetProvider(); } [Dot42.DexImport("setProvider", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetProvider(value); } } /// <summary> /// <para>Return the UTC time of this fix, in milliseconds since January 1, 1970.</para><para>Note that the UTC time on a device is not monotonic: it can jump forwards or backwards unpredictably. So always use getElapsedRealtimeNanos when calculating time deltas.</para><para>On the other hand, getTime is useful for presenting a human readable time to the user, or for carefully comparing location fixes across reboot or across devices.</para><para>All locations generated by the LocationManager are guaranteed to have a valid UTC time, however remember that the system time may have changed since the location was generated.</para><para></para> /// </summary> /// <returns> /// <para>time of fix, in milliseconds since January 1, 1970. </para> /// </returns> /// <java-name> /// getTime /// </java-name> public long Time { [Dot42.DexImport("getTime", "()J", AccessFlags = 1)] get{ return GetTime(); } [Dot42.DexImport("setTime", "(J)V", AccessFlags = 1)] set{ SetTime(value); } } /// <summary> /// <para>Get the latitude, in degrees.</para><para>All locations generated by the LocationManager will have a valid latitude. </para> /// </summary> /// <java-name> /// getLatitude /// </java-name> public double Latitude { [Dot42.DexImport("getLatitude", "()D", AccessFlags = 1)] get{ return GetLatitude(); } [Dot42.DexImport("setLatitude", "(D)V", AccessFlags = 1)] set{ SetLatitude(value); } } /// <summary> /// <para>Get the longitude, in degrees.</para><para>All locations generated by the LocationManager will have a valid longitude. </para> /// </summary> /// <java-name> /// getLongitude /// </java-name> public double Longitude { [Dot42.DexImport("getLongitude", "()D", AccessFlags = 1)] get{ return GetLongitude(); } [Dot42.DexImport("setLongitude", "(D)V", AccessFlags = 1)] set{ SetLongitude(value); } } /// <summary> /// <para>Get the altitude if available, in meters above sea level.</para><para>If this location does not have an altitude then 0.0 is returned. </para> /// </summary> /// <java-name> /// getAltitude /// </java-name> public double Altitude { [Dot42.DexImport("getAltitude", "()D", AccessFlags = 1)] get{ return GetAltitude(); } [Dot42.DexImport("setAltitude", "(D)V", AccessFlags = 1)] set{ SetAltitude(value); } } /// <summary> /// <para>Get the speed if it is available, in meters/second over ground.</para><para>If this location does not have a speed then 0.0 is returned. </para> /// </summary> /// <java-name> /// getSpeed /// </java-name> public float Speed { [Dot42.DexImport("getSpeed", "()F", AccessFlags = 1)] get{ return GetSpeed(); } [Dot42.DexImport("setSpeed", "(F)V", AccessFlags = 1)] set{ SetSpeed(value); } } /// <summary> /// <para>Get the bearing, in degrees.</para><para>Bearing is the horizontal direction of travel of this device, and is not related to the device orientation. It is guaranteed to be in the range (0.0, 360.0] if the device has a bearing.</para><para>If this location does not have a bearing then 0.0 is returned. </para> /// </summary> /// <java-name> /// getBearing /// </java-name> public float Bearing { [Dot42.DexImport("getBearing", "()F", AccessFlags = 1)] get{ return GetBearing(); } [Dot42.DexImport("setBearing", "(F)V", AccessFlags = 1)] set{ SetBearing(value); } } /// <summary> /// <para>Get the estimated accuracy of this location, in meters.</para><para>We define accuracy as the radius of 68% confidence. In other words, if you draw a circle centered at this location's latitude and longitude, and with a radius equal to the accuracy, then there is a 68% probability that the true location is inside the circle.</para><para>In statistical terms, it is assumed that location errors are random with a normal distribution, so the 68% confidence circle represents one standard deviation. Note that in practice, location errors do not always follow such a simple distribution.</para><para>This accuracy estimation is only concerned with horizontal accuracy, and does not indicate the accuracy of bearing, velocity or altitude if those are included in this Location.</para><para>If this location does not have an accuracy, then 0.0 is returned. All locations generated by the LocationManager include an accuracy. </para> /// </summary> /// <java-name> /// getAccuracy /// </java-name> public float Accuracy { [Dot42.DexImport("getAccuracy", "()F", AccessFlags = 1)] get{ return GetAccuracy(); } [Dot42.DexImport("setAccuracy", "(F)V", AccessFlags = 1)] set{ SetAccuracy(value); } } /// <summary> /// <para>Returns additional provider-specific information about the location fix as a Bundle. The keys and values are determined by the provider. If no additional information is available, null is returned.</para><para>A number of common key/value pairs are listed below. Providers that use any of the keys on this list must provide the corresponding value as described below.</para><para><ul><li><para>satellites - the number of satellites used to derive the fix </para></li></ul></para> /// </summary> /// <java-name> /// getExtras /// </java-name> public global::Android.Os.Bundle Extras { [Dot42.DexImport("getExtras", "()Landroid/os/Bundle;", AccessFlags = 1)] get{ return GetExtras(); } [Dot42.DexImport("setExtras", "(Landroid/os/Bundle;)V", AccessFlags = 1)] set{ SetExtras(value); } } } /// <summary> /// <para>An abstract superclass for location providers. A location provider provides periodic reports on the geographical location of the device.</para><para>Each provider has a set of criteria under which it may be used; for example, some providers require GPS hardware and visibility to a number of satellites; others require the use of the cellular radio, or access to a specific carrier's network, or to the internet. They may also have different battery consumption characteristics or monetary costs to the user. The Criteria class allows providers to be selected based on user-specified criteria. </para> /// </summary> /// <java-name> /// android/location/LocationProvider /// </java-name> [Dot42.DexImport("android/location/LocationProvider", AccessFlags = 1057)] public abstract partial class LocationProvider /* scope: __dot42__ */ { /// <java-name> /// OUT_OF_SERVICE /// </java-name> [Dot42.DexImport("OUT_OF_SERVICE", "I", AccessFlags = 25)] public const int OUT_OF_SERVICE = 0; /// <java-name> /// TEMPORARILY_UNAVAILABLE /// </java-name> [Dot42.DexImport("TEMPORARILY_UNAVAILABLE", "I", AccessFlags = 25)] public const int TEMPORARILY_UNAVAILABLE = 1; /// <java-name> /// AVAILABLE /// </java-name> [Dot42.DexImport("AVAILABLE", "I", AccessFlags = 25)] public const int AVAILABLE = 2; [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal LocationProvider() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the name of this provider. </para> /// </summary> /// <java-name> /// getName /// </java-name> [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetName() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns true if this provider meets the given criteria, false otherwise. </para> /// </summary> /// <java-name> /// meetsCriteria /// </java-name> [Dot42.DexImport("meetsCriteria", "(Landroid/location/Criteria;)Z", AccessFlags = 1)] public virtual bool MeetsCriteria(global::Android.Location.Criteria criteria) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns true if the provider requires access to a data network (e.g., the Internet), false otherwise. </para> /// </summary> /// <java-name> /// requiresNetwork /// </java-name> [Dot42.DexImport("requiresNetwork", "()Z", AccessFlags = 1025)] public abstract bool RequiresNetwork() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns true if the provider requires access to a satellite-based positioning system (e.g., GPS), false otherwise. </para> /// </summary> /// <java-name> /// requiresSatellite /// </java-name> [Dot42.DexImport("requiresSatellite", "()Z", AccessFlags = 1025)] public abstract bool RequiresSatellite() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns true if the provider requires access to an appropriate cellular network (e.g., to make use of cell tower IDs), false otherwise. </para> /// </summary> /// <java-name> /// requiresCell /// </java-name> [Dot42.DexImport("requiresCell", "()Z", AccessFlags = 1025)] public abstract bool RequiresCell() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns true if the use of this provider may result in a monetary charge to the user, false if use is free. It is up to each provider to give accurate information. </para> /// </summary> /// <java-name> /// hasMonetaryCost /// </java-name> [Dot42.DexImport("hasMonetaryCost", "()Z", AccessFlags = 1025)] public abstract bool HasMonetaryCost() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns true if the provider is able to provide altitude information, false otherwise. A provider that reports altitude under most circumstances but may occassionally not report it should return true. </para> /// </summary> /// <java-name> /// supportsAltitude /// </java-name> [Dot42.DexImport("supportsAltitude", "()Z", AccessFlags = 1025)] public abstract bool SupportsAltitude() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns true if the provider is able to provide speed information, false otherwise. A provider that reports speed under most circumstances but may occassionally not report it should return true. </para> /// </summary> /// <java-name> /// supportsSpeed /// </java-name> [Dot42.DexImport("supportsSpeed", "()Z", AccessFlags = 1025)] public abstract bool SupportsSpeed() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns true if the provider is able to provide bearing information, false otherwise. A provider that reports bearing under most circumstances but may occassionally not report it should return true. </para> /// </summary> /// <java-name> /// supportsBearing /// </java-name> [Dot42.DexImport("supportsBearing", "()Z", AccessFlags = 1025)] public abstract bool SupportsBearing() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the power requirement for this provider.</para><para></para> /// </summary> /// <returns> /// <para>the power requirement for this provider, as one of the constants Criteria.POWER_REQUIREMENT_*. </para> /// </returns> /// <java-name> /// getPowerRequirement /// </java-name> [Dot42.DexImport("getPowerRequirement", "()I", AccessFlags = 1025)] public abstract int GetPowerRequirement() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns a constant describing horizontal accuracy of this provider. If the provider returns finer grain or exact location, Criteria#ACCURACY_FINE is returned, otherwise if the location is only approximate then Criteria#ACCURACY_COARSE is returned. </para> /// </summary> /// <java-name> /// getAccuracy /// </java-name> [Dot42.DexImport("getAccuracy", "()I", AccessFlags = 1025)] public abstract int GetAccuracy() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the name of this provider. </para> /// </summary> /// <java-name> /// getName /// </java-name> public string Name { [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetName(); } } /// <summary> /// <para>Returns the power requirement for this provider.</para><para></para> /// </summary> /// <returns> /// <para>the power requirement for this provider, as one of the constants Criteria.POWER_REQUIREMENT_*. </para> /// </returns> /// <java-name> /// getPowerRequirement /// </java-name> public int PowerRequirement { [Dot42.DexImport("getPowerRequirement", "()I", AccessFlags = 1025)] get{ return GetPowerRequirement(); } } /// <summary> /// <para>Returns a constant describing horizontal accuracy of this provider. If the provider returns finer grain or exact location, Criteria#ACCURACY_FINE is returned, otherwise if the location is only approximate then Criteria#ACCURACY_COARSE is returned. </para> /// </summary> /// <java-name> /// getAccuracy /// </java-name> public int Accuracy { [Dot42.DexImport("getAccuracy", "()I", AccessFlags = 1025)] get{ return GetAccuracy(); } } } }
42.480971
1,376
0.639819
[ "Apache-2.0" ]
Dot42Xna/master
Generated/v4.0/Android.Location.cs
129,482
C#
#if HE_SYSCORE && STEAMWORKS_NET && HE_STEAMCOMPLETE && !HE_STEAMFOUNDATION && !DISABLESTEAMWORKS using Steamworks; using UnityEngine.Events; namespace HeathenEngineering.SteamworksIntegration { [System.Serializable] public class AvailableBeaconLocationsUpdatedEvent : UnityEvent<AvailableBeaconLocationsUpdated_t> { } } #endif
33.8
105
0.813609
[ "MIT" ]
KD-Kevin/Age-of-War---Like-Game
Age Of War Game/Assets/Imported Assets/_Heathen Engineering/Assets/com.heathen.steamworkscomplete/Runtime/Events/AvailableBeaconLocationsUpdatedEvent.cs
340
C#
using System; using System.Threading.Tasks; using Windows.ApplicationModel.Core; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace Template10.Services.WindowService { public class WindowHelper { private Window Main { get; set; } private Window Window { get; set; } private ApplicationView View { get; set; } private CoreApplicationView CoreView { get; set; } public bool IsOpen => CoreView != null; public async Task ShowAsync<T>(object param = null, ViewSizePreference size = ViewSizePreference.UseHalf) { if (this.IsOpen) { await CoreView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () => { this.Close(); }); } else { this.Main = Window.Current; } this.CoreView = CoreApplication.CreateNewView(); await CoreView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () => { this.Window = Window.Current; var frame = new Frame(); frame.NavigationFailed += (s, e) => { System.Diagnostics.Debugger.Break(); }; this.Window.Content = frame; frame.Navigate(typeof(T), param); this.View = ApplicationView.GetForCurrentView(); this.View.Consolidated += Helper_Consolidated; }); if (await ApplicationViewSwitcher.TryShowAsStandaloneAsync(this.View.Id, size)) { await ApplicationViewSwitcher.SwitchAsync(this.View.Id); } } void Helper_Consolidated(ApplicationView sender, ApplicationViewConsolidatedEventArgs args) { this.Close(); } public void Close() { if (this.IsOpen) { if (CoreApplication.GetCurrentView().IsMain) return; this.View.Consolidated -= Helper_Consolidated; try { this.Window.Close(); } finally { this.View = null; this.Window = null; this.CoreView = null; } // reactivate main var view = CoreApplication.GetCurrentView(); view.CoreWindow.Activate(); } } } }
32.15
114
0.520995
[ "Apache-2.0" ]
ArtjomP/Template10
Template10 (Services)/WindowService/WindowHelper.cs
2,574
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("VisualStudio.Delphi.ConverterWizard.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Loris Technologies Inc")] [assembly: AssemblyProduct("VisualStudio.Delphi.ConverterWizard.Test")] [assembly: AssemblyCopyright("Copyright © Loris Technologies Inc 2007")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM componenets. 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("0a90a6aa-016b-4ee8-b8a3-6076690f365c")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
40.5
84
0.759259
[ "Unlicense" ]
JackTrapper/Delphi-for-Visual-Studio
DelphiForVisualStudio/VisualStudio.Delphi.ConverterWizard.Test/Properties/AssemblyInfo.cs
1,461
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using Materia.Imaging; using Materia.Nodes.Helpers; using Materia.Nodes.Attributes; using Newtonsoft.Json; using Materia.Textures; using Materia.Imaging.GLProcessing; namespace Materia.Nodes.Atomic { public enum BlendType { AddSub = 0, Copy = 1, Multiply = 2, Screen = 3, Overlay = 4, HardLight = 5, SoftLight = 6, ColorDodge = 7, LinearDodge = 8, ColorBurn = 9, LinearBurn = 10, VividLight = 11, Divide = 12, Subtract = 13, Difference = 14, Darken = 15, Lighten = 16, Hue = 17, Saturation = 18, Color = 19, Luminosity = 20, LinearLight = 21 } public class BlendNode : ImageNode { NodeInput first; NodeInput second; NodeInput mask; NodeOutput Output; BlendProcessor processor; float alpha; [Promote(NodeType.Float)] [Slider(IsInt = false, Max = 1, Min = 0, Snap = false, Ticks = new float[0])] public float Alpha { get { return alpha; } set { if (value < 0) alpha = 0; if (value > 1) alpha = 1; alpha = value; TryAndProcess(); } } BlendType mode; [Promote(NodeType.Float)] [Title(Title = "Blend Mode")] public BlendType Mode { get { return mode; } set { mode = value; TryAndProcess(); } } public BlendNode(int w, int h, GraphPixelType p = GraphPixelType.RGBA) { Name = "Blend"; width = w; height = h; alpha = 1; mode = BlendType.Copy; previewProcessor = new BasicImageRenderer(); processor = new BlendProcessor(); internalPixelType = p; tileX = tileY = 1; Id = Guid.NewGuid().ToString(); Inputs = new List<NodeInput>(); Output = new NodeOutput(NodeType.Color | NodeType.Gray, this); first = new NodeInput(NodeType.Color | NodeType.Gray, this, "Foreground"); second = new NodeInput(NodeType.Color | NodeType.Gray, this, "Background"); mask = new NodeInput(NodeType.Gray, this, "Mask"); first.OnInputAdded += OnInputAdded; first.OnInputRemoved += OnInputRemoved; first.OnInputChanged += OnInputChanged; second.OnInputRemoved += OnInputRemoved; second.OnInputAdded += OnInputAdded; second.OnInputChanged += OnInputChanged; mask.OnInputRemoved += OnInputRemoved; mask.OnInputAdded += OnInputAdded; mask.OnInputChanged += OnInputChanged; Inputs.Add(first); Inputs.Add(second); Inputs.Add(mask); Outputs = new List<NodeOutput>(); Outputs.Add(Output); } private void OnInputChanged(NodeInput n) { TryAndProcess(); } private void OnInputRemoved(NodeInput n) { TryAndProcess(); } private void OnInputAdded(NodeInput n) { TryAndProcess(); } public override void TryAndProcess() { if(first.HasInput && second.HasInput) { Process(); } } void Process() { GLTextuer2D i1 = (GLTextuer2D)first.Input.Data; GLTextuer2D i2 = (GLTextuer2D)second.Input.Data; GLTextuer2D i3 = null; if(mask.Input != null) { i3 = (GLTextuer2D)mask.Input.Data; } if (i1 == null || i2 == null) return; if (i1.Id == 0) return; if (i2.Id == 0) return; CreateBufferIfNeeded(); int pmode = (int)mode; float palpha = alpha; if(ParentGraph != null && ParentGraph.HasParameterValue(Id, "Mode")) { pmode = ParentGraph.GetParameterValue<int>(Id, "Mode"); } if(ParentGraph != null && ParentGraph.HasParameterValue(Id, "Alpha")) { palpha = ParentGraph.GetParameterValue<float>(Id, "Alpha"); } processor.TileX = tileX; processor.TileY = tileY; processor.Alpha = palpha; processor.BlendMode = pmode; processor.Process(width, height, i1, i2, i3, buffer); processor.Complete(); Updated(); Output.Data = buffer; Output.Changed(); } public override void Dispose() { base.Dispose(); if(processor != null) { processor.Release(); processor = null; } } protected override void OnWidthHeightSet() { TryAndProcess(); } public class BlendData : NodeData { public string mode; public float alpha; } public override string GetJson() { BlendData d = new BlendData(); FillBaseNodeData(d); d.mode = mode.ToString(); d.alpha = alpha; return JsonConvert.SerializeObject(d); } public override void FromJson(Dictionary<string, Node> nodes, string data) { BlendData d = JsonConvert.DeserializeObject<BlendData>(data); SetBaseNodeDate(d); Enum.TryParse<BlendType>(d.mode, out mode); alpha = d.alpha; SetConnections(nodes, d.outputs); OnWidthHeightSet(); } } }
25.391667
87
0.498523
[ "MIT" ]
0xflotus/Materia
Materia/Nodes/Atomic/BlendNode.cs
6,096
C#
using Content.Client.UserInterface.Stylesheets; using Content.Client.Utility; using Content.Shared.GameObjects.Components.Atmos.GasTank; using Robust.Client.Graphics.Drawing; using Robust.Client.Interfaces.ResourceManagement; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; using Robust.Client.UserInterface.CustomControls; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Maths; namespace Content.Client.UserInterface.Atmos.GasTank { public class GasTankWindow : BaseWindow { private GasTankBoundUserInterface _owner; private readonly Label _lblName; private readonly VBoxContainer _topContainer; private readonly Control _contentContainer; private readonly IResourceCache _resourceCache = default!; private readonly RichTextLabel _lblPressure; private readonly FloatSpinBox _spbPressure; private readonly RichTextLabel _lblInternals; private readonly Button _btnInternals; public GasTankWindow(GasTankBoundUserInterface owner) { TextureButton btnClose; _resourceCache = IoCManager.Resolve<IResourceCache>(); _owner = owner; var rootContainer = new LayoutContainer {Name = "GasTankRoot"}; AddChild(rootContainer); MouseFilter = MouseFilterMode.Stop; var panelTex = _resourceCache.GetTexture("/Textures/Interface/Nano/button.svg.96dpi.png"); var back = new StyleBoxTexture { Texture = panelTex, Modulate = Color.FromHex("#25252A"), }; back.SetPatchMargin(StyleBox.Margin.All, 10); var topPanel = new PanelContainer { PanelOverride = back, MouseFilter = MouseFilterMode.Pass }; var bottomWrap = new LayoutContainer { Name = "BottomWrap" }; rootContainer.AddChild(topPanel); rootContainer.AddChild(bottomWrap); LayoutContainer.SetAnchorPreset(topPanel, LayoutContainer.LayoutPreset.Wide); LayoutContainer.SetMarginBottom(topPanel, -85); LayoutContainer.SetAnchorPreset(bottomWrap, LayoutContainer.LayoutPreset.VerticalCenterWide); LayoutContainer.SetGrowHorizontal(bottomWrap, LayoutContainer.GrowDirection.Both); var topContainerWrap = new VBoxContainer { Children = { (_topContainer = new VBoxContainer()), new Control {CustomMinimumSize = (0, 110)} } }; rootContainer.AddChild(topContainerWrap); LayoutContainer.SetAnchorPreset(topContainerWrap, LayoutContainer.LayoutPreset.Wide); var font = _resourceCache.GetFont("/Fonts/Boxfont-round/Boxfont Round.ttf", 13); var topRow = new MarginContainer { MarginLeftOverride = 4, MarginTopOverride = 2, MarginRightOverride = 12, MarginBottomOverride = 2, Children = { new HBoxContainer { Children = { (_lblName = new Label { Text = Loc.GetString("Gas Tank"), FontOverride = font, FontColorOverride = StyleNano.NanoGold, SizeFlagsVertical = SizeFlags.ShrinkCenter }), new Control { CustomMinimumSize = (20, 0), SizeFlagsHorizontal = SizeFlags.Expand }, (btnClose = new TextureButton { StyleClasses = {SS14Window.StyleClassWindowCloseButton}, SizeFlagsVertical = SizeFlags.ShrinkCenter }) } } } }; var middle = new PanelContainer { PanelOverride = new StyleBoxFlat {BackgroundColor = Color.FromHex("#202025")}, Children = { new MarginContainer { MarginLeftOverride = 8, MarginRightOverride = 8, MarginTopOverride = 4, MarginBottomOverride = 4, Children = { (_contentContainer = new VBoxContainer()) } } } }; _topContainer.AddChild(topRow); _topContainer.AddChild(new PanelContainer { CustomMinimumSize = (0, 2), PanelOverride = new StyleBoxFlat {BackgroundColor = Color.FromHex("#525252ff")} }); _topContainer.AddChild(middle); _topContainer.AddChild(new PanelContainer { CustomMinimumSize = (0, 2), PanelOverride = new StyleBoxFlat {BackgroundColor = Color.FromHex("#525252ff")} }); _lblPressure = new RichTextLabel(); _contentContainer.AddChild(_lblPressure); //internals _lblInternals = new RichTextLabel {CustomMinimumSize = (200, 0), SizeFlagsVertical = SizeFlags.ShrinkCenter}; _btnInternals = new Button {Text = Loc.GetString("Toggle")}; _contentContainer.AddChild( new MarginContainer { MarginTopOverride = 7, Children = { new HBoxContainer { Children = {_lblInternals, _btnInternals} } } }); // Separator _contentContainer.AddChild(new Control { CustomMinimumSize = new Vector2(0, 10) }); _contentContainer.AddChild(new Label { Text = Loc.GetString("Output Pressure"), Align = Label.AlignMode.Center }); _spbPressure = new FloatSpinBox {IsValid = f => f >= 0 || f <= 3000}; _contentContainer.AddChild( new MarginContainer { MarginRightOverride = 25, MarginLeftOverride = 25, MarginBottomOverride = 7, Children = { _spbPressure } } ); // Handlers _spbPressure.OnValueChanged += args => { _owner.SetOutputPressure(args.Value); }; _btnInternals.OnPressed += args => { _owner.ToggleInternals(); }; btnClose.OnPressed += _ => Close(); } public void UpdateState(GasTankBoundUserInterfaceState state) { _lblPressure.SetMarkup(Loc.GetString("Pressure: {0:0.##} kPa", state.TankPressure)); _btnInternals.Disabled = !state.CanConnectInternals; _lblInternals.SetMarkup(Loc.GetString("Internals: [color={0}]{1}[/color]", state.InternalsConnected ? "green" : "red", state.InternalsConnected ? "Connected" : "Disconnected")); if (state.OutputPressure.HasValue) { _spbPressure.Value = state.OutputPressure.Value; } } protected override DragMode GetDragModeFor(Vector2 relativeMousePos) { return DragMode.Move; } protected override bool HasPoint(Vector2 point) { return false; } } }
35.029661
105
0.507318
[ "MIT" ]
BananaFlambe/space-station-14
Content.Client/UserInterface/Atmos/GasTank/GasTankWindow.cs
8,269
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AdventureWorks.Dal.Adapter.v54.DatabaseSpecific; using AdventureWorks.Dal.Adapter.v54.TypedViewClasses; using AdventureWorks.Dal.Adapter.v54.HelperClasses; using AdventureWorks.Dal.Adapter.v54.Linq; using SD.LLBLGen.Pro.ORMSupportClasses; namespace RawBencher.Benchers { /// <summary> /// Specific bencher for LLBLGen Pro, doing no-change tracking fetch, using a Typed View poco with a linq query. /// </summary> public class LLBLGenProNoChangeTrackingLinqPocoBencher : BencherBase<SohLinqPocoRow> { /// <summary> /// Initializes a new instance of the <see cref="LLBLGenProNoChangeTrackingLinqPocoBencher"/> class. /// </summary> public LLBLGenProNoChangeTrackingLinqPocoBencher() : base(r => r.SalesOrderId, usesChangeTracking:false, usesCaching:false) { } /// <summary> /// Fetches the individual element /// </summary> /// <param name="key">The key of the element to fetch.</param> /// <returns>The fetched element, or null if not found</returns> public override SohLinqPocoRow FetchIndividual(int key) { using(var adapter = new DataAccessAdapter()) { var metaData = new LinqMetaData(adapter); return metaData.SohLinqPoco.FirstOrDefault(s => s.SalesOrderId == key); } } /// <summary> /// Fetches the complete set of elements and returns this set as an IEnumerable. /// </summary> /// <returns>the set fetched</returns> public override IEnumerable<SohLinqPocoRow> FetchSet() { using(var adapter = new DataAccessAdapter()) { var metaData = new LinqMetaData(adapter); return metaData.SohLinqPoco.ToList(); } } /// <summary> /// Creates the name of the framework this bencher is for. Use the overload which accepts a format string and a type to create a name based on a /// specific version /// </summary> /// <returns>the framework name.</returns> protected override string CreateFrameworkNameImpl() { return CreateFrameworkName("LLBLGen Pro v{0} (v{1}), Poco typed view with Linq", typeof(DataAccessAdapterBase)); } } }
31.691176
146
0.727146
[ "MIT" ]
sanekpr/RawDataAccessBencher
RawBencher/Benchers/LLBLGenProNoChangeTrackingLinqPocoBencher.cs
2,157
C#
namespace TRuDI.TafAdapter.Interface { using System; using TRuDI.HanAdapter.Interface; /// <summary> /// Common interface used by all TAF adapters for the resulting data object. /// </summary> public interface ITafData { /// <summary> /// TAF to that the data belongs to. /// </summary> TafId TafId { get; } /// <summary> /// Start of the billing period. /// </summary> DateTime Begin { get; } /// <summary> /// End of the billing period. /// </summary> DateTime End { get; } } }
22.857143
81
0.50625
[ "Apache-2.0", "MIT" ]
flobecker/trudi-koala
src/TRuDI.TafAdapter.Interface/ITafData.cs
642
C#