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 |
|---|---|---|---|---|---|---|---|---|
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace Demos.Properties {
using System;
/// <summary>
/// 一个强类型的资源类,用于查找本地化的字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// 返回此类使用的缓存的 ResourceManager 实例。
/// </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("Demos.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 重写当前线程的 CurrentUICulture 属性,对
/// 使用此强类型资源类的所有资源查找执行重写。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 38.171875 | 171 | 0.586983 | [
"MIT"
] | AFei19911012/WPFSamples | Demos/Properties/Resources.Designer.cs | 2,803 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Memberships.Entities
{
[Table("ItemType")]
public class ItemType
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[MaxLength(255)]
[Required]
public string Title { get; set; }
}
} | 24.421053 | 61 | 0.696121 | [
"MIT"
] | jessepatricio/Memberships | Docs/Memberships-Video-Code-Finished/Memberships - Video Code - Finished/Memberships/Entities/ItemType.cs | 466 | C# |
//
// System.ComponentModel.TypeConverter test cases
//
// Authors:
// Gert Driesen (drieseng@users.sourceforge.net)
//
// (c) 2005 Novell, Inc. (http://www.ximian.com)
//
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using NUnit.Framework;
namespace MonoTests.System.ComponentModel
{
[TestFixture]
public class TypeConverterTests
{
[Test]
public void DefaultImplementation ()
{
BConverter converter = new BConverter ();
C c = new C ();
Assert.IsNull (converter.GetProperties (c), "#1");
Assert.IsNull (converter.GetProperties (null, c), "#2");
Assert.IsNull (converter.GetProperties (null, c, null), "#3");
Assert.IsNull (converter.GetProperties (null), "#4");
Assert.IsNull (converter.GetProperties (null, null), "#5");
Assert.IsNull (converter.GetProperties (null, null, null), "#6");
Assert.IsFalse (converter.GetCreateInstanceSupported (), "#7");
Assert.IsFalse (converter.GetCreateInstanceSupported (null), "#8");
Assert.IsFalse (converter.GetPropertiesSupported (), "#9");
Assert.IsFalse (converter.GetPropertiesSupported (null), "#10");
Assert.IsTrue (converter.CanConvertFrom (typeof (InstanceDescriptor)), "#11");
Assert.IsTrue (converter.CanConvertFrom (null, typeof (InstanceDescriptor)), "#12");
Assert.IsTrue (converter.CanConvertTo (typeof (string)), "#13");
Assert.IsTrue (converter.CanConvertTo (null, typeof (string)), "#14");
}
[Test]
public void GetProperties ()
{
PropertyDescriptorCollection properties = null;
C c = new C ();
TypeConverter converter = TypeDescriptor.GetConverter (c);
Assert.AreEqual (typeof (AConverter).FullName, converter.GetType ().FullName, "#1");
properties = converter.GetProperties (c);
Assert.AreEqual (1, properties.Count, "#2");
Assert.AreEqual ("A", properties[0].Name, "#3");
// ensure collection is read-only
try {
properties.Clear ();
Assert.Fail ("#4");
} catch (NotSupportedException) {
// read-only collection cannot be modified
}
properties = converter.GetProperties (null, c);
Assert.AreEqual (1, properties.Count, "#5");
Assert.AreEqual ("A", properties[0].Name, "#6");
// ensure collection is read-only
try {
properties.Clear ();
Assert.Fail ("#7");
} catch (NotSupportedException) {
// read-only collection cannot be modified
}
properties = converter.GetProperties (null, c, null);
Assert.AreEqual (2, properties.Count, "#8");
// ensure collection is read-only
try {
properties.Clear ();
Assert.Fail ("#9");
} catch (NotSupportedException) {
// read-only collection cannot be modified
}
properties = converter.GetProperties (null);
Assert.IsNull (properties, "#10");
properties = converter.GetProperties (null, null);
Assert.IsNull (properties, "#11");
properties = converter.GetProperties (null, null, null);
Assert.IsNull (properties, "#12");
}
[Test]
public void GetConvertFromException ()
{
MockTypeConverter converter = new MockTypeConverter ();
try {
converter.GetConvertFromException (null);
Assert.Fail ("#A1");
} catch (NotSupportedException ex) {
// MockTypeConverter cannot convert from (null)
Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#A2");
Assert.IsNull (ex.InnerException, "#A3");
Assert.IsNotNull (ex.Message, "#A4");
Assert.IsTrue (ex.Message.IndexOf (typeof (MockTypeConverter).Name) != -1, "#A5");
Assert.IsTrue (ex.Message.IndexOf ("(null)") != -1, "#A6");
}
try {
converter.GetConvertFromException ("B");
Assert.Fail ("#B1");
} catch (NotSupportedException ex) {
// MockTypeConverter cannot convert from System.String
Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#B2");
Assert.IsNull (ex.InnerException, "#B3");
Assert.IsNotNull (ex.Message, "#B4");
Assert.IsTrue (ex.Message.IndexOf (typeof (MockTypeConverter).Name) != -1, "#B5");
Assert.IsTrue (ex.Message.IndexOf (typeof (string).FullName) != -1, "#B6");
}
}
[Test]
public void GetConvertToException ()
{
MockTypeConverter converter = new MockTypeConverter ();
try {
converter.GetConvertToException (null, typeof (DateTime));
Assert.Fail ("#A1");
} catch (NotSupportedException ex) {
// 'MockTypeConverter' is unable to convert '(null)'
// to 'System.DateTime'
Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#A2");
Assert.IsNull (ex.InnerException, "#A3");
Assert.IsNotNull (ex.Message, "#A4");
Assert.IsTrue (ex.Message.IndexOf ("'" + typeof (MockTypeConverter).Name + "'") != -1, "#A5");
Assert.IsTrue (ex.Message.IndexOf ("'(null)'") != -1, "#A6");
Assert.IsTrue (ex.Message.IndexOf ("'" + typeof (DateTime).FullName + "'") != -1, "#A7");
}
try {
converter.GetConvertToException ("B", typeof (DateTime));
Assert.Fail ("#B1");
} catch (NotSupportedException ex) {
// 'MockTypeConverter' is unable to convert 'System.String'
// to 'System.DateTime'
Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#B2");
Assert.IsNull (ex.InnerException, "#B3");
Assert.IsNotNull (ex.Message, "#B4");
Assert.IsTrue (ex.Message.IndexOf (typeof (MockTypeConverter).Name) != -1, "#B5");
Assert.IsTrue (ex.Message.IndexOf (typeof (string).FullName) != -1, "#B6");
}
}
[Test]
public void ConvertToWithCulture ()
{
var culture = CultureInfo.CreateSpecificCulture ("sv-se");
var converter = TypeDescriptor.GetConverter (typeof (string));
Assert.AreEqual ("0,5", (string) converter.ConvertTo (null, culture, 0.5, typeof (string)));
}
public class FooConverter<T> : TypeConverter
{
}
[TypeConverter (typeof (FooConverter<string>))]
public string FooProperty {
get { return ""; }
}
[Test]
public void TestGenericTypeConverterInstantiation ()
{
Assert.IsNotNull (GetType ().GetProperty ("FooProperty").GetCustomAttributes (false));
}
[ExpectedException (typeof (NullReferenceException))]
public void GetConvertToException_DestinationType_Null ()
{
MockTypeConverter converter = new MockTypeConverter ();
converter.GetConvertToException ("B", (Type) null);
}
[Test]
public void IsValid ()
{
var tc = new TypeConverter ();
Assert.IsFalse (tc.IsValid (null));
}
}
[TypeConverter (typeof (AConverter))]
public class C
{
[Browsable (true)]
public int A {
get { return 0; }
}
[Browsable (false)]
public int B {
get { return 0; }
}
}
public class MockTypeConverter : TypeConverter
{
public new Exception GetConvertFromException (object value)
{
return base.GetConvertFromException (value);
}
public new Exception GetConvertToException (object value, Type destinationType)
{
return base.GetConvertToException (value, destinationType);
}
}
public class AConverter : TypeConverter
{
public override PropertyDescriptorCollection GetProperties (ITypeDescriptorContext context, object value, Attribute[] attributes)
{
if (value is C) {
return TypeDescriptor.GetProperties (value, attributes);
}
return base.GetProperties (context, value, attributes);
}
public override bool GetPropertiesSupported (ITypeDescriptorContext context)
{
return true;
}
}
public class BConverter : TypeConverter
{
}
}
| 29.72 | 131 | 0.67712 | [
"Apache-2.0"
] | AvolitesMarkDaniel/mono | mcs/class/System/Test/System.ComponentModel/TypeConverterTests.cs | 7,430 | 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("Example2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Example2")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[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("832cfb4e-0e63-4e2b-9282-a0fded04ef2f")]
// 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")]
| 39 | 85 | 0.728344 | [
"MIT"
] | Real-Serious-Games/Metrics | Examples/Example2/Properties/AssemblyInfo.cs | 1,446 | C# |
//
// Copyright (C) 2018 Authlete, 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.
//
namespace Authlete.Types
{
/// <summary>
/// Values for the <c>"code_challenge_method"</c> metadata
/// defined in
/// <a href="https://tools.ietf.org/html/rfc7636">RFC 7636</a>
/// (Proof Key for Code Exchange by OAuth Public Clients).
/// </summary>
public enum CodeChallengeMethod
{
/// <summary>
/// <c>"plain"</c>, meaning <c>code_challenge =
/// code_verifier</c>. See
/// <a href="https://tools.ietf.org/html/rfc7636#section-4.2">4.2.
/// Client Creates the Code Challenge</a> of
/// <a href="https://tools.ietf.org/html/rfc7636">RFC 7636</a>
/// for details.
/// </summary>
PLAIN = 1,
/// <summary>
/// <c>S256</c>, meaning <c>code_challenge =
/// BASE64URL-ENCODE(SHA256(ASCII(code_verifier)))</c>. See
/// <a href="https://tools.ietf.org/html/rfc7636#section-4.2">4.2.
/// Client Creates the Code Challenge</a> of
/// <a href="https://tools.ietf.org/html/rfc7636">RFC 7636</a>
/// for details.
/// </summary>
S256,
}
}
| 33.686275 | 74 | 0.611758 | [
"Apache-2.0"
] | authlete/authlete-csharp | Authlete/Types/CodeChallengeMethod.cs | 1,720 | 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.Peering.V20190901Preview.Inputs
{
/// <summary>
/// The properties that define a BGP session.
/// </summary>
public sealed class BgpSessionArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The maximum number of prefixes advertised over the IPv4 session.
/// </summary>
[Input("maxPrefixesAdvertisedV4")]
public Input<int>? MaxPrefixesAdvertisedV4 { get; set; }
/// <summary>
/// The maximum number of prefixes advertised over the IPv6 session.
/// </summary>
[Input("maxPrefixesAdvertisedV6")]
public Input<int>? MaxPrefixesAdvertisedV6 { get; set; }
/// <summary>
/// The MD5 authentication key of the session.
/// </summary>
[Input("md5AuthenticationKey")]
public Input<string>? Md5AuthenticationKey { get; set; }
/// <summary>
/// The IPv4 session address on peer's end.
/// </summary>
[Input("peerSessionIPv4Address")]
public Input<string>? PeerSessionIPv4Address { get; set; }
/// <summary>
/// The IPv6 session address on peer's end.
/// </summary>
[Input("peerSessionIPv6Address")]
public Input<string>? PeerSessionIPv6Address { get; set; }
/// <summary>
/// The IPv4 prefix that contains both ends' IPv4 addresses.
/// </summary>
[Input("sessionPrefixV4")]
public Input<string>? SessionPrefixV4 { get; set; }
/// <summary>
/// The IPv6 prefix that contains both ends' IPv6 addresses.
/// </summary>
[Input("sessionPrefixV6")]
public Input<string>? SessionPrefixV6 { get; set; }
public BgpSessionArgs()
{
}
}
}
| 31.984615 | 81 | 0.607023 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Peering/V20190901Preview/Inputs/BgpSessionArgs.cs | 2,079 | C# |
using System;
using System.Linq;
using System.Reflection;
namespace DataConnector
{
/// <summary>
/// Represents a configurable convention mapper.
/// </summary>
/// <remarks>
/// By default this mapper replaces <see cref="StandardMapper" /> without change, which means backwards compatibility
/// is kept.
/// </remarks>
public class ConventionMapper : IMapper
{
/// <summary>
/// Gets or sets the get sequence name logic.
/// </summary>
public Func<Type, PropertyInfo, string> GetSequenceName { get; set; }
/// <summary>
/// Gets or sets the inflect column name logic.
/// </summary>
public Func<IInflector, string, string> InflectColumnName { get; set; }
/// <summary>
/// Gets or sets the inflect table name logic.
/// </summary>
public Func<IInflector, string, string> InflectTableName { get; set; }
/// <summary>
/// Gets or sets the is primary key auto increment logic.
/// </summary>
public Func<Type, bool> IsPrimaryKeyAutoIncrement { get; set; }
/// <summary>
/// Gets or sets the map column logic.
/// </summary>
public Func<ColumnInfo, Type, PropertyInfo, bool> MapColumn { get; set; }
/// <summary>
/// Gets or set the map primary key logic.
/// </summary>
public Func<TableInfo, Type, bool> MapPrimaryKey { get; set; }
/// <summary>
/// Gets or sets the map table logic.
/// </summary>
public Func<TableInfo, Type, bool> MapTable { get; set; }
/// <summary>
/// Gets or sets the from db convert logic.
/// </summary>
public Func<PropertyInfo, Type, Func<object, object>> FromDbConverter { get; set; }
/// <summary>
/// Gets or sets the to db converter logic.
/// </summary>
public Func<PropertyInfo, Func<object, object>> ToDbConverter { get; set; }
/// <summary>
/// Constructs a new instance of convention mapper.
/// </summary>
public ConventionMapper()
{
GetSequenceName = (t, pi) => null;
InflectColumnName = (inflect, cn) => cn;
InflectTableName = (inflect, tn) => tn;
MapPrimaryKey = (ti, t) =>
{
var primaryKey = t.GetCustomAttributes(typeof(PrimaryKeyAttribute), true).FirstOrDefault() as PrimaryKeyAttribute;
if (primaryKey != null)
{
ti.PrimaryKey = primaryKey.Value;
ti.SequenceName = primaryKey.SequenceName;
ti.AutoIncrement = primaryKey.AutoIncrement;
return true;
}
var prop = t.GetProperties().FirstOrDefault(p =>
{
if (p.Name.Equals("Id", StringComparison.OrdinalIgnoreCase))
return true;
if (p.Name.Equals(t.Name + "Id", StringComparison.OrdinalIgnoreCase))
return true;
if (p.Name.Equals(t.Name + "_Id", StringComparison.OrdinalIgnoreCase))
return true;
return false;
});
if (prop == null)
return false;
ti.PrimaryKey = InflectColumnName(Inflector.Instance, prop.Name);
ti.AutoIncrement = IsPrimaryKeyAutoIncrement(prop.PropertyType);
ti.SequenceName = GetSequenceName(t, prop);
return true;
};
MapTable = (ti, t) =>
{
var tableName = t.GetCustomAttributes(typeof(TableNameAttribute), true).FirstOrDefault() as TableNameAttribute;
ti.TableName = tableName != null ? tableName.Value : InflectTableName(Inflector.Instance, t.Name);
MapPrimaryKey(ti, t);
return true;
};
IsPrimaryKeyAutoIncrement = t =>
{
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
t = t.GetGenericArguments()[0];
if (t == typeof(long) || t == typeof(ulong))
return true;
if (t == typeof(int) || t == typeof(uint))
return true;
if (t == typeof(short) || t == typeof(ushort))
return true;
return false;
};
MapColumn = (ci, t, pi) =>
{
// Check if declaring poco has [Explicit] attribute
var isExplicit = t.GetCustomAttributes(typeof(ExplicitColumnsAttribute), true).Any();
// Check for [Column]/[Ignore] Attributes
var column = pi.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault() as ColumnAttribute;
if (isExplicit && column == null)
return false;
if (pi.GetCustomAttributes(typeof(IgnoreAttribute), true).Any())
return false;
// Read attribute
if (column != null)
{
ci.ColumnName = column.Name ?? InflectColumnName(Inflector.Instance, pi.Name);
ci.ForceToUtc = column.ForceToUtc;
ci.ResultColumn = (column as ResultColumnAttribute) != null;
ci.InsertTemplate = column.InsertTemplate;
ci.UpdateTemplate = column.UpdateTemplate;
}
else
{
ci.ColumnName = InflectColumnName(Inflector.Instance, pi.Name);
}
return true;
};
FromDbConverter = (pi, t) =>
{
if (pi != null)
{
var valueConverter = pi.GetCustomAttributes(typeof(ValueConverterAttribute), true).FirstOrDefault() as ValueConverterAttribute;
if (valueConverter != null)
return valueConverter.ConvertFromDb;
}
return null;
};
ToDbConverter = (pi) =>
{
if (pi != null)
{
var valueConverter = pi.GetCustomAttributes(typeof(ValueConverterAttribute), true).FirstOrDefault() as ValueConverterAttribute;
if (valueConverter != null)
return valueConverter.ConvertToDb;
}
return null;
};
}
/// <summary>
/// Get information about the table associated with a POCO class
/// </summary>
/// <param name="pocoType">The poco type.</param>
/// <returns>A TableInfo instance</returns>
/// <remarks>
/// This method must return a valid TableInfo.
/// To create a TableInfo from a POCO's attributes, use TableInfo.FromPoco
/// </remarks>
public TableInfo GetTableInfo(Type pocoType)
{
var ti = new TableInfo();
return MapTable(ti, pocoType) ? ti : null;
}
/// <summary>
/// Get information about the column associated with a property of a POCO
/// </summary>
/// <param name="pocoProperty">The PropertyInfo of the property being queried</param>
/// <returns>A reference to a ColumnInfo instance, or null to ignore this property</returns>
/// <remarks>
/// To create a ColumnInfo from a property's attributes, use PropertyInfo.FromProperty
/// </remarks>
public ColumnInfo GetColumnInfo(PropertyInfo pocoProperty)
{
var ci = new ColumnInfo();
return MapColumn(ci, pocoProperty.DeclaringType, pocoProperty) ? ci : null;
}
/// <summary>
/// Supply a function to convert a database value to the correct property value
/// </summary>
/// <param name="targetProperty">The target property</param>
/// <param name="sourceType">The type of data returned by the DB</param>
/// <returns>A Func that can do the conversion, or null for no conversion</returns>
public Func<object, object> GetFromDbConverter(PropertyInfo targetProperty, Type sourceType)
{
return FromDbConverter != null ? FromDbConverter(targetProperty, sourceType) : null;
}
/// <summary>
/// Supply a function to convert a property value into a database value
/// </summary>
/// <param name="sourceProperty">The property to be converted</param>
/// <returns>A Func that can do the conversion</returns>
/// <remarks>
/// This conversion is only used for converting values from POCO's that are
/// being Inserted or Updated.
/// Conversion is not available for parameter values passed directly to queries.
/// </remarks>
public Func<object, object> GetToDbConverter(PropertyInfo sourceProperty)
{
return ToDbConverter != null ? ToDbConverter(sourceProperty) : null;
}
}
} | 40.758772 | 147 | 0.536318 | [
"MIT"
] | kieuphi/DataConnector | DataConnector/DataConnector/ConventionMapper.cs | 9,295 | C# |
// Copyright (c) 2019, WebsitePanel-Support.net.
// Distributed by websitepanel-support.net
// Build and fixed by Key4ce - IT Professionals
// https://www.key4ce.com
//
// Original source:
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class HeliconZoo_Settings {
/// <summary>
/// HostingPackagesGrid control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView HostingPackagesGrid;
/// <summary>
/// HostingPackagesInstallButtonsPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel HostingPackagesInstallButtonsPanel;
/// <summary>
/// btnInstall control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnInstall;
/// <summary>
/// HostingPackagesErrorsPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel HostingPackagesErrorsPanel;
/// <summary>
/// HostingPackagesLoadingError control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label HostingPackagesLoadingError;
/// <summary>
/// EnginesPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel EnginesPanel;
/// <summary>
/// QuotasEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox QuotasEnabled;
/// <summary>
/// WebCosoleEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox WebCosoleEnabled;
/// <summary>
/// ButtonAddEngine control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button ButtonAddEngine;
/// <summary>
/// EngineForm control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.UpdatePanel EngineForm;
/// <summary>
/// EngineName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EngineName;
/// <summary>
/// EngineFriendlyName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EngineFriendlyName;
/// <summary>
/// EngineFullPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EngineFullPath;
/// <summary>
/// EngineArguments control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EngineArguments;
/// <summary>
/// EngineTransport control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList EngineTransport;
/// <summary>
/// EngineProtocol control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList EngineProtocol;
/// <summary>
/// EnginePortLower control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnginePortLower;
/// <summary>
/// EnginePortUpper control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnginePortUpper;
/// <summary>
/// EngineMinInstances control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EngineMinInstances;
/// <summary>
/// EngineMaxInstances control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EngineMaxInstances;
/// <summary>
/// EngineTimeLimit control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EngineTimeLimit;
/// <summary>
/// EngineGracefulShutdownTimeout control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EngineGracefulShutdownTimeout;
/// <summary>
/// EngineMemoryLimit control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EngineMemoryLimit;
/// <summary>
/// EnvKey1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnvKey1;
/// <summary>
/// EnvValue1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnvValue1;
/// <summary>
/// EnvKey2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnvKey2;
/// <summary>
/// EnvValue2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnvValue2;
/// <summary>
/// EnvKey3 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnvKey3;
/// <summary>
/// EnvValue3 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnvValue3;
/// <summary>
/// EnvKey4 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnvKey4;
/// <summary>
/// EnvValue4 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnvValue4;
/// <summary>
/// EnvKey5 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnvKey5;
/// <summary>
/// EnvValue5 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnvValue5;
/// <summary>
/// EnvKey6 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnvKey6;
/// <summary>
/// EnvValue6 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnvValue6;
/// <summary>
/// EnvKey7 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnvKey7;
/// <summary>
/// EnvValue7 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnvValue7;
/// <summary>
/// EnvKey8 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnvKey8;
/// <summary>
/// EnvValue8 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox EnvValue8;
/// <summary>
/// EngineFormButtons control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel EngineFormButtons;
/// <summary>
/// ButtonSaveEngine control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button ButtonSaveEngine;
/// <summary>
/// ButtonCancelEngineForm control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button ButtonCancelEngineForm;
/// <summary>
/// EngineGrid control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView EngineGrid;
}
| 35.128736 | 90 | 0.618284 | [
"BSD-3-Clause"
] | Key4ce/Websitepanel | WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/HeliconZoo_Settings.ascx.designer.cs | 15,281 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace TelerikBlazor.App.Models
{
public partial class Customer
{
public Customer()
{
CustomerCustomerDemo = new HashSet<CustomerCustomerDemo>();
Orders = new HashSet<Order>();
}
[Key]
[Column("CustomerID")]
[StringLength(5)]
public string CustomerId { get; set; }
[Required]
[StringLength(40)]
public string CompanyName { get; set; }
[StringLength(30)]
public string ContactName { get; set; }
[StringLength(30)]
public string ContactTitle { get; set; }
[StringLength(60)]
public string Address { get; set; }
[StringLength(15)]
public string City { get; set; }
[StringLength(15)]
public string Region { get; set; }
[StringLength(10)]
public string PostalCode { get; set; }
[StringLength(15)]
public string Country { get; set; }
[StringLength(24)]
public string Phone { get; set; }
[StringLength(24)]
public string Fax { get; set; }
[InverseProperty("Customer")]
public ICollection<CustomerCustomerDemo> CustomerCustomerDemo { get; set; }
[InverseProperty("Customer")]
public ICollection<Order> Orders { get; set; }
}
}
| 30.479167 | 83 | 0.598086 | [
"MIT"
] | ZeoxZeos/TelerikBalzor_v08 | TelerikBlazor/TelerikBlazor.App/Models/Customers.cs | 1,465 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Azure.EventGrid.Inputs
{
public sealed class EventSubscriptionAdvancedFilterNumberLessThanOrEqualGetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Specifies the field within the event data that you want to use for filtering. Type of the field can be a number, boolean, or string.
/// </summary>
[Input("key", required: true)]
public Input<string> Key { get; set; } = null!;
/// <summary>
/// Specifies a single value to compare to when using a single value operator.
/// </summary>
[Input("value", required: true)]
public Input<double> Value { get; set; } = null!;
public EventSubscriptionAdvancedFilterNumberLessThanOrEqualGetArgs()
{
}
}
}
| 34.1875 | 144 | 0.665448 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi-bot/pulumi-azure | sdk/dotnet/EventGrid/Inputs/EventSubscriptionAdvancedFilterNumberLessThanOrEqualGetArgs.cs | 1,094 | C# |
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using StardewValley.Locations;
using Microsoft.Xna.Framework;
namespace FarmHouseRedone
{
internal class FarmHouse_getFloors_Patch
{
public static void Postfix(ref List<Rectangle> __result, FarmHouse __instance)
{
__result.Clear();
var state = OtherLocations.DecoratableStates.getState(__instance);
__result = state.getFloors();
if (__result.Count > 0)
{
return;
}
else
{
switch (__instance.upgradeLevel)
{
case 0:
__result.Add(new Rectangle(1, 3, 10, 9));
break;
case 1:
__result.Add(new Rectangle(1, 3, 6, 9));
__result.Add(new Rectangle(7, 3, 11, 9));
__result.Add(new Rectangle(18, 8, 2, 2));
__result.Add(new Rectangle(20, 3, 9, 8));
break;
case 2:
case 3:
__result.Add(new Rectangle(1, 3, 12, 6));
__result.Add(new Rectangle(15, 3, 13, 6));
__result.Add(new Rectangle(13, 5, 2, 2));
__result.Add(new Rectangle(0, 12, 10, 11));
__result.Add(new Rectangle(10, 12, 11, 9));
__result.Add(new Rectangle(21, 17, 2, 2));
__result.Add(new Rectangle(23, 12, 11, 11));
break;
}
Logger.Log("Found " + __result.Count + " floors.");
}
}
}
//class FarmHouse_getForbiddenPetWarpTiles_Patch
//{
// public static void Postfix(List<Rectangle> __result, FarmHouse __instance)
// {
// __result.Clear();
// FarmHouseState state = FarmHouseStates.getState(__instance);
// state.wallDictionary.Clear();
// //Logger.Log("Getting walls...");
// if (state.WallsData == null)
// FarmHouseStates.updateFromMapPath(__instance, __instance.mapPath);
// if (state.WallsData != "")
// {
// string[] wallArray = state.WallsData.Split(' ');
// for (int index = 0; index < wallArray.Length; index += 5)
// {
// try
// {
// Rectangle rectResult = new Rectangle(Convert.ToInt32(wallArray[index]), Convert.ToInt32(wallArray[index + 1]), Convert.ToInt32(wallArray[index + 3]), Convert.ToInt32(wallArray[index + 4]));
// __result.Add(rectResult);
// state.wallDictionary[rectResult] = wallArray[index + 2];
// }
// catch (IndexOutOfRangeException)
// {
// Logger.Log("Partial wall rectangle definition detected! (" + state.WallsData.Substring(index) + ") Wall rectangles must be defined as\nX Y Identifier Width Height\nPlease ensure all wall definitions have exactly these 5 values.", LogLevel.Error);
// }
// catch (FormatException)
// {
// string errorLocation = "";
// for (int errorIndex = index; errorIndex < wallArray.Length && errorIndex - index < 5; errorIndex += 1)
// {
// errorLocation += wallArray[errorIndex] + " ";
// }
// Logger.Log("Incorrect wall rectangle format. (" + errorLocation + ") Wall rectangles must be defined as\nX Y Identifier Width Height\nPlease ensure all wall definitions have exactly these 5 values.", LogLevel.Error);
// }
// }
// foreach (Rectangle floorRect in __result)
// {
// //Logger.Log("Found wall rectangle (" + floorRect.X + ", " + floorRect.Y + ", " + floorRect.Width + ", " + floorRect.Height + ")");
// }
// }
// else
// {
// switch (__instance.upgradeLevel)
// {
// case 0:
// __result.Add(new Rectangle(1, 1, 10, 3));
// state.wallDictionary[new Rectangle(1, 1, 10, 3)] = "House";
// break;
// case 1:
// __result.Add(new Rectangle(1, 1, 17, 3));
// state.wallDictionary[new Rectangle(1, 1, 17, 3)] = "2";
// __result.Add(new Rectangle(18, 6, 2, 2));
// state.wallDictionary[new Rectangle(18, 6, 2, 2)] = "3";
// __result.Add(new Rectangle(20, 1, 9, 3));
// state.wallDictionary[new Rectangle(20, 1, 9, 3)] = "4";
// break;
// case 2:
// case 3:
// __result.Add(new Rectangle(1, 1, 12, 3));
// __result.Add(new Rectangle(15, 1, 13, 3));
// __result.Add(new Rectangle(13, 3, 2, 2));
// __result.Add(new Rectangle(1, 10, 10, 3));
// __result.Add(new Rectangle(13, 10, 8, 3));
// __result.Add(new Rectangle(21, 15, 2, 2));
// __result.Add(new Rectangle(23, 10, 11, 3));
// break;
// }
// }
// }
//}
//public static void Prefix(xTile.Dimensions.Location tileLocation, xTile.Dimensions.Rectangle viewport, Farmer who, bool __result, FarmHouse __instance)
//{
// if (__instance.map.GetLayer("Buildings").Tiles[tileLocation] != null)
// {
// }
//}
//Issue: should not make use of typeof(FarmHouse) ever
} | 45.104478 | 273 | 0.46542 | [
"MIT"
] | strobel1ght/FarmHouseRedone | FarmHouseRedone/FarmHouse_getFloors_Patch.cs | 6,046 | C# |
//-----------------------------------------------------------------------------
// FILE: WorkflowGetLastResultRequest.cs
// CONTRIBUTOR: Jeff Lill
// COPYRIGHT: Copyright (c) 2005-2022 by neonFORGE LLC. 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.Generic;
using System.ComponentModel;
using Neon.Cadence;
using Neon.Common;
namespace Neon.Cadence.Internal
{
/// <summary>
/// <b>client --> proxy:</b> Returns the result from the last execution of the workflow.
/// This can be used by CRON workflows to retrieve state from the last workflow execution.
/// </summary>
[InternalProxyMessage(InternalMessageTypes.WorkflowGetLastResultRequest)]
internal class WorkflowGetLastResultRequest : WorkflowRequest
{
/// <summary>
/// Default constructor.
/// </summary>
public WorkflowGetLastResultRequest()
{
Type = InternalMessageTypes.WorkflowGetLastResultRequest;
}
/// <inheritdoc/>
public override InternalMessageTypes ReplyType => InternalMessageTypes.WorkflowGetLastResultReply;
/// <inheritdoc/>
internal override ProxyMessage Clone()
{
var clone = new WorkflowGetLastResultRequest();
CopyTo(clone);
return clone;
}
/// <inheritdoc/>
protected override void CopyTo(ProxyMessage target)
{
base.CopyTo(target);
}
}
}
| 32.612903 | 106 | 0.649852 | [
"Apache-2.0"
] | codelastnight/neonKUBE | Lib/Neon.Cadence/Internal/WorkflowMessages/WorkflowGetLastResultRequest.cs | 2,024 | C# |
// Copyright (c) 2022 cathery
using UnrealBuildTool;
public class AdvancedUMG : ModuleRules
{
public AdvancedUMG(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs;
PrivateDependencyModuleNames.AddRange(new string[]
{
"Core",
"CoreUObject",
"Engine",
"Slate",
"SlateCore",
"InputCore",
"UMG",
});
}
}
| 16.956522 | 62 | 0.697436 | [
"MIT"
] | cathery/AdvancedUMG | Source/AdvancedUMG/AdvancedUMG.Build.cs | 390 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Configuration;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.Entities;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;
using Umbraco.Extensions;
using uSync.Core.Models;
namespace uSync.Core.Serialization.Serializers
{
[SyncSerializer("B3F7F247-6077-406D-8480-DB1004C8211C", "ContentTypeSerializer", uSyncConstants.Serialization.ContentType)]
public class ContentTypeSerializer : ContentTypeBaseSerializer<IContentType>, ISyncSerializer<IContentType>
{
private readonly IContentTypeService contentTypeService;
private readonly IFileService fileService;
public ContentTypeSerializer(
IEntityService entityService, ILogger<ContentTypeSerializer> logger,
IDataTypeService dataTypeService,
IContentTypeService contentTypeService,
IFileService fileService,
IShortStringHelper shortStringHelper)
: base(entityService, logger, dataTypeService, contentTypeService, UmbracoObjectTypes.DocumentTypeContainer, shortStringHelper)
{
this.contentTypeService = contentTypeService;
this.fileService = fileService;
}
protected override SyncAttempt<XElement> SerializeCore(IContentType item, SyncSerializerOptions options)
{
var node = SerializeBase(item);
var info = SerializeInfo(item);
var parent = item.ContentTypeComposition.FirstOrDefault(x => x.Id == item.ParentId);
if (parent != null)
{
info.Add(new XElement("Parent", parent.Alias,
new XAttribute("Key", parent.Key)));
}
else if (item.Level != 1)
{
var folderNode = this.GetFolderNode(item);
if (folderNode != null)
info.Add(folderNode);
}
// compositions ?
info.Add(SerializeCompostions((ContentTypeCompositionBase)item));
// templates
var templateAlias =
(item.DefaultTemplate != null && item.DefaultTemplate.Id != 0)
? item.DefaultTemplate.Alias
: "";
info.Add(new XElement("DefaultTemplate", templateAlias));
var templates = SerailizeTemplates(item);
if (templates != null)
info.Add(templates);
node.Add(info);
node.Add(SerializeStructure(item));
node.Add(SerializeProperties(item));
node.Add(SerializeTabs(item));
return SyncAttempt<XElement>.Succeed(item.Name, node, typeof(IContentType), ChangeType.Export);
}
protected override void SerializeExtraProperties(XElement node, IContentType item, IPropertyType property)
{
node.Add(new XElement("Variations", property.Variations));
}
private XElement SerailizeTemplates(IContentType item)
{
var node = new XElement("AllowedTemplates");
if (item.AllowedTemplates.Any())
{
foreach (var template in item.AllowedTemplates.OrderBy(x => x.Alias))
{
node.Add(new XElement("Template", template.Alias,
new XAttribute("Key", template.Key)));
}
}
return node;
}
protected override SyncAttempt<IContentType> DeserializeCore(XElement node, SyncSerializerOptions options)
{
var attempt = FindOrCreate(node);
if (!attempt.Success) throw attempt.Exception;
var item = attempt.Result;
var details = new List<uSyncChange>();
details.AddRange(DeserializeBase(item, node));
details.AddRange(DeserializeTabs(item, node));
details.AddRange(DeserializeProperties(item, node, options));
// content type only property stuff.
details.AddRange(DeserializeContentTypeProperties(item, node));
// clean tabs
details.AddRange(CleanTabs(item, node, options));
// templates
details.AddRange(DeserializeTemplates(item, node));
// contentTypeService.Save(item);
return SyncAttempt<IContentType>.Succeed(item.Name, item, ChangeType.Import, details);
}
protected override IEnumerable<uSyncChange> DeserializeExtraProperties(IContentType item, IPropertyType property, XElement node)
{
var variations = node.Element("Variations").ValueOrDefault(ContentVariation.Nothing);
if (property.Variations != variations)
{
var change = uSyncChange.Update("Property/Variations", "Variations", property.Variations, variations);
property.Variations = variations;
return change.AsEnumerableOfOne();
}
return Enumerable.Empty<uSyncChange>();
}
public override SyncAttempt<IContentType> DeserializeSecondPass(IContentType item, XElement node, SyncSerializerOptions options)
{
logger.LogDebug("Deserialize Second Pass {0}", item.Alias);
var details = new List<uSyncChange>();
details.AddRange(DeserializeCompositions(item, node));
details.AddRange(DeserializeStructure(item, node));
if (!options.Flags.HasFlag(SerializerFlags.DoNotSave) && item.IsDirty())
contentTypeService.Save(item);
CleanFolder(item, node);
return SyncAttempt<IContentType>.Succeed(item.Name, item, ChangeType.Import, details);
}
private IEnumerable<uSyncChange> DeserializeContentTypeProperties(IContentType item, XElement node)
{
var info = node?.Element("Info");
if (info == null) return Enumerable.Empty<uSyncChange>();
var changes = new List<uSyncChange>();
var isContainer = info.Element("IsListView").ValueOrDefault(false);
if (item.IsContainer != isContainer)
{
changes.AddUpdate("IsListView", item.IsContainer, isContainer, "Info/IsListView");
item.IsContainer = isContainer;
}
var masterTemplate = info.Element("DefaultTemplate").ValueOrDefault(string.Empty);
if (!string.IsNullOrEmpty(masterTemplate))
{
var template = fileService.GetTemplate(masterTemplate);
if (template != null)
{
if (item.DefaultTemplate == null || template.Alias != item.DefaultTemplate.Alias)
{
changes.AddUpdate("DefaultTemplate", item.DefaultTemplate?.Alias ?? string.Empty, masterTemplate, "DefaultTemplate");
item.SetDefaultTemplate(template);
}
}
else
{
// elements don't have a defaultTemplate, but it can be valid to have the old defaultTemplate in the db.
// (it would then re-appear if the user untoggles is element) See issue #203
//
// So we only log this as a problem if the default template is missing on a non-element doctype.
if (!item.IsElement)
{
changes.AddUpdate("DefaultTemplate", item.DefaultTemplate?.Alias ?? string.Empty, "Cannot find Template", "DefaultTemplate", false);
}
}
}
return changes;
}
private IEnumerable<uSyncChange> DeserializeTemplates(IContentType item, XElement node)
{
var templates = node?.Element("Info")?.Element("AllowedTemplates");
if (templates == null) return Enumerable.Empty<uSyncChange>();
var allowedTemplates = new List<ITemplate>();
var changes = new List<uSyncChange>();
foreach (var template in templates.Elements("Template"))
{
var alias = template.Value;
var key = template.Attribute("Key").ValueOrDefault(Guid.Empty);
var templateItem = default(ITemplate);
if (key != Guid.Empty)
templateItem = fileService.GetTemplate(key);
if (templateItem == null)
templateItem = fileService.GetTemplate(alias);
if (templateItem != null)
{
logger.LogDebug("Adding Template: {0}", templateItem.Alias);
allowedTemplates.Add(templateItem);
}
}
var currentTemplates = string.Join(",", item.AllowedTemplates.Select(x => x.Alias).OrderBy(x => x));
var newTemplates = string.Join(",", allowedTemplates.Select(x => x.Alias).OrderBy(x => x));
if (currentTemplates != newTemplates)
{
changes.AddUpdate("AllowedTemplates", currentTemplates, newTemplates, "AllowedTemplates");
}
item.AllowedTemplates = allowedTemplates;
return changes;
}
protected override Attempt<IContentType> CreateItem(string alias, ITreeEntity parent, string itemType)
{
var item = new ContentType(shortStringHelper, -1)
{
Alias = alias
};
if (parent != null)
{
if (parent is IContentType parentContent)
{
item.AddContentType(parentContent);
}
item.SetParent(parent);
}
return Attempt.Succeed((IContentType)item);
}
protected override void SaveContainer(EntityContainer container)
{
logger.LogDebug("Saving Container (In main class) {0}", container.Key.ToString());
contentTypeService.SaveContainer(container);
}
}
}
| 37.514706 | 156 | 0.590259 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | JohanPlate/uSync | uSync.Core/Serialization/Serializers/ContentTypeSerializer.cs | 10,206 | 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.IO;
using Microsoft.ML.Data.IO;
using Microsoft.ML.RunTests;
using Microsoft.ML.StaticPipe;
using Microsoft.ML.Transforms;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.ML.Tests.Transformers
{
public sealed class PcaTests : TestDataPipeBase
{
private readonly string _dataSource;
private readonly TextSaver _saver;
public PcaTests(ITestOutputHelper helper)
: base(helper)
{
_dataSource = GetDataPath("generated_regression_dataset.csv");
_saver = new TextSaver(ML, new TextSaver.Arguments { Silent = true, OutputHeader = false });
}
[Fact]
public void PcaWorkout()
{
var data = TextLoaderStatic.CreateReader(_env,
c => (label: c.LoadFloat(11), weight: c.LoadFloat(0), features: c.LoadFloat(1, 10)),
separator: ';', hasHeader: true)
.Read(_dataSource);
var invalidData = TextLoaderStatic.CreateReader(_env,
c => (label: c.LoadFloat(11), weight: c.LoadFloat(0), features: c.LoadText(1, 10)),
separator: ';', hasHeader: true)
.Read(_dataSource);
var est = ML.Transforms.Projection.ProjectToPrincipalComponents("pca", "features", rank: 4, seed: 10);
TestEstimatorCore(est, data.AsDynamic, invalidInput: invalidData.AsDynamic);
var estNonDefaultArgs = ML.Transforms.Projection.ProjectToPrincipalComponents("pca", "features", rank: 3, weightColumn: "weight", overSampling: 2, center: false);
TestEstimatorCore(estNonDefaultArgs, data.AsDynamic, invalidInput: invalidData.AsDynamic);
Done();
}
[Fact]
public void TestPcaEstimator()
{
var data = TextLoaderStatic.CreateReader(ML,
c => (label: c.LoadFloat(11), features: c.LoadFloat(0, 10)),
separator: ';', hasHeader: true)
.Read(_dataSource);
var est = ML.Transforms.Projection.ProjectToPrincipalComponents("pca", "features", rank: 5, seed: 1);
var outputPath = GetOutputPath("PCA", "pca.tsv");
var savedData = ML.Data.TakeRows(est.Fit(data.AsDynamic).Transform(data.AsDynamic), 4);
savedData = ML.Transforms.SelectColumns("pca").Fit(savedData).Transform(savedData);
using (var fs = File.Create(outputPath))
ML.Data.SaveAsText(savedData, fs, headerRow: true, keepHidden: true);
CheckEquality("PCA", "pca.tsv", digitsOfPrecision: 4);
Done();
}
}
}
| 40.328571 | 174 | 0.628055 | [
"MIT"
] | geffzhang/machinelearning | test/Microsoft.ML.Tests/Transformers/PcaTests.cs | 2,825 | 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("MaterialPositioner")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MaterialPositioner")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5434d44f-846f-448f-840f-f03f6a724715")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.081081 | 84 | 0.747339 | [
"BSD-3-Clause"
] | mpcoombes/MaterialPredictor | MaterialPositioner/Properties/AssemblyInfo.cs | 1,412 | 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 UnicodeUtil = Lucene.Net.Util.UnicodeUtil;
namespace Lucene.Net.Index
{
sealed class FreqProxTermsWriter : TermsHashConsumer
{
public override TermsHashConsumerPerThread AddThread(TermsHashPerThread perThread)
{
return new FreqProxTermsWriterPerThread(perThread);
}
internal override void CreatePostings(RawPostingList[] postings, int start, int count)
{
int end = start + count;
for (int i = start; i < end; i++)
postings[i] = new PostingList();
}
private static int compareText(char[] text1, int pos1, char[] text2, int pos2)
{
while (true)
{
char c1 = text1[pos1++];
char c2 = text2[pos2++];
if (c1 != c2)
{
if (0xffff == c2)
return 1;
else if (0xffff == c1)
return - 1;
else
return c1 - c2;
}
else if (0xffff == c1)
return 0;
}
}
internal override void CloseDocStore(SegmentWriteState state)
{
}
public override void Abort()
{
}
// TODO: would be nice to factor out more of this, eg the
// FreqProxFieldMergeState, and code to visit all Fields
// under the same FieldInfo together, up into TermsHash*.
// Other writers would presumably share alot of this...
public override void Flush(IDictionary<TermsHashConsumerPerThread, ICollection<TermsHashConsumerPerField>> threadsAndFields, SegmentWriteState state)
{
// Gather all FieldData's that have postings, across all
// ThreadStates
var allFields = new List<FreqProxTermsWriterPerField>();
foreach(var entry in threadsAndFields)
{
var fields = entry.Value;
foreach(var i in fields)
{
FreqProxTermsWriterPerField perField = (FreqProxTermsWriterPerField)i;
if (perField.termsHashPerField.numPostings > 0)
allFields.Add(perField);
}
}
// Sort by field name
allFields.Sort();
int numAllFields = allFields.Count;
// TODO: allow Lucene user to customize this consumer:
FormatPostingsFieldsConsumer consumer = new FormatPostingsFieldsWriter(state, fieldInfos);
/*
Current writer chain:
FormatPostingsFieldsConsumer
-> IMPL: FormatPostingsFieldsWriter
-> FormatPostingsTermsConsumer
-> IMPL: FormatPostingsTermsWriter
-> FormatPostingsDocConsumer
-> IMPL: FormatPostingsDocWriter
-> FormatPostingsPositionsConsumer
-> IMPL: FormatPostingsPositionsWriter
*/
int start = 0;
while (start < numAllFields)
{
FieldInfo fieldInfo = allFields[start].fieldInfo;
System.String fieldName = fieldInfo.name;
int end = start + 1;
while (end < numAllFields && allFields[end].fieldInfo.name.Equals(fieldName))
end++;
FreqProxTermsWriterPerField[] fields = new FreqProxTermsWriterPerField[end - start];
for (int i = start; i < end; i++)
{
fields[i - start] = allFields[i];
// Aggregate the storePayload as seen by the same
// field across multiple threads
fieldInfo.storePayloads |= fields[i - start].hasPayloads;
}
// If this field has postings then add them to the
// segment
AppendPostings(fields, consumer);
for (int i = 0; i < fields.Length; i++)
{
TermsHashPerField perField = fields[i].termsHashPerField;
int numPostings = perField.numPostings;
perField.Reset();
perField.ShrinkHash(numPostings);
fields[i].Reset();
}
start = end;
}
foreach(var entry in threadsAndFields)
{
FreqProxTermsWriterPerThread perThread = (FreqProxTermsWriterPerThread) entry.Key;
perThread.termsHashPerThread.Reset(true);
}
consumer.Finish();
}
private byte[] payloadBuffer;
/* Walk through all unique text tokens (Posting
* instances) found in this field and serialize them
* into a single RAM segment. */
internal void AppendPostings(FreqProxTermsWriterPerField[] fields, FormatPostingsFieldsConsumer consumer)
{
int numFields = fields.Length;
FreqProxFieldMergeState[] mergeStates = new FreqProxFieldMergeState[numFields];
for (int i = 0; i < numFields; i++)
{
FreqProxFieldMergeState fms = mergeStates[i] = new FreqProxFieldMergeState(fields[i]);
System.Diagnostics.Debug.Assert(fms.field.fieldInfo == fields [0].fieldInfo);
// Should always be true
bool result = fms.NextTerm();
System.Diagnostics.Debug.Assert(result);
}
FormatPostingsTermsConsumer termsConsumer = consumer.AddField(fields[0].fieldInfo);
FreqProxFieldMergeState[] termStates = new FreqProxFieldMergeState[numFields];
bool currentFieldOmitTermFreqAndPositions = fields[0].fieldInfo.omitTermFreqAndPositions;
while (numFields > 0)
{
// Get the next term to merge
termStates[0] = mergeStates[0];
int numToMerge = 1;
for (int i = 1; i < numFields; i++)
{
char[] text = mergeStates[i].text;
int textOffset = mergeStates[i].textOffset;
int cmp = compareText(text, textOffset, termStates[0].text, termStates[0].textOffset);
if (cmp < 0)
{
termStates[0] = mergeStates[i];
numToMerge = 1;
}
else if (cmp == 0)
termStates[numToMerge++] = mergeStates[i];
}
FormatPostingsDocsConsumer docConsumer = termsConsumer.AddTerm(termStates[0].text, termStates[0].textOffset);
// Now termStates has numToMerge FieldMergeStates
// which all share the same term. Now we must
// interleave the docID streams.
while (numToMerge > 0)
{
FreqProxFieldMergeState minState = termStates[0];
for (int i = 1; i < numToMerge; i++)
if (termStates[i].docID < minState.docID)
minState = termStates[i];
int termDocFreq = minState.termFreq;
FormatPostingsPositionsConsumer posConsumer = docConsumer.AddDoc(minState.docID, termDocFreq);
ByteSliceReader prox = minState.prox;
// Carefully copy over the prox + payload info,
// changing the format to match Lucene's segment
// format.
if (!currentFieldOmitTermFreqAndPositions)
{
// omitTermFreqAndPositions == false so we do write positions &
// payload
int position = 0;
for (int j = 0; j < termDocFreq; j++)
{
int code = prox.ReadVInt();
position += (code >> 1);
int payloadLength;
if ((code & 1) != 0)
{
// This position has a payload
payloadLength = prox.ReadVInt();
if (payloadBuffer == null || payloadBuffer.Length < payloadLength)
payloadBuffer = new byte[payloadLength];
prox.ReadBytes(payloadBuffer, 0, payloadLength);
}
else
payloadLength = 0;
posConsumer.AddPosition(position, payloadBuffer, 0, payloadLength);
} //End for
posConsumer.Finish();
}
if (!minState.NextDoc())
{
// Remove from termStates
int upto = 0;
for (int i = 0; i < numToMerge; i++)
if (termStates[i] != minState)
termStates[upto++] = termStates[i];
numToMerge--;
System.Diagnostics.Debug.Assert(upto == numToMerge);
// Advance this state to the next term
if (!minState.NextTerm())
{
// OK, no more terms, so remove from mergeStates
// as well
upto = 0;
for (int i = 0; i < numFields; i++)
if (mergeStates[i] != minState)
mergeStates[upto++] = mergeStates[i];
numFields--;
System.Diagnostics.Debug.Assert(upto == numFields);
}
}
}
docConsumer.Finish();
}
termsConsumer.Finish();
}
internal UnicodeUtil.UTF8Result termsUTF8 = new UnicodeUtil.UTF8Result();
internal sealed class PostingList:RawPostingList
{
internal int docFreq; // # times this term occurs in the current doc
internal int lastDocID; // Last docID where this term occurred
internal int lastDocCode; // Code for prior doc
internal int lastPosition; // Last position where this term occurred
}
internal override int BytesPerPosting()
{
return RawPostingList.BYTES_SIZE + 4 * DocumentsWriter.INT_NUM_BYTE;
}
}
} | 30.851485 | 158 | 0.635751 | [
"Apache-2.0"
] | Anomalous-Software/Lucene.NET | src/core/Index/FreqProxTermsWriter.cs | 9,348 | C# |
namespace TechTalk.SpecFlow.IdeIntegration.Options
{
public interface IIntegrationOptionsProvider
{
IntegrationOptions GetOptions();
void ClearCache();
}
} | 23 | 51 | 0.706522 | [
"BSD-3-Clause"
] | 304NotModified/SpecFlow.VisualStudio | IdeIntegration/Options/IIntegrationOptionsProvider.cs | 186 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using RefScout.Analyzer.Context;
namespace RefScout.Analyzer.Notes.Messages;
internal abstract class Message<TContext> : Message where TContext : IContext
{
public abstract override NoteType Type { get; }
public sealed override bool Test(IContext context, Assembly assembly) =>
context is TContext analyzerContext && Test(analyzerContext, assembly);
public sealed override bool Test(IContext context, AssemblyRef reference) =>
context is TContext analyzerContext && Test(analyzerContext, reference);
public sealed override string Generate(IContext context, Assembly assembly) =>
context is TContext analyzerContext
? Generate(analyzerContext, assembly)
: throw new NotSupportedException(
$"This note generator is made contexts derived of {typeof(TContext).Name}, {context.GetType()} is not derived.");
public sealed override string Generate(IContext context, AssemblyRef reference) =>
context is TContext analyzerContext
? Generate(analyzerContext, reference)
: throw new NotSupportedException(
$"This note generator is made contexts derived of {typeof(TContext).Name}, {context.GetType()} is not derived.");
[ExcludeFromCodeCoverage]
public virtual bool Test(TContext context, Assembly assembly) => false;
[ExcludeFromCodeCoverage]
public virtual string Generate(TContext context, Assembly assembly) =>
throw new NotSupportedException("Implement the assembly generate method to support note for assemblies.");
[ExcludeFromCodeCoverage]
public virtual bool Test(TContext context, AssemblyRef reference) => false;
[ExcludeFromCodeCoverage]
public virtual string Generate(TContext context, AssemblyRef reference) =>
throw new NotSupportedException("Implement the reference generate method to support note for references.");
} | 46.833333 | 129 | 0.736655 | [
"MIT"
] | Droppers/AssemblyAnalyzer | src/RefScout.Analyzer/Notes/Messages/Message{T}.cs | 1,969 | C# |
using System.Collections.Generic;
using MyBlog.Data.Interfaces;
namespace MyBlog.Data.Models
{
public class Category : IMyBlogItem
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<BlogPost> BlogPosts { get; set; }
}
}
| 22.230769 | 60 | 0.650519 | [
"MIT"
] | PacktPublishing/Web-Development-with-Blazor | Chapter03/MyBlog/MyBlog.Data/Models/Category.cs | 291 | C# |
using System;
using GovorunPavel;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Playing");
var govor = new SpeakerPavel();
govor.Speak("1234567890");
Console.ReadLine();
}
}
}
| 14.45 | 38 | 0.570934 | [
"MIT"
] | PavelKulbida/Govorun | ConsoleTest/Program.cs | 291 | 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("PartyLeaderRoleXP")]
[assembly: AssemblyDescription("Give Party Leader XP from designated party roles")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PartyLeaderRoleXP")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[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("55a97357-07c5-4d02-bb5b-5d1c1bb664f7")]
// 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.1.0")]
[assembly: AssemblyFileVersion("1.1.0")]
| 39.222222 | 84 | 0.747875 | [
"MIT"
] | CptBoma/MB2.PartyLeaderMatters | Properties/AssemblyInfo.cs | 1,415 | C# |
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using RCV.FileContainer.Container;
using RCV.FileContainer.Contracts;
using RCV.FileContainer.Extensions;
using RCV.FileContainer.Utilities;
namespace RCV_FileContainer.Test.Container
{
[TestClass]
public class AzureBlobContainerTests
{
#region private fields
private IFileContainer _fileContainer;
private CloudStorageAccount _cloudStorageAccount;
private CloudBlobContainer _cloudBlobContainer;
private const string CONNECTION_STRING = "DefaultEndpointsProtocol=https;AccountName=bmwrcvdev;AccountKey=YW6ZSxrc4MOM3QhEGHyBkhZxyyEXVW1xd3ZB/thC5zSjBHQ68THwexwKR1jvl3vxPkHNQ+5VNWZHx4lWjAt1hw==;EndpointSuffix=core.windows.net";
private const string CONTAINER_NAME = "automatedtests";
private const string FILE_NAME = "CopyFile.txt";
private const string FILE_CONTENT = "FooBar";
private const string NEW_DIRECTORY = "NewDirectory";
private const string SOURCE_DIRECTORY = "SourceDirectory";
private const string TARGET_DIRECTORY = "TargetDirectory";
private const string DUMMY_DIRECTORY = "DummyDirectory";
#endregion
#region test initialization
[TestInitialize]
public void Initialize()
{
_fileContainer = new AzureBlobContainer(CONNECTION_STRING, CONTAINER_NAME);
_cloudStorageAccount = CloudStorageAccount.Parse(CONNECTION_STRING);
_cloudBlobContainer = _cloudStorageAccount.CreateCloudBlobClient().GetContainerReference(CONTAINER_NAME);
// SourceDirectory/CopyFile.txt
TaskUtilities.ExecuteSync(_cloudBlobContainer.GetCloudBlockBlobReference(FILE_NAME, SOURCE_DIRECTORY).UploadTextAsync(FILE_CONTENT));
// SourceDirectory/DummyDirectory/CopyFile.txt
TaskUtilities.ExecuteSync(_cloudBlobContainer.GetCloudBlockBlobReference(FILE_NAME, DUMMY_DIRECTORY, new[] { SOURCE_DIRECTORY }).UploadTextAsync(FILE_CONTENT));
// TargetDirectory/CopyFile.txt
TaskUtilities.ExecuteSync(_cloudBlobContainer.GetCloudBlockBlobReference(FILE_NAME, TARGET_DIRECTORY).UploadTextAsync(FILE_CONTENT));
// CopyFile.txt
TaskUtilities.ExecuteSync(_cloudBlobContainer.GetCloudBlockBlobReference(FILE_NAME).UploadTextAsync(FILE_CONTENT));
}
[TestCleanup]
public void Cleanup()
{
_cloudBlobContainer.GetDirectoryReference(string.Empty).DeleteRecursive();
}
#endregion
#region test methods
[DataTestMethod]
[DataRow(SOURCE_DIRECTORY, null, new[] { TARGET_DIRECTORY }, DisplayName = "Copy directory with target directory")]
[DataRow(DUMMY_DIRECTORY, new[] { SOURCE_DIRECTORY }, null, DisplayName = "Copy directory with source directory")]
[DataRow(DUMMY_DIRECTORY, new[] { SOURCE_DIRECTORY }, new[] { TARGET_DIRECTORY }, DisplayName = "Copy directory with both directories")]
public void CopyDirectoryTest(string directoryName, string[] sourcePath, string[] targetPath)
{
// Arrange
string relativeAddress = BlobUtilities.GetPath(directoryName, sourcePath);
CloudBlobDirectory sourceCloudBlobDirectory = _cloudBlobContainer.GetDirectoryReference(relativeAddress);
int expectedChildCount = TaskUtilities
.ExecuteSync(
sourceCloudBlobDirectory.ListBlobsSegmentedAsync(
useFlatBlobListing: true,
blobListingDetails: BlobListingDetails.None,
maxResults: null,
currentToken: new BlobContinuationToken(),
options: new BlobRequestOptions(),
operationContext: new OperationContext()
)
)
.Results
.Count();
// Act
_fileContainer.CopyDirectory(directoryName, sourcePath, targetPath);
CloudBlobDirectory targetCloudBlobDirectory = _cloudBlobContainer.GetDirectoryReference(BlobUtilities.GetPath(directoryName, targetPath));
int actualChildCount = TaskUtilities
.ExecuteSync(
targetCloudBlobDirectory.ListBlobsSegmentedAsync(
useFlatBlobListing: true,
blobListingDetails: BlobListingDetails.None,
maxResults: null,
currentToken: new BlobContinuationToken(),
options: new BlobRequestOptions(),
operationContext: new OperationContext()
)
)
.Results
.Count();
// Assert
Assert.AreEqual(expectedChildCount, actualChildCount);
}
[DataTestMethod]
[DataRow(FILE_NAME, null, FILE_NAME, new[] { TARGET_DIRECTORY, SOURCE_DIRECTORY }, true, DisplayName = "Copy file with target directory")]
[DataRow(FILE_NAME, new[] { SOURCE_DIRECTORY }, FILE_NAME, null, true, DisplayName = "Copy file with source directory")]
[DataRow(FILE_NAME, new[] { SOURCE_DIRECTORY }, FILE_NAME, new[] { TARGET_DIRECTORY, SOURCE_DIRECTORY }, true, DisplayName = "Copy file with both directories")]
public void CopyFileTest(string sourceFileName, string[] sourceParentFolders, string targetFileName, string[] targetParentFolders, bool overwriteIfExists = false)
{
// Act
_fileContainer.CopyFile(sourceFileName, sourceParentFolders, targetFileName, targetParentFolders, overwriteIfExists);
CloudBlockBlob cloudBlockBlobReference = _cloudBlobContainer.GetCloudBlockBlobReference(targetFileName, path: targetParentFolders);
bool result = TaskUtilities.ExecuteSync(cloudBlockBlobReference.ExistsAsync());
// Assert
Assert.IsTrue(result);
}
[DataTestMethod]
[DataRow(new []{ NEW_DIRECTORY }, NEW_DIRECTORY , null, DisplayName = "Create directory without path")]
[DataRow(new []{ TARGET_DIRECTORY, NEW_DIRECTORY }, NEW_DIRECTORY, new[] { TARGET_DIRECTORY }, DisplayName = "Create directory with path")]
public void CreateDirectoryTest(string[] expectedResult, string directoryName, string[] path)
{
// Act
string[] actualResult = _fileContainer.CreateDirectory(directoryName, path);
// Assert
CollectionAssert.AreEqual(expectedResult, actualResult);
}
[DataTestMethod]
[DataRow(FILE_NAME, new byte[] { 0x46, 0x6F, 0x6F, 0x42, 0x61, 0x72 }, null, DisplayName = "Create file with byte array without path")]
[DataRow(FILE_NAME, new byte[] { 0x46, 0x6F, 0x6F, 0x42, 0x61, 0x72 }, new[] { TARGET_DIRECTORY, SOURCE_DIRECTORY }, DisplayName = "Create file with byte array with path")]
public void CreateFileWithByteArrayTest(string fileName, byte[] fileContent, string[] path)
{
// Act
_fileContainer.CreateFile(fileName, fileContent, path);
CloudBlob cloudBlob = _cloudBlobContainer.GetCloudBlockBlobReference(fileName, path: path);
TaskUtilities.ExecuteSync(cloudBlob.FetchAttributesAsync());
var actualResult = new byte[cloudBlob.Properties.Length];
CloudBlockBlob cloudBlockBlobReference = _cloudBlobContainer.GetCloudBlockBlobReference(fileName, path: path);
TaskUtilities.ExecuteSync(cloudBlockBlobReference.DownloadToByteArrayAsync(actualResult, 0));
// Assert
CollectionAssert.AreEqual(fileContent, actualResult);
}
[DataTestMethod]
[DataRow(FILE_NAME, null, DisplayName = "Create file with stream without path")]
[DataRow(FILE_NAME, new object[] { new[] { TARGET_DIRECTORY, SOURCE_DIRECTORY } }, DisplayName = "Create file with stream with path")]
public void CreateFileWithStreamTest(string fileName, string[] path)
{
// Act
_fileContainer.CreateFile(fileName, Stream.Null, path);
CloudBlockBlob cloudBlockBlobReference = _cloudBlobContainer.GetCloudBlockBlobReference(fileName, path: path);
bool result = TaskUtilities.ExecuteSync(cloudBlockBlobReference.ExistsAsync());
// Assert
Assert.IsTrue(result);
}
[DataTestMethod]
[DataRow(SOURCE_DIRECTORY, null, DisplayName = "Delete directory without path")]
[DataRow(DUMMY_DIRECTORY, new object[] { new[] { SOURCE_DIRECTORY } }, DisplayName = "Delete directory with path")]
public void DeleteDirectoryTest(string directoryName, string[] path)
{
// Act
_fileContainer.DeleteDirectory(directoryName, path);
bool result = _fileContainer.ExistsDirectory(directoryName, path);
// Assert
Assert.IsFalse(result);
}
[DataTestMethod]
[DataRow(FILE_NAME, null, DisplayName = "Delete file without path")]
[DataRow(FILE_NAME, new object[] { new[] { SOURCE_DIRECTORY } }, DisplayName = "Delete file with path")]
public void DeleteFileTest(string fileName, string[] path)
{
// Act
_fileContainer.DeleteFile(fileName, path);
CloudBlockBlob cloudBlockBlobReference = _cloudBlobContainer.GetCloudBlockBlobReference(fileName, path: path);
bool result = TaskUtilities.ExecuteSync(cloudBlockBlobReference.ExistsAsync());
// Assert
Assert.IsFalse(result);
}
[DataTestMethod]
[DataRow(SOURCE_DIRECTORY, null, DisplayName = "Exists directory without path")]
[DataRow(DUMMY_DIRECTORY, new object[] { new[] { SOURCE_DIRECTORY } }, DisplayName = "Exists directory with path")]
public void ExistsDirectoryTest(string directoryName, string[] path)
{
// Act
bool result = _fileContainer.ExistsDirectory(directoryName, path);
// Assert
Assert.IsTrue(result);
}
[DataTestMethod]
[DataRow(FILE_NAME, null, DisplayName = "Exists file without path")]
[DataRow(FILE_NAME, new object[] { new[] { SOURCE_DIRECTORY } }, DisplayName = "Exists file with path")]
public void ExistsFileTest(string fileName, string[] path)
{
// Act
bool result = _fileContainer.ExistsFile(fileName, path);
// Assert
Assert.IsTrue(result);
}
[TestMethod]
public void ExistsPathTest()
{
// Act
bool result = _fileContainer.ExistsPath(new[] { SOURCE_DIRECTORY });
// Assert
Assert.IsTrue(result);
}
[DataTestMethod]
[DataRow(new[] { "https://bmwrcvdev.blob.core.windows.net/automatedtests/SourceDirectory", "https://bmwrcvdev.blob.core.windows.net/automatedtests/TargetDirectory" }, null, DisplayName = "Get directories without path")]
[DataRow(new[] { "https://bmwrcvdev.blob.core.windows.net/automatedtests/SourceDirectory/DummyDirectory" }, new object[] { new[] { SOURCE_DIRECTORY } }, DisplayName = "Get directories with path")]
public void GetDirectoriesTest(string[] expectedResult, string[] path)
{
// Act
string[] actualResult = _fileContainer
.GetDirectories(path)
.ToArray();
// Assert
CollectionAssert.AreEqual(expectedResult, actualResult);
}
[DataTestMethod]
[DataRow(new[] { SOURCE_DIRECTORY, TARGET_DIRECTORY }, "*", null, DisplayName = "Get directory names without path")]
[DataRow(new[] { DUMMY_DIRECTORY }, "*", new[] { SOURCE_DIRECTORY }, DisplayName = "Get directory names with path")]
public void GetDirectoryNamesTest(string[] expectedResult, string searchPattern, string[] path)
{
// Act
string[] actualResult = _fileContainer.GetDirectoryNames(searchPattern, path).ToArray();
// Assert
CollectionAssert.AreEqual(expectedResult, actualResult);
}
[DataTestMethod]
[DataRow(FILE_NAME, null, DisplayName = "Get file content without path")]
[DataRow(FILE_NAME, new object[] { new[] { SOURCE_DIRECTORY } }, DisplayName = "Get file content with path")]
public void GetFileContentTest(string fileName, string[] path)
{
// Act
string result = _fileContainer.GetFileContent(fileName, path);
// Assert
Assert.AreEqual(FILE_CONTENT, result);
}
[DataTestMethod]
[DataRow(new[] { FILE_NAME }, "*", null, DisplayName = "Get file names without path and with extension")]
[DataRow(new[] { FILE_NAME }, "*", new[] { SOURCE_DIRECTORY }, DisplayName = "Get file names with path and with extension")]
public void GetFileNamesTest(string[] expectedResult, string searchPattern, string[] path)
{
// Act
string[] actualResult = _fileContainer.GetFileNames(searchPattern, path).ToArray();
// Assert
CollectionAssert.AreEqual(expectedResult, actualResult);
}
[DataTestMethod]
[DataRow(new[] { "https://bmwrcvdev.blob.core.windows.net/automatedtests/CopyFile.txt" }, null, DisplayName = "Get files without path")]
[DataRow(new[] { "https://bmwrcvdev.blob.core.windows.net/automatedtests/SourceDirectory/CopyFile.txt" }, new object[] { new[] { SOURCE_DIRECTORY } }, DisplayName = "Get files with path")]
public void GetFilesTest(string[] expectedResult, string[] path)
{
// Act
string[] actualResult = _fileContainer
.GetFiles(path)
.ToArray();
// Assert
CollectionAssert.AreEqual(expectedResult, actualResult);
}
[DataTestMethod]
[DataRow(FILE_NAME, null, DisplayName = "Get file stream without path")]
[DataRow(FILE_NAME, new object[] { new[] { SOURCE_DIRECTORY } }, DisplayName = "Get file stream with path")]
public void GetFileStreamTest(string fileName, string[] path)
{
// Arrange
bool result;
// Act
using (Stream stream = _fileContainer.GetFileStream(fileName, new[] { SOURCE_DIRECTORY }))
{
result = stream.CanRead && !stream.CanWrite;
}
// Assert
Assert.IsTrue(result);
}
[DataTestMethod]
[DataRow(FILE_NAME, null, DisplayName = "Get write stream without path")]
[DataRow(FILE_NAME, new object[] { new[] { SOURCE_DIRECTORY } }, DisplayName = "Get write stream with path")]
public void GetWriteStreamTest(string fileName, string[] path)
{
// Arrange
bool result;
// Act
using (Stream stream = _fileContainer.GetWriteStream(FILE_NAME, path))
{
result = !stream.CanRead && stream.CanWrite;
}
// Assert
Assert.IsTrue(result);
}
[DataTestMethod]
[DataRow(SOURCE_DIRECTORY, null, new[] { TARGET_DIRECTORY }, DisplayName = "Move directory without source path")]
[DataRow(DUMMY_DIRECTORY, new[] { SOURCE_DIRECTORY }, null, DisplayName = "Move directory without target path")]
[DataRow(DUMMY_DIRECTORY, new[] { SOURCE_DIRECTORY }, new[] { TARGET_DIRECTORY }, DisplayName = "Move directory with both paths")]
public void MoveDirectoryTest(string directoryName, string[] sourcePath, string[] targetPath)
{
// Arrange
string relativeAddress = BlobUtilities.GetPath(directoryName, sourcePath);
CloudBlobDirectory sourceCloudBlobDirectory = _cloudBlobContainer.GetDirectoryReference(relativeAddress);
int expectedChildCount = TaskUtilities
.ExecuteSync(
sourceCloudBlobDirectory.ListBlobsSegmentedAsync(
useFlatBlobListing: true,
blobListingDetails: BlobListingDetails.None,
maxResults: null,
currentToken: new BlobContinuationToken(),
options: new BlobRequestOptions(),
operationContext: new OperationContext()
)
)
.Results.Count();
// Act
_fileContainer.MoveDirectory(directoryName, sourcePath, targetPath);
string path = BlobUtilities.GetPath(directoryName, targetPath);
CloudBlobDirectory targetCloudBlobDirectory = _cloudBlobContainer.GetDirectoryReference(path);
int actualChildCount = TaskUtilities
.ExecuteSync(
targetCloudBlobDirectory.ListBlobsSegmentedAsync(
useFlatBlobListing: true,
blobListingDetails: BlobListingDetails.None,
maxResults: null,
currentToken: new BlobContinuationToken(),
options: new BlobRequestOptions(),
operationContext: new OperationContext()
)
)
.Results.Count();
// Assert
Assert.IsFalse(_fileContainer.ExistsDirectory(directoryName, sourcePath));
Assert.AreEqual(expectedChildCount, actualChildCount);
}
[DataTestMethod]
[DataRow(FILE_NAME, null, DisplayName = "Get write stream without path")]
[DataRow(FILE_NAME, new object[] { new[] { SOURCE_DIRECTORY } }, DisplayName = "Get write stream with path")]
public void ReadAllBytesTest(string fileName, string[] path)
{
// Arrange
var expectedResult = new byte[] { 0x46, 0x6F, 0x6F, 0x42, 0x61, 0x72 };
// Act
byte[] actualResult = _fileContainer.ReadAllBytes(fileName, path);
// Assert
CollectionAssert.AreEqual(expectedResult, actualResult);
}
[DataTestMethod]
[DataRow(FILE_NAME, FILE_CONTENT, null, DisplayName = "Set file content without path")]
[DataRow(FILE_NAME, FILE_CONTENT, new[] { SOURCE_DIRECTORY }, DisplayName = "Set file content with path")]
public void SetFileContentTest(string fileName, string fileContent, string[] path)
{
// Act
_fileContainer.SetFileContent(fileName, fileContent, path);
var target = new byte[6];
CloudBlockBlob cloudBlockBlobReference = _cloudBlobContainer.GetCloudBlockBlobReference(fileName, path: path);
TaskUtilities.ExecuteSync(cloudBlockBlobReference.DownloadToByteArrayAsync(target, 0));
string result = Encoding.UTF8.GetString(target);
// Assert
Assert.AreEqual(fileContent, result);
}
[DataTestMethod]
[DataRow(FILE_NAME, null, DisplayName = "Set file stream without path")]
[DataRow(FILE_NAME, new object[] { new[] { SOURCE_DIRECTORY } }, DisplayName = "Set file stream with path")]
public void SetFileStreamTest(string fileName, string[] path)
{
// Arrange
using (var streamContent = new MemoryStream(Encoding.Default.GetBytes(FILE_CONTENT)))
{
_fileContainer.SetFileStream(fileName, streamContent, path);
}
var target = new byte[6];
CloudBlockBlob cloudBlockBlobReference = _cloudBlobContainer.GetCloudBlockBlobReference(fileName, path: path);
TaskUtilities.ExecuteSync(cloudBlockBlobReference.DownloadToByteArrayAsync(target, 0));
string result = Encoding.UTF8.GetString(target);
// Assert
Assert.AreEqual(FILE_CONTENT, result);
}
#endregion
}
} | 43.302575 | 236 | 0.635165 | [
"Apache-2.0"
] | Robotron-GmbH/BMW-Labeltool-Lite | RCV-LT-Lite-BE/ExternalLibraries/RCV-FileContainer/RCV-FileContainer/RCV-FileContainer.Test/Container/AzureBlobContainerTests.cs | 20,181 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebRole1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} | 19.166667 | 67 | 0.561739 | [
"MIT"
] | Azure-Samples/cloud-services-dotnet-multiple-websites-in-one-webrole | CSharp/MultiWebsitesOneWebRole/WebRole1/Controllers/HomeController.cs | 577 | C# |
using Microsoft.Extensions.Logging;
using org.apache.zookeeper;
using Surging.Core.CPlatform.Address;
using Surging.Core.CPlatform.Mqtt;
using Surging.Core.CPlatform.Mqtt.Implementation;
using Surging.Core.CPlatform.Serialization;
using Surging.Core.CPlatform.Transport.Implementation;
using Surging.Core.CPlatform.Utilities;
using Surging.Core.Zookeeper.Configurations;
using Surging.Core.Zookeeper.Internal;
using Surging.Core.Zookeeper.WatcherProvider;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Surging.Core.Zookeeper
{
public class ZooKeeperMqttServiceRouteManager : MqttServiceRouteManagerBase, IDisposable
{
private readonly ConfigInfo _configInfo;
private readonly ISerializer<byte[]> _serializer;
private readonly IMqttServiceFactory _mqttServiceFactory;
private readonly ILogger<ZooKeeperMqttServiceRouteManager> _logger;
private MqttServiceRoute[] _routes;
private readonly IZookeeperClientProvider _zookeeperClientProvider;
public ZooKeeperMqttServiceRouteManager(ConfigInfo configInfo, ISerializer<byte[]> serializer,
ISerializer<string> stringSerializer, IMqttServiceFactory mqttServiceFactory,
ILogger<ZooKeeperMqttServiceRouteManager> logger, IZookeeperClientProvider zookeeperClientProvider) : base(stringSerializer)
{
_configInfo = configInfo;
_serializer = serializer;
_mqttServiceFactory = mqttServiceFactory;
_logger = logger;
_zookeeperClientProvider = zookeeperClientProvider;
EnterRoutes().Wait();
}
/// <summary>
/// 获取所有可用的mqtt服务路由信息。
/// </summary>
/// <returns>服务路由集合。</returns>
public override async Task<IEnumerable<MqttServiceRoute>> GetRoutesAsync()
{
await EnterRoutes();
return _routes;
}
/// <summary>
/// 清空所有的mqtt服务路由。
/// </summary>
/// <returns>一个任务。</returns>
public override async Task ClearAsync()
{
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("准备清空所有mqtt路由配置。");
var zooKeepers = await _zookeeperClientProvider.GetZooKeepers();
foreach (var zooKeeper in zooKeepers)
{
var path = _configInfo.MqttRoutePath;
var childrens = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var index = 0;
while (childrens.Count() > 1)
{
var nodePath = "/" + string.Join("/", childrens);
if (await zooKeeper.Item2.existsAsync(nodePath) != null)
{
var result = await zooKeeper.Item2.getChildrenAsync(nodePath);
if (result?.Children != null)
{
foreach (var child in result.Children)
{
var childPath = $"{nodePath}/{child}";
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug($"准备删除:{childPath}。");
await zooKeeper.Item2.deleteAsync(childPath);
}
}
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug($"准备删除:{nodePath}。");
await zooKeeper.Item2.deleteAsync(nodePath);
}
index++;
childrens = childrens.Take(childrens.Length - index).ToArray();
}
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("路由配置清空完成。");
}
}
/// <summary>
/// 设置mqtt服务路由。
/// </summary>
/// <param name="routes">服务路由集合。</param>
/// <returns>一个任务。</returns>
protected override async Task SetRoutesAsync(IEnumerable<MqttServiceDescriptor> routes)
{
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("准备添加mqtt服务路由。");
var zooKeepers = await _zookeeperClientProvider.GetZooKeepers();
foreach (var zooKeeper in zooKeepers)
{
await CreateSubdirectory(zooKeeper, _configInfo.MqttRoutePath);
var path = _configInfo.MqttRoutePath;
routes = routes.ToArray();
foreach (var serviceRoute in routes)
{
var nodePath = $"{path}{serviceRoute.MqttDescriptor.Topic}";
var nodeData = _serializer.Serialize(serviceRoute);
if (await zooKeeper.Item2.existsAsync(nodePath) == null)
{
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug($"节点:{nodePath}不存在将进行创建。");
await zooKeeper.Item2.createAsync(nodePath, nodeData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
else
{
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug($"将更新节点:{nodePath}的数据。");
var onlineData = (await zooKeeper.Item2.getDataAsync(nodePath)).Data;
if (!DataEquals(nodeData, onlineData))
await zooKeeper.Item2.setDataAsync(nodePath, nodeData);
}
}
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("mqtt服务路由添加成功。");
}
}
public override async Task RemveAddressAsync(IEnumerable<AddressModel> Address)
{
var routes = await GetRoutesAsync();
foreach (var route in routes)
{
route.MqttEndpoint = route.MqttEndpoint.Except(Address);
}
await base.SetRoutesAsync(routes);
}
public override async Task RemoveByTopicAsync(string topic, IEnumerable<AddressModel> endpoint)
{
var routes = await GetRoutesAsync();
var route = routes.Where(p => p.MqttDescriptor.Topic == topic).SingleOrDefault();
if (route != null)
{
route.MqttEndpoint = route.MqttEndpoint.Except(endpoint);
await base.SetRoutesAsync(new MqttServiceRoute[] { route });
}
}
public override async Task SetRoutesAsync(IEnumerable<MqttServiceRoute> routes)
{
var hostAddr = NetUtils.GetHostAddress();
var serviceRoutes = await GetRoutes(routes.Select(p => p.MqttDescriptor.Topic));
if (serviceRoutes.Count() > 0)
{
foreach (var route in routes)
{
var serviceRoute = serviceRoutes.Where(p => p.MqttDescriptor.Topic == route.MqttDescriptor.Topic).FirstOrDefault();
if (serviceRoute != null)
{
var addresses = serviceRoute.MqttEndpoint.Concat(
route.MqttEndpoint.Except(serviceRoute.MqttEndpoint)).ToList();
foreach (var address in route.MqttEndpoint)
{
addresses.Remove(addresses.Where(p => p.ToString() == address.ToString()).FirstOrDefault());
addresses.Add(address);
}
route.MqttEndpoint = addresses;
}
}
}
await RemoveExceptRoutesAsync(routes, hostAddr);
await base.SetRoutesAsync(routes);
}
private async Task RemoveExceptRoutesAsync(IEnumerable<MqttServiceRoute> routes, AddressModel hostAddr)
{
var path = _configInfo.MqttRoutePath;
routes = routes.ToArray();
var zooKeepers = await _zookeeperClientProvider.GetZooKeepers();
foreach (var zooKeeper in zooKeepers)
{
if (_routes != null)
{
var oldRouteTopics = _routes.Select(i => i.MqttDescriptor.Topic).ToArray();
var newRouteTopics = routes.Select(i => i.MqttDescriptor.Topic).ToArray();
var deletedRouteTopics = oldRouteTopics.Except(newRouteTopics).ToArray();
foreach (var deletedRouteTopic in deletedRouteTopics)
{
var addresses = _routes.Where(p => p.MqttDescriptor.Topic == deletedRouteTopic).Select(p => p.MqttEndpoint).FirstOrDefault();
if (addresses.Contains(hostAddr))
{
var nodePath = $"{path}{deletedRouteTopic}";
await zooKeeper.Item2.deleteAsync(nodePath);
}
}
}
}
}
private async Task CreateSubdirectory((ManualResetEvent, ZooKeeper) zooKeeper, string path)
{
zooKeeper.Item1.WaitOne();
if (await zooKeeper.Item2.existsAsync(path) != null)
return;
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation($"节点{path}不存在,将进行创建。");
var childrens = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var nodePath = "/";
foreach (var children in childrens)
{
nodePath += children;
if (await zooKeeper.Item2.existsAsync(nodePath) == null)
{
await zooKeeper.Item2.createAsync(nodePath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
nodePath += "/";
}
}
private async Task<MqttServiceRoute> GetRoute(byte[] data)
{
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug($"准备转换mqtt服务路由,配置内容:{Encoding.UTF8.GetString(data)}。");
if (data == null)
return null;
var descriptor = _serializer.Deserialize<byte[], MqttServiceDescriptor>(data);
return (await _mqttServiceFactory.CreateMqttServiceRoutesAsync(new[] { descriptor })).First();
}
private async Task<MqttServiceRoute> GetRoute(string path)
{
MqttServiceRoute result = null;
var zooKeeper = await GetZooKeeper();
var watcher = new NodeMonitorWatcher(GetZooKeeper, path,
async (oldData, newData) => await NodeChange(oldData, newData));
if (await zooKeeper.Item2.existsAsync(path) != null)
{
var data = (await zooKeeper.Item2.getDataAsync(path, watcher)).Data;
watcher.SetCurrentData(data);
result = await GetRoute(data);
}
return result;
}
private async Task<MqttServiceRoute[]> GetRoutes(IEnumerable<string> childrens)
{
var rootPath = _configInfo.MqttRoutePath;
childrens = childrens.ToArray();
var routes = new List<MqttServiceRoute>(childrens.Count());
foreach (var children in childrens)
{
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug($"准备从节点:{children}中获取mqtt路由信息。");
var nodePath = $"{rootPath}{children}";
var route = await GetRoute(nodePath);
if (route != null)
routes.Add(route);
}
return routes.ToArray();
}
private async Task EnterRoutes()
{
if (_routes != null)
return;
var zooKeeper = await GetZooKeeper();
zooKeeper.Item1.WaitOne();
var watcher = new ChildrenMonitorWatcher(GetZooKeeper, _configInfo.MqttRoutePath,
async (oldChildrens, newChildrens) => await ChildrenChange(oldChildrens, newChildrens));
if (await zooKeeper.Item2.existsAsync(_configInfo.MqttRoutePath, watcher) != null)
{
var result = await zooKeeper.Item2.getChildrenAsync(_configInfo.MqttRoutePath, watcher);
var childrens = result.Children.ToArray();
watcher.SetCurrentData(childrens);
_routes = await GetRoutes(childrens);
}
else
{
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning($"无法获取mqtt路由信息,因为节点:{_configInfo.RoutePath},不存在。");
_routes = new MqttServiceRoute[0];
}
}
private static bool DataEquals(IReadOnlyList<byte> data1, IReadOnlyList<byte> data2)
{
if (data1.Count != data2.Count)
return false;
for (var i = 0; i < data1.Count; i++)
{
var b1 = data1[i];
var b2 = data2[i];
if (b1 != b2)
return false;
}
return true;
}
public async Task NodeChange(byte[] oldData, byte[] newData)
{
if (DataEquals(oldData, newData))
return;
var newRoute = await GetRoute(newData);
//得到旧的mqtt路由。
var oldRoute = _routes.FirstOrDefault(i => i.MqttDescriptor.Topic == newRoute.MqttDescriptor.Topic);
lock (_routes)
{
//删除旧mqtt路由,并添加上新的mqtt路由。
_routes =
_routes
.Where(i => i.MqttDescriptor.Topic != newRoute.MqttDescriptor.Topic)
.Concat(new[] { newRoute }).ToArray();
}
//触发路由变更事件。
OnChanged(new MqttServiceRouteChangedEventArgs(newRoute, oldRoute));
}
public async Task ChildrenChange(string[] oldChildrens, string[] newChildrens)
{
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug($"最新的mqtt节点信息:{string.Join(",", newChildrens)}");
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug($"旧的mqtt节点信息:{string.Join(",", oldChildrens)}");
//计算出已被删除的节点。
var deletedChildrens = oldChildrens.Except(newChildrens).ToArray();
//计算出新增的节点。
var createdChildrens = newChildrens.Except(oldChildrens).ToArray();
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug($"需要被删除的mqtt路由节点:{string.Join(",", deletedChildrens)}");
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug($"需要被添加的mqtt路由节点:{string.Join(",", createdChildrens)}");
//获取新增的mqtt路由信息。
var newRoutes = (await GetRoutes(createdChildrens)).ToArray();
var routes = _routes.ToArray();
lock (_routes)
{
_routes = _routes
//删除无效的节点路由。
.Where(i => !deletedChildrens.Contains(i.MqttDescriptor.Topic))
//连接上新的mqtt路由。
.Concat(newRoutes)
.ToArray();
}
//需要删除的Topic路由集合。
var deletedRoutes = routes.Where(i => deletedChildrens.Contains(i.MqttDescriptor.Topic)).ToArray();
//触发删除事件。
OnRemoved(deletedRoutes.Select(route => new MqttServiceRouteEventArgs(route)).ToArray());
//触发路由被创建事件。
OnCreated(newRoutes.Select(route => new MqttServiceRouteEventArgs(route)).ToArray());
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("mqtt路由数据更新成功。");
}
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
public void Dispose()
{
}
private async ValueTask<(ManualResetEvent, ZooKeeper)> GetZooKeeper()
{
var zooKeeper = await _zookeeperClientProvider.GetZooKeeper();
return zooKeeper;
}
}
}
| 40.746269 | 149 | 0.551832 | [
"MIT"
] | 914132883/surging | src/Surging.Core/Surging.Core.Zookeeper/ZooKeeperMqttServiceRouteManager.cs | 17,060 | C# |
#region BSD License
/*
Copyright (c) 2004-2005 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com)
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.
* The name of the author may not be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
using Prebuild.Core.Attributes;
using Prebuild.Core.Interfaces;
using Prebuild.Core.Utilities;
namespace Prebuild.Core.Nodes
{
/// <summary>
///
/// </summary>
[DataNode("Options")]
public class OptionsNode : DataNode
{
#region Fields
private static readonly Dictionary<string,FieldInfo> m_OptionFields = new Dictionary<string, FieldInfo>();
[OptionNode("CompilerDefines")]
private string m_CompilerDefines = "";
/// <summary>
///
/// </summary>
public string CompilerDefines
{
get
{
return m_CompilerDefines;
}
set
{
m_CompilerDefines = value;
}
}
[OptionNode("OptimizeCode")]
private bool m_OptimizeCode;
/// <summary>
///
/// </summary>
public bool OptimizeCode
{
get
{
return m_OptimizeCode;
}
set
{
m_OptimizeCode = value;
}
}
[OptionNode("CheckUnderflowOverflow")]
private bool m_CheckUnderflowOverflow;
/// <summary>
///
/// </summary>
public bool CheckUnderflowOverflow
{
get
{
return m_CheckUnderflowOverflow;
}
set
{
m_CheckUnderflowOverflow = value;
}
}
[OptionNode("AllowUnsafe")]
private bool m_AllowUnsafe;
/// <summary>
///
/// </summary>
public bool AllowUnsafe
{
get
{
return m_AllowUnsafe;
}
set
{
m_AllowUnsafe = value;
}
}
[OptionNode("PreBuildEvent")]
private string m_PreBuildEvent;
/// <summary>
///
/// </summary>
public string PreBuildEvent
{
get
{
return m_PreBuildEvent;
}
set
{
m_PreBuildEvent = value;
}
}
[OptionNode("PostBuildEvent")]
private string m_PostBuildEvent;
/// <summary>
///
/// </summary>
public string PostBuildEvent
{
get
{
return m_PostBuildEvent;
}
set
{
m_PostBuildEvent = value;
}
}
[OptionNode("PreBuildEventArgs")]
private string m_PreBuildEventArgs;
/// <summary>
///
/// </summary>
public string PreBuildEventArgs
{
get
{
return m_PreBuildEventArgs;
}
set
{
m_PreBuildEventArgs = value;
}
}
[OptionNode("PostBuildEventArgs")]
private string m_PostBuildEventArgs;
/// <summary>
///
/// </summary>
public string PostBuildEventArgs
{
get
{
return m_PostBuildEventArgs;
}
set
{
m_PostBuildEventArgs = value;
}
}
[OptionNode("RunPostBuildEvent")]
private string m_RunPostBuildEvent;
/// <summary>
///
/// </summary>
public string RunPostBuildEvent
{
get
{
return m_RunPostBuildEvent;
}
set
{
m_RunPostBuildEvent = value;
}
}
[OptionNode("RunScript")]
private string m_RunScript;
/// <summary>
///
/// </summary>
public string RunScript
{
get
{
return m_RunScript;
}
set
{
m_RunScript = value;
}
}
[OptionNode("WarningLevel")]
private int m_WarningLevel = 4;
/// <summary>
///
/// </summary>
public int WarningLevel
{
get
{
return m_WarningLevel;
}
set
{
m_WarningLevel = value;
}
}
[OptionNode("WarningsAsErrors")]
private bool m_WarningsAsErrors;
/// <summary>
///
/// </summary>
public bool WarningsAsErrors
{
get
{
return m_WarningsAsErrors;
}
set
{
m_WarningsAsErrors = value;
}
}
[OptionNode("SuppressWarnings")]
private string m_SuppressWarnings = "";
/// <summary>
///
/// </summary>
public string SuppressWarnings
{
get
{
return m_SuppressWarnings;
}
set
{
m_SuppressWarnings = value;
}
}
[OptionNode("Prefer32Bit")]
private bool m_Prefer32Bit;
/// <summary>
///
/// </summary>
public bool Prefer32Bit
{
get
{
return m_Prefer32Bit;
}
set
{
m_Prefer32Bit = value;
}
}
[OptionNode("OutputPath")]
private string m_OutputPath = "bin/";
/// <summary>
///
/// </summary>
public string OutputPath
{
get
{
return m_OutputPath;
}
set
{
m_OutputPath = value;
}
}
[OptionNode("GenerateDocumentation")]
private bool m_GenerateDocumentation;
/// <summary>
///
/// </summary>
public bool GenerateDocumentation
{
get
{
return m_GenerateDocumentation;
}
set
{
m_GenerateDocumentation = value;
}
}
[OptionNode("GenerateXmlDocFile")]
private bool m_GenerateXmlDocFile;
/// <summary>
///
/// </summary>
public bool GenerateXmlDocFile
{
get
{
return m_GenerateXmlDocFile;
}
set
{
m_GenerateXmlDocFile = value;
}
}
[OptionNode("XmlDocFile")]
private string m_XmlDocFile = "";
/// <summary>
///
/// </summary>
public string XmlDocFile
{
get
{
return m_XmlDocFile;
}
set
{
m_XmlDocFile = value;
}
}
[OptionNode("KeyFile")]
private string m_KeyFile = "";
/// <summary>
///
/// </summary>
public string KeyFile
{
get
{
return m_KeyFile;
}
set
{
m_KeyFile = value;
}
}
[OptionNode("DebugInformation")]
private bool m_DebugInformation;
/// <summary>
///
/// </summary>
public bool DebugInformation
{
get
{
return m_DebugInformation;
}
set
{
m_DebugInformation = value;
}
}
[OptionNode("RegisterComInterop")]
private bool m_RegisterComInterop;
/// <summary>
///
/// </summary>
public bool RegisterComInterop
{
get
{
return m_RegisterComInterop;
}
set
{
m_RegisterComInterop = value;
}
}
[OptionNode("RemoveIntegerChecks")]
private bool m_RemoveIntegerChecks;
/// <summary>
///
/// </summary>
public bool RemoveIntegerChecks
{
get
{
return m_RemoveIntegerChecks;
}
set
{
m_RemoveIntegerChecks = value;
}
}
[OptionNode("IncrementalBuild")]
private bool m_IncrementalBuild;
/// <summary>
///
/// </summary>
public bool IncrementalBuild
{
get
{
return m_IncrementalBuild;
}
set
{
m_IncrementalBuild = value;
}
}
[OptionNode("BaseAddress")]
private string m_BaseAddress = "285212672";
/// <summary>
///
/// </summary>
public string BaseAddress
{
get
{
return m_BaseAddress;
}
set
{
m_BaseAddress = value;
}
}
[OptionNode("FileAlignment")]
private int m_FileAlignment = 4096;
/// <summary>
///
/// </summary>
public int FileAlignment
{
get
{
return m_FileAlignment;
}
set
{
m_FileAlignment = value;
}
}
[OptionNode("NoStdLib")]
private bool m_NoStdLib;
/// <summary>
///
/// </summary>
public bool NoStdLib
{
get
{
return m_NoStdLib;
}
set
{
m_NoStdLib = value;
}
}
private readonly List<string> m_FieldsDefined = new List<string>();
#endregion
#region Constructors
/// <summary>
/// Initializes the <see cref="OptionsNode"/> class.
/// </summary>
static OptionsNode()
{
Type t = typeof(OptionsNode);
foreach(FieldInfo f in t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
{
object[] attrs = f.GetCustomAttributes(typeof(OptionNodeAttribute), false);
if(attrs == null || attrs.Length < 1)
{
continue;
}
OptionNodeAttribute ona = (OptionNodeAttribute)attrs[0];
m_OptionFields[ona.NodeName] = f;
}
}
#endregion
#region Properties
/// <summary>
/// Gets the <see cref="Object"/> at the specified index.
/// </summary>
/// <value></value>
public object this[string index]
{
get
{
if(!m_OptionFields.ContainsKey(index))
{
return null;
}
FieldInfo f = m_OptionFields[index];
return f.GetValue(this);
}
}
/// <summary>
/// Gets the <see cref="Object"/> at the specified index.
/// </summary>
/// <value></value>
public object this[string index, object defaultValue]
{
get
{
object valueObject = this[index];
if(valueObject != null && valueObject is string && ((string)valueObject).Length == 0)
{
return defaultValue;
}
return valueObject;
}
}
#endregion
#region Private Methods
private void FlagDefined(string name)
{
if(!m_FieldsDefined.Contains(name))
{
m_FieldsDefined.Add(name);
}
}
private void SetOption(string nodeName, string val)
{
lock(m_OptionFields)
{
if(!m_OptionFields.ContainsKey(nodeName))
{
return;
}
FieldInfo f = m_OptionFields[nodeName];
f.SetValue(this, Helper.TranslateValue(f.FieldType, val));
FlagDefined(f.Name);
}
}
#endregion
#region Public Methods
/// <summary>
/// Parses the specified node.
/// </summary>
/// <param name="node">The node.</param>
public override void Parse(XmlNode node)
{
if( node == null )
{
throw new ArgumentNullException("node");
}
foreach(XmlNode child in node.ChildNodes)
{
SetOption(child.Name, Helper.InterpolateForEnvironmentVariables(child.InnerText));
}
}
/// <summary>
/// Copies to.
/// </summary>
/// <param name="opt">The opt.</param>
public void CopyTo(OptionsNode opt)
{
if(opt == null)
{
return;
}
foreach(FieldInfo f in m_OptionFields.Values)
{
if(m_FieldsDefined.Contains(f.Name))
{
f.SetValue(opt, f.GetValue(this));
opt.m_FieldsDefined.Add(f.Name);
}
}
}
#endregion
}
}
| 17.108729 | 108 | 0.612871 | [
"BSD-3-Clause"
] | AI-Grid/AI-Grid-2.0 | Prebuild/src/Core/Nodes/OptionsNode.cs | 11,172 | C# |
using Fss.HumanCapitalManager.Core.Models;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tests.Core
{
[TestFixture]
public class RolePickList_Tests
{
[Test]
[Category("Integration")]
[Description("Core.RolePickList.Integration")]
public void RolePickList_can_construct()
{
// AAA - Arrange, Act, Assert
// Arrange
var sut = new RolePickList(() => new RoleCollection(),
() => new Role());
// Act
// Assert
Assert.Multiple(() =>
{
Assert.That(sut.Roles, Is.Not.Null);
Assert.That(sut.SelectedRole, Is.Null);
});
}
[Test]
[Category("Integration")]
[Description("Core.RolePickList.Integration")]
public void RolePickList_can_add_skill()
{
// AAA - Arrange, Act, Assert
// Arrange
RolePickList sut = new RolePickList(() => new RoleCollection(),
() => new Role());
var r1 = new Role() { RoleID = 101, Name = "DEV" };
var r2 = new Role() { RoleID = 102, Name = "SQA" };
var r3 = new Role() { RoleID = 103, Name = "PM" };
// Act
sut.AddRole(r1);
sut.AddRole(r2);
sut.AddRole(r3);
// Assert
Assert.Multiple(() =>
{
Assert.That(sut.Roles, Is.Not.Null);
Assert.That(sut.Roles.Count == 3);
Assert.That(sut.SelectedRole, Is.Null);
});
}
[Test]
[Category("Integration")]
[Description("Core.RolePickList.Integration")]
public void RolePickList_can_remove_skill_by_reference()
{
// AAA - Arrange, Act, Assert
// Arrange
RolePickList sut = new RolePickList(() => new RoleCollection(),
() => new Role());
var r1 = new Role() { RoleID = 101, Name = "DEV" };
var r2 = new Role() { RoleID = 102, Name = "SQA" };
var r3 = new Role() { RoleID = 103, Name = "PM" };
sut.AddRole(r1);
sut.AddRole(r2);
sut.AddRole(r3);
// Act
var firstRemove = sut.RemoveRole(r3);
var secondRemove = sut.RemoveRole(r3);
// Assert
Assert.Multiple(() =>
{
Assert.That(sut.Roles, Is.Not.Null);
Assert.That(firstRemove, Is.True);
Assert.That(secondRemove, Is.False);
Assert.That(sut.Roles.Count == 2);
Assert.That(sut.SelectedRole, Is.Null);
});
}
[Test]
[Category("Integration")]
[Description("Core.RolePickList.Integration")]
public void RolePickList_can_remove_skill_by_value()
{
// AAA - Arrange, Act, Assert
// Arrange
RolePickList sut = new RolePickList(() => new RoleCollection(),
() => new Role());
var r1 = new Role() { RoleID = 101, Name = "DEV" };
var r2 = new Role() { RoleID = 102, Name = "SQA" };
var r3 = new Role() { RoleID = 103, Name = "PM" };
// Act
sut.AddRole(r1);
sut.AddRole(r2);
sut.AddRole(r3);
// Act
var firstRemove = sut.RemoveRole(new Role { RoleID = 101, Name = "DEV" });
// Assert
Assert.Multiple(() =>
{
Assert.That(sut.Roles, Is.Not.Null);
Assert.That(firstRemove, Is.True);
Assert.That(sut.Roles.Count == 2);
Assert.That(sut.SelectedRole, Is.Null);
});
}
[Test]
[Category("Integration")]
[Description("Core.RolePickList.Integration")]
public void RolePickList_can_select_existing_skill()
{
// AAA - Arrange, Act, Assert
// Arrange
RolePickList sut = new RolePickList(() => new RoleCollection(),
() => new Role());
var r1 = new Role() { RoleID = 101, Name = "DEV" };
var r2 = new Role() { RoleID = 102, Name = "SQA" };
var r3 = new Role() { RoleID = 103, Name = "PM" };
sut.AddRole(r1);
sut.AddRole(r2);
sut.AddRole(r3);
// Act
sut.SelectedRole = r3;
// Assert
Assert.Multiple(() =>
{
Assert.That(sut.Roles, Is.Not.Null);
Assert.That(sut.SelectedRole, Is.Not.Null);
});
}
}
}
//var r1 = new Role() { RoleID = 101, Name = "DEV"};
//var r2 = new Role() { RoleID = 102, Name = "SQA" };
//var r3 = new Role() { RoleID = 103, Name = "PM" };
//var r4 = new Role() { RoleID = 104, Name = "BLD" };
//var r5 = new Role() { RoleID = 105, Name = "SCCM" };
//var r6 = new Role() { RoleID = 106, Name = "DEV Lead" };
//var r7 = new Role() { RoleID = 107, Name = "SCRMM" }; | 31.116279 | 86 | 0.466181 | [
"MIT"
] | Tom-Wells-NW/Mvvm-Demo-01 | Tests.Core/RolePickList_Tests.cs | 5,354 | C# |
using System;
using System.IO;
namespace UberStrok.Core.Serialization
{
public static class Int32Proxy
{
public static int Deserialize(Stream bytes)
{
byte[] buffer = new byte[4];
bytes.Read(buffer, 0, 4);
return BitConverter.ToInt32(buffer, 0);
}
public static void Serialize(Stream bytes, int instance)
{
byte[] buffer = BitConverter.GetBytes(instance);
bytes.Write(buffer, 0, buffer.Length);
}
}
}
| 23.782609 | 65 | 0.555759 | [
"MIT"
] | PoH98/uberstrok | src/UberStrok.Core.Serialization/Int32Proxy.cs | 549 | C# |
// ----------------------------------------------------------------------------
// <copyright file="PhotonTransformViewRotationControl.cs" company="Exit Games GmbH">
// PhotonNetwork Framework for Unity - Copyright (C) 2016 Exit Games GmbH
// </copyright>
// <summary>
// Component to synchronize rotations via PUN PhotonView.
// </summary>
// <author>developer@exitgames.com</author>
// ----------------------------------------------------------------------------
using UnityEngine;
using System.Collections;
public class PhotonTransformViewRotationControl
{
PhotonTransformViewRotationModel m_Model;
Quaternion m_NetworkRotation;
public PhotonTransformViewRotationControl( PhotonTransformViewRotationModel model )
{
m_Model = model;
}
/// <summary>
/// Gets the last rotation that was received through the network
/// </summary>
/// <returns></returns>
public Quaternion GetNetworkRotation()
{
return m_NetworkRotation;
}
public Quaternion GetRotation( Quaternion currentRotation )
{
switch( m_Model.InterpolateOption )
{
default:
case PhotonTransformViewRotationModel.InterpolateOptions.Disabled:
return m_NetworkRotation;
case PhotonTransformViewRotationModel.InterpolateOptions.RotateTowards:
return Quaternion.RotateTowards( currentRotation, m_NetworkRotation, m_Model.InterpolateRotateTowardsSpeed * Time.deltaTime );
case PhotonTransformViewRotationModel.InterpolateOptions.Lerp:
return Quaternion.Lerp( currentRotation, m_NetworkRotation, m_Model.InterpolateLerpSpeed * Time.deltaTime );
}
}
public void OnPhotonSerializeView( Quaternion currentRotation, PhotonStream stream, PhotonMessageInfo info )
{
if( m_Model.SynchronizeEnabled == false )
{
return;
}
if( stream.isWriting == true )
{
stream.SendNext( currentRotation );
m_NetworkRotation = currentRotation;
}
else
{
m_NetworkRotation = (Quaternion)stream.ReceiveNext();
}
}
} | 34.203125 | 139 | 0.624486 | [
"Unlicense"
] | FaizanHZaidi/alternate-realities | 10_photon_networking/Networking_Basics/Assets/Photon Unity Networking/Plugins/PhotonNetwork/Views/PhotonTransformViewRotationControl.cs | 2,191 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Utilities;
using System;
using System.Collections.Generic;
using Unity.Profiling;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit
{
/// <summary>
/// Abstract class for core MRTK system with functionality defined for managing and accessing IMixedRealityDataProviders
/// </summary>
public abstract class BaseDataProviderAccessCoreSystem : BaseCoreSystem, IMixedRealityDataProviderAccess
{
private readonly List<IMixedRealityDataProvider> dataProviders = new List<IMixedRealityDataProvider>();
public override void Reset()
{
base.Reset();
foreach (var provider in dataProviders)
{
provider.Reset();
}
}
/// <inheritdoc />
public override void Enable()
{
base.Enable();
foreach (var provider in dataProviders)
{
provider.Enable();
}
}
private static readonly ProfilerMarker UpdatePerfMarker = new ProfilerMarker("[MRTK] BaseDataProviderAccessCoreSystem.Update");
/// <inheritdoc />
public override void Update()
{
using (UpdatePerfMarker.Auto())
{
base.Update();
foreach (var provider in dataProviders)
{
provider.Update();
}
}
}
private static readonly ProfilerMarker LateUpdatePerfMarker = new ProfilerMarker("[MRTK] BaseDataProviderAccessCoreSystem.LateUpdate");
/// <inheritdoc />
public override void LateUpdate()
{
using (LateUpdatePerfMarker.Auto())
{
base.LateUpdate();
foreach (var provider in dataProviders)
{
provider.LateUpdate();
}
}
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="registrar">The <see cref="IMixedRealityServiceRegistrar"/> instance that loaded the service.</param>
/// <param name="profile">The configuration profile for the service.</param>
[Obsolete("This constructor is obsolete (registrar parameter is no longer required) and will be removed in a future version of the Microsoft Mixed Reality Toolkit.")]
protected BaseDataProviderAccessCoreSystem(
IMixedRealityServiceRegistrar registrar,
BaseMixedRealityProfile profile = null) : this(profile)
{
Registrar = registrar;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="profile">The configuration profile for the service.</param>
protected BaseDataProviderAccessCoreSystem(
BaseMixedRealityProfile profile = null) : base(profile)
{ }
#region IMixedRealityDataProviderAccess Implementation
/// <inheritdoc />
public virtual IReadOnlyList<IMixedRealityDataProvider> GetDataProviders()
{
return dataProviders.AsReadOnly();
}
/// <inheritdoc />
public virtual IReadOnlyList<T> GetDataProviders<T>() where T : IMixedRealityDataProvider
{
List<T> selected = new List<T>();
foreach (var provider in dataProviders)
{
if (provider is T providerT)
{
selected.Add(providerT);
}
}
return selected;
}
/// <inheritdoc />
public virtual IMixedRealityDataProvider GetDataProvider(string name)
{
foreach (var provider in dataProviders)
{
if (provider.Name == name)
{
return provider;
}
}
return null;
}
/// <inheritdoc />
public virtual T GetDataProvider<T>(string name = null) where T : IMixedRealityDataProvider
{
foreach (var provider in dataProviders)
{
if (provider is T providerT)
{
if (name == null || provider.Name == name)
{
return providerT;
}
}
}
return default(T);
}
#endregion IMixedRealityDataProviderAccess Implementation
/// <summary>
/// Registers a data provider of the specified type.
/// </summary>
protected bool RegisterDataProvider<T>(
Type concreteType,
string providerName,
SupportedPlatforms supportedPlatforms = (SupportedPlatforms)(-1),
params object[] args) where T : IMixedRealityDataProvider
{
return RegisterDataProviderInternal<T>(
true, // Retry with an added IMixedRealityService parameter
concreteType,
providerName,
supportedPlatforms,
args);
}
/// <summary>
/// Registers a data provider of the specified type.
/// </summary>
[Obsolete("RegisterDataProvider<T>(Type, SupportedPlatforms, param object[]) is obsolete and will be removed from a future version of MRTK\n" +
"Please use RegisterDataProvider<T>(Type, string, SupportedPlatforms, params object[])")]
protected bool RegisterDataProvider<T>(
Type concreteType,
SupportedPlatforms supportedPlatforms = (SupportedPlatforms)(-1),
params object[] args) where T : IMixedRealityDataProvider
{
return RegisterDataProvider<T>(
concreteType,
string.Empty,
supportedPlatforms,
args);
}
/// <summary>
/// Internal method that creates an instance of the specified concrete type and registers the provider.
/// </summary>
private bool RegisterDataProviderInternal<T>(
bool retryWithRegistrar,
Type concreteType,
string providerName,
SupportedPlatforms supportedPlatforms = (SupportedPlatforms)(-1),
params object[] args) where T : IMixedRealityDataProvider
{
if (!PlatformUtility.IsPlatformSupported(supportedPlatforms))
{
DebugUtilities.LogVerboseFormat(
"Not registering data provider of type {0} with name {1} because the current platform is not in supported platforms {2}",
concreteType,
providerName,
supportedPlatforms);
return false;
}
if (concreteType == null)
{
if (!Application.isEditor)
{
Debug.LogWarning($"Unable to register {typeof(T).Name} data provider ({(!string.IsNullOrWhiteSpace(providerName) ? providerName : "unknown")}) because the value of concreteType is null.\n" +
"This may be caused by code being stripped during linking. The link.xml file in the MixedRealityToolkit.Generated folder is used to control code preservation.\n" +
"More information can be found at https://docs.unity3d.com/Manual/ManagedCodeStripping.html.");
}
return false;
}
SupportedUnityXRPipelines selectedPipeline =
#if UNITY_2020_1_OR_NEWER
SupportedUnityXRPipelines.XRSDK;
#elif UNITY_2019
!XRSettingsUtilities.LegacyXRAvailable ? SupportedUnityXRPipelines.XRSDK : SupportedUnityXRPipelines.LegacyXR;
#else
SupportedUnityXRPipelines.LegacyXR;
#endif
if (MixedRealityExtensionServiceAttribute.Find(concreteType) is MixedRealityDataProviderAttribute providerAttribute)
{
if (!providerAttribute.SupportedUnityXRPipelines.HasFlag(selectedPipeline))
{
DebugUtilities.LogVerboseFormat("{0} not suitable for the current XR pipeline ({1})", concreteType.Name, selectedPipeline);
return false;
}
}
if (!typeof(IMixedRealityDataProvider).IsAssignableFrom(concreteType))
{
Debug.LogError($"Unable to register the {concreteType.Name} data provider. It does not implement {typeof(IMixedRealityDataProvider)}.");
return false;
}
T dataProviderInstance;
try
{
dataProviderInstance = (T)Activator.CreateInstance(concreteType, args);
}
catch (Exception e)
{
if (retryWithRegistrar && (e is MissingMethodException))
{
Debug.LogWarning($"Failed to find an appropriate constructor for the {concreteType.Name} data provider. Adding the Registrar instance and re-attempting registration.");
#pragma warning disable 0618
List<object> updatedArgs = new List<object>();
updatedArgs.Add(Registrar);
if (args != null)
{
updatedArgs.AddRange(args);
}
return RegisterDataProviderInternal<T>(
false, // Do NOT retry, we have already added the configured IMIxedRealityServiceRegistrar
concreteType,
providerName,
supportedPlatforms,
updatedArgs.ToArray());
#pragma warning restore 0618
}
Debug.LogError($"Failed to register the {concreteType.Name} data provider: {e.GetType()} - {e.Message}");
// Failures to create the concrete type generally surface as nested exceptions - just logging
// the top level exception itself may not be helpful. If there is a nested exception (for example,
// null reference in the constructor of the object itself), it's helpful to also surface those here.
if (e.InnerException != null)
{
Debug.LogError("Underlying exception information: " + e.InnerException);
}
return false;
}
return RegisterDataProvider(dataProviderInstance);
}
/// <summary>
/// Registers a service of the specified type.
/// </summary>
/// <typeparam name="T">The interface type of the data provider to be registered.</typeparam>
/// <param name="dataProviderInstance">An instance of the data provider to be registered.</param>
protected bool RegisterDataProvider<T>(T dataProviderInstance) where T : IMixedRealityDataProvider
{
if (dataProviderInstance == null)
{
Debug.LogWarning($"Unable to add a {dataProviderInstance.Name} data provider with a null instance.");
return false;
}
dataProviders.Add(dataProviderInstance);
dataProviderInstance.Initialize();
return true;
}
/// <summary>
/// Unregisters a data provider of the specified type.
/// </summary>
/// <typeparam name="T">The interface type of the data provider to be unregistered.</typeparam>
/// <param name="name">The name of the data provider to unregister.</param>
/// <returns>True if the data provider was successfully unregistered, false otherwise.</returns>
/// <remarks>If the name argument is not specified, the first instance will be unregistered</remarks>
protected bool UnregisterDataProvider<T>(string name = null) where T : IMixedRealityDataProvider
{
T dataProviderInstance = GetDataProvider<T>(name);
if (dataProviderInstance == null) { return false; }
return UnregisterDataProvider(dataProviderInstance);
}
/// <summary>
/// Unregisters a data provider.
/// </summary>
/// <typeparam name="T">The interface type of the data provider to be unregistered.</typeparam>
/// <param name="service">The specific data provider instance to unregister.</param>
/// <returns>True if the data provider was successfully unregistered, false otherwise.</returns>
protected bool UnregisterDataProvider<T>(T dataProviderInstance) where T : IMixedRealityDataProvider
{
if (dataProviderInstance == null)
{
return false;
}
if (dataProviders.Contains(dataProviderInstance))
{
dataProviders.Remove(dataProviderInstance);
dataProviderInstance.Disable();
dataProviderInstance.Destroy();
return true;
}
return false;
}
}
}
| 38.209302 | 210 | 0.575167 | [
"MIT"
] | ForJobOk/MixedRealityToolkit-Unity | Assets/MRTK/Core/Services/BaseDataProviderAccessCoreSystem.cs | 13,146 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface IRule
{
void Execute(string input, ref CGAContext context);
void Validate();
string GetPattern();
void SetPattern(string pattern);
}
| 16.928571 | 52 | 0.776371 | [
"MIT"
] | sigr3s/Unity_CGA | Assets/Scripts/BaseRule/IRule.cs | 239 | C# |
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Text.RegularExpressions;
using Microsoft.Recognizers.Definitions.German;
namespace Microsoft.Recognizers.Text.Number.German
{
public class NumberExtractor : CachedNumberExtractor
{
private const RegexOptions RegexFlags = RegexOptions.Singleline | RegexOptions.ExplicitCapture;
private static readonly ConcurrentDictionary<(NumberMode, NumberOptions), NumberExtractor> Instances =
new ConcurrentDictionary<(NumberMode, NumberOptions), NumberExtractor>();
private readonly string keyPrefix;
private NumberExtractor(BaseNumberOptionsConfiguration config)
: base(config.Options)
{
keyPrefix = string.Intern(ExtractType + "_" + config.Options + "_" + config.Mode + "_" + config.Culture);
var builder = ImmutableDictionary.CreateBuilder<Regex, TypeTag>();
// Add Cardinal
CardinalExtractor cardExtract = null;
switch (config.Mode)
{
case NumberMode.PureNumber:
cardExtract = CardinalExtractor.GetInstance(config);
break;
case NumberMode.Currency:
builder.Add(
BaseNumberExtractor.CurrencyRegex,
RegexTagGenerator.GenerateRegexTag(Constants.INTEGER_PREFIX, Constants.NUMBER_SUFFIX));
break;
case NumberMode.Default:
break;
}
if (cardExtract == null)
{
cardExtract = CardinalExtractor.GetInstance(config);
}
builder.AddRange(cardExtract.Regexes);
// Add Fraction
var fracExtract = FractionExtractor.GetInstance(config);
builder.AddRange(fracExtract.Regexes);
Regexes = builder.ToImmutable();
var ambiguityBuilder = ImmutableDictionary.CreateBuilder<Regex, Regex>();
// Do not filter the ambiguous number cases like '$2000' in NumberWithUnit, otherwise they can't be resolved.
if (config.Mode != NumberMode.Unit)
{
foreach (var item in NumbersDefinitions.AmbiguityFiltersDict)
{
ambiguityBuilder.Add(new Regex(item.Key, RegexFlags), new Regex(item.Value, RegexFlags));
}
}
AmbiguityFiltersDict = ambiguityBuilder.ToImmutable();
}
internal sealed override ImmutableDictionary<Regex, TypeTag> Regexes { get; }
protected sealed override ImmutableDictionary<Regex, Regex> AmbiguityFiltersDict { get; }
protected sealed override string ExtractType { get; } = Constants.SYS_NUM; // "Number";
public static NumberExtractor GetInstance(BaseNumberOptionsConfiguration config)
{
var extractorKey = (config.Mode, config.Options);
if (!Instances.ContainsKey(extractorKey))
{
var instance = new NumberExtractor(config);
Instances.TryAdd(extractorKey, instance);
}
return Instances[extractorKey];
}
protected override object GenKey(string input)
{
return (keyPrefix, input);
}
}
} | 36.48913 | 121 | 0.613643 | [
"MIT"
] | QPC-database/Recognizers-Text | .NET/Microsoft.Recognizers.Text.Number/German/Extractors/NumberExtractor.cs | 3,359 | C# |
namespace EasyTransport.Tests.Integration.WebSocket
{
using System;
using System.Collections.Concurrent;
using System.Net;
using EasyTransport.Common.Models.Events;
using EasyTransport.WebSocket.Client;
using EasyTransport.WebSocket.Server;
using NUnit.Framework;
internal class Context
{
protected WebSocketServer Server;
protected WebSocketClient Client;
protected ConcurrentQueue<WebSocketEventBase> ServerEvents;
protected ConcurrentQueue<WebSocketEventBase> ClientEvents;
public Context()
{
ServerEvents = new ConcurrentQueue<WebSocketEventBase>();
ClientEvents = new ConcurrentQueue<WebSocketEventBase>();
}
protected void Given_a_websocket_server()
{
var endpoint = new IPEndPoint(IPAddress.Loopback, 11859);
Server = new WebSocketServer(endpoint);
Server.OnEvent += OnServerEvent;
}
protected void Given_a_websocket_client(string endpoint = "ws://localhost:11859/")
{
Client = new WebSocketClient(new Uri(endpoint), TimeSpan.FromSeconds(10));
Client.OnEvent += (sender, eArgs) => ClientEvents.Enqueue(eArgs);
}
private void OnServerEvent(object sender, WebSocketEventBase serverEvent)
{
ServerEvents.Enqueue(serverEvent);
}
[TearDown]
public void TestTearDown()
{
ClientEvents = new ConcurrentQueue<WebSocketEventBase>();
Client?.Dispose();
ServerEvents= new ConcurrentQueue<WebSocketEventBase>();
Server.OnEvent -= OnServerEvent;
Server.Dispose();
}
}
} | 31.418182 | 90 | 0.642361 | [
"MIT"
] | NimaAra/Easy.Transport_old | EasyTransport.Tests.Integration/WebSocket/Context.cs | 1,730 | C# |
using Datagrammer.Quic.Protocol.Packet;
using Xunit;
namespace Tests.Packet
{
public class PacketNumberTests
{
[Theory]
[InlineData("9b32", "a82f30ea", "a82f9b32")]
[InlineData("5c02", "abe8bc", "ac5c02")]
[InlineData("ace8fe", "abe8bc", "ace8fe")]
[InlineData("bff4", "2700bec8", "2700bff4")]
public void Decode_ByLargestAcknowledged_ResultIsExpected(string truncated, string largest, string expected)
{
//Arrange
var truncatedNumber = PacketNumber.Parse(Utils.ParseHexString(truncated));
var largestNumber = PacketNumber.Parse(Utils.ParseHexString(largest));
var expectedNumber = PacketNumber.Parse(Utils.ParseHexString(expected));
//Act
var resultNumber = truncatedNumber.DecodeByLargestAcknowledged(largestNumber);
//Assert
Assert.Equal(expectedNumber, resultNumber);
}
[Theory]
[InlineData("a82f9b32", "a82f30ea", "9b32")]
[InlineData("ac5c02", "abe8bc", "5c02")]
[InlineData("ace8fe", "abe8bc", "ace8fe")]
[InlineData("2700bff4", "2700bec8", "bff4")]
public void Encode_ByLargestAcknowledged_ResultIsExpected(string initial, string largest, string expected)
{
//Arrange
var initialNumber = PacketNumber.Parse(Utils.ParseHexString(initial));
var largestNumber = PacketNumber.Parse(Utils.ParseHexString(largest));
var expectedNumber = PacketNumber.Parse(Utils.ParseHexString(expected));
//Act
var resultNumber = initialNumber.EncodeByLargestAcknowledged(largestNumber);
//Assert
Assert.Equal(expectedNumber, resultNumber);
}
}
}
| 37.702128 | 116 | 0.637698 | [
"MIT"
] | gendalf90/Datagrammer.Quic | Datagrammer.Quic/Tests/Packet/PacketNumberTests.cs | 1,774 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EagleSpawner : MonoBehaviour {
public float gap = 20;
public float followers = 2;
public GameObject prefab;
void Awake () {
//GameObject leaderObject = Instantiate(prefab, transform.position + new Vector3(0, 0, 0), transform.rotation);
GameObject leaderObject = Instantiate(prefab, transform, false);
GameObject target = GameObject.CreatePrimitive(PrimitiveType.Sphere);
target.transform.position = leaderObject.transform.position + (leaderObject.transform.forward * 1000);
leaderObject.AddComponent<Boid>();
leaderObject.AddComponent<Seek>().targetGameObject = target;
for(int i = 1; i <= followers; i += 1)
{
//GameObject followerLeft = Instantiate(prefab, transform.position + new Vector3((i * -20), 0, (i * 20)), transform.rotation);
//GameObject followerRight = Instantiate(prefab, transform.position + new Vector3((i * 20), 0, (i * 20)), transform.rotation);
GameObject followerLeft = Instantiate(prefab, transform, false);
GameObject followerRight = Instantiate(prefab, transform, false);
followerLeft.transform.position += new Vector3((i * -gap), 0, (i * gap));
followerRight.transform.position += new Vector3((i * gap), 0, (i * gap));
followerLeft.AddComponent<Boid>();
followerRight.AddComponent<Boid>();
followerLeft.AddComponent<OffsetPursue>().leader = leaderObject.GetComponent<Boid>();
followerRight.AddComponent<OffsetPursue>().leader = leaderObject.GetComponent<Boid>();
}
}
void Update () {
}
}
| 46.648649 | 138 | 0.663384 | [
"MIT"
] | GJB93/Space1999 | Assets/Scripts/EagleSpawner.cs | 1,728 | C# |
// Copyright 2018 by JCoder58. See License.txt for license
// Auto-generated --- Do not modify.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UE4.Core;
using UE4.CoreUObject;
using UE4.CoreUObject.Native;
using UE4.InputCore;
using UE4.Native;
#pragma warning disable CS0108
using UE4.UnrealEd.Native;
namespace UE4.UnrealEd {
///<summary>DEditor Static Component Mask Parameter Value</summary>
public unsafe partial class DEditorStaticComponentMaskParameterValue : DEditorParameterValue {
///<summary>Parameter Value</summary>
public unsafe DComponentMaskParameter ParameterValue {
get {return DEditorStaticComponentMaskParameterValue_ptr->ParameterValue;}
set {DEditorStaticComponentMaskParameterValue_ptr->ParameterValue = value;}
}
static DEditorStaticComponentMaskParameterValue() {
StaticClass = Main.GetClass("DEditorStaticComponentMaskParameterValue");
}
internal unsafe DEditorStaticComponentMaskParameterValue_fields* DEditorStaticComponentMaskParameterValue_ptr => (DEditorStaticComponentMaskParameterValue_fields*) ObjPointer.ToPointer();
///<summary>Convert from IntPtr to UObject</summary>
public static implicit operator DEditorStaticComponentMaskParameterValue(IntPtr p) => UObject.Make<DEditorStaticComponentMaskParameterValue>(p);
///<summary>Get UE4 Class</summary>
public static Class StaticClass {get; private set;}
///<summary>Get UE4 Default Object for this Class</summary>
public static DEditorStaticComponentMaskParameterValue DefaultObject => Main.GetDefaultObject(StaticClass);
///<summary>Spawn an object of this class</summary>
public static DEditorStaticComponentMaskParameterValue New(UObject obj = null, Name name = new Name()) => Main.NewObject(StaticClass, obj, name);
}
}
| 50.473684 | 195 | 0.758081 | [
"MIT"
] | UE4DotNet/Plugin | DotNet/DotNet/UE4/Generated/UnrealEd/DEditorStaticComponentMaskParameterValue.cs | 1,918 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Carlos.Domain;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
namespace Carlos.Configuration
{
public static class IdentityConfiguration
{
public static IApplicationBuilder UseApplicationIdentity(this IApplicationBuilder builder,
IServiceProvider serviceProvider)
{
using (var scope = serviceProvider.CreateScope())
{
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<User>>();
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<Role>>();
SeedRoles(roleManager).Wait();
SeedUsers(userManager).Wait();
SeedUserRoles(userManager).Wait();
}
return builder;
}
private static IEnumerable<Role> Roles()
{
return new List<Role> {
new Role {Id = "role_admin", Name = "ROLE_ADMIN"},
new Role {Id = "role_user",Name = "ROLE_USER"}
};
}
private static IEnumerable<User> Users()
{
return new List<User> {
new User {
Id = "user-0",
UserName = "system",
PasswordHash = "$2a$10$mE.qmcV0mFU5NcKh73TZx.z4ueI/.bDWbj0T1BYyqP481kGGarKLG",
FirstName = "",
LastName = "System",
Email = "system@localhost",
Activated = true,
LangKey = "en"
},
new User {
Id = "user-1",
UserName = "anonymoususer",
PasswordHash = "$2a$10$j8S5d7Sr7.8VTOYNviDPOeWX8KcYILUVJBsYV83Y5NtECayypx9lO",
FirstName = "Anonymous",
LastName = "User",
Email = "anonymous@localhost",
Activated = true,
LangKey = "en"
},
new User {
Id = "user-2",
UserName = "admin",
PasswordHash = "$2a$10$gSAhZrxMllrbgj/kkK9UceBPpChGWJA7SYIb1Mqo.n5aNLq1/oRrC",
FirstName = "admin",
LastName = "Administrator",
Email = "admin@localhost",
Activated = true,
LangKey = "en"
},
new User {
Id = "user-3",
UserName = "user",
PasswordHash = "$2a$10$VEjxo0jq2YG9Rbk2HmX9S.k1uZBGYUHdUcid3g/vfiEl7lwWgOH/K",
FirstName = "",
LastName = "User",
Email = "user@localhost",
Activated = true,
LangKey = "en"
}
};
}
private static IDictionary<string, string[]> UserRoles()
{
return new Dictionary<string, string[]> {
{"user-0", new[] {"ROLE_ADMIN", "ROLE_USER"}},
{"user-2", new[] {"ROLE_ADMIN", "ROLE_USER"}},
{"user-3", new[] {"ROLE_USER"}}
};
}
private static async Task SeedRoles(RoleManager<Role> roleManager)
{
foreach (var role in Roles())
{
var dbRole = await roleManager.FindByNameAsync(role.Name);
if (dbRole == null)
{
await roleManager.CreateAsync(role);
}
else
{
await roleManager.UpdateAsync(dbRole);
}
}
}
private static async Task SeedUsers(UserManager<User> userManager)
{
foreach (var user in Users())
{
var dbUser = await userManager.FindByIdAsync(user.Id);
if (dbUser == null)
{
await userManager.CreateAsync(user);
}
else
{
await userManager.UpdateAsync(dbUser);
}
}
}
private static async Task SeedUserRoles(UserManager<User> userManager)
{
foreach (var (id, roles) in UserRoles())
{
var user = await userManager.FindByIdAsync(id);
await userManager.AddToRolesAsync(user, roles);
}
}
}
}
| 34.17037 | 98 | 0.471277 | [
"Apache-2.0"
] | carloseduardofernandes/JhipsterCadastroDotNet | src/Cadastro/Configuration/IdentityStartup.cs | 4,613 | 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("04-CompareTextFiles")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("04-CompareTextFiles")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("cc1b32f1-e458-4860-89df-d37c9f6d56cb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.135135 | 84 | 0.746279 | [
"MIT"
] | mpenchev86/Telerik-Academy | CSharp-Part2/Text-Files-Homework/04-CompareTextFiles/Properties/AssemblyInfo.cs | 1,414 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Gcp.Compute.Inputs
{
public sealed class RegionUrlMapPathMatcherRouteRuleRouteActionUrlRewriteGetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Prior to forwarding the request to the selected service, the request's host
/// header is replaced with contents of hostRewrite. The value must be between 1 and
/// 255 characters.
/// </summary>
[Input("hostRewrite")]
public Input<string>? HostRewrite { get; set; }
/// <summary>
/// Prior to forwarding the request to the selected backend service, the matching
/// portion of the request's path is replaced by pathPrefixRewrite. The value must
/// be between 1 and 1024 characters.
/// </summary>
[Input("pathPrefixRewrite")]
public Input<string>? PathPrefixRewrite { get; set; }
public RegionUrlMapPathMatcherRouteRuleRouteActionUrlRewriteGetArgs()
{
}
}
}
| 35.75 | 106 | 0.67366 | [
"ECL-2.0",
"Apache-2.0"
] | dimpu47/pulumi-gcp | sdk/dotnet/Compute/Inputs/RegionUrlMapPathMatcherRouteRuleRouteActionUrlRewriteGetArgs.cs | 1,287 | 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.V20210101.Outputs
{
/// <summary>
/// Message envelope that contains the common Azure resource manager properties and the resource provider specific content.
/// </summary>
[OutputType]
public sealed class ResponseMessageEnvelopeRemotePrivateEndpointConnectionResponse
{
/// <summary>
/// Azure-AsyncOperation Error info.
/// </summary>
public readonly Outputs.ErrorEntityResponse? Error;
/// <summary>
/// Resource Id. Typically ID is populated only for responses to GET requests. Caller is responsible for passing in this
/// value for GET requests only.
/// For example: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupId}/providers/Microsoft.Web/sites/{sitename}
/// </summary>
public readonly string? Id;
/// <summary>
/// MSI resource
/// </summary>
public readonly Outputs.ManagedServiceIdentityResponse? Identity;
/// <summary>
/// Geographical region resource belongs to e.g. SouthCentralUS, SouthEastAsia.
/// </summary>
public readonly string? Location;
/// <summary>
/// Name of resource.
/// </summary>
public readonly string? Name;
/// <summary>
/// Azure resource manager plan.
/// </summary>
public readonly Outputs.ArmPlanResponse? Plan;
/// <summary>
/// Resource specific properties.
/// </summary>
public readonly Outputs.RemotePrivateEndpointConnectionResponse? Properties;
/// <summary>
/// SKU description of the resource.
/// </summary>
public readonly Outputs.SkuDescriptionResponse? Sku;
/// <summary>
/// Azure-AsyncOperation Status info.
/// </summary>
public readonly string? Status;
/// <summary>
/// Tags associated with resource.
/// </summary>
public readonly ImmutableDictionary<string, string>? Tags;
/// <summary>
/// Type of resource e.g "Microsoft.Web/sites".
/// </summary>
public readonly string? Type;
/// <summary>
/// Logical Availability Zones the service is hosted in
/// </summary>
public readonly ImmutableArray<string> Zones;
[OutputConstructor]
private ResponseMessageEnvelopeRemotePrivateEndpointConnectionResponse(
Outputs.ErrorEntityResponse? error,
string? id,
Outputs.ManagedServiceIdentityResponse? identity,
string? location,
string? name,
Outputs.ArmPlanResponse? plan,
Outputs.RemotePrivateEndpointConnectionResponse? properties,
Outputs.SkuDescriptionResponse? sku,
string? status,
ImmutableDictionary<string, string>? tags,
string? type,
ImmutableArray<string> zones)
{
Error = error;
Id = id;
Identity = identity;
Location = location;
Name = name;
Plan = plan;
Properties = properties;
Sku = sku;
Status = status;
Tags = tags;
Type = type;
Zones = zones;
}
}
}
| 32.684685 | 130 | 0.600055 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Web/V20210101/Outputs/ResponseMessageEnvelopeRemotePrivateEndpointConnectionResponse.cs | 3,628 | C# |
#pragma checksum "C:\Users\Jonathan\csharp\ASP.NET-Core-Fundamentals\OdeToFood\OdeToFood\Pages\Shared\_Layout.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "fcad9ad50433a280371e0a942b72b56323143675"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(OdeToFood.Pages.Shared.Pages_Shared__Layout), @"mvc.1.0.view", @"/Pages/Shared/_Layout.cshtml")]
[assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Pages/Shared/_Layout.cshtml", typeof(OdeToFood.Pages.Shared.Pages_Shared__Layout))]
namespace OdeToFood.Pages.Shared
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#line 1 "C:\Users\Jonathan\csharp\ASP.NET-Core-Fundamentals\OdeToFood\OdeToFood\Pages\_ViewImports.cshtml"
using OdeToFood;
#line default
#line hidden
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"fcad9ad50433a280371e0a942b72b56323143675", @"/Pages/Shared/_Layout.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"0820fb6dbe507f6ce740cdfd07cdc5236e4275df", @"/Pages/_ViewImports.cshtml")]
public class Pages_Shared__Layout : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("rel", new global::Microsoft.AspNetCore.Html.HtmlString("stylesheet"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/bootstrap/dist/css/bootstrap.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/css/site.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("include", "Development", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", "https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-href", "~/lib/bootstrap/dist/css/bootstrap.min.css", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-test-class", "sr-only", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-test-property", "position", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-test-value", "absolute", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_9 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", "~/css/site.min.css", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_10 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("exclude", "Development", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_11 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "/Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_12 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("navbar-brand"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_13 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "/Restaurants/List", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_14 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "/About", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_15 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "/Contact", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_16 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("name", "_CookieConsentPartial", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_17 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/jquery/dist/jquery.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_18 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/bootstrap/dist/js/bootstrap.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_19 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "~/js/site.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_20 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_21 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-src", "~/lib/jquery/dist/jquery.min.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_22 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-test", "window.jQuery", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_23 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("crossorigin", new global::Microsoft.AspNetCore.Html.HtmlString("anonymous"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_24 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("integrity", new global::Microsoft.AspNetCore.Html.HtmlString("sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_25 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_26 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-src", "~/lib/bootstrap/dist/js/bootstrap.min.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_27 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-test", "window.jQuery && window.jQuery.fn && window.jQuery.fn.modal", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_28 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("integrity", new global::Microsoft.AspNetCore.Html.HtmlString("sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_29 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "~/js/site.min.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.EnvironmentTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper;
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.LinkTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper;
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
BeginContext(0, 25, true);
WriteLiteral("<!DOCTYPE html>\r\n<html>\r\n");
EndContext();
BeginContext(25, 838, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("head", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "b67aa3e42e934fd2a52d2e2d37efc14b", async() => {
BeginContext(31, 121, true);
WriteLiteral("\r\n <meta charset=\"utf-8\" />\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\r\n <title>");
EndContext();
BeginContext(153, 17, false);
#line 6 "C:\Users\Jonathan\csharp\ASP.NET-Core-Fundamentals\OdeToFood\OdeToFood\Pages\Shared\_Layout.cshtml"
Write(ViewData["Title"]);
#line default
#line hidden
EndContext();
BeginContext(170, 28, true);
WriteLiteral(" - OdeToFood</title>\r\n\r\n ");
EndContext();
BeginContext(198, 193, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("environment", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "3a20713db69c4e3398605a502995b326", async() => {
BeginContext(233, 10, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(243, 71, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "deb60e1d5d9045b7ae789d4068778c0f", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(314, 10, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(324, 47, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "b8b5fc2bcfb84d3d859d004dd660537b", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(371, 6, true);
WriteLiteral("\r\n ");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.EnvironmentTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper.Include = (string)__tagHelperAttribute_3.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(391, 6, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(397, 457, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("environment", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "af0c17ff20024bb6810fe91d3bfa07c0", async() => {
BeginContext(432, 10, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(442, 305, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "92102a2ecec2476592a35105b7951a1d", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LinkTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper.Href = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper.FallbackHref = (string)__tagHelperAttribute_5.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5);
__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper.FallbackTestClass = (string)__tagHelperAttribute_6.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6);
__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper.FallbackTestProperty = (string)__tagHelperAttribute_7.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_7);
__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper.FallbackTestValue = (string)__tagHelperAttribute_8.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_8);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(747, 10, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(757, 77, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "6c95db8f91424e6e9d78868d93346592", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LinkTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper.Href = (string)__tagHelperAttribute_9.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_9);
#line 16 "C:\Users\Jonathan\csharp\ASP.NET-Core-Fundamentals\OdeToFood\OdeToFood\Pages\Shared\_Layout.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper.AppendVersion = true;
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-append-version", __Microsoft_AspNetCore_Mvc_TagHelpers_LinkTagHelper.AppendVersion, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(834, 6, true);
WriteLiteral("\r\n ");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.EnvironmentTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper.Exclude = (string)__tagHelperAttribute_10.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_10);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(854, 2, true);
WriteLiteral("\r\n");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(863, 2, true);
WriteLiteral("\r\n");
EndContext();
BeginContext(865, 2509, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("body", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "7a23146e2067445a894b44b203aa2af9", async() => {
BeginContext(871, 517, true);
WriteLiteral(@"
<nav class=""navbar navbar-inverse navbar-fixed-top"">
<div class=""container"">
<div class=""navbar-header"">
<button type=""button"" class=""navbar-toggle"" data-toggle=""collapse"" data-target="".navbar-collapse"">
<span class=""sr-only"">Toggle navigation</span>
<span class=""icon-bar""></span>
<span class=""icon-bar""></span>
<span class=""icon-bar""></span>
</button>
");
EndContext();
BeginContext(1388, 55, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "697182950ee0444a901fcdb5cbf2d2a7", async() => {
BeginContext(1430, 9, true);
WriteLiteral("OdeToFood");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_11.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_11);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_12);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1443, 143, true);
WriteLiteral("\r\n </div>\r\n <div class=\"navbar-collapse collapse\">\r\n <ul class=\"nav navbar-nav\">\r\n <li>");
EndContext();
BeginContext(1586, 29, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "72fcae8473a442b392a997a29457964e", async() => {
BeginContext(1607, 4, true);
WriteLiteral("Home");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_11.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_11);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1615, 31, true);
WriteLiteral("</li>\r\n <li>");
EndContext();
BeginContext(1646, 47, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "dd9e050c350648f08996272d7a013a9a", async() => {
BeginContext(1678, 11, true);
WriteLiteral("Restaurants");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_13.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_13);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1693, 31, true);
WriteLiteral("</li>\r\n <li>");
EndContext();
BeginContext(1724, 30, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "fbe33660e9ab4b8d8276d79438f3ccc7", async() => {
BeginContext(1745, 5, true);
WriteLiteral("About");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_14.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_14);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1754, 31, true);
WriteLiteral("</li>\r\n <li>");
EndContext();
BeginContext(1785, 34, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "31f95035aa78452fa247af8aa253ee49", async() => {
BeginContext(1808, 7, true);
WriteLiteral("Contact");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_15.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_15);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1819, 84, true);
WriteLiteral("</li>\r\n </ul>\r\n </div>\r\n </div>\r\n </nav>\r\n\r\n ");
EndContext();
BeginContext(1903, 40, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("partial", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "fe776ee5a02d4c548c31da099bf6f384", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper.Name = (string)__tagHelperAttribute_16.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_16);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1943, 54, true);
WriteLiteral("\r\n\r\n <div class=\"container body-content\">\r\n ");
EndContext();
BeginContext(1998, 12, false);
#line 45 "C:\Users\Jonathan\csharp\ASP.NET-Core-Fundamentals\OdeToFood\OdeToFood\Pages\Shared\_Layout.cshtml"
Write(RenderBody());
#line default
#line hidden
EndContext();
BeginContext(2010, 117, true);
WriteLiteral("\r\n <hr />\r\n <footer>\r\n <p>© 2019 - OdeToFood</p>\r\n </footer>\r\n </div>\r\n\r\n ");
EndContext();
BeginContext(2127, 258, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("environment", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "439fd9776ca944f89d986b6156860a95", async() => {
BeginContext(2162, 10, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(2172, 51, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "f6bed921696949b4a37fc0ba722bfc35", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_17);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(2223, 10, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(2233, 60, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ec5b8f15127a48f08334831a3e76d914", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_18);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(2293, 10, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(2303, 62, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "cee3ad86f68f40b796bdb2f3e05bd543", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_19.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_19);
#line 55 "C:\Users\Jonathan\csharp\ASP.NET-Core-Fundamentals\OdeToFood\OdeToFood\Pages\Shared\_Layout.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion = true;
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-append-version", __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(2365, 6, true);
WriteLiteral("\r\n ");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.EnvironmentTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper.Include = (string)__tagHelperAttribute_3.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(2385, 6, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(2391, 924, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("environment", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ccb653652de64907847b741505fbb1b9", async() => {
BeginContext(2426, 10, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(2436, 353, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4e9441b57b574f39b6e904badf28b750", async() => {
BeginContext(2770, 10, true);
WriteLiteral("\r\n ");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_20.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_20);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.FallbackSrc = (string)__tagHelperAttribute_21.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_21);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.FallbackTestExpression = (string)__tagHelperAttribute_22.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_22);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_23);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_24);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(2789, 10, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(2799, 420, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "02b13249504f44d89a40d4c8b6576bc1", async() => {
BeginContext(3200, 10, true);
WriteLiteral("\r\n ");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_25.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_25);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.FallbackSrc = (string)__tagHelperAttribute_26.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_26);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.FallbackTestExpression = (string)__tagHelperAttribute_27.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_27);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_23);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_28);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(3219, 10, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(3229, 66, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ad4f5e886559456a8b7d35bf24221219", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_29.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_29);
#line 70 "C:\Users\Jonathan\csharp\ASP.NET-Core-Fundamentals\OdeToFood\OdeToFood\Pages\Shared\_Layout.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion = true;
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-append-version", __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(3295, 6, true);
WriteLiteral("\r\n ");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.EnvironmentTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper.Exclude = (string)__tagHelperAttribute_10.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_10);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(3315, 8, true);
WriteLiteral("\r\n\r\n ");
EndContext();
BeginContext(3324, 41, false);
#line 73 "C:\Users\Jonathan\csharp\ASP.NET-Core-Fundamentals\OdeToFood\OdeToFood\Pages\Shared\_Layout.cshtml"
Write(RenderSection("Scripts", required: false));
#line default
#line hidden
EndContext();
BeginContext(3365, 2, true);
WriteLiteral("\r\n");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(3374, 11, true);
WriteLiteral("\r\n</html>\r\n");
EndContext();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 83.214063 | 415 | 0.681582 | [
"MIT"
] | codejoncode/ASP.NET-Core-Fundamentals | OdeToFood/OdeToFood/obj/Debug/netcoreapp2.1/Razor/Pages/Shared/_Layout.g.cshtml.cs | 53,257 | C# |
using System;
using System.Web;
namespace Ecommerce.Entity
{
public class ShippingCompanyModel
{
public long ShippingCompanyId { get; set; }
public string Title { get; set; }
public string CompanyWebAddrress { get; set; }
public string TrackingUrl { get; set; }
public bool RequiresShippingCode { get; set; }
public HttpPostedFileBase ShippingStampImage { get; set; }
public decimal W1000 { get; set; }
public decimal W1250 { get; set; }
public decimal W1500 { get; set; }
public decimal W1750 { get; set; }
public decimal W2000 { get; set; }
public decimal W5000 { get; set; }
public decimal W30000 { get; set; }
}
public class ShippingPackageModel
{
public long Id { get; set; }
public string Title { get; set; }
public long ShippingCompanyId { get; set; }
public PackageType PackageType { get; set; }
public string Details { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime UpdatedOn { get; set; }
public decimal Price { get; set; }
public decimal AdditionalPrice { get; set; }
public decimal RestrictedPostagePrice { get; set; }
public decimal AdditionalRestrictedPostagePrice { get; set; }
public decimal PerPalletPrice { get; set; }
public decimal AdditionalPalletPrice { get; set; }
public int WeightFrom { get; set; }
public int WeightTo { get; set; }
public string DeliveryTime { get; set; }
public string ShippingCompany { get; set; }
public string CompanyTitle { get; set; }
public PriorityLevel PriorityLevel { get; set; }
}
public class PostcodeModel
{
public long Id { get; set; }
public string Postcode { get; set; }
public PostcodeRestrictedLevel RestrictionLevels { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime UpdatedOn { get; set; }
public decimal FirstItemPrice { get; set; }
public decimal EachAdditionalItemPrice { get; set; }
public string StrRestrictionLevels { get; set; }
}
public enum PriorityLevel
{
Economy = 1, Standard = 2, Express = 3
}
public enum PackageType
{
Letter = 1, LargeEnvelope = 2, Package = 3, LargePackage = 4, StockPile = 5
}
public enum PostcodeRestrictedLevel
{
NoPostage = 1, HighPostage = 2
}
}
| 35.828571 | 83 | 0.616029 | [
"MIT"
] | sherikhanx/SOSERP | Ecommerce/Entity/ShippingManagement.cs | 2,510 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LinePathManager : MonoBehaviour {
public List<GameObject> zone3Objects;
public Color c1 = Color.yellow;
public Color c2 = Color.red;
public int lengthOfLineRenderer = 10;
void Start () {
//visitingOrder = new int[] { 0, 3, 2, 1, 4, 5, 8, 7, 9, 10};
}
// Update is called once per frame
void Update () {
}
public void drawLines()
{
LineRenderer lr = this.gameObject.AddComponent<LineRenderer>();
lr.material = new Material(Shader.Find("Sprites/Default"));
lr.widthMultiplier = 0.2f;
lr.positionCount = zone3Objects.Count;
// A simple 2 color gradient with a fixed alpha of 1.0f.
float alpha = 1.0f;
Gradient gradient = new Gradient();
gradient.SetKeys(
new GradientColorKey[] { new GradientColorKey(c1, 0.0f), new GradientColorKey(c2, 1.0f) },
new GradientAlphaKey[] { new GradientAlphaKey(alpha, 0.0f), new GradientAlphaKey(alpha, 1.0f) }
);
lr.colorGradient = gradient;
int i = 0;
foreach (GameObject go in zone3Objects)
{
Debug.Log("LINE DRAWING: " + i);
lr.SetPosition(i, go.transform.position);
i++;
}
}
public void visitAsset(GameObject go)
{
zone3Objects.Add(go);
}
}
| 25.357143 | 107 | 0.603521 | [
"MIT"
] | fwild/PoetryEscapeRoom | Assets/_scripts/LinePathManager.cs | 1,422 | C# |
// The MIT License (MIT)
//
// Copyright (c) 2015-2016 Rasmus Mikkelsen
// Copyright (c) 2015-2016 eBay Software Foundation
// https://github.com/rasmus/EventFlow
//
// 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.
//
namespace EventFlow.Core
{
public interface IIdentity
{
string Value { get; }
}
}
| 43.419355 | 83 | 0.745914 | [
"MIT"
] | AntoineGa/EventFlow | Source/EventFlow/Core/IIdentity.cs | 1,348 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Synapse
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// LibraryOperations operations.
/// </summary>
internal partial class LibraryOperations : IServiceOperations<SynapseManagementClient>, ILibraryOperations
{
/// <summary>
/// Initializes a new instance of the LibraryOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal LibraryOperations(SynapseManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SynapseManagementClient
/// </summary>
public SynapseManagementClient Client { get; private set; }
/// <summary>
/// Get library by name.
/// </summary>
/// <remarks>
/// Get library by name in a workspace.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='libraryName'>
/// Library name
/// </param>
/// <param name='workspaceName'>
/// The name of the workspace
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<LibraryResource>> GetWithHttpMessagesAsync(string resourceGroupName, string libraryName, string workspaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ApiVersion != null)
{
if (Client.ApiVersion.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "Client.ApiVersion", 1);
}
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (Client.SubscriptionId != null)
{
if (Client.SubscriptionId.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "Client.SubscriptionId", 1);
}
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (libraryName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "libraryName");
}
if (workspaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "workspaceName");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("libraryName", libraryName);
tracingParameters.Add("workspaceName", workspaceName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Synapse/workspaces/{workspaceName}/libraries/{libraryName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{libraryName}", System.Uri.EscapeDataString(libraryName));
_url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(workspaceName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<LibraryResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LibraryResource>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 42.780919 | 280 | 0.564219 | [
"MIT"
] | EitanGayor/azure-sdk-for-net | sdk/synapse/Microsoft.Azure.Management.Synapse/src/Generated/LibraryOperations.cs | 12,107 | C# |
//using System;
//using System.ComponentModel;//needed to overide OnClosing
////I removed useless usings
//using System.Windows.Forms;
//using SharpDX.Direct3D11;
//using SharpDX.DXGI;
//using SharpDX;
//namespace WindowsFormsApplication2
//{
// using Device = SharpDX.Direct3D11.Device;
// using Buffer = SharpDX.Direct3D11.Buffer;
// public partial class Form1 : Form
// {
// Device d;
// SwapChain sc;
// Texture2D target;
// RenderTargetView targetveiw;
// public Form1()
// {
// InitializeComponent();
// SwapChainDescription scd = new SwapChainDescription()
// {
// BufferCount = 1, //how many buffers are used for writing. it's recommended to have at least 2 buffers but this is an example
// Flags = SwapChainFlags.None,
// IsWindowed = true, //it's windowed
// ModeDescription = new ModeDescription(
// this.ClientSize.Width, //windows veiwable width
// this.ClientSize.Height, //windows veiwable height
// new Rational(60, 1), //refresh rate
// Format.R8G8B8A8_UNorm), //pixel format, you should resreach this for your specific implementation
// OutputHandle = this.Handle, //the magic
// SampleDescription = new SampleDescription(1, 0), //the first number is how many samples to take, anything above one is multisampling.
// SwapEffect = SwapEffect.Discard,
// Usage = Usage.RenderTargetOutput
// };
// Device.CreateWithSwapChain(
// SharpDX.Direct3D.DriverType.Hardware,//hardware if you have a graphics card otherwise you can use software
// DeviceCreationFlags.Debug, //helps debuging don't use this for release verion
// scd, //the swapchain description made above
// out d, out sc //our directx objects
// );
// target = Texture2D.FromSwapChain<Texture2D>(sc, 0);
// targetveiw = new RenderTargetView(d, target);
// d.ImmediateContext.OutputMerger.SetRenderTargets(targetveiw);
// }
// protected override void OnClosing(CancelEventArgs e)
// {
// //dipose of all objects
// d.Dispose();
// sc.Dispose();
// target.Dispose();
// targetveiw.Dispose();
// base.OnClosing(e);
// }
// protected override void OnPaint(PaintEventArgs e)
// {
// //I am rendering here for this example
// //normally I use a seperate thread to call Draw() and Present() in a loop
// d.ImmediateContext.ClearRenderTargetView(targetveiw, Color.CornflowerBlue);//Color to make it look like default XNA project output.
// sc.Present(0, PresentFlags.None);
// base.OnPaint(e);
// }
// }
//} | 39.231707 | 174 | 0.541498 | [
"MIT"
] | lukix29/LixChat | LixChat/Code/Extensions/DeviceContext.cs | 3,219 | 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("AWSSDK.CostAndUsageReport")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Cost and Usage Report Service. The AWS Cost and Usage Report Service API allows you to enable and disable the Cost and Usage report, as well as modify the report name, the data granularity, and the delivery preferences.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.5.1.7")] | 49.1875 | 303 | 0.752859 | [
"Apache-2.0"
] | joshongithub/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/CostAndUsageReport/Properties/AssemblyInfo.cs | 1,574 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class User32
{
[DllImport(Libraries.User32, ExactSpelling = true)]
public static extern BOOL IsZoomed(IntPtr hWnd);
}
}
| 29.375 | 71 | 0.73617 | [
"MIT"
] | AArnott/winforms | src/System.Windows.Forms.Primitives/src/Interop/User32/Interop.IsZoomed.cs | 472 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210
{
using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions;
/// <summary>Onprem disk details data.</summary>
public partial class DiskDetails :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IDiskDetails,
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IDiskDetailsInternal
{
/// <summary>Backing field for <see cref="MaxSizeMb" /> property.</summary>
private long? _maxSizeMb;
/// <summary>The hard disk max size in MB.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public long? MaxSizeMb { get => this._maxSizeMb; set => this._maxSizeMb = value; }
/// <summary>Backing field for <see cref="VhdId" /> property.</summary>
private string _vhdId;
/// <summary>The VHD Id.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string VhdId { get => this._vhdId; set => this._vhdId = value; }
/// <summary>Backing field for <see cref="VhdName" /> property.</summary>
private string _vhdName;
/// <summary>The VHD name.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string VhdName { get => this._vhdName; set => this._vhdName = value; }
/// <summary>Backing field for <see cref="VhdType" /> property.</summary>
private string _vhdType;
/// <summary>The type of the volume.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string VhdType { get => this._vhdType; set => this._vhdType = value; }
/// <summary>Creates an new <see cref="DiskDetails" /> instance.</summary>
public DiskDetails()
{
}
}
/// Onprem disk details data.
public partial interface IDiskDetails :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IJsonSerializable
{
/// <summary>The hard disk max size in MB.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The hard disk max size in MB.",
SerializedName = @"maxSizeMB",
PossibleTypes = new [] { typeof(long) })]
long? MaxSizeMb { get; set; }
/// <summary>The VHD Id.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The VHD Id.",
SerializedName = @"vhdId",
PossibleTypes = new [] { typeof(string) })]
string VhdId { get; set; }
/// <summary>The VHD name.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The VHD name.",
SerializedName = @"vhdName",
PossibleTypes = new [] { typeof(string) })]
string VhdName { get; set; }
/// <summary>The type of the volume.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The type of the volume.",
SerializedName = @"vhdType",
PossibleTypes = new [] { typeof(string) })]
string VhdType { get; set; }
}
/// Onprem disk details data.
internal partial interface IDiskDetailsInternal
{
/// <summary>The hard disk max size in MB.</summary>
long? MaxSizeMb { get; set; }
/// <summary>The VHD Id.</summary>
string VhdId { get; set; }
/// <summary>The VHD name.</summary>
string VhdName { get; set; }
/// <summary>The type of the volume.</summary>
string VhdType { get; set; }
}
} | 42.876289 | 125 | 0.61962 | [
"MIT"
] | AverageDesigner/azure-powershell | src/Migrate/generated/api/Models/Api20210210/DiskDetails.cs | 4,063 | C# |
///-----------------------------------------------------------------
/// File: IMainBaseModel.cs
/// Author: Andre Laskawy
/// Date: 30.09.2018 14:34:27
///-----------------------------------------------------------------
namespace Nanomite.Common.Models.Base
{
using Google.Protobuf;
using System;
/// <summary>
/// Defines the <see cref="IMainBaseModel"/>
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IMainBaseModel<T> : IMainBaseModel, IBaseModel<T> where T : IMessage
{
}
/// <summary>
/// Defines the <see cref="IMainBaseModel" />
/// </summary>
public interface IMainBaseModel : IBaseModel
{
/// <summary>
/// Gets or sets the creation date and time.
/// </summary>
DateTime CreatedDT { get; set; }
/// <summary>
/// Gets or sets the last modified date and time.
/// </summary>
DateTime ModifiedDT { get; set; }
}
}
| 28.833333 | 89 | 0.465318 | [
"MIT"
] | andre-laskawy/nanomite-common | src/Nanomite.Common/Models/Base/Interfaces/IMainBaseModel.cs | 1,040 | 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("AWSSDK.NetworkManager")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Network Manager. This is the initial SDK release for AWS Network Manager.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.5.0.8")] | 44.5 | 157 | 0.747191 | [
"Apache-2.0"
] | orinem/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/NetworkManager/Properties/AssemblyInfo.cs | 1,424 | C# |
using System;
using System.Xml;
using System.Collections.Generic;
using System.Windows.Media;
using SharpVectors.Dom;
using SharpVectors.Dom.Svg;
using SharpVectors.Runtime;
using SharpVectors.Renderers.Wpf;
namespace SharpVectors.Converters
{
public sealed class LinkVisitor : WpfLinkVisitor
{
#region Private Fields
private bool _isAggregated;
private GeometryCollection _aggregatedGeom;
private SvgStyleableElement _aggregatedFill;
private Dictionary<string, bool> _dicLinks;
#endregion
#region Constructors and Destructor
public LinkVisitor()
{
_dicLinks = new Dictionary<string, bool>();
}
#endregion
#region Public Properties
public override bool Aggregates
{
get {
return true;
}
}
public override bool IsAggregate
{
get {
return _isAggregated;
}
}
public override string AggregatedLayerName
{
get {
return SvgObject.LinksLayer;
}
}
#endregion
#region Public Methods
public override bool Exists(string linkId)
{
if (string.IsNullOrWhiteSpace(linkId))
{
return false;
}
if (_dicLinks != null && _dicLinks.Count != 0)
{
return _dicLinks.ContainsKey(linkId);
}
return false;
}
public override void Initialize(DrawingGroup linkGroup, WpfDrawingContext context)
{
if (linkGroup != null)
{
SvgLink.SetKey(linkGroup, SvgObject.LinksLayer);
}
}
public override void Visit(DrawingGroup group, SvgAElement element, WpfDrawingContext context, float opacity)
{
_isAggregated = false;
if (group == null || element == null || context == null)
{
return;
}
AddExtraLinkInformation(group, element);
//string linkId = element.GetAttribute("id");
string linkId = GetElementName(element);
if (string.IsNullOrWhiteSpace(linkId))
{
return;
}
SvgLink.SetKey(group, linkId);
if (_dicLinks.ContainsKey(linkId))
{
_isAggregated = _dicLinks[linkId];
return;
}
string linkAction = element.GetAttribute("onclick");
if (string.IsNullOrWhiteSpace(linkAction))
{
linkAction = element.GetAttribute("onmouseover");
if (!string.IsNullOrWhiteSpace(linkAction) &&
linkAction.StartsWith("parent.svgMouseOverName", StringComparison.OrdinalIgnoreCase))
{
SvgLink.SetAction(group, SvgLinkAction.LinkTooltip);
}
else
{
SvgLink.SetAction(group, SvgLinkAction.LinkNone);
}
}
else
{
if (linkAction.StartsWith("parent.svgClick", StringComparison.OrdinalIgnoreCase))
{
SvgLink.SetAction(group, SvgLinkAction.LinkPage);
}
else if (linkAction.StartsWith("parent.svgOpenHtml", StringComparison.OrdinalIgnoreCase))
{
SvgLink.SetAction(group, SvgLinkAction.LinkHtml);
}
else
{
SvgLink.SetAction(group, SvgLinkAction.LinkNone);
}
}
if (!string.IsNullOrWhiteSpace(linkAction))
{
if (linkAction.IndexOf("'Top'", StringComparison.OrdinalIgnoreCase) > 0)
{
SvgLink.SetLocation(group, "Top");
}
else if (linkAction.IndexOf("'Bottom'", StringComparison.OrdinalIgnoreCase) > 0)
{
SvgLink.SetLocation(group, "Bottom");
}
else
{
SvgLink.SetLocation(group, "Top");
}
}
this.AggregateChildren(element, context, opacity);
if (_isAggregated)
{
Geometry drawGeometry = null;
if (_aggregatedGeom.Count == 1)
{
drawGeometry = _aggregatedGeom[0];
}
else
{
GeometryGroup geomGroup = new GeometryGroup();
geomGroup.FillRule = FillRule.Nonzero;
for (int i = 0; i < _aggregatedGeom.Count; i++)
{
geomGroup.Children.Add(_aggregatedGeom[i]);
}
drawGeometry = geomGroup;
}
WpfSvgPaint fillPaint = new WpfSvgPaint(context, _aggregatedFill, "fill");
Brush brush = fillPaint.GetBrush(false);
SvgObject.SetName(brush, linkId + "_Brush");
GeometryDrawing drawing = new GeometryDrawing(brush, null, drawGeometry);
group.Children.Add(drawing);
}
_dicLinks.Add(linkId, _isAggregated);
}
public static string GetElementName(SvgElement element)
{
if (element == null)
{
return string.Empty;
}
string elementId = element.Id;
if (elementId != null)
{
elementId = elementId.Trim();
}
if (string.IsNullOrWhiteSpace(elementId))
{
return string.Empty;
}
elementId = elementId.Replace(':', '_');
elementId = elementId.Replace(" ", string.Empty);
elementId = elementId.Replace('.', '_');
elementId = elementId.Replace('-', '_');
return elementId;
}
#endregion
#region Private Methods
private void AddExtraLinkInformation(DrawingGroup group, SvgElement element)
{
string linkColor = element.GetAttribute(CssConstants.PropColor);
if (!string.IsNullOrWhiteSpace(linkColor))
{
SvgLink.SetColor(group, linkColor);
}
string linkPartsId = element.GetAttribute("partsid");
if (!string.IsNullOrWhiteSpace(linkPartsId))
{
SvgLink.SetPartsId(group, linkPartsId);
}
string linkType = element.GetAttribute("type");
if (!string.IsNullOrWhiteSpace(linkType))
{
SvgLink.SetPartsId(group, linkType);
}
string linkNumber = element.GetAttribute("num");
if (!string.IsNullOrWhiteSpace(linkNumber))
{
SvgLink.SetPartsId(group, linkNumber);
}
string linkPin = element.GetAttribute("pin");
if (!string.IsNullOrWhiteSpace(linkPin))
{
SvgLink.SetPartsId(group, linkPin);
}
string linkLineId = element.GetAttribute("lineid");
if (!string.IsNullOrWhiteSpace(linkLineId))
{
SvgLink.SetPartsId(group, linkLineId);
}
}
private void AggregateChildren(SvgAElement aElement, WpfDrawingContext context, float opacity)
{
_isAggregated = false;
if (aElement == null || aElement.ChildNodes == null)
{
return;
}
string aggregatedFill = aElement.GetAttribute("fill");
bool isFillFound = !string.IsNullOrWhiteSpace(aggregatedFill);
SvgStyleableElement paintElement = null;
if (isFillFound)
{
paintElement = aElement;
}
XmlNode targetNode = aElement;
// Check if the children of the link are wrapped in a Group Element...
if (aElement.ChildNodes.Count == 1)
{
var groupElement = aElement.ChildNodes[0] as SvgGElement;
if (groupElement != null)
{
targetNode = groupElement;
}
}
WpfDrawingSettings settings = context.Settings;
GeometryCollection geomColl = new GeometryCollection();
foreach (XmlNode node in targetNode.ChildNodes)
{
if (node.NodeType != XmlNodeType.Element)
{
continue;
}
// Handle a case where the clip element has "use" element as a child...
if (string.Equals(node.LocalName, "use"))
{
SvgUseElement useElement = (SvgUseElement)node;
XmlElement refEl = useElement.ReferencedElement;
if (refEl != null)
{
XmlElement refElParent = (XmlElement)refEl.ParentNode;
useElement.OwnerDocument.Static = true;
useElement.CopyToReferencedElement(refEl);
refElParent.RemoveChild(refEl);
useElement.AppendChild(refEl);
foreach (XmlNode useChild in useElement.ChildNodes)
{
if (useChild.NodeType != XmlNodeType.Element)
{
continue;
}
var element = useChild as SvgStyleableElement;
if (element != null && element.RenderingHint == SvgRenderingHint.Shape)
{
Geometry childPath = CreateGeometry(element, settings.OptimizePath);
if (childPath != null)
{
if (isFillFound)
{
string elementFill = element.GetAttribute("fill");
if (!string.IsNullOrWhiteSpace(elementFill) &&
!string.Equals(elementFill, aggregatedFill, StringComparison.OrdinalIgnoreCase))
{
return;
}
}
else
{
aggregatedFill = element.GetAttribute("fill");
isFillFound = !string.IsNullOrWhiteSpace(aggregatedFill);
if (isFillFound)
{
paintElement = element;
}
}
geomColl.Add(childPath);
}
}
}
useElement.RemoveChild(refEl);
useElement.RestoreReferencedElement(refEl);
refElParent.AppendChild(refEl);
useElement.OwnerDocument.Static = false;
}
}
//else if (string.Equals(node.LocalName, "g"))
//{
//}
else
{
var element = node as SvgStyleableElement;
if (element != null && element.RenderingHint == SvgRenderingHint.Shape)
{
Geometry childPath = CreateGeometry(element, settings.OptimizePath);
if (childPath != null)
{
if (isFillFound)
{
string elementFill = element.GetAttribute("fill");
if (!string.IsNullOrWhiteSpace(elementFill) &&
!string.Equals(elementFill, aggregatedFill, StringComparison.OrdinalIgnoreCase))
{
return;
}
}
else
{
aggregatedFill = element.GetAttribute("fill");
isFillFound = !string.IsNullOrWhiteSpace(aggregatedFill);
if (isFillFound)
{
paintElement = element;
}
}
geomColl.Add(childPath);
}
}
}
}
if (geomColl.Count == 0 || paintElement == null)
{
return;
}
_aggregatedFill = paintElement;
_aggregatedGeom = geomColl;
_isAggregated = true;
}
#endregion
}
}
| 34.738155 | 125 | 0.439555 | [
"MIT",
"BSD-3-Clause"
] | Altua/SharpVectors | Source/SharpVectorConvertersWpf/LinkVisitor.cs | 13,932 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using TypeLite.Extensions;
using TypeLite.ReadOnlyDictionary;
using TypeLite.TsModels;
namespace TypeLite
{
/// <summary>
/// Generates TypeScript definitions form the code model.
/// </summary>
public class TsGenerator
{
protected TsTypeFormatterCollection _typeFormatters;
protected TypeConvertorCollection _typeConvertors;
protected TsMemberIdentifierFormatter _memberFormatter;
protected TsMemberTypeFormatter _memberTypeFormatter;
protected TsTypeVisibilityFormatter _typeVisibilityFormatter;
protected TsModuleNameFormatter _moduleNameFormatter;
protected IDocAppender _docAppender;
protected HashSet<TsClass> _generatedClasses;
protected HashSet<TsEnum> _generatedEnums;
protected List<string> _references;
/// <summary>
/// Gets collection of formatters for individual TsTypes
/// </summary>
public IReadOnlyDictionary<Type, TsTypeFormatter> Formaters
{
get
{
return new ReadOnlyDictionaryWrapper<Type, TsTypeFormatter>(_typeFormatters._formatters);
}
}
/// <summary>
/// Gets or sets string for the single indentation level.
/// </summary>
public string IndentationString { get; set; }
/// <summary>
/// Gets or sets bool value indicating whether enums should be generated as 'const enum'. Default value is true.
/// </summary>
public bool GenerateConstEnums { get; set; }
/// <summary>
/// Initializes a new instance of the TsGenerator class with the default formatters.
/// </summary>
public TsGenerator()
{
_references = new List<string>();
_generatedClasses = new HashSet<TsClass>();
_generatedEnums = new HashSet<TsEnum>();
_typeFormatters = new TsTypeFormatterCollection();
_typeFormatters.RegisterTypeFormatter<TsClass>((type, formatter) => {
var tsClass = ((TsClass)type);
if (!tsClass.GenericArguments.Any()) return tsClass.Name;
return tsClass.Name + "<" + string.Join(", ", tsClass.GenericArguments.Select(a => a as TsCollection != null ? this.GetFullyQualifiedTypeName(a) + "[]" : this.GetFullyQualifiedTypeName(a))) + ">";
});
_typeFormatters.RegisterTypeFormatter<TsSystemType>((type, formatter) => ((TsSystemType)type).Kind.ToTypeScriptString());
_typeFormatters.RegisterTypeFormatter<TsCollection>((type, formatter) => {
var itemType = ((TsCollection)type).ItemsType;
var itemTypeAsClass = itemType as TsClass;
if (itemTypeAsClass == null || !itemTypeAsClass.GenericArguments.Any()) return this.GetTypeName(itemType);
return this.GetTypeName(itemType);
});
_typeFormatters.RegisterTypeFormatter<TsEnum>((type, formatter) => ((TsEnum)type).Name);
_typeConvertors = new TypeConvertorCollection();
_docAppender = new NullDocAppender();
_memberFormatter = DefaultMemberFormatter;
_memberTypeFormatter = DefaultMemberTypeFormatter;
_typeVisibilityFormatter = DefaultTypeVisibilityFormatter;
_moduleNameFormatter = DefaultModuleNameFormatter;
this.IndentationString = "\t";
this.GenerateConstEnums = true;
}
public bool DefaultTypeVisibilityFormatter(TsClass tsClass, string typeName)
{
return false;
}
public string DefaultModuleNameFormatter(TsModule module)
{
return module.Name;
}
public string DefaultMemberFormatter(TsProperty identifier)
{
return identifier.Name;
}
public string DefaultMemberTypeFormatter(TsProperty tsProperty, string memberTypeName)
{
var asCollection = tsProperty.PropertyType as TsCollection;
var isCollection = asCollection != null;
return memberTypeName + (isCollection ? string.Concat(Enumerable.Repeat("[]", asCollection.Dimension)) : "");
}
/// <summary>
/// Registers the formatter for the specific TsType
/// </summary>
/// <typeparam name="TFor">The type to register the formatter for. TFor is restricted to TsType and derived classes.</typeparam>
/// <param name="formatter">The formatter to register</param>
/// <remarks>
/// If a formatter for the type is already registered, it is overwritten with the new value.
/// </remarks>
public void RegisterTypeFormatter<TFor>(TsTypeFormatter formatter) where TFor : TsType
{
_typeFormatters.RegisterTypeFormatter<TFor>(formatter);
}
/// <summary>
/// Registers the custom formatter for the TsClass type.
/// </summary>
/// <param name="formatter">The formatter to register.</param>
public void RegisterTypeFormatter(TsTypeFormatter formatter)
{
_typeFormatters.RegisterTypeFormatter<TsClass>(formatter);
}
/// <summary>
/// Registers the converter for the specific Type
/// </summary>
/// <typeparam name="TFor">The type to register the converter for.</typeparam>
/// <param name="convertor">The converter to register</param>
/// <remarks>
/// If a converter for the type is already registered, it is overwritten with the new value.
/// </remarks>
public void RegisterTypeConvertor<TFor>(TypeConvertor convertor)
{
_typeConvertors.RegisterTypeConverter<TFor>(convertor);
}
/// <summary>
/// Sets the formatter for class member identifiers.
/// </summary>
/// <param name="formatter">The formatter to register.</param>
public void SetIdentifierFormatter(TsMemberIdentifierFormatter formatter)
{
_memberFormatter = formatter;
}
/// <summary>
/// Sets the formatter for class member types.
/// </summary>
/// <param name="formatter">The formatter to register.</param>
public void SetMemberTypeFormatter(TsMemberTypeFormatter formatter)
{
_memberTypeFormatter = formatter;
}
/// <summary>
/// Sets the formatter for class member types.
/// </summary>
/// <param name="formatter">The formatter to register.</param>
public void SetTypeVisibilityFormatter(TsTypeVisibilityFormatter formatter)
{
_typeVisibilityFormatter = formatter;
}
/// <summary>
/// Sets the formatter for module names.
/// </summary>
/// <param name="formatter">The formatter to register.</param>
public void SetModuleNameFormatter(TsModuleNameFormatter formatter)
{
_moduleNameFormatter = formatter;
}
/// <summary>
/// Sets the document appender.
/// </summary>
/// <param name="appender">The ducument appender.</param>
public void SetDocAppender(IDocAppender appender)
{
_docAppender = appender;
}
/// <summary>
/// Add a typescript reference
/// </summary>
/// <param name="reference">Name of d.ts file used as typescript reference</param>
public void AddReference(string reference)
{
_references.Add(reference);
}
/// <summary>
/// Generates TypeScript definitions for properties and enums in the model.
/// </summary>
/// <param name="model">The code model with classes to generate definitions for.</param>
/// <returns>TypeScript definitions for classes in the model.</returns>
public string Generate(TsModel model)
{
return this.Generate(model, TsGeneratorOutput.Properties | TsGeneratorOutput.Enums);
}
/// <summary>
/// Generates TypeScript definitions for classes and/or enums in the model.
/// </summary>
/// <param name="model">The code model with classes to generate definitions for.</param>
/// <param name="generatorOutput">The type of definitions to generate</param>
/// <returns>TypeScript definitions for classes and/or enums in the model..</returns>
public string Generate(TsModel model, TsGeneratorOutput generatorOutput)
{
var sb = new ScriptBuilder(this.IndentationString);
if ((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties
|| (generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
{
if ((generatorOutput & TsGeneratorOutput.Constants) == TsGeneratorOutput.Constants)
{
// We can't generate constants together with properties or fields, because we can't set values in a .d.ts file.
throw new InvalidOperationException("Cannot generate constants together with properties or fields");
}
foreach (var reference in _references.Concat(model.References))
{
this.AppendReference(reference, sb);
}
sb.AppendLine();
}
foreach (var module in model.Modules)
{
this.AppendModule(module, sb, generatorOutput);
}
return sb.ToString();
}
/// <summary>
/// Generates reference to other d.ts file and appends it to the output.
/// </summary>
/// <param name="reference">The reference file to generate reference for.</param>
/// <param name="sb">The output</param>
protected virtual void AppendReference(string reference, ScriptBuilder sb)
{
sb.AppendFormat("/// <reference path=\"{0}\" />", reference);
sb.AppendLine();
}
protected virtual void AppendModule(TsModule module, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
{
var classes = module.Classes.Where(c => !_typeConvertors.IsConvertorRegistered(c.Type) && !c.IsIgnored).ToList();
var enums = module.Enums.Where(e => !_typeConvertors.IsConvertorRegistered(e.Type) && !e.IsIgnored).ToList();
if ((generatorOutput == TsGeneratorOutput.Enums && enums.Count == 0) ||
(generatorOutput == TsGeneratorOutput.Properties && classes.Count == 0) ||
(enums.Count == 0 && classes.Count == 0))
{
return;
}
var moduleName = GetModuleName(module);
var generateModuleHeader = moduleName != string.Empty;
IndentationLevelScope indentationLevelScope = null;
if (generateModuleHeader)
{
if (generatorOutput != TsGeneratorOutput.Enums &&
(generatorOutput & TsGeneratorOutput.Constants) != TsGeneratorOutput.Constants)
{
sb.Append("declare ");
}
sb.AppendLine(string.Format("module {0} {{", moduleName));
indentationLevelScope = sb.IncreaseIndentation();
}
if ((generatorOutput & TsGeneratorOutput.Enums) == TsGeneratorOutput.Enums)
{
foreach (var enumModel in enums)
{
this.AppendEnumDefinition(enumModel, sb, generatorOutput);
}
}
if (((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties)
|| (generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
{
foreach (var classModel in classes)
{
this.AppendClassDefinition(classModel, sb, generatorOutput);
}
}
if ((generatorOutput & TsGeneratorOutput.Constants) == TsGeneratorOutput.Constants)
{
foreach (var classModel in classes)
{
if (classModel.IsIgnored)
{
continue;
}
this.AppendConstantModule(classModel, sb);
}
}
if (generateModuleHeader)
{
sb.DecreaseIndentation(indentationLevelScope);
sb.AppendLine("}");
}
}
/// <summary>
/// Generates class definition and appends it to the output.
/// </summary>
/// <param name="classModel">The class to generate definition for.</param>
/// <param name="sb">The output.</param>
/// <param name="generatorOutput"></param>
protected virtual void AppendClassDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
{
string typeName = this.GetTypeName(classModel);
string visibility = this.GetTypeVisibility(classModel, typeName) ? "export " : "";
_docAppender.AppendClassDoc(sb, classModel, typeName);
sb.AppendFormatIndented("{0}class {1}", visibility, typeName);
if (classModel.BaseType != null)
{
sb.AppendFormat(" extends {0}", this.GetFullyQualifiedTypeName(classModel.BaseType));
}
if (classModel.Interfaces.Count > 0)
{
var implementations = classModel.Interfaces.Select(GetFullyQualifiedTypeName).ToArray();
var prefixFormat = classModel.Type.IsInterface ? " extends {0}"
: classModel.BaseType != null ? " , {0}"
: " extends {0}";
sb.AppendFormat(prefixFormat, string.Join(" ,", implementations));
}
sb.AppendLine(" {");
var members = new List<TsProperty>();
if ((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties)
{
members.AddRange(classModel.Properties);
}
if ((generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
{
members.AddRange(classModel.Fields);
}
using (sb.IncreaseIndentation())
{
foreach (var property in members)
{
if (property.IsIgnored)
{
continue;
}
_docAppender.AppendPropertyDoc(sb, property, this.GetPropertyName(property), this.GetPropertyType(property));
sb.AppendLineIndented(string.Format("{0}: {1};", this.GetPropertyName(property), this.GetPropertyType(property)));
}
}
sb.AppendLineIndented("}");
_generatedClasses.Add(classModel);
}
protected virtual void AppendEnumDefinition(TsEnum enumModel, ScriptBuilder sb, TsGeneratorOutput output)
{
string typeName = this.GetTypeName(enumModel);
string visibility = (output & TsGeneratorOutput.Enums) == TsGeneratorOutput.Enums || (output & TsGeneratorOutput.Constants) == TsGeneratorOutput.Constants ? "export " : "";
_docAppender.AppendEnumDoc(sb, enumModel, typeName);
string constSpecifier = this.GenerateConstEnums ? "const " : string.Empty;
sb.AppendLineIndented(string.Format("{0}{2}enum {1} {{", visibility, typeName, constSpecifier));
using (sb.IncreaseIndentation())
{
int i = 1;
foreach (var v in enumModel.Values)
{
_docAppender.AppendEnumValueDoc(sb, v);
sb.AppendLineIndented(string.Format(i < enumModel.Values.Count ? "{0} = {1}," : "{0} = {1}", v.Name, v.Value));
i++;
}
}
sb.AppendLineIndented("}");
_generatedEnums.Add(enumModel);
}
/// <summary>
/// Generates class definition and appends it to the output.
/// </summary>
/// <param name="classModel">The class to generate definition for.</param>
/// <param name="sb">The output.</param>
/// <param name="generatorOutput"></param>
protected virtual void AppendConstantModule(TsClass classModel, ScriptBuilder sb)
{
if (!classModel.Constants.Any())
{
return;
}
string typeName = this.GetTypeName(classModel);
sb.AppendLineIndented(string.Format("export module {0} {{", typeName));
using (sb.IncreaseIndentation())
{
foreach (var property in classModel.Constants)
{
if (property.IsIgnored)
{
continue;
}
_docAppender.AppendConstantModuleDoc(sb, property, this.GetPropertyName(property), this.GetPropertyType(property));
sb.AppendFormatIndented("export var {0}: {1} = {2};", this.GetPropertyName(property), this.GetPropertyType(property), this.GetPropertyConstantValue(property));
sb.AppendLine();
}
}
sb.AppendLineIndented("}");
_generatedClasses.Add(classModel);
}
/// <summary>
/// Gets fully qualified name of the type
/// </summary>
/// <param name="type">The type to get name of</param>
/// <returns>Fully qualified name of the type</returns>
public string GetFullyQualifiedTypeName(TsType type)
{
var moduleName = string.Empty;
if (type as TsModuleMember != null && !_typeConvertors.IsConvertorRegistered(type.Type))
{
var memberType = (TsModuleMember)type;
moduleName = memberType.Module != null ? GetModuleName(memberType.Module) : string.Empty;
}
else if (type as TsCollection != null)
{
var collectionType = (TsCollection)type;
moduleName = GetCollectionModuleName(collectionType, moduleName);
}
if (type.Type.IsGenericParameter)
{
return this.GetTypeName(type);
}
if (!string.IsNullOrEmpty(moduleName))
{
var name = moduleName + "." + this.GetTypeName(type);
return name;
}
return this.GetTypeName(type);
}
/// <summary>
/// Recursively finds the module name for the underlaying ItemsType of a TsCollection.
/// </summary>
/// <param name="collectionType">The TsCollection object.</param>
/// <param name="moduleName">The module name.</param>
/// <returns></returns>
public string GetCollectionModuleName(TsCollection collectionType, string moduleName)
{
if (collectionType.ItemsType as TsModuleMember != null && !_typeConvertors.IsConvertorRegistered(collectionType.ItemsType.Type))
{
if (!collectionType.ItemsType.Type.IsGenericParameter)
moduleName = ((TsModuleMember)collectionType.ItemsType).Module != null ? GetModuleName(((TsModuleMember)collectionType.ItemsType).Module) : string.Empty;
}
if (collectionType.ItemsType as TsCollection != null)
{
moduleName = GetCollectionModuleName((TsCollection)collectionType.ItemsType, moduleName);
}
return moduleName;
}
/// <summary>
/// Gets name of the type in the TypeScript
/// </summary>
/// <param name="type">The type to get name of</param>
/// <returns>name of the type</returns>
public string GetTypeName(TsType type)
{
if (_typeConvertors.IsConvertorRegistered(type.Type))
{
return _typeConvertors.ConvertType(type.Type);
}
return _typeFormatters.FormatType(type);
}
/// <summary>
/// Gets property name in the TypeScript
/// </summary>
/// <param name="property">The property to get name of</param>
/// <returns>name of the property</returns>
public string GetPropertyName(TsProperty property)
{
var name = _memberFormatter(property);
if (property.IsOptional)
{
name += "?";
}
return name;
}
/// <summary>
/// Gets property type in the TypeScript
/// </summary>
/// <param name="property">The property to get type of</param>
/// <returns>type of the property</returns>
public string GetPropertyType(TsProperty property)
{
var fullyQualifiedTypeName = GetFullyQualifiedTypeName(property.PropertyType);
return _memberTypeFormatter(property, fullyQualifiedTypeName);
}
/// <summary>
/// Gets property constant value in TypeScript format
/// </summary>
/// <param name="property">The property to get constant value of</param>
/// <returns>constant value of the property</returns>
public string GetPropertyConstantValue(TsProperty property)
{
var quote = property.PropertyType.Type == typeof(string) ? "\"" : "";
return quote + property.ConstantValue.ToString() + quote;
}
/// <summary>
/// Gets whether a type should be marked with "Export" keyword in TypeScript
/// </summary>
/// <param name="tsClass"></param>
/// <param name="typeName">The type to get the visibility of</param>
/// <returns>bool indicating if type should be marked weith keyword "Export"</returns>
public bool GetTypeVisibility(TsClass tsClass, string typeName)
{
return _typeVisibilityFormatter(tsClass, typeName);
}
/// <summary>
/// Formats a module name
/// </summary>
/// <param name="module">The module to be formatted</param>
/// <returns>The module name after formatting.</returns>
public string GetModuleName(TsModule module)
{
return _moduleNameFormatter(module);
}
}
}
| 40.168142 | 212 | 0.582639 | [
"MIT"
] | eberlitz/WebApiClientTS | src/TypeLite/TsGenerator.cs | 22,697 | C# |
using Genbox.SimpleS3.Core.Abstracts;
using Genbox.SimpleS3.Core.Abstracts.Request;
using Genbox.SimpleS3.Core.Common.Constants;
using Genbox.SimpleS3.Core.Internals.Xml;
using Genbox.SimpleS3.Core.Network.Requests.Buckets;
namespace Genbox.SimpleS3.Core.Internals.Marshallers.Requests.Buckets;
internal class PutBucketAccelerateConfigurationRequestMarshal : IRequestMarshal<PutBucketAccelerateConfigurationRequest>
{
public Stream? MarshalRequest(PutBucketAccelerateConfigurationRequest request, SimpleS3Config config)
{
request.SetQueryParameter(AmzParameters.Accelerate, string.Empty);
FastXmlWriter writer = new FastXmlWriter(150);
writer.WriteStartElement("AccelerateConfiguration", "http://s3.amazonaws.com/doc/2006-03-01/");
writer.WriteElement("Status", request.AccelerationEnabled ? "Enabled" : "Suspended");
writer.WriteEndElement("AccelerateConfiguration");
return new MemoryStream(writer.GetBytes());
}
} | 44.545455 | 120 | 0.787755 | [
"MIT"
] | Genbox/SimpleS3Net | src/SimpleS3.Core/Internals/Marshallers/Requests/Buckets/PutBucketAccelerateConfigurationRequestMarshal.cs | 980 | C# |
using System.Collections.Generic;
using System.Security.Claims;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Security.Claims;
namespace RabbitMQ.Source.Security
{
[Dependency(ReplaceServices = true)]
public class FakeCurrentPrincipalAccessor : ThreadCurrentPrincipalAccessor
{
protected override ClaimsPrincipal GetClaimsPrincipal()
{
return GetPrincipal();
}
private ClaimsPrincipal _principal;
private ClaimsPrincipal GetPrincipal()
{
if (_principal == null)
{
lock (this)
{
if (_principal == null)
{
_principal = new ClaimsPrincipal(
new ClaimsIdentity(
new List<Claim>
{
new Claim(AbpClaimTypes.UserId,"2e701e62-0953-4dd3-910b-dc6cc93ccb0d"),
new Claim(AbpClaimTypes.UserName,"admin"),
new Claim(AbpClaimTypes.Email,"admin@abp.io")
}
)
);
}
}
}
return _principal;
}
}
}
| 30.295455 | 107 | 0.462116 | [
"MIT"
] | arajpant/Abp-MessageQueue-RabbitMq | Source/test/RabbitMQ.Source.TestBase/Security/FakeCurrentPrincipalAccessor.cs | 1,335 | C# |
using System;
using System.Linq.Expressions;
namespace System.Reflection {
public static class PropertyCompiler {
public static Func<object, object?> ObjectGetter(this PropertyAccessor This) {
var Method = This.Property.GetGetMethod(true);
if (Method is null) {
throw new ArgumentException("Unable to find getter");
}
var Instance = Expression.Parameter(typeof(object), "i");
var InstanceCast = Expression.Convert(Instance, This.EntityType);
var GetterCall = Expression.Call(InstanceCast, Method);
var ReturnCast = Expression.Convert(GetterCall, typeof(object));
var tret = Expression.Lambda(ReturnCast, Instance).Compile();
var ret = (Func<object, object?>)tret;
return ret;
}
public static Action<object, object?> ObjectSetter(this PropertyAccessor This) {
var Method = This.Property.GetSetMethod(true);
if (Method is null) {
throw new ArgumentException("Unable to find setter");
}
var Instance = Expression.Parameter(typeof(object), "i");
var InstanceCast = Expression.Convert(Instance, This.EntityType);
var Argument = Expression.Parameter(typeof(object), "a");
var ArgumentCast = Expression.Convert(Argument, This.PropertyType);
var SetterCall = Expression.Call(InstanceCast, Method, ArgumentCast);
var tret = Expression.Lambda(SetterCall, Instance, Argument).Compile();
var ret = (Action<object, object?>)tret;
return ret;
}
public static Func<TEntity, object?> EntityGetter<TEntity>(this PropertyAccessor<TEntity> This) {
var Method = This.Property.GetGetMethod(true);
if (Method is null) {
throw new ArgumentException("Unable to find getter");
}
var Instance = Expression.Parameter(typeof(TEntity), "i");
var GetterCall = Expression.Call(Instance, Method);
var GetterCast = Expression.Convert(GetterCall, typeof(object));
var tret = Expression.Lambda(GetterCast, Instance).Compile();
var ret = (Func<TEntity, object?>)tret;
return ret;
}
public static Action<TEntity, object?> EntitySetter<TEntity>(this PropertyAccessor<TEntity> This) {
var Method = This.Property.GetSetMethod(true);
if (Method is null) {
throw new ArgumentException("Unable to find setter");
}
var Instance = Expression.Parameter(typeof(TEntity), "i");
var Argument = Expression.Parameter(typeof(object), "a");
var ArgumentCast = Expression.Convert(Argument, This.PropertyType);
var SetterCall = Expression.Call(Instance, Method, ArgumentCast);
var tret = Expression.Lambda(SetterCall, Instance, Argument).Compile();
var ret = (Action<TEntity, object?>)tret;
return ret;
}
public static Func<TEntity, TProperty> ValueGetter<TEntity, TProperty>(this PropertyAccessor<TEntity, TProperty> This) {
var Method = This.Property.GetGetMethod(true);
if(Method is null) {
throw new ArgumentException("Unable to find getter");
}
var Instance = Expression.Parameter(typeof(TEntity), "i");
var GetterCall = Expression.Call(Instance, Method);
var tret = Expression.Lambda(GetterCall, Instance).Compile();
var ret = (Func<TEntity, TProperty>)tret;
return ret;
}
public static Action<TEntity, TProperty> ValueSetter<TEntity, TProperty>(this PropertyAccessor<TEntity, TProperty> This) {
var Method = This.Property.GetSetMethod(true);
if (Method is null) {
throw new ArgumentException("Unable to find setter");
}
var Instance = Expression.Parameter(typeof(TEntity), "i");
var Argument = Expression.Parameter(typeof(TProperty), "a");
var SetterCall = Expression.Call(Instance, Method, Argument);
var tret = Expression.Lambda(SetterCall, Instance, Argument).Compile();
var ret = (Action<TEntity, TProperty>)tret;
return ret;
}
}
}
| 38.163793 | 130 | 0.607861 | [
"MIT"
] | MediatedCommunications/InfoOf | src/InfoOf/Compilers/PropertyCompiler.cs | 4,429 | C# |
using Example.Domain;
using System.Data.Entity;
namespace Example.DAL
{
internal class ExampleContext : DbContext
{
public ExampleContext() : base("ExampleContextConnectionString")
{
Database.SetInitializer(new CreateDatabaseIfNotExists<ExampleContext>());
}
public DbSet<EmployeeEntity> Employees { get; set; }
public DbSet<DepartmentEntity> Departments { get; set; }
}
}
| 25.882353 | 85 | 0.672727 | [
"MIT"
] | AlexMem/ExampleSolution | ExampleSolution/Example.DAL/ExampleContext.cs | 442 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using System.Web.OData.Builder;
using System.Xml.Linq;
using Microsoft.OData.Core;
using Microsoft.OData.Core.UriParser;
using Microsoft.OData.Core.UriParser.Semantic;
using Microsoft.OData.Edm;
using Microsoft.TestCommon;
namespace System.Web.OData.Query.Expressions
{
public class FilterBinderTests
{
private const string NotTesting = "";
private static readonly Uri _serviceBaseUri = new Uri("http://server/service/");
private static Dictionary<Type, IEdmModel> _modelCache = new Dictionary<Type, IEdmModel>();
public static TheoryDataSet<decimal?, bool, object> MathRoundDecimal_DataSet
{
get
{
return new TheoryDataSet<decimal?, bool, object>
{
{ null, false, typeof(InvalidOperationException) },
{ 5.9m, true, true },
{ 5.4m, false, false },
};
}
}
#region Inequalities
[Theory]
[InlineData(null, true, true)]
[InlineData("", false, false)]
[InlineData("Doritos", false, false)]
public void EqualityOperatorWithNull(string productName, bool withNullPropagation, bool withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"ProductName eq null",
"$it => ($it.ProductName == null)");
RunFilters(filters,
new Product { ProductName = productName },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, false, false)]
[InlineData("", false, false)]
[InlineData("Doritos", true, true)]
public void EqualityOperator(string productName, bool withNullPropagation, bool withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"ProductName eq 'Doritos'",
"$it => ($it.ProductName == \"Doritos\")");
RunFilters(filters,
new Product { ProductName = productName },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, true, true)]
[InlineData("", true, true)]
[InlineData("Doritos", false, false)]
public void NotEqualOperator(string productName, bool withNullPropagation, bool withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"ProductName ne 'Doritos'",
"$it => ($it.ProductName != \"Doritos\")");
RunFilters(filters,
new Product { ProductName = productName },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, false, false)]
[InlineData(5.01, true, true)]
[InlineData(4.99, false, false)]
public void GreaterThanOperator(object unitPrice, bool withNullPropagation, bool withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"UnitPrice gt 5.00m",
Error.Format("$it => ($it.UnitPrice > Convert({0:0.00}))", 5.0),
Error.Format("$it => (($it.UnitPrice > Convert({0:0.00})) == True)", 5.0));
RunFilters(filters,
new Product { UnitPrice = ToNullable<decimal>(unitPrice) },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, false, false)]
[InlineData(5.0, true, true)]
[InlineData(4.99, false, false)]
public void GreaterThanEqualOperator(object unitPrice, bool withNullPropagation, bool withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"UnitPrice ge 5.00m",
Error.Format("$it => ($it.UnitPrice >= Convert({0:0.00}))", 5.0),
Error.Format("$it => (($it.UnitPrice >= Convert({0:0.00})) == True)", 5.0));
RunFilters(filters,
new Product { UnitPrice = ToNullable<decimal>(unitPrice) },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, false, false)]
[InlineData(4.99, true, true)]
[InlineData(5.01, false, false)]
public void LessThanOperator(object unitPrice, bool withNullPropagation, bool withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"UnitPrice lt 5.00m",
Error.Format("$it => ($it.UnitPrice < Convert({0:0.00}))", 5.0),
NotTesting);
RunFilters(filters,
new Product { UnitPrice = ToNullable<decimal>(unitPrice) },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, false, false)]
[InlineData(5.0, true, true)]
[InlineData(5.01, false, false)]
public void LessThanOrEqualOperator(object unitPrice, bool withNullPropagation, bool withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"UnitPrice le 5.00m",
Error.Format("$it => ($it.UnitPrice <= Convert({0:0.00}))", 5.0),
NotTesting);
RunFilters(filters,
new Product { UnitPrice = ToNullable<decimal>(unitPrice) },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Fact]
public void NegativeNumbers()
{
VerifyQueryDeserialization(
"UnitPrice le -5.00m",
Error.Format("$it => ($it.UnitPrice <= Convert({0:0.00}))", -5.0),
NotTesting);
}
[Theory]
[InlineData("DateTimeOffsetProp eq DateTimeOffsetProp", "$it => ($it.DateTimeOffsetProp == $it.DateTimeOffsetProp)")]
[InlineData("DateTimeOffsetProp ne DateTimeOffsetProp", "$it => ($it.DateTimeOffsetProp != $it.DateTimeOffsetProp)")]
[InlineData("DateTimeOffsetProp ge DateTimeOffsetProp", "$it => ($it.DateTimeOffsetProp >= $it.DateTimeOffsetProp)")]
[InlineData("DateTimeOffsetProp le DateTimeOffsetProp", "$it => ($it.DateTimeOffsetProp <= $it.DateTimeOffsetProp)")]
public void DateTimeOffsetInEqualities(string clause, string expectedExpression)
{
// There's currently a bug here. For now, the test checks for the presence of the bug (as a reminder to fix
// the test once the bug is fixed).
// The following assert shows the behavior with the bug and should be removed once the bug is fixed.
Assert.Throws<ODataException>(() => Bind("" + clause));
// TODO: Enable once ODataUriParser handles DateTimeOffsets
// The following call shows the behavior without the bug, and should be enabled once the bug is fixed.
//VerifyQueryDeserialization<DataTypes>("" + clause, expectedExpression);
}
[Theory]
[InlineData("DateTimeProp eq DateTimeProp", "$it => ($it.DateTimeProp == $it.DateTimeProp)")]
[InlineData("DateTimeProp ne DateTimeProp", "$it => ($it.DateTimeProp != $it.DateTimeProp)")]
[InlineData("DateTimeProp ge DateTimeProp", "$it => ($it.DateTimeProp >= $it.DateTimeProp)")]
[InlineData("DateTimeProp le DateTimeProp", "$it => ($it.DateTimeProp <= $it.DateTimeProp)")]
public void DateInEqualities(string clause, string expectedExpression)
{
VerifyQueryDeserialization<DataTypes>(
"" + clause,
expectedExpression);
}
#endregion
#region Logical Operators
[Fact]
[ReplaceCulture]
public void BooleanOperatorNullableTypes()
{
VerifyQueryDeserialization(
"UnitPrice eq 5.00m or CategoryID eq 0",
Error.Format("$it => (($it.UnitPrice == Convert(5.00)) OrElse ($it.CategoryID == 0))", 5.0, 0),
NotTesting);
}
[Fact]
public void BooleanComparisonOnNullableAndNonNullableType()
{
VerifyQueryDeserialization(
"Discontinued eq true",
"$it => ($it.Discontinued == Convert(True))",
"$it => (($it.Discontinued == Convert(True)) == True)");
}
[Fact]
public void BooleanComparisonOnNullableType()
{
VerifyQueryDeserialization(
"Discontinued eq Discontinued",
"$it => ($it.Discontinued == $it.Discontinued)",
"$it => (($it.Discontinued == $it.Discontinued) == True)");
}
[Theory]
[InlineData(null, null, false, false)]
[InlineData(5.0, 0, true, true)]
[InlineData(null, 1, false, false)]
public void OrOperator(object unitPrice, object unitsInStock, bool withNullPropagation, bool withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"UnitPrice eq 5.00m or UnitsInStock eq 0",
Error.Format("$it => (($it.UnitPrice == Convert({0:0.00})) OrElse (Convert($it.UnitsInStock) == Convert({1})))", 5.0, 0),
NotTesting);
RunFilters(filters,
new Product { UnitPrice = ToNullable<decimal>(unitPrice), UnitsInStock = ToNullable<short>(unitsInStock) },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, null, false, false)]
[InlineData(5.0, 10, true, true)]
[InlineData(null, 1, false, false)]
public void AndOperator(object unitPrice, object unitsInStock, bool withNullPropagation, bool withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"UnitPrice eq 5.00m and UnitsInStock eq 10.00m",
Error.Format("$it => (($it.UnitPrice == Convert({0:0.00})) AndAlso (Convert($it.UnitsInStock) == Convert({1:0.00})))", 5.0, 10.0),
NotTesting);
RunFilters(filters,
new Product { UnitPrice = ToNullable<decimal>(unitPrice), UnitsInStock = ToNullable<short>(unitsInStock) },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, false, true)] // This is an interesting cas for null propagation.
[InlineData(5.0, false, false)]
[InlineData(5.5, true, true)]
public void Negation(object unitPrice, bool withNullPropagation, bool withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"not (UnitPrice eq 5.00m)",
Error.Format("$it => Not(($it.UnitPrice == Convert({0:0.00})))", 5.0),
NotTesting);
RunFilters(filters,
new Product { UnitPrice = ToNullable<decimal>(unitPrice) },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, true, true)] // This is an interesting cas for null propagation.
[InlineData(true, false, false)]
[InlineData(false, true, true)]
public void BoolNegation(bool discontinued, bool withNullPropagation, bool withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"not Discontinued",
"$it => Convert(Not($it.Discontinued))",
"$it => (Not($it.Discontinued) == True)");
RunFilters(filters,
new Product { Discontinued = ToNullable<bool>(discontinued) },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Fact]
public void NestedNegation()
{
VerifyQueryDeserialization(
"not (not(not (Discontinued)))",
"$it => Convert(Not(Not(Not($it.Discontinued))))",
"$it => (Not(Not(Not($it.Discontinued))) == True)");
}
#endregion
#region Arithmetic Operators
[Theory]
[InlineData(null, false, false)]
[InlineData(5.0, true, true)]
[InlineData(15.01, false, false)]
public void Subtraction(object unitPrice, bool withNullPropagation, bool withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"UnitPrice sub 1.00m lt 5.00m",
Error.Format("$it => (($it.UnitPrice - Convert({0:0.00})) < Convert({1:0.00}))", 1.0, 5.0),
Error.Format("$it => ((($it.UnitPrice - Convert({0:0.00})) < Convert({1:0.00})) == True)", 1.0, 5.0));
RunFilters(filters,
new Product { UnitPrice = ToNullable<decimal>(unitPrice) },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Fact]
public void Addition()
{
VerifyQueryDeserialization(
"UnitPrice add 1.00m lt 5.00m",
Error.Format("$it => (($it.UnitPrice + Convert({0:0.00})) < Convert({1:0.00}))", 1.0, 5.0),
NotTesting);
}
[Fact]
public void Multiplication()
{
VerifyQueryDeserialization(
"UnitPrice mul 1.00m lt 5.00m",
Error.Format("$it => (($it.UnitPrice * Convert({0:0.00})) < Convert({1:0.00}))", 1.0, 5.0),
NotTesting);
}
[Fact]
public void Division()
{
VerifyQueryDeserialization(
"UnitPrice div 1.00m lt 5.00m",
Error.Format("$it => (($it.UnitPrice / Convert({0:0.00})) < Convert({1:0.00}))", 1.0, 5.0),
NotTesting);
}
[Fact]
public void Modulo()
{
VerifyQueryDeserialization(
"UnitPrice mod 1.00m lt 5.00m",
Error.Format("$it => (($it.UnitPrice % Convert({0:0.00})) < Convert({1:0.00}))", 1.0, 5.0),
NotTesting);
}
#endregion
# region NULL handling
[Theory]
[InlineData("UnitsInStock eq UnitsOnOrder", null, null, false, true)]
[InlineData("UnitsInStock ne UnitsOnOrder", null, null, false, false)]
[InlineData("UnitsInStock gt UnitsOnOrder", null, null, false, false)]
[InlineData("UnitsInStock ge UnitsOnOrder", null, null, false, false)]
[InlineData("UnitsInStock lt UnitsOnOrder", null, null, false, false)]
[InlineData("UnitsInStock le UnitsOnOrder", null, null, false, false)]
[InlineData("(UnitsInStock add UnitsOnOrder) eq UnitsInStock", null, null, false, true)]
[InlineData("(UnitsInStock sub UnitsOnOrder) eq UnitsInStock", null, null, false, true)]
[InlineData("(UnitsInStock mul UnitsOnOrder) eq UnitsInStock", null, null, false, true)]
[InlineData("(UnitsInStock div UnitsOnOrder) eq UnitsInStock", null, null, false, true)]
[InlineData("(UnitsInStock mod UnitsOnOrder) eq UnitsInStock", null, null, false, true)]
[InlineData("UnitsInStock eq UnitsOnOrder", 1, null, false, false)]
[InlineData("UnitsInStock eq UnitsOnOrder", 1, 1, true, true)]
public void NullHandling(string filter, object unitsInStock, object unitsOnOrder, bool withNullPropagation, bool withoutNullPropagation)
{
var filters = VerifyQueryDeserialization("" + filter);
RunFilters(filters,
new Product { UnitsInStock = ToNullable<short>(unitsInStock), UnitsOnOrder = ToNullable<short>(unitsOnOrder) },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData("UnitsInStock eq null", null, true, true)] // NULL == constant NULL is true when null propagation is enabled
[InlineData("UnitsInStock ne null", null, false, false)] // NULL != constant NULL is false when null propagation is enabled
public void NullHandling_LiteralNull(string filter, object unitsInStock, bool withNullPropagation, bool withoutNullPropagation)
{
var filters = VerifyQueryDeserialization("" + filter);
RunFilters(filters,
new Product { UnitsInStock = ToNullable<short>(unitsInStock) },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
#endregion
[Theory]
[InlineData("StringProp gt 'Middle'", "Middle", false)]
[InlineData("StringProp ge 'Middle'", "Middle", true)]
[InlineData("StringProp lt 'Middle'", "Middle", false)]
[InlineData("StringProp le 'Middle'", "Middle", true)]
[InlineData("StringProp ge StringProp", "", true)]
[InlineData("StringProp gt null", "", true)]
[InlineData("null gt StringProp", "", false)]
[InlineData("'Middle' gt StringProp", "Middle", false)]
[InlineData("'a' lt 'b'", "", true)]
public void StringComparisons_Work(string filter, string value, bool expectedResult)
{
var filters = VerifyQueryDeserialization<DataTypes>(filter);
var result = RunFilter(filters.WithoutNullPropagation, new DataTypes { StringProp = value });
Assert.Equal(result, expectedResult);
}
// Issue: 477
[Theory]
[InlineData("indexof('hello', StringProp) gt UIntProp")]
[InlineData("indexof('hello', StringProp) gt ULongProp")]
[InlineData("indexof('hello', StringProp) gt UShortProp")]
[InlineData("indexof('hello', StringProp) gt NullableUShortProp")]
[InlineData("indexof('hello', StringProp) gt NullableUIntProp")]
[InlineData("indexof('hello', StringProp) gt NullableULongProp")]
public void ComparisonsInvolvingCastsAndNullableValues(string filter)
{
var filters = VerifyQueryDeserialization<DataTypes>(filter);
RunFilters(filters,
new DataTypes(),
new { WithNullPropagation = false, WithoutNullPropagation = typeof(ArgumentNullException) });
}
[Theory]
[InlineData(null, null, true, true)]
[InlineData("not doritos", 0, true, true)]
[InlineData("Doritos", 1, false, false)]
public void Grouping(string productName, object unitsInStock, bool withNullPropagation, bool withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"((ProductName ne 'Doritos') or (UnitPrice lt 5.00m))",
Error.Format("$it => (($it.ProductName != \"Doritos\") OrElse ($it.UnitPrice < Convert({0:0.00})))", 5.0),
NotTesting);
RunFilters(filters,
new Product { ProductName = productName, UnitsInStock = ToNullable<short>(unitsInStock) },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Fact]
public void MemberExpressions()
{
var filters = VerifyQueryDeserialization(
"Category/CategoryName eq 'Snacks'",
"$it => ($it.Category.CategoryName == \"Snacks\")",
"$it => (IIF(($it.Category == null), null, $it.Category.CategoryName) == \"Snacks\")");
RunFilters(filters,
new Product { },
new { WithNullPropagation = false, WithoutNullPropagation = typeof(NullReferenceException) });
RunFilters(filters,
new Product { Category = new Category { CategoryName = "Snacks" } },
new { WithNullPropagation = true, WithoutNullPropagation = true });
}
[Fact]
public void MemberExpressionsRecursive()
{
var filters = VerifyQueryDeserialization(
"Category/Product/Category/CategoryName eq 'Snacks'",
"$it => ($it.Category.Product.Category.CategoryName == \"Snacks\")",
NotTesting);
RunFilters(filters,
new Product { },
new { WithNullPropagation = false, WithoutNullPropagation = typeof(NullReferenceException) });
}
[Fact]
public void ComplexPropertyNavigation()
{
var filters = VerifyQueryDeserialization(
"SupplierAddress/City eq 'Redmond'",
"$it => ($it.SupplierAddress.City == \"Redmond\")",
"$it => (IIF(($it.SupplierAddress == null), null, $it.SupplierAddress.City) == \"Redmond\")");
RunFilters(filters,
new Product { },
new { WithNullPropagation = false, WithoutNullPropagation = typeof(NullReferenceException) });
RunFilters(filters,
new Product { SupplierAddress = new Address { City = "Redmond" } },
new { WithNullPropagation = true, WithoutNullPropagation = true });
}
#region Any/All
[Fact]
public void AnyOnNavigationEnumerableCollections()
{
var filters = VerifyQueryDeserialization(
"Category/EnumerableProducts/any(P: P/ProductName eq 'Snacks')",
"$it => $it.Category.EnumerableProducts.Any(P => (P.ProductName == \"Snacks\"))",
NotTesting);
RunFilters(filters,
new Product
{
Category = new Category
{
EnumerableProducts = new Product[]
{
new Product { ProductName = "Snacks" },
new Product { ProductName = "NonSnacks" }
}
}
},
new { WithNullPropagation = true, WithoutNullPropagation = true });
RunFilters(filters,
new Product
{
Category = new Category
{
EnumerableProducts = new Product[]
{
new Product { ProductName = "NonSnacks" }
}
}
},
new { WithNullPropagation = false, WithoutNullPropagation = false });
}
[Fact]
public void AnyOnNavigationQueryableCollections()
{
var filters = VerifyQueryDeserialization(
"Category/QueryableProducts/any(P: P/ProductName eq 'Snacks')",
"$it => $it.Category.QueryableProducts.Any(P => (P.ProductName == \"Snacks\"))",
NotTesting);
RunFilters(filters,
new Product
{
Category = new Category
{
QueryableProducts = new Product[]
{
new Product { ProductName = "Snacks" },
new Product { ProductName = "NonSnacks" }
}.AsQueryable()
}
},
new { WithNullPropagation = true, WithoutNullPropagation = true });
RunFilters(filters,
new Product
{
Category = new Category
{
QueryableProducts = new Product[]
{
new Product { ProductName = "NonSnacks" }
}.AsQueryable()
}
},
new { WithNullPropagation = false, WithoutNullPropagation = false });
}
[Fact]
public void AnyOnNavigation_NullCollection()
{
var filters = VerifyQueryDeserialization(
"Category/EnumerableProducts/any(P: P/ProductName eq 'Snacks')",
"$it => $it.Category.EnumerableProducts.Any(P => (P.ProductName == \"Snacks\"))",
NotTesting);
RunFilters(filters,
new Product
{
Category = new Category
{
}
},
new { WithNullPropagation = false, WithoutNullPropagation = typeof(ArgumentNullException) });
RunFilters(filters,
new Product
{
Category = new Category
{
EnumerableProducts = new Product[]
{
new Product { ProductName = "Snacks" }
}
}
},
new { WithNullPropagation = true, WithoutNullPropagation = true });
}
[Fact]
public void AllOnNavigation_NullCollection()
{
var filters = VerifyQueryDeserialization(
"Category/EnumerableProducts/all(P: P/ProductName eq 'Snacks')",
"$it => $it.Category.EnumerableProducts.All(P => (P.ProductName == \"Snacks\"))",
NotTesting);
RunFilters(filters,
new Product
{
Category = new Category
{
}
},
new { WithNullPropagation = false, WithoutNullPropagation = typeof(ArgumentNullException) });
RunFilters(filters,
new Product
{
Category = new Category
{
EnumerableProducts = new Product[]
{
new Product { ProductName = "Snacks" }
}
}
},
new { WithNullPropagation = true, WithoutNullPropagation = true });
}
[Fact]
public void MultipleAnys_WithSameRangeVariableName()
{
VerifyQueryDeserialization(
"AlternateIDs/any(n: n eq 42) and AlternateAddresses/any(n : n/City eq 'Redmond')",
"$it => ($it.AlternateIDs.Any(n => (n == 42)) AndAlso $it.AlternateAddresses.Any(n => (n.City == \"Redmond\")))",
NotTesting);
}
[Fact]
public void MultipleAlls_WithSameRangeVariableName()
{
VerifyQueryDeserialization(
"AlternateIDs/all(n: n eq 42) and AlternateAddresses/all(n : n/City eq 'Redmond')",
"$it => ($it.AlternateIDs.All(n => (n == 42)) AndAlso $it.AlternateAddresses.All(n => (n.City == \"Redmond\")))",
NotTesting);
}
[Fact]
public void AnyOnNavigationEnumerableCollections_EmptyFilter()
{
VerifyQueryDeserialization(
"Category/EnumerableProducts/any()",
"$it => $it.Category.EnumerableProducts.Any()",
NotTesting);
}
[Fact]
public void AnyOnNavigationQueryableCollections_EmptyFilter()
{
VerifyQueryDeserialization(
"Category/QueryableProducts/any()",
"$it => $it.Category.QueryableProducts.Any()",
NotTesting);
}
[Fact]
public void AllOnNavigationEnumerableCollections()
{
VerifyQueryDeserialization(
"Category/EnumerableProducts/all(P: P/ProductName eq 'Snacks')",
"$it => $it.Category.EnumerableProducts.All(P => (P.ProductName == \"Snacks\"))",
NotTesting);
}
[Fact]
public void AllOnNavigationQueryableCollections()
{
VerifyQueryDeserialization(
"Category/QueryableProducts/all(P: P/ProductName eq 'Snacks')",
"$it => $it.Category.QueryableProducts.All(P => (P.ProductName == \"Snacks\"))",
NotTesting);
}
[Fact]
public void AnyInSequenceNotNested()
{
VerifyQueryDeserialization(
"Category/QueryableProducts/any(P: P/ProductName eq 'Snacks') or Category/QueryableProducts/any(P2: P2/ProductName eq 'Snacks')",
"$it => ($it.Category.QueryableProducts.Any(P => (P.ProductName == \"Snacks\")) OrElse $it.Category.QueryableProducts.Any(P2 => (P2.ProductName == \"Snacks\")))",
NotTesting);
}
[Fact]
public void AllInSequenceNotNested()
{
VerifyQueryDeserialization(
"Category/QueryableProducts/all(P: P/ProductName eq 'Snacks') or Category/QueryableProducts/all(P2: P2/ProductName eq 'Snacks')",
"$it => ($it.Category.QueryableProducts.All(P => (P.ProductName == \"Snacks\")) OrElse $it.Category.QueryableProducts.All(P2 => (P2.ProductName == \"Snacks\")))",
NotTesting);
}
[Fact]
public void AnyOnPrimitiveCollection()
{
var filters = VerifyQueryDeserialization(
"AlternateIDs/any(id: id eq 42)",
"$it => $it.AlternateIDs.Any(id => (id == 42))",
NotTesting);
RunFilters(
filters,
new Product { AlternateIDs = new[] { 1, 2, 42 } },
new { WithNullPropagation = true, WithoutNullPropagation = true });
RunFilters(
filters,
new Product { AlternateIDs = new[] { 1, 2 } },
new { WithNullPropagation = false, WithoutNullPropagation = false });
}
[Fact]
public void AllOnPrimitiveCollection()
{
VerifyQueryDeserialization(
"AlternateIDs/all(id: id eq 42)",
"$it => $it.AlternateIDs.All(id => (id == 42))",
NotTesting);
}
[Fact]
public void AnyOnComplexCollection()
{
var filters = VerifyQueryDeserialization(
"AlternateAddresses/any(address: address/City eq 'Redmond')",
"$it => $it.AlternateAddresses.Any(address => (address.City == \"Redmond\"))",
NotTesting);
RunFilters(
filters,
new Product { AlternateAddresses = new[] { new Address { City = "Redmond" } } },
new { WithNullPropagation = true, WithoutNullPropagation = true });
RunFilters(
filters,
new Product(),
new { WithNullPropagation = false, WithoutNullPropagation = typeof(ArgumentNullException) });
}
[Fact]
public void AllOnComplexCollection()
{
VerifyQueryDeserialization(
"AlternateAddresses/all(address: address/City eq 'Redmond')",
"$it => $it.AlternateAddresses.All(address => (address.City == \"Redmond\"))",
NotTesting);
}
[Fact]
public void RecursiveAllAny()
{
VerifyQueryDeserialization(
"Category/QueryableProducts/all(P: P/Category/EnumerableProducts/any(PP: PP/ProductName eq 'Snacks'))",
"$it => $it.Category.QueryableProducts.All(P => P.Category.EnumerableProducts.Any(PP => (PP.ProductName == \"Snacks\")))",
NotTesting);
}
#endregion
#region String Functions
[Theory]
[InlineData("Abcd", -1, "Abcd", true, typeof(ArgumentOutOfRangeException))]
[InlineData("Abcd", 0, "Abcd", true, true)]
[InlineData("Abcd", 1, "bcd", true, true)]
[InlineData("Abcd", 3, "d", true, true)]
[InlineData("Abcd", 4, "", true, true)]
[InlineData("Abcd", 5, "", true, typeof(ArgumentOutOfRangeException))]
public void StringSubstringStart(string productName, int startIndex, string compareString, bool withNullPropagation, object withoutNullPropagation)
{
string filter = String.Format("substring(ProductName, {0}) eq '{1}'", startIndex, compareString);
var filters = VerifyQueryDeserialization(filter);
RunFilters(filters,
new Product { ProductName = productName },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData("Abcd", -1, 4, "Abcd", true, typeof(ArgumentOutOfRangeException))]
[InlineData("Abcd", -1, 3, "Abc", true, typeof(ArgumentOutOfRangeException))]
[InlineData("Abcd", 0, 1, "A", true, true)]
[InlineData("Abcd", 0, 4, "Abcd", true, true)]
[InlineData("Abcd", 0, 3, "Abc", true, true)]
[InlineData("Abcd", 0, 5, "Abcd", true, typeof(ArgumentOutOfRangeException))]
[InlineData("Abcd", 1, 3, "bcd", true, true)]
[InlineData("Abcd", 1, 5, "bcd", true, typeof(ArgumentOutOfRangeException))]
[InlineData("Abcd", 2, 1, "c", true, true)]
[InlineData("Abcd", 3, 1, "d", true, true)]
[InlineData("Abcd", 4, 1, "", true, typeof(ArgumentOutOfRangeException))]
[InlineData("Abcd", 0, -1, "", true, typeof(ArgumentOutOfRangeException))]
[InlineData("Abcd", 5, -1, "", true, typeof(ArgumentOutOfRangeException))]
public void StringSubstringStartAndLength(string productName, int startIndex, int length, string compareString, bool withNullPropagation, object withoutNullPropagation)
{
string filter = String.Format("substring(ProductName, {0}, {1}) eq '{2}'", startIndex, length, compareString);
var filters = VerifyQueryDeserialization(filter);
RunFilters(filters,
new Product { ProductName = productName },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, false, typeof(NullReferenceException))]
[InlineData("Abcd", true, true)]
[InlineData("Abd", false, false)]
public void StringSubstringOf(string productName, bool withNullPropagation, object withoutNullPropagation)
{
// In OData, the order of parameters is actually reversed in the resulting
// String.Contains expression
var filters = VerifyQueryDeserialization(
"contains(ProductName, 'Abc')",
"$it => $it.ProductName.Contains(\"Abc\")",
NotTesting);
RunFilters(filters,
new Product { ProductName = productName },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
filters = VerifyQueryDeserialization(
"contains(ProductName, 'Abc')",
"$it => $it.ProductName.Contains(\"Abc\")",
NotTesting);
}
[Theory]
[InlineData(null, false, typeof(NullReferenceException))]
[InlineData("Abcd", true, true)]
[InlineData("Abd", false, false)]
public void StringStartsWith(string productName, bool withNullPropagation, object withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"startswith(ProductName, 'Abc')",
"$it => $it.ProductName.StartsWith(\"Abc\")",
NotTesting);
RunFilters(filters,
new Product { ProductName = productName },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, false, typeof(NullReferenceException))]
[InlineData("AAbc", true, true)]
[InlineData("Abcd", false, false)]
public void StringEndsWith(string productName, bool withNullPropagation, object withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"endswith(ProductName, 'Abc')",
"$it => $it.ProductName.EndsWith(\"Abc\")",
NotTesting);
RunFilters(filters,
new Product { ProductName = productName },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, false, typeof(NullReferenceException))]
[InlineData("AAbc", true, true)]
[InlineData("", false, false)]
public void StringLength(string productName, bool withNullPropagation, object withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"length(ProductName) gt 0",
"$it => ($it.ProductName.Length > 0)",
"$it => ((IIF(($it.ProductName == null), null, Convert($it.ProductName.Length)) > Convert(0)) == True)");
RunFilters(filters,
new Product { ProductName = productName },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, false, typeof(NullReferenceException))]
[InlineData("12345Abc", true, true)]
[InlineData("1234Abc", false, false)]
public void StringIndexOf(string productName, bool withNullPropagation, object withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"indexof(ProductName, 'Abc') eq 5",
"$it => ($it.ProductName.IndexOf(\"Abc\") == 5)",
NotTesting);
RunFilters(filters,
new Product { ProductName = productName },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, false, typeof(NullReferenceException))]
[InlineData("123uctName", true, true)]
[InlineData("1234Abc", false, false)]
public void StringSubstring(string productName, bool withNullPropagation, object withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"substring(ProductName, 3) eq 'uctName'",
"$it => ($it.ProductName.Substring(3) == \"uctName\")",
NotTesting);
RunFilters(filters,
new Product { ProductName = productName },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
VerifyQueryDeserialization(
"substring(ProductName, 3, 4) eq 'uctN'",
"$it => ($it.ProductName.Substring(3, 4) == \"uctN\")",
NotTesting);
}
[Theory]
[InlineData(null, false, typeof(NullReferenceException))]
[InlineData("Tasty Treats", true, true)]
[InlineData("Tasty Treatss", false, false)]
public void StringToLower(string productName, bool withNullPropagation, object withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"tolower(ProductName) eq 'tasty treats'",
"$it => ($it.ProductName.ToLower() == \"tasty treats\")",
NotTesting);
RunFilters(filters,
new Product { ProductName = productName },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, false, typeof(NullReferenceException))]
[InlineData("Tasty Treats", true, true)]
[InlineData("Tasty Treatss", false, false)]
public void StringToUpper(string productName, bool withNullPropagation, object withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"toupper(ProductName) eq 'TASTY TREATS'",
"$it => ($it.ProductName.ToUpper() == \"TASTY TREATS\")",
NotTesting);
RunFilters(filters,
new Product { ProductName = productName },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, false, typeof(NullReferenceException))]
[InlineData("Tasty Treats", true, true)]
[InlineData("Tasty Treatss", false, false)]
public void StringTrim(string productName, bool withNullPropagation, object withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"trim(ProductName) eq 'Tasty Treats'",
"$it => ($it.ProductName.Trim() == \"Tasty Treats\")",
NotTesting);
RunFilters(filters,
new Product { ProductName = productName },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Fact]
public void StringConcat()
{
var filters = VerifyQueryDeserialization(
"concat('Food', 'Bar') eq 'FoodBar'",
"$it => (\"Food\".Concat(\"Bar\") == \"FoodBar\")",
NotTesting);
RunFilters(filters,
new Product { },
new { WithNullPropagation = true, WithoutNullPropagation = true });
}
[Fact]
public void RecursiveMethodCall()
{
var filters = VerifyQueryDeserialization(
"floor(floor(UnitPrice)) eq 123m",
"$it => ($it.UnitPrice.Value.Floor().Floor() == 123)",
NotTesting);
RunFilters(filters,
new Product { },
new { WithNullPropagation = false, WithoutNullPropagation = typeof(InvalidOperationException) });
}
#endregion
#region Date Functions
[Fact]
public void DateDay()
{
var filters = VerifyQueryDeserialization(
"day(DiscontinuedDate) eq 8",
"$it => ($it.DiscontinuedDate.Value.Day == 8)",
NotTesting);
RunFilters(filters,
new Product { },
new { WithNullPropagation = false, WithoutNullPropagation = typeof(InvalidOperationException) });
RunFilters(filters,
new Product { DiscontinuedDate = new DateTime(2000, 10, 8) },
new { WithNullPropagation = true, WithoutNullPropagation = true });
}
public void DateDayNonNullable()
{
VerifyQueryDeserialization(
"day(NonNullableDiscontinuedDate) eq 8",
"$it => ($it.NonNullableDiscontinuedDate.Day == 8)");
}
[Fact]
public void DateMonth()
{
VerifyQueryDeserialization(
"month(DiscontinuedDate) eq 8",
"$it => ($it.DiscontinuedDate.Value.Month == 8)",
NotTesting);
}
[Fact]
public void DateYear()
{
VerifyQueryDeserialization(
"year(DiscontinuedDate) eq 1974",
"$it => ($it.DiscontinuedDate.Value.Year == 1974)",
NotTesting);
}
[Fact]
public void DateHour()
{
VerifyQueryDeserialization("hour(DiscontinuedDate) eq 8",
"$it => ($it.DiscontinuedDate.Value.Hour == 8)",
NotTesting);
}
[Fact]
public void DateMinute()
{
VerifyQueryDeserialization(
"minute(DiscontinuedDate) eq 12",
"$it => ($it.DiscontinuedDate.Value.Minute == 12)",
NotTesting);
}
[Fact]
public void DateSecond()
{
VerifyQueryDeserialization(
"second(DiscontinuedDate) eq 33",
"$it => ($it.DiscontinuedDate.Value.Second == 33)",
NotTesting);
}
[Theory]
[InlineData("year(DiscontinuedOffset) eq 100", "$it => ($it.DiscontinuedOffset.Year == 100)")]
[InlineData("month(DiscontinuedOffset) eq 100", "$it => ($it.DiscontinuedOffset.Month == 100)")]
[InlineData("day(DiscontinuedOffset) eq 100", "$it => ($it.DiscontinuedOffset.Day == 100)")]
[InlineData("hour(DiscontinuedOffset) eq 100", "$it => ($it.DiscontinuedOffset.Hour == 100)")]
[InlineData("minute(DiscontinuedOffset) eq 100", "$it => ($it.DiscontinuedOffset.Minute == 100)")]
[InlineData("second(DiscontinuedOffset) eq 100", "$it => ($it.DiscontinuedOffset.Second == 100)")]
public void DateTimeOffsetFunctions(string filter, string expression)
{
VerifyQueryDeserialization(filter, expression);
}
[Theory]
[InlineData("years(DiscontinuedSince) eq 100", "$it => $it.DiscontinuedSince.Years == 100")]
[InlineData("months(DiscontinuedSince) eq 100", "$it => $it.DiscontinuedSince.Months == 100")]
[InlineData("days(DiscontinuedSince) eq 100", "$it => $it.DiscontinuedSince.Days == 100")]
[InlineData("hours(DiscontinuedSince) eq 100", "$it => $it.DiscontinuedSince.Hours == 100")]
[InlineData("minutes(DiscontinuedSince) eq 100", "$it => $it.DiscontinuedSince.Minutes == 100")]
[InlineData("seconds(DiscontinuedSince) eq 100", "$it => $it.DiscontinuedSince.Seconds == 100")]
public void TimespanFunctions(string filter, string expression)
{
// There's currently a bug here. For now, the test checks for the presence of the bug (as a reminder to fix
// the test once the bug is fixed).
// The following assert shows the behavior with the bug and should be removed once the bug is fixed.
Assert.Throws<ODataException>(() => Bind(filter));
// TODO: Timespans are not handled well in the uri parser
// The following call shows the behavior without the bug, and should be enabled once the bug is fixed.
//VerifyQueryDeserialization(filter, expression);
}
#endregion
#region Math Functions
[Theory, PropertyData("MathRoundDecimal_DataSet")]
public void MathRoundDecimal(decimal? unitPrice, bool withNullPropagation, object withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"round(UnitPrice) gt 5.00m",
Error.Format("$it => ($it.UnitPrice.Value.Round() > {0:0.00})", 5.0),
NotTesting);
RunFilters(filters,
new Product { UnitPrice = ToNullable<decimal>(unitPrice) },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, false, typeof(InvalidOperationException))]
[InlineData(5.9d, true, true)]
[InlineData(5.4d, false, false)]
public void MathRoundDouble(double? weight, bool withNullPropagation, object withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"round(Weight) gt 5d",
Error.Format("$it => ($it.Weight.Value.Round() > {0})", 5),
NotTesting);
RunFilters(filters,
new Product { Weight = ToNullable<double>(weight) },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, false, typeof(InvalidOperationException))]
[InlineData(5.9f, true, true)]
[InlineData(5.4f, false, false)]
public void MathRoundFloat(float? width, bool withNullPropagation, object withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"round(Width) gt 5f",
Error.Format("$it => (Convert($it.Width).Value.Round() > {0})", 5),
NotTesting);
RunFilters(filters,
new Product { Width = ToNullable<float>(width) },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, false, typeof(InvalidOperationException))]
[InlineData(5.4, true, true)]
[InlineData(4.4, false, false)]
public void MathFloor(object unitPrice, bool withNullPropagation, object withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"floor(UnitPrice) eq 5m",
"$it => ($it.UnitPrice.Value.Floor() == 5)",
NotTesting);
RunFilters(filters,
new Product { UnitPrice = ToNullable<decimal>(unitPrice) },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData(null, false, typeof(InvalidOperationException))]
[InlineData(4.1, true, true)]
[InlineData(5.9, false, false)]
public void MathCeiling(object unitPrice, bool withNullPropagation, object withoutNullPropagation)
{
var filters = VerifyQueryDeserialization(
"ceiling(UnitPrice) eq 5m",
"$it => ($it.UnitPrice.Value.Ceiling() == 5)",
NotTesting);
RunFilters(filters,
new Product { UnitPrice = ToNullable<decimal>(unitPrice) },
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData("floor(FloatProp) eq floor(FloatProp)")]
[InlineData("round(FloatProp) eq round(FloatProp)")]
[InlineData("ceiling(FloatProp) eq ceiling(FloatProp)")]
[InlineData("floor(DoubleProp) eq floor(DoubleProp)")]
[InlineData("round(DoubleProp) eq round(DoubleProp)")]
[InlineData("ceiling(DoubleProp) eq ceiling(DoubleProp)")]
[InlineData("floor(DecimalProp) eq floor(DecimalProp)")]
[InlineData("round(DecimalProp) eq round(DecimalProp)")]
[InlineData("ceiling(DecimalProp) eq ceiling(DecimalProp)")]
public void MathFunctions_VariousTypes(string filter)
{
var filters = VerifyQueryDeserialization<DataTypes>(filter);
RunFilters(filters, new DataTypes(), new { WithNullPropagation = true, WithoutNullPropagation = true });
}
#endregion
#region Data Types
[Fact]
public void GuidExpression()
{
VerifyQueryDeserialization<DataTypes>(
"GuidProp eq 0EFDAECF-A9F0-42F3-A384-1295917AF95E",
"$it => ($it.GuidProp == 0efdaecf-a9f0-42f3-a384-1295917af95e)");
// verify case insensitivity
VerifyQueryDeserialization<DataTypes>(
"GuidProp eq 0EFDAECF-A9F0-42F3-A384-1295917AF95E",
"$it => ($it.GuidProp == 0efdaecf-a9f0-42f3-a384-1295917af95e)");
}
[Theory]
[InlineData("DateTimeProp eq 2000-12-12T12:00:00Z", "$it => ($it.DateTimeProp == {0})")]
[InlineData("DateTimeProp lt 2000-12-12T12:00:00Z", "$it => ($it.DateTimeProp < {0})")]
// TODO: [InlineData("DateTimeProp ge datetime'2000-12-12T12:00'", "$it => ($it.DateTimeProp >= {0})")] (uriparser fails on optional seconds)
public void DateTimeExpression(string clause, string expectedExpression)
{
var dateTime = new DateTimeOffset(new DateTime(2000, 12, 12, 12, 0, 0), TimeSpan.Zero);
VerifyQueryDeserialization<DataTypes>(
"" + clause,
Error.Format(expectedExpression, dateTime));
}
[Theory]
[InlineData("DateTimeOffsetProp eq datetimeoffset'2002-10-10T17:00:00Z'", "$it => ($it.DateTimeOffsetProp == {0})", 0)]
[InlineData("DateTimeOffsetProp ge datetimeoffset'2002-10-10T17:00:00Z'", "$it => ($it.DateTimeOffsetProp >= {0})", 0)]
[InlineData("DateTimeOffsetProp le datetimeoffset'2002-10-10T17:00:00-07:00'", "$it => ($it.DateTimeOffsetProp <= {0})", -7)]
[InlineData("DateTimeOffsetProp eq datetimeoffset'2002-10-10T17:00:00-0600'", "$it => ($it.DateTimeOffsetProp == {0})", -6)]
[InlineData("DateTimeOffsetProp lt datetimeoffset'2002-10-10T17:00:00-05'", "$it => ($it.DateTimeOffsetProp < {0})", -5)]
[InlineData("DateTimeOffsetProp ne datetimeoffset'2002-10-10T17:00:00%2B09:30'", "$it => ($it.DateTimeOffsetProp != {0})", 9.5)]
[InlineData("DateTimeOffsetProp gt datetimeoffset'2002-10-10T17:00:00%2B0545'", "$it => ($it.DateTimeOffsetProp > {0})", 5.75)]
public void DateTimeOffsetExpression(string clause, string expectedExpression, double offsetHours)
{
var dateTimeOffset = new DateTimeOffset(2002, 10, 10, 17, 0, 0, TimeSpan.FromHours(offsetHours));
// There's currently a bug here. For now, the test checks for the presence of the bug (as a reminder to fix
// the test once the bug is fixed).
// The following assert shows the behavior with the bug and should be removed once the bug is fixed.
Assert.Throws<ODataException>(() => Bind("" + clause));
// TODO: No DateTimeOffset parsing in ODataUriParser
// The following call shows the behavior without the bug, and should be enabled once the bug is fixed.
//VerifyQueryDeserialization<DataTypes>(
// "" + clause,
// Error.Format(expectedExpression, dateTimeOffset));
}
[Fact]
public void IntegerLiteralSuffix()
{
// long L
VerifyQueryDeserialization<DataTypes>(
"LongProp lt 987654321L and LongProp gt 123456789l",
"$it => (($it.LongProp < 987654321) AndAlso ($it.LongProp > 123456789))");
VerifyQueryDeserialization<DataTypes>(
"LongProp lt -987654321L and LongProp gt -123456789l",
"$it => (($it.LongProp < -987654321) AndAlso ($it.LongProp > -123456789))");
}
[Fact]
public void RealLiteralSuffixes()
{
// Float F
VerifyQueryDeserialization<DataTypes>(
"FloatProp lt 4321.56F and FloatProp gt 1234.56f",
Error.Format("$it => (($it.FloatProp < {0:0.00}) AndAlso ($it.FloatProp > {1:0.00}))", 4321.56, 1234.56));
// Decimal M
VerifyQueryDeserialization<DataTypes>(
"DecimalProp lt 4321.56M and DecimalProp gt 1234.56m",
Error.Format("$it => (($it.DecimalProp < {0:0.00}) AndAlso ($it.DecimalProp > {1:0.00}))", 4321.56, 1234.56));
}
[Theory]
[InlineData("'hello,world'", "hello,world")]
[InlineData("'''hello,world'", "'hello,world")]
[InlineData("'hello,world'''", "hello,world'")]
[InlineData("'hello,''wor''ld'", "hello,'wor'ld")]
[InlineData("'hello,''''''world'", "hello,'''world")]
[InlineData("'\"hello,world\"'", "\"hello,world\"")]
[InlineData("'\"hello,world'", "\"hello,world")]
[InlineData("'hello,world\"'", "hello,world\"")]
[InlineData("'hello,\"world'", "hello,\"world")]
[InlineData("'México D.F.'", "México D.F.")]
[InlineData("'æææøøøååå'", "æææøøøååå")]
[InlineData("'いくつかのテキスト'", "いくつかのテキスト")]
public void StringLiterals(string literal, string expected)
{
VerifyQueryDeserialization<Product>(
"ProductName eq " + literal,
String.Format("$it => ($it.ProductName == \"{0}\")", expected));
}
[Theory]
[InlineData('$')]
[InlineData('&')]
[InlineData('+')]
[InlineData(',')]
[InlineData('/')]
[InlineData(':')]
[InlineData(';')]
[InlineData('=')]
[InlineData('?')]
[InlineData('@')]
[InlineData(' ')]
[InlineData('<')]
[InlineData('>')]
[InlineData('#')]
[InlineData('%')]
[InlineData('{')]
[InlineData('}')]
[InlineData('|')]
[InlineData('\\')]
[InlineData('^')]
[InlineData('~')]
[InlineData('[')]
[InlineData(']')]
[InlineData('`')]
public void SpecialCharactersInStringLiteral(char c)
{
var filters = VerifyQueryDeserialization<Product>(
"ProductName eq '" + c + "'",
String.Format("$it => ($it.ProductName == \"{0}\")", c));
RunFilters(
filters,
new Product { ProductName = c.ToString() },
new { WithNullPropagation = true, WithoutNullPropagation = true });
}
#endregion
#region Casts
[Fact]
public void NSCast_OnEnumerableEntityCollection_GeneratesExpression_WithOfTypeOnEnumerable()
{
var filters = VerifyQueryDeserialization(
"Category/EnumerableProducts/System.Web.OData.Query.Expressions.DerivedProduct/any(p: p/ProductName eq 'ProductName')",
"$it => $it.Category.EnumerableProducts.OfType().Any(p => (p.ProductName == \"ProductName\"))",
NotTesting);
Assert.NotNull(filters.WithoutNullPropagation);
}
[Fact]
public void NSCast_OnQueryableEntityCollection_GeneratesExpression_WithOfTypeOnQueryable()
{
var filters = VerifyQueryDeserialization(
"Category/QueryableProducts/System.Web.OData.Query.Expressions.DerivedProduct/any(p: p/ProductName eq 'ProductName')",
"$it => $it.Category.QueryableProducts.OfType().Any(p => (p.ProductName == \"ProductName\"))",
NotTesting);
}
[Fact]
public void NSCast_OnEntityCollection_CanAccessDerivedInstanceProperty()
{
var filters = VerifyQueryDeserialization(
"Category/Products/System.Web.OData.Query.Expressions.DerivedProduct/any(p: p/DerivedProductName eq 'DerivedProductName')");
RunFilters(
filters,
new Product { Category = new Category { Products = new Product[] { new DerivedProduct { DerivedProductName = "DerivedProductName" } } } },
new { WithNullPropagation = true, WithoutNullPropagation = true });
RunFilters(
filters,
new Product { Category = new Category { Products = new Product[] { new DerivedProduct { DerivedProductName = "NotDerivedProductName" } } } },
new { WithNullPropagation = false, WithoutNullPropagation = false });
}
[Fact]
public void NSCast_OnSingleEntity_GeneratesExpression_WithAsOperator()
{
var filters = VerifyQueryDeserialization(
"System.Web.OData.Query.Expressions.Product/ProductName eq 'ProductName'",
"$it => (($it As Product).ProductName == \"ProductName\")",
NotTesting);
}
[Theory]
[InlineData("System.Web.OData.Query.Expressions.Product/ProductName eq 'ProductName'")]
[InlineData("System.Web.OData.Query.Expressions.DerivedProduct/DerivedProductName eq 'DerivedProductName'")]
[InlineData("System.Web.OData.Query.Expressions.DerivedProduct/Category/CategoryID eq 123")]
[InlineData("System.Web.OData.Query.Expressions.DerivedProduct/Category/System.Web.OData.Query.Expressions.DerivedCategory/CategoryID eq 123")]
public void Inheritance_WithDerivedInstance(string filter)
{
var filters = VerifyQueryDeserialization<DerivedProduct>(filter);
RunFilters<DerivedProduct>(filters,
new DerivedProduct { Category = new DerivedCategory { CategoryID = 123 }, ProductName = "ProductName", DerivedProductName = "DerivedProductName" },
new { WithNullPropagation = true, WithoutNullPropagation = true });
}
[Theory]
[InlineData("System.Web.OData.Query.Expressions.DerivedProduct/DerivedProductName eq 'ProductName'")]
[InlineData("System.Web.OData.Query.Expressions.DerivedProduct/Category/CategoryID eq 123")]
[InlineData("System.Web.OData.Query.Expressions.DerivedProduct/Category/System.Web.OData.Query.Expressions.DerivedCategory/CategoryID eq 123")]
public void Inheritance_WithBaseInstance(string filter)
{
var filters = VerifyQueryDeserialization<Product>(filter);
RunFilters<Product>(filters,
new Product(),
new { WithNullPropagation = false, WithoutNullPropagation = typeof(NullReferenceException) });
}
[Fact]
public void CastToNonDerivedType_Throws()
{
Assert.Throws<ODataException>(
() => VerifyQueryDeserialization<Product>("System.Web.OData.Query.Expressions.DerivedCategory/CategoryID eq 123"),
"Encountered invalid type cast. 'System.Web.OData.Query.Expressions.DerivedCategory' is not assignable from 'System.Web.OData.Query.Expressions.Product'.");
}
[Theory]
[InlineData("Edm.Int32 eq 123", "The child type 'Edm.Int32' in a cast was not an entity type. Casts can only be performed on entity types.")]
[InlineData("ProductName/Edm.String eq 123", "Can only bind segments that are Navigation, Structural, Complex, or Collections. We found a segment " +
"'ProductName' that isn't any of those. Please revise the query.")]
public void CastToNonEntityType_Throws(string filter, string error)
{
Assert.Throws<ODataException>(
() => VerifyQueryDeserialization<Product>(filter), error);
}
[Theory]
[InlineData("Edm.NonExistentType eq 123")]
[InlineData("Category/Edm.NonExistentType eq 123")]
[InlineData("Category/Products/Edm.NonExistentType eq 123")]
public void CastToNonExistantType_Throws(string filter)
{
Assert.Throws<ODataException>(
() => VerifyQueryDeserialization<Product>(filter),
"The child type 'Edm.NonExistentType' in a cast was not an entity type. Casts can only be performed on entity types.");
}
#endregion
[Theory]
[InlineData("UShortProp eq 12", "$it => (Convert($it.UShortProp) == 12)")]
[InlineData("ULongProp eq 12L", "$it => (Convert($it.ULongProp) == 12)")]
[InlineData("UIntProp eq 12", "$it => (Convert($it.UIntProp) == 12)")]
[InlineData("CharProp eq 'a'", "$it => (Convert($it.CharProp.ToString()) == \"a\")")]
[InlineData("CharArrayProp eq 'a'", "$it => (new String($it.CharArrayProp) == \"a\")")]
[InlineData("BinaryProp eq binary'23ABFF'", "$it => ($it.BinaryProp.ToArray() == System.Byte[])")]
[InlineData("XElementProp eq '<name />'", "$it => ($it.XElementProp.ToString() == \"<name />\")")]
public void NonstandardEdmPrimtives(string filter, string expression)
{
var filters = VerifyQueryDeserialization<DataTypes>(filter, expression, NotTesting);
RunFilters(filters,
new DataTypes
{
UShortProp = 12,
ULongProp = 12,
UIntProp = 12,
CharProp = 'a',
CharArrayProp = new[] { 'a' },
BinaryProp = new Binary(new byte[] { 35, 171, 255 }),
XElementProp = new XElement("name")
},
new { WithNullPropagation = true, WithoutNullPropagation = true });
}
[Theory]
[InlineData("BinaryProp eq binary'23ABFF'", "$it => ($it.BinaryProp.ToArray() == System.Byte[])", true, true)]
[InlineData("BinaryProp ne binary'23ABFF'", "$it => ($it.BinaryProp.ToArray() != System.Byte[])", false, false)]
[InlineData("ByteArrayProp eq binary'23ABFF'", "$it => ($it.ByteArrayProp == System.Byte[])", true, true)]
[InlineData("ByteArrayProp ne binary'23ABFF'", "$it => ($it.ByteArrayProp != System.Byte[])", false, false)]
[InlineData("binary'23ABFF' eq binary'23ABFF'", "$it => (System.Byte[] == System.Byte[])", true, true)]
[InlineData("binary'23ABFF' ne binary'23ABFF'", "$it => (System.Byte[] != System.Byte[])", false, false)]
[InlineData("ByteArrayPropWithNullValue ne binary'23ABFF'", "$it => ($it.ByteArrayPropWithNullValue != System.Byte[])", true, true)]
[InlineData("ByteArrayPropWithNullValue ne ByteArrayPropWithNullValue", "$it => ($it.ByteArrayPropWithNullValue != $it.ByteArrayPropWithNullValue)", false, false)]
[InlineData("ByteArrayPropWithNullValue ne null", "$it => ($it.ByteArrayPropWithNullValue != null)", false, false)]
[InlineData("ByteArrayPropWithNullValue eq null", "$it => ($it.ByteArrayPropWithNullValue == null)", true, true)]
[InlineData("null ne ByteArrayPropWithNullValue", "$it => (null != $it.ByteArrayPropWithNullValue)", false, false)]
[InlineData("null eq ByteArrayPropWithNullValue", "$it => (null == $it.ByteArrayPropWithNullValue)", true, true)]
public void ByteArrayComparisons(string filter, string expression, bool withNullPropagation, object withoutNullPropagation)
{
var filters = VerifyQueryDeserialization<DataTypes>(filter, expression, NotTesting);
RunFilters(filters,
new DataTypes
{
BinaryProp = new Binary(new byte[] { 35, 171, 255 }),
ByteArrayProp = new byte[] { 35, 171, 255 }
},
new { WithNullPropagation = withNullPropagation, WithoutNullPropagation = withoutNullPropagation });
}
[Theory]
[InlineData("binary'23ABFF' ge binary'23ABFF'", "GreaterThanOrEqual")]
[InlineData("binary'23ABFF' le binary'23ABFF'", "LessThanOrEqual")]
[InlineData("binary'23ABFF' lt binary'23ABFF'", "LessThan")]
[InlineData("binary'23ABFF' gt binary'23ABFF'", "GreaterThan")]
[InlineData("binary'23ABFF' add binary'23ABFF'", "Add")]
[InlineData("binary'23ABFF' sub binary'23ABFF'", "Subtract")]
[InlineData("binary'23ABFF' mul binary'23ABFF'", "Multiply")]
[InlineData("binary'23ABFF' div binary'23ABFF'", "Divide")]
public void DisAllowed_ByteArrayComparisons(string filter, string op)
{
Assert.Throws<ODataException>(
() => Bind<DataTypes>(filter),
Error.Format("A binary operator with incompatible types was detected. Found operand types 'Edm.Binary' and 'Edm.Binary' for operator kind '{0}'.", op));
}
[Theory]
[InlineData("NullableUShortProp eq 12", "$it => (Convert($it.NullableUShortProp.Value) == Convert(12))")]
[InlineData("NullableULongProp eq 12L", "$it => (Convert($it.NullableULongProp.Value) == Convert(12))")]
[InlineData("NullableUIntProp eq 12", "$it => (Convert($it.NullableUIntProp.Value) == Convert(12))")]
[InlineData("NullableCharProp eq 'a'", "$it => ($it.NullableCharProp.Value.ToString() == \"a\")")]
public void Nullable_NonstandardEdmPrimitives(string filter, string expression)
{
var filters = VerifyQueryDeserialization<DataTypes>(filter, expression, NotTesting);
RunFilters(filters,
new DataTypes(),
new { WithNullPropagation = false, WithoutNullPropagation = typeof(InvalidOperationException) });
}
[Fact]
public void MultipleConstants_Are_Parameterized()
{
VerifyQueryDeserialization("ProductName eq '1' or ProductName eq '2' or ProductName eq '3' or ProductName eq '4'",
"$it => (((($it.ProductName == \"1\") OrElse ($it.ProductName == \"2\")) OrElse ($it.ProductName == \"3\")) OrElse ($it.ProductName == \"4\"))",
NotTesting);
}
[Fact]
public void Constants_Are_Not_Parameterized_IfDisabled()
{
var filters = VerifyQueryDeserialization("ProductName eq '1'", settingsCustomizer: (settings) =>
{
settings.EnableConstantParameterization = false;
});
Assert.Equal("$it => ($it.ProductName == \"1\")", (filters.WithoutNullPropagation as Expression).ToString());
}
#region Negative Tests
[Fact]
public void TypeMismatchInComparison()
{
Assert.Throws<ODataException>(() => Bind("length(123) eq 12"));
}
#endregion
private Expression<Func<Product, bool>> Bind(string filter, ODataQuerySettings querySettings = null)
{
return Bind<Product>(filter, querySettings);
}
private Expression<Func<T, bool>> Bind<T>(string filter, ODataQuerySettings querySettings = null) where T : class
{
IEdmModel model = GetModel<T>();
FilterClause filterNode = CreateFilterNode(filter, model, typeof(T));
if (querySettings == null)
{
querySettings = CreateSettings();
}
return Bind<T>(filterNode, model, CreateFakeAssembliesResolver(), querySettings);
}
private static Expression<Func<TEntityType, bool>> Bind<TEntityType>(FilterClause filterNode, IEdmModel model, IAssembliesResolver assembliesResolver, ODataQuerySettings querySettings)
{
return FilterBinder.Bind<TEntityType>(filterNode, model, assembliesResolver, querySettings);
}
private IAssembliesResolver CreateFakeAssembliesResolver()
{
return new NoAssembliesResolver();
}
private FilterClause CreateFilterNode(string filter, IEdmModel model, Type entityType)
{
var queryUri = new Uri(_serviceBaseUri, String.Format("Products?$filter={0}", Uri.EscapeDataString(filter)));
IEdmEntityType productType = model.SchemaElements.OfType<IEdmEntityType>().Single(t => t.Name == entityType.Name);
return ODataUriParser.ParseFilter(filter, model, productType);
}
private static ODataQuerySettings CreateSettings()
{
return new ODataQuerySettings
{
HandleNullPropagation = HandleNullPropagationOption.False // A value other than Default is required for calls to Bind.
};
}
private void RunFilters<T>(dynamic filters, T product, dynamic expectedValue)
{
var filterWithNullPropagation = filters.WithNullPropagation as Expression<Func<T, bool>>;
if (expectedValue.WithNullPropagation is Type)
{
Assert.Throws(expectedValue.WithNullPropagation as Type, () => RunFilter(filterWithNullPropagation, product));
}
else
{
Assert.Equal(RunFilter(filterWithNullPropagation, product), expectedValue.WithNullPropagation);
}
var filterWithoutNullPropagation = filters.WithoutNullPropagation as Expression<Func<T, bool>>;
if (expectedValue.WithoutNullPropagation is Type)
{
Assert.Throws(expectedValue.WithoutNullPropagation as Type, () => RunFilter(filterWithoutNullPropagation, product));
}
else
{
Assert.Equal(RunFilter(filterWithoutNullPropagation, product), expectedValue.WithoutNullPropagation);
}
}
private bool RunFilter<T>(Expression<Func<T, bool>> filter, T instance)
{
return filter.Compile().Invoke(instance);
}
private dynamic VerifyQueryDeserialization(string filter, string expectedResult = null, string expectedResultWithNullPropagation = null, Action<ODataQuerySettings> settingsCustomizer = null)
{
return VerifyQueryDeserialization<Product>(filter, expectedResult, expectedResultWithNullPropagation, settingsCustomizer);
}
private dynamic VerifyQueryDeserialization<T>(string filter, string expectedResult = null, string expectedResultWithNullPropagation = null, Action<ODataQuerySettings> settingsCustomizer = null) where T : class
{
IEdmModel model = GetModel<T>();
FilterClause filterNode = CreateFilterNode(filter, model, typeof(T));
IAssembliesResolver assembliesResolver = CreateFakeAssembliesResolver();
Func<ODataQuerySettings, ODataQuerySettings> customizeSettings = (settings) =>
{
if (settingsCustomizer != null)
{
settingsCustomizer.Invoke(settings);
}
return settings;
};
var filterExpr = Bind<T>(
filterNode,
model,
assembliesResolver,
customizeSettings(new ODataQuerySettings { HandleNullPropagation = HandleNullPropagationOption.False }));
if (!String.IsNullOrEmpty(expectedResult))
{
VerifyExpression(filterExpr, expectedResult);
}
expectedResultWithNullPropagation = expectedResultWithNullPropagation ?? expectedResult;
var filterExprWithNullPropagation = Bind<T>(
filterNode,
model,
assembliesResolver,
customizeSettings(new ODataQuerySettings { HandleNullPropagation = HandleNullPropagationOption.True }));
if (!String.IsNullOrEmpty(expectedResultWithNullPropagation))
{
VerifyExpression(filterExprWithNullPropagation, expectedResultWithNullPropagation ?? expectedResult);
}
return new
{
WithNullPropagation = filterExprWithNullPropagation,
WithoutNullPropagation = filterExpr
};
}
private void VerifyExpression(Expression filter, string expectedExpression)
{
// strip off the beginning part of the expression to get to the first
// actual query operator
string resultExpression = ExpressionStringBuilder.ToString(filter);
Assert.True(resultExpression == expectedExpression,
String.Format("Expected expression '{0}' but the deserializer produced '{1}'", expectedExpression, resultExpression));
}
private IEdmModel GetModel<T>() where T : class
{
Type key = typeof(T);
IEdmModel value;
if (!_modelCache.TryGetValue(key, out value))
{
ODataModelBuilder model = new ODataConventionModelBuilder();
model.EntitySet<T>("Products");
value = _modelCache[key] = model.GetEdmModel();
}
return value;
}
private T? ToNullable<T>(object value) where T : struct
{
return value == null ? null : (T?)Convert.ChangeType(value, typeof(T));
}
private class NoAssembliesResolver : IAssembliesResolver
{
public ICollection<Assembly> GetAssemblies()
{
return new Assembly[0];
}
}
}
}
| 44.978184 | 217 | 0.581794 | [
"Apache-2.0"
] | dotnetwise/aspnetwebstack | test/System.Web.OData.Test/OData/Query/Expressions/FilterBinderTests.cs | 76,339 | C# |
/**
* MapMarker extends Map
*
* Supports the graphical tasks involved that Map methods can not manage, because it is a higher level class.
*
*
* */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;
using Debug = UnityEngine.Debug;
public class MapMarker : Map {
protected List<List<MapPointMarker>> clusterMarkers = new List<List<MapPointMarker> >();
protected List<List<OnlineMapsDrawingLine>> clusterLines = new List<List<OnlineMapsDrawingLine>> ();
//protected List<OnlineMapsDrawingLine> quadsDrawed = new List<OnlineMapsDrawingLine>();
List<Vector2> pointsBase=null;
protected Hashtable connectionsLinesPerLevel = new Hashtable();
private bool drawTheClustersQuad = false;
public GameObject clusterPrefab;
public GameObject customMarkerGameObject;
public Canvas customMarkerCanvas;
public Sprite customGroupPointMarker;
private List<MarkerInstance> markers = new List<MarkerInstance>();
private Canvas canvas;
private OnlineMapsTileSetControl control;
public bool resetted = false;
public MapMarker()
{
OnlineMapsControlBase.instance.OnMapClick += OnMapClick;
OnlineMaps.instance.OnChangePosition += showClusters;
OnlineMaps.instance.OnChangeZoom += OnMapUpdateZoom;
control = OnlineMapsTileSetControl.instance;
//canvas = container.GetComponentInParent<Canvas>();
}
private Camera worldCamera
{
get
{
if (canvas.renderMode == RenderMode.ScreenSpaceOverlay) return null;
return canvas.worldCamera;
}
}
public void OnMapUpdated()
{
//SilkMap.instance.refreshStack();
//if (markers!=null)
// UpdateMarkers();
}
public void OnMapUpdateZoom()
{
this.setViewerZoom(OnlineMaps.instance.zoom);
}
public List<MapPointMarker> getVisiblePoints()
{
List<MapPointMarker> visiblePoints = new List<MapPointMarker>();
int levelMap = 0;
foreach (MapPointMarker point in this.GetPoints())
if (point.isVisible() && areCoordinatesOnMap(point.getX(), point.getY()))
visiblePoints.Add(point);
for (levelMap=0; levelMap < this.clusterManager.getNumLevels(); levelMap++)
{
foreach (MapPointMarker clusterPoint in this.getClusterMarkersAtLevel(levelMap))
{
if (clusterPoint.isVisible() && areCoordinatesOnMap(clusterPoint.getX(), clusterPoint.getY()))
visiblePoints.Add(clusterPoint);
}
}
foreach (GridCluster gc in this.clusterManager.getPointGroupClusters())
if (gc.getCenter().isVisible() && areCoordinatesOnMap(gc.getCenter().getX(), gc.getCenter().getY()))
visiblePoints.Add((MapPointMarker)gc.getCenter());
return visiblePoints;
}
public List<string> getSceneValuesOfProperty(string propertyName)
{
List<string> valuesOfProperty = new List<string>();
foreach (MapPointMarker pointMarker in getVisiblePoints())
if (pointMarker.isCluster() || pointMarker.isGroupPoint())
{
foreach (MapPointMarker pointMarkerCluster in pointMarker.getClusteredPoints())
{
var values = pointMarkerCluster.getPropertyValue(propertyName);
valuesOfProperty.AddRange(values.Except(valuesOfProperty));
}
}
else
{
var values = pointMarker.getPropertyValue(propertyName);
valuesOfProperty.AddRange(values.Except(valuesOfProperty));
/*var values = pointMarker.getPropertyValue(propertyName);
if (values.Count>0 && !valuesOfProperty.Contains(values[0]))
valuesOfProperty.Add(pointMarker.getPropertyValue(propertyName)[0]);*/
}
return valuesOfProperty;
}
public void UpdateMarkers()
{
foreach (MarkerInstance marker in markers) UpdateMarker(marker);
}
private bool areCoordinatesOnMap(double longitude, double latitude)
{
bool areOnMap = true;
Vector2 screenPosition = control.GetScreenPosition(longitude, latitude);
if (screenPosition.x < 0 || screenPosition.x > Screen.width ||
screenPosition.y < 0 || screenPosition.y > Screen.height)
areOnMap = false;
return areOnMap;
}
private void UpdateMarker(MarkerInstance marker)
{
//Debug.Log("PABLO: - UPDATE MARKER VISIBILITY");
if (marker == null)
return;
double px = marker.data.longitude;
double py = marker.data.latitude;
Vector2 screenPosition = control.GetScreenPosition(px, py);
if (screenPosition.x < 0 || screenPosition.x > Screen.width ||
screenPosition.y < 0 || screenPosition.y > Screen.height)
{
marker.gameObject.SetActive(false);
return;
}
if (marker.mapMarker != null && marker.mapMarker.isVisible())
{
int numPoints = marker.mapMarker.getGridCluster().getNumVisiblePoints();
string newTitle = numPoints.ToString();
if (!newTitle.Equals(marker.data.title)) {
marker.data.title = newTitle;
SetText(marker.transform, "Title", newTitle);
}
if (SilkMap.instance.map.GetDimension() == 3)
{
/*
marker.transform.localPosition = marker.mapMarker.getMarker3D().transform.localPosition;
if (marker.transform.localRotation.eulerAngles.x == 90)
marker.transform.Rotate(new Vector3(-45, 0, 0));
*/
var position = OnlineMapsTileSetControl.instance.GetWorldPosition(marker.mapMarker.getVector2());
marker.transform.localPosition = new Vector3(position.x, -position.z,3f);
marker.transform.localRotation = Quaternion.Euler(new Vector3(-45, 180, 0));
}
else
{
/*
Vector2 newPosition = OnlineMapsControlBase.instance.GetPosition(new Vector2(marker.mapMarker.getX(), marker.mapMarker.getY()));
marker.transform.localPosition = new Vector3(-newPosition.x, marker.transform.localPosition.y+0.5f, newPosition.y);
if (marker.transform.localRotation.eulerAngles.x == 45)
marker.transform.Rotate(new Vector3(45, 0, 0));
*/
var position = OnlineMapsTileSetControl.instance.GetWorldPosition(marker.mapMarker.getVector2());
marker.transform.localPosition = new Vector3(position.x, -position.z,0f);
marker.transform.localRotation = Quaternion.Euler(new Vector3(0, 180, 0));
}
if (!marker.gameObject.activeSelf)
marker.gameObject.SetActive(true);
/*
Vector2 screenPosition = control.GetScreenPosition(px, py);
if (screenPosition.x < 0 || screenPosition.x > Screen.width ||
screenPosition.y < 0 || screenPosition.y > Screen.height)
{
marker.gameObject.SetActive(false);
return;
}
RectTransform markerRectTransform = marker.transform;
if (!marker.gameObject.activeSelf) marker.gameObject.SetActive(true);
Camera worldCamera = null;
if (customMarkerCanvas.renderMode != RenderMode.ScreenSpaceOverlay)
worldCamera = canvas.worldCamera;
Vector2 point;
RectTransformUtility.ScreenPointToLocalPointInRectangle(markerRectTransform as RectTransform, screenPosition, worldCamera, out point);
markerRectTransform.localPosition = point;*/
}
else
marker.gameObject.SetActive(false);
}
public void fixZoomInterval(OnlineMaps oMaps, float min, float max)
{
OnlineMaps.instance.zoomRange = new OnlineMapsRange(min, max);
}
public void fixPositionInterval(OnlineMaps oMaps, float latMin, float longMin, float latMax, float longMax)
{
oMaps.positionRange = new OnlineMapsPositionRange(latMin, longMin, latMax, longMax);
}
public List<OnlineMapsDrawingLine> getConnectionLinesOfCluster(int clusterPosition, int level)
{
List<List<OnlineMapsDrawingLine>> levelConnections = (List<List<OnlineMapsDrawingLine>>)connectionsLinesPerLevel[level];
if (levelConnections != null && levelConnections.Count>=clusterPosition)
return levelConnections[clusterPosition];
else
return null;
}
public new void reset()
{
this.resetted = false;
if (markers != null)
{
foreach (MarkerInstance markerI in markers)
GameObject.DestroyImmediate(markerI.gameObject);
markers.Clear();
}
for (int i=0;i<points.Count;i++)
{
MapPointMarker point = (MapPointMarker)points[i];
if (point.isCluster() || !maintainPoints)
{
if(point.getMarker3D()!= null)
point.getMarker3D().DestroyInstance();
point.getMarker2D().DestroyInstance();
}
}
for (int i=0;i<clusterMarkers.Count;i++)
{
List< MapPointMarker> clusterMarkersList = clusterMarkers[i];
for (int j=0;j<clusterMarkersList.Count;j++)
{
//UnityEngine.Object.Destroy(clusterMarkersList[j].getMarker3D().prefab);
clusterMarkersList[j].reset();
if(clusterMarkersList[j].getMarker3D()!=null)
clusterMarkersList[j].getMarker3D().Dispose();
if (clusterMarkersList[j].getMarker2D() != null)
clusterMarkersList[j].getMarker2D().Dispose();
}
clusterMarkersList.RemoveRange(0, clusterMarkersList.Count);
}
clusterMarkers.RemoveRange(0, clusterMarkers.Count);
for (int i = 0; i < clusterLines.Count; i++)
{
List<OnlineMapsDrawingLine> clusterLinesList = clusterLines[i];
for (int j = 0; j < clusterLinesList.Count; j++)
{
clusterLinesList[j].Dispose();
}
clusterLinesList.RemoveRange(0, clusterLinesList.Count);
}
base.reset();
clusterLines.RemoveRange(0, clusterLines.Count);
List<int> keyList = new List<int>();
foreach (int el in connectionsLinesPerLevel.Keys)
{
keyList.Add(el);
}
for (int i=0;i<keyList.Count;i++)
{
List<List<OnlineMapsDrawingLine>> levelConnections = (List < List < OnlineMapsDrawingLine >>)connectionsLinesPerLevel[keyList[i]];
for (int j=0;j<levelConnections.Count;j++)
{
List<OnlineMapsDrawingLine> listLine = levelConnections[j];
for (int u = 0; u < listLine.Count; u++)
{
if (listLine[u]!=null)
listLine[u].Dispose();
}
listLine.RemoveRange(0, listLine.Count);
}
connectionsLinesPerLevel.Remove(keyList[i]);
}
}
public override void updateClustersDimension(short dimension)
{
for (int level = 0; level < clusterMarkers.Count; level++) // clusterManager.getNumLevels(); level++)
if (clusterMarkers[level]!=null)
foreach (MapPointMarker mapPoint in this.clusterMarkers[level])
mapPoint.setDimension(dimension);
}
public override void createGraphicRelationData()
{
int level;
//while (!relationsLoaded)
// yield return null;
for (level = 0; level < clusterManager.getNumLevels(); level++)
{
//this.clusterMarkers.Add(new List<MapPointMarker>());
//this.clusterLines.Add(new List<OnlineMapsDrawingLine>());
// Each level , a list lines per cluster
if (clusterManager.getGridClustersAtLevel(level) != null)
{
List<List<OnlineMapsDrawingLine>> levelConnections = new List<List<OnlineMapsDrawingLine>>();
for (int a = 0; a < clusterManager.getGridClustersAtLevel(level).Count; a++)
levelConnections.Add(new List<OnlineMapsDrawingLine>());
connectionsLinesPerLevel.Add(level, levelConnections);
}
}
for (level = 0; level < clusterManager.getNumLevels(); level++)
{
List<GridCluster> clusters = clusterManager.getGridClustersAtLevel(level);
// Debug.Log("En el nivel " + level + " hay " + clusters.Count + " cluster ");
if (clusters!=null && clusters.Count > 0 && !clusters[0].getCenter().isCluster())
{
for (int i = 0; i < clusters.Count; i++)
{
if (level == 0)
{
clusters[i].initConnectionsList(clusters.Count);
clusters[i].updateConnections(clusters);
List<List<OnlineMapsDrawingLine>> levelConnections = (List<List<OnlineMapsDrawingLine>>)connectionsLinesPerLevel[level];
for (int clusterCon = 0; clusterCon < clusters.Count; clusterCon++)
if (clusters[i].getConnections()[clusterCon] == 0)
levelConnections[i].Add(null);
else
levelConnections[i].Add(addConnection(clusters[i], clusters[clusterCon], clusters[i].getConnections()[clusterCon]));
}
}
}
}
}
public void update()
{
int level;
int c = 1;
if (clusterManager.hasData())
return;
distributeGroupsOnCircle();
updateClustering();
this.positionsGroup.Clear();
//Debug.Log("Hay " + clusterManager.getPointGroupClusters().Count + " gouppoints");
var crono3 = Stopwatch.StartNew();
foreach (GridCluster gCluster in clusterManager.getPointGroupClusters())
{
MapPointMarker point = getClusterMarker(gCluster, -c);
c++;
}
for (level = 0; level < clusterManager.getNumLevels(); level++)
{
this.clusterMarkers.Add(new List<MapPointMarker>());
this.clusterLines.Add(new List<OnlineMapsDrawingLine>());
// Each level , a list lines per cluster
/* MEMO
List<List<OnlineMapsDrawingLine>> levelConnections = new List<List<OnlineMapsDrawingLine>>();
for (int a = 0; a < clusterManager.getGridClustersAtLevel(level).Count; a++)
levelConnections.Add(new List<OnlineMapsDrawingLine>());
connectionsLinesPerLevel.Add(level, levelConnections); */
}
for (level = 0; level < clusterManager.getNumLevels(); level++)
{
List<GridCluster> clusters = clusterManager.getGridClustersAtLevel(level);
//Debug.Log("En el nivel " + level + " hay " + clusters.Count + " cluster ");
if (clusters!=null && clusters.Count > 0 ) // && !clusters[0].getCenter().isCluster())
{
for (int i = 0; i < clusters.Count; i++)
{
// Creating cluster marker
//MapPointMarker point = getClusterMarker(clusters[i], level * 1000 + i);
MapPointMarker point = null;
//Debug.Log("El cluster " + i + " del nivel " + level + " tiene " + clusters[i].getNumVisiblePoints() + " puntos visibles");
if (clusters[i].getNumVisiblePoints() == 1)
point = (MapPointMarker)(clusters[i].getPoints()[0]);
else
point = getClusterMarker(clusters[i], level * 1000 + i);
clusterMarkers[level].Add(point);
if (level == 0)
{
clusters[i].initConnectionsList(clusters.Count);
clusters[i].updateConnections(clusters);
/* MEMO
List<List<OnlineMapsDrawingLine>> levelConnections = (List<List<OnlineMapsDrawingLine>>)connectionsLinesPerLevel[level];
for (int clusterCon = 0; clusterCon < clusters.Count; clusterCon++)
if (clusters[i].getConnections()[clusterCon] == 0)
levelConnections[i].Add(null);
else
levelConnections[i].Add(addConnection(clusters[i], clusters[clusterCon], clusters[i].getConnections()[clusterCon]));
*/
}
}
}
}
this.positionsGroup.Clear();
//Debug.Log($"markes y conections {crono2.ElapsedMilliseconds * 0.001f} segundos");
}
public void addMarkerInstance(MapPointMarker mapPointMarker) {
mapPointMarker.assignTexture(null);
GameObject markerGameObject = GameObject.Instantiate(customMarkerGameObject, customMarkerCanvas.transform) as GameObject;
//gObject.transform.parent = mapPointMarker.getMarker3D().instance.transform;
RectTransform rectTransform = markerGameObject.transform as RectTransform;
//rectTransform.SetParent(customMarkerContainer);
markerGameObject.transform.localScale = Vector3.one;
MarkerInstance marker = new MarkerInstance();
MarkerData data = new MarkerData();
data.title = mapPointMarker.getGridCluster().getNumPoints().ToString();
data.longitude = mapPointMarker.getX();
data.latitude = mapPointMarker.getY();
marker.data = data;
marker.gameObject = markerGameObject;
marker.transform = rectTransform;
//marker.transform.Rotate(new Vector3(90, 180, 0));
/*
Quaternion quatRotation = Quaternion.identity;
quatRotation.x = 45;
quatRotation.y = 180;
marker.transform.localRotation = quatRotation;*/
marker.mapMarker = mapPointMarker;
mapPointMarker.markerInstance = marker;
mapPointMarker.getMarker2D().texture = null;
mapPointMarker.getMarker2D().enabled = false;
if (mapPointMarker.getMarker3D() != null)
{
mapPointMarker.getMarker3D().enabled = false;
mapPointMarker.getMarker3D().instance.SetActive(false);
}
SetText(rectTransform, "Title", data.title);
markers.Add(marker);
}
private void SetText(RectTransform rt, string childName, string value)
{
var title = rt.GetComponentInChildren<Text>();
if (title != null) title.text = value;
}
protected MapPointMarker getClusterMarker(GridCluster gCluster, int id)
{
MapPointMarker mapPoint = new MapPointMarker(gCluster.getCenter().getX(), gCluster.getCenter().getY(), clusterPrefab, true);
mapPoint.setGridCluster(gCluster);
mapPoint.setLabel("Cluster " + id);
//if(mapPoint.getMarker3D()!= null)
// mapPoint.getMarker3D().instance.name = id.ToString();
mapPoint.setClusteredPoints(gCluster.getPoints());
mapPoint.setCluster(true);
if (mapPoint.getMarker3D() != null)
{
mapPoint.getMarker3D().altitude = 30.0f;
mapPoint.getMarker3D().altitudeType = OnlineMapsAltitudeType.absolute;
mapPoint.getMarker3D().scale = getScale(gCluster, this.points.Count);
}
mapPoint.setMap(this);
addMarkerInstance(mapPoint);
if (mapPoint.isGroupPoint())
{
var img = mapPoint.markerInstance.gameObject.GetComponentInChildren<Image>();
if (img != null)
{
img.sprite = customGroupPointMarker;
foreach (var imgchild in img.GetComponentsInChildren<Image>())
{
if (imgchild != img)
imgchild.sprite = customGroupPointMarker;
}
}
}
gCluster.setCenter(mapPoint);
//if (gCluster.isGroupPoints())
// Debug.Log("AQUI");
/*
if (gCluster.getCategory().Equals("silknow.org/#pthing"))
{
SphereCollider sphereCollider = mapPoint.getMarker3D().instance.GetComponent<SphereCollider>();
sphereCollider.radius = 1;
//mapPoint.getMarker3D().scale = mapPoint.getMarker3D().scale * 100.0f;
}
else
{
CapsuleCollider capsuleCollider = mapPoint.getMarker3D().instance.GetComponent<CapsuleCollider>();
capsuleCollider.radius = 0.5f;
capsuleCollider.height = 1.5f;
capsuleCollider.direction = 1;
mapPoint.getMarker3D().altitude = 70.0f;
//mapPoint.getMarker3D().transform.position = mapPoint.getMarker3D().transform.position + new Vector3(0.0f, 60.0f, 0.0f);
//mapPoint.getMarker3D().al
}*/
mapPoint.hide();
return mapPoint;
}
public new void setViewerPosition(float x, float y)
{
base.setViewerPosition(x, y);
OnlineMaps.instance.position = new Vector2(x, y);
}
private OnlineMapsDrawingLine addConnection(GridCluster clusterFrom, GridCluster clusterTo, int numConnections)
{
MapPoint from = clusterFrom.getCenter();
MapPoint to = clusterTo.getCenter();
List<Vector2> points = new List<Vector2>();
points.Add(from.getVector2());
points.Add(to.getVector2());
OnlineMapsDrawingLine oLine = new OnlineMapsDrawingLine(points, Color.blue);
oLine.width = 1.0f;
oLine.visible = true;
OnlineMapsDrawingElementManager.AddItem(oLine);
oLine.visible = false;
oLine.name = "connection";
return oLine;
}
private void getRectEcuationParameters(MapPoint from, MapPoint to, ref float m, ref float b)
{
m = (from.getY() - to.getY()) / (from.getX() - to.getX());
b = from.getY() - m * from.getX();
}
private void OnClusterClick(int id)
{
Debug.Log("Click ON " + id);
}
private void OnMapClick()
{
//Vector3 mousePosition = Input.mousePosition;
// Converts the screen coordinates to geographic.
//Vector3 mouseGeoLocation = OnlineMapsControlBase.instance.GetCoords(mousePosition);
//double lng, lat;
/*
if (true)
return;
OnlineMapsControlBase.instance.GetCoords(out lng, out lat);
Component omarker = OnlineMapsControlBase3D.instance.GetComponent("OnlineMapsMarker3D");
GameObject selected=null;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
// Casts the ray and get the first game object hit
if (Physics.Raycast(ray, out hit, 1000))
selected = hit.transform.gameObject;
String name = "null";
if (selected != null && (!selected.name.Equals("Map")))
{
Debug.Log("Se selecciona " + selected.name);
name = selected.name;
if (isPoint(name))
{
if (name.Contains("Cube"))
name = selected.transform.parent.name;
if (name.Contains("(Clone)"))
name = name.Substring(0, name.IndexOf("("));
Debug.Log("Ahora name vale " + name);
//nt numPoint = Int32.Parse(name);
//mPoint = numPoint * (-1);
//MapPointMarker pointMarker = (MapPointMarker)points[numPoint];
MapPointMarker pointMarker = (MapPointMarker)getPointPerLabel(name);
Debug.Log("Ha seleccionado el punto " + pointMarker.getLabel());
Debug.Log("EL marker3D esta " + pointMarker.getMarker3D().enabled);
List<string> values = pointMarker.getPropertyValue("technique");
foreach (string s in values)
Debug.Log("Valor de technique = " + s);
MapItemPopup.instance.OnMarkerClick(pointMarker);
SilkMap.Instance.changeCam();
}
else
{
GridCluster cluster = getClusterByName(name);
if (cluster != null)
{
Debug.Log("Seleccionado el cluster " + name + " con " + cluster.getNumPoints() + " datos");
int clusterClicked = Int32.Parse(name);
showLines(getConnectionLinesOfCluster(clusterClicked, 0));
if (selectedCluster != -1)
hideLines(getConnectionLinesOfCluster(selectedCluster, 0));
selectedCluster = clusterClicked;
}
}
}
*/
//Debug.Log("LLAMA AL ONCLICK2 en " + lng + " , " + lat + " hay un obj con id "+name);
}
public bool isPoint(string name)
{
//int numPoint = Int32.Parse(name);
//if (numPoint < 0)
if (name.Contains("Cube") || name.Contains("Clone"))
return true;
else
return false;
}
public void showLines(List<OnlineMapsDrawingLine> lineList)
{
if (lineList!=null)
for (int i = 0; i < lineList.Count; i++)
if (lineList[i]!=null)
lineList[i].visible = true;
}
public void hideLines(List<OnlineMapsDrawingLine> lineList)
{
if (lineList!=null)
for (int i = 0; i < lineList.Count; i++)
if (lineList[i] != null)
lineList[i].visible = false;
}
public GridCluster getClusterByName(String name)
{
GridCluster cluster = null;
int numCluster = Int32.Parse(name);
int level = (int)(numCluster / 1000);
int position = numCluster % 1000;
List<GridCluster> clusters = clusterManager.getGridClustersAtLevel(level);
cluster = clusters[position];
return cluster;
}
public int getScale(GridCluster cluster, int totalNumPoints)
{
int scaleMin = 5;
int scaleMax = 40;
int scale;
int clusterPoints = cluster.getNumPoints();
scale = scaleMin + (int) ((3*scaleMax*clusterPoints)/totalNumPoints);
if (!cluster.isGroupPoints())
scale = scale / 4;
return 20; // scale;
}
public override void showClustersAtZoom(float zoom)
{
int level = clusterManager.getLevel(zoom);
int levelInc = clusterManager.getLevel(zoom + 2);
if (levelInc > level && level>1)
level = levelInc;
int numLevels = clusterManager.getNumLevels();
//if (level>=0 && level < clusterManager.getNumLevels())
if (level>=0 && level < clusterManager.getNumLevels()-1) // menos 1
{
if (this.clusterMarkers.Count > 0)
{
List<MapPointMarker> clusterList = this.clusterMarkers[level];
if (!this.resetted)
{
for (int i = 0; i < points.Count; i++)
points[i].hide();
this.resetted = true;
}
//List<GridCluster> clusters = clusterManager.getGridClustersAtLevel(level);
//Debug.Log("Se muestran los clusters de zoom " + zoom +" level "+ level+ "hay "+ clusterList.Count);
for (int i = 0; i < clusterList.Count; i++)
{
if (clusterList[i].getMarker3D() != null)
{
clusterList[i].getMarker3D().scale =
20.0f; //scaleCorrection(clusters[i], this.points.Count, zoom);
}
/*if (clusterList[i].getGridCluster() != null)
{
clusterList[i].getGridCluster().getCenter().show();
}*/
if (clusterList[i].getMarker2D().InMapView())
{
clusterList[i].show();
UpdateMarker(clusterList[i].markerInstance);
}
}
/*
foreach (MapPoint p in clusterManager.getPointGroupsPoints())
p.hide();*/
}
}
else
{
for (int i = 0; i < points.Count; i++)
{
/* float corrector = 1.0f;
if (level == 1) //zoom > 4 && zoom <= 6)
corrector = 3.25f;
if (level == 2) //zoom > 6 && zoom <= 8)
corrector = 3.25f;
if (level == 3) //zoom > 8)
corrector = 3.5f;
*/
var corrector = 3.5f;
if (((MapPointMarker)(points[i])).getMarker3D()!=null)
((MapPointMarker)(points[i])).getMarker3D().scale =40f;
points[i].show();
}
foreach (MapPoint p in clusterManager.getPointGroupsPoints())
{
//p.show();
if (((MapPointMarker) p).getMarker2D().InMapView())
{
p.show();
UpdateMarker(((MapPointMarker) p).markerInstance);
}
}
//UpdateMarkers();
/*
foreach (MapPoint p in pointsWithRelation)
{
//p.showAllRelations();
}*/
}
}
public override void hideClustersAtZoom(float zoom)
{
int level = clusterManager.getLevel(zoom);
int levelInc = clusterManager.getLevel(zoom+2);
if (levelInc > level && level>1)
level = levelInc;
if (level>=0 && level < clusterManager.getNumLevels())
{
for (int i = 0; i < points.Count; i++)
points[i].hide();
//foreach (MapPoint p in clusterManager.getPointGroupsPoints())
// p.hide();
//Debug.Log("MapMarker-->hideClustersAtZoom " + level);
//Debug.Log(clusterMarkers.Count);
if (this.clusterMarkers.Count > 0)
{
List<MapPointMarker> clusterList = this.clusterMarkers[level];
List<OnlineMapsDrawingLine> clusterLineList = this.clusterLines[level];
for (int i = 0; i < clusterList.Count; i++)
{
if (clusterList[i].getGridCluster() != null)
clusterList[i].getGridCluster().getCenter().hide();
clusterList[i].hide();
//clusterList[i].getGridCluster().hideRelations();
//clusterLineList[i].visible = false;
}
/*
for (int q = 0; q < quadsDrawed.Count; q++)
{
OnlineMapsDrawingLine oLineQuad = quadsDrawed[q];
oLineQuad.visible = false;
OnlineMapsDrawingElementManager.RemoveItem(oLineQuad);
}
quadsDrawed.RemoveRange(0, quadsDrawed.Count);*/
}
}
}
public List<MapPointMarker> getClusterMarkersAtLevel(int level)
{
if (this.clusterMarkers.Count > 0)
return this.clusterMarkers[level];
else
return null;
}
private void drawQuad(List<MapPoint> quadPoints, int q)
{
/*
List<Vector2> points = new List<Vector2>();
points.Add(new Vector2(quadPoints[0].getX(), quadPoints[0].getY()));
points.Add(new Vector2(quadPoints[1].getX(), quadPoints[1].getY()));
points.Add(new Vector2(quadPoints[2].getX(), quadPoints[2].getY()));
points.Add(new Vector2(quadPoints[3].getX(), quadPoints[3].getY()));
OnlineMapsDrawingLine oLine = new OnlineMapsDrawingLine(points, Color.green);
oLine.width = 2.0f;
oLine.visible = true;
OnlineMapsDrawingElementManager.AddItem(oLine);
quadsDrawed.Add(oLine);*/
}
public int scaleCorrection(GridCluster cluster, int numPoints, float zoom)
{
int scale = getScale(cluster, this.points.Count);
// Debug.Log(zoom);
float corrector = 1.0f;
//int level = clusterManager.getLevel(zoom);
/*
switch (level)
{
//zoom > 4 && zoom <= 6)
case 1:
corrector = 2.0f;
break;
//zoom > 6 && zoom <= 8)
case 2:
corrector = 2.5f;
break;
//zoom > 8)
case 3:
corrector = 3.0f;
break;
}
*/
//scale = (int)(scale * corrector);
//if (!cluster.getCategory().Equals("silknow.org/#pthing"))
// scale = scale * 2;
return scale;
}
public override void removeAllGraphicClusters()
{
if (this.clusterMarkers.Count > 0)
{
for (int level = 0; level < clusterManager.getNumLevels(); level++)
{
List<MapPointMarker> clusterList = this.clusterMarkers[level];
//List<OnlineMapsDrawingLine> clusterLineList = this.clusterLines[level];
//List<GridCluster> clusters = clusterManager.getGridClustersAtLevel(level);
for (int i = 0; i < clusterList.Count; i++)
clusterList[i].reset();
clusterList.Clear();
}
}
}
public override void changeProjection(int dimension)
{
if (dimension == MapPoint.TWO_DIMENSION)
{
Camera.main.orthographic = true;
Camera.main.orthographicSize = 287.5f;
OnlineMapsCameraOrbit.instance.rotation = new Vector2(0, 0);
}
else
{
Camera.main.orthographic = false;
OnlineMapsCameraOrbit.instance.rotation = new Vector2(35, 0);
}
update();
}
[Serializable]
public class MarkerData
{
public string title;
public float longitude;
public float latitude;
}
public class MarkerInstance
{
public MarkerData data;
public GameObject gameObject;
public RectTransform transform;
public MapPointMarker mapMarker;
}
}
| 31.789286 | 148 | 0.554235 | [
"Apache-2.0"
] | silknow/silkmap | Assets/scripts/MapMarker.cs | 35,606 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace NearbyNowWebFormsExample.Account
{
public partial class Login : Page
{
protected void Page_Load(object sender, EventArgs e)
{
RegisterHyperLink.NavigateUrl = "Register.aspx";
OpenAuthLogin.ReturnUrl = Request.QueryString["ReturnUrl"];
var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
if (!String.IsNullOrEmpty(returnUrl))
{
RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl;
}
}
}
} | 28.791667 | 84 | 0.646889 | [
"MIT"
] | NearbyNow/NearbyNow-aspnetwebformexample | NearbyNowWebFormsExample/Account/Login.aspx.cs | 693 | 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 pinpoint-2016-12-01.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.Pinpoint.Model
{
/// <summary>
/// Specifies a condition to evaluate for an activity in a journey.
/// </summary>
public partial class SimpleCondition
{
private EventCondition _eventCondition;
private SegmentCondition _segmentCondition;
private SegmentDimensions _segmentDimensions;
/// <summary>
/// Gets and sets the property EventCondition.
/// <para>
/// The dimension settings for the event that's associated with the activity.
/// </para>
/// </summary>
public EventCondition EventCondition
{
get { return this._eventCondition; }
set { this._eventCondition = value; }
}
// Check to see if EventCondition property is set
internal bool IsSetEventCondition()
{
return this._eventCondition != null;
}
/// <summary>
/// Gets and sets the property SegmentCondition.
/// <para>
/// The segment that's associated with the activity.
/// </para>
/// </summary>
public SegmentCondition SegmentCondition
{
get { return this._segmentCondition; }
set { this._segmentCondition = value; }
}
// Check to see if SegmentCondition property is set
internal bool IsSetSegmentCondition()
{
return this._segmentCondition != null;
}
/// <summary>
/// Gets and sets the property SegmentDimensions.
/// <para>
/// The dimension settings for the segment that's associated with the activity.
/// </para>
/// </summary>
public SegmentDimensions SegmentDimensions
{
get { return this._segmentDimensions; }
set { this._segmentDimensions = value; }
}
// Check to see if SegmentDimensions property is set
internal bool IsSetSegmentDimensions()
{
return this._segmentDimensions != null;
}
}
} | 31.191489 | 106 | 0.626876 | [
"Apache-2.0"
] | NGL321/aws-sdk-net | sdk/src/Services/Pinpoint/Generated/Model/SimpleCondition.cs | 2,932 | C# |
using System;
using Vostok.Commons.Helpers;
namespace Vostok.Configuration.Parsers
{
internal static class TimeSpanParser
{
private const string MilliSeconds1 = "ms";
private const string MilliSeconds2 = "msec";
private const string MilliSeconds3 = "millisecond";
private const string MilliSeconds4 = "milliseconds";
private const string Seconds1 = "s";
private const string Seconds2 = "sec";
private const string Seconds3 = "second";
private const string Seconds4 = "seconds";
private const string Minutes1 = "m";
private const string Minutes2 = "min";
private const string Minutes3 = "minute";
private const string Minutes4 = "minutes";
private const string Hours1 = "h";
private const string Hours2 = "hour";
private const string Hours3 = "hours";
private const string Days1 = "d";
private const string Days2 = "day";
private const string Days3 = "days";
public static bool TryParse(string input, out TimeSpan result)
{
input = PrepareInput(input);
if (TimeSpan.TryParse(input, out result))
return true;
bool TryParse(string unit, out double res) => NumericTypeParser<double>.TryParse(PrepareInput(input, unit), out res);
bool TryGet(FromValue method, string unit, out TimeSpan res)
{
if (!input.Contains(unit)) return false;
if (!TryParse(unit, out var val)) return false;
res = method(val);
return true;
}
return
TryGet(TimeSpan.FromMilliseconds, MilliSeconds4, out result) ||
TryGet(TimeSpan.FromMilliseconds, MilliSeconds3, out result) ||
TryGet(TimeSpan.FromSeconds, Seconds4, out result) ||
TryGet(TimeSpan.FromSeconds, Seconds3, out result) ||
TryGet(TimeSpan.FromMinutes, Minutes4, out result) ||
TryGet(TimeSpan.FromMinutes, Minutes3, out result) ||
TryGet(TimeSpan.FromHours, Hours3, out result) ||
TryGet(TimeSpan.FromHours, Hours2, out result) ||
TryGet(TimeSpan.FromDays, Days3, out result) ||
TryGet(TimeSpan.FromDays, Days2, out result) ||
TryGet(TimeSpan.FromMilliseconds, MilliSeconds2, out result) ||
TryGet(TimeSpan.FromSeconds, Seconds2, out result) ||
TryGet(TimeSpan.FromMinutes, Minutes2, out result) ||
TryGet(TimeSpan.FromMilliseconds, MilliSeconds1, out result) ||
TryGet(TimeSpan.FromSeconds, Seconds1, out result) ||
TryGet(TimeSpan.FromMinutes, Minutes1, out result) ||
TryGet(TimeSpan.FromHours, Hours1, out result) ||
TryGet(TimeSpan.FromDays, Days1, out result);
}
private static string PrepareInput(string input, string unit) =>
input.Replace(unit, string.Empty).Trim('.').Trim();
private static string PrepareInput(string input) =>
input.ToLower().Replace(',', '.');
private delegate TimeSpan FromValue(double value);
}
} | 42.233766 | 129 | 0.603936 | [
"MIT"
] | goverdovskiy/configuration | Vostok.Configuration/Parsers/TimeSpanParser.cs | 3,254 | 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 Image_compressor.Properties
{
/// <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 Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Image_compressor.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 38.736111 | 182 | 0.604518 | [
"MIT"
] | catinwarmhands/Image-compressor | Image_compressor/Properties/Resources.Designer.cs | 2,791 | C# |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.AWSSupport.Model
{
/// <summary>
/// <para>Contains the following objects or data if successful. Otherwise, returns an error.</para>
/// </summary>
public partial class DescribeTrustedAdvisorCheckRefreshStatusesResult
{
private List<TrustedAdvisorCheckRefreshStatus> statuses = new List<TrustedAdvisorCheckRefreshStatus>();
/// <summary>
/// The refresh status of the specified Trusted Advisor checks.
///
/// </summary>
public List<TrustedAdvisorCheckRefreshStatus> Statuses
{
get { return this.statuses; }
set { this.statuses = value; }
}
/// <summary>
/// Adds elements to the Statuses collection
/// </summary>
/// <param name="statuses">The values to add to the Statuses collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeTrustedAdvisorCheckRefreshStatusesResult WithStatuses(params TrustedAdvisorCheckRefreshStatus[] statuses)
{
foreach (TrustedAdvisorCheckRefreshStatus element in statuses)
{
this.statuses.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the Statuses collection
/// </summary>
/// <param name="statuses">The values to add to the Statuses collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeTrustedAdvisorCheckRefreshStatusesResult WithStatuses(IEnumerable<TrustedAdvisorCheckRefreshStatus> statuses)
{
foreach (TrustedAdvisorCheckRefreshStatus element in statuses)
{
this.statuses.Add(element);
}
return this;
}
// Check to see if Statuses property is set
internal bool IsSetStatuses()
{
return this.statuses.Count > 0;
}
}
}
| 38.164557 | 177 | 0.6534 | [
"Apache-2.0"
] | jdluzen/aws-sdk-net-android | AWSSDK/Amazon.AWSSupport/Model/DescribeTrustedAdvisorCheckRefreshStatusesResult.cs | 3,015 | C# |
#if WITH_EDITOR
#if PLATFORM_64BITS
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace UnrealEngine
{
/// <summary>A group and all the actors controlled by the group</summary>
[StructLayout(LayoutKind.Explicit,Size=32)]
public partial struct FInterpGroupActorInfo
{
[FieldOffset(0)]
public FName ObjectName;
public TObjectArray<AActor> Actors
{
get{ unsafe { fixed (void* p = &this) { return new TObjectArray<AActor>((FScriptArray)Marshal.PtrToStructure(new IntPtr(p)+16, typeof(FScriptArray)));}}}
set{ unsafe { fixed (void* p = &this) { Marshal.StructureToPtr(value.InterArray,new IntPtr(p)+16, false);}}}
}
}
}
#endif
#endif
| 27.461538 | 159 | 0.731092 | [
"MIT"
] | RobertAcksel/UnrealCS | Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile_Editor_64bits/FInterpGroupActorInfo.cs | 714 | 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 WSACompanion.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.419355 | 151 | 0.582006 | [
"MIT"
] | CsakiTheOne/WSACompanion | WSACompanion/Properties/Settings.Designer.cs | 1,069 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Deal_data1_2 : MonoBehaviour
{
private double Input = 0;
// Start is called before the first frame update
void Start()
{
GetComponent<InputField>().onEndEdit.AddListener(Accept);
}
// Update is called once per frame
void Accept(string value)
{
if (double.TryParse(value, out Input) == true)
{
Exp_1.B_thickness = Input;
}
}
}
| 21.791667 | 65 | 0.642447 | [
"MIT"
] | wsmitpwtind/Virtual-simulation-experiment-platform | Assets/scripts/Experiments_1/Deal_data1_2.cs | 525 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.Custom;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Demonstration algorithm of popular indicators and plotting them.
/// </summary>
/// <meta name="tag" content="indicators" />
/// <meta name="tag" content="indicator classes" />
/// <meta name="tag" content="plotting indicators" />
/// <meta name="tag" content="charting" />
/// <meta name="tag" content="indicator field selection" />
public class IndicatorSuiteAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private string _ticker = "SPY";
private string _customTicker = "WIKI/FB";
private Symbol _symbol;
private Symbol _customSymbol;
private Indicators _indicators;
private Indicators _selectorIndicators;
private IndicatorBase<IndicatorDataPoint> _ratio;
//RSI Custom Data:
private RelativeStrengthIndex _rsiCustom;
private Minimum _minCustom;
private Maximum _maxCustom;
private decimal _price;
/// <summary>
/// Initialize the data and resolution you require for your strategy
/// </summary>
public override void Initialize()
{
//Initialize
SetStartDate(2013, 1, 1);
SetEndDate(2014, 12, 31);
SetCash(25000);
//Add as many securities as you like. All the data will be passed into the event handler:
_symbol = AddSecurity(SecurityType.Equity, _ticker, Resolution.Daily).Symbol;
//Add the Custom Data:
_customSymbol = AddData<Quandl>(_customTicker, Resolution.Daily).Symbol;
//Set up default Indicators, these indicators are defined on the Value property of incoming data (except ATR and AROON which use the full TradeBar object)
_indicators = new Indicators
{
BB = BB(_symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily),
RSI = RSI(_symbol, 14, MovingAverageType.Simple, Resolution.Daily),
ATR = ATR(_symbol, 14, MovingAverageType.Simple, Resolution.Daily),
EMA = EMA(_symbol, 14, Resolution.Daily),
SMA = SMA(_symbol, 14, Resolution.Daily),
MACD = MACD(_symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Daily),
AROON = AROON(_symbol, 20, Resolution.Daily),
MOM = MOM(_symbol, 20, Resolution.Daily),
MOMP = MOMP(_symbol, 20, Resolution.Daily),
STD = STD(_symbol, 20, Resolution.Daily),
MIN = MIN(_symbol, 14, Resolution.Daily), // by default if the symbol is a tradebar type then it will be the min of the low property
MAX = MAX(_symbol, 14, Resolution.Daily) // by default if the symbol is a tradebar type then it will be the max of the high property
};
// Here we're going to define indicators using 'selector' functions. These 'selector' functions will define what data gets sent into the indicator
// These functions have a signature like the following: decimal Selector(BaseData baseData), and can be defined like: baseData => baseData.Value
// We'll define these 'selector' functions to select the Low value
//
// For more information on 'anonymous functions' see: http://en.wikipedia.org/wiki/Anonymous_function
// https://msdn.microsoft.com/en-us/library/bb397687.aspx
//
_selectorIndicators = new Indicators
{
BB = BB(_symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily, Field.Low),
RSI = RSI(_symbol, 14, MovingAverageType.Simple, Resolution.Daily, Field.Low),
EMA = EMA(_symbol, 14, Resolution.Daily, Field.Low),
SMA = SMA(_symbol, 14, Resolution.Daily, Field.Low),
MACD = MACD(_symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Daily, Field.Low),
MOM = MOM(_symbol, 20, Resolution.Daily, Field.Low),
MOMP = MOMP(_symbol, 20, Resolution.Daily, Field.Low),
STD = STD(_symbol, 20, Resolution.Daily, Field.Low),
MIN = MIN(_symbol, 14, Resolution.Daily, Field.High), // this will find the 14 day min of the high property
MAX = MAX(_symbol, 14, Resolution.Daily, Field.Low), // this will find the 14 day max of the low property
// ATR and AROON are special in that they accept a TradeBar instance instead of a decimal, we could easily project and/or transform the input TradeBar
// before it gets sent to the ATR/AROON indicator, here we use a function that will multiply the input trade bar by a factor of two
ATR = ATR(_symbol, 14, MovingAverageType.Simple, Resolution.Daily, SelectorDoubleTradeBar),
AROON = AROON(_symbol, 20, Resolution.Daily, SelectorDoubleTradeBar)
};
//Custom Data Indicator:
_rsiCustom = RSI(_customSymbol, 14, MovingAverageType.Simple, Resolution.Daily);
_minCustom = MIN(_customSymbol, 14, Resolution.Daily);
_maxCustom = MAX(_customSymbol, 14, Resolution.Daily);
// in addition to defining indicators on a single security, you can all define 'composite' indicators.
// these are indicators that require multiple inputs. the most common of which is a ratio.
// suppose we seek the ratio of BTC to SPY, we could write the following:
var spyClose = Identity(_symbol);
var fbClose = Identity(_customSymbol);
// this will create a new indicator whose value is FB/SPY
_ratio = fbClose.Over(spyClose);
// we can also easily plot our indicators each time they update using th PlotIndicator function
PlotIndicator("Ratio", _ratio);
}
/// <summary>
/// Custom data event handler:
/// </summary>
/// <param name="data">Quandl - dictionary Bars of Quandl Data</param>
public void OnData(Quandl data)
{
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">TradeBars IDictionary object with your stock data</param>
public void OnData(TradeBars data)
{
if (!_indicators.BB.IsReady || !_indicators.RSI.IsReady) return;
_price = data["SPY"].Close;
if (!Portfolio.HoldStock)
{
int quantity = (int)Math.Floor(Portfolio.Cash / data[_symbol].Close);
//Order function places trades: enter the string symbol and the quantity you want:
Order(_symbol, quantity);
//Debug sends messages to the user console: "Time" is the algorithm time keeper object
Debug("Purchased SPY on " + Time.ToShortDateString());
}
}
/// <summary>
/// Fire plotting events once per day.
/// </summary>
public override void OnEndOfDay()
{
if (!_indicators.BB.IsReady) return;
Plot("BB", "Price", _price);
Plot("BB", _indicators.BB.UpperBand, _indicators.BB.MiddleBand, _indicators.BB.LowerBand);
Plot("RSI", _indicators.RSI);
//Custom data indicator
Plot("RSI-BTC", _rsiCustom);
Plot("ATR", _indicators.ATR);
Plot("STD", _indicators.STD);
Plot("AROON", _indicators.AROON.AroonUp, _indicators.AROON.AroonDown);
// The following Plot method calls are commented out because of the 10 series limit for backtests
//Plot("MOM", _indicators.MOM);
//Plot("MOMP", _indicators.MOMP);
//Plot("MACD", "Price", _price);
//Plot("MACD", _indicators.MACD.Fast, _indicators.MACD.Slow, _indicators.MACD.Signal);
//Plot("Averages", _indicators.EMA, _indicators.SMA);
}
/// <summary>
/// Class to hold a bunch of different indicators for this example
/// </summary>
private class Indicators
{
public BollingerBands BB;
public SimpleMovingAverage SMA;
public ExponentialMovingAverage EMA;
public RelativeStrengthIndex RSI;
public AverageTrueRange ATR;
public StandardDeviation STD;
public AroonOscillator AROON;
public Momentum MOM;
public MomentumPercent MOMP;
public MovingAverageConvergenceDivergence MACD;
public Minimum MIN;
public Maximum MAX;
}
/// <summary>
/// Function used to select a trade bar that has double the values of the input trade bar
/// </summary>
private static TradeBar SelectorDoubleTradeBar(IBaseData baseData)
{
var bar = (TradeBar)baseData;
return new TradeBar
{
Close = 2 * bar.Close,
DataType = bar.DataType,
High = 2 * bar.High,
Low = 2 * bar.Low,
Open = 2 * bar.Open,
Symbol = bar.Symbol,
Time = bar.Time,
Value = 2 * bar.Value,
Volume = 2 * bar.Volume,
Period = bar.Period
};
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "19.104%"},
{"Drawdown", "7.300%"},
{"Expectancy", "0"},
{"Net Profit", "41.858%"},
{"Sharpe Ratio", "1.649"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.021"},
{"Beta", "0.965"},
{"Annual Standard Deviation", "0.109"},
{"Annual Variance", "0.012"},
{"Information Ratio", "-1.355"},
{"Tracking Error", "0.021"},
{"Treynor Ratio", "0.187"},
{"Total Fees", "$1.00"}
};
}
}
| 44.898496 | 166 | 0.597505 | [
"Apache-2.0"
] | AENotFound/Lean | Algorithm.CSharp/IndicatorSuiteAlgorithm.cs | 11,943 | C# |
// Copyright 2021, Mikhail Paulyshka
// SPDX-License-Identifier: MIT
using System;
using System.Collections.Generic;
using System.Text;
using Mixaill.HwInfo.SetupApi.Defines;
namespace Mixaill.HwInfo.SetupApi
{
public class DevicePropertyValue
{
public DevicePropertyType Type { get; } = DevicePropertyType.Empty;
public object Value { get; } = null;
protected DevicePropertyValue(DevicePropertyType type)
{
Type = type;
}
}
public class DevicePropertyValueUInt32 : DevicePropertyValue
{
public new UInt32 Value { get; }
public DevicePropertyValueUInt32(DevicePropertyType type, byte[] data) : base(type)
{
Value = BitConverter.ToUInt32(data, 0);
}
}
public class DevicePropertyValueGuid : DevicePropertyValue
{
public new Guid Value { get; }
public DevicePropertyValueGuid(DevicePropertyType type, byte[] data) : base(type)
{
Value = new Guid(data);
}
}
public class DevicePropertyValueString : DevicePropertyValue
{
public new string Value { get; }
public DevicePropertyValueString(DevicePropertyType type, byte[] data) : base(type)
{
Value = Encoding.Unicode.GetString(data);
}
}
public class DevicePropertyValueStringList : DevicePropertyValue
{
public new List<string> Value { get; } = new List<string>();
public DevicePropertyValueStringList(DevicePropertyType type, byte[] data) : base(type)
{
Value = data.SeparateRegMultiSz();
}
}
internal static class DevicePropertyValueFactory
{
public static DevicePropertyValue Create(DevicePropertyType type, byte[] data)
{
switch (type)
{
case DevicePropertyType.UInt32:
return new DevicePropertyValueUInt32(type, data);
case DevicePropertyType.Guid:
return new DevicePropertyValueGuid(type, data);
case DevicePropertyType.String:
return new DevicePropertyValueString(type, data);
case DevicePropertyType.StringList:
return new DevicePropertyValueStringList(type, data);
}
throw new NotImplementedException($"DevPropType {type} is not implemented");
}
}
}
| 29.011905 | 95 | 0.622897 | [
"MIT"
] | Mixaill/Mixaill.HwInfo | Mixaill.HwInfo.SetupApi/DevicePropertyValue.cs | 2,439 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type IdentitySecurityDefaultsEnforcementPolicyRequest.
/// </summary>
public partial class IdentitySecurityDefaultsEnforcementPolicyRequest : BaseRequest, IIdentitySecurityDefaultsEnforcementPolicyRequest
{
/// <summary>
/// Constructs a new IdentitySecurityDefaultsEnforcementPolicyRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public IdentitySecurityDefaultsEnforcementPolicyRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified IdentitySecurityDefaultsEnforcementPolicy using POST.
/// </summary>
/// <param name="identitySecurityDefaultsEnforcementPolicyToCreate">The IdentitySecurityDefaultsEnforcementPolicy to create.</param>
/// <returns>The created IdentitySecurityDefaultsEnforcementPolicy.</returns>
public System.Threading.Tasks.Task<IdentitySecurityDefaultsEnforcementPolicy> CreateAsync(IdentitySecurityDefaultsEnforcementPolicy identitySecurityDefaultsEnforcementPolicyToCreate)
{
return this.CreateAsync(identitySecurityDefaultsEnforcementPolicyToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified IdentitySecurityDefaultsEnforcementPolicy using POST.
/// </summary>
/// <param name="identitySecurityDefaultsEnforcementPolicyToCreate">The IdentitySecurityDefaultsEnforcementPolicy to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created IdentitySecurityDefaultsEnforcementPolicy.</returns>
public async System.Threading.Tasks.Task<IdentitySecurityDefaultsEnforcementPolicy> CreateAsync(IdentitySecurityDefaultsEnforcementPolicy identitySecurityDefaultsEnforcementPolicyToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<IdentitySecurityDefaultsEnforcementPolicy>(identitySecurityDefaultsEnforcementPolicyToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified IdentitySecurityDefaultsEnforcementPolicy.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified IdentitySecurityDefaultsEnforcementPolicy.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<IdentitySecurityDefaultsEnforcementPolicy>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified IdentitySecurityDefaultsEnforcementPolicy.
/// </summary>
/// <returns>The IdentitySecurityDefaultsEnforcementPolicy.</returns>
public System.Threading.Tasks.Task<IdentitySecurityDefaultsEnforcementPolicy> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified IdentitySecurityDefaultsEnforcementPolicy.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The IdentitySecurityDefaultsEnforcementPolicy.</returns>
public async System.Threading.Tasks.Task<IdentitySecurityDefaultsEnforcementPolicy> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<IdentitySecurityDefaultsEnforcementPolicy>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified IdentitySecurityDefaultsEnforcementPolicy using PATCH.
/// </summary>
/// <param name="identitySecurityDefaultsEnforcementPolicyToUpdate">The IdentitySecurityDefaultsEnforcementPolicy to update.</param>
/// <returns>The updated IdentitySecurityDefaultsEnforcementPolicy.</returns>
public System.Threading.Tasks.Task<IdentitySecurityDefaultsEnforcementPolicy> UpdateAsync(IdentitySecurityDefaultsEnforcementPolicy identitySecurityDefaultsEnforcementPolicyToUpdate)
{
return this.UpdateAsync(identitySecurityDefaultsEnforcementPolicyToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified IdentitySecurityDefaultsEnforcementPolicy using PATCH.
/// </summary>
/// <param name="identitySecurityDefaultsEnforcementPolicyToUpdate">The IdentitySecurityDefaultsEnforcementPolicy to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception>
/// <returns>The updated IdentitySecurityDefaultsEnforcementPolicy.</returns>
public async System.Threading.Tasks.Task<IdentitySecurityDefaultsEnforcementPolicy> UpdateAsync(IdentitySecurityDefaultsEnforcementPolicy identitySecurityDefaultsEnforcementPolicyToUpdate, CancellationToken cancellationToken)
{
if (identitySecurityDefaultsEnforcementPolicyToUpdate.AdditionalData != null)
{
if (identitySecurityDefaultsEnforcementPolicyToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.ResponseHeaders) ||
identitySecurityDefaultsEnforcementPolicyToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.StatusCode))
{
throw new ClientException(
new Error
{
Code = GeneratedErrorConstants.Codes.NotAllowed,
Message = String.Format(GeneratedErrorConstants.Messages.ResponseObjectUsedForUpdate, identitySecurityDefaultsEnforcementPolicyToUpdate.GetType().Name)
});
}
}
if (identitySecurityDefaultsEnforcementPolicyToUpdate.AdditionalData != null)
{
if (identitySecurityDefaultsEnforcementPolicyToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.ResponseHeaders) ||
identitySecurityDefaultsEnforcementPolicyToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.StatusCode))
{
throw new ClientException(
new Error
{
Code = GeneratedErrorConstants.Codes.NotAllowed,
Message = String.Format(GeneratedErrorConstants.Messages.ResponseObjectUsedForUpdate, identitySecurityDefaultsEnforcementPolicyToUpdate.GetType().Name)
});
}
}
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<IdentitySecurityDefaultsEnforcementPolicy>(identitySecurityDefaultsEnforcementPolicyToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IIdentitySecurityDefaultsEnforcementPolicyRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IIdentitySecurityDefaultsEnforcementPolicyRequest Expand(Expression<Func<IdentitySecurityDefaultsEnforcementPolicy, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IIdentitySecurityDefaultsEnforcementPolicyRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IIdentitySecurityDefaultsEnforcementPolicyRequest Select(Expression<Func<IdentitySecurityDefaultsEnforcementPolicy, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="identitySecurityDefaultsEnforcementPolicyToInitialize">The <see cref="IdentitySecurityDefaultsEnforcementPolicy"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(IdentitySecurityDefaultsEnforcementPolicy identitySecurityDefaultsEnforcementPolicyToInitialize)
{
}
}
}
| 50.848101 | 233 | 0.673056 | [
"MIT"
] | DamienTehDemon/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/IdentitySecurityDefaultsEnforcementPolicyRequest.cs | 12,051 | C# |
using System.Collections.Generic;
using CoreLayer.Citrix.Adc.NitroClient.Commands.Configuration.System.SystemBackup;
using Xunit;
namespace CoreLayer.Citrix.Adc.NitroClientTests.Commands.Configuration.System.SystemBackup
{
public class SystemBackupDeleteCommandTest
{
[Theory]
[ClassData(typeof(SystemBackupDeleteCommandTestData))]
// TODO - Add more meaningful tests?
public void SystemBackupDeleteCommandValidationTest(
SystemBackupDeleteCommand command,
Dictionary<string, string> expected)
{
Assert.Equal(expected["Options"], command.Data.Options.ToString());
}
}
} | 35.105263 | 90 | 0.715142 | [
"Apache-2.0"
] | CoreLayer/CoreLayer.Citrix.Adc.Nitro | src/CoreLayer.Citrix.Adc.NitroClientTests/Commands/Configuration/System/SystemBackup/SystemBackupDeleteCommandTest.cs | 667 | 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.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Iot.Transform;
using Aliyun.Acs.Iot.Transform.V20180120;
namespace Aliyun.Acs.Iot.Model.V20180120
{
public class DeleteDevicePropRequest : RpcAcsRequest<DeleteDevicePropResponse>
{
public DeleteDevicePropRequest()
: base("Iot", "2018-01-20", "DeleteDeviceProp", "iot", "openAPI")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null);
}
}
private string productKey;
private string propKey;
private string iotId;
private string iotInstanceId;
private string deviceName;
public string ProductKey
{
get
{
return productKey;
}
set
{
productKey = value;
DictionaryUtil.Add(QueryParameters, "ProductKey", value);
}
}
public string PropKey
{
get
{
return propKey;
}
set
{
propKey = value;
DictionaryUtil.Add(QueryParameters, "PropKey", value);
}
}
public string IotId
{
get
{
return iotId;
}
set
{
iotId = value;
DictionaryUtil.Add(QueryParameters, "IotId", value);
}
}
public string IotInstanceId
{
get
{
return iotInstanceId;
}
set
{
iotInstanceId = value;
DictionaryUtil.Add(QueryParameters, "IotInstanceId", value);
}
}
public string DeviceName
{
get
{
return deviceName;
}
set
{
deviceName = value;
DictionaryUtil.Add(QueryParameters, "DeviceName", value);
}
}
public override DeleteDevicePropResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return DeleteDevicePropResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 24.512195 | 134 | 0.660697 | [
"Apache-2.0"
] | bitType/aliyun-openapi-net-sdk | aliyun-net-sdk-iot/Iot/Model/V20180120/DeleteDevicePropRequest.cs | 3,015 | C# |
// Copyright (c) Source Tree Solutions, LLC. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Author: Joe Audette
// Created: 2014-11-24
// Last Modified: 2014-11-25
//
//using cloudscribe.Resources;
using System;
using System.ComponentModel.DataAnnotations;
//using cloudscribe.Configuration.DataAnnotations;
namespace cloudscribe.Core.Web.ViewModels.CoreData
{
public class CurrencyViewModel
{
private Guid guid = Guid.Empty;
public Guid Guid
{
get { return guid; }
set { guid = value; }
}
private string title = string.Empty;
//[Display(Name = "Title", ResourceType = typeof(CommonResources))]
//[Required(ErrorMessageResourceName = "TitleRequired", ErrorMessageResourceType = typeof(CommonResources))]
public string Title
{
get { return title; }
set { title = value; }
}
private string code = string.Empty;
//[Display(Name = "Code", ResourceType = typeof(CommonResources))]
//[Required(ErrorMessageResourceName = "CodeRequired", ErrorMessageResourceType = typeof(CommonResources))]
//[StringLengthWithConfig(MinimumLength = 1, MaximumLength = 3, MinLengthKey = "CurrencyCodeMinLength", MaxLengthKey = "CurrencyCodeMaxLength", ErrorMessageResourceName = "CurrencyCodeLengthErrorFormat", ErrorMessageResourceType = typeof(CommonResources))]
public string Code
{
get { return code; }
set { code = value; }
}
}
}
| 34.851064 | 264 | 0.656899 | [
"Apache-2.0"
] | HananeMoshe/cloudscribe-master | src/cloudscribe.Core.Web/ViewModels/CoreData/CurrencyViewModel.cs | 1,640 | C# |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using PureCloudPlatform.Client.V2.Client;
namespace PureCloudPlatform.Client.V2.Model
{
/// <summary>
/// ChatSettings
/// </summary>
[DataContract]
public partial class ChatSettings : IEquatable<ChatSettings>
{
/// <summary>
/// Initializes a new instance of the <see cref="ChatSettings" /> class.
/// </summary>
/// <param name="MessageRetentionPeriodDays">Retention time for messages in days.</param>
public ChatSettings(int? MessageRetentionPeriodDays = null)
{
this.MessageRetentionPeriodDays = MessageRetentionPeriodDays;
}
/// <summary>
/// Retention time for messages in days
/// </summary>
/// <value>Retention time for messages in days</value>
[DataMember(Name="messageRetentionPeriodDays", EmitDefaultValue=false)]
public int? MessageRetentionPeriodDays { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ChatSettings {\n");
sb.Append(" MessageRetentionPeriodDays: ").Append(MessageRetentionPeriodDays).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
Formatting = Formatting.Indented
});
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as ChatSettings);
}
/// <summary>
/// Returns true if ChatSettings instances are equal
/// </summary>
/// <param name="other">Instance of ChatSettings to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ChatSettings other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return true &&
(
this.MessageRetentionPeriodDays == other.MessageRetentionPeriodDays ||
this.MessageRetentionPeriodDays != null &&
this.MessageRetentionPeriodDays.Equals(other.MessageRetentionPeriodDays)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.MessageRetentionPeriodDays != null)
hash = hash * 59 + this.MessageRetentionPeriodDays.GetHashCode();
return hash;
}
}
}
}
| 31.677165 | 104 | 0.555556 | [
"MIT"
] | F-V-L/platform-client-sdk-dotnet | build/src/PureCloudPlatform.Client.V2/Model/ChatSettings.cs | 4,023 | C# |
// <copyright file="DiagnosticSourceSubscriberBenchmark.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using BenchmarkDotNet.Attributes;
using OpenTelemetry.Instrumentation;
namespace Benchmarks.Instrumentation
{
[InProcess]
public class DiagnosticSourceSubscriberBenchmark
{
[Params(1, 2)]
public int SubscriberCount;
[Params(false, true)]
public bool UseIsEnabledFilter;
private const string SourceName = "MySource";
private readonly DiagnosticListener listener = new(SourceName);
private readonly List<DiagnosticSourceSubscriber> subscribers = new();
private readonly Func<string, object, object, bool> isEnabledFilter = (name, arg1, arg2) => ((EventPayload)arg1).Data == "Data";
[GlobalSetup]
public void GlobalSetup()
{
for (var i = 0; i < this.SubscriberCount; ++i)
{
var subscriber = new DiagnosticSourceSubscriber(
new TestListener(),
this.UseIsEnabledFilter ? this.isEnabledFilter : null);
this.subscribers.Add(subscriber);
subscriber.Subscribe();
}
}
[GlobalCleanup]
public void GlobalCleanup()
{
foreach (var subscriber in this.subscribers)
{
subscriber.Dispose();
}
}
[Benchmark]
public void WriteDiagnosticSourceEvent()
{
var payload = new EventPayload("Data");
this.listener.Write("SomeEvent", payload);
}
private struct EventPayload
{
public EventPayload(string data)
{
this.Data = data;
}
public string Data { get; }
}
private class TestListener : ListenerHandler
{
public TestListener()
: base(DiagnosticSourceSubscriberBenchmark.SourceName)
{
}
public override bool SupportsNullActivity => true;
}
}
}
| 30.351648 | 136 | 0.616582 | [
"Apache-2.0"
] | BearerPipelineTest/opentelemetry-dotnet | test/Benchmarks/Instrumentation/DiagnosticSourceSubscriberBenchmark.cs | 2,762 | C# |
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
using System;
using System.Collections.Generic;
#nullable disable
namespace T0001
{
public partial class OutUnpart
{
public string PnHeader { get; set; }
}
} | 22.153846 | 97 | 0.673611 | [
"MIT"
] | twoutlook/BlazorServerDbContextExample | BlazorServerEFCoreSample/T0001/OutUnpart.cs | 290 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Sistema
{
public partial class Cadastro_Funcionario : Form
{
MySqlConnection conexao;
MySqlCommand comando;
string strSQL;
public Cadastro_Funcionario()
{
InitializeComponent();
}
private void bntCadastro_Click(object sender, EventArgs e)
{
if (TxtNome.TextLength == 0 || TxtEmail.TextLength == 0 ||
TxtTelefone.TextLength == 0 || TxtCPF.TextLength == 0)
{
MessageBox.Show("Alguma das caixas de texto esta vazia!");
}
else
{
try
{
conexao = new MySqlConnection("Server=localhost;Database=sistema;Uid=root;Pwd=1234;");
strSQL = "INSERT INTO FUNCIONARIO " +
"(NOME,EMAIL,TELEFONE,CPF,DATANASC,SEXO) VALUES" +
"(@NOME,@EMAIL,@TELEFONE,@CPF,@DATANASC,@SEXO);";
comando = new MySqlCommand(strSQL, conexao);
comando.Parameters.AddWithValue("@NOME", TxtNome.Text);
comando.Parameters.AddWithValue("@EMAIL", TxtEmail.Text);
comando.Parameters.AddWithValue("@TELEFONE", TxtTelefone.Text);
comando.Parameters.AddWithValue("@CPF", TxtCPF.Text);
comando.Parameters.AddWithValue("@DATANASC", TxtData.Text);
comando.Parameters.AddWithValue("@SEXO", CheckOp());
conexao.Open();
comando.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conexao.Close();
conexao = null;
comando = null;
MessageBox.Show("Cliente cadastrado com sucesso");
}
}
}
private string CheckOp()
{
if (RadioMasculino.Checked == true)
{
return "Masculino";
}
else
{
return "Feminino";
}
}
private void button1_Click_1(object sender, EventArgs e)
{
this.Dispose();
}
}
}
| 32.425 | 106 | 0.502313 | [
"MIT"
] | Davi-Code-Developer/Sistema-Vidracaria | Sistema/Cadastro/Cadastro_Funcionario.cs | 2,596 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
namespace Marmalade.Expressions
{
public class Group : ICompareTo
{
public List<Boolean> booleans = new List<Boolean>();
private bool result;
private Comparison comparison;
private Match match;
public bool Result => result;
public Comparison Comparison => comparison;
public bool CompareNext => Comparison > Comparison.None;
public Group(Match match)
{
this.match = match;
ParseGroup();
}
public static implicit operator bool(Group group) => group.Result;
private void ParseGroup()
{
System.Text.RegularExpressions.Group boolGroup = match.Groups["bool"];
if (boolGroup.Success)
{
CaptureCollection captures = boolGroup.Captures;
for (int i = 0; i < captures.Count; i++)
{
Capture capture = captures[i];
Boolean boolean = new Boolean(capture);
booleans.Add(boolean);
}
result = CompareBooleans();
}
else
result = true;
comparison = ParseComparison();
}
private Comparison ParseComparison()
{
string comparisonString = match.Groups["group_comparison"].Value;
switch (comparisonString)
{
case "&&":
return Comparison.And;
case "||":
return Comparison.Or;
default:
return Comparison.None;
}
}
private bool CompareBooleans()
{
Boolean previousBoolean = null;
bool currentValue = true;
for (int i = 0; i < booleans.Count; i++)
{
Boolean boolean = booleans[i];
if (previousBoolean != null)
{
if (previousBoolean.Comparison == Comparison.And)
currentValue = previousBoolean && boolean;
else
currentValue = previousBoolean || boolean;
}
else
currentValue = boolean;
if (!boolean.CompareNext)
return currentValue;
previousBoolean = boolean;
}
return currentValue;
}
}
}
| 28.097826 | 82 | 0.495551 | [
"MIT"
] | mangosaucedev/com.mangosauce.marmalade.core | Runtime/Scripts/Expressions/Group.cs | 2,585 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ST_Computer
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 23.130435 | 66 | 0.586466 | [
"MIT"
] | JW33/Star-Trek-Computer | ST_Computer/Program.cs | 534 | C# |
using System.Threading.Tasks;
namespace Ola.Extensions.Identity.DisallowNames
{
/// <summary>
/// 非法名称管理接口。
/// </summary>
public interface IDisallowNameManager : ISingletonService
{
/// <summary>
/// 保存非法名称。
/// </summary>
/// <param name="names">名称集合,多个非法名称以“,”或“\r\n”分割。</param>
/// <returns>返回保存结果。</returns>
DataResult Save(string names);
/// <summary>
/// 删除非法名称。
/// </summary>
/// <param name="id">非法名称Id。</param>
/// <returns>返回删除结果。</returns>
DataResult Delete(int id);
/// <summary>
/// 删除非法名称。
/// </summary>
/// <param name="ids">非法名称Id。</param>
/// <returns>返回删除结果。</returns>
DataResult Delete(int[] ids);
/// <summary>
/// 判断当前名称是否为非法名称。
/// </summary>
/// <param name="name">名称。</param>
/// <returns>返回判断结果。</returns>
bool IsDisallowed(string name);
/// <summary>
/// 判断当前名称是否为非法名称。
/// </summary>
/// <param name="name">名称。</param>
/// <returns>返回判断结果。</returns>
Task<bool> IsDisallowedAsync(string name);
/// <summary>
/// 分页获取非法名称。
/// </summary>
/// <param name="query">非法名称查询实例。</param>
/// <returns>返回非法名称列表。</returns>
DisallowNameQuery Load(DisallowNameQuery query);
}
} | 27.153846 | 65 | 0.509207 | [
"MIT"
] | Oladn/Ola | Ola.Extensions/Identity/DisallowNames/IDisallowNameManager.cs | 1,726 | C# |
/*
* SendinBlue API
*
* SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails and SMS - and much more... You can download our wrappers at https://github.com/orgs/sendinblue **Possible responses** | Code | Message | | :- -- -- -- -- -- --: | - -- -- -- -- -- -- | | 200 | OK. Successful Request | | 201 | OK. Successful Creation | | 202 | OK. Request accepted | | 204 | OK. Successful Update/Deletion | | 400 | Error. Bad Request | | 401 | Error. Authentication Needed | | 402 | Error. Not enough credit, plan upgrade needed | | 403 | Error. Permission denied | | 404 | Error. Object does not exist | | 405 | Error. Method not allowed | | 406 | Error. Not Acceptable |
*
* OpenAPI spec version: 3.0.0
* Contact: contact@sendinblue.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using SwaggerDateConverter = sib_api_v3_sdk.Client.SwaggerDateConverter;
namespace sib_api_v3_sdk.Model
{
/// <summary>
/// RemoveContactFromList
/// </summary>
[DataContract]
public partial class RemoveContactFromList : IEquatable<RemoveContactFromList>
{
/// <summary>
/// Initializes a new instance of the <see cref="RemoveContactFromList" /> class.
/// </summary>
/// <param name="emails">Required if 'all' is false. Emails to remove from a list. You can pass a maximum of 150 emails for removal in one request..</param>
/// <param name="all">Required if 'emails' is empty. Remove all existing contacts from a list.</param>
public RemoveContactFromList(List<string> emails = default(List<string>), bool? all = default(bool?))
{
this.Emails = emails;
this.All = all;
}
/// <summary>
/// Required if 'all' is false. Emails to remove from a list. You can pass a maximum of 150 emails for removal in one request.
/// </summary>
/// <value>Required if 'all' is false. Emails to remove from a list. You can pass a maximum of 150 emails for removal in one request.</value>
[DataMember(Name="emails", EmitDefaultValue=false)]
public List<string> Emails { get; set; }
/// <summary>
/// Required if 'emails' is empty. Remove all existing contacts from a list
/// </summary>
/// <value>Required if 'emails' is empty. Remove all existing contacts from a list</value>
[DataMember(Name="all", EmitDefaultValue=false)]
public bool? All { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class RemoveContactFromList {\n");
sb.Append(" Emails: ").Append(Emails).Append("\n");
sb.Append(" All: ").Append(All).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as RemoveContactFromList);
}
/// <summary>
/// Returns true if RemoveContactFromList instances are equal
/// </summary>
/// <param name="input">Instance of RemoveContactFromList to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(RemoveContactFromList input)
{
if (input == null)
return false;
return
(
this.Emails == input.Emails ||
this.Emails != null &&
this.Emails.SequenceEqual(input.Emails)
) &&
(
this.All == input.All ||
(this.All != null &&
this.All.Equals(input.All))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Emails != null)
hashCode = hashCode * 59 + this.Emails.GetHashCode();
if (this.All != null)
hashCode = hashCode * 59 + this.All.GetHashCode();
return hashCode;
}
}
}
}
| 41.816794 | 853 | 0.574297 | [
"MIT"
] | dbraillon/APIv3-csharp-library | src/sib_api_v3_sdk/Model/RemoveContactFromList.cs | 5,478 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DocumentModel;
using DynamoDB.Libs;
using DynamoDB.Models;
using Amazon.DynamoDBv2.Model;
using System.Net;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace DynamoDB_3.Controllers
{
[Produces("application/json")]
[Route("api/DynamoDb")]
public class DynamoDbController : Controller
{
private readonly IPutItem _putItem;
private readonly IGetItem _getItem;
private readonly IUpdateItem _updateItem;
private readonly IDeleteItem _deleteItem;
public DynamoDbController(IGetItem getItem, IPutItem putItem, IUpdateItem updateItem, IDeleteItem deleteItem)
{
_getItem = getItem;
_putItem = putItem;
_updateItem = updateItem;
_deleteItem = deleteItem;
}
#region GET
[Route("getitems")]
public async Task<JsonResult> GetItems([FromQuery] int? id, string replydatetime)
{
Item item = new Item();
item.Id = id.Value;
item.ReplyDateTime = replydatetime;
var jsonResult = await _getItem.GetItems<Item>(item, Item.nomeTabela);
return Json(jsonResult);
}
#endregion
#region PUT
[Route("putitems")]
public async Task<IActionResult> PutItems([FromQuery] int id, string replydatetime, double? price)
{
Item item = new Item();
item.Id = id;
item.Price = price;
item.ReplyDateTime = replydatetime;
var response = await _putItem.PutItems<Item>(item, Item.nomeTabela);
if (response.HttpStatusCode.Equals(HttpStatusCode.OK))
return Ok();
else
return BadRequest(response);
}
#endregion
#region UPDATE
[Route("updateitems")]
public async Task<IActionResult> UpdateItems([FromQuery] int id, string replydatetime, double price)
{
Item item = new Item();
item.Id = id;
item.ReplyDateTime = replydatetime;
item.Price = price;
var response = await _updateItem.UpdateItems<Item>(item, Item.nomeTabela);
if (response.HttpStatusCode.Equals(HttpStatusCode.OK))
return Ok();
else
return BadRequest(response);
}
#endregion
#region DELETE
[Route("deleteitems")]
public async Task<IActionResult> DeleteItems([FromQuery] int id, string replydatetime)
{
Item item = new Item();
item.Id = id;
item.ReplyDateTime = replydatetime;
var response = await _deleteItem.DeleteItems<Item>(item, Item.nomeTabela);
if (response.HttpStatusCode.Equals(HttpStatusCode.OK))
return Ok();
else
return BadRequest(response);
}
#endregion
}
}
| 30.666667 | 118 | 0.578804 | [
"CC0-1.0"
] | danilocrispim/DynamoDB_Component | DynamoDB_3.1/Controllers/DynamoDbController.cs | 3,314 | C# |
using System.Collections.Generic;
using dnlib.DotNet;
using NoFuserEx.Deobfuscator.Deobfuscators;
using NoFuserEx.Deobfuscator.Deobfuscators.Constants;
namespace NoFuserEx.Deobfuscator {
internal class DeobfuscatorManager {
readonly AssemblyManager assemblyManager;
readonly List<IDeobfuscator> deobfuscators;
internal DeobfuscatorManager(AssemblyManager assemblyManager) {
this.assemblyManager = assemblyManager;
deobfuscators = new List<IDeobfuscator>();
}
void SelectDeobfuscators() {
Logger.Verbose("Adding deobfuscators...");
if (!Options.NoUnpack) {
deobfuscators.Add(new CompressorDeobfuscator());
Logger.VeryVerbose("Added compressor deobfuscator.");
}
if (!Options.NoTamper) {
deobfuscators.Add(new AntiTamperDeobfuscator());
Logger.VeryVerbose("Added anti-tamper deobfuscator.");
}
if (!Options.NoResources) {
deobfuscators.Add(new ResourcesDeobfuscator());
Logger.VeryVerbose("Added resources deobfuscator.");
}
if (!Options.NoConstants) {
deobfuscators.Add(new ConstantsDeobfuscator());
Logger.VeryVerbose("Added constants deobfuscator.");
}
if (!Options.NoProxyCalls) {
deobfuscators.Add(new ProxyDeobfuscator());
Logger.VeryVerbose("Added proxy deobfuscator.");
}
deobfuscators.Add(new AntiDumperDeobfuscator());
Logger.VeryVerbose("Added anti-dumper deobfuscator.");
deobfuscators.Add(new AntiDebuggerDeobfuscator());
Logger.VeryVerbose("Added anti-debugger deobfuscator.");
}
internal void Start() {
SelectDeobfuscators();
DetectConfuserVersion();
foreach (var deobfuscator in deobfuscators) {
var deobfuscated = deobfuscator.Deobfuscate(assemblyManager);
if (deobfuscated)
deobfuscator.Log();
}
Logger.WriteLine(string.Empty);
}
void DetectConfuserVersion() {
Logger.Verbose("Detecting ConfuserEx version...");
var versions = new List<string>();
var module = assemblyManager.Module;
foreach (var attribute in module.CustomAttributes) {
if (attribute.TypeFullName != "ConfusedByAttribute")
continue;
foreach (var argument in attribute.ConstructorArguments) {
if (argument.Type.ElementType != ElementType.String)
continue;
var value = argument.Value.ToString();
if (!value.Contains("ConfuserEx"))
continue;
Logger.Info($"Detected: {value}");
versions.Add(value);
}
}
if (versions.Count >= 1)
return;
if (Options.ForceDeobfuscation) {
Logger.Info("Forced deobfuscation.");
return;
}
Logger.Exclamation("ConfuserEx doesn't detected. Use de4dot.");
Logger.Exit();
}
}
}
| 35.734043 | 77 | 0.561477 | [
"MIT"
] | Aholicknight/NoFuserEx | NoFuserEx/NoFuserEx/Deobfuscator/DeobfuscatorManager.cs | 3,361 | C# |
using bbt.gateway.common.Repositories;
namespace bbt.gateway.common
{
public class RepositoryManager : IRepositoryManager
{
private readonly DatabaseContext _databaseContext;
//private readonly DodgeDatabaseContext _dodgeDatabaseContext;
private readonly SmsBankingDatabaseContext _smsBankingDatabaseContext;
//private UserRepository _userRepository;
private DirectBlacklistRepository _directBlacklistRepository;
private HeaderRepository _headerRepository;
private OperatorRepository _operatorRepository;
private BlacklistEntryRepository _blacklistEntryRepository;
private PhoneConfigurationRepository _phoneConfigurationRepository;
private MailConfigurationRepository _mailConfigurationRepository;
private OtpRequestLogRepository _otpRequestLogRepository;
private MailRequestLogRepository _mailRequestLogRepository;
private PushNotificationRequestLogRepository _pushNotificationRequestLogRepository;
private SmsResponseLogRepository _smsResponseLogRepository;
private SmsRequestLogRepository _smsRequestLogRepository;
private OtpResponseLogRepository _otpResponseLogRepository;
private MailResponseLogRepository _mailResponseLogRepository;
private PushNotificationResponseLogRepository _pushNotificationResponseLogRepository;
private OtpTrackingLogRepository _otpTrackingLogRepository;
private TransactionRepository _transactionRepository;
private WhitelistRepository _whitelistRepository;
public RepositoryManager(DatabaseContext databaseContext,
SmsBankingDatabaseContext smsBankingDatabaseContext)
{
_databaseContext = databaseContext;
//_dodgeDatabaseContext = dodgeDatabaseContext;
_smsBankingDatabaseContext = smsBankingDatabaseContext;
}
public IHeaderRepository Headers => _headerRepository ??= new HeaderRepository(_databaseContext);
public IOperatorRepository Operators => _operatorRepository ??= new OperatorRepository(_databaseContext);
public IBlacklistEntryRepository BlackListEntries => _blacklistEntryRepository ??= new BlacklistEntryRepository(_databaseContext);
public IPhoneConfigurationRepository PhoneConfigurations => _phoneConfigurationRepository ??= new PhoneConfigurationRepository(_databaseContext);
public IOtpRequestLogRepository OtpRequestLogs => _otpRequestLogRepository ??= new OtpRequestLogRepository(_databaseContext);
public ISmsResponseLogRepository SmsResponseLogs => _smsResponseLogRepository ??= new SmsResponseLogRepository(_databaseContext);
public ISmsRequestLogRepository SmsRequestLogs => _smsRequestLogRepository ?? new SmsRequestLogRepository(_databaseContext);
public IOtpResponseLogRepository OtpResponseLogs => _otpResponseLogRepository ??= new OtpResponseLogRepository(_databaseContext);
public IOtpTrackingLogRepository OtpTrackingLog => _otpTrackingLogRepository ??= new OtpTrackingLogRepository(_databaseContext);
//public IUserRepository Users => _userRepository ??= new UserRepository(_dodgeDatabaseContext);
public IDirectBlacklistRepository DirectBlacklists => _directBlacklistRepository ??= new DirectBlacklistRepository(_smsBankingDatabaseContext);
public IMailConfigurationRepository MailConfigurations => _mailConfigurationRepository ??= new MailConfigurationRepository(_databaseContext);
public IMailRequestLogRepository MailRequestLogs => _mailRequestLogRepository ??= new MailRequestLogRepository(_databaseContext);
public IMailResponseLogRepository MailResponseLogs => _mailResponseLogRepository ??= new MailResponseLogRepository(_databaseContext);
public IPushNotificationRequestLogRepository PushNotificationRequestLogs => _pushNotificationRequestLogRepository ??= new PushNotificationRequestLogRepository(_databaseContext);
public IPushNotificationResponseLogRepository PushNotificationResponseLogs => _pushNotificationResponseLogRepository ??= new PushNotificationResponseLogRepository(_databaseContext);
public ITransactionRepository Transactions => _transactionRepository ??= new TransactionRepository(_databaseContext);
public IWhitelistRepository Whitelist => _whitelistRepository ??= new WhitelistRepository(_databaseContext);
public int SaveChanges()
{
return _databaseContext.SaveChanges();
}
//public int SaveDodgeChanges()
//{
// return _dodgeDatabaseContext.SaveChanges();
//}
public int SaveSmsBankingChanges()
{
return _smsBankingDatabaseContext.SaveChanges();
}
public void Dispose()
{
_databaseContext.Dispose();
//_dodgeDatabaseContext.Dispose();
_smsBankingDatabaseContext.Dispose();
}
}
}
| 52.231579 | 189 | 0.778315 | [
"MIT"
] | hub-burgan-com-tr/bbt.gateway.messaging | bbt.gateway.common/RepositoryManager.cs | 4,964 | C# |
#region License
// Copyright (c) 2014 Tim Fischer
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the 'Software'), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.Collections.Generic;
using System.Threading.Tasks;
using Koden.Utils.Models;
namespace Koden.Utils.REST
{
/// <summary>
/// Interface to Asynchronous REST Client
/// </summary>
public interface IRESTClientAsync
{
/// <summary>
/// Gets or sets the additional headers.
/// </summary>
/// <value>
/// The additional headers.
/// </value>
Dictionary<string, string> AdditionalHeaders { get; set; }
/// <summary>
/// Gets or sets the type of the content.
/// </summary>
/// <value>
/// The type of the content.
/// </value>
string ContentType { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [log enabled].
/// </summary>
/// <value>
/// <c>true</c> if [log enabled]; otherwise, <c>false</c>.
/// </value>
bool LogEnabled { get; set; }
/// <summary>
/// Gets or sets the method (GET,POST,PUT, etc).
/// </summary>
/// <value>
/// The method.
/// </value>
HTTPOperation Method { get; set; }
/// <summary>
/// Gets or sets the data to POST to an API.
/// </summary>
/// <value>
/// The post data.
/// </value>
string PostData { get; set; }
/// <summary>
/// Gets or sets the time out.
/// </summary>
/// <value>
/// The time out.
/// </value>
int TimeOut { get; set; }
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
void Dispose();
/// <summary>
/// Does the request asynchronously.
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
Task<FWRetVal<string>> DoRequestAsync(string parameters);
/// <summary>
/// Does the request asynchronously.
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <param name="userID">The user identifier.</param>
/// <param name="password">The password.</param>
/// <param name="timeOut">The time out.</param>
/// <param name="authtype">The authtype.</param>
/// <returns></returns>
Task<FWRetVal<string>> DoRequestAsync(string parameters, string userID, string password, int timeOut, string authtype);
/// <summary>
/// Calls a RESTful API using login Token Gets the API data.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="restOperation">The rest operation (GET,DELETE,PUT,etc).</param>
/// <param name="endpoint">The endpoint.</param>
/// <param name="apiMethod">The API method.</param>
/// <param name="loginToken">The login token.</param>
/// <param name="formData">The form data.</param>
/// <param name="postAsJSON">if set to <c>true</c> [post as json].</param>
/// <param name="returnJSON">if set to <c>true</c> [return json].</param>
/// <param name="isOData">if set to <c>true</c> [is o data].</param>
/// <returns></returns>
Task<FWRetVal<T>> CallAPIUsingTokenAsync<T>(HTTPOperation restOperation, string endpoint, string apiMethod, Dictionary<string, string> loginToken, string formData, bool postAsJSON, bool returnJSON, bool isOData);
/// <summary>
/// Gets the login token (generally at login).
/// </summary>
/// <param name="endpoint">The endpoint.</param>
/// <param name="userID">The user identifier.</param>
/// <param name="password">The password.</param>
/// <returns></returns>
Task<Dictionary<string, string>> GetLoginTokenAsync(string endpoint, string userID, string password);
/// <summary>
/// Gets the login token (generally at login).
/// </summary>
/// <param name="endpoint">The endpoint.</param>
/// <param name="userID">The user identifier.</param>
/// <param name="password">The password.</param>
/// <param name="company">The Company.</param>
/// <returns></returns>
Task<Dictionary<string, string>> GetLoginTokenAsync(string endpoint, string userID, string password, string company);
}
}
| 40.40146 | 220 | 0.597651 | [
"Unlicense"
] | TJF0700/Koden | Koden.Utils/Interfaces/IRESTClientAsync.cs | 5,535 | C# |
using System;
using System.ComponentModel;
using Windows.ApplicationModel;
namespace Microsoft.Maui.Controls.Compatibility.Platform.UWP
{
public abstract class WindowsBasePage : Microsoft.UI.Xaml.Window
{
Application _application;
public WindowsBasePage()
{
if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled)
{
Microsoft.UI.Xaml.Application.Current.Suspending += OnApplicationSuspending;
Microsoft.UI.Xaml.Application.Current.Resuming += OnApplicationResuming;
}
}
internal Platform Platform { get; private set; }
public abstract Application CreateApplication();
protected abstract Platform CreatePlatform();
public virtual void LoadApplication(Application application)
{
if (application == null)
throw new ArgumentNullException("application");
_application = application;
Application.SetCurrentApplication(application);
if (_application.MainPage != null)
RegisterWindow(_application.MainPage);
application.PropertyChanged += OnApplicationPropertyChanged;
_application.SendStart();
}
protected void RegisterWindow(Page page)
{
if (page == null)
throw new ArgumentNullException("page");
Platform = CreatePlatform();
Platform.SetPage(page);
}
void OnApplicationPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "MainPage")
{
if (Platform == null)
RegisterWindow(_application.MainPage);
Platform.SetPage(_application.MainPage);
}
}
void OnApplicationResuming(object sender, object e)
{
Application.Current?.SendResume();
}
async void OnApplicationSuspending(object sender, SuspendingEventArgs e)
{
var sendSleepTask = Application.Current?.SendSleepAsync();
if (sendSleepTask == null)
return;
SuspendingDeferral deferral = e.SuspendingOperation.GetDeferral();
try
{
await sendSleepTask;
}
finally
{
deferral.Complete();
}
}
}
} | 24.024691 | 80 | 0.735355 | [
"MIT"
] | JanNepras/maui | src/Compatibility/Core/src/UAP/WindowsBasePage.cs | 1,946 | C# |
using IceShopBL;
using IceShopDB.Models;
using IceShopLib;
using IceShopLib.Validation;
using Serilog;
using System;
using System.Collections.Generic;
using System.Text;
namespace IceShopUI.Menus
{
internal sealed class MenuManager
{
private static readonly MenuManager _instance = new MenuManager();
internal Queue<IMenu> MenuChain;
static MenuManager() { }
private MenuManager() { MenuChain = new Queue<IMenu>(); }
public static MenuManager Instance { get { return _instance; } }
internal void StartMenuChain(IMenu firstMenu)
{
Log.Information($"Starting menu chain...");
ReadyNextMenu(firstMenu);
RunThroughMenuChain();
}
internal void ReadyNextMenu(IMenu nextMenu)
{
Log.Information($"Adding new menu to menu chain: {nextMenu.GetType().Name}");
MenuChain.Enqueue(nextMenu);
}
internal void RunThroughMenuChain()
{
while (MenuChain.Count > 0)
{
MenuChain.Dequeue().Run();
}
}
}
}
| 24.021277 | 89 | 0.60496 | [
"MIT"
] | 201019-UiPath/WeisVincent-P0 | IceShop/IceShopUI/Menus/MenuManager.cs | 1,131 | C# |
#region License
/*
Copyright © 2014-2019 European Support Limited
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.
*/
#endregion
using Amdocs.Ginger.Common;
using Amdocs.Ginger.Repository;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace Ginger
{
/// <summary>
/// Interaction logic for ucTag.xaml
/// </summary>
public partial class ucTag : UserControl
{
public Guid GUID { get { return mTag.Guid; } }
RepositoryItemTag mTag;
BrushConverter bc = new BrushConverter();
public ucTag(RepositoryItemTag tag)
{
InitializeComponent();
mTag = tag;
GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(lblTagName, Label.ContentProperty, mTag, RepositoryItemTag.Fields.Name);
GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(lblTagName, Label.ToolTipProperty, mTag, RepositoryItemTag.Fields.Description);
closeImage.Visibility = Visibility.Hidden;
xDeleteTagBtn.Tag = tag;
tagStack.ToolTip = tag.Name;
lblTagName.ToolTip = tag.Name;
}
public void SetLabelText(string text)
{
lblTagName.Content = text;
}
private void tagStack_MouseLeave(object sender, MouseEventArgs e)
{
tagStack.Background = (Brush)FindResource("$SelectionColor_VeryLightBlue");
closeImage.Visibility = Visibility.Collapsed;
}
private void tagStack_MouseEnter(object sender, MouseEventArgs e)
{
tagStack.Background = (Brush)FindResource("$SelectionColor_Pink");
closeImage.Visibility = Visibility.Visible;
}
}
} | 32.257143 | 156 | 0.686005 | [
"Apache-2.0"
] | fainagof/Ginger | Ginger/Ginger/TagsLib/ucTag.xaml.cs | 2,259 | C# |
// Copyright (c) 2019, WebsitePanel-Support.net.
// Distributed by websitepanel-support.net
// Build and fixed by Key4ce - IT Professionals
// https://www.key4ce.com
//
// Original source:
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace WebsitePanel.WebPortal
{
public class WebsitePanelSiteMapProvider : SiteMapProvider
{
private const string DEFAULT_PAGE_URL = "~/Default.aspx?pid=";
private const string ROOT_NODE_KEY = "wsp_root";
private const string PAGE_ID_PARAM = "pid";
private SiteMapProvider parentSiteMapProvider = null;
public WebsitePanelSiteMapProvider()
{
}
// Implement the CurrentNode property.
public override SiteMapNode CurrentNode
{
get
{
// page id
string pid = GetCurrentPageID();
// find page by id
if (PortalConfiguration.Site.Pages.ContainsKey(pid))
{
return CreateNodeFromPage(PortalConfiguration.Site.Pages[pid]);
}
return null;
}
}
// Implement the RootNode property.
public override SiteMapNode RootNode
{
get { return new SiteMapNode(this, ROOT_NODE_KEY, "", ""); }
}
// Implement the ParentProvider property.
public override SiteMapProvider ParentProvider
{
get { return parentSiteMapProvider; }
set { parentSiteMapProvider = value; }
}
// Implement the RootProvider property.
public override SiteMapProvider RootProvider
{
get
{
// If the current instance belongs to a provider hierarchy, it
// cannot be the RootProvider. Rely on the ParentProvider.
if (this.ParentProvider != null)
{
return ParentProvider.RootProvider;
}
// If the current instance does not have a ParentProvider, it is
// not a child in a hierarchy, and can be the RootProvider.
else
{
return this;
}
}
}
// Implement the FindSiteMapNode method.
public override SiteMapNode FindSiteMapNode(string rawUrl)
{
int idx = rawUrl.IndexOf("?pid=");
if (idx == -1)
return null;
// page id
string pid = null;
int ampIdx = rawUrl.IndexOf("&", idx);
pid = (ampIdx == -1) ? rawUrl.Substring(idx + 5) : rawUrl.Substring(idx + 5, ampIdx - idx - 5);
// find page by id
if (PortalConfiguration.Site.Pages.ContainsKey(pid))
{
return CreateNodeFromPage(PortalConfiguration.Site.Pages[pid]);
}
return null;
}
// Implement the GetChildNodes method.
public override SiteMapNodeCollection GetChildNodes(SiteMapNode node)
{
// pid
string pid = node.Key;
SiteMapNodeCollection children = new SiteMapNodeCollection();
if (PortalConfiguration.Site.Pages.ContainsKey(pid))
{
// fill collection
foreach (PortalPage page in PortalConfiguration.Site.Pages[pid].Pages)
{
if (page.Hidden)
continue;
SiteMapNode childNode = CreateNodeFromPage(page);
if (childNode != null)
children.Add(childNode);
}
}
else
{
// check if this is a root node
if (node.Key == ROOT_NODE_KEY)
{
foreach (PortalPage page in PortalConfiguration.Site.Pages.Values)
{
if (page.ParentPage == null && !page.Hidden)
{
SiteMapNode childNode = CreateNodeFromPage(page);
if (childNode != null)
children.Add(childNode);
}
}
}
}
return children;
}
protected override SiteMapNode GetRootNodeCore()
{
return RootNode;
}
// Implement the GetParentNode method.
public override SiteMapNode GetParentNode(SiteMapNode node)
{
string pid = node.Key;
if (pid == ROOT_NODE_KEY)
return null;
// find page
if (PortalConfiguration.Site.Pages.ContainsKey(pid))
{
PortalPage page = PortalConfiguration.Site.Pages[pid];
if (page.ParentPage != null)
return CreateNodeFromPage(page.ParentPage);
}
return null;
}
// Implement the ProviderBase.Initialize property.
// Initialize is used to initialize the state that the Provider holds, but
// not actually build the site map.
public override void Initialize(string name, NameValueCollection attributes)
{
lock (this)
{
base.Initialize(name, attributes);
}
}
private SiteMapNode CreateNodeFromPage(PortalPage page)
{
string url = String.IsNullOrEmpty(page.Url) ? DEFAULT_PAGE_URL + page.Name : page.Url;
string localizedName = DefaultPage.GetLocalizedPageName(page.Name);
NameValueCollection attrs = new NameValueCollection();
attrs["target"] = page.Target;
attrs["align"] = page.Align;
SiteMapNode node = new SiteMapNode(this, page.Name,
url,
localizedName,
localizedName, page.Roles, attrs, null, null);
if (!page.Enabled)
node.Url = "";
if (IsNodeAccessibleToUser(HttpContext.Current, node))
{
return node;
}
return null;
}
private bool IsNodeAccessibleToUser(HttpContext context, SiteMapNode node)
{
if (node == null)
{
throw new ArgumentNullException("node");
}
if (context == null)
{
throw new ArgumentNullException("context");
}
if (!this.SecurityTrimmingEnabled)
{
return true;
}
if (node.Roles != null)
{
return DefaultPage.IsAccessibleToUser(HttpContext.Current, node.Roles);
}
return false;
}
// Private helper methods
// Get the URL of the currently displayed page.
private string GetCurrentPageID()
{
try
{
// The current HttpContext.
HttpContext currentContext = HttpContext.Current;
if (currentContext != null)
{
return (currentContext.Request[PAGE_ID_PARAM] != null) ? currentContext.Request[PAGE_ID_PARAM] : "";
}
else
{
throw new Exception("HttpContext.Current is Invalid");
}
}
catch (Exception e)
{
throw new NotSupportedException("This provider requires a valid context.", e);
}
}
}
}
| 35.814815 | 121 | 0.538469 | [
"BSD-3-Clause"
] | Key4ce/Websitepanel | WebsitePanel/Sources/WebsitePanel.WebPortal/Code/WebsitePanelSiteMapProvider.cs | 9,670 | C# |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Garmin Canada Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2020 Garmin Canada Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 21.30Release
// Tag = production/akw/21.30.00-0-g324900c
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Linq;
namespace Dynastream.Fit
{
/// <summary>
/// Implements the UserProfile profile message.
/// </summary>
public class UserProfileMesg : Mesg
{
#region Fields
#endregion
/// <summary>
/// Field Numbers for <see cref="UserProfileMesg"/>
/// </summary>
public sealed class FieldDefNum
{
public const byte MessageIndex = 254;
public const byte FriendlyName = 0;
public const byte Gender = 1;
public const byte Age = 2;
public const byte Height = 3;
public const byte Weight = 4;
public const byte Language = 5;
public const byte ElevSetting = 6;
public const byte WeightSetting = 7;
public const byte RestingHeartRate = 8;
public const byte DefaultMaxRunningHeartRate = 9;
public const byte DefaultMaxBikingHeartRate = 10;
public const byte DefaultMaxHeartRate = 11;
public const byte HrSetting = 12;
public const byte SpeedSetting = 13;
public const byte DistSetting = 14;
public const byte PowerSetting = 16;
public const byte ActivityClass = 17;
public const byte PositionSetting = 18;
public const byte TemperatureSetting = 21;
public const byte LocalId = 22;
public const byte GlobalId = 23;
public const byte WakeTime = 28;
public const byte SleepTime = 29;
public const byte HeightSetting = 30;
public const byte UserRunningStepLength = 31;
public const byte UserWalkingStepLength = 32;
public const byte DepthSetting = 47;
public const byte DiveCount = 49;
public const byte Invalid = Fit.FieldNumInvalid;
}
#region Constructors
public UserProfileMesg() : base(Profile.GetMesg(MesgNum.UserProfile))
{
}
public UserProfileMesg(Mesg mesg) : base(mesg)
{
}
#endregion // Constructors
#region Methods
///<summary>
/// Retrieves the MessageIndex field</summary>
/// <returns>Returns nullable ushort representing the MessageIndex field</returns>
public ushort? GetMessageIndex()
{
Object val = GetFieldValue(254, 0, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToUInt16(val));
}
/// <summary>
/// Set MessageIndex field</summary>
/// <param name="messageIndex_">Nullable field value to be set</param>
public void SetMessageIndex(ushort? messageIndex_)
{
SetFieldValue(254, 0, messageIndex_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the FriendlyName field</summary>
/// <returns>Returns byte[] representing the FriendlyName field</returns>
public byte[] GetFriendlyName()
{
byte[] data = (byte[])GetFieldValue(0, 0, Fit.SubfieldIndexMainField);
return data.Take(data.Length - 1).ToArray();
}
///<summary>
/// Retrieves the FriendlyName field</summary>
/// <returns>Returns String representing the FriendlyName field</returns>
public String GetFriendlyNameAsString()
{
byte[] data = (byte[])GetFieldValue(0, 0, Fit.SubfieldIndexMainField);
return data != null ? Encoding.UTF8.GetString(data, 0, data.Length - 1) : null;
}
///<summary>
/// Set FriendlyName field</summary>
/// <param name="friendlyName_"> field value to be set</param>
public void SetFriendlyName(String friendlyName_)
{
byte[] data = Encoding.UTF8.GetBytes(friendlyName_);
byte[] zdata = new byte[data.Length + 1];
data.CopyTo(zdata, 0);
SetFieldValue(0, 0, zdata, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set FriendlyName field</summary>
/// <param name="friendlyName_">field value to be set</param>
public void SetFriendlyName(byte[] friendlyName_)
{
SetFieldValue(0, 0, friendlyName_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Gender field</summary>
/// <returns>Returns nullable Gender enum representing the Gender field</returns>
public Gender? GetGender()
{
object obj = GetFieldValue(1, 0, Fit.SubfieldIndexMainField);
Gender? value = obj == null ? (Gender?)null : (Gender)obj;
return value;
}
/// <summary>
/// Set Gender field</summary>
/// <param name="gender_">Nullable field value to be set</param>
public void SetGender(Gender? gender_)
{
SetFieldValue(1, 0, gender_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Age field
/// Units: years</summary>
/// <returns>Returns nullable byte representing the Age field</returns>
public byte? GetAge()
{
Object val = GetFieldValue(2, 0, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToByte(val));
}
/// <summary>
/// Set Age field
/// Units: years</summary>
/// <param name="age_">Nullable field value to be set</param>
public void SetAge(byte? age_)
{
SetFieldValue(2, 0, age_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Height field
/// Units: m</summary>
/// <returns>Returns nullable float representing the Height field</returns>
public float? GetHeight()
{
Object val = GetFieldValue(3, 0, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToSingle(val));
}
/// <summary>
/// Set Height field
/// Units: m</summary>
/// <param name="height_">Nullable field value to be set</param>
public void SetHeight(float? height_)
{
SetFieldValue(3, 0, height_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Weight field
/// Units: kg</summary>
/// <returns>Returns nullable float representing the Weight field</returns>
public float? GetWeight()
{
Object val = GetFieldValue(4, 0, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToSingle(val));
}
/// <summary>
/// Set Weight field
/// Units: kg</summary>
/// <param name="weight_">Nullable field value to be set</param>
public void SetWeight(float? weight_)
{
SetFieldValue(4, 0, weight_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Language field</summary>
/// <returns>Returns nullable Language enum representing the Language field</returns>
public Language? GetLanguage()
{
object obj = GetFieldValue(5, 0, Fit.SubfieldIndexMainField);
Language? value = obj == null ? (Language?)null : (Language)obj;
return value;
}
/// <summary>
/// Set Language field</summary>
/// <param name="language_">Nullable field value to be set</param>
public void SetLanguage(Language? language_)
{
SetFieldValue(5, 0, language_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ElevSetting field</summary>
/// <returns>Returns nullable DisplayMeasure enum representing the ElevSetting field</returns>
public DisplayMeasure? GetElevSetting()
{
object obj = GetFieldValue(6, 0, Fit.SubfieldIndexMainField);
DisplayMeasure? value = obj == null ? (DisplayMeasure?)null : (DisplayMeasure)obj;
return value;
}
/// <summary>
/// Set ElevSetting field</summary>
/// <param name="elevSetting_">Nullable field value to be set</param>
public void SetElevSetting(DisplayMeasure? elevSetting_)
{
SetFieldValue(6, 0, elevSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the WeightSetting field</summary>
/// <returns>Returns nullable DisplayMeasure enum representing the WeightSetting field</returns>
public DisplayMeasure? GetWeightSetting()
{
object obj = GetFieldValue(7, 0, Fit.SubfieldIndexMainField);
DisplayMeasure? value = obj == null ? (DisplayMeasure?)null : (DisplayMeasure)obj;
return value;
}
/// <summary>
/// Set WeightSetting field</summary>
/// <param name="weightSetting_">Nullable field value to be set</param>
public void SetWeightSetting(DisplayMeasure? weightSetting_)
{
SetFieldValue(7, 0, weightSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the RestingHeartRate field
/// Units: bpm</summary>
/// <returns>Returns nullable byte representing the RestingHeartRate field</returns>
public byte? GetRestingHeartRate()
{
Object val = GetFieldValue(8, 0, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToByte(val));
}
/// <summary>
/// Set RestingHeartRate field
/// Units: bpm</summary>
/// <param name="restingHeartRate_">Nullable field value to be set</param>
public void SetRestingHeartRate(byte? restingHeartRate_)
{
SetFieldValue(8, 0, restingHeartRate_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DefaultMaxRunningHeartRate field
/// Units: bpm</summary>
/// <returns>Returns nullable byte representing the DefaultMaxRunningHeartRate field</returns>
public byte? GetDefaultMaxRunningHeartRate()
{
Object val = GetFieldValue(9, 0, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToByte(val));
}
/// <summary>
/// Set DefaultMaxRunningHeartRate field
/// Units: bpm</summary>
/// <param name="defaultMaxRunningHeartRate_">Nullable field value to be set</param>
public void SetDefaultMaxRunningHeartRate(byte? defaultMaxRunningHeartRate_)
{
SetFieldValue(9, 0, defaultMaxRunningHeartRate_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DefaultMaxBikingHeartRate field
/// Units: bpm</summary>
/// <returns>Returns nullable byte representing the DefaultMaxBikingHeartRate field</returns>
public byte? GetDefaultMaxBikingHeartRate()
{
Object val = GetFieldValue(10, 0, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToByte(val));
}
/// <summary>
/// Set DefaultMaxBikingHeartRate field
/// Units: bpm</summary>
/// <param name="defaultMaxBikingHeartRate_">Nullable field value to be set</param>
public void SetDefaultMaxBikingHeartRate(byte? defaultMaxBikingHeartRate_)
{
SetFieldValue(10, 0, defaultMaxBikingHeartRate_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DefaultMaxHeartRate field
/// Units: bpm</summary>
/// <returns>Returns nullable byte representing the DefaultMaxHeartRate field</returns>
public byte? GetDefaultMaxHeartRate()
{
Object val = GetFieldValue(11, 0, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToByte(val));
}
/// <summary>
/// Set DefaultMaxHeartRate field
/// Units: bpm</summary>
/// <param name="defaultMaxHeartRate_">Nullable field value to be set</param>
public void SetDefaultMaxHeartRate(byte? defaultMaxHeartRate_)
{
SetFieldValue(11, 0, defaultMaxHeartRate_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the HrSetting field</summary>
/// <returns>Returns nullable DisplayHeart enum representing the HrSetting field</returns>
public DisplayHeart? GetHrSetting()
{
object obj = GetFieldValue(12, 0, Fit.SubfieldIndexMainField);
DisplayHeart? value = obj == null ? (DisplayHeart?)null : (DisplayHeart)obj;
return value;
}
/// <summary>
/// Set HrSetting field</summary>
/// <param name="hrSetting_">Nullable field value to be set</param>
public void SetHrSetting(DisplayHeart? hrSetting_)
{
SetFieldValue(12, 0, hrSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the SpeedSetting field</summary>
/// <returns>Returns nullable DisplayMeasure enum representing the SpeedSetting field</returns>
public DisplayMeasure? GetSpeedSetting()
{
object obj = GetFieldValue(13, 0, Fit.SubfieldIndexMainField);
DisplayMeasure? value = obj == null ? (DisplayMeasure?)null : (DisplayMeasure)obj;
return value;
}
/// <summary>
/// Set SpeedSetting field</summary>
/// <param name="speedSetting_">Nullable field value to be set</param>
public void SetSpeedSetting(DisplayMeasure? speedSetting_)
{
SetFieldValue(13, 0, speedSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DistSetting field</summary>
/// <returns>Returns nullable DisplayMeasure enum representing the DistSetting field</returns>
public DisplayMeasure? GetDistSetting()
{
object obj = GetFieldValue(14, 0, Fit.SubfieldIndexMainField);
DisplayMeasure? value = obj == null ? (DisplayMeasure?)null : (DisplayMeasure)obj;
return value;
}
/// <summary>
/// Set DistSetting field</summary>
/// <param name="distSetting_">Nullable field value to be set</param>
public void SetDistSetting(DisplayMeasure? distSetting_)
{
SetFieldValue(14, 0, distSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the PowerSetting field</summary>
/// <returns>Returns nullable DisplayPower enum representing the PowerSetting field</returns>
public DisplayPower? GetPowerSetting()
{
object obj = GetFieldValue(16, 0, Fit.SubfieldIndexMainField);
DisplayPower? value = obj == null ? (DisplayPower?)null : (DisplayPower)obj;
return value;
}
/// <summary>
/// Set PowerSetting field</summary>
/// <param name="powerSetting_">Nullable field value to be set</param>
public void SetPowerSetting(DisplayPower? powerSetting_)
{
SetFieldValue(16, 0, powerSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActivityClass field</summary>
/// <returns>Returns nullable ActivityClass enum representing the ActivityClass field</returns>
public ActivityClass? GetActivityClass()
{
object obj = GetFieldValue(17, 0, Fit.SubfieldIndexMainField);
ActivityClass? value = obj == null ? (ActivityClass?)null : (ActivityClass)obj;
return value;
}
/// <summary>
/// Set ActivityClass field</summary>
/// <param name="activityClass_">Nullable field value to be set</param>
public void SetActivityClass(ActivityClass? activityClass_)
{
SetFieldValue(17, 0, activityClass_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the PositionSetting field</summary>
/// <returns>Returns nullable DisplayPosition enum representing the PositionSetting field</returns>
public DisplayPosition? GetPositionSetting()
{
object obj = GetFieldValue(18, 0, Fit.SubfieldIndexMainField);
DisplayPosition? value = obj == null ? (DisplayPosition?)null : (DisplayPosition)obj;
return value;
}
/// <summary>
/// Set PositionSetting field</summary>
/// <param name="positionSetting_">Nullable field value to be set</param>
public void SetPositionSetting(DisplayPosition? positionSetting_)
{
SetFieldValue(18, 0, positionSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TemperatureSetting field</summary>
/// <returns>Returns nullable DisplayMeasure enum representing the TemperatureSetting field</returns>
public DisplayMeasure? GetTemperatureSetting()
{
object obj = GetFieldValue(21, 0, Fit.SubfieldIndexMainField);
DisplayMeasure? value = obj == null ? (DisplayMeasure?)null : (DisplayMeasure)obj;
return value;
}
/// <summary>
/// Set TemperatureSetting field</summary>
/// <param name="temperatureSetting_">Nullable field value to be set</param>
public void SetTemperatureSetting(DisplayMeasure? temperatureSetting_)
{
SetFieldValue(21, 0, temperatureSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the LocalId field</summary>
/// <returns>Returns nullable ushort representing the LocalId field</returns>
public ushort? GetLocalId()
{
Object val = GetFieldValue(22, 0, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToUInt16(val));
}
/// <summary>
/// Set LocalId field</summary>
/// <param name="localId_">Nullable field value to be set</param>
public void SetLocalId(ushort? localId_)
{
SetFieldValue(22, 0, localId_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field GlobalId</returns>
public int GetNumGlobalId()
{
return GetNumFieldValues(23, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the GlobalId field</summary>
/// <param name="index">0 based index of GlobalId element to retrieve</param>
/// <returns>Returns nullable byte representing the GlobalId field</returns>
public byte? GetGlobalId(int index)
{
Object val = GetFieldValue(23, index, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToByte(val));
}
/// <summary>
/// Set GlobalId field</summary>
/// <param name="index">0 based index of global_id</param>
/// <param name="globalId_">Nullable field value to be set</param>
public void SetGlobalId(int index, byte? globalId_)
{
SetFieldValue(23, index, globalId_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the WakeTime field
/// Comment: Typical wake time</summary>
/// <returns>Returns nullable uint representing the WakeTime field</returns>
public uint? GetWakeTime()
{
Object val = GetFieldValue(28, 0, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToUInt32(val));
}
/// <summary>
/// Set WakeTime field
/// Comment: Typical wake time</summary>
/// <param name="wakeTime_">Nullable field value to be set</param>
public void SetWakeTime(uint? wakeTime_)
{
SetFieldValue(28, 0, wakeTime_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the SleepTime field
/// Comment: Typical bed time</summary>
/// <returns>Returns nullable uint representing the SleepTime field</returns>
public uint? GetSleepTime()
{
Object val = GetFieldValue(29, 0, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToUInt32(val));
}
/// <summary>
/// Set SleepTime field
/// Comment: Typical bed time</summary>
/// <param name="sleepTime_">Nullable field value to be set</param>
public void SetSleepTime(uint? sleepTime_)
{
SetFieldValue(29, 0, sleepTime_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the HeightSetting field</summary>
/// <returns>Returns nullable DisplayMeasure enum representing the HeightSetting field</returns>
public DisplayMeasure? GetHeightSetting()
{
object obj = GetFieldValue(30, 0, Fit.SubfieldIndexMainField);
DisplayMeasure? value = obj == null ? (DisplayMeasure?)null : (DisplayMeasure)obj;
return value;
}
/// <summary>
/// Set HeightSetting field</summary>
/// <param name="heightSetting_">Nullable field value to be set</param>
public void SetHeightSetting(DisplayMeasure? heightSetting_)
{
SetFieldValue(30, 0, heightSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the UserRunningStepLength field
/// Units: m
/// Comment: User defined running step length set to 0 for auto length</summary>
/// <returns>Returns nullable float representing the UserRunningStepLength field</returns>
public float? GetUserRunningStepLength()
{
Object val = GetFieldValue(31, 0, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToSingle(val));
}
/// <summary>
/// Set UserRunningStepLength field
/// Units: m
/// Comment: User defined running step length set to 0 for auto length</summary>
/// <param name="userRunningStepLength_">Nullable field value to be set</param>
public void SetUserRunningStepLength(float? userRunningStepLength_)
{
SetFieldValue(31, 0, userRunningStepLength_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the UserWalkingStepLength field
/// Units: m
/// Comment: User defined walking step length set to 0 for auto length</summary>
/// <returns>Returns nullable float representing the UserWalkingStepLength field</returns>
public float? GetUserWalkingStepLength()
{
Object val = GetFieldValue(32, 0, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToSingle(val));
}
/// <summary>
/// Set UserWalkingStepLength field
/// Units: m
/// Comment: User defined walking step length set to 0 for auto length</summary>
/// <param name="userWalkingStepLength_">Nullable field value to be set</param>
public void SetUserWalkingStepLength(float? userWalkingStepLength_)
{
SetFieldValue(32, 0, userWalkingStepLength_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DepthSetting field</summary>
/// <returns>Returns nullable DisplayMeasure enum representing the DepthSetting field</returns>
public DisplayMeasure? GetDepthSetting()
{
object obj = GetFieldValue(47, 0, Fit.SubfieldIndexMainField);
DisplayMeasure? value = obj == null ? (DisplayMeasure?)null : (DisplayMeasure)obj;
return value;
}
/// <summary>
/// Set DepthSetting field</summary>
/// <param name="depthSetting_">Nullable field value to be set</param>
public void SetDepthSetting(DisplayMeasure? depthSetting_)
{
SetFieldValue(47, 0, depthSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DiveCount field</summary>
/// <returns>Returns nullable uint representing the DiveCount field</returns>
public uint? GetDiveCount()
{
Object val = GetFieldValue(49, 0, Fit.SubfieldIndexMainField);
if(val == null)
{
return null;
}
return (Convert.ToUInt32(val));
}
/// <summary>
/// Set DiveCount field</summary>
/// <param name="diveCount_">Nullable field value to be set</param>
public void SetDiveCount(uint? diveCount_)
{
SetFieldValue(49, 0, diveCount_, Fit.SubfieldIndexMainField);
}
#endregion // Methods
} // Class
} // namespace
| 37.777927 | 110 | 0.560476 | [
"MIT"
] | epvanhouten/PowerToSpeed | PowerToSpeed/Dynastream/Fit/Profile/Mesgs/UserProfileMesg.cs | 28,069 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace UPSik.DriverClient.Models
{
public class User
{
public enum UserType
{
Courier = 1,
Customer = 2
}
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public Address Address { get; set; }
public UserType Type { get; set; }
}
}
| 22.458333 | 44 | 0.556586 | [
"MIT"
] | PawelSzatkowski/UPSik | UPSik/UPSik.DriverClient/Models/User.cs | 541 | C# |
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using ICSharpCode.AvalonEdit.Utils;
using ICSharpCode.NRefactory;
using ICSharpCode.NRefactory.Editor;
namespace ICSharpCode.AvalonEdit.Document
{
/// <summary>
/// The TextAnchor class references an offset (a position between two characters).
/// It automatically updates the offset when text is inserted/removed in front of the anchor.
/// </summary>
/// <remarks>
/// <para>Use the <see cref="Offset"/> property to get the offset from a text anchor.
/// Use the <see cref="TextDocument.CreateAnchor"/> method to create an anchor from an offset.
/// </para>
/// <para>
/// The document will automatically update all text anchors; and because it uses weak references to do so,
/// the garbage collector can simply collect the anchor object when you don't need it anymore.
/// </para>
/// <para>Moreover, the document is able to efficiently update a large number of anchors without having to look
/// at each anchor object individually. Updating the offsets of all anchors usually only takes time logarithmic
/// to the number of anchors. Retrieving the <see cref="Offset"/> property also runs in O(lg N).</para>
/// <inheritdoc cref="IsDeleted" />
/// <inheritdoc cref="MovementType" />
/// <para>If you want to track a segment, you can use the <see cref="AnchorSegment"/> class which
/// implements <see cref="ISegment"/> using two text anchors.</para>
/// </remarks>
/// <example>
/// Usage:
/// <code>TextAnchor anchor = document.CreateAnchor(offset);
/// ChangeMyDocument();
/// int newOffset = anchor.Offset;
/// </code>
/// </example>
public sealed class TextAnchor : ITextAnchor
{
readonly TextDocument document;
internal TextAnchorNode node;
internal TextAnchor(TextDocument document)
{
this.document = document;
}
/// <summary>
/// Gets the document owning the anchor.
/// </summary>
public TextDocument Document {
get { return document; }
}
/// <inheritdoc/>
public AnchorMovementType MovementType { get; set; }
/// <inheritdoc/>
public bool SurviveDeletion { get; set; }
/// <inheritdoc/>
public bool IsDeleted {
get {
document.DebugVerifyAccess();
return node == null;
}
}
/// <inheritdoc/>
public event EventHandler Deleted;
internal void OnDeleted(DelayedEvents delayedEvents)
{
node = null;
delayedEvents.DelayedRaise(Deleted, this, EventArgs.Empty);
}
/// <summary>
/// Gets the offset of the text anchor.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
public int Offset {
get {
document.DebugVerifyAccess();
TextAnchorNode n = this.node;
if (n == null)
throw new InvalidOperationException();
int offset = n.length;
if (n.left != null)
offset += n.left.totalLength;
while (n.parent != null) {
if (n == n.parent.right) {
if (n.parent.left != null)
offset += n.parent.left.totalLength;
offset += n.parent.length;
}
n = n.parent;
}
return offset;
}
}
/// <summary>
/// Gets the line number of the anchor.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
public int Line {
get {
return document.GetLineByOffset(this.Offset).LineNumber;
}
}
/// <summary>
/// Gets the column number of this anchor.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
public int Column {
get {
int offset = this.Offset;
return offset - document.GetLineByOffset(offset).Offset + 1;
}
}
/// <summary>
/// Gets the text location of this anchor.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
public TextLocation Location {
get {
return document.GetLocation(this.Offset);
}
}
/// <inheritdoc/>
public override string ToString()
{
return "[TextAnchor Offset=" + Offset + "]";
}
}
}
| 30.391608 | 121 | 0.674643 | [
"MIT"
] | GlobalcachingEU/GSAKWrapper | ICSharpCode.AvalonEdit/Document/TextAnchor.cs | 4,348 | C# |
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public class XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapMongoDBBsonObjectIdWrapWrapWrapWrapWrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Type type = typeof(XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapMongoDBBsonObjectIdWrapWrapWrapWrap);
Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0);
Utils.EndObjectRegister(type, L, translator, null, null,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0);
Utils.RegisterFunc(L, Utils.CLS_IDX, "__Register", _m___Register_xlua_st_);
Utils.EndClassRegister(type, L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CreateInstance(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
if(LuaAPI.lua_gettop(L) == 1)
{
XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapMongoDBBsonObjectIdWrapWrapWrapWrap gen_ret = new XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapMongoDBBsonObjectIdWrapWrapWrapWrap();
translator.Push(L, gen_ret);
return 1;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapMongoDBBsonObjectIdWrapWrapWrapWrap constructor!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m___Register_xlua_st_(RealStatePtr L)
{
try {
{
System.IntPtr _L = LuaAPI.lua_touserdata(L, 1);
XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapMongoDBBsonObjectIdWrapWrapWrapWrap.__Register( _L );
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
}
}
| 26.845455 | 225 | 0.610227 | [
"MIT"
] | zxsean/DCET | Unity/Assets/Model/XLua/Gen/XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapMongoDBBsonObjectIdWrapWrapWrapWrapWrap.cs | 2,955 | C# |
// This file is part of Silk.NET.
//
// You may modify and distribute Silk.NET under the terms
// of the MIT license. See the LICENSE file for details.
using System;
using Silk.NET.Core.Attributes;
#pragma warning disable 1591
namespace Silk.NET.OpenGL
{
[NativeName("Name", "VertexProvokingMode")]
public enum VertexProvokingMode : int
{
[NativeName("Name", "GL_FIRST_VERTEX_CONVENTION")]
FirstVertexConvention = 0x8E4D,
[NativeName("Name", "GL_LAST_VERTEX_CONVENTION")]
LastVertexConvention = 0x8E4E,
}
}
| 24.347826 | 58 | 0.696429 | [
"MIT"
] | ThomasMiz/Silk.NET | src/OpenGL/Silk.NET.OpenGL/Enums/VertexProvokingMode.gen.cs | 560 | C# |
using HousingSite.Data;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using HousingSite.Pages.HouseMapComponents;
namespace HousingSite.Pages
{
public partial class HouseMapClass : ComponentBase
{
[Inject]
IJSRuntime JSRuntime { get; set; }
[Inject]
protected HouseTableService HouseService { get; set; }
[Inject]
protected MapService MappingService { get; set; }
#region Variables
private string sessionKey = "";
private string[] userPinCoords = null;
private string mapClicked = null;
private double clickX;
private double clickY;
protected List<HouseData> houseData = new List<HouseData>();
protected List<bool> housesInRadius = new List<bool>();
protected bool init = false;
protected int housesAdded = 0;
protected string statusText = "";
protected string city = "Nijmegen";
protected int priceMin = 200;
protected int priceMax = 800;
protected int area = 0;
protected int bedrooms = 0;
protected string place = "Nijmegen Platolaan";
protected double radius = 2.5;
protected int radiusTime = 10;
protected int housenum = 0;
protected bool viewSingleHouse = false;
protected int selectedHouse = -1;
protected bool routesCalculated = false;
protected string walkingRouteText = "Walking route";
protected string drivingRouteText = "Driving route";
protected string transitRouteText = "Transit route";
public enum HouseFilters { all, circle, isochrone };
protected static string[] houseFilterStrings = new string[3] { "All", "Only inside circle", "Only inside isochrone" };
protected HouseFilters selectedHouseFilter = HouseFilters.circle;
public enum TravelModes { none, walking, driving, transit };
protected static string[] travelModeStrings = new string[4] { "", "Walking", "Driving", "Public transport" };
protected TravelModes selectedTravelMode = TravelModes.driving;
public enum CalculationModes { none, time, distance };
protected static string[] calculationModeStrings = new string[3] { "", "Time", "Distance" };
protected CalculationModes selectedCalculationMode = CalculationModes.distance;
protected float travelTime = 10;
protected float travelDistance = 3;
protected bool showSearchOptions = true;
protected Dictionary<string, double[]> addressCoordinatesDictionary = new Dictionary<string, double[]>();
protected Dictionary<string, string> addressQueue = new Dictionary<string, string>();
protected KeyValuePair<string, double[]> baseAddress = new KeyValuePair<string, double[]>();
protected int transactions = 0;
protected bool AddUserLocationOnClick = false;
protected bool HouseCalculationsFinished = true;
protected int progress1Value = 0;
protected int progress2Value = 0;
protected int progress3Value = 0;
protected int progress1Max = 0;
protected int progress2Max = 0;
protected int progress3Max = 0;
protected int progress1Fill = 0;
protected int progress2Fill = 0;
protected int progress3Fill = 0;
public struct SearchParams
{
public string city;
public int priceMin;
public int priceMax;
public int area;
public int bedrooms;
}
public SearchParams lastSearchParams;
#endregion
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JSRuntime.InvokeAsync<string>("loadMapScenario", Credentials.BingMapsKey);
SyncSessionKey();
//Console.WriteLine("Hi");
}
//while (true)
//{
//Console.WriteLine(showSearchOptions);
//System.Threading.Thread.Sleep(1000);
//}
}
//public HouseMapComponent_SearchOptions SearchOptions;
//public HouseMapComponent_MapOptions MapOptions;
//protected async Task GetChildComponentVariables()
//{
// if (showSearchOptions)
// {
// await SearchOptions.UpdateParentVariables();
// }
// else await MapOptions.UpdateParentVariables();
// await Test();
//}
//protected async Task Test()
//{
// Console.WriteLine("Testy");
// Console.WriteLine("showSearchOptions = " + showSearchOptions);
// Console.WriteLine("city = " + city);
// Console.WriteLine("priceMin = " + priceMin);
// Console.WriteLine("priceMax = "+ priceMax);
// Console.WriteLine("area = " + area);
// Console.WriteLine("bedrooms = " + bedrooms);
// Console.WriteLine("selectedHouseFilter = " + selectedHouseFilter);
// Console.WriteLine("selectedTravelMode = " + selectedTravelMode);
// Console.WriteLine("selectedCalculationMode = " + selectedCalculationMode);
// Console.WriteLine("travelDistance = " + travelDistance);
// Console.WriteLine("travelTime = " + travelTime);
// Console.WriteLine("place = " + place);
// Console.WriteLine("radius = " + radius);
// Console.WriteLine("AddUserLocationOnClick = " + AddUserLocationOnClick);
//}
protected async Task MouseClicked(MouseEventArgs e)
{
clickX = e.ClientX;
clickY = e.ClientY;
mapClicked = null;
SyncMapClicked();
}
protected async Task ToggleAddUserLocationOnClick()
{
// Pass !AddUserLocationOnClick since it's not updated immediately
await JSRuntime.InvokeAsync<Task>("AddUserLocationOnClick", !AddUserLocationOnClick);
}
private async void CheckBaseKey()
{
if (baseAddress.Key == null || baseAddress.Value == null || baseAddress.Key != place)
{
//baseAddress = new KeyValuePair<string, double[]>(place, MappingService.GetPDOKinfoFromAddress(place));
double[] baseCoordinates = await MappingService.GetSingleLocationTask(place);
baseAddress = new KeyValuePair<string, double[]>(place, baseCoordinates);
transactions++;
Console.WriteLine("New base address: " + baseAddress.Key + " (" + baseAddress.Value[0] + " " + baseAddress.Value[1] + ")");
}
}
protected async Task FindHouses()
{
CheckBaseKey();
if (CheckIfSameParams())
{
Console.WriteLine("Same params. Refreshing view.");
await RefreshVisibleHouses();
}
else
{
HouseCalculationsFinished = false;
Console.WriteLine("Other params. Getting new data!");
houseData.Clear();
housesInRadius.Clear();
HouseService.houseData.Clear();
await JSRuntime.InvokeAsync<Task>("ClearHouses");
await JSRuntime.InvokeAsync<Task>("ClearHousePins");
await JSRuntime.InvokeAsync<Task>("CalculateCircleAtAddressWithRadius", baseAddress.Value, radius);
housesAdded = 0;
SetLastParams(city, priceMin, priceMax, area, bedrooms);
await HouseService.SetSearchParams(city, priceMin, priceMax, area, bedrooms);
progress1Max = HouseService.sitesChecked.Count;
for (int s = 0; s < HouseService.sitesChecked.Count; s++)
{
//progressValue1 = (s / HouseService.sitesChecked.Count) * 100;
string sn = HouseService.housingSites.Keys.ElementAt(s);
if (HouseService.sitesChecked[s] == true)
{
Console.WriteLine("Site " + s + "(" + sn + ") is checked!");
statusText = "Processing " + sn;
this.StateHasChanged();
await HouseService.RunAsync(s);
houseData = await HouseService.GetHouseData();
for(int h= housesInRadius.Count; h< houseData.Count; h++)
{
housesInRadius.Add(true);
}
Console.WriteLine(houseData.Count + " houses retrieved");
statusText = "Adding houses from " + sn;
this.StateHasChanged();
//await CheckHouseDistances();
//Console.WriteLine(housesInRadius.Count + " house distances checked");
//await AddColorPinsToHousesInRadius();
await AddHousesToQueue();
housesAdded = houseData.Count;
statusText = "Added houses from " + sn;
this.StateHasChanged();
}
progress1Value = s+1;
progress1Fill = (progress1Max == 0) ? 0 : (progress1Value * 100 / progress1Max);
//progress1Fill = (progress1Max == 0) ? 0 : (progress1Value / progress1Max) * 100;
this.StateHasChanged();
}
await AddHousesToQueue();
await UpdateDictionary();
await CheckHouseDistances();
//Console.WriteLine(housesInRadius.Count + " house distances checked");
//await AddColorPinsToHousesInRadius();
await AddColorPinsToAllHouses();
Console.WriteLine(transactions + " transactions done.");
await ApplyHouseFilter();
HouseCalculationsFinished = true;
//Debugging
//await HouseService.SetSearchParams(city, 100, 2000, area, bedrooms);
//await HouseService.RunAsync(0);
//houseData = await HouseService.GetHouseData();
//await AddPinsToHouses();
}
}
#region Map manipulation
protected async Task ClearMap()
{
await JSRuntime.InvokeAsync<Task>("ClearMap");
housenum = 1;
}
protected async Task PlacePinAtAddress()
{
CheckBaseKey();
//await JSRuntime.InvokeAsync<Task>("DrawCircleAtAddressWithRadius", place, radius);
await JSRuntime.InvokeAsync<Task>("AddBaseLocationPintoAddress", baseAddress.Value);
}
protected async Task DrawCircleAtAddress()
{
CheckBaseKey();
//await JSRuntime.InvokeAsync<Task>("DrawCircleAtAddressWithRadius", place, radius);
await JSRuntime.InvokeAsync<Task>("DrawCircleAtAddressWithRadius", baseAddress.Value, radius);
}
protected async Task DrawIsochroneAtAddress()
{
//await JSRuntime.InvokeAsync<Task>("DrawCircleAtAddressWithRadius", place, radius);
//await JSRuntime.InvokeAsync<Task>("GetIsochroneByTime", MappingService.GetPDOKinfoFromAddress(place), "walking", radiusTime); //GetIsochroneByTime
CheckBaseKey();
if (selectedCalculationMode == CalculationModes.time)
{
Console.WriteLine("Calculating with a " + selectedTravelMode + " time of " + travelTime + " minutes.");
await JSRuntime.InvokeAsync<Task>("GetIsochroneByTime", baseAddress.Value, selectedTravelMode.ToString(), travelTime);
}
else if (selectedCalculationMode == CalculationModes.distance)
{
Console.WriteLine("Calculating with a " + selectedTravelMode + " distance of " + travelDistance + " kilometres.");
await JSRuntime.InvokeAsync<Task>("GetIsochroneByDistance", baseAddress.Value, selectedTravelMode.ToString(), travelDistance);
}
else Console.WriteLine("No calculation mode selected.");
}
#endregion
#region Testing
protected string imageColor = "green";
protected async Task TestPin()
{
await JSRuntime.InvokeAsync<Task>("ClearMap");
//await JSRuntime.InvokeAsync<Task>("AddColorHousetoAddress", "Linie 544 Apeldoorn", "Title", "Description", imageColor);
await JSRuntime.InvokeAsync<Task>("AddColorHousetoAddress", MappingService.GetPDOKinfoFromAddress("Linie 544 Apeldoorn"), "Title", "Description", imageColor);
switch (imageColor)
{
case "green":
imageColor = "yellow";
break;
case "yellow":
imageColor = "red";
break;
case "red":
imageColor = "green";
break;
}
}
#endregion
protected async Task SwitchLayer()
{
viewSingleHouse = !viewSingleHouse;
this.StateHasChanged();
await JSRuntime.InvokeAsync<Task>("SwitchLayer");
await AddToSpecificLayer();
}
//protected async Task SetChosenHouse()
//{
// if (houseData == null || houseData.Count == 0) { return; }
// selectedHouse = 0;
// routesCalculated = false;
// string houseQueryExtend = houseData[selectedHouse].street + " " + houseData[selectedHouse].postalCode + " " + houseData[selectedHouse].city + " Netherlands";
// //await JSRuntime.InvokeAsync<Task>("SetChosenHouse", houseQueryExtend);
// await JSRuntime.InvokeAsync<Task>("SetChosenHouse", MappingService.GetPDOKinfoFromAddress(houseQueryExtend));
// await GetRouteWithMode(houseQueryExtend, place, "Driving");
// await GetRouteWithMode(houseQueryExtend, place, "Walking");
// await GetRouteWithMode(houseQueryExtend, place, "Transit");
// routesCalculated = true;
//}
protected async Task SetChosenHouse(int housenum)
{
selectedHouse = housenum;
Console.WriteLine(selectedHouse);
routesCalculated = false;
double[] coords = addressCoordinatesDictionary[houseData[selectedHouse].postalCode.Replace(" ", "")];
if (coords != null)
{
Console.WriteLine("Coords: " + coords[0] + " " + coords[1]);
await JSRuntime.InvokeAsync<Task>("CheckAddressInsideBounds", coords);
}
//string houseQueryExtend = houseData[selectedHouse].street + " " + houseData[selectedHouse].postalCode + " " + houseData[selectedHouse].city + " Netherlands";
////await JSRuntime.InvokeAsync<Task>("SetChosenHouse", houseQueryExtend);
//double[] coords = MappingService.GetPDOKinfoFromAddress(houseQueryExtend);
////await JSRuntime.InvokeAsync<Task>("SetChosenHouse", coords);
//await JSRuntime.InvokeAsync<Task>("CheckAddressInsideIsochrone", coords);
//await GetRouteWithMode(houseQueryExtend, place, "Driving");
//await GetRouteWithMode(houseQueryExtend, place, "Walking");
//await GetRouteWithMode(houseQueryExtend, place, "Transit");
//routesCalculated = true;
await SwitchLayer();
}
protected async Task PlotRoute(string mode)
{
//await Task.Run(() => Console.WriteLine(mode));
await JSRuntime.InvokeAsync<Task>("PlotRoute", mode.ToLower());
}
protected async Task GetRoutes()
{
string houseQueryExtend = houseData[selectedHouse].street + " " + houseData[selectedHouse].postalCode + " " + houseData[selectedHouse].city + " Netherlands";
//await JSRuntime.InvokeAsync<Task>("SetChosenHouse", houseQueryExtend);
//await JSRuntime.InvokeAsync<Task>("SetChosenHouse", MappingService.GetPDOKinfoFromAddress(houseQueryExtend));
await JSRuntime.InvokeAsync<Task>("SetChosenHouse", addressCoordinatesDictionary[houseData[selectedHouse].postalCode.Replace(" ", "")]);
await GetRouteWithMode(houseQueryExtend, place, "Driving");
await GetRouteWithMode(houseQueryExtend, place, "Walking");
await GetRouteWithMode(houseQueryExtend, place, "Transit");
routesCalculated = true;
}
}
}
| 42.729798 | 171 | 0.591573 | [
"MIT"
] | MSGvanEmmerloot/HousingSite | HousingSite/Pages/HouseMapClass/HouseMapClass_Base.cs | 16,923 | 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("InfinysBreakfastOrders.Common")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("InfinysBreakfastOrders.Common")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("badb4299-2451-469f-8fd3-0b5f69b7ed17")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.675676 | 84 | 0.749825 | [
"MIT"
] | g-stoyanov/InfinysBreakfastOrders | Source/InfinysBreakfastOrders.Common/Properties/AssemblyInfo.cs | 1,434 | C# |
using System;
using System.ComponentModel;
using EfsTools.Attributes;
namespace EfsTools.Items.Nv
{
[Serializable]
[NvItemId(714)]
[Attributes(13)]
public class DataServicesMobileIpEnableProfile
{
public DataServicesMobileIpEnableProfile()
{
EnableProfs = new byte[6];
}
[ElementsCount(6)]
[ElementType("uint8")]
[Description("")]
public byte[] EnableProfs { get; set; }
}
} | 22.590909 | 51 | 0.579477 | [
"MIT"
] | HomerSp/EfsTools | EfsTools/Items/Nv/DataServicesMobileIpEnableProfile.cs | 497 | C# |
using System.Text;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Flatten.Contexts;
using DocumentFormat.OpenXml.Flatten.ElementConverters.CommonElement;
using dotnetCampus.OpenXmlUnitConverter;
using static DocumentFormat.OpenXml.Flatten.ElementConverters.ShapeGeometryConverters.ShapeGeometryFormulaHelper;
using ElementEmuSize = dotnetCampus.OpenXmlUnitConverter.EmuSize;
namespace DocumentFormat.OpenXml.Flatten.ElementConverters.ShapeGeometryConverters
{
/// <summary>
/// 双括号
/// </summary>
public class BracketPairGeometry : ShapeGeometryBase
{
/// <inheritdoc />
public override string? ToGeometryPathString(ElementEmuSize emuSize, AdjustValueList? adjusts = null)
{
return null;
}
/// <inheritdoc />
public override ShapePath[]? GetMultiShapePaths(ElementEmuSize emuSize, AdjustValueList? adjusts = null)
{
var (h, w, l, r, t, b, hd2, hd4, hd5, hd6, hd8, ss, hc, vc, ls, ss2, ss4, ss6, ss8, wd2, wd4, wd5, wd6, wd8, wd10, cd2, cd4, cd6, cd8) = GetFormulaProperties(emuSize);
// <avLst xmlns="http://schemas.openxmlformats.org/drawingml/2006/main">
// <gd name="adj" fmla="val 16667" />
//</avLst>
var customAdj = adjusts?.GetAdjustValue("adj");
var adj = customAdj ?? 16667d;
//当adj为最低为0,导致一些值为0,参与公式乘除运算,导致路径有误
adj = System.Math.Max(adj, 0.1);
//<gdLst xmlns="http://schemas.openxmlformats.org/drawingml/2006/main">
// <gd name="a" fmla="pin 0 adj 50000" />
var a = Pin(0, adj, 50000);
// <gd name="x1" fmla="*/ ss a 100000" />
var x1 = ss * a / 100000;
// <gd name="x2" fmla="+- r 0 x1" />
var x2 = r - x1;
// <gd name="y2" fmla="+- b 0 x1" />
var y2 = b - x1;
// <gd name="il" fmla="*/ x1 29289 100000" />
var il = x1 * 29289 / 100000;
// <gd name="ir" fmla="+- r 0 il" />
var ir = r - il;
// <gd name="ib" fmla="+- b 0 il" />
var ib = b - il;
//</gdLst>
var shapePaths = new ShapePath[3];
// <pathLst xmlns="http://schemas.openxmlformats.org/drawingml/2006/main">
// <path stroke="false" extrusionOk="false">
// <moveTo>
// <pt x="l" y="x1" />
// </moveTo>
var currentPoint = new EmuPoint(l, x1);
var stringPath = new StringBuilder();
stringPath.Append($"M {EmuToPixelString(currentPoint.X)},{EmuToPixelString(currentPoint.Y)} ");
// <arcTo wR="x1" hR="x1" stAng="cd2" swAng="cd4" />
var wR = x1;
var hR = x1;
var stAng = cd2;
var swAng = cd4;
currentPoint = ArcToToString(stringPath, currentPoint, wR, hR, stAng, swAng);
// <lnTo>
// <pt x="x2" y="t" />
// </lnTo>
currentPoint = LineToToString(stringPath, x2, t);
// <arcTo wR="x1" hR="x1" stAng="3cd4" swAng="cd4" />
wR = x1;
hR = x1;
stAng = 3 * cd4;
swAng = cd4;
currentPoint = ArcToToString(stringPath, currentPoint, wR, hR, stAng, swAng);
// <lnTo>
// <pt x="r" y="y2" />
// </lnTo>
currentPoint = LineToToString(stringPath, r, y2);
// <arcTo wR="x1" hR="x1" stAng="0" swAng="cd4" />
wR = x1;
hR = x1;
stAng = 0;
swAng = cd4;
currentPoint = ArcToToString(stringPath, currentPoint, wR, hR, stAng, swAng);
// <lnTo>
// <pt x="x1" y="b" />
// </lnTo>
currentPoint = LineToToString(stringPath, x1, b);
// <arcTo wR="x1" hR="x1" stAng="cd4" swAng="cd4" />
wR = x1;
hR = x1;
stAng = cd4;
swAng = cd4;
currentPoint = ArcToToString(stringPath, currentPoint, wR, hR, stAng, swAng);
// <close />
// </path>
stringPath.Append("z ");
shapePaths[0] = new ShapePath(stringPath.ToString(), PathFillModeValues.None, isStroke: false);
// <path fill="none">
// <moveTo>
// <pt x="x1" y="b" />
// </moveTo>
stringPath.Clear();
currentPoint = new EmuPoint(x1, b);
stringPath.Append($"M {EmuToPixelString(currentPoint.X)},{EmuToPixelString(currentPoint.Y)} ");
// <arcTo wR="x1" hR="x1" stAng="cd4" swAng="cd4" />
wR = x1;
hR = x1;
stAng = cd4;
swAng = cd4;
currentPoint = ArcToToString(stringPath, currentPoint, wR, hR, stAng, swAng);
// <lnTo>
// <pt x="l" y="x1" />
// </lnTo>
currentPoint = LineToToString(stringPath, l, x1);
// <arcTo wR="x1" hR="x1" stAng="cd2" swAng="cd4" />
wR = x1;
hR = x1;
stAng = cd2;
swAng = cd4;
currentPoint = ArcToToString(stringPath, currentPoint, wR, hR, stAng, swAng);
shapePaths[1] = new ShapePath(stringPath.ToString(), PathFillModeValues.None);
// 这是特别再切成两段 - 政道
// <moveTo>
// <pt x="x2" y="t" />
// </moveTo>
stringPath.Clear();
currentPoint = new EmuPoint(x2, t);
stringPath.Append($"M {EmuToPixelString(currentPoint.X)},{EmuToPixelString(currentPoint.Y)} ");
// <arcTo wR="x1" hR="x1" stAng="3cd4" swAng="cd4" />
wR = x1;
hR = x1;
stAng = 3 * cd4;
swAng = cd4;
currentPoint = ArcToToString(stringPath, currentPoint, wR, hR, stAng, swAng);
// <lnTo>
// <pt x="r" y="y2" />
// </lnTo>
currentPoint = LineToToString(stringPath, r, y2);
// <arcTo wR="x1" hR="x1" stAng="0" swAng="cd4" />
wR = x1;
hR = x1;
stAng = 0;
swAng = cd4;
currentPoint = ArcToToString(stringPath, currentPoint, wR, hR, stAng, swAng);
// </path>
//</pathLst>
shapePaths[2] = new ShapePath(stringPath.ToString(), PathFillModeValues.None);
//<rect l="l" t="t" r="ir" b="b" xmlns="http://schemas.openxmlformats.org/drawingml/2006/main" />
InitializeShapeTextRectangle(l, t, ir, b);
return shapePaths;
}
}
}
| 40.644578 | 179 | 0.498296 | [
"MIT"
] | dotnet-campus/DocumentFormat.OpenXml.Extensions | src/DocumentFormat.OpenXml.Flatten/DocumentFormat.OpenXml.Flatten/ElementConverters/Shape/ShapeGeometryConverters/BracketPairGeometry.cs | 6,833 | C# |
using Store.Domain.Enitities;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.ModelConfiguration;
namespace Store.Data.EF.Maps
{
public class UsuarioMap : EntityTypeConfiguration<Usuario>
{
public UsuarioMap()
{
//tabela
ToTable(nameof(Usuario));
//Chave primaria
HasKey(pk => pk.Id);
//Colunas
Property(c => c.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption
.Identity);
Property(c => c.Nome)
.HasColumnType("varchar")
.HasMaxLength(100)
.IsRequired();
Property(c => c.Email)
.HasColumnType("varchar")
.HasMaxLength(80)
.IsRequired()
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(new IndexAttribute("UQ_dbo_Usuario.Email") { IsUnique = true })
);
Property(c => c.Senha).
HasColumnType("varchar")
.HasMaxLength(100)
.IsRequired();
Property(c => c.DataCadastro);
//relacionamento
}
}
}
| 27.729167 | 103 | 0.527423 | [
"MIT"
] | guiagostini/Cursos-Tutoriais | Loja/Store.Data/EF/Maps/UsuarioMap.cs | 1,333 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel; //Component
using System.Data;
using System.Data.Common; //DbDataAdapter
namespace System.Data.Odbc
{
/////////////////////////////////////////////////////////////////////////
// Event Handlers
//
/////////////////////////////////////////////////////////////////////////
public delegate void OdbcRowUpdatingEventHandler(object sender, OdbcRowUpdatingEventArgs e);
public delegate void OdbcRowUpdatedEventHandler(object sender, OdbcRowUpdatedEventArgs e);
/////////////////////////////////////////////////////////////////////////
// OdbcRowUpdatingEventArgs
//
/////////////////////////////////////////////////////////////////////////
public sealed class OdbcRowUpdatingEventArgs : RowUpdatingEventArgs
{
public OdbcRowUpdatingEventArgs(DataRow row, IDbCommand command, StatementType statementType, DataTableMapping tableMapping)
: base(row, command, statementType, tableMapping)
{
}
new public OdbcCommand Command
{
get { return (base.Command as OdbcCommand); }
set
{
base.Command = value;
}
}
override protected IDbCommand BaseCommand
{
get { return base.BaseCommand; }
set { base.BaseCommand = (value as OdbcCommand); }
}
}
/////////////////////////////////////////////////////////////////////////
// OdbcRowUpdatedEventArgs
//
/////////////////////////////////////////////////////////////////////////
public sealed class OdbcRowUpdatedEventArgs : RowUpdatedEventArgs
{
public OdbcRowUpdatedEventArgs(DataRow row, IDbCommand command, StatementType statementType, DataTableMapping tableMapping)
: base(row, command, statementType, tableMapping)
{
}
new public OdbcCommand Command
{
get { return (OdbcCommand)base.Command; }
}
}
}
| 34.53125 | 132 | 0.51991 | [
"MIT"
] | Aevitas/corefx | src/System.Data.Odbc/src/System/Data/Odbc/OdbcRowUpdatingEvent.cs | 2,210 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.