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
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace Microsoft.EntityFrameworkCore.Metadata; /// <summary> /// Represents a navigation property that is part of a relationship /// that is forwarded through a third entity type. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples. /// </remarks> public class RuntimeSkipNavigation : RuntimePropertyBase, IRuntimeSkipNavigation { private readonly RuntimeForeignKey _foreignKey; private readonly bool _isOnDependent; private readonly bool _isCollection; // Warning: Never access these fields directly as access needs to be thread-safe private IClrCollectionAccessor? _collectionAccessor; private bool _collectionAccessorInitialized; private ICollectionLoader? _manyToManyLoader; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [EntityFrameworkInternal] public RuntimeSkipNavigation( string name, Type clrType, PropertyInfo? propertyInfo, FieldInfo? fieldInfo, RuntimeEntityType declaringEntityType, RuntimeEntityType targetEntityType, RuntimeForeignKey foreignKey, bool collection, bool onDependent, PropertyAccessMode propertyAccessMode, bool eagerLoaded) : base(name, propertyInfo, fieldInfo, propertyAccessMode) { ClrType = clrType; DeclaringEntityType = declaringEntityType; TargetEntityType = targetEntityType; _foreignKey = foreignKey; if (foreignKey.ReferencingSkipNavigations == null) { foreignKey.ReferencingSkipNavigations = new SortedSet<RuntimeSkipNavigation>(SkipNavigationComparer.Instance) { this }; } else { foreignKey.ReferencingSkipNavigations.Add(this); } _isCollection = collection; _isOnDependent = onDependent; if (eagerLoaded) { SetAnnotation(CoreAnnotationNames.EagerLoaded, true); } } /// <summary> /// Gets the type of value that this navigation holds. /// </summary> protected override Type ClrType { get; } /// <summary> /// Gets the type that this property belongs to. /// </summary> public override RuntimeEntityType DeclaringEntityType { get; } /// <summary> /// Gets the entity type that this navigation property will hold an instance(s) of. /// </summary> public virtual RuntimeEntityType TargetEntityType { get; } /// <summary> /// Gets or sets the inverse navigation. /// </summary> [DisallowNull] public virtual RuntimeSkipNavigation? Inverse { get; set; } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns>A string that represents the current object.</returns> public override string ToString() => ((IReadOnlySkipNavigation)this).ToDebugString(MetadataDebugStringOptions.SingleLineDefault); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual DebugView DebugView => new( () => ((IReadOnlySkipNavigation)this).ToDebugString(), () => ((IReadOnlySkipNavigation)this).ToDebugString(MetadataDebugStringOptions.LongDefault)); /// <inheritdoc /> IReadOnlyEntityType IReadOnlyNavigationBase.DeclaringEntityType { [DebuggerStepThrough] get => DeclaringEntityType; } /// <inheritdoc /> IReadOnlyEntityType IReadOnlyNavigationBase.TargetEntityType { [DebuggerStepThrough] get => TargetEntityType; } /// <inheritdoc /> IReadOnlyForeignKey IReadOnlySkipNavigation.ForeignKey { [DebuggerStepThrough] get => _foreignKey; } /// <inheritdoc /> IReadOnlySkipNavigation IReadOnlySkipNavigation.Inverse { [DebuggerStepThrough] get => Inverse!; } /// <inheritdoc /> bool IReadOnlySkipNavigation.IsOnDependent { [DebuggerStepThrough] get => _isOnDependent; } /// <inheritdoc /> bool IReadOnlyNavigationBase.IsCollection { [DebuggerStepThrough] get => _isCollection; } /// <inheritdoc /> IClrCollectionAccessor? INavigationBase.GetCollectionAccessor() => NonCapturingLazyInitializer.EnsureInitialized( ref _collectionAccessor, ref _collectionAccessorInitialized, this, static navigation => { navigation.EnsureReadOnly(); return new ClrCollectionAccessorFactory().Create(navigation); }); /// <inheritdoc /> ICollectionLoader IRuntimeSkipNavigation.GetManyToManyLoader() => NonCapturingLazyInitializer.EnsureInitialized( ref _manyToManyLoader, this, static navigation => { navigation.EnsureReadOnly(); return new ManyToManyLoaderFactory().Create(navigation); }); }
35.790698
140
0.671865
[ "MIT" ]
Applesauce314/efcore
src/EFCore/Metadata/RuntimeSkipNavigation.cs
6,156
C#
using System.Threading.Tasks; namespace Dfc.SharedConfig.Services { public interface ISharedConfigurationService { Task<T> GetConfigAsync<T>(string serviceName, string keyName, bool isDataEncrypted = false); Task SetConfigAsync<T>(string serviceName, string keyName, string data, bool isDataEncrypted = false); } }
31.363636
110
0.742029
[ "MIT" ]
SkillsFundingAgency/dfc-sharedconfig-pkg-netstandard
Dfc.SharedConfig/Services/ISharedConfigurationService.cs
347
C#
using System; using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Wallhaven.API.Models { public partial class WallhavenImage { [JsonProperty("data")] public WallhavenImageData Data { get; set; } } public partial class WallhavenImageData { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("url")] public Uri Url { get; set; } [JsonProperty("short_url")] public Uri ShortUrl { get; set; } [JsonProperty("uploader")] public WallhavenImageUploader Uploader { get; set; } [JsonProperty("views")] public int Views { get; set; } [JsonProperty("favorites")] public int Favorites { get; set; } [JsonProperty("source")] public string Source { get; set; } [JsonProperty("purity")] public WallhavenPurity Purity { get; set; } [JsonProperty("category")] public string Category { get; set; } [JsonProperty("dimension_x")] public int DimensionX { get; set; } [JsonProperty("dimension_y")] public int DimensionY { get; set; } [JsonProperty("resolution")] public string Resolution { get; set; } [JsonProperty("ratio")] public string Ratio { get; set; } [JsonProperty("file_size")] public int FileSize { get; set; } [JsonProperty("file_type")] public string FileType { get; set; } [JsonProperty("created_at")] public DateTimeOffset CreatedAt { get; set; } [JsonProperty("colors")] public string[] Colors { get; set; } [JsonProperty("path")] public Uri Path { get; set; } [JsonProperty("thumbs")] public WallhavenImageThumbs Thumbs { get; set; } [JsonProperty("tags")] public WallhavenImageTag[] Tags { get; set; } } public partial class WallhavenImageTag { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("alias")] public string Alias { get; set; } [JsonProperty("category_id")] public int CategoryId { get; set; } [JsonProperty("category")] public string Category { get; set; } [JsonProperty("purity")] public WallhavenPurity Purity { get; set; } [JsonProperty("created_at")] public DateTimeOffset CreatedAt { get; set; } } public partial class WallhavenImageThumbs { [JsonProperty("large")] public Uri Large { get; set; } [JsonProperty("original")] public Uri Original { get; set; } [JsonProperty("small")] public Uri Small { get; set; } } public partial class WallhavenImageUploader { [JsonProperty("username")] public string Username { get; set; } [JsonProperty("group")] public string Group { get; set; } [JsonProperty("avatar")] public Dictionary<string, Uri> Avatar { get; set; } } public partial class WallhavenImage { public static WallhavenImage FromJson(string json) => JsonConvert.DeserializeObject<WallhavenImage>(json, WallhavenPaginatedDataConverter.Settings); } }
26.291045
157
0.570536
[ "MIT" ]
Venipa/Wallhaven.API
Models/WallhavenImage.cs
3,525
C#
using System.IO; using System.Linq; namespace AdventOfCode.Solutions.Day1 { internal class SolutionPart2 : IntSolution { private int[] _depths; public SolutionPart2() { LoadFile(); } public int Solve() { int increases = 0; // Compute sliding average first for (int i = 0; i < _depths.Length - 2; ++i) { _depths[i] += _depths[i + 1] + _depths[i + 2]; } for (int i = 1; i < _depths.Length - 2; ++i) { increases += _depths[i - 1] < _depths[i] ? 1 : 0; } return increases; } private void LoadFile() { _depths = File.ReadLines("./Content/Day1/1.txt").Select(line => int.Parse(line)).ToArray(); } } }
22.475
104
0.440489
[ "MIT" ]
janovrom/AdventOfCode
Solutions/Day1/SolutionPart2.cs
901
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 IpSecurityProfileRequest. /// </summary> public partial class IpSecurityProfileRequest : BaseRequest, IIpSecurityProfileRequest { /// <summary> /// Constructs a new IpSecurityProfileRequest. /// </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 IpSecurityProfileRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified IpSecurityProfile using POST. /// </summary> /// <param name="ipSecurityProfileToCreate">The IpSecurityProfile to create.</param> /// <returns>The created IpSecurityProfile.</returns> public System.Threading.Tasks.Task<IpSecurityProfile> CreateAsync(IpSecurityProfile ipSecurityProfileToCreate) { return this.CreateAsync(ipSecurityProfileToCreate, CancellationToken.None); } /// <summary> /// Creates the specified IpSecurityProfile using POST. /// </summary> /// <param name="ipSecurityProfileToCreate">The IpSecurityProfile to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created IpSecurityProfile.</returns> public async System.Threading.Tasks.Task<IpSecurityProfile> CreateAsync(IpSecurityProfile ipSecurityProfileToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<IpSecurityProfile>(ipSecurityProfileToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified IpSecurityProfile. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified IpSecurityProfile. /// </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<IpSecurityProfile>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified IpSecurityProfile. /// </summary> /// <returns>The IpSecurityProfile.</returns> public System.Threading.Tasks.Task<IpSecurityProfile> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified IpSecurityProfile. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The IpSecurityProfile.</returns> public async System.Threading.Tasks.Task<IpSecurityProfile> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<IpSecurityProfile>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified IpSecurityProfile using PATCH. /// </summary> /// <param name="ipSecurityProfileToUpdate">The IpSecurityProfile to update.</param> /// <returns>The updated IpSecurityProfile.</returns> public System.Threading.Tasks.Task<IpSecurityProfile> UpdateAsync(IpSecurityProfile ipSecurityProfileToUpdate) { return this.UpdateAsync(ipSecurityProfileToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified IpSecurityProfile using PATCH. /// </summary> /// <param name="ipSecurityProfileToUpdate">The IpSecurityProfile 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 IpSecurityProfile.</returns> public async System.Threading.Tasks.Task<IpSecurityProfile> UpdateAsync(IpSecurityProfile ipSecurityProfileToUpdate, CancellationToken cancellationToken) { if (ipSecurityProfileToUpdate.AdditionalData != null) { if (ipSecurityProfileToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.ResponseHeaders) || ipSecurityProfileToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.StatusCode)) { throw new ClientException( new Error { Code = GeneratedErrorConstants.Codes.NotAllowed, Message = String.Format(GeneratedErrorConstants.Messages.ResponseObjectUsedForUpdate, ipSecurityProfileToUpdate.GetType().Name) }); } } if (ipSecurityProfileToUpdate.AdditionalData != null) { if (ipSecurityProfileToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.ResponseHeaders) || ipSecurityProfileToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.StatusCode)) { throw new ClientException( new Error { Code = GeneratedErrorConstants.Codes.NotAllowed, Message = String.Format(GeneratedErrorConstants.Messages.ResponseObjectUsedForUpdate, ipSecurityProfileToUpdate.GetType().Name) }); } } this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<IpSecurityProfile>(ipSecurityProfileToUpdate, 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 IIpSecurityProfileRequest 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 IIpSecurityProfileRequest Expand(Expression<Func<IpSecurityProfile, 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 IIpSecurityProfileRequest 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 IIpSecurityProfileRequest Select(Expression<Func<IpSecurityProfile, 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="ipSecurityProfileToInitialize">The <see cref="IpSecurityProfile"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(IpSecurityProfile ipSecurityProfileToInitialize) { } } }
44.063291
161
0.622714
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IpSecurityProfileRequest.cs
10,443
C#
using System; using System.Collections.Generic; using System.Runtime.InteropServices.ComTypes; using System.Text; using MetaPrograms.Expressions; namespace MetaPrograms.Members { public class ImportDirective { public IEnumerable<LocalVariable> GetLocalVariables() { var result = new List<LocalVariable>(); if (AsDefault != null) { result.Add(AsDefault); } if (AsNamespace != null) { result.Add(AsNamespace); } if (AsTuple != null) { result.AddRange(AsTuple.Variables); } return result; } public ModuleSpecifier What { get; set; } public ModuleSpecifier From { get; set; } public LocalVariable AsDefault { get; set; } public TupleExpression AsTuple { get; set; } public LocalVariable AsNamespace { get; set; } public class ModuleSpecifier { public ModuleMember Module { get; set; } public string ModulePath { get; set; } public string GetModulePath() { if (!string.IsNullOrEmpty(ModulePath)) { return ModulePath; } else if (Module != null) { return string.Join("/", GetModulePathParts(Module)); } throw new InvalidCodeModelException( $"Import directive module specifier has neither Module nor ModulePath."); } private static IEnumerable<string> GetModulePathParts(ModuleMember module) { var pathParts = new List<string>(); pathParts.Add("."); if (module.FolderPath != null) { pathParts.AddRange(module.FolderPath); } pathParts.Add(module.Name.ToString()); return pathParts; } } } }
27.376623
93
0.499051
[ "MIT" ]
felix-b/MetaPrograms
Source/MetaPrograms/Members/ImportDirective.cs
2,110
C#
using SpiceSharp.ParameterSets; namespace SpiceSharp.Components.CurrentControlledVoltageSources { /// <summary> /// Base parameters for a <see cref="CurrentControlledVoltageSource"/> /// </summary> /// <seealso cref="ParameterSet"/> public class Parameters : ParameterSet { /// <summary> /// Gets or sets the transresistance gain. /// </summary> /// <value> /// The transresistance gain. /// </value> [ParameterName("gain"), ParameterInfo("Transresistance (gain)")] public double Coefficient { get; set; } } }
28.761905
74
0.610927
[ "MIT" ]
Polyfly/SpiceSharp
SpiceSharp/Components/Voltagesources/CCVS/Parameters.cs
606
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace PyromancersJourney.Framework { internal struct VertexEverything : IVertexType { public Vector3 Position; public Color Color; public Vector3 Normal; public Vector2 Texture; VertexDeclaration IVertexType.VertexDeclaration => VertexEverything.VertexDeclaration; public static readonly VertexDeclaration VertexDeclaration = new( new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0), new VertexElement(sizeof(float) * 3, VertexElementFormat.Color, VertexElementUsage.Color, 0), new VertexElement(sizeof(float) * 3 + 4, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0), new VertexElement(sizeof(float) * 3 + 4 + sizeof(float) * 3, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0) ); public VertexEverything(Vector3 pos, Vector3 n, Vector2 tex) { this.Position = pos; this.Color = Color.White; this.Normal = n; this.Texture = tex; } } }
37.516129
142
0.675838
[ "MIT" ]
ChulkyBow/StardewValleyMods
PyromancersJourney/Framework/VertexEverything.cs
1,163
C#
using System.Collections; public class Engine : IEnumerable<GameState> { private int Width { get; } private int Height { get; } private GameState _state; public Engine(int width, int height, IEnumerable<Coordinate> initialState) { Width = width; Height = height; _state = GameState.Initialise(width, height, initialState); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator<GameState> GetEnumerator() { while (true) { yield return _state; _state = _state.Next(); } } }
20.787879
79
0.561224
[ "MIT" ]
spadger/game-of-life
Engine.cs
688
C#
namespace OpenAFSClientManager { partial class CifsControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CifsControl)); this.authenticationLevelComboBox = new System.Windows.Forms.ComboBox(); this.authenticationLevelLabel = new System.Windows.Forms.Label(); this.maximumVirtualCircuitsTextBox = new System.Windows.Forms.TextBox(); this.maximumVirtualCircuitsLabel = new System.Windows.Forms.Label(); this.multiplexedRequestsTextBox = new System.Windows.Forms.TextBox(); this.multiplexedRequestsLabel = new System.Windows.Forms.Label(); this.applyButton = new System.Windows.Forms.Button(); this.locateAdapterCheckBox = new System.Windows.Forms.CheckBox(); this.lanAdapterLabel = new System.Windows.Forms.Label(); this.adapterNumberComboBox = new System.Windows.Forms.ComboBox(); this.netbiosNameTextBox = new System.Windows.Forms.TextBox(); this.netbiosNameLabel = new System.Windows.Forms.Label(); this.SuspendLayout(); // // authenticationLevelComboBox // this.authenticationLevelComboBox.FormattingEnabled = true; this.authenticationLevelComboBox.Items.AddRange(new object[] { resources.GetString("authenticationLevelComboBox.Items"), resources.GetString("authenticationLevelComboBox.Items1"), resources.GetString("authenticationLevelComboBox.Items2")}); resources.ApplyResources(this.authenticationLevelComboBox, "authenticationLevelComboBox"); this.authenticationLevelComboBox.Name = "authenticationLevelComboBox"; // // authenticationLevelLabel // resources.ApplyResources(this.authenticationLevelLabel, "authenticationLevelLabel"); this.authenticationLevelLabel.Name = "authenticationLevelLabel"; // // maximumVirtualCircuitsTextBox // resources.ApplyResources(this.maximumVirtualCircuitsTextBox, "maximumVirtualCircuitsTextBox"); this.maximumVirtualCircuitsTextBox.Name = "maximumVirtualCircuitsTextBox"; // // maximumVirtualCircuitsLabel // resources.ApplyResources(this.maximumVirtualCircuitsLabel, "maximumVirtualCircuitsLabel"); this.maximumVirtualCircuitsLabel.Name = "maximumVirtualCircuitsLabel"; // // multiplexedRequestsTextBox // resources.ApplyResources(this.multiplexedRequestsTextBox, "multiplexedRequestsTextBox"); this.multiplexedRequestsTextBox.Name = "multiplexedRequestsTextBox"; // // multiplexedRequestsLabel // resources.ApplyResources(this.multiplexedRequestsLabel, "multiplexedRequestsLabel"); this.multiplexedRequestsLabel.Name = "multiplexedRequestsLabel"; // // applyButton // resources.ApplyResources(this.applyButton, "applyButton"); this.applyButton.Name = "applyButton"; this.applyButton.UseVisualStyleBackColor = true; this.applyButton.Click += new System.EventHandler(this.applyButton_Click); // // locateAdapterCheckBox // resources.ApplyResources(this.locateAdapterCheckBox, "locateAdapterCheckBox"); this.locateAdapterCheckBox.Name = "locateAdapterCheckBox"; this.locateAdapterCheckBox.UseVisualStyleBackColor = true; // // lanAdapterLabel // resources.ApplyResources(this.lanAdapterLabel, "lanAdapterLabel"); this.lanAdapterLabel.Name = "lanAdapterLabel"; // // adapterNumberComboBox // resources.ApplyResources(this.adapterNumberComboBox, "adapterNumberComboBox"); this.adapterNumberComboBox.FormattingEnabled = true; this.adapterNumberComboBox.Items.AddRange(new object[] { resources.GetString("adapterNumberComboBox.Items")}); this.adapterNumberComboBox.Name = "adapterNumberComboBox"; // // netbiosNameTextBox // resources.ApplyResources(this.netbiosNameTextBox, "netbiosNameTextBox"); this.netbiosNameTextBox.Name = "netbiosNameTextBox"; // // netbiosNameLabel // resources.ApplyResources(this.netbiosNameLabel, "netbiosNameLabel"); this.netbiosNameLabel.Name = "netbiosNameLabel"; // // CifsControl // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.authenticationLevelComboBox); this.Controls.Add(this.authenticationLevelLabel); this.Controls.Add(this.maximumVirtualCircuitsTextBox); this.Controls.Add(this.maximumVirtualCircuitsLabel); this.Controls.Add(this.multiplexedRequestsTextBox); this.Controls.Add(this.multiplexedRequestsLabel); this.Controls.Add(this.applyButton); this.Controls.Add(this.locateAdapterCheckBox); this.Controls.Add(this.lanAdapterLabel); this.Controls.Add(this.adapterNumberComboBox); this.Controls.Add(this.netbiosNameTextBox); this.Controls.Add(this.netbiosNameLabel); this.Name = "CifsControl"; this.Load += new System.EventHandler(this.CifsControl_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ComboBox authenticationLevelComboBox; private System.Windows.Forms.Label authenticationLevelLabel; private System.Windows.Forms.TextBox maximumVirtualCircuitsTextBox; private System.Windows.Forms.Label maximumVirtualCircuitsLabel; private System.Windows.Forms.TextBox multiplexedRequestsTextBox; private System.Windows.Forms.Label multiplexedRequestsLabel; private System.Windows.Forms.Button applyButton; private System.Windows.Forms.CheckBox locateAdapterCheckBox; private System.Windows.Forms.Label lanAdapterLabel; private System.Windows.Forms.ComboBox adapterNumberComboBox; private System.Windows.Forms.TextBox netbiosNameTextBox; private System.Windows.Forms.Label netbiosNameLabel; } }
49.165605
144
0.633372
[ "MIT" ]
asankah/openafsclientmmc
CifsControl.Designer.cs
7,721
C#
using Abp.MultiTenancy; using SimpleTask.Authorization.Users; namespace SimpleTask.MultiTenancy { public class Tenant : AbpTenant<User> { public Tenant() { } public Tenant(string tenancyName, string name) : base(tenancyName, name) { } } }
18.111111
54
0.564417
[ "MIT" ]
Thomasqhl/TaskSystem
SimpleTask.Core/MultiTenancy/Tenant.cs
328
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SFML.System; using SFML.Graphics; namespace WGP { /// <summary> /// A capsule shaped hitbox. /// </summary> public class CapsuleHitbox : SingleShapeHitbox { #region Private Fields private Vector2f _halfExtend; private int _numberOfVerticesPerCorner; private float _radius; #endregion Private Fields #region Public Constructors /// <summary> /// Constructor. /// </summary> public CapsuleHitbox() : base() { _halfExtend = new Vector2f(); _radius = 0; NumberOfVerticesPerCorner = 5; } /// <summary> /// Copy constructor. /// </summary> /// <param name="copy"></param> public CapsuleHitbox(CapsuleHitbox copy) : this() { _halfExtend = copy.HalfExtend; _radius = copy.Radius; NumberOfVerticesPerCorner = copy.NumberOfVerticesPerCorner; Position = copy.Position; Origin = copy.Origin; Scale = copy.Scale; Rotation = copy.Rotation; } #endregion Public Constructors #region Public Properties /// <summary> /// The half of the size of the rectangle (how much it will extend from the middle). /// </summary> public Vector2f HalfExtend { get => _halfExtend; set { _halfExtend = value; Update(); } } /// <summary> /// The number of vertices per corner. A higher value means more precise collisions but at a /// higher cost of performances. /// </summary> public int NumberOfVerticesPerCorner { get => _numberOfVerticesPerCorner; set { _numberOfVerticesPerCorner = value; Update(); } } /// <summary> /// The radius of the corners. /// </summary> public float Radius { get => _radius; set { _radius = value; Update(); } } #endregion Public Properties #region Public Methods public override object Clone() => new CapsuleHitbox(this); #endregion Public Methods #region Private Methods private void Update() { Vertices.Clear(); var result = new List<Vector2f>(); float usedRadius = Utilities.Min(Radius, HalfExtend.X, HalfExtend.Y); for (int i = 0; i < NumberOfVerticesPerCorner; i++) { var vec = new Vector2f(Utilities.Max(0, HalfExtend.X - usedRadius), -HalfExtend.Y + usedRadius); vec += new Vector2f(0, -usedRadius).Rotate(Angle.FromDegrees(Utilities.Interpolation(Utilities.Percent(i, 0, NumberOfVerticesPerCorner - 1), 0f, 90))); result.Add(vec); } for (int i = 0; i < NumberOfVerticesPerCorner; i++) { var vec = new Vector2f(Utilities.Max(0, HalfExtend.X - usedRadius), HalfExtend.Y - usedRadius); vec += new Vector2f(usedRadius, 0).Rotate(Angle.FromDegrees(Utilities.Interpolation(Utilities.Percent(i, 0, NumberOfVerticesPerCorner - 1), 0f, 90))); result.Add(vec); } for (int i = 0; i < NumberOfVerticesPerCorner; i++) { var vec = new Vector2f(Utilities.Min(0, -HalfExtend.X + usedRadius), HalfExtend.Y - usedRadius); vec += new Vector2f(0, usedRadius).Rotate(Angle.FromDegrees(Utilities.Interpolation(Utilities.Percent(i, 0, NumberOfVerticesPerCorner - 1), 0f, 90))); result.Add(vec); } for (int i = 0; i < NumberOfVerticesPerCorner; i++) { var vec = new Vector2f(Utilities.Min(0, -HalfExtend.X + usedRadius), -HalfExtend.Y + usedRadius); vec += new Vector2f(-usedRadius, 0).Rotate(Angle.FromDegrees(Utilities.Interpolation(Utilities.Percent(i, 0, NumberOfVerticesPerCorner - 1), 0f, 90))); result.Add(vec); } Vertices.Add(new Tuple<List<Vector2f>, CombineMode>(result, CombineMode.ADD)); } #endregion Private Methods } }
32.035461
167
0.546823
[ "MIT" ]
WildGoat07/WildGoatPackage.NET
CapsuleHitbox.cs
4,519
C#
// ContextError.cs // // Copyright 2010 Microsoft 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.ComponentModel; using System.Text; namespace Microsoft.Ajax.Utilities { public class ContextError { public int ErrorNumber { get; set; } // error information properties public string File { get; set; } public virtual int Severity { get; set; } public virtual string Subcategory { get; set; } [Localizable(false)] public virtual string ErrorCode { get; set; } public virtual int StartLine { get; set; } public virtual int StartColumn { get; set; } public virtual int EndLine { get; set; } public virtual int EndColumn { get; set; } public virtual string Message { get; set; } public virtual bool IsError { get; set; } public string HelpKeyword { get; set; } /// <summary> /// Convert the exception to a VisualStudio format error message /// file(startline[-endline]?,startcol[-endcol]?):[ subcategory] category [errorcode]: message /// </summary> /// <returns></returns> public override string ToString() { var sb = StringBuilderPool.Acquire(); try { if (!string.IsNullOrEmpty(File)) { sb.Append(File); } // if there is a startline, then there must be a location. // no start line, then no location if (StartLine > 0) { // we will always at least start with the start line sb.AppendFormat("({0}", StartLine); if (EndLine > StartLine) { if (StartColumn > 0 && EndColumn > 0) { // all four values were specified sb.AppendFormat(",{0},{1},{2}", StartColumn, EndLine, EndColumn); } else { // one or both of the columns wasn't specified, so ignore them both sb.AppendFormat("-{0}", EndLine); } } else if (StartColumn > 0) { sb.AppendFormat(",{0}", StartColumn); if (EndColumn > StartColumn) { sb.AppendFormat("-{0}", EndColumn); } } sb.Append(')'); } // seaprate the location from the error description sb.Append(':'); // if there is a subcategory, add it prefaced with a space if (!string.IsNullOrEmpty(Subcategory)) { sb.Append(' '); sb.Append(Subcategory); } // not localizable sb.Append(IsError ? " error " : " warning "); // if there is an error code if (!string.IsNullOrEmpty(ErrorCode)) { sb.Append(ErrorCode); } // separate description from the message sb.Append(": "); if (!string.IsNullOrEmpty(Message)) { sb.Append(Message); } return sb.ToString(); } finally { sb.Release(); } } internal static string GetSubcategory(int severity) { // guide: 0 == there will be a run-time error if this code executes // 1 == the programmer probably did not intend to do this // 2 == this can lead to problems in the future. // 3 == this can lead to performance problems // 4 == this is just not right switch (severity) { case 0: return CommonStrings.Severity0; case 1: return CommonStrings.Severity1; case 2: return CommonStrings.Severity2; case 3: return CommonStrings.Severity3; case 4: return CommonStrings.Severity4; default: return CommonStrings.SeverityUnknown.FormatInvariant(severity); } } } public class ContextErrorEventArgs : EventArgs { public ContextError Error { get; set; } public ContextErrorEventArgs() { } } }
31.215116
102
0.48184
[ "MIT" ]
4vz/jovice
Aphysoft.Share/External/AjaxMin/ContextError.cs
5,371
C#
/******************************************************************************* * Copyright 2012-2019 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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.MTurk; using Amazon.MTurk.Model; namespace Amazon.PowerShell.Cmdlets.MTR { /// <summary> /// The <code>NotifyWorkers</code> operation sends an email to one or more Workers that /// you specify with the Worker ID. You can specify up to 100 Worker IDs to send the same /// message with a single call to the NotifyWorkers operation. The NotifyWorkers operation /// will send a notification email to a Worker only if you have previously approved or /// rejected work from the Worker. /// </summary> [Cmdlet("Send", "MTRWorkerNotification", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("Amazon.MTurk.Model.NotifyWorkersFailureStatus")] [AWSCmdlet("Calls the Amazon MTurk Service NotifyWorkers API operation.", Operation = new[] {"NotifyWorkers"}, SelectReturnType = typeof(Amazon.MTurk.Model.NotifyWorkersResponse))] [AWSCmdletOutput("Amazon.MTurk.Model.NotifyWorkersFailureStatus or Amazon.MTurk.Model.NotifyWorkersResponse", "This cmdlet returns a collection of Amazon.MTurk.Model.NotifyWorkersFailureStatus objects.", "The service call response (type Amazon.MTurk.Model.NotifyWorkersResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class SendMTRWorkerNotificationCmdlet : AmazonMTurkClientCmdlet, IExecutor { #region Parameter MessageText /// <summary> /// <para> /// <para>The text of the email message to send. Can include up to 4,096 characters</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String MessageText { get; set; } #endregion #region Parameter Subject /// <summary> /// <para> /// <para>The subject line of the email message to send. Can include up to 200 characters.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String Subject { get; set; } #endregion #region Parameter WorkerId /// <summary> /// <para> /// <para>A list of Worker IDs you wish to notify. You can notify upto 100 Workers at a time.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyCollection] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] [Alias("WorkerIds")] public System.String[] WorkerId { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'NotifyWorkersFailureStatuses'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.MTurk.Model.NotifyWorkersResponse). /// Specifying the name of a property of type Amazon.MTurk.Model.NotifyWorkersResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "NotifyWorkersFailureStatuses"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the WorkerId parameter. /// The -PassThru parameter is deprecated, use -Select '^WorkerId' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^WorkerId' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.WorkerId), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Send-MTRWorkerNotification (NotifyWorkers)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.MTurk.Model.NotifyWorkersResponse, SendMTRWorkerNotificationCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.WorkerId; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.MessageText = this.MessageText; #if MODULAR if (this.MessageText == null && ParameterWasBound(nameof(this.MessageText))) { WriteWarning("You are passing $null as a value for parameter MessageText which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.Subject = this.Subject; #if MODULAR if (this.Subject == null && ParameterWasBound(nameof(this.Subject))) { WriteWarning("You are passing $null as a value for parameter Subject which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif if (this.WorkerId != null) { context.WorkerId = new List<System.String>(this.WorkerId); } #if MODULAR if (this.WorkerId == null && ParameterWasBound(nameof(this.WorkerId))) { WriteWarning("You are passing $null as a value for parameter WorkerId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.MTurk.Model.NotifyWorkersRequest(); if (cmdletContext.MessageText != null) { request.MessageText = cmdletContext.MessageText; } if (cmdletContext.Subject != null) { request.Subject = cmdletContext.Subject; } if (cmdletContext.WorkerId != null) { request.WorkerIds = cmdletContext.WorkerId; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.MTurk.Model.NotifyWorkersResponse CallAWSServiceOperation(IAmazonMTurk client, Amazon.MTurk.Model.NotifyWorkersRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon MTurk Service", "NotifyWorkers"); try { #if DESKTOP return client.NotifyWorkers(request); #elif CORECLR return client.NotifyWorkersAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String MessageText { get; set; } public System.String Subject { get; set; } public List<System.String> WorkerId { get; set; } public System.Func<Amazon.MTurk.Model.NotifyWorkersResponse, SendMTRWorkerNotificationCmdlet, object> Select { get; set; } = (response, cmdlet) => response.NotifyWorkersFailureStatuses; } } }
46.343972
282
0.616727
[ "Apache-2.0" ]
5u5hma/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/MTurk/Basic/Send-MTRWorkerNotification-Cmdlet.cs
13,069
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.Text; using Microsoft.ML.CommandLine; using Microsoft.ML.Internal.Utilities; using Microsoft.ML.Runtime; namespace Microsoft.ML.TestFramework { using Conditional = System.Diagnostics.ConditionalAttribute; /// <summary> /// This class is used to represent the command line encoding of a component plus its /// settings. Typically, these settings will be parsed at a later time. Parsing at /// the parent level merely gathers the settings into an instance of SubComponent. /// </summary> [Serializable] public class SubComponent : IEquatable<SubComponent> { private static readonly string[] _empty = new string[0]; private string _kind; private string[] _settings; /// <summary> /// The type/kind of sub-component. This string will never be null, but may be empty. /// </summary> public string Kind { get { return _kind; } set { _kind = value ?? ""; } } /// <summary> /// The settings strings for the sub-component. This array will never be null, but may be empty. /// </summary> public string[] Settings { get { return _settings; } set { _settings = value ?? _empty; } } public string SubComponentSettings { get { return CmdParser.CombineSettings(_settings); } set { _settings = string.IsNullOrEmpty(value) ? _empty : new string[] { value }; } } /// <summary> /// It's generally better to use the IsGood() extension method. It handles null testing /// and empty testing. /// </summary> public bool IsEmpty { get { AssertValid(); return _kind.Length == 0 && _settings.Length == 0; } } public SubComponent() { _kind = ""; _settings = _empty; AssertValid(); } public SubComponent(string kind) { _kind = kind ?? ""; _settings = _empty; AssertValid(); } /// <summary> /// This assumes ownership of the settings array. /// </summary> public SubComponent(string kind, params string[] settings) { _kind = kind ?? ""; if (settings == null || settings.Length == 1 && string.IsNullOrEmpty(settings[0])) settings = _empty; _settings = settings; AssertValid(); } public SubComponent(string kind, string settings) { _kind = kind ?? ""; if (string.IsNullOrEmpty(settings)) _settings = _empty; else _settings = new string[] { settings }; AssertValid(); } [Conditional("DEBUG")] private void AssertValid() { Contracts.AssertValue(_kind); Contracts.AssertValue(_settings); } public bool Equals(SubComponent other) { if (other == null) return false; if (_kind != other._kind) return false; if (_settings.Length != other._settings.Length) return false; for (int i = 0; i < _settings.Length; i++) { if (_settings[i] != other._settings[i]) return false; } return true; } public override string ToString() { if (IsEmpty) return "{}"; if (_settings.Length == 0) return _kind; string str = CmdParser.CombineSettings(_settings); StringBuilder sb = new StringBuilder(); CmdQuoter.QuoteValue(str, sb, true); return _kind + sb.ToString(); } public override bool Equals(object obj) { SubComponent other = obj as SubComponent; if (other == null) return false; return Equals(other); } public override int GetHashCode() { int hash = Kind.GetHashCode(); for (int i = 0; i < Settings.Length; i++) hash = CombineHash(hash, Settings[i].GetHashCode()); return hash; } private static uint CombineHash(uint u1, uint u2) { return ((u1 << 7) | (u1 >> 25)) ^ u2; } private static int CombineHash(int n1, int n2) { return (int)CombineHash((uint)n1, (uint)n2); } private static void ParseCore(string str, out string kind, out string args) { kind = args = null; if (string.IsNullOrWhiteSpace(str)) return; str = str.Trim(); int ich = str.IndexOf('{'); if (ich < 0) { kind = str; return; } if (ich == 0 || str[str.Length - 1] != '}') throw Contracts.Except("Invalid SubComponent string: mismatched braces, or empty component name."); kind = str.Substring(0, ich); args = CmdLexer.UnquoteValue(str.Substring(ich)); } internal static SubComponent Parse(string str) { string kind; string args; ParseCore(str, out kind, out args); Contracts.AssertValueOrNull(kind); Contracts.AssertValueOrNull(args); return new SubComponent(kind, args); } internal static SubComponent<TRes, TSig> Parse<TRes, TSig>(string str) where TRes : class { string kind; string args; ParseCore(str, out kind, out args); Contracts.AssertValueOrNull(kind); Contracts.AssertValueOrNull(args); return new SubComponent<TRes, TSig>(kind, args); } public static SubComponent Create(Type type) { Contracts.Check(type != null && typeof(SubComponent).IsAssignableFrom(type)); return (SubComponent)Activator.CreateInstance(type); } public static SubComponent Clone(SubComponent src, Type type = null) { if (src == null) return null; var dst = Create(type ?? src.GetType()); dst._kind = src._kind; if (Utils.Size(src._settings) == 0) dst._settings = _empty; else dst._settings = (string[])src._settings.Clone(); return dst; } } [Serializable] public class SubComponent<TRes, TSig> : SubComponent where TRes : class { public SubComponent() : base() { } public SubComponent(string kind) : base(kind) { } public SubComponent(string kind, params string[] settings) : base(kind, settings) { } public TRes CreateInstance(IHostEnvironment env, params object[] extra) { string options = CmdParser.CombineSettings(Settings); TRes result; if (ComponentCatalog.TryCreateInstance<TRes, TSig>(env, out result, Kind, options, extra)) return result; throw Contracts.Except("Unknown loadable class: {0}", Kind).MarkSensitive(MessageSensitivity.None); } } public static class SubComponentExtensions { public static bool IsGood(this SubComponent src) { return src != null && !src.IsEmpty; } } }
29.860902
115
0.526375
[ "MIT" ]
GitHubPang/machinelearning
test/Microsoft.ML.TestFramework/SubComponent.cs
7,945
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 LimeDownloader.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LimeDownloader.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to using System; ///using System.Collections.Generic; ///using System.Linq; ///using System.Text; ///using System.Threading.Tasks; ///using System.Net; ///using System.Reflection; ///using System.Threading; /// ///namespace LimeDownloader ///{ /// /// static class Stub /// { /// //vars /// public static List&lt;string&gt; ListURLS = new List&lt;string&gt; { &quot;$URL$&quot; }; /// /// public static void Main() /// { /// foreach (string url in ListURLS.ToList()) /// { /// DownloadFiles(url); /// [rest of string was truncated]&quot;;. /// </summary> internal static string Stub { get { return ResourceManager.GetString("Stub", resourceCulture); } } } }
40.505263
180
0.568347
[ "MIT" ]
ANONGHOST666/Lime-Downloader
LimeDownloader/Properties/Resources.Designer.cs
3,850
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.ProviderHub.Outputs { [OutputType] public sealed class ResourceTypeRegistrationPropertiesResponseExtensionOptions { public readonly Outputs.ResourceTypeExtensionOptionsResponseResourceCreationBegin? ResourceCreationBegin; [OutputConstructor] private ResourceTypeRegistrationPropertiesResponseExtensionOptions(Outputs.ResourceTypeExtensionOptionsResponseResourceCreationBegin? resourceCreationBegin) { ResourceCreationBegin = resourceCreationBegin; } } }
34.08
164
0.776995
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/ProviderHub/Outputs/ResourceTypeRegistrationPropertiesResponseExtensionOptions.cs
852
C#
// Decompiled with JetBrains decompiler // Type: Functal.FnFunction_IsLessThanOrEqual_UInt64 // Assembly: Functal, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: 47DC2DAE-D56F-4FC5-A0C3-CC69F2DF9A1F // Assembly location: \\WSE\Folder Redirection\JP\Downloads\Functal-1_0_0\Functal.dll namespace Functal { internal class FnFunction_IsLessThanOrEqual_UInt64 : FnFunction<bool> { [FnArg] protected FnObject<ulong> LeftVal; [FnArg] protected FnObject<ulong> RightVal; public override bool GetValue() { return this.LeftVal.GetValue() <= this.RightVal.GetValue(); } } }
28.318182
85
0.738363
[ "MIT" ]
jpdillingham/Functal
src/FnFunction_IsLessThanOrEqual_UInt64.cs
625
C#
using Newtonsoft.Json.Linq; using PeterO.Cbor; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO.Pipes; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Timers; using XOPE_UI.Definitions; using XOPE_UI.Native; using XOPE_UI.Spy.ServerType; namespace XOPE_UI.Spy { //TODO: this is kinda weird so maybe just remove it and put it back into the mainWindow class; //though, add some sort of translation class for incomming data public class NamedPipeServer : IServer { public event EventHandler<Packet> OnNewPacket; public event EventHandler<Connection> OnNewConnection; public event EventHandler<Connection> OnCloseConnection; public SpyData Data { get; private set; } ConcurrentQueue<byte[]> outBuffer; CancellationTokenSource cancellationTokenSource; Task serverThread; // Change this to something easier to follow Dictionary<Guid, IMessageWithResponse> jobs; // This contains Messages that are expecting a response public NamedPipeServer() { Data = new SpyData(); outBuffer = new ConcurrentQueue<byte[]>(); jobs = new Dictionary<Guid, IMessageWithResponse>(); } public void Send(IMessage message) { outBuffer.Enqueue(Encoding.ASCII.GetBytes(message.ToJson().ToString())); //TODO: Convert to cbor } public void Send(IMessageWithResponse message) { outBuffer.Enqueue(Encoding.ASCII.GetBytes(message.ToJson().ToString())); //TODO: Convert to cbor jobs.Add(message.JobId, message); } // TODO: refactor most of this function public void RunAsync() { if (serverThread != null) { Console.WriteLine("Cannot start new server thread, as one already exists"); return; } cancellationTokenSource = new CancellationTokenSource(); serverThread = Task.Factory.StartNew(() => { using (NamedPipeServerStream serverStream = new NamedPipeServerStream("xopeui")) { serverStream.WaitForConnection(); Console.WriteLine("Server connected to Server"); NamedPipeClientStream clientStream = null; try { byte[] buffer = new byte[65536]; while (serverStream.IsConnected && !cancellationTokenSource.IsCancellationRequested) { int bytesAvailable; Win32API.PeekNamedPipe((IntPtr)serverStream.SafePipeHandle.DangerousGetHandle(), out _, 0, out _, out bytesAvailable, out _); if (bytesAvailable > 0) { int len = serverStream.Read(buffer, 0, 65536); if (len > 0) { CBORObject cbor = CBORObject.DecodeFromBytes((new ArraySegment<byte>(buffer, 0, len)).ToArray()); JObject json = JObject.Parse(cbor.ToString()); //Console.WriteLine($"Incoming message: {(ServerMessageType)json.Value<Int32>("messageType")}"); ServerMessageType messageType = (ServerMessageType)json.Value<Int32>("messageType"); if (messageType == ServerMessageType.CONNECTED_SUCCESS) { Console.WriteLine($"Connection success: {json}"); string spyPipeServerName = json.Value<string>("spyPipeServerName"); clientStream = new NamedPipeClientStream(spyPipeServerName); clientStream.Connect(2000); if (!clientStream.IsConnected) { Console.WriteLine("Unable to connect to Spy's Server. Aborting..."); break; } } else if (messageType == ServerMessageType.HOOKED_FUNCTION_CALL) { HookedFuncType hookedFuncType = (HookedFuncType)json.Value<Int32>("functionName"); //Console.WriteLine($"Message hookedType: {hookedFuncType}"); if (hookedFuncType == HookedFuncType.CONNECT || hookedFuncType == HookedFuncType.WSACONNECT) { Connection connection = new Connection( json.Value<Int32>("socket"), json.Value<Int32>("protocol"), json.Value<Int32>("addrFamily"), new IPAddress(json.Value<Int32>("addr")), json.Value<Int32>("port"), Connection.Status.ESTABLISHED ); int connectRet = json.Value<int>("ret"); int connectLastError = json.Value<int>("lastError"); if (connectRet == 0) { Data.Connections.TryAdd(json.Value<Int32>("socket"), connection); OnNewConnection?.Invoke(this, connection); Console.WriteLine("new connection"); } else if (connectRet == -1 && connectLastError == 10035) // ret == SOCKET_ERROR and error == WSAEWOULDBLOCK { connection.SocketStatus = Connection.Status.CONNECTING; Data.Connections.TryAdd(json.Value<Int32>("socket"), connection); System.Timers.Timer timer = new System.Timers.Timer(); int counter = 0; timer.Elapsed += (object sender, ElapsedEventArgs e) => { EventHandler<JObject> callback = (object o, JObject resp) => { Console.WriteLine(resp); if (++counter >= 5) { Console.WriteLine($"Socket never became writable. Socket: {connection.SocketId}"); Data.Connections.TryRemove(connection.SocketId, out _); } else if (resp.Value<bool>("writable") == false) { timer.Start(); } }; Send(new IsSocketWritable(callback) { SocketId = connection.SocketId }); }; timer.Interval = 1000; timer.AutoReset = false; timer.Start(); } else { Console.WriteLine($"Socket connected failed. Socket: {connection.SocketId} | " + $"Connect Ret: {connectRet} | " + $"WSALastError: {connectLastError}"); } } else if (hookedFuncType == HookedFuncType.CLOSE) { int socketId = json.Value<Int32>("socket"); Connection matchingConnection = Data.Connections[socketId]; //Data.Connections.FirstOrDefault((Connection c) => c.SocketId == socketId); if (matchingConnection != null && matchingConnection.SocketStatus != Connection.Status.CLOSED) { matchingConnection.SocketStatus = Connection.Status.CLOSED; matchingConnection.LastStatusChangeTime = DateTime.Now; System.Timers.Timer t = new System.Timers.Timer(); t.Elapsed += (object sender, ElapsedEventArgs e) => { Data.Connections.TryRemove(matchingConnection.SocketId, out Connection v); }; t.Interval = 7000; t.AutoReset = false; t.Start(); OnCloseConnection?.Invoke(this, matchingConnection); } } else { int socket = json.Value<int>("socket"); byte[] data = Convert.FromBase64String(json.Value<String>("packetDataB64")); Packet packet = new Packet { Id = Guid.NewGuid(), Type = hookedFuncType, Data = data, Length = data.Length, Socket = socket, }; OnNewPacket?.Invoke(this, packet); if (!Data.Connections.ContainsKey(socket)) { Console.WriteLine($"Missed Connect/WSAConnect for socket {socket}. Reqesting info..."); Connection connection = new Connection( socket, json.Value<Int32>("protocol"), json.Value<Int32>("addrFamily"), new IPAddress(json.Value<Int32>("addr")), json.Value<Int32>("port"), Connection.Status.REQUESTING_INFO ); Data.Connections.TryAdd(connection.SocketId, connection); SocketInfo socketInfo = new SocketInfo() { SocketId = socket }; socketInfo.OnResponse += (object o, JObject resp) => { Data.Connections.TryAdd(socket, connection); OnNewConnection?.Invoke(this, connection); // Console.WriteLine($"Added previously opened socket {socket}"); }; Send(socketInfo); } } } else if (messageType == ServerMessageType.JOB_RESPONSE) { Guid guid = Guid.Parse(json.Value<String>("jobId")); jobs[guid].NotifyResponse(json); jobs.Remove(guid); } else if (messageType == ServerMessageType.ERROR_MESSAGE) { Console.WriteLine($"[Spy-Error] {json.Value<String>("errorMessage")}"); } else if (messageType == ServerMessageType.INVALID_MESSAGE) { Console.WriteLine($"[Server-Error] Received a INVALID_MESSAGE. Check if the messageType was sent by Spy."); } } } FlushOutBuffer(clientStream); Thread.Sleep(20); } Console.WriteLine("Closing server..."); if (serverStream.IsConnected) { Send(new ShutdownSpy()); FlushOutBuffer(clientStream); } } catch (Exception ex) { Console.WriteLine($"Server error. Aborting server! Message: {ex.Message}"); Debug.WriteLine($"Server error. Message: {ex.Message}"); Debug.WriteLine($"Stacktrack:\n{ex.StackTrace}"); } finally { Console.WriteLine("Server closed!"); } if (clientStream.IsConnected) clientStream.Close(); } }, cancellationTokenSource.Token, TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning, TaskScheduler.Default); } public void ShutdownServerAndWait() { if (serverThread == null) return; cancellationTokenSource.Cancel(); serverThread.Wait(5000); serverThread = null; } private void FlushOutBuffer(NamedPipeClientStream clientStream) { if (clientStream == null) { Console.WriteLine("Client Stream is null. Cannot send message(s) to Spy."); return; } while (outBuffer.TryDequeue(out byte[] data)) { clientStream.Write(data, 0, data.Length); clientStream.WriteByte(0); } } } }
53.503268
180
0.381871
[ "MIT" ]
MotionFlex0/XOPE-.NET
src/XOPE_UI.Spy/NamedPipeServer.cs
16,374
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using NuGet.Common; using NuGet.Packaging.Core; namespace NuGet.Packaging.Signing { public static class RepositorySignatureInfoUtility { /// <summary> /// Gets SignedPackageVerifierSettings from a given RepositorySignatureInfo. /// </summary> /// <param name="repoSignatureInfo">RepositorySignatureInfo to be used.</param> /// <param name="fallbackSettings">SignedPackageVerifierSettings to be used if RepositorySignatureInfo is unavailable.</param> /// <returns>SignedPackageVerifierSettings based on the RepositorySignatureInfo and SignedPackageVerifierSettings.</returns> public static SignedPackageVerifierSettings GetSignedPackageVerifierSettings( RepositorySignatureInfo repoSignatureInfo, SignedPackageVerifierSettings fallbackSettings) { if (fallbackSettings == null) { throw new ArgumentNullException(nameof(fallbackSettings)); } if (repoSignatureInfo == null) { return fallbackSettings; } else { var repositoryAllowList = GetRepositoryAllowList(repoSignatureInfo.RepositoryCertificateInfos); // Allow unsigned only if the common settings allow it and repository does not have all packages signed var allowUnsigned = fallbackSettings.AllowUnsigned && !repoSignatureInfo.AllRepositorySigned; // Allow an empty repository certificate list only if the repository does not have all packages signed var allowNoRepositoryCertificateList = !repoSignatureInfo.AllRepositorySigned; // Allow untrusted only if the common settings allow it and repository does not have all packages signed var allowUntrusted = fallbackSettings.AllowUntrusted && !repoSignatureInfo.AllRepositorySigned; return new SignedPackageVerifierSettings( allowUnsigned, fallbackSettings.AllowIllegal, allowUntrusted, fallbackSettings.AllowIgnoreTimestamp, fallbackSettings.AllowMultipleTimestamps, fallbackSettings.AllowNoTimestamp, fallbackSettings.AllowUnknownRevocation, fallbackSettings.ReportUnknownRevocation, allowNoRepositoryCertificateList, fallbackSettings.AllowNoClientCertificateList, fallbackSettings.VerificationTarget, fallbackSettings.SignaturePlacement, fallbackSettings.RepositoryCountersignatureVerificationBehavior, fallbackSettings.RevocationMode, repositoryAllowList?.AsReadOnly(), fallbackSettings.ClientCertificateList); } } private static List<CertificateHashAllowListEntry> GetRepositoryAllowList(IEnumerable<IRepositoryCertificateInfo> repositoryCertificateInfos) { List<CertificateHashAllowListEntry> repositoryAllowList = null; if (repositoryCertificateInfos != null) { repositoryAllowList = new List<CertificateHashAllowListEntry>(); foreach (var certInfo in repositoryCertificateInfos) { var verificationTarget = VerificationTarget.Repository; var signaturePlacement = SignaturePlacement.PrimarySignature | SignaturePlacement.Countersignature; foreach (var hashAlgorithm in SigningSpecifications.V1.AllowedHashAlgorithms) { AddCertificateFingerprintIntoAllowList(verificationTarget, signaturePlacement, hashAlgorithm, certInfo, repositoryAllowList); } } } return repositoryAllowList; } private static void AddCertificateFingerprintIntoAllowList( VerificationTarget target, SignaturePlacement placement, HashAlgorithmName algorithm, IRepositoryCertificateInfo certInfo, List<CertificateHashAllowListEntry> allowList) { var fingerprint = certInfo.Fingerprints[algorithm.ConvertToOidString()]; if (!string.IsNullOrEmpty(fingerprint)) { allowList.Add(new CertificateHashAllowListEntry(target, placement, fingerprint, algorithm)); } } } }
45.971154
149
0.652374
[ "Apache-2.0" ]
CosminRadu/NuGet.Client
src/NuGet.Core/NuGet.Packaging/Signing/Utility/RepositorySignatureInfoUtility.cs
4,781
C#
namespace InControl.NativeProfile { using System; // @cond nodoc public class PowerAMiniProExControllerMacProfile : Xbox360DriverMacProfile { public PowerAMiniProExControllerMacProfile() { Name = "PowerA Mini Pro Ex Controller"; Meta = "PowerA Mini Pro Ex Controller on Mac"; Matchers = new[] { new NativeInputDeviceMatcher { VendorID = 0x15e4, ProductID = 0x3f00, }, new NativeInputDeviceMatcher { VendorID = 0x24c6, ProductID = 0x531a, }, new NativeInputDeviceMatcher { VendorID = 0x24c6, ProductID = 0x5300, }, }; } } // @endcond }
18.176471
75
0.66343
[ "MIT" ]
BattlerockStudios/GGJ2019
Assets/InControl/Source/Native/DeviceProfiles/Generated/PowerAMiniProExControllerMacProfile.cs
618
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using CoreWCF.IdentityModel.Tokens; namespace CoreWCF.Security.Tokens { public delegate void IssuedSecurityTokenHandler(SecurityToken issuedToken, EndpointAddress tokenRequestor); public delegate void RenewedSecurityTokenHandler(SecurityToken newSecurityToken, SecurityToken oldSecurityToken); public interface IIssuanceSecurityTokenAuthenticator { IssuedSecurityTokenHandler IssuedSecurityTokenHandler { get; set; } RenewedSecurityTokenHandler RenewedSecurityTokenHandler { get; set; } } }
39.235294
117
0.8006
[ "MIT" ]
AlexanderSemenyak/CoreWCF
src/CoreWCF.Primitives/src/CoreWCF/Security/Tokens/IIssuanceSecurityTokenAuthenticator.cs
667
C#
using Microsoft.AspNetCore.SignalR; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HospitalMachine.entry { public class BaseResult { public int result { get; set; } public string message { get; set; } public Object data { get; set; } } public class ReplyResult { } public class LoginResult { public int result { get; set; } public string message { get; set; } public Object data { get; set; } } }
19.5
43
0.624542
[ "Apache-2.0" ]
HZRelaper2020/HospitalMachine
entry/ReplyResult.cs
548
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("ClrExtract")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("ClrExtract")] [assembly: System.Reflection.AssemblyTitleAttribute("ClrExtract")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
40.833333
80
0.646939
[ "MIT" ]
SamB1990/MSSQL_CLR_Extractor
src/obj/Debug/netcoreapp3.0/ClrExtract.AssemblyInfo.cs
980
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; namespace Azure.IoT.TimeSeriesInsights { internal partial class TimeSeriesHierarchiesRestClient { private string environmentFqdn; private string apiVersion; private ClientDiagnostics _clientDiagnostics; private HttpPipeline _pipeline; /// <summary> Initializes a new instance of TimeSeriesHierarchiesRestClient. </summary> /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="environmentFqdn"> Per environment FQDN, for example 10000000-0000-0000-0000-100000000109.env.timeseries.azure.com. You can obtain this domain name from the response of the Get Environments API, Azure portal, or Azure Resource Manager. </param> /// <param name="apiVersion"> Api Version. </param> /// <exception cref="ArgumentNullException"> <paramref name="environmentFqdn"/> or <paramref name="apiVersion"/> is null. </exception> public TimeSeriesHierarchiesRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string environmentFqdn, string apiVersion = "2020-07-31") { if (environmentFqdn == null) { throw new ArgumentNullException(nameof(environmentFqdn)); } if (apiVersion == null) { throw new ArgumentNullException(nameof(apiVersion)); } this.environmentFqdn = environmentFqdn; this.apiVersion = apiVersion; _clientDiagnostics = clientDiagnostics; _pipeline = pipeline; } internal HttpMessage CreateListRequest(string continuationToken, string clientSessionId) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.AppendRaw("https://", false); uri.AppendRaw(environmentFqdn, false); uri.AppendPath("/timeseries/hierarchies", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; if (continuationToken != null) { request.Headers.Add("x-ms-continuation", continuationToken); } if (clientSessionId != null) { request.Headers.Add("x-ms-client-session-id", clientSessionId); } request.Headers.Add("Accept", "application/json"); return message; } /// <summary> Returns time series hierarchies definitions in pages. </summary> /// <param name="continuationToken"> Continuation token from previous page of results to retrieve the next page of the results in calls that support pagination. To get the first page results, specify null continuation token as parameter value. Returned continuation token is null if all results have been returned, and there is no next page of results. </param> /// <param name="clientSessionId"> Optional client session ID. Service records this value. Allows the service to trace a group of related operations across services, and allows the customer to contact support regarding a particular group of requests. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public async Task<Response<GetHierarchiesPage>> ListAsync(string continuationToken = null, string clientSessionId = null, CancellationToken cancellationToken = default) { using var message = CreateListRequest(continuationToken, clientSessionId); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { GetHierarchiesPage value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = GetHierarchiesPage.DeserializeGetHierarchiesPage(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Returns time series hierarchies definitions in pages. </summary> /// <param name="continuationToken"> Continuation token from previous page of results to retrieve the next page of the results in calls that support pagination. To get the first page results, specify null continuation token as parameter value. Returned continuation token is null if all results have been returned, and there is no next page of results. </param> /// <param name="clientSessionId"> Optional client session ID. Service records this value. Allows the service to trace a group of related operations across services, and allows the customer to contact support regarding a particular group of requests. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public Response<GetHierarchiesPage> List(string continuationToken = null, string clientSessionId = null, CancellationToken cancellationToken = default) { using var message = CreateListRequest(continuationToken, clientSessionId); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { GetHierarchiesPage value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = GetHierarchiesPage.DeserializeGetHierarchiesPage(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateExecuteBatchRequest(HierarchiesBatchRequest parameters, string clientSessionId) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.AppendRaw("https://", false); uri.AppendRaw(environmentFqdn, false); uri.AppendPath("/timeseries/hierarchies/$batch", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; if (clientSessionId != null) { request.Headers.Add("x-ms-client-session-id", clientSessionId); } request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; return message; } /// <summary> Executes a batch get, create, update, delete operation on multiple time series hierarchy definitions. </summary> /// <param name="parameters"> Time series hierarchies batch request body. </param> /// <param name="clientSessionId"> Optional client session ID. Service records this value. Allows the service to trace a group of related operations across services, and allows the customer to contact support regarding a particular group of requests. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="parameters"/> is null. </exception> public async Task<Response<HierarchiesBatchResponse>> ExecuteBatchAsync(HierarchiesBatchRequest parameters, string clientSessionId = null, CancellationToken cancellationToken = default) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateExecuteBatchRequest(parameters, clientSessionId); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { HierarchiesBatchResponse value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = HierarchiesBatchResponse.DeserializeHierarchiesBatchResponse(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Executes a batch get, create, update, delete operation on multiple time series hierarchy definitions. </summary> /// <param name="parameters"> Time series hierarchies batch request body. </param> /// <param name="clientSessionId"> Optional client session ID. Service records this value. Allows the service to trace a group of related operations across services, and allows the customer to contact support regarding a particular group of requests. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="parameters"/> is null. </exception> public Response<HierarchiesBatchResponse> ExecuteBatch(HierarchiesBatchRequest parameters, string clientSessionId = null, CancellationToken cancellationToken = default) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateExecuteBatchRequest(parameters, clientSessionId); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { HierarchiesBatchResponse value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = HierarchiesBatchResponse.DeserializeHierarchiesBatchResponse(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } } }
58.041026
369
0.65091
[ "MIT" ]
AME-Redmond/azure-sdk-for-net
sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/src/Generated/TimeSeriesHierarchiesRestClient.cs
11,318
C#
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.Content; using IRTaktiks.Input; using IRTaktiks.Input.EventArgs; using IRTaktiks.Components.Playable; using IRTaktiks.Components.Logic; using IRTaktiks.Components.Manager; using IRTaktiks.Components.Config; namespace IRTaktiks.Components.Screen { /// <summary> /// Config screen of the game. /// </summary> public class ConfigScreen : IScreen { #region Properties /// <summary> /// The configuration manager of the player one. /// </summary> private ConfigurationManager PlayerOneConfigurationManagerField; /// <summary> /// The configuration manager of the player one. /// </summary> public ConfigurationManager PlayerOneConfigurationManager { get { return PlayerOneConfigurationManagerField; } set { PlayerOneConfigurationManagerField = value; } } /// <summary> /// The configuration manager of the player two. /// </summary> private ConfigurationManager PlayerTwoConfigurationManagerField; /// <summary> /// The configuration manager of the player two. /// </summary> public ConfigurationManager PlayerTwoConfigurationManager { get { return PlayerTwoConfigurationManagerField; } set { PlayerTwoConfigurationManagerField = value; } } /// <summary> /// Indicates that the player one done its configuration. /// </summary> private bool PlayerOneConfigurated; /// <summary> /// Indicates that the player two done its configuration. /// </summary> private bool PlayerTwoConfigurated; #endregion #region Constructor /// <summary> /// Constructor of class. /// </summary> /// <param name="game">The instance of game that is running.</param> /// <param name="priority">Drawing priority of screen. Higher indicates that the screen will be at the top of the others.</param> public ConfigScreen(Game game, int priority) : base(game, priority) { this.PlayerOneConfigurationManagerField = new ConfigurationManager(game, PlayerIndex.One); this.PlayerTwoConfigurationManagerField = new ConfigurationManager(game, PlayerIndex.Two); this.PlayerOneConfigurated = false; this.PlayerTwoConfigurated = false; this.PlayerOneConfigurationManager.Configurated += new ConfigurationManager.ConfiguratedEventHandler(PlayerOne_Configurated); this.PlayerTwoConfigurationManager.Configurated += new ConfigurationManager.ConfiguratedEventHandler(PlayerTwo_Configurated); } #endregion #region Component Methods /// <summary> /// Allows the game component to perform any initialization it needs to before starting /// to run. This is where it can query for any required services and load content. /// </summary> public override void Initialize() { // Configuration managers this.Components.Add(this.PlayerOneConfigurationManager); this.Components.Add(this.PlayerTwoConfigurationManager); // Player one configuration items. this.Components.Add(this.PlayerOneConfigurationManager.Keyboard); this.Components.Add(this.PlayerOneConfigurationManager.PlayerConfig); for (int index = 0; index < this.PlayerOneConfigurationManager.UnitsConfig.Count; index++) { this.Components.Add(this.PlayerOneConfigurationManager.UnitsConfig[index]); } // Player two configuration items. this.Components.Add(this.PlayerTwoConfigurationManager.Keyboard); this.Components.Add(this.PlayerTwoConfigurationManager.PlayerConfig); for (int index = 0; index < this.PlayerTwoConfigurationManager.UnitsConfig.Count; index++) { this.Components.Add(this.PlayerTwoConfigurationManager.UnitsConfig[index]); } // Shows the map. IRTGame game = this.Game as IRTGame; game.MapManager.Visible = true; base.Initialize(); } /// <summary> /// Allows the game component to update itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Update(GameTime gameTime) { if (this.PlayerOneConfigurated && this.PlayerTwoConfigurated) { this.ConfigGame(); (this.Game as IRTGame).ChangeScreen(IRTGame.GameScreens.GameScreen); } base.Update(gameTime); } /// <summary> /// Called when the DrawableGameComponent needs to be drawn. Override this method /// with component-specific drawing code. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Draw(GameTime gameTime) { base.Draw(gameTime); } #endregion #region Methods /// <summary> /// Configure the game, creating all players and its units. /// </summary> private void ConfigGame() { IRTGame game = this.Game as IRTGame; game.PlayerOne = this.ConfigPlayer(this.PlayerOneConfigurationManager); game.PlayerTwo = this.ConfigPlayer(this.PlayerTwoConfigurationManager); } /// <summary> /// Configure one player, based on the given ConfigurationManager informations. /// </summary> /// <param name="configurationManager">The ConfigurationManager used to configure the player.</param> /// <returns>One player with its units configured.</returns> private Player ConfigPlayer(ConfigurationManager configurationManager) { Player player = new Player(this.Game, configurationManager.PlayerConfig.DisplayText.ToString(), configurationManager.PlayerIndex); for (int index = 0; index < configurationManager.UnitsConfig.Count; index++) { Attributes unitAttribute = new Attributes( IRTSettings.Default.BaseLevel, Character.Instance[configurationManager.UnitsConfig[index].CharacterIndex].Job, Element.Holy, configurationManager.UnitsConfig[index].Strength, configurationManager.UnitsConfig[index].Agility, configurationManager.UnitsConfig[index].Vitality, configurationManager.UnitsConfig[index].Inteligence, configurationManager.UnitsConfig[index].Dexterity ); string unitName = configurationManager.UnitsConfig[index].DisplayText.ToString(); Texture2D unitTexture = Character.Instance[configurationManager.UnitsConfig[index].CharacterIndex].Texture; Vector2 unitPosition = default(Vector2); Orientation unitOrientation = default(Orientation); switch (configurationManager.PlayerIndex) { case PlayerIndex.One: unitPosition = new Vector2((TextureManager.Instance.Sprites.Menu.Background.Width + 50), TextureManager.Instance.Sprites.Menu.Background.Width + (index * 60)); unitOrientation = Orientation.Right; break; case PlayerIndex.Two: unitPosition = new Vector2(IRTSettings.Default.Width - (TextureManager.Instance.Sprites.Menu.Background.Width + 50), TextureManager.Instance.Sprites.Menu.Background.Width + (index * 60)); unitOrientation = Orientation.Left; break; } Unit unit = new Unit(this.Game, player, unitPosition, unitAttribute, unitOrientation, unitTexture, unitName); player.Units.Add(unit); } return player; } #endregion #region Event Handling /// <summary> /// Executes when the player one done its configuration. /// </summary> private void PlayerOne_Configurated() { this.PlayerOneConfigurated = true; this.PlayerOneConfigurationManager.Unregister(); this.PlayerOneConfigurationManager.Keyboard.Unregister(); this.PlayerOneConfigurationManager.PlayerConfig.Unregister(); for (int index = 0; index < this.PlayerOneConfigurationManager.UnitsConfig.Count; index++) { this.PlayerOneConfigurationManager.UnitsConfig[index].Unregister(); } } /// <summary> /// Executes when the player two done its configuration. /// </summary> private void PlayerTwo_Configurated() { this.PlayerTwoConfigurated = true; this.PlayerTwoConfigurationManager.Unregister(); this.PlayerTwoConfigurationManager.Keyboard.Unregister(); this.PlayerTwoConfigurationManager.PlayerConfig.Unregister(); for (int index = 0; index < this.PlayerTwoConfigurationManager.UnitsConfig.Count; index++) { this.PlayerTwoConfigurationManager.UnitsConfig[index].Unregister(); } } #endregion } }
39.810277
212
0.614774
[ "MIT" ]
schalleneider/irtaktiks
src/IRTaktiks/IRTaktiks/Components/Screen/ConfigScreen.cs
10,072
C#
using System.Reflection.Emit; using WebAssembly.Runtime.Compilation; namespace WebAssembly.Instructions { /// <summary> /// Compare equal to zero (return 1 if operand is zero, 0 otherwise). /// </summary> public class Int64EqualZero : SimpleInstruction { /// <summary> /// Always <see cref="OpCode.Int64EqualZero"/>. /// </summary> public sealed override OpCode OpCode => OpCode.Int64EqualZero; /// <summary> /// Creates a new <see cref="Int64EqualZero"/> instance. /// </summary> public Int64EqualZero() { } internal sealed override void Compile(CompilationContext context) { var stack = context.Stack; context.PopStackNoReturn(this.OpCode, WebAssemblyValueType.Int64); stack.Push(WebAssemblyValueType.Int32); context.Emit(OpCodes.Ldc_I4_0); context.Emit(OpCodes.Conv_I8); context.Emit(OpCodes.Ceq); } } }
28.138889
78
0.604146
[ "Apache-2.0" ]
Astn/dotnet-webassembly
WebAssembly/Instructions/Int64EqualZero.cs
1,013
C#
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. 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. * */ #endregion using System.Threading; using Quartz.Core; namespace Quartz.Spi { /// <summary> /// The interface to be implemented by classes that want to provide a thread /// pool for the <see cref="IScheduler" />'s use. /// </summary> /// <remarks> /// <see cref="IThreadPool" /> implementation instances should ideally be made /// for the sole use of Quartz. Most importantly, when the method /// <see cref="BlockForAvailableThreads()" /> returns a value of 1 or greater, /// there must still be at least one available thread in the pool when the /// method <see cref="RunInThread(IThreadRunnable)"/> is called a few moments (or /// many moments) later. If this assumption does not hold true, it may /// result in extra JobStore queries and updates, and if clustering features /// are being used, it may result in greater imballance of load. /// </remarks> /// <seealso cref="QuartzScheduler" /> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> public interface IThreadPool { /// <summary> /// Execute the given <see cref="IThreadRunnable" /> in the next /// available <see cref="Thread" />. /// </summary> /// <remarks> /// The implementation of this interface should not throw exceptions unless /// there is a serious problem (i.e. a serious misconfiguration). If there /// are no available threads, rather it should either queue the IRunnable, or /// block until a thread is available, depending on the desired strategy. /// </remarks> bool RunInThread(IThreadRunnable runnable); /// <summary> /// Determines the number of threads that are currently available in in /// the pool. Useful for determining the number of times /// <see cref="RunInThread(IThreadRunnable)"/> can be called before returning /// false. /// </summary> ///<remarks> /// The implementation of this method should block until there is at /// least one available thread. ///</remarks> /// <returns>the number of currently available threads</returns> int BlockForAvailableThreads(); /// <summary> /// Must be called before the <see cref="ThreadPool" /> is /// used, in order to give the it a chance to Initialize. /// </summary> /// <remarks> /// Typically called by the <see cref="ISchedulerFactory" />. /// </remarks> void Initialize(); /// <summary> /// Called by the QuartzScheduler to inform the <see cref="ThreadPool" /> /// that it should free up all of it's resources because the scheduler is /// shutting down. /// </summary> void Shutdown(bool waitForJobsToComplete); /// <summary> /// Get the current number of threads in the <see cref="IThreadPool" />. /// </summary> int PoolSize { get; } /// <summary> /// Inform the <see cref="IThreadPool" /> of the Scheduler instance's Id, /// prior to initialize being invoked. /// </summary> string InstanceId { set; } /// <summary> /// Inform the <see cref="IThreadPool" /> of the Scheduler instance's name, /// prior to initialize being invoked. /// </summary> string InstanceName { set; } } }
40.165049
92
0.626058
[ "MIT" ]
TrevorDArcyEvans/EllieWare
Code/Quartz.NET/src/Quartz/SPI/IThreadPool.cs
4,137
C#
using System; using System.Linq; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Razor.TagHelpers; using Microsoft.Extensions.Options; using Robotify.AspNetCore.Config; namespace Robotify.AspNetCore.MetaTags { public class RobotifyMetaTagHelperComponent : TagHelperComponent { private readonly IOptions<RobotifyOptions> options; public RobotifyMetaTagHelperComponent(IOptions<RobotifyOptions> options) { this.options = options; } [ViewContext] public ViewContext ViewContext { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { if (options.Value.Enabled && context.TagName.Equals("head", StringComparison.Ordinal)) { var keys = ViewContext.ActionDescriptor.Properties.Keys.OfType<string>().Where(k => k.StartsWith(RobotifyMetaTagAttribute.Key)); foreach (var key in keys) { if (ViewContext.ActionDescriptor.Properties.TryGetValue(key, out object value) && value is RobotifyMetaTag metaTag) { var tag = $"\t<meta name=\"{metaTag.UserAgent}\" content=\"{string.Join(",", metaTag.Directives)}\">\n"; output.PostContent.AppendHtml(tag); } } } } } }
36.761905
145
0.595855
[ "MIT" ]
rickbutterfield/robotify-netcore
src/Robotify.AspNetCore/MetaTags/RobotifyMetaTagHelperComponent.cs
1,546
C#
using System; using System.Linq; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Streams; namespace StreamsTest { [TestClass] public class StreamTest { [TestMethod] public void EmptyStreamStartsAtEnd() { Stream<int> stream = new Stream<int>(new int[0]); Assert.IsTrue(stream.AtEnd); } [TestMethod] public void EmptyStreamReturnsDefaultValue() { Stream<int> s1 = new Stream<int>(new int[0]); Assert.AreEqual(0, s1.Next()); Assert.AreEqual(0, s1.Peek()); Stream<object> s2 = new Stream<object>(new object[0]); Assert.IsNull(s2.Next()); Assert.IsNull(s2.Peek()); } [TestMethod] public void SendingNextToEmptyStreamAlwaysReturnsDefaultValue() { Stream<object> stream = new Stream<object>(new object[0]); Assert.IsNull(stream.Next()); Assert.IsNull(stream.Next()); Assert.IsNull(stream.Next()); } [TestMethod] public void NextAdvancesTheStreamPosition() { Stream<int> stream = new Stream<int>(new int[3] { 1, 2, 3 }); Assert.AreEqual(0, stream.Position); stream.Next(); Assert.AreEqual(1, stream.Position); } [TestMethod] public void NextAdvancesTheStreamPositionUntilTheEnd() { Stream<int> stream = new Stream<int>(new int[3] { 1, 2, 3 }); stream.Next(); stream.Next(); stream.Next(); Assert.IsTrue(stream.AtEnd); stream.Next(); Assert.IsTrue(stream.AtEnd); } [TestMethod] public void PeekDoesNotAdvancesTheStreamPosition() { Stream<int> stream = new Stream<int>(new int[3] { 1, 2, 3 }); Assert.AreEqual(0, stream.Position); stream.Peek(); Assert.AreEqual(0, stream.Position); } [TestMethod] public void NextReturnsTheStreamElementsInOrder() { Stream<int> stream = new Stream<int>(new int[3] { 1, 2, 3 }); Assert.AreEqual(1, stream.Next()); Assert.AreEqual(2, stream.Next()); Assert.AreEqual(3, stream.Next()); } [TestMethod] public void UpToReturnsTheElementsFromTheCurrentPositionToTheFirstOccurrence() { Stream<int> stream = new Stream<int>(Enumerable.Range(1, 10)); IEnumerable<int> expected = new int[2] { 2, 3 }; stream.Next(); // Discard first Assert.IsTrue(expected.SequenceEqual(stream.UpTo(4))); } [TestMethod] public void UpToLimitIsNotInclusive() { Stream<int> stream = new Stream<int>(Enumerable.Range(1, 10)); stream.UpTo(4); Assert.AreEqual(5, stream.Next()); } [TestMethod] public void UpToStopsAtTheEndIfOccurrenceNotFound() { Stream<int> stream = new Stream<int>(Enumerable.Range(1, 3)); IEnumerable<int> expected = new int[3] { 1, 2, 3 }; Assert.IsTrue(expected.SequenceEqual(stream.UpTo(11))); } [TestMethod] public void UpToEndReturnsTheElementsFromCurrentPositionToTheEnd() { Stream<int> stream = new Stream<int>(Enumerable.Range(1, 5)); IEnumerable<int> expected = new int[3] { 3, 4, 5 }; stream.Next(); // Discard first stream.Next(); // Discard second Assert.IsTrue(expected.SequenceEqual(stream.UpToEnd())); } [TestMethod] public void UpToAlsoAcceptsFunctionsAsParameter() { Stream<int> stream = new Stream<int>(Enumerable.Range(1, 5)); Func<int, bool> even = (n) => n % 2 == 0; Assert.IsTrue(stream.UpTo(even).SequenceEqual(new int[1] { 1 })); Assert.IsTrue(stream.UpTo(even).SequenceEqual(new int[1] { 3 })); Assert.IsTrue(stream.UpTo(even).SequenceEqual(new int[1] { 5 })); Assert.IsTrue(stream.UpTo(even).SequenceEqual(new int[0])); } [TestMethod] public void UpToAcceptsANullParameter() { Stream<string> stream = new Stream<string>(new string[3] { "a", null, "b" }); Assert.IsTrue(stream.UpTo((string)null).SequenceEqual(new string[1] { "a" })); } [TestMethod] public void NextAcceptsAnIntegerArgAndReturnsAsManyElementsAsTheArgSays() { Stream<int> stream = new Stream<int>(Enumerable.Range(1, 10)); Assert.IsTrue(stream.Next(3).SequenceEqual(new int[3] { 1, 2, 3 })); Assert.IsTrue(stream.Next(2).SequenceEqual(new int[2] { 4, 5 })); } [TestMethod] public void IfNextReachesTheEndItStopsRightThereRegardlessOfTheCountParameter() { Stream<int> stream = new Stream<int>(Enumerable.Range(1, 10)); stream.Next(5); // Discard the first half Assert.IsTrue(stream.Next(10).SequenceEqual(new int[5] { 6, 7, 8, 9, 10 })); } [TestMethod] public void SkipAllowsMeToQuicklyDiscardElements() { Stream<int> stream = new Stream<int>(Enumerable.Range(1, 10)); stream.Skip(5); // Discard the first half Assert.AreEqual(5, stream.Position); Assert.AreEqual(6, stream.Next()); } [TestMethod] public void MovingOverTheEndShouldNotIncrementThePosition() { Stream<int> stream = new Stream<int>(Enumerable.Range(1, 3)); stream.Next(10); Assert.AreEqual(3, stream.Position); } [TestMethod] public void SkippingOverTheEndShouldNotIncrementThePosition() { Stream<int> stream = new Stream<int>(Enumerable.Range(1, 3)); stream.Skip(10); Assert.AreEqual(3, stream.Position); } } }
34.725714
90
0.565411
[ "MIT" ]
RichoM/Streams
src/StreamsTest/StreamTest.cs
6,079
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Jag.VictimServices.Interfaces.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// TraceInfo /// </summary> public partial class MicrosoftDynamicsCRMTraceInfo { /// <summary> /// Initializes a new instance of the MicrosoftDynamicsCRMTraceInfo /// class. /// </summary> public MicrosoftDynamicsCRMTraceInfo() { CustomInit(); } /// <summary> /// Initializes a new instance of the MicrosoftDynamicsCRMTraceInfo /// class. /// </summary> public MicrosoftDynamicsCRMTraceInfo(IList<MicrosoftDynamicsCRMErrorInfo> errorInfoList = default(IList<MicrosoftDynamicsCRMErrorInfo>)) { ErrorInfoList = errorInfoList; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "ErrorInfoList")] public IList<MicrosoftDynamicsCRMErrorInfo> ErrorInfoList { get; set; } } }
28.96
144
0.627762
[ "Apache-2.0" ]
JonTaylorBCGov2/pssg-cscp-cpu
cpu-interfaces/Dynamics-Autorest/Models/MicrosoftDynamicsCRMTraceInfo.cs
1,448
C#
using Twilio.Http; namespace Twilio.Clients { /// <summary> /// Interface for a Twilio Client /// </summary> public interface ITwilioRestClient { /// <summary> /// Get the account sid all requests are made against /// </summary> string AccountSid { get; } /// <summary> /// Get the region requests are made against /// </summary> string Region { get; } /// <summary> /// Get the http client that makes requests /// </summary> HttpClient HttpClient { get; } /// <summary> /// Make a request to Twilio /// </summary> /// /// <param name="request">Request to make</param> /// <returns>response of the request</returns> Response Request(Request request); #if !NET35 /// <summary> /// Make a request to Twilio /// </summary> /// /// <param name="request">Request to make</param> /// <returns>response of the request</returns> System.Threading.Tasks.Task<Response> RequestAsync(Request request); #endif } }
25.333333
76
0.542105
[ "MIT" ]
BrimmingDev/twilio-csharp
src/Twilio/Clients/ITwilioRestClient.cs
1,142
C#
using System.Threading.Tasks; namespace HotChocolate.Execution.Processing { /// <summary> /// Represents a deprioritized part of the query that will be executed after /// the main execution has finished. /// </summary> internal interface IDeferredExecutionTask { /// <summary> /// Executes the deferred execution task with the specified /// <paramref name="operationContext"/>. /// </summary> /// <param name="operationContext"> /// The operation context. /// </param> /// <returns> /// The query result that the deferred execution task produced. /// </returns> Task<IQueryResult> ExecuteAsync(IOperationContext operationContext); } }
31.333333
80
0.625
[ "MIT" ]
Asshiah/hotchocolate
src/HotChocolate/Core/src/Execution/Processing/IDeferredExecutionTask.cs
752
C#
using System; using System.Collections.Generic; #nullable disable namespace DemoInsertTown.Models { public partial class NamesWithSalary { public string FullName { get; set; } public decimal Salary { get; set; } } }
18.571429
45
0.646154
[ "MIT" ]
Katsarov/EF-Core
02.ORM_Lab/ORMLab/DemoInsertTown/Models/NamesWithSalary.cs
262
C#
using ManahostManager.Utils; using MsgPack.Serialization; using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; namespace ManahostManager.Domain.Entity { // Payment for accessing all Manahost features => VIP // No HomeId so this table won't be accessible through the advanced search [Table("Payment")] public class Payment { [Key] public int Id { get; set; } [MaxLength(256, ErrorMessage = GenericError.DOES_NOT_MEET_REQUIREMENTS)] public String AccountName { get; set; } [MaxLength(256, ErrorMessage = GenericError.DOES_NOT_MEET_REQUIREMENTS)] public String Label { get; set; } public String RemoteIP { get; set; } public Decimal? Price { get; set; } public int SubscriptionId { get; set; } [IgnoreDataMember] [MessagePackIgnore] public Subscription Subscription { get; set; } } }
28.657143
80
0.685942
[ "MIT" ]
charla-n/ManahostManager
ManahostManager.Domain/Entity/Payment.cs
1,005
C#
using System.IO; using System; using Aspose.Pdf; namespace Aspose.Pdf.Examples.CSharp.AsposePDF.DocumentConversion.PDFToHTMLFormat { public class SingleHTML { public static void Run() { try { // ExStart:SingleHTML // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion_PDFToHTMLFormat(); // Load source PDF file Document doc = new Document(dataDir + "input.pdf"); // Instantiate HTML Save options object HtmlSaveOptions newOptions = new HtmlSaveOptions(); // Enable option to embed all resources inside the HTML newOptions.PartsEmbeddingMode = HtmlSaveOptions.PartsEmbeddingModes.EmbedAllIntoHtml; // This is just optimization for IE and can be omitted newOptions.LettersPositioningMethod = HtmlSaveOptions.LettersPositioningMethods.UseEmUnitsAndCompensationOfRoundingErrorsInCss; newOptions.RasterImagesSavingMode = HtmlSaveOptions.RasterImagesSavingModes.AsEmbeddedPartsOfPngPageBackground; newOptions.FontSavingMode = HtmlSaveOptions.FontSavingModes.SaveInAllFormats; // Output file path string outHtmlFile = "SingleHTML_out.html"; doc.Save(outHtmlFile, newOptions); // ExEnd:SingleHTML } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
40.225
143
0.622126
[ "MIT" ]
Swisscard/Aspose.PDF-for-.NET
Examples/CSharp/AsposePDF/DocumentConversion/PDFToHTMLFormat/SingleHTML.cs
1,609
C#
using PlayFab.PfEditor.EditorModels; using System; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; namespace PlayFab.PfEditor { public class PlayFabEditorToolsMenu : UnityEditor.Editor { public static float buttonWidth = 200; public static Vector2 scrollPos = Vector2.zero; public static void DrawToolsPanel() { scrollPos = GUILayout.BeginScrollView(scrollPos, PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")); buttonWidth = EditorGUIUtility.currentViewWidth > 400 ? EditorGUIUtility.currentViewWidth / 2 : 200; using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear"))) { EditorGUILayout.LabelField("CLOUD SCRIPT:", PlayFabEditorHelper.uiStyle.GetStyle("labelStyle")); GUILayout.Space(10); if (GUILayout.Button("IMPORT", PlayFabEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinHeight(30))) { ImportCloudScript(); } GUILayout.Space(10); if (File.Exists(PlayFabEditorDataService.EnvDetails.localCloudScriptPath)) { if (GUILayout.Button("REMOVE", PlayFabEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinHeight(30))) { PlayFabEditorDataService.EnvDetails.localCloudScriptPath = string.Empty; PlayFabEditorDataService.SaveEnvDetails(); } GUILayout.Space(10); if (GUILayout.Button("EDIT", PlayFabEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinHeight(30))) { EditorUtility.OpenWithDefaultApp(PlayFabEditorDataService.EnvDetails.localCloudScriptPath); } } } if (File.Exists(PlayFabEditorDataService.EnvDetails.localCloudScriptPath)) { var path = File.Exists(PlayFabEditorDataService.EnvDetails.localCloudScriptPath) ? PlayFabEditorDataService.EnvDetails.localCloudScriptPath : PlayFabEditorHelper.CLOUDSCRIPT_PATH; var shortPath = "..." + path.Substring(path.LastIndexOf('/')); using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear"))) { GUILayout.FlexibleSpace(); if (GUILayout.Button(shortPath, PlayFabEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinWidth(110), GUILayout.MinHeight(20))) { EditorUtility.RevealInFinder(path); } // GUILayout.Space(10); // if (GUILayout.Button("EDIT LOCALLY", PlayFabEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinWidth(90), GUILayout.MinHeight(20))) // { // EditorUtility.OpenWithDefaultApp(path); // } GUILayout.FlexibleSpace(); } using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear"))) { GUILayout.FlexibleSpace(); if (GUILayout.Button("SAVE TO PLAYFAB", PlayFabEditorHelper.uiStyle.GetStyle("Button"), GUILayout.MinHeight(32), GUILayout.Width(buttonWidth))) { if (EditorUtility.DisplayDialog("Deployment Confirmation", "This action will upload your local Cloud Script changes to PlayFab?", "Continue", "Cancel")) { BeginCloudScriptUpload(); } } GUILayout.FlexibleSpace(); } } else { using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear"))) { GUILayout.FlexibleSpace(); EditorGUILayout.LabelField("No Cloud Script files added. Import your file to get started.", PlayFabEditorHelper.uiStyle.GetStyle("orTxt")); GUILayout.FlexibleSpace(); } } GUILayout.EndScrollView(); } private static void ImportCloudScript() { var dialogResponse = EditorUtility.DisplayDialogComplex("Selcet an Import Option", "What Cloud Script file do you want to import?", "Use my latest PlayFab revision", "Cancel", "Use my local file"); switch (dialogResponse) { case 0: // use PlayFab GetCloudScriptRevision(); break; case 1: // cancel return; case 2: //use local SelectLocalFile(); break; } } private static void GetCloudScriptRevision() { // empty request object gets latest versions PlayFabEditorApi.GetCloudScriptRevision(new EditorModels.GetCloudScriptRevisionRequest(), (GetCloudScriptRevisionResult result) => { var csPath = PlayFabEditorHelper.CLOUDSCRIPT_PATH; var location = Path.GetDirectoryName(csPath); try { if (!Directory.Exists(location)) Directory.CreateDirectory(location); if (!File.Exists(csPath)) using (var newfile = File.Create(csPath)) { } File.WriteAllText(csPath, result.Files[0].FileContents); Debug.Log("CloudScript uploaded successfully!"); PlayFabEditorDataService.EnvDetails.localCloudScriptPath = csPath; PlayFabEditorDataService.SaveEnvDetails(); AssetDatabase.Refresh(); } catch (Exception ex) { Debug.LogException(ex); // PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, ex.Message); return; } }, PlayFabEditorHelper.SharedErrorCallback); } private static void SelectLocalFile() { var starterPath = File.Exists(PlayFabEditorDataService.EnvDetails.localCloudScriptPath) ? Application.dataPath : PlayFabEditorDataService.EnvDetails.localCloudScriptPath; var cloudScriptPath = string.Empty; cloudScriptPath = EditorUtility.OpenFilePanel("Select your Cloud Script file", starterPath, "js"); if (!string.IsNullOrEmpty(cloudScriptPath)) { PlayFabEditorDataService.EnvDetails.localCloudScriptPath = cloudScriptPath; PlayFabEditorDataService.SaveEnvDetails(); } } private static void BeginCloudScriptUpload() { var filePath = File.Exists(PlayFabEditorDataService.EnvDetails.localCloudScriptPath) ? PlayFabEditorDataService.EnvDetails.localCloudScriptPath : PlayFabEditorHelper.CLOUDSCRIPT_PATH; if (!File.Exists(PlayFabEditorDataService.EnvDetails.localCloudScriptPath) && !File.Exists(PlayFabEditorHelper.CLOUDSCRIPT_PATH)) { PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, "Cloud Script Upload Failed: null or corrupt file at path(" + filePath + ")."); return; } var s = File.OpenText(filePath); var contents = s.ReadToEnd(); s.Close(); var request = new UpdateCloudScriptRequest(); request.Publish = EditorUtility.DisplayDialog("Deployment Options", "Do you want to make this Cloud Script live after uploading?", "Yes", "No"); request.Files = new List<CloudScriptFile>(){ new CloudScriptFile() { Filename = PlayFabEditorHelper.CLOUDSCRIPT_FILENAME, FileContents = contents } }; PlayFabEditorApi.UpdateCloudScript(request, (UpdateCloudScriptResult result) => { PlayFabEditorDataService.EnvDetails.localCloudScriptPath = filePath; PlayFabEditorDataService.SaveEnvDetails(); Debug.Log("CloudScript uploaded successfully!"); }, PlayFabEditorHelper.SharedErrorCallback); } } }
47.151351
209
0.56758
[ "MIT" ]
BrianPeek/Scavenger
src/Unity/Assets/PlayFabEditorExtensions/Editor/Scripts/Panels/PlayFabEditorToolsMenu.cs
8,723
C#
using FlatRedBall.Glue.Plugins.EmbeddedPlugins.ManagePlugins.ViewModels; using FlatRedBall.Glue.Plugins.ExportedImplementations; using FlatRedBall.Glue.Plugins.ExportedInterfaces; using FlatRedBall.IO; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace FlatRedBall.Glue.Plugins.EmbeddedPlugins.ManagePlugins { /// <summary> /// Interaction logic for PluginView.xaml /// </summary> public partial class PluginView : UserControl { PluginContainer pluginContainer { get { return (DataContext as PluginViewModel)?.BackingData; } } static string UninstallPluginFile { get { return FileManager.UserApplicationData + "FRBDK/Plugins/Uninstall.txt"; } } public PluginView() { InitializeComponent(); } private void HandleExportPluginClicked(object sender, RoutedEventArgs e) { if(DataContext != null) { Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = pluginContainer.Name.Replace(" ", ""); // Default file name dlg.DefaultExt = ".plug"; // Default file extension dlg.Filter = "Plugin (.plug)|*.plug"; // Filter files by extension // Show save file dialog box Nullable<bool> result = dlg.ShowDialog(); // Process save file dialog box results if (result == true) { // Save document string filename = dlg.FileName; ExportPluginLogic exportPluginLogic = new ExportPluginLogic(); string pluginFolder = FileManager.GetDirectory(pluginContainer.AssemblyLocation); exportPluginLogic.CreatePluginFromDirectory( sourceDirectory: pluginFolder, destinationFileName: filename, includeAllFiles: true); var startInfo = new ProcessStartInfo(); startInfo.FileName = FileManager.GetDirectory(filename); startInfo.UseShellExecute = true; System.Diagnostics.Process.Start(startInfo); } } } private void HandleUninstallPlugin(object sender, RoutedEventArgs e) { if(DataContext != null) { var directoryToDelete = FileManager.GetDirectory( pluginContainer.AssemblyLocation); // try deleteing it, probably won't be able to because the plugin is in-use try { FileManager.DeleteDirectory(directoryToDelete); } catch(UnauthorizedAccessException ex) { EditorObjects.IoC.Container.Get<IGlueCommands>().DialogCommands.ShowMessageBox("Success - Glue must be restarted to finish removing the plugin."); using (StreamWriter w = File.AppendText(UninstallPluginFile)) { w.WriteLine(directoryToDelete); } } } } private void HandleOpenPluginFolderClicked(object sender, RoutedEventArgs e) { if(pluginContainer != null) { ProcessStartInfo psi = new ProcessStartInfo(); psi.UseShellExecute = true; psi.FileName = FileManager.GetDirectory(pluginContainer.AssemblyLocation); System.Diagnostics.Process.Start(psi); } } } }
32.409449
166
0.585034
[ "MIT" ]
coldacid/FlatRedBall
FRBDK/Glue/Glue/Plugins/EmbeddedPlugins/ManagePlugins/PluginView.xaml.cs
4,118
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 iot-2015-05-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.IoT.Model { /// <summary> /// The resource registration failed. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class ResourceRegistrationFailureException : AmazonIoTException { /// <summary> /// Constructs a new ResourceRegistrationFailureException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public ResourceRegistrationFailureException(string message) : base(message) {} /// <summary> /// Construct instance of ResourceRegistrationFailureException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public ResourceRegistrationFailureException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of ResourceRegistrationFailureException /// </summary> /// <param name="innerException"></param> public ResourceRegistrationFailureException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of ResourceRegistrationFailureException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public ResourceRegistrationFailureException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of ResourceRegistrationFailureException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public ResourceRegistrationFailureException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the ResourceRegistrationFailureException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected ResourceRegistrationFailureException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
48.072581
178
0.687301
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/IoT/Generated/Model/ResourceRegistrationFailureException.cs
5,961
C#
using Mews.Fiscalizations.Core.Model; namespace Mews.Fiscalizations.Hungary.Models { public sealed class SupplierInfo : Info { public SupplierInfo(TaxpayerIdentificationNumber taxpayerId, Name name, SimpleAddress address, VatCode vatCode) : base(taxpayerId, name, address) { VatCode = Check.IsNotNull(vatCode, nameof(vatCode)); } public VatCode VatCode { get; } } }
27.3125
119
0.668192
[ "MIT" ]
MewsSystems/fiscalizations
src/Hungary/Mews.Fiscalizations.Hungary/Models/Invoice/SupplierInfo.cs
439
C#
using System; using System.Diagnostics; using System.Linq; using System.Reflection; namespace NSeed.Seeding.Extensions { internal static class TypeExtensions { public static bool IsSeedType(this Type type) { Debug.Assert(type != null); return !type.IsAbstract && type.IsSealed && type.GetInterfaces().Contains(typeof(ISeed)); } public static bool IsSeedingSetupType(this Type type) { Debug.Assert(type != null); return !type.IsAbstract && type.GetInterfaces().Contains(typeof(ISeedingSetup)) && type.HasParameterlessConstructor(); } private static readonly Type[] EmptyTypeArray = new Type[0]; public static bool HasParameterlessConstructor(this Type type) { Debug.Assert(type != null); return type.GetConstructor(EmptyTypeArray) != null; } public static bool IsSeedOutputProperty(this PropertyInfo propertyInfo) { Debug.Assert(propertyInfo != null); return propertyInfo.CanRead && propertyInfo.CanWrite && PropertyTypeIsSeedOutputType(propertyInfo.PropertyType); bool PropertyTypeIsSeedOutputType(Type propertyType) { return propertyType.Name == "Output" && propertyType.IsClass && propertyType.IsAbstract == false && // It must not be a static class, which means !IsAbstract && !IsSealed, // but we already checked for !IsAbstract so there is no need for additional check. propertyType.IsNestedPublic && propertyType.DeclaringType.IsSeedType(); } } } }
35.396226
107
0.569296
[ "MIT" ]
nseedio/nseed
lab/DynamicAssemblyLoading/nseed/NSeed.Seeding/Extensions/TypeExtensions.cs
1,878
C#
// Wi Advice (https://github.com/raste/WiAdvice)(http://www.wiadvice.com/) // Copyright (c) 2015 Georgi Kolev. // Licensed under Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0). using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using DataAccess; namespace BusinessLayer { public class BusinessLog { private string userIPadress { get; set; } private long UserID { get; set; } public BusinessLog(long userID, string ipAdress) { UserID = userID; userIPadress = ipAdress; } public BusinessLog(long userID) { UserID = userID; userIPadress = "127.0.0.1"; } /// <summary> /// Adds new Log /// </summary> private void Add(Entities objectContext, Log newLog) { Tools.AssertObjectContextExists(objectContext); if (newLog == null) { throw new ArgumentNullException("newLog"); } objectContext.AddToLogSet(newLog); Tools.Save(objectContext); } /// <summary> /// Builds new log /// </summary> private void BuildLog(Entities objectContext, LogType type, string typeOfObect, long obectID, string description) { if (userIPadress == null || userIPadress.Length < 1) { throw new BusinessException("userIPadress is null or empty"); } if (typeOfObect == null || typeOfObect.Length < 1) { throw new BusinessException("typeOfObect is null or empty"); } if (obectID < 1) { throw new BusinessException("obectID is < 1"); } if (description == null || description.Length < 1) { throw new BusinessException("description is null or empty"); } BusinessUser businessUser = new BusinessUser(); User currUser = null; if (UserID < 1) { if (typeOfObect == "comment") { currUser = businessUser.GetGuest(); } else { currUser = businessUser.GetSystem(); } } else { currUser = businessUser.Get(UserID, true); } if (currUser == null) { throw new BusinessException("currUser is null"); } UserID user = Tools.GetUserID(objectContext, currUser); Log newLog = new Log(); newLog.UserID = user; newLog.dateCreated = DateTime.UtcNow; newLog.description = description; newLog.type = GetLogTypeAsString(type); newLog.typeModifiedSubject = typeOfObect; newLog.IDModifiedSubject = obectID; newLog.userIPadress = userIPadress; Add(objectContext, newLog); } private void BuildUserLog(EntitiesUsers userContext, LogType type, string typeOfObect, User modifiedUser, string description) { if (userIPadress == null || userIPadress.Length < 1) { throw new BusinessException("userIPadress is null or empty"); } if (typeOfObect == null || typeOfObect.Length < 1) { throw new BusinessException("typeOfObect is null or empty"); } if (modifiedUser == null) { throw new BusinessException("modifiedUserID is null"); } if (description == null || description.Length < 1) { throw new BusinessException("description is null or empty"); } BusinessUser businessUser = new BusinessUser(); User currUser = null; if (UserID < 1) { currUser = businessUser.GetSystem(userContext); } else { currUser = businessUser.Get(userContext, UserID, true); } if (currUser == null) { throw new BusinessException("currUser is null"); } UserLog newLog = new UserLog(); newLog.UserModifying = currUser; newLog.dateCreated = DateTime.UtcNow; newLog.description = description; newLog.type = GetLogTypeAsString(type); newLog.typeModified = typeOfObect; newLog.UserModified = modifiedUser; newLog.IpAdress = userIPadress; userContext.AddToUserLogSet(newLog); Tools.Save(userContext); } public void LogAdvertisement(Entities objectContext, Advertisement advert, LogType type, string field, string oldValue, User currUser) { Tools.AssertObjectContextExists(objectContext); if (advert == null) { throw new BusinessException("advert is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("Advertisement ID : {0} was added by {1}.", advert.ID, currUser.username); break; case LogType.delete: description = string.Format("Advertisement ID : {0} was deleted by {1}.", advert.ID, currUser.username); break; case LogType.undelete: description = string.Format("Advertisement ID : {0} was UN-deleted by {1}.", advert.ID, currUser.username); break; case LogType.edit: description = string.Format("Advertisement ID : {0}, field : {1}, was modified by {2}, old value was : ' {3} '" , advert.ID, field, currUser.username, oldValue); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Advertisements", type)); } BuildLog(objectContext, type, "advertisement", advert.ID, description); } public void LogSiteText(Entities objectContext, SiteNews siteText, LogType type, string field, string oldValue, User currUser) { Tools.AssertObjectContextExists(objectContext); if (siteText == null) { throw new BusinessException("siteText is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("Site text : ' {0} ' was added by {1}.", siteText.name, currUser.username); break; case LogType.delete: description = string.Format("Site text : ' {0} ' was deleted by {1}.", siteText.name, currUser.username); break; case LogType.undelete: description = string.Format("Site text : ' {0} ' was UN-deleted by {1}.", siteText.name, currUser.username); break; case LogType.edit: description = string.Format("Site text : ' {0} ', field : {1}, was modified by {2}, old value was : ' {3} '" , siteText.name, field, currUser.username, oldValue); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Site texts", type)); } BuildLog(objectContext, type, "siteText", siteText.ID, description); } public void LogCategory(Entities objectContext, Category category, LogType type, string field, string oldValue, User currUser) { Tools.AssertObjectContextExists(objectContext); if (category == null) { throw new BusinessException("category is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("Category : ' {0} ' was added by {1}.", category.name, currUser.username); break; case LogType.delete: description = string.Format("Category : ' {0} ' was deleted by {1}.", category.name, currUser.username); break; case LogType.undelete: description = string.Format("Category : ' {0} ' was UN-deleted by {1}.", category.name, currUser.username); break; case LogType.edit: description = string.Format("Category : ' {0} ', field : {1}, was modified by {2}, old value was : ' {3} '" , category.name, field, currUser.username, oldValue); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Categories", type)); } BuildLog(objectContext, type, "category", category.ID, description); } public void LogProduct(Entities objectContext, Product product, LogType type, string field, string oldValue, User currUser) { Tools.AssertObjectContextExists(objectContext); if (product == null) { throw new BusinessException("product is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("Product : ' {0} ' was added by {1}.", product.name, currUser.username); break; case LogType.delete: description = string.Format("Product : ' {0} ' was deleted by {1}.", product.name, currUser.username); break; case LogType.undelete: description = string.Format("Product : ' {0} ' was UN-deleted by {1}.", product.name, currUser.username); break; case LogType.edit: description = string.Format("Product : ' {0} ', field : {1}, was modified by {2}, old value was : ' {3} '" , product.name, field, currUser.username, oldValue); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Products", type)); } BuildLog(objectContext, type, "product", product.ID, description); } public void LogSuggestion(Entities objectContext, Suggestion suggestion, LogType type, User currUser) { Tools.AssertObjectContextExists(objectContext); if (suggestion == null) { throw new BusinessException("suggestion is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("Suggestion ID : '{0}' was added by {1}.", suggestion.ID, currUser.username); break; case LogType.delete: description = string.Format("Suggestion ID : '{0}' was deleted by {1}.", suggestion.ID, currUser.username); break; case LogType.undelete: description = string.Format("Suggestion ID : '{0}' was UN-deleted by {1}.", suggestion.ID, currUser.username); break; case LogType.edit: throw new BusinessException("LogType.edit is not supported for suggestions"); } BuildLog(objectContext, type, "suggestion", suggestion.ID, description); } public void LogRateProduct(Entities objectContext, Product product, ProductRating rating, LogType type, User currUser) { Tools.AssertObjectContextExists(objectContext); if (product == null) { throw new BusinessException("product is null"); } if (rating == null) { throw new BusinessException("rating is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("Product : '{0}' was rated by {1}, rating id : {2}.", product.name, currUser.username, rating.ID); break; case LogType.delete: if (!rating.UserReference.IsLoaded) { rating.UserReference.Load(); } User userRated = Tools.GetUserFromUserDatabase(rating.User.ID); description = string.Format("Product : '{0}' rating by {1} ID : {2} was removed by {3}, rating id : {4}." , product.name, userRated.username, userRated.ID, currUser.username, rating.ID); break; case LogType.undelete: if (!rating.UserReference.IsLoaded) { rating.UserReference.Load(); } User userRated2 = Tools.GetUserFromUserDatabase(rating.User.ID); description = string.Format("Product : '{0}' rating by {1} ID : {2} was Un-deleted by {3}, rating id : {4}." , product.name, userRated2.username, userRated2.ID, currUser.username, rating.ID); break; case LogType.edit: throw new BusinessException("LogType.edit is not supported for rate products"); } BuildLog(objectContext, type, "rateProduct", product.ID, description); } public void LogRateComment(Entities objectContext, Comment comment, CommentRating rating, LogType type, User currUser) { Tools.AssertObjectContextExists(objectContext); if (comment == null) { throw new BusinessException("comment is null"); } if (rating == null) { throw new BusinessException("rating is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("Comment ID : '{0}' was rated by {1}, rating id : {2}.", comment.ID, currUser.username, rating.ID); break; case LogType.delete: if (!rating.UserReference.IsLoaded) { rating.UserReference.Load(); } User userRated = Tools.GetUserFromUserDatabase(rating.User.ID); description = string.Format("Comment ID : '{0}' rating by {1} ID : {2} was removed by {3}, rating id : {4}." , comment.ID, userRated.username, userRated.ID, currUser.username, rating.ID); break; case LogType.undelete: if (!rating.UserReference.IsLoaded) { rating.UserReference.Load(); } User userRated2 = Tools.GetUserFromUserDatabase(rating.User.ID); description = string.Format("Comment ID : '{0}' rating by {1} ID : {2} was Un-deleted by {3}, rating id : {4}." , comment.ID, userRated2.username, userRated2.ID, currUser.username, rating.ID); break; case LogType.edit: throw new BusinessException("LogType.edit is not supported for rate comments"); } BuildLog(objectContext, type, "rateComment", comment.ID, description); } public void LogCompany(Entities objectContext, Company company, LogType type, string field, string oldValue, User currUser) { Tools.AssertObjectContextExists(objectContext); if (company == null) { throw new BusinessException("company is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("Company : ' {0} ' was added by {1}.", company.name, currUser.username); break; case LogType.delete: description = string.Format("Company : ' {0} ' was deleted by {1}.", company.name, currUser.username); break; case LogType.undelete: description = string.Format("Company : ' {0} ' was UN-deleted by {1}.", company.name, currUser.username); break; case LogType.edit: description = string.Format("Company : ' {0} ', field : {1}, was modified by {2}, old value was : ' {3} '" , company.name, field, currUser.username, oldValue); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Companies", type)); } BuildLog(objectContext, type, "company", company.ID, description); } public void LogCompanyType(Entities objectContext, CompanyType companyType, LogType type, string field, string oldValue, User currUser) { Tools.AssertObjectContextExists(objectContext); if (companyType == null) { throw new BusinessException("companyType is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("Company type : ' {0} ' was added by {1}.", companyType.name, currUser.username); break; case LogType.delete: description = string.Format("Company type : ' {0} ' was deleted by {1}.", companyType.name, currUser.username); break; case LogType.undelete: description = string.Format("Company type : ' {0} ' was UN-deleted by {1}.", companyType.name, currUser.username); break; case LogType.edit: description = string.Format("Company type : ' {0} ', field : {1}, was modified by {2}, old value was : ' {3} '" , companyType.name, field, currUser.username, oldValue); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Company types", type)); } BuildLog(objectContext, type, "companyType", companyType.ID, description); } public void LogUser(Entities objectContext, EntitiesUsers userContext, User userModified, LogType type, string field, string oldValue, User currUser) { Tools.AssertObjectContextExists(objectContext); Tools.AssertObjectContextExists(userContext); if (userModified == null) { throw new BusinessException("userModified is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("User : ' {0} ' registered by {1}.", userModified.username, currUser.username); break; case LogType.delete: description = string.Format("User : ' {0} ' was deleted by {1}.", userModified.username, currUser.username); break; case LogType.undelete: description = string.Format("User : ' {0} ' was UN-deleted by {1}.", userModified.username, currUser.username); break; case LogType.edit: if (currUser == userModified) { description = string.Format("User : ' {0} ' modified field : {1}, old value was : ' {2} '" , userModified.username, field, oldValue); } else { description = string.Format("User : ' {0} ', field : {1}, was modified by {2}, old value was : ' {3} '" , userModified.username, field, currUser.username, oldValue); } break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Users", type)); } BuildLog(objectContext, type, "user", userModified.ID, description); BuildUserLog(userContext, type, "user", userModified, description); } public void LogCompanyCharacteristic(Entities objectContext, CompanyCharacterestics characteristic, LogType type, string field, string oldValue, User currUser) { Tools.AssertObjectContextExists(objectContext); if (characteristic == null) { throw new BusinessException("characteristic is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("Company characteristic : ' {0} ' was added by {1}.", characteristic.name, currUser.username); break; case LogType.delete: description = string.Format("Company characteristic : ' {0} ' was deleted by {1}.", characteristic.name, currUser.username); break; case LogType.undelete: description = string.Format("Company characteristic : ' {0} ' was UN-deleted by {1}.", characteristic.name, currUser.username); break; case LogType.edit: description = string.Format("Company characteristic : ' {0} ', field : {1}, was modified by {2}, old value was : ' {3} '" , characteristic.name, field, currUser.username, oldValue); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Company characteristics", type)); } BuildLog(objectContext, type, "companyCharacteristic", characteristic.ID, description); } public void LogProductCharacteristic(Entities objectContext, ProductCharacteristics characteristic, LogType type, string field, string oldValue, User currUser) { Tools.AssertObjectContextExists(objectContext); if (characteristic == null) { throw new BusinessException("characteristic is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("Product characteristic : ' {0} ' was added by {1}.", characteristic.name, currUser.username); break; case LogType.delete: description = string.Format("Product characteristic : ' {0} ' was deleted by {1}.", characteristic.name, currUser.username); break; case LogType.undelete: description = string.Format("Product characteristic : ' {0} ' was UN-deleted by {1}.", characteristic.name, currUser.username); break; case LogType.edit: description = string.Format("Product characteristic : ' {0} ', field : {1}, was modified by {2}, old value was : ' {3} '" , characteristic.name, field, currUser.username, oldValue); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Product characteristics", type)); } BuildLog(objectContext, type, "productCharacteristic", characteristic.ID, description); } public void LogProductLink(Entities objectContext, ProductLink link, LogType type, string field, string oldValue, User currUser) { Tools.AssertObjectContextExists(objectContext); if (link == null) { throw new BusinessException("link is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } if (!link.ProductReference.IsLoaded) { link.ProductReference.Load(); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("Product link : ' {0} ' (for product ' {1} ' ID : {2}) was added by {3}." , link.link, link.Product.name, link.Product.ID, currUser.username); break; case LogType.delete: description = string.Format("Product link : ' {0} ' (for product ' {1} ' ID : {2}) was deleted by {3}." , link.link, link.Product.name, link.Product.ID, currUser.username); break; case LogType.undelete: description = string.Format("Product link : ' {0} ' (for product ' {1} ' ID : {2}) was UN-deleted by {3}." , link.link, link.Product.name, link.Product.ID, currUser.username); break; case LogType.edit: description = string.Format("Product link : ' {0} ' (for product ' {1} ' ID : {2}), field : {3}, was modified by {4}, old value was : ' {5} '" , link.link, link.Product.name, link.Product.ID, field, currUser.username, oldValue); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Product links", type)); } BuildLog(objectContext, type, "productLink", link.ID, description); } public void LogProductAlternativeName(Entities objectContext, AlternativeProductName altName, LogType type, User currUser) { Tools.AssertObjectContextExists(objectContext); if (altName == null) { throw new BusinessException("altName is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; if (!altName.ProductReference.IsLoaded) { altName.ProductReference.Load(); } switch (type) { case LogType.create: description = string.Format("Alternative product name : ' {0} ' for product id : {1} was added by {2}." , altName.name, altName.Product.ID, currUser.username); break; case LogType.delete: description = string.Format("Alternative product name : ' {0} ' for product id : {1} was deleted by {2}." , altName.name, altName.Product.ID, currUser.username); break; case LogType.undelete: description = string.Format("Alternative product name : ' {0} ' for product id : {1} was UN-deleted by {2}." , altName.name, altName.Product.ID, currUser.username); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Alternative product name", type)); } BuildLog(objectContext, type, "alternativeProductName", altName.ID, description); } public void LogCompanyAlternativeName(Entities objectContext, AlternativeCompanyName altName, LogType type, User currUser) { Tools.AssertObjectContextExists(objectContext); if (altName == null) { throw new BusinessException("altName is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; if (!altName.CompanyReference.IsLoaded) { altName.CompanyReference.Load(); } switch (type) { case LogType.create: description = string.Format("Alternative company name : ' {0} ' for company id : {1} was added by {2}." , altName.name, altName.Company.ID, currUser.username); break; case LogType.delete: description = string.Format("Alternative company name : ' {0} ' for company id : {1} was deleted by {2}." , altName.name, altName.Company.ID, currUser.username); break; case LogType.undelete: description = string.Format("Alternative company name : ' {0} ' for company id : {1} was UN-deleted by {2}." , altName.name, altName.Company.ID, currUser.username); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Alternative company name", type)); } BuildLog(objectContext, type, "alternativeCompanyName", altName.ID, description); } public void LogProductVariant(Entities objectContext, ProductVariant variant, LogType type, string field, string oldValue, User currUser) { Tools.AssertObjectContextExists(objectContext); if (variant == null) { throw new BusinessException("variant is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } if (!variant.ProductReference.IsLoaded) { variant.ProductReference.Load(); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("Product variant : ' {0} ' for ' {1} ' ID : {2} was added by {3}." , variant.name, variant.Product.name, variant.Product.ID, currUser.username); break; case LogType.delete: description = string.Format("Product variant : ' {0} ' for ' {1} ' ID : {2} was deleted by {2}." , variant.name, variant.Product.name, variant.Product.ID, currUser.username); break; case LogType.undelete: description = string.Format("Product variant : ' {0} ' for ' {1} ' ID : {2} was UN-deleted by {2}." , variant.name, variant.Product.name, variant.Product.ID, currUser.username); break; case LogType.edit: description = string.Format("Product variant : ' {0} ', field : {1}, was modified by {2}, old value was : ' {3} '" , variant.name, field, currUser.username, oldValue); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Product SUB variants", type)); } BuildLog(objectContext, type, "productVariant", variant.ID, description); } public void LogProductTopic(Entities objectContext, ProductTopic topic, LogType type, string field, string oldValue, User currUser) { Tools.AssertObjectContextExists(objectContext); if (topic == null) { throw new BusinessException("topic is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } if (!topic.ProductReference.IsLoaded) { topic.ProductReference.Load(); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("Product topic : ' {0} ' for ' {1} ' ID : {2} was created by {3}." , topic.name, topic.Product.name, topic.Product.ID, currUser.username); break; case LogType.delete: description = string.Format("Product topic : ' {0} ' for ' {1} ' ID : {2} was deleted by {3}." , topic.name, topic.Product.name, topic.Product.ID, currUser.username); break; case LogType.edit: description = string.Format("Product topic : ' {0} ', field : {1}, was modified by {2}, old value was : ' {3} '" , topic.name, field, currUser.username, oldValue); break; case LogType.undelete: description = string.Format("Product topic : ' {0} ', for ' {1} ' ID : {2} was UNdeleted by {3}." , topic.name, topic.Product.name, topic.Product.ID, currUser.username); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Product topics", type)); } BuildLog(objectContext, type, "productTopic", topic.ID, description); } public void LogProductSubVariant(Entities objectContext, ProductSubVariant variant, LogType type, string field, string oldValue, User currUser) { Tools.AssertObjectContextExists(objectContext); if (variant == null) { throw new BusinessException("variant is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } if (!variant.ProductReference.IsLoaded) { variant.ProductReference.Load(); } if (!variant.VariantReference.IsLoaded) { variant.VariantReference.Load(); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("Product sub variant : ' {0} ' for product ' {1} ' ID : {2}, variant ' {3} ' ID : {4}, was added by {5}." , variant.name, variant.Product.name, variant.Product.ID, variant.Variant.name, variant.Variant.ID, currUser.username); break; case LogType.delete: description = string.Format("Product sub variant : ' {0} ' for product ' {1} ' ID : {2}, variant ' {3} ' ID : {4}, was deleted by {2}." , variant.name, variant.Product.name, variant.Product.ID, variant.Variant.name, variant.Variant.ID, currUser.username); break; case LogType.undelete: description = string.Format("Product sub variant : ' {0} ' for ' {1} ' ID : {2}, variant ' {3} ' ID : {4}, was UN-deleted by {2}." , variant.name, variant.Product.name, variant.Product.ID, variant.Variant.name, variant.Variant.ID, currUser.username); break; case LogType.edit: description = string.Format("Product sub variant : ' {0} ', field : {1}, was modified by {2}, old value was : ' {3} '" , variant.name, field, currUser.username, oldValue); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Product variants", type)); } BuildLog(objectContext, type, "productSubVariant", variant.ID, description); } /// <summary> /// guestname only if user added comment is guest, for other types user is wanted /// </summary> public void LogComment(Entities objectContext, Comment comment, LogType type, string field, string oldValue, User currUser) { Tools.AssertObjectContextExists(objectContext); if (comment == null) { throw new BusinessException("comment is null"); } if (currUser == null && string.IsNullOrEmpty(comment.guestname)) { throw new BusinessException("currUser is null AND guestName is empty"); } string description = string.Empty; switch (type) { case LogType.create: string name = string.Empty; if (currUser == null) { name = string.Format("{0} (guest)", comment.guestname); } else { name = currUser.username; } description = string.Format("Comment ID : ' {0} ' was written by {1}.", comment.ID, name); break; case LogType.delete: if (currUser == null) { throw new BusinessException("User deleting comment cannot be null"); } description = string.Format("Comment ID : ' {0} ' was deleted by {1}.", comment.ID, currUser.username); break; case LogType.undelete: if (currUser == null) { throw new BusinessException("User Un-deleting comment cannot be null"); } description = string.Format("Comment ID : ' {0} ' was UN-deleted by {1}.", comment.ID, currUser.username); break; case LogType.edit: if (currUser == null) { throw new BusinessException("User editing comment cannot be null"); } description = string.Format("Comment ID : ' {0} ', field : {1}, was modified by {2}, old value was : ' {3} '" , comment.ID, field, currUser.username, oldValue); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Comments", type)); } BuildLog(objectContext, type, "comment", comment.ID, description); } public void LogIpBan(Entities objectContext, IpBan ipBan, LogType type, string field, string oldValue, User currUser) { Tools.AssertObjectContextExists(objectContext); if (ipBan == null) { throw new BusinessException("ipBan is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("{0} banned ip adress : {1}.", currUser.username, ipBan.IPadress); break; case LogType.delete: description = string.Format("{0} Unbanned adress : ' {1} '.", currUser.username, ipBan.IPadress); break; case LogType.undelete: description = string.Format("Ip adress : ' {0} ' was banned AGAIN, this time by {1}.", ipBan.IPadress, currUser.username); break; case LogType.edit: description = string.Format("Ip BAN ID : ' {0} ', field : {1}, was modified by {2}, old value was : ' {3} '" , ipBan.ID, field, currUser.username, oldValue); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for ip bans", type)); } BuildLog(objectContext, type, "IpBan", ipBan.ID, description); } public void LogNotify(Entities objectContext, NotifyOnNewContent notify, LogType type, User currUser) { Tools.AssertObjectContextExists(objectContext); if (notify == null) { throw new BusinessException("notify is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("{0} added to notifies {1} {2}.", currUser.username, notify.type, notify.ID); break; case LogType.delete: if (!notify.UserReference.IsLoaded) { notify.UserReference.Load(); } if (notify.User.ID != currUser.ID) { User notifyUser = Tools.GetUserFromUserDatabase(notify.User); description = string.Format("{0} unsubscribed user {1} ID : {2} on notifies for {3} {4}." , currUser.username, notifyUser.username, notifyUser.ID, notify.type, notify.ID); } else { description = string.Format("{0} unsubscribed for notifies on {1} {2}.", currUser.username, notify.type, notify.ID); } break; case LogType.undelete: description = string.Format("{0} subscribed for notifies AGAIN on {1} {2}.", currUser.username, notify.type, notify.ID); break; case LogType.edit: throw new BusinessException("LogType.edit is not supported on notifies."); } BuildLog(objectContext, type, "notify", notify.ID, description); } /// <summary> /// LogType.Edit when active status has changed with newstatus: declined, accepted, expired /// </summary> public void LogTypeSuggestion(Entities objectContext, EntitiesUsers userContext , TypeSuggestion suggestion, LogType type, User currUser, string newstatus) { Tools.AssertObjectContextExists(objectContext); if (suggestion == null) { throw new BusinessException("suggestion is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; switch (type) { case LogType.create: if (!suggestion.ToUserReference.IsLoaded) { suggestion.ToUserReference.Load(); } BusinessUser bUser = new BusinessUser(); User toUser = bUser.Get(userContext, suggestion.ToUser.ID, true); description = string.Format("{0} sent suggestion for {1} {2} to {3} ID : {4}." , currUser.username, suggestion.type, suggestion.typeID, toUser.username, toUser.ID); break; case LogType.delete: description = string.Format("{0} removed suggestion.", currUser.username); break; case LogType.edit: if (string.IsNullOrEmpty(newstatus)) { throw new BusinessException("newstatus is empty"); } switch (newstatus) { case "declined": description = string.Format("{0} declined suggestion.", currUser.username); break; case "accepted": description = string.Format("{0} accepted suggestion.", currUser.username); break; case "expired": description = string.Format("{0} set suggestion as EXPIRED, because it wasn`t accepted or declined in {1} days." , currUser.username, Configuration.TypeSuggestionDaysAfterWhichSuggestionExpires); break; default: throw new BusinessException(string.Format("newstatus = {0} is not supported status", newstatus)); } break; default: throw new BusinessException(string.Format("LogType = {} is not supported type for typesuggestions", type)); } BuildLog(objectContext, type, "typeSuggestion", suggestion.ID, description); } public void LogRole(Entities objectContext, EntitiesUsers userContext, UserAction uaction, LogType type, User approver) { Tools.AssertObjectContextExists(objectContext); Tools.AssertObjectContextExists(userContext); if (uaction == null) { throw new BusinessException("uaction is null"); } if (approver == null) { approver = Tools.GetSystem(); } if (!uaction.ActionReference.IsLoaded) { uaction.ActionReference.Load(); } if (!uaction.UserReference.IsLoaded) { uaction.UserReference.Load(); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("Role ' {0} ' was given to {1} ID : {2}, by {3}" , uaction.Action.name, uaction.User.username, uaction.User.ID, approver.username); break; case LogType.delete: description = string.Format("Role ' {0} ' was removed from {1} ID : {2}, by {3}" , uaction.Action.name, uaction.User.username, uaction.User.ID, approver.username); break; case LogType.undelete: description = string.Format("Role ' {0} ' was given AGAIN to {1} ID : {2}, by {3}" , uaction.Action.name, uaction.User.username, uaction.User.ID, approver.username); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported type for Roles.", type.ToString())); } BuildLog(objectContext, type, "role", uaction.User.ID, description); BuildUserLog(userContext, type, "role", uaction.User, description); } public void LogUserTypeAction(Entities objectContext, UsersTypeAction action, LogType type, User approver) { Tools.AssertObjectContextExists(objectContext); if (action == null) { throw new BusinessException("action is null"); } if (approver == null) { approver = Tools.GetSystem(); } if (!action.TypeActionReference.IsLoaded) { action.TypeActionReference.Load(); } if (!action.UserReference.IsLoaded) { action.UserReference.Load(); } User actionUser = Tools.GetUserFromUserDatabase(action.User); string description = string.Empty; switch (type) { case LogType.create: if (action.User.ID == approver.ID) { description = string.Format("{0} ID : {1} took type role for ' {2} ' (took the role from another user or the type didn`t had any editors)" , actionUser.username, actionUser.ID, action.TypeAction.name); } else { description = string.Format("Type role ' {0} ' was given to {1} ID : {2}, by {3}" , action.TypeAction.name, actionUser.username, actionUser.ID, approver.username); } break; case LogType.delete: description = string.Format("Type role ' {0} ' was removed from {1} ID : {2}, by {3}" , action.TypeAction.name, actionUser.username, actionUser.ID, approver.username); break; case LogType.undelete: if (action.User.ID == approver.ID) { description = string.Format("{0} ID : {1} took type role for ' {2} ' ( RECEIVED AGAIN ) (took the role from another user or the type didn`t had any editors)" , actionUser.username, actionUser.ID, action.TypeAction.name); } else { description = string.Format("Type role ' {0} ' was given AGAIN to {1} ID : {2}, by {3}" , action.TypeAction.name, actionUser.username, actionUser.ID, approver.username); } break; default: throw new BusinessException(string.Format("LogType = {0} is not supported type for Type roles.", type.ToString())); } BuildLog(objectContext, type, "role", action.User.ID, description); } /// <summary> /// removeType : accept , decline, removing /// </summary> public void LogActionTransfer(Entities objectContext, EntitiesUsers userContext, TransferTypeAction transfer, LogType type, User user, string removeType) { Tools.AssertObjectContextExists(objectContext); Tools.AssertObjectContextExists(userContext); if (transfer == null) { throw new BusinessException("transfer is null"); } BusinessUser bUser = new BusinessUser(); if (user == null) { user = bUser.GetSystem(userContext); } if (!transfer.UserTypeActionReference.IsLoaded) { transfer.UserTypeActionReference.Load(); } if (!transfer.UserTypeAction.TypeActionReference.IsLoaded) { transfer.UserTypeAction.TypeActionReference.Load(); } if (!transfer.UserTransferingReference.IsLoaded) { transfer.UserTransferingReference.Load(); } if (!transfer.UserReceivingReference.IsLoaded) { transfer.UserReceivingReference.Load(); } User transferor = bUser.GetWithoutVisible(userContext, transfer.UserTransfering.ID, true); User receiver = bUser.GetWithoutVisible(userContext, transfer.UserReceiving.ID, true); string descrForTransferingUser = string.Empty; string descrForReceivingUser = string.Empty; string actionType = transfer.UserTypeAction.TypeAction.type; long typeID = transfer.UserTypeAction.TypeAction.typeID; switch (type) { case LogType.create: descrForTransferingUser = string.Format("{0} started transfering role for {1} {2} to {3} ID : {4}. Transfer ID : {5}." , transferor.username, actionType, typeID, receiver.username, receiver.ID, transfer.ID); descrForReceivingUser = string.Format("{0} ID : {1} started transfering role for {2} {3} to {4}. Transfer ID : {5}." , transferor.username, transferor.ID, actionType, typeID, receiver.username, transfer.ID); break; case LogType.delete: switch (removeType) { case "accept": descrForReceivingUser = string.Format("{0} accepted transfer on role for {1} {2} by {3} ID : {4}. Transfer ID : {5}." , receiver.username, actionType, typeID, transferor.username, transferor.ID, transfer.ID); descrForTransferingUser = string.Format("{0} ID : {1} accepted transfer on role for {2} {3} by {4}. Transfer ID : {5}." , receiver.username, receiver.ID, actionType, typeID, transferor.username, transfer.ID); break; case "decline": if (transferor == user) { descrForReceivingUser = string.Format("{0} ID : {1} declined his transfer on role for {2} {3} to {4}. Transfer ID : {5}." , user.username, user.ID, actionType, typeID, receiver.username, transfer.ID); descrForTransferingUser = string.Format("{0} declined his transfer on role for {1} {2} to {3} ID : {4}. Transfer ID : {5}." , user.username, actionType, typeID, receiver.username, receiver.ID, transfer.ID); } else if (receiver == user) { descrForReceivingUser = string.Format("{0} declined transfer on role for {1} {2} by {3} ID : {4}. Transfer ID : {5}." , user.username, actionType, typeID, transferor.username, transferor.ID, transfer.ID); descrForTransferingUser = string.Format("{0} ID : {1} declined transfer on role for {2} {3} by {4}. Transfer ID : {5}." , user.username, user.ID, actionType, typeID, transferor.username, transfer.ID); } else { throw new BusinessException(string.Format ("User id : {0} shouldn`t be able to decline transfer ID : {0}, because he isn`t either the user transfering or receiving." , user.ID, transfer.ID)); } break; case "removing": descrForReceivingUser = string.Format("{0} removed transfer on role for {1} {2} by {3} ID : {4}. Transfer ID : {5}." , user.username, actionType, typeID, transferor.username, transferor.ID, transfer.ID); descrForTransferingUser = string.Format("{0} removed transfer on role for {1} {2} by {3}. Transfer ID : {4}." , user.username, actionType, typeID, transferor.username, transfer.ID); break; default: throw new BusinessException(string.Format("removeType = {0} is not supported type for Action transfer roles.", removeType)); } break; default: throw new BusinessException(string.Format("LogType = {0} is not supported type for Action transfer roles.", type.ToString())); } BuildLog(objectContext, type, "roleTransfer", transferor.ID, descrForTransferingUser); BuildLog(objectContext, type, "roleTransfer", receiver.ID, descrForReceivingUser); } public void LogGetActionFromUser(Entities objectContext, TypeAction action, User userTaking, User userWhichHadAction) { Tools.AssertObjectContextExists(objectContext); if (action == null) { throw new BusinessException("action is null"); } if (userTaking == null) { throw new BusinessException("userTaking is null"); } if (userWhichHadAction == null) { throw new BusinessException("userWhichHadAction is null"); } string descrForUserTaking = string.Empty; string descrForUserWhichHadAction = string.Empty; descrForUserTaking = string.Format("{0} took action for {1} {2} from ' {3} ' ID : {4}.", userTaking.username , action.type, action.typeID, userWhichHadAction.username, userWhichHadAction.ID); descrForUserWhichHadAction = string.Format("' {0} ' ID : {1} took action for {2} {3} from {4}.", userTaking.username , userTaking.ID, action.type, action.typeID, userWhichHadAction.username); BuildLog(objectContext, LogType.create, "roleTaking", userTaking.ID, descrForUserTaking); BuildLog(objectContext, LogType.delete, "roleTaking", userWhichHadAction.ID, descrForUserWhichHadAction); } public void LogCompanyCategory(Entities objectContext, CategoryCompany category, LogType type, User currUser) { Tools.AssertObjectContextExists(objectContext); if (category == null) { throw new BusinessException("category is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } if (!category.CategoryReference.IsLoaded) { category.CategoryReference.Load(); } if (!category.CompanyReference.IsLoaded) { category.CompanyReference.Load(); } string description = string.Empty; switch (type) { case LogType.create: description = string.Format("Category ' {0} ' ID : {1}, was added to Company ' {2} ' ID : {3}, by {2}." , category.Category.name, category.Category.ID, category.Company.name, category.Company.ID, currUser.username); break; case LogType.delete: description = string.Format("Category ' {0} ' ID : {1}, for Company ' {2} ' ID : {3}, was deleted by {2}." , category.Category.name, category.Category.ID, category.Company.name, category.Company.ID, currUser.username); break; case LogType.undelete: description = string.Format("Category ' {0} ' ID : {1}, for Company ' {2} ' ID : {3}, was Un deleted by {2}." , category.Category.name, category.Category.ID, category.Company.name, category.Company.ID, currUser.username); break; case LogType.edit: throw new BusinessException("LogType.edit is not supported for CategoryCompany"); } BuildLog(objectContext, type, "categoryCompany", category.ID, description); } /// <summary> /// Returns logs type=create for products /// </summary> public IEnumerable<Log> getAddedProducts(Entities objectContext) { Tools.AssertObjectContextExists(objectContext); IEnumerable<Log> getProducts = objectContext.LogSet.Where(log => log.type == "create" && log.typeModifiedSubject == "product"). OrderByDescending<Log, long> (new Func<Log, long>(IdSelectorLog)); return getProducts; } /// <summary> /// Returns logs type=setDeleted for products /// </summary> public IEnumerable<Log> getDeletedProducts(Entities objectContext) { Tools.AssertObjectContextExists(objectContext); IEnumerable<Log> getProducts = objectContext.LogSet.Where(log => log.type == "setDeleted" && log.typeModifiedSubject == "product"). OrderByDescending<Log, long> (new Func<Log, long>(IdSelectorLog)); return getProducts; } public Log getDeletedProduct(Entities objectContext, long id) { Tools.AssertObjectContextExists(objectContext); if (id < 1) { throw new BusinessException("id is < 1"); } Log getProduct = objectContext.LogSet.FirstOrDefault (log => log.type == "setDeleted" && log.typeModifiedSubject == "product" && log.IDModifiedSubject == id); return getProduct; } public IEnumerable<Log> getUnDeletedProducts(Entities objectContext) { Tools.AssertObjectContextExists(objectContext); IEnumerable<Log> getProducts = objectContext.LogSet.Where(log => log.type == "unSetDeleted" && log.typeModifiedSubject == "product"). OrderByDescending<Log, long> (new Func<Log, long>(IdSelectorLog)); return getProducts; } public IEnumerable<Log> getProductEditLogs(Entities objectContext, long prodID) { Tools.AssertObjectContextExists(objectContext); if (prodID < 1) { throw new BusinessException("prodID is < 1"); } IEnumerable<Log> getProduct = objectContext.LogSet.Where(log => log.typeModifiedSubject == "product" && log.IDModifiedSubject == prodID). OrderByDescending<Log, long>(new Func<Log, long>(IdSelectorLog)); return getProduct; } public IEnumerable<Log> getProductCharacteristicEditLogs(Entities objectContext, long typeID) { Tools.AssertObjectContextExists(objectContext); if (typeID < 1) { throw new BusinessException("typeID is < 1"); } IEnumerable<Log> getProductCharacteristics = objectContext.LogSet.Where (log => log.typeModifiedSubject == "productCharacteristic" && log.IDModifiedSubject == typeID). OrderByDescending<Log, long>(new Func<Log, long>(IdSelectorLog)); return getProductCharacteristics; } public IEnumerable<Log> getAddedCategories(Entities objectContext) { Tools.AssertObjectContextExists(objectContext); IEnumerable<Log> getCategories = objectContext.LogSet.Where(log => log.type == "create" && log.typeModifiedSubject == "categoty"). OrderByDescending<Log, long> (new Func<Log, long>(IdSelectorLog)); return getCategories; } public IEnumerable<Log> getDeletedCategories(Entities objectContext) { Tools.AssertObjectContextExists(objectContext); IEnumerable<Log> getCategories = objectContext.LogSet.Where(log => log.type == "setDeleted" && log.typeModifiedSubject == "category"). OrderByDescending<Log, long> (new Func<Log, long>(IdSelectorLog)); return getCategories; } public Log getDeletedCategory(Entities objectContext, long catID) { Tools.AssertObjectContextExists(objectContext); if (catID < 1) { throw new BusinessException("catID is < 1"); } Log category = objectContext.LogSet. OrderByDescending<Log, long>(new Func<Log, long>(IdSelectorLog)). FirstOrDefault(log => log.type == "setDeleted" && log.typeModifiedSubject == "category" && log.IDModifiedSubject == catID); return category; } public IEnumerable<Log> getUnDeletedCategories(Entities objectContext) { Tools.AssertObjectContextExists(objectContext); IEnumerable<Log> getCategories = objectContext.LogSet.Where(log => log.type == "unSetDeleted" && log.typeModifiedSubject == "category"). OrderByDescending<Log, long> (new Func<Log, long>(IdSelectorLog)); return getCategories; } public IEnumerable<Log> getCategoryEditLogs(Entities objectContext, long typeID) { Tools.AssertObjectContextExists(objectContext); if (typeID < 1) { throw new BusinessException("typeID is < 1"); } IEnumerable<Log> getLogs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "category" && log.IDModifiedSubject == typeID). OrderByDescending<Log, long> (new Func<Log, long>(IdSelectorLog)); return getLogs; } public IEnumerable<Log> getAddedCompanies(Entities objectContext) { Tools.AssertObjectContextExists(objectContext); IEnumerable<Log> getCompanies = objectContext.LogSet.Where(log => log.type == "create" && log.typeModifiedSubject == "company"). OrderByDescending<Log, long> (new Func<Log, long>(IdSelectorLog)); return getCompanies; } public IEnumerable<Log> getDeletedCompanies(Entities objectContext) { Tools.AssertObjectContextExists(objectContext); IEnumerable<Log> getCompanies = objectContext.LogSet.Where(log => log.type == "setDeleted" && log.typeModifiedSubject == "company"). OrderByDescending<Log, long> (new Func<Log, long>(IdSelectorLog)); return getCompanies; } public Log getDeletedCompany(Entities objectContext, long id) { Tools.AssertObjectContextExists(objectContext); if (id < 1) { throw new BusinessException("id is < 1"); } Log getCompanies = objectContext.LogSet.FirstOrDefault (log => log.type == "setDeleted" && log.typeModifiedSubject == "company" && log.IDModifiedSubject == id); return getCompanies; } public Log getDeletedCompanyCharacteristic(Entities objectContext, long id) { Tools.AssertObjectContextExists(objectContext); if (id < 1) { throw new BusinessException("id is < 1"); } Log getCompanies = objectContext.LogSet.FirstOrDefault (log => log.type == "setDeleted" && log.typeModifiedSubject == "companyCharacteristic" && log.IDModifiedSubject == id); return getCompanies; } public IEnumerable<Log> getUnDeletedCompanies(Entities objectContext) { Tools.AssertObjectContextExists(objectContext); IEnumerable<Log> getCompanies = objectContext.LogSet.Where(log => log.type == "unSetDeleted" && log.typeModifiedSubject == "company"). OrderByDescending<Log, long> (new Func<Log, long>(IdSelectorLog)); return getCompanies; } public IEnumerable<Log> getCompanyEditLogs(Entities objectContext, long typeID) { Tools.AssertObjectContextExists(objectContext); if (typeID < 1) { throw new BusinessException("id is < 1"); } IEnumerable<Log> getLogs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "company" && log.IDModifiedSubject == typeID). OrderByDescending<Log, long> (new Func<Log, long>(IdSelectorLog)); return getLogs; } public IEnumerable<Log> getCompanyCharacteristicEditLogs(Entities objectContext, long typeID) { Tools.AssertObjectContextExists(objectContext); if (typeID < 1) { throw new BusinessException("id is < 1"); } IEnumerable<Log> getLogs = objectContext.LogSet.Where (log => log.typeModifiedSubject == "companyCharacteristic" && log.IDModifiedSubject == typeID). OrderByDescending<Log, long>(new Func<Log, long>(IdSelectorLog)); return getLogs; } public IEnumerable<Log> getCompanyCategoryEditLogs(Entities objectContext, long typeID) { Tools.AssertObjectContextExists(objectContext); if (typeID < 1) { throw new BusinessException("id is < 1"); } IEnumerable<Log> getLogs = objectContext.LogSet.Where (log => log.typeModifiedSubject == "categoryCompany" && log.IDModifiedSubject == typeID). OrderByDescending<Log, long>(new Func<Log, long>(IdSelectorLog)); return getLogs; } public IEnumerable<Log> getRegisteredUsers(Entities objectContext) { Tools.AssertObjectContextExists(objectContext); IEnumerable<Log> getUsers = objectContext.LogSet.Where(log => log.type == "create" && log.typeModifiedSubject == "user"). OrderByDescending<Log, long> (new Func<Log, long>(IdSelectorLog)); return getUsers; } public IEnumerable<Log> getDeletedUsers(Entities objectContext) { Tools.AssertObjectContextExists(objectContext); IEnumerable<Log> getUsers = objectContext.LogSet.Where(log => log.type == "setDeleted" && log.typeModifiedSubject == "user"). OrderByDescending<Log, long> (new Func<Log, long>(IdSelectorLog)); return getUsers; } public Log getDeletedUser(Entities objectContext, long userID) { Tools.AssertObjectContextExists(objectContext); if (userID < 1) { throw new BusinessException("userID is < 1"); } Log getUser = objectContext.LogSet.FirstOrDefault(logs => logs.type == "setDeleted" && logs.IDModifiedSubject == userID && logs.typeModifiedSubject == "user"); return getUser; } public IEnumerable<Log> getUserChanges(Entities objectContext, long typeID) { Tools.AssertObjectContextExists(objectContext); if (typeID < 1) { throw new BusinessException("typeID is < 1"); } IEnumerable<Log> getUsers = objectContext.LogSet.Where(log => log.IDModifiedSubject == typeID && log.typeModifiedSubject == "user"). OrderByDescending<Log, long> (new Func<Log, long>(IdSelectorLog)); return getUsers; } public IEnumerable<Log> getUserRolesChanges(Entities objectContext, long typeID) { Tools.AssertObjectContextExists(objectContext); if (typeID < 1) { throw new BusinessException("typeID is < 1"); } IEnumerable<Log> getLogs = objectContext.LogSet.Where(log => log.IDModifiedSubject == typeID && log.typeModifiedSubject == "role"). OrderByDescending<Log, long> (new Func<Log, long>(IdSelectorLog)); return getLogs; } /// <summary> /// used for Sorting by Descending , sorts by id /// </summary> private long IdSelectorLog(Log log) { if (log == null) { throw new ArgumentNullException("statistic"); } return log.ID; } public void LogCompanyImage(Entities objectContext, CompanyImage image, LogType type, User currUser) { Tools.AssertObjectContextExists(objectContext); if (image == null) { throw new BusinessException("image is null"); } string description = string.Empty; switch (type) { case LogType.create: if (currUser == null) { throw new BusinessException("currUser is null"); } description = string.Format("Company image id : ' {0} ' was uploaded by {1}.", image.ID, currUser.username); break; case LogType.delete: if (currUser == null) { currUser = Tools.GetSystem(); } description = string.Format("Company image id : ' {0} ' was removed by {1}.", image.ID, currUser.username); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Company images.", type.ToString())); } BuildLog(objectContext, type, "companyImage", image.ID, description); } public void LogProductImage(Entities objectContext, ProductImage image, LogType type, User currUser) { Tools.AssertObjectContextExists(objectContext); if (image == null) { throw new BusinessException("image is null"); } string description = string.Empty; switch (type) { case LogType.create: if (currUser == null) { throw new BusinessException("currUser is null"); } description = string.Format("Product image id : ' {0} ' was uploaded by {1}.", image.ID, currUser.username); break; case LogType.delete: if (currUser == null) { currUser = Tools.GetSystem(); } description = string.Format("Product image id : ' {0} ' was removed by {1}.", image.ID, currUser.username); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Product images.", type.ToString())); } BuildLog(objectContext, type, "productImage", image.ID, description); } public void LogCategoryImage(Entities objectContext, Category category, LogType type, User currUser) { Tools.AssertObjectContextExists(objectContext); if (category == null) { throw new BusinessException("category is null"); } string description = string.Empty; switch (type) { case LogType.create: if (currUser == null) { throw new BusinessException("currUser is null"); } description = string.Format("Category image id : ' {0} ' was uploaded by {1}.", category.ID, currUser.username); break; case LogType.delete: if (currUser == null) { currUser = Tools.GetSystem(); } description = string.Format("Category image id : ' {0} ' was removed by {1}.", category.ID, currUser.username); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Category images.", type.ToString())); } BuildLog(objectContext, type, "category", category.ID, description); } /// <summary> /// Used when systems deletes image (from table) because it doesnt exist /// </summary> public void SystemDeleteProductImageLog(Entities objectContext, ProductImage image) { Tools.AssertObjectContextExists(objectContext); if (image == null) { throw new BusinessException("image is null."); } System.Text.StringBuilder descr = new StringBuilder(); descr.Append("System is deleting ProductImage with ID "); descr.Append(image.ID); if (image.url == "") { descr.Append(" , because url : "); descr.Append(image.url); descr.Append(" hasnt changed for last5 minutes."); } else { descr.Append(" , because file with url : "); descr.Append(image.url); descr.Append(" doesnt exist."); } Log newLog = new Log(); newLog.dateCreated = DateTime.UtcNow; newLog.description = descr.ToString(); newLog.type = "setDeleted"; newLog.typeModifiedSubject = "productImage"; newLog.IDModifiedSubject = image.ID; newLog.UserID = Tools.GetUserID(objectContext, Tools.GetSystem()); newLog.userIPadress = "127.0.0.1"; Add(objectContext, newLog); } /// <summary> /// Used when systems deletes image (from table) because it doesnt exist /// </summary> public void SystemDeleteCompanyImageLog(Entities objectContext, CompanyImage image) { Tools.AssertObjectContextExists(objectContext); if (image == null) { throw new BusinessException("image is null."); } System.Text.StringBuilder descr = new StringBuilder(); descr.Append("System is deleting CompanyImage with ID "); descr.Append(image.ID); if (image.url == "") { descr.Append(" , because url : "); descr.Append(image.url); descr.Append(" hasnt changed for last5 minutes."); } else { descr.Append(" , because file with url : "); descr.Append(image.url); descr.Append(" doesnt exist."); } Log newLog = new Log(); newLog.dateCreated = DateTime.UtcNow; newLog.description = descr.ToString(); newLog.type = "setDeleted"; newLog.typeModifiedSubject = "companyImage"; newLog.IDModifiedSubject = image.ID; newLog.UserID = Tools.GetUserID(objectContext, Tools.GetSystem()); newLog.userIPadress = "127.0.0.1"; Add(objectContext, newLog); } public void LogReport(Entities objectContext, Report report, LogType type, string field, User currUser) { Tools.AssertObjectContextExists(objectContext); if (report == null) { throw new BusinessException("report is null"); } if (currUser == null) { throw new BusinessException("currUser is null"); } string description = string.Empty; switch (type) { case LogType.create: string aboutTypeId = string.Empty; if (report.reportType != "general") { aboutTypeId = string.Format(", ID : {0}", report.aboutTypeId); } description = string.Format("Report type ' {0} ', about type ' {1} '{2}, was written by {3}" , report.reportType, report.aboutType, aboutTypeId, currUser.username); break; case LogType.edit: description = string.Format("Report ID : {0} , field : {1}, was modified by {2}, old value was : false" , report.ID, field, currUser.username); break; default: throw new BusinessException(string.Format("LogType = {0} is not supported for Reports.")); } BuildLog(objectContext, type, "report", report.ID, description); } /// <summary> /// Return logs sorted by params /// </summary> /// <param name="logType">all,create,edit,setDeleted,unSetDeleted</param> public List<Log> GetLogs(Entities objectContext, String logType, String aboutType, long aboutTypeId, int numOfLogs, long fromUserId) { CheckData(objectContext, logType, aboutType, aboutTypeId, numOfLogs, fromUserId); List<Log> Logs = new List<Log>(); Logs = SortByAboutType(objectContext, aboutType, aboutTypeId); Logs = SortByLogType(Logs, logType); Logs = SortByUserId(objectContext, Logs, fromUserId); Logs = SortByNumber(Logs, numOfLogs); return Logs; } private List<Log> SortByUserId(Entities objectContext, List<Log> Logs, long fromUserId) { if (fromUserId < 0) { throw new BusinessException("fromUserId < 0"); } long count = Logs.Count<Log>(); if (count > 0 && fromUserId != 0) { List<Log> SortedList = new List<Log>(); BusinessUser businessUser = new BusinessUser(); User user = businessUser.GetWithoutVisible(fromUserId, false); if (user != null) { UserID userid = Tools.GetUserID(objectContext, user); foreach (Log log in Logs) { if (log.UserID == userid) { SortedList.Add(log); } } return SortedList; } else { return SortedList; } } else { return Logs; } } private List<Log> SortByNumber(List<Log> Logs, int numOfLogs) { if (numOfLogs < 1) { throw new BusinessException("numOfLogs is < 1"); } long count = Logs.Count<Log>(); if (count > 1) { if (numOfLogs >= count) { return Logs; } else { List<Log> SortedList = new List<Log>(); for (int i = 0; i < numOfLogs; i++) { SortedList.Add(Logs[i]); } return SortedList; } } else { return Logs; } } private List<Log> SortByLogType(List<Log> Logs, String logType) { if (string.IsNullOrEmpty(logType)) { throw new BusinessException("logType is null or empty"); } if (Logs.Count<Log>() > 0) { List<Log> SortedList = new List<Log>(); switch (logType) { case ("all"): return Logs; case ("create"): foreach (Log log in Logs) { if (log.type == logType) { SortedList.Add(log); } } break; case ("edit"): foreach (Log log in Logs) { if (log.type == logType) { SortedList.Add(log); } } break; case ("setDeleted"): foreach (Log log in Logs) { if (log.type == logType) { SortedList.Add(log); } } break; case ("unSetDeleted"): foreach (Log log in Logs) { if (log.type == logType) { SortedList.Add(log); } } break; default: string error = string.Format("logType = " + logType + " is not valid type."); throw new BusinessException(error); } return SortedList; } else { return Logs; } } private List<Log> SortByAboutType(Entities objectContext, String aboutType, long aboutTypeId) { Tools.AssertObjectContextExists(objectContext); IEnumerable<Log> logs; switch (aboutType) { case ("all"): logs = objectContext.LogSet.OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("product"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "product" && log.IDModifiedSubject == aboutTypeId). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("prodCharacteristic"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "productCharacteristic" && log.IDModifiedSubject == aboutTypeId). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aProducts"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "product"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aProdCharacteristics"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "productCharacteristic"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aProdImages"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "productImage"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("company"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "company" && log.IDModifiedSubject == aboutTypeId). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("compCharacteristic"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "companyCharacteristic" && log.IDModifiedSubject == aboutTypeId). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("compCategory"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "categoryCompany" && log.IDModifiedSubject == aboutTypeId). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aCompanies"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "company"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aCompCharacteristics"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "companyCharacteristic"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aCompCategories"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "categoryCompany"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aCompImages"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "companyImage"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("category"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "category" && log.IDModifiedSubject == aboutTypeId). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aCategories"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "category"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aProductTopics"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "productTopic"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("productTopic"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "productTopic" && log.IDModifiedSubject == aboutTypeId). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("user"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "user" && log.IDModifiedSubject == aboutTypeId). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aUsers"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "user"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aUsrRoles"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "role"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aUsrTransfers"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "roleTransfer"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("userTransfers"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "roleTransfer" && log.IDModifiedSubject == aboutTypeId). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aRoleTakings"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "roleTaking"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("roleTakings"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "roleTaking" && log.IDModifiedSubject == aboutTypeId). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("report"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "report" && log.IDModifiedSubject == aboutTypeId). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("notify"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "notify" && log.IDModifiedSubject == aboutTypeId). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aReports"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "report"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aNotifies"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "notify"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("siteText"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "siteText" && log.IDModifiedSubject == aboutTypeId); break; case ("aSiteTexts"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "siteText"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("suggestion"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "suggestion" && log.IDModifiedSubject == aboutTypeId); break; case ("aSuggestions"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "suggestion"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("advertisement"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "advertisement" && log.IDModifiedSubject == aboutTypeId); break; case ("aAdvertisements"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "advertisement"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("usersRoles"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "role" && log.IDModifiedSubject == aboutTypeId). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aComments"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "comment"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aCompTypes"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "companyType"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aRateComments"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "rateComment"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("aRateProducts"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "rateProduct"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("companyType"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "companyType" && log.IDModifiedSubject == aboutTypeId); break; case ("ipBan"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "IpBan" && log.IDModifiedSubject == aboutTypeId); break; case ("aIpBans"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "IpBan"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("productVariant"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "productVariant" && log.IDModifiedSubject == aboutTypeId); break; case ("aProductVariants"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "productVariant"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("productSubVariant"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "productSubVariant" && log.IDModifiedSubject == aboutTypeId); break; case ("aProductSubVariants"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "productSubVariant"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("typeSuggestion"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "typeSuggestion" && log.IDModifiedSubject == aboutTypeId); break; case ("aTypeSuggestions"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "typeSuggestion"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("altCompanyName"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "alternativeCompanyName" && log.IDModifiedSubject == aboutTypeId); break; case ("compsAlternativeNames"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "alternativeCompanyName"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("altProductyName"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "alternativeProductName" && log.IDModifiedSubject == aboutTypeId); break; case ("prodsAlternativeNames"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "alternativeProductName"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; case ("productLink"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "productLink" && log.IDModifiedSubject == aboutTypeId); break; case ("aProductLinks"): logs = objectContext.LogSet.Where(log => log.typeModifiedSubject == "productLink"). OrderByDescending<Log, long>(new Func<Log, long>(IdSelector)); break; // add new types here default: string error = string.Format("aboutType = {0} is not valid type", aboutType); throw new BusinessException(error); } List<Log> SortedLogs = new List<Log>(); foreach (Log log in logs) { SortedLogs.Add(log); } return SortedLogs; } private void CheckData(Entities objectContext, String logType, String aboutType, long aboutTypeId, int numOfLogs, long fromUserId) { Tools.AssertObjectContextExists(objectContext); if (string.IsNullOrEmpty(logType)) { throw new BusinessException("logType is null or empty"); } if (string.IsNullOrEmpty(aboutType)) { throw new BusinessException("aboutType is null or empty"); } if (aboutTypeId < 1) { throw new BusinessException("aboutTypeId is < 1"); } if (numOfLogs < 1) { throw new BusinessException("numOfLogs is < 1"); } if (fromUserId < 0) { throw new BusinessException("fromUserId < 0"); } } private long IdSelector(Log log) { if (log == null) { throw new ArgumentNullException("log"); } return log.ID; } public List<Log> GetLogsWithIpAdress(Entities objectContext, string IpAdress, long number) { Tools.AssertObjectContextExists(objectContext); if (string.IsNullOrEmpty(IpAdress)) { throw new BusinessException("IpAdress is empty"); } List<Log> logs = objectContext.GetLogsWithIP(IpAdress, number).ToList(); return logs; } private static string GetLogTypeAsString(LogType type) { string str = string.Empty; switch (type) { case LogType.create: str = "create"; break; case LogType.delete: str = "setDeleted"; break; case LogType.edit: str = "edit"; break; case LogType.undelete: str = "unSetDeleted"; break; default: throw new BusinessException(string.Format("type = {0} is not supported type.", type.ToString())); } return str; } } }
42.472514
181
0.512586
[ "Apache-2.0" ]
raste/WiAdvice
Source/BusinessLayer/BusinessLog.cs
105,079
C#
using System; namespace Stencil.Native { public static partial class NativeAssumptions { public static string DEFAULT_ASSEMBLY_NAMESPACE = "Stencil.Native.Droid"; } }
17.272727
81
0.715789
[ "MIT" ]
DanMasterson1/stencil
Source/Stencil.Native/Stencil.Native.Droid/Core/NativeAssumptions.cs
192
C#
// Copyright (c) Duende Software. All rights reserved. // See LICENSE in the project root for license information. namespace IdentityServer.API.UI { public class ConsentOptions { public static bool EnableOfflineAccess = true; public static string OfflineAccessDisplayName = "Offline Access"; public static string OfflineAccessDescription = "Access to your applications and resources, even when you are offline"; public static readonly string MustChooseOneErrorMessage = "You must pick at least one permission"; public static readonly string InvalidSelectionErrorMessage = "Invalid selection"; } }
38.352941
127
0.745399
[ "MIT" ]
BuiTanLan/trouble-training
Src/IdentityServer/API/Controlers/Consent/ConsentOptions.cs
652
C#
using System.Text.Json.Serialization; using BeeSharp.ApiComponents.ApiModels.JsonConverter.Annotations; using BeeSharp.HiveEngine.ApiComponents.ApiModels.JsonConverter.Annotations; namespace BeeSharp.HiveEngine.ApiComponents.ApiModels.BroadcastOps.CustomJson.HiveEngine.Contracts.Tokens { [HiveEngineContract("tokens", "transferOwnership")] public class HiveEngineTokensTransferOwnershipModel : HiveEngineOperation { [JsonPropertyName("symbol")] public string Symbol { get; } [JsonPropertyName("to")] public string To { get; } public HiveEngineTokensTransferOwnershipModel(string symbol, string to) { Symbol = symbol; To = to; } } }
37.631579
105
0.731469
[ "Apache-2.0" ]
NorisBlockchainSolutions/BeeSharp.HiveEngine
BeeSharp.HiveEngine/ApiComponents/ApiModels/BroadcastOps/CustomJson/HiveEngine/Contracts/Tokens/HiveEngineTokensTransferOwnershipModel.cs
717
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Gama.Cooperacion.Wpf.Views { /// <summary> /// Interaction logic for StatusBarView.xaml /// </summary> public partial class StatusBarView : UserControl { public StatusBarView() { InitializeComponent(); } } }
22.827586
52
0.722054
[ "MIT" ]
PFC-acl-amg/GamaPFC
GamaPFC/Gama.Cooperacion.Wpf/Views/StatusBarView.xaml.cs
664
C#
using SimpleMigrations; namespace Athena.Data.Migrations { [Migration(20180329115355, "RefactorOfferings")] public class RefactorOfferings : ScriptMigration { public RefactorOfferings() : base("20180329115355_RefactorOfferings.sql") { } } }
24.333333
82
0.667808
[ "MIT" ]
athena-scheduler/athena
src/Athena.Data/Migrations/20180329115355_RefactorOfferings.cs
292
C#
using Omnius.Core.RocketPack.DefinitionCompiler.Models; using Omnius.Core.RocketPack.DefinitionCompiler.Parsers.Extensions; using Sprache; namespace Omnius.Core.RocketPack.DefinitionCompiler.Parsers; internal static class DefinitionParser { private static readonly NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger(); // 「"」で囲まれた文字列を抽出するパーサー private static readonly Parser<string> _stringLiteralParser = from leading in Parse.WhiteSpace.XMany() from openQuote in Parse.Char('\"') from fragments in Parse.Char('\\').Then(_ => Parse.AnyChar.Select(c => $"\\{c}")).Or(Parse.CharExcept("\\\"").XMany().Text()).XMany() from closeQuote in Parse.Char('\"') from trailing in Parse.WhiteSpace.XMany() select string.Join(string.Empty, fragments).Replace("\\\"", "\""); // 英数字と'_'の文字列を抽出するパーサー private static readonly Parser<string> _nameParser = from name in Parse.Char(x => (x >= '0' && x <= '9') || (x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z') || x == '_', "Name").AtLeastOnce().Text() select name; // example: syntax v1.0; private static readonly Parser<string> _syntaxParser = from keyword in Parse.String("syntax").TokenWithSkipComment() from type in Parse.String("v1.0").TokenWithSkipComment().Text() from semicolon in Parse.Char(';').TokenWithSkipComment() select type; // example: option csharp_namespace "RocketPack.Messages"; private static readonly Parser<OptionDefinition> _optionParser = from keyword in Parse.String("option").TokenWithSkipComment() from name in _nameParser.TokenWithSkipComment() from value in ExpressionParser.GetParser() from semicolon in Parse.Char(';').TokenWithSkipComment() select new OptionDefinition(name, value.Compile().Invoke()); // example: using "RocketPack.Messages"; private static readonly Parser<UsingDefinition> _usingParser = from keyword in Parse.String("using").TokenWithSkipComment() from value in _stringLiteralParser.TokenWithSkipComment() from semicolon in Parse.Char(';').TokenWithSkipComment() select new UsingDefinition(value); // example: namespace "RocketPack.Messages"; private static readonly Parser<NamespaceDefinition> _namespaceParser = from keyword in Parse.String("namespace").TokenWithSkipComment() from value in _stringLiteralParser.TokenWithSkipComment() from semicolon in Parse.Char(';').TokenWithSkipComment() select new NamespaceDefinition(value); // example: [csharp_recyclable] private static readonly Parser<string> _attributeParser = from beginTag in Parse.Char('[').TokenWithSkipComment() from name in _nameParser.TokenWithSkipComment() from endTag in Parse.Char(']').TokenWithSkipComment() select name; // example: capacity: 1024, private static readonly Parser<(string key, object value)> _parametersElementParser = from key in _nameParser.TokenWithSkipComment() from colon in Parse.Char(':').TokenWithSkipComment() from value in ExpressionParser.GetParser() from comma in Parse.Char(',').Or(Parse.Return(',')).TokenWithSkipComment() select (key, value.Compile().Invoke()); // example: (capacity: 1024, recyclable: true) private static readonly Parser<Dictionary<string, object>> _parametersParser = from beginTag in Parse.Char('(').TokenWithSkipComment() from elements in _parametersElementParser.XMany().TokenWithSkipComment() from endTag in Parse.Char(')').TokenWithSkipComment() select new Dictionary<string, object>(elements.Select(n => new KeyValuePair<string, object>(n.key, n.value))); private static readonly Parser<IntType> _intTypeParser = from isSigned in Parse.Char('u').Then(n => Parse.Return(false)).Or(Parse.Return(true)) from type in Parse.String("int") from size in Parse.Decimal from isOptional in Parse.Char('?').Then(n => Parse.Return(true)).Or(Parse.Return(false)).TokenWithSkipComment() select new IntType(isSigned, int.Parse(size), isOptional); private static readonly Parser<BoolType> _boolTypeParser = from type in Parse.String("bool").TokenWithSkipComment() from isOptional in Parse.Char('?').Then(n => Parse.Return(true)).Or(Parse.Return(false)).TokenWithSkipComment() select new BoolType(isOptional); private static readonly Parser<FloatType> _floatTypeParser = from type in Parse.String("float").TokenWithSkipComment() from size in Parse.Decimal.TokenWithSkipComment() from isOptional in Parse.Char('?').Then(n => Parse.Return(true)).Or(Parse.Return(false)).TokenWithSkipComment() select new FloatType(int.Parse(size), isOptional); private static readonly Parser<StringType> _stringTypeParser = from type in Parse.String("string").TokenWithSkipComment() from isOptional in Parse.Char('?').Then(n => Parse.Return(true)).Or(Parse.Return(false)).TokenWithSkipComment() from parameters in _parametersParser.Or(Parse.Return(new Dictionary<string, object>())).TokenWithSkipComment() select new StringType(isOptional, parameters); private static readonly Parser<TimestampType> _timestampTypeParser = from type in Parse.String("timestamp") from isOptional in Parse.Char('?').Then(n => Parse.Return(true)).Or(Parse.Return(false)).TokenWithSkipComment() select new TimestampType(isOptional); private static readonly Parser<BytesType> _memoryTypeParser = from type in Parse.String("bytes").TokenWithSkipComment() from isOptional in Parse.Char('?').Then(n => Parse.Return(true)).Or(Parse.Return(false)).TokenWithSkipComment() from parameters in _parametersParser.Or(Parse.Return(new Dictionary<string, object>())).TokenWithSkipComment() select new BytesType(isOptional, parameters); private static readonly Parser<CustomType> _customTypeParser = from type in _nameParser.Text() from isOptional in Parse.Char('?').Then(n => Parse.Return(true)).Or(Parse.Return(false)).TokenWithSkipComment() select new CustomType(type, isOptional); private static readonly Parser<VectorType> _vectorTypeParser = from type in Parse.String("vector").TokenWithSkipComment() from beginType in Parse.String("<").TokenWithSkipComment() from elementType in _boolTypeParser .Or<TypeBase>(_intTypeParser) .Or(_floatTypeParser) .Or(_stringTypeParser) .Or(_timestampTypeParser) .Or(_memoryTypeParser) .Or(_customTypeParser).TokenWithSkipComment() from endType in Parse.String(">").TokenWithSkipComment() from isOptional in Parse.Char('?').Then(n => Parse.Return(true)).Or(Parse.Return(false)).TokenWithSkipComment() from parameters in _parametersParser.Or(Parse.Return(new Dictionary<string, object>())).TokenWithSkipComment() select new VectorType(elementType, isOptional, parameters); private static readonly Parser<MapType> _mapTypeParser = from type in Parse.String("map").TokenWithSkipComment() from beginType in Parse.Char('<').TokenWithSkipComment() from keyType in _boolTypeParser .Or<TypeBase>(_intTypeParser) .Or(_floatTypeParser) .Or(_stringTypeParser) .Or(_timestampTypeParser) .Or(_memoryTypeParser) .Or(_customTypeParser).TokenWithSkipComment() from comma in Parse.Char(',').TokenWithSkipComment() from valueType in _boolTypeParser .Or<TypeBase>(_intTypeParser) .Or(_floatTypeParser) .Or(_stringTypeParser) .Or(_timestampTypeParser) .Or(_memoryTypeParser) .Or(_customTypeParser).TokenWithSkipComment() from endType in Parse.Char('>').TokenWithSkipComment() from isOptional in Parse.Char('?').Then(n => Parse.Return(true)).Or(Parse.Return(false)).TokenWithSkipComment() from parameters in _parametersParser.Or(Parse.Return(new Dictionary<string, object>())).TokenWithSkipComment() select new MapType(keyType, valueType, isOptional, parameters); private static readonly Parser<EnumElement> _enumElementParser = from attributes in _attributeParser.XMany().TokenWithSkipComment() from name in _nameParser.TokenWithSkipComment() from equal in Parse.Char('=').TokenWithSkipComment() from id in Parse.Decimal.TokenWithSkipComment() from comma in Parse.Char(',').TokenWithSkipComment() select new EnumElement(attributes.ToList(), name, int.Parse(id)); private static readonly Parser<EnumDefinition> _enumDefinitionParser = (from attributes in _attributeParser.XMany().TokenWithSkipComment() from keyword in Parse.String("enum").TokenWithSkipComment() from name in _nameParser.TokenWithSkipComment() from colon in Parse.Char(':').TokenWithSkipComment() from type in _intTypeParser from beginTag in Parse.Char('{').TokenWithSkipComment() from enumProperties in _enumElementParser.Except(Parse.Char('}')).XMany().TokenWithSkipComment() from endTag in Parse.Char('}').TokenWithSkipComment() select new EnumDefinition(attributes.ToList(), name, type, enumProperties.ToList())).Named("enum"); private static readonly Parser<ObjectElement> _objectElementParser = from attributes in _attributeParser.XMany().TokenWithSkipComment() from name in _nameParser.TokenWithSkipComment() from colon in Parse.Char(':').TokenWithSkipComment() from type in _boolTypeParser .Or<TypeBase>(_intTypeParser) .Or(_floatTypeParser) .Or(_stringTypeParser) .Or(_timestampTypeParser) .Or(_memoryTypeParser) .Or(_vectorTypeParser) .Or(_mapTypeParser) .Or(_customTypeParser).TokenWithSkipComment() from comma in Parse.Char(',').TokenWithSkipComment() select new ObjectElement(attributes.ToList(), name, type); private static readonly Parser<ObjectDefinition> _objectDefinitionParser = from attributes in _attributeParser.XMany().TokenWithSkipComment() from type in Parse.String("struct").TokenWithSkipComment().Return(MessageFormatType.Struct).Or(Parse.String("message").TokenWithSkipComment().Return(MessageFormatType.Message)) from name in _nameParser.TokenWithSkipComment() from beginTag in Parse.Char('{').TokenWithSkipComment() from elements in _objectElementParser.Except(Parse.Char('}')).XMany().TokenWithSkipComment() from endTag in Parse.Char('}').TokenWithSkipComment() select new ObjectDefinition(attributes.ToList(), name, type, elements.ToList()); private static readonly Parser<FuncElement> _funcElementParser = from attributes in _attributeParser.XMany().TokenWithSkipComment() from name in _nameParser.TokenWithSkipComment() from colon in Parse.Char(':').TokenWithSkipComment() from beginParam in Parse.Char('(').TokenWithSkipComment() from inType in _customTypeParser.Or(Parse.Return<CustomType?>(null)) from endParam in Parse.Char(')').TokenWithSkipComment() from arrow in Parse.String("->").TokenWithSkipComment() from beginResult in Parse.Char('(').TokenWithSkipComment() from outType in _customTypeParser.Or(Parse.Return<CustomType?>(null)) from endResult in Parse.Char(')').TokenWithSkipComment() from comma in Parse.Char(',').TokenWithSkipComment() select new FuncElement(attributes.ToList(), name, inType, outType); private static readonly Parser<ServiceDefinition> _serviceDefinitionParser = from attributes in _attributeParser.XMany().TokenWithSkipComment() from keyword in Parse.String("service").TokenWithSkipComment() from name in _nameParser.TokenWithSkipComment() from beginTag in Parse.Char('{').TokenWithSkipComment() from funcElements in _funcElementParser.Except(Parse.Char('}')).XMany().TokenWithSkipComment() from endTag in Parse.Char('}').TokenWithSkipComment() select new ServiceDefinition(attributes.ToList(), name, funcElements.ToList()); private static readonly Parser<RocketPackDefinition> _rocketPackDefinitionParser = from syntax in _syntaxParser.Once().TokenWithSkipComment() from usings in _usingParser.XMany().TokenWithSkipComment() from @namespace in _namespaceParser.Once().TokenWithSkipComment() from options in _optionParser.XMany().TokenWithSkipComment() from contents in _enumDefinitionParser.Or<object>(_objectDefinitionParser).Or(_serviceDefinitionParser).XMany().TokenWithSkipComment().End() select new RocketPackDefinition( usings, @namespace.First(), options, contents.OfType<EnumDefinition>().ToList(), contents.OfType<ObjectDefinition>().ToList(), contents.OfType<ServiceDefinition>().ToList()); private static string LoadDefinition(string path) { using var reader = new StreamReader(path); var text = reader.ReadToEnd(); return text; } private static RocketPackDefinition ParseDefinition(string text) { var result = _rocketPackDefinitionParser.Parse(text); foreach (var item in result.Objects) { item.Namespace = result.Namespace.Value; } foreach (var item in result.Enums) { item.Namespace = result.Namespace.Value; } foreach (var item in result.Services) { item.Namespace = result.Namespace.Value; } return result; } private static void ValidateDefinition(RocketPackDefinition result) { // struct形式のメッセージはOptional型は認めない。 foreach (var objectDefinition in result.Objects.Where(n => n.FormatType == MessageFormatType.Struct)) { if (objectDefinition.Elements.Any(n => n.Type.IsOptional)) throw new Exception(); } } public static RocketPackDefinition Load(string definitionFilePath) { try { // Load var text = LoadDefinition(definitionFilePath); // Parse var result = ParseDefinition(text); // Validate ValidateDefinition(result); return result; } catch (Exception e) { _logger.Error(e, $"Load Error: {definitionFilePath}"); throw; } } }
50.084746
184
0.684602
[ "MIT" ]
OmniusLabs/Omnix
src/Omnius.Core.RocketPack.DefinitionCompiler/Parsers/DefinitionParser.cs
14,879
C#
using System; using System.CodeDom; using System.CodeDom.Compiler; using System.CodeDom.CSharp; using System.IO; using System.Reflection; using System.Text; using Microsoft.CSharp; namespace ConsoleTester { public static class Program { public static void Main() { CodeCompileUnit unit = new CodeCompileUnit { Namespaces = { new CodeNamespace { Name = "MyNamespace.Name", Imports = { new CodeNamespaceImport("System"), new CodeNamespaceImport("System.Collections"), new CodeNamespaceImport("System.Collections.Generic") }, UserData = { ["GenerateImports"] = true }, Types = { new CodeTypeDeclaration { IsPartial = true, IsClass = true, IsEnum = false, IsStruct = false, IsInterface = false, TypeAttributes = TypeAttributes.Public | TypeAttributes.Abstract, Name = "MyClass", CustomAttributes = { new CodeAttributeDeclaration { Name = "MyAttribute" } }, UserData = { ["IsStatic"] = true }, Comments = { new CodeCommentStatement("This is a doc comment on a class.", true) }, Members = { new CodeConstructor { Name = "MyClass", Comments = { new CodeCommentStatement("This is a doc comment on a constructor.", true) }, Attributes = MemberAttributes.Public, BaseConstructorArgs = { new CodePrimitiveExpression(false) }, Parameters = { new CodeParameterDeclarationExpression { Name = "name", Type = new CodeTypeReference(typeof(string)), } }, CustomAttributes = { new CodeAttributeDeclaration { Name = "MyAttribute" } }, }, new CodeMemberMethod { Name = "MyMethod", ReturnType = new CodeTypeReference(typeof(void)), Parameters = { new CodeParameterDeclarationExpression { Name = "name", Type = new CodeTypeReference(typeof(string)), } }, CustomAttributes = { new CodeAttributeDeclaration { Name = "MyAttribute" } }, Comments = { new CodeCommentStatement("This is a doc comment on a method.", true) }, }, new CodeMemberProperty { Name = "Name", Attributes = MemberAttributes.Public, Type = new CodeTypeReference(typeof(string)), HasGet = true, HasSet = false, Comments = { new CodeCommentStatement("This is a doc comment on a property.", true) }, CustomAttributes = { new CodeAttributeDeclaration { Name = "MyAttribute" } }, }, new CodeMemberProperty { Name = "Description", Attributes = MemberAttributes.Public, Type = new CodeTypeReference(typeof(string)), HasGet = true, HasSet = false, Comments = { new CodeCommentStatement("This is a doc comment on a property.", true) } } } } } } } }; StringBuilder builder = new StringBuilder(); using (var writer = new StringWriter(builder)) { CSharpCodeProvider provider = new CSharpCodeProvider(); CSharpCodeGenerator generator = new CSharpCodeGenerator(); generator.MoveUsingsOutsideNamespace = true; generator.MultiLineDocComments = true; CodeGeneratorOptions options = new CodeGeneratorOptions { BracingStyle = "C", BlankLinesBetweenMembers = false, IndentString = " " }; generator.GenerateCodeFromCompileUnit(unit, writer, options); } Console.Write(builder); Console.ReadKey(); } } }
45.852273
117
0.273978
[ "MIT" ]
sped-mobi/System.CodeDom.Extensions
src/ConsoleTester/Program.cs
8,072
C#
using System; using static System.Console; using System.IO; using static System.IO.Directory; using static System.IO.Path; using static System.Environment; namespace WorkingWithFileSystem { class Program { static void Main(string[] args) { // OutputFileSystemInfo(); //WorkWithDirectories(); WorkWithFiles(); } public static void OutputFileSystemInfo() { WriteLine($"Path.PathSeparator: {PathSeparator}"); WriteLine($"Path.DirectorySeparatorChar: {DirectorySeparatorChar}"); WriteLine($"Directory.GetCurrentDirectory(): {GetCurrentDirectory()}"); WriteLine($"Environment.CurrentDirectory: {CurrentDirectory}"); WriteLine($"Environment.SystemDirectory: {SystemDirectory}"); WriteLine($"Path.GetTempPath(): {GetTempPath()}"); WriteLine($"GetFolderPath(SpecialFolder):"); WriteLine($" System: {GetFolderPath(SpecialFolder.System)}"); WriteLine($" ApplicationData: {GetFolderPath(SpecialFolder.ApplicationData)}"); WriteLine($" MyDocuments: {GetFolderPath(SpecialFolder.MyDocuments)}"); WriteLine($" Personal: {GetFolderPath(SpecialFolder.Personal)}"); } public static void WorkWithDirectories() { // define a custom directory path string userFolder = GetFolderPath(SpecialFolder.Personal); var customFolder = new string[] { userFolder, "Code", "Chapter09", "OutputFiles" }; string dir = Combine(customFolder); WriteLine($"Working with: {dir}"); // check if it exists WriteLine($"Does it exist? {Exists(dir)}"); // create a directory WriteLine("Creating it..."); CreateDirectory(dir); WriteLine($"Does it exist? {Exists(dir)}"); Write("Confirm the directory exists, and then press ENTER: "); ReadLine(); // delete a directory WriteLine("Deleting it..."); Delete(dir, recursive: true); WriteLine($"Does it exist? {Exists(dir)}"); } public static void WorkWithFiles() { // define a custom directory path string userFolder = GetFolderPath(SpecialFolder.Personal); var customFolder = new string[] { userFolder, "Code", "Chapter09", "OutputFiles" }; string dir = Combine(customFolder); CreateDirectory(dir); // define file paths string textFile = Combine(dir, "Dummy.txt"); string backupFile = Combine(dir, "Dummy.bak"); WriteLine($"Working with: {textFile}"); // check if a file exists WriteLine($"Does it exist? {File.Exists(textFile)}"); // create a new text file and write a line to it StreamWriter textWriter = File.CreateText(textFile); textWriter.WriteLine("Hello, C#!"); textWriter.Close(); // close file and release resources WriteLine($"Does it exist? {File.Exists(textFile)}"); // copy a file and overwrite if it already exists File.Copy( sourceFileName: textFile, destFileName: backupFile, overwrite: true); WriteLine($"Does {backupFile} exist? {File.Exists(backupFile)}"); Write("Confirm the files exist, and then press ENTER: "); ReadLine(); // delete a file File.Delete(textFile); WriteLine($"Does it exist? {File.Exists(textFile)}"); // read from a text file WriteLine($"Reading contents of {backupFile}:"); StreamReader textReader = File.OpenText(backupFile); WriteLine(textReader.ReadToEnd()); textReader.Close(); } } }
35.565217
106
0.557213
[ "MIT" ]
Narasegowda/CSharp-7.1-and-.NET-Core-2.0-Modern-Cross-Platform-Development-Third-Edition
VS2017/Chapter09/WorkingWithFileSystem/Program.cs
4,092
C#
using System; namespace DevStore.Infra { public class Class1 { } }
9
24
0.617284
[ "MIT" ]
lipegomes/csharp-studies
DevStore/DevStore.Infra/Class1.cs
83
C#
using Chilicki.Cantor.Domain.Entities; using Chilicki.Cantor.Infrastructure.Configurations.EntityConfigurations.Base; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Chilicki.Cantor.Infrastructure.Configurations.EntityConfigurations { public class WalletCurrencyConfiguration : BaseEntityConfiguration<WalletCurrency> { public override void ConfigureEntity(EntityTypeBuilder<WalletCurrency> builder) { builder .HasOne(p => p.Owner) .WithMany(p => p.Currencies) .HasForeignKey("OwnerId") .IsRequired() .OnDelete(DeleteBehavior.Cascade); builder .HasOne(p => p.Currency) .WithMany() .HasForeignKey("CurrencyId") .IsRequired() .OnDelete(DeleteBehavior.Cascade); } } }
34.851852
87
0.632306
[ "MIT" ]
mchilicki/cantor-backend
Chilicki.Cantor/Chilicki.Cantor.Infrastructure/Configurations/EntityConfigurations/WalletCurrencyConfiguration.cs
943
C#
using System.IO; using System; using Aspose.Pdf; using Aspose.Pdf.Facades; namespace Aspose.Pdf.Examples.CSharp.AsposePDFFacades.Forms { public class CopyOuterField { public static void Run() { try { // ExStart:CopyOuterField // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Forms(); // Open document FormEditor formEditor = new FormEditor(); // Open the document and create a FormEditor object formEditor.BindPdf(dataDir + "CopyOuterField.pdf"); // Copy a text field from one document to another one formEditor.CopyOuterField( dataDir + "input.pdf", "textfield", 1); // Close and save the output document formEditor.Save(dataDir + "CopyOuterField_out.pdf"); // ExEnd:CopyOuterField } catch (Exception ex) { Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx."); } } } }
34.815789
230
0.57294
[ "MIT" ]
Swisscard/Aspose.PDF-for-.NET
Examples/CSharp/AsposePdfFacades/Forms/CopyOuterField.cs
1,323
C#
using Riven.Dtos; using System; using System.Collections.Generic; using System.Text; namespace Company.Project.Authorization.Roles.Dtos { public class RoleDto : EntityDto<Guid?> { /// <summary> /// 名称(编码)-不可被修改 /// </summary> public virtual string Name { get; set; } /// <summary> /// 显示名称 /// </summary> public virtual string DisplayName { get; set; } /// <summary> /// 描述 /// </summary> public virtual string Description { get; set; } /// <summary> /// 是否为系统内置 /// </summary> public virtual bool IsStatic { get; set; } } }
20.96875
55
0.529061
[ "Apache-2.0" ]
rivenfx/ProjectQ
src/Company.Project.Application/Authorization/Roles/Dtos/RoleDto.cs
717
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Cvm.V20170312.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class ResetInstancesTypeRequest : AbstractModel { /// <summary> /// 一个或多个待操作的实例ID。可通过[`DescribeInstances`](https://cloud.tencent.com/document/api/213/15728)接口返回值中的`InstanceId`获取。本接口每次请求批量实例的上限为1。 /// </summary> [JsonProperty("InstanceIds")] public string[] InstanceIds{ get; set; } /// <summary> /// 实例机型。不同实例机型指定了不同的资源规格,具体取值可通过调用接口[`DescribeInstanceTypeConfigs`](https://cloud.tencent.com/document/api/213/15749)来获得最新的规格表或参见[实例类型](https://cloud.tencent.com/document/product/213/11518)描述。 /// </summary> [JsonProperty("InstanceType")] public string InstanceType{ get; set; } /// <summary> /// 是否对运行中的实例选择强制关机。建议对运行中的实例先手动关机。取值范围:<br><li>TRUE:表示在正常关机失败后进行强制关机<br><li>FALSE:表示在正常关机失败后不进行强制关机<br><br>默认取值:FALSE。<br><br>强制关机的效果等同于关闭物理计算机的电源开关。强制关机可能会导致数据丢失或文件系统损坏,请仅在服务器不能正常关机时使用。 /// </summary> [JsonProperty("ForceStop")] public bool? ForceStop{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamArraySimple(map, prefix + "InstanceIds.", this.InstanceIds); this.SetParamSimple(map, prefix + "InstanceType", this.InstanceType); this.SetParamSimple(map, prefix + "ForceStop", this.ForceStop); } } }
38.810345
201
0.674367
[ "Apache-2.0" ]
allenlooplee/tencentcloud-sdk-dotnet
TencentCloud/Cvm/V20170312/Models/ResetInstancesTypeRequest.cs
2,711
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201 { using Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell; /// <summary>Class representing the Kusto database properties.</summary> [System.ComponentModel.TypeConverter(typeof(ReadWriteDatabasePropertiesTypeConverter))] public partial class ReadWriteDatabaseProperties { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.ReadWriteDatabaseProperties" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabaseProperties" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabaseProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new ReadWriteDatabaseProperties(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.ReadWriteDatabaseProperties" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabaseProperties" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabaseProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new ReadWriteDatabaseProperties(content); } /// <summary> /// Creates a new instance of <see cref="ReadWriteDatabaseProperties" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabaseProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.ReadWriteDatabaseProperties" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal ReadWriteDatabaseProperties(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("Statistics")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).Statistics = (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IDatabaseStatistics) content.GetValueForProperty("Statistics",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).Statistics, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.DatabaseStatisticsTypeConverter.ConvertFrom); } if (content.Contains("ProvisioningState")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.ProvisioningState.CreateFrom); } if (content.Contains("SoftDeletePeriod")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).SoftDeletePeriod = (global::System.TimeSpan?) content.GetValueForProperty("SoftDeletePeriod",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).SoftDeletePeriod, (v) => v is global::System.TimeSpan _v ? _v : global::System.Xml.XmlConvert.ToTimeSpan( v.ToString() )); } if (content.Contains("HotCachePeriod")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).HotCachePeriod = (global::System.TimeSpan?) content.GetValueForProperty("HotCachePeriod",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).HotCachePeriod, (v) => v is global::System.TimeSpan _v ? _v : global::System.Xml.XmlConvert.ToTimeSpan( v.ToString() )); } if (content.Contains("IsFollowed")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).IsFollowed = (bool?) content.GetValueForProperty("IsFollowed",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).IsFollowed, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); } if (content.Contains("StatisticsSize")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).StatisticsSize = (float?) content.GetValueForProperty("StatisticsSize",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).StatisticsSize, (__y)=> (float) global::System.Convert.ChangeType(__y, typeof(float))); } AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.ReadWriteDatabaseProperties" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal ReadWriteDatabaseProperties(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("Statistics")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).Statistics = (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IDatabaseStatistics) content.GetValueForProperty("Statistics",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).Statistics, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.DatabaseStatisticsTypeConverter.ConvertFrom); } if (content.Contains("ProvisioningState")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.ProvisioningState.CreateFrom); } if (content.Contains("SoftDeletePeriod")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).SoftDeletePeriod = (global::System.TimeSpan?) content.GetValueForProperty("SoftDeletePeriod",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).SoftDeletePeriod, (v) => v is global::System.TimeSpan _v ? _v : global::System.Xml.XmlConvert.ToTimeSpan( v.ToString() )); } if (content.Contains("HotCachePeriod")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).HotCachePeriod = (global::System.TimeSpan?) content.GetValueForProperty("HotCachePeriod",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).HotCachePeriod, (v) => v is global::System.TimeSpan _v ? _v : global::System.Xml.XmlConvert.ToTimeSpan( v.ToString() )); } if (content.Contains("IsFollowed")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).IsFollowed = (bool?) content.GetValueForProperty("IsFollowed",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).IsFollowed, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); } if (content.Contains("StatisticsSize")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).StatisticsSize = (float?) content.GetValueForProperty("StatisticsSize",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IReadWriteDatabasePropertiesInternal)this).StatisticsSize, (__y)=> (float) global::System.Convert.ChangeType(__y, typeof(float))); } AfterDeserializePSObject(content); } /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// Class representing the Kusto database properties. [System.ComponentModel.TypeConverter(typeof(ReadWriteDatabasePropertiesTypeConverter))] public partial interface IReadWriteDatabaseProperties { } }
77.032967
480
0.708916
[ "MIT" ]
AlanFlorance/azure-powershell
src/Kusto/generated/api/Models/Api20220201/ReadWriteDatabaseProperties.PowerShell.cs
13,839
C#
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using MongoDB.Driver; using Shopping.Api.Data; using Shopping.Api.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Shopping.Api.Controllers { [ApiController] [Route("[controller]")] public class ProductController : ControllerBase { private readonly ILogger<ProductController> _logger; private readonly ProductContext _productContext; public ProductController(ILogger<ProductController> logger, ProductContext productContext) { _logger = logger; _productContext = productContext; } [HttpGet] public async Task<IEnumerable<Product>> Get() { IEnumerable<Product> products = null; try { products = await _productContext.products.Find(p => true).ToListAsync(); } catch (Exception ex) { _logger.LogInformation(ex.Message); } return products; } } }
26.906977
98
0.632671
[ "MIT" ]
Ibrahimayman/run-devops
Shopping/Shopping.Api/Controllers/ProductController.cs
1,159
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Torque2dMitToPhaserConverter.AbstractSyntaxTreeClasses { public class OpenCurlyBracket : CodeBlock { public override string ConvertToCode() { return "{"; } } }
19.764706
64
0.690476
[ "MIT" ]
jeffmorettievermoregamestudios/Torque2dMitToPhaserConverter
Torque2dMitToPhaserConverter/Torque2dMitToPhaserConverter/AbstractSyntaxTreeClasses/OpenCurlyBracket.cs
338
C#
using UnityEngine; public class TestScript : ScriptableObject { void OnEnable () { Debug.Log("start"); } public void MetodTest() { Debug.Log("TEST TEST TEST"); } }
12.733333
43
0.612565
[ "MIT" ]
randalfien/scriptable-object-component
TestScript.cs
193
C#
namespace GvasFormat.Serialization.Game.Scenarios.POIs.Modern.Actors { public class ModernPOI_WindFarm_A_01_Small { } }
20
68
0.721429
[ "MIT" ]
SokolovPavel/gvas-converter
GvasFormat/Astroneer/Types/Game/Scenarios/POIs/Modern/Actors/ModernPOI_WindFarm_A-01_Small.cs
140
C#
using System.Linq; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Middleware; using JsonApiDotNetCore.Queries.Expressions; using JsonApiDotNetCore.Queries.Internal.Parsing; using JsonApiDotNetCore.Resources.Annotations; namespace JsonApiDotNetCore.QueryStrings.Internal { public abstract class QueryStringParameterReader { private readonly IResourceContextProvider _resourceContextProvider; private readonly bool _isCollectionRequest; protected ResourceContext RequestResource { get; } protected bool IsAtomicOperationsRequest { get; } protected QueryStringParameterReader(IJsonApiRequest request, IResourceContextProvider resourceContextProvider) { ArgumentGuard.NotNull(request, nameof(request)); ArgumentGuard.NotNull(resourceContextProvider, nameof(resourceContextProvider)); _resourceContextProvider = resourceContextProvider; _isCollectionRequest = request.IsCollection; RequestResource = request.SecondaryResource ?? request.PrimaryResource; IsAtomicOperationsRequest = request.Kind == EndpointKind.AtomicOperations; } protected ResourceContext GetResourceContextForScope(ResourceFieldChainExpression scope) { if (scope == null) { return RequestResource; } var lastField = scope.Fields.Last(); var type = lastField is RelationshipAttribute relationship ? relationship.RightType : lastField.Property.PropertyType; return _resourceContextProvider.GetResourceContext(type); } protected void AssertIsCollectionRequest() { if (!_isCollectionRequest) { throw new QueryParseException("This query string parameter can only be used on a collection of resources (not on a single resource)."); } } } }
38.235294
151
0.704615
[ "MIT" ]
jlits/JsonApiDotNetCore
src/JsonApiDotNetCore/QueryStrings/Internal/QueryStringParameterReader.cs
1,950
C#
using System.Collections.Generic; using UnityEngine; /// <summary> /// A very simples object pooling class /// </summary> public class SimpleObjectPool : MonoBehaviour { /// <summary> /// The prefab that this object pool returns instances of /// </summary> public GameObject prefab; /// <summary> /// Collection of currently inactive instances of the prefab /// </summary> private Stack<GameObject> inactiveInstances; public SimpleObjectPool() { this.inactiveInstances = new Stack<GameObject>(0); } /// <summary> /// Returns an instance of the prefab /// </summary> /// <returns></returns> public GameObject GetObject() { GameObject spwanedGameObject; // if there is an inactive instance of the prefab ready to return, return that if (this.inactiveInstances.Count > 0) { // remove the instance from the collection of inactive instances spwanedGameObject = inactiveInstances.Pop(); } else { spwanedGameObject = GameObject.Instantiate(prefab); // add the PooledObejct component to the prefab so we know it came from this pool var pooledObject = spwanedGameObject.AddComponent<PooledObject>(); pooledObject.pool = this; } // put the instance in the root of the scene and enable it spwanedGameObject.transform.SetParent(null); spwanedGameObject.SetActive(true); // return a reference to the instace return spwanedGameObject; } /// <summary> /// Returns an instance of the prefab to the pool. /// </summary> /// <param name="toReturn">To return.</param> public void ReturnObject(GameObject toReturn) { var pooledObject = toReturn.GetComponent<PooledObject>(); // if instance came from this pool, return it to the pool if (pooledObject != null && pooledObject.pool == this) { // make the instance a child of this and disable it toReturn.transform.SetParent(transform); toReturn.SetActive(false); // add the instance to the collection of inactive instances this.inactiveInstances.Push(toReturn); } else { // otherwise, just destroy it Debug.LogWarning($"{toReturn.name} was returned to a pool it wasn't from! Destroying..."); Destroy(toReturn); } } }
31.2375
102
0.619048
[ "MIT" ]
gafda/Tryouts
Assets/Scripts/MainMenu/SimpleObjectPool.cs
2,501
C#
// ---------------------------------------------------------------------------------------- // COPYRIGHT NOTICE // ---------------------------------------------------------------------------------------- // // The Source Code Store LLC // ACTIVEGANTT SCHEDULER COMPONENT FOR C# - ActiveGanttCSN // Windows Forms Control // Copyright (c) 2002-2017 The Source Code Store LLC // // All Rights Reserved. No parts of this file may be reproduced, modified or transmitted // in any form or by any means without the written permission of the author. // // ---------------------------------------------------------------------------------------- using System; namespace MSP2007 { public class Task : clsItemBase { internal clsCollectionBase mp_oCollection; private int mp_lUID; private int mp_lID; private string mp_sName; private E_TYPE_4 mp_yType; private bool mp_bIsNull; private System.DateTime mp_dtCreateDate; private string mp_sContact; private string mp_sWBS; private string mp_sWBSLevel; private string mp_sOutlineNumber; private int mp_lOutlineLevel; private int mp_lPriority; private System.DateTime mp_dtStart; private System.DateTime mp_dtFinish; private Duration mp_oDuration; private E_DURATIONFORMAT mp_yDurationFormat; private Duration mp_oWork; private System.DateTime mp_dtStop; private System.DateTime mp_dtResume; private bool mp_bResumeValid; private bool mp_bEffortDriven; private bool mp_bRecurring; private bool mp_bOverAllocated; private bool mp_bEstimated; private bool mp_bMilestone; private bool mp_bSummary; private bool mp_bCritical; private bool mp_bIsSubproject; private bool mp_bIsSubprojectReadOnly; private string mp_sSubprojectName; private bool mp_bExternalTask; private string mp_sExternalTaskProject; private System.DateTime mp_dtEarlyStart; private System.DateTime mp_dtEarlyFinish; private System.DateTime mp_dtLateStart; private System.DateTime mp_dtLateFinish; private int mp_lStartVariance; private int mp_lFinishVariance; private float mp_fWorkVariance; private int mp_lFreeSlack; private int mp_lTotalSlack; private float mp_fFixedCost; private E_FIXEDCOSTACCRUAL mp_yFixedCostAccrual; private int mp_lPercentComplete; private int mp_lPercentWorkComplete; private Decimal mp_cCost; private Decimal mp_cOvertimeCost; private Duration mp_oOvertimeWork; private System.DateTime mp_dtActualStart; private System.DateTime mp_dtActualFinish; private Duration mp_oActualDuration; private Decimal mp_cActualCost; private Decimal mp_cActualOvertimeCost; private Duration mp_oActualWork; private Duration mp_oActualOvertimeWork; private Duration mp_oRegularWork; private Duration mp_oRemainingDuration; private Decimal mp_cRemainingCost; private Duration mp_oRemainingWork; private Decimal mp_cRemainingOvertimeCost; private Duration mp_oRemainingOvertimeWork; private float mp_fACWP; private float mp_fCV; private E_CONSTRAINTTYPE mp_yConstraintType; private int mp_lCalendarUID; private System.DateTime mp_dtConstraintDate; private System.DateTime mp_dtDeadline; private bool mp_bLevelAssignments; private bool mp_bLevelingCanSplit; private int mp_lLevelingDelay; private E_LEVELINGDELAYFORMAT mp_yLevelingDelayFormat; private System.DateTime mp_dtPreLeveledStart; private System.DateTime mp_dtPreLeveledFinish; private string mp_sHyperlink; private string mp_sHyperlinkAddress; private string mp_sHyperlinkSubAddress; private bool mp_bIgnoreResourceCalendar; private string mp_sNotes; private bool mp_bHideBar; private bool mp_bRollup; private float mp_fBCWS; private float mp_fBCWP; private int mp_lPhysicalPercentComplete; private E_EARNEDVALUEMETHOD mp_yEarnedValueMethod; private TaskPredecessorLink_C mp_oPredecessorLink_C; private Duration mp_oActualWorkProtected; private Duration mp_oActualOvertimeWorkProtected; private TaskExtendedAttribute_C mp_oExtendedAttribute_C; private TaskBaseline_C mp_oBaseline_C; private TaskOutlineCode_C mp_oOutlineCode_C; private bool mp_bIsPublished; private string mp_sStatusManager; private System.DateTime mp_dtCommitmentStart; private System.DateTime mp_dtCommitmentFinish; private E_COMMITMENTTYPE mp_yCommitmentType; private TimephasedData_C mp_oTimephasedData_C; public Task() { mp_lUID = 0; mp_lID = 0; mp_sName = ""; mp_yType = E_TYPE_4.T_4_FIXED_UNITS; mp_bIsNull = false; mp_dtCreateDate = new System.DateTime(0); mp_sContact = ""; mp_sWBS = ""; mp_sWBSLevel = ""; mp_sOutlineNumber = ""; mp_lOutlineLevel = 0; mp_lPriority = 0; mp_dtStart = new System.DateTime(0); mp_dtFinish = new System.DateTime(0); mp_oDuration = new Duration(); mp_yDurationFormat = E_DURATIONFORMAT.DF_M; mp_oWork = new Duration(); mp_dtStop = new System.DateTime(0); mp_dtResume = new System.DateTime(0); mp_bResumeValid = false; mp_bEffortDriven = false; mp_bRecurring = false; mp_bOverAllocated = false; mp_bEstimated = false; mp_bMilestone = false; mp_bSummary = false; mp_bCritical = false; mp_bIsSubproject = false; mp_bIsSubprojectReadOnly = false; mp_sSubprojectName = ""; mp_bExternalTask = false; mp_sExternalTaskProject = ""; mp_dtEarlyStart = new System.DateTime(0); mp_dtEarlyFinish = new System.DateTime(0); mp_dtLateStart = new System.DateTime(0); mp_dtLateFinish = new System.DateTime(0); mp_lStartVariance = 0; mp_lFinishVariance = 0; mp_fWorkVariance = 0; mp_lFreeSlack = 0; mp_lTotalSlack = 0; mp_fFixedCost = 0; mp_yFixedCostAccrual = E_FIXEDCOSTACCRUAL.FCA_START; mp_lPercentComplete = 0; mp_lPercentWorkComplete = 0; mp_cCost = 0; mp_cOvertimeCost = 0; mp_oOvertimeWork = new Duration(); mp_dtActualStart = new System.DateTime(0); mp_dtActualFinish = new System.DateTime(0); mp_oActualDuration = new Duration(); mp_cActualCost = 0; mp_cActualOvertimeCost = 0; mp_oActualWork = new Duration(); mp_oActualOvertimeWork = new Duration(); mp_oRegularWork = new Duration(); mp_oRemainingDuration = new Duration(); mp_cRemainingCost = 0; mp_oRemainingWork = new Duration(); mp_cRemainingOvertimeCost = 0; mp_oRemainingOvertimeWork = new Duration(); mp_fACWP = 0; mp_fCV = 0; mp_yConstraintType = E_CONSTRAINTTYPE.CT_AS_SOON_AS_POSSIBLE; mp_lCalendarUID = 0; mp_dtConstraintDate = new System.DateTime(0); mp_dtDeadline = new System.DateTime(0); mp_bLevelAssignments = false; mp_bLevelingCanSplit = false; mp_lLevelingDelay = 0; mp_yLevelingDelayFormat = E_LEVELINGDELAYFORMAT.LDF_M; mp_dtPreLeveledStart = new System.DateTime(0); mp_dtPreLeveledFinish = new System.DateTime(0); mp_sHyperlink = ""; mp_sHyperlinkAddress = ""; mp_sHyperlinkSubAddress = ""; mp_bIgnoreResourceCalendar = false; mp_sNotes = ""; mp_bHideBar = false; mp_bRollup = false; mp_fBCWS = 0; mp_fBCWP = 0; mp_lPhysicalPercentComplete = 0; mp_yEarnedValueMethod = E_EARNEDVALUEMETHOD.EVM_PERCENT_COMPLETE; mp_oPredecessorLink_C = new TaskPredecessorLink_C(); mp_oActualWorkProtected = new Duration(); mp_oActualOvertimeWorkProtected = new Duration(); mp_oExtendedAttribute_C = new TaskExtendedAttribute_C(); mp_oBaseline_C = new TaskBaseline_C(); mp_oOutlineCode_C = new TaskOutlineCode_C(); mp_bIsPublished = false; mp_sStatusManager = ""; mp_dtCommitmentStart = new System.DateTime(0); mp_dtCommitmentFinish = new System.DateTime(0); mp_yCommitmentType = E_COMMITMENTTYPE.CT_THE_TASK_HAS_NO_DELIVERABLE_OR_DEPENDENCY_ON_A_DELIVERABLE; mp_oTimephasedData_C = new TimephasedData_C(); } public int lUID { get { return mp_lUID; } set { mp_lUID = value; } } public int lID { get { return mp_lID; } set { mp_lID = value; } } public string sName { get { return mp_sName; } set { if (value.Length > 512) { value = value.Substring(0, 512); } mp_sName = value; } } public E_TYPE_4 yType { get { return mp_yType; } set { mp_yType = value; } } public bool bIsNull { get { return mp_bIsNull; } set { mp_bIsNull = value; } } public System.DateTime dtCreateDate { get { return mp_dtCreateDate; } set { mp_dtCreateDate = value; } } public string sContact { get { return mp_sContact; } set { if (value.Length > 512) { value = value.Substring(0, 512); } mp_sContact = value; } } public string sWBS { get { return mp_sWBS; } set { mp_sWBS = value; } } public string sWBSLevel { get { return mp_sWBSLevel; } set { mp_sWBSLevel = value; } } public string sOutlineNumber { get { return mp_sOutlineNumber; } set { if (value.Length > 512) { value = value.Substring(0, 512); } mp_sOutlineNumber = value; } } public int lOutlineLevel { get { return mp_lOutlineLevel; } set { mp_lOutlineLevel = value; } } public int lPriority { get { return mp_lPriority; } set { mp_lPriority = value; } } public System.DateTime dtStart { get { return mp_dtStart; } set { mp_dtStart = value; } } public System.DateTime dtFinish { get { return mp_dtFinish; } set { mp_dtFinish = value; } } public Duration oDuration { get { return mp_oDuration; } } public E_DURATIONFORMAT yDurationFormat { get { return mp_yDurationFormat; } set { mp_yDurationFormat = value; } } public Duration oWork { get { return mp_oWork; } } public System.DateTime dtStop { get { return mp_dtStop; } set { mp_dtStop = value; } } public System.DateTime dtResume { get { return mp_dtResume; } set { mp_dtResume = value; } } public bool bResumeValid { get { return mp_bResumeValid; } set { mp_bResumeValid = value; } } public bool bEffortDriven { get { return mp_bEffortDriven; } set { mp_bEffortDriven = value; } } public bool bRecurring { get { return mp_bRecurring; } set { mp_bRecurring = value; } } public bool bOverAllocated { get { return mp_bOverAllocated; } set { mp_bOverAllocated = value; } } public bool bEstimated { get { return mp_bEstimated; } set { mp_bEstimated = value; } } public bool bMilestone { get { return mp_bMilestone; } set { mp_bMilestone = value; } } public bool bSummary { get { return mp_bSummary; } set { mp_bSummary = value; } } public bool bCritical { get { return mp_bCritical; } set { mp_bCritical = value; } } public bool bIsSubproject { get { return mp_bIsSubproject; } set { mp_bIsSubproject = value; } } public bool bIsSubprojectReadOnly { get { return mp_bIsSubprojectReadOnly; } set { mp_bIsSubprojectReadOnly = value; } } public string sSubprojectName { get { return mp_sSubprojectName; } set { if (value.Length > 512) { value = value.Substring(0, 512); } mp_sSubprojectName = value; } } public bool bExternalTask { get { return mp_bExternalTask; } set { mp_bExternalTask = value; } } public string sExternalTaskProject { get { return mp_sExternalTaskProject; } set { if (value.Length > 512) { value = value.Substring(0, 512); } mp_sExternalTaskProject = value; } } public System.DateTime dtEarlyStart { get { return mp_dtEarlyStart; } set { mp_dtEarlyStart = value; } } public System.DateTime dtEarlyFinish { get { return mp_dtEarlyFinish; } set { mp_dtEarlyFinish = value; } } public System.DateTime dtLateStart { get { return mp_dtLateStart; } set { mp_dtLateStart = value; } } public System.DateTime dtLateFinish { get { return mp_dtLateFinish; } set { mp_dtLateFinish = value; } } public int lStartVariance { get { return mp_lStartVariance; } set { mp_lStartVariance = value; } } public int lFinishVariance { get { return mp_lFinishVariance; } set { mp_lFinishVariance = value; } } public float fWorkVariance { get { return mp_fWorkVariance; } set { mp_fWorkVariance = value; } } public int lFreeSlack { get { return mp_lFreeSlack; } set { mp_lFreeSlack = value; } } public int lTotalSlack { get { return mp_lTotalSlack; } set { mp_lTotalSlack = value; } } public float fFixedCost { get { return mp_fFixedCost; } set { mp_fFixedCost = value; } } public E_FIXEDCOSTACCRUAL yFixedCostAccrual { get { return mp_yFixedCostAccrual; } set { mp_yFixedCostAccrual = value; } } public int lPercentComplete { get { return mp_lPercentComplete; } set { mp_lPercentComplete = value; } } public int lPercentWorkComplete { get { return mp_lPercentWorkComplete; } set { mp_lPercentWorkComplete = value; } } public Decimal cCost { get { return mp_cCost; } set { mp_cCost = value; } } public Decimal cOvertimeCost { get { return mp_cOvertimeCost; } set { mp_cOvertimeCost = value; } } public Duration oOvertimeWork { get { return mp_oOvertimeWork; } } public System.DateTime dtActualStart { get { return mp_dtActualStart; } set { mp_dtActualStart = value; } } public System.DateTime dtActualFinish { get { return mp_dtActualFinish; } set { mp_dtActualFinish = value; } } public Duration oActualDuration { get { return mp_oActualDuration; } } public Decimal cActualCost { get { return mp_cActualCost; } set { mp_cActualCost = value; } } public Decimal cActualOvertimeCost { get { return mp_cActualOvertimeCost; } set { mp_cActualOvertimeCost = value; } } public Duration oActualWork { get { return mp_oActualWork; } } public Duration oActualOvertimeWork { get { return mp_oActualOvertimeWork; } } public Duration oRegularWork { get { return mp_oRegularWork; } } public Duration oRemainingDuration { get { return mp_oRemainingDuration; } } public Decimal cRemainingCost { get { return mp_cRemainingCost; } set { mp_cRemainingCost = value; } } public Duration oRemainingWork { get { return mp_oRemainingWork; } } public Decimal cRemainingOvertimeCost { get { return mp_cRemainingOvertimeCost; } set { mp_cRemainingOvertimeCost = value; } } public Duration oRemainingOvertimeWork { get { return mp_oRemainingOvertimeWork; } } public float fACWP { get { return mp_fACWP; } set { mp_fACWP = value; } } public float fCV { get { return mp_fCV; } set { mp_fCV = value; } } public E_CONSTRAINTTYPE yConstraintType { get { return mp_yConstraintType; } set { mp_yConstraintType = value; } } public int lCalendarUID { get { return mp_lCalendarUID; } set { mp_lCalendarUID = value; } } public System.DateTime dtConstraintDate { get { return mp_dtConstraintDate; } set { mp_dtConstraintDate = value; } } public System.DateTime dtDeadline { get { return mp_dtDeadline; } set { mp_dtDeadline = value; } } public bool bLevelAssignments { get { return mp_bLevelAssignments; } set { mp_bLevelAssignments = value; } } public bool bLevelingCanSplit { get { return mp_bLevelingCanSplit; } set { mp_bLevelingCanSplit = value; } } public int lLevelingDelay { get { return mp_lLevelingDelay; } set { mp_lLevelingDelay = value; } } public E_LEVELINGDELAYFORMAT yLevelingDelayFormat { get { return mp_yLevelingDelayFormat; } set { mp_yLevelingDelayFormat = value; } } public System.DateTime dtPreLeveledStart { get { return mp_dtPreLeveledStart; } set { mp_dtPreLeveledStart = value; } } public System.DateTime dtPreLeveledFinish { get { return mp_dtPreLeveledFinish; } set { mp_dtPreLeveledFinish = value; } } public string sHyperlink { get { return mp_sHyperlink; } set { if (value.Length > 512) { value = value.Substring(0, 512); } mp_sHyperlink = value; } } public string sHyperlinkAddress { get { return mp_sHyperlinkAddress; } set { if (value.Length > 512) { value = value.Substring(0, 512); } mp_sHyperlinkAddress = value; } } public string sHyperlinkSubAddress { get { return mp_sHyperlinkSubAddress; } set { if (value.Length > 512) { value = value.Substring(0, 512); } mp_sHyperlinkSubAddress = value; } } public bool bIgnoreResourceCalendar { get { return mp_bIgnoreResourceCalendar; } set { mp_bIgnoreResourceCalendar = value; } } public string sNotes { get { return mp_sNotes; } set { mp_sNotes = value; } } public bool bHideBar { get { return mp_bHideBar; } set { mp_bHideBar = value; } } public bool bRollup { get { return mp_bRollup; } set { mp_bRollup = value; } } public float fBCWS { get { return mp_fBCWS; } set { mp_fBCWS = value; } } public float fBCWP { get { return mp_fBCWP; } set { mp_fBCWP = value; } } public int lPhysicalPercentComplete { get { return mp_lPhysicalPercentComplete; } set { mp_lPhysicalPercentComplete = value; } } public E_EARNEDVALUEMETHOD yEarnedValueMethod { get { return mp_yEarnedValueMethod; } set { mp_yEarnedValueMethod = value; } } public TaskPredecessorLink_C oPredecessorLink_C { get { return mp_oPredecessorLink_C; } } public Duration oActualWorkProtected { get { return mp_oActualWorkProtected; } } public Duration oActualOvertimeWorkProtected { get { return mp_oActualOvertimeWorkProtected; } } public TaskExtendedAttribute_C oExtendedAttribute_C { get { return mp_oExtendedAttribute_C; } } public TaskBaseline_C oBaseline_C { get { return mp_oBaseline_C; } } public TaskOutlineCode_C oOutlineCode_C { get { return mp_oOutlineCode_C; } } public bool bIsPublished { get { return mp_bIsPublished; } set { mp_bIsPublished = value; } } public string sStatusManager { get { return mp_sStatusManager; } set { mp_sStatusManager = value; } } public System.DateTime dtCommitmentStart { get { return mp_dtCommitmentStart; } set { mp_dtCommitmentStart = value; } } public System.DateTime dtCommitmentFinish { get { return mp_dtCommitmentFinish; } set { mp_dtCommitmentFinish = value; } } public E_COMMITMENTTYPE yCommitmentType { get { return mp_yCommitmentType; } set { mp_yCommitmentType = value; } } public TimephasedData_C oTimephasedData_C { get { return mp_oTimephasedData_C; } } public string Key { get { return mp_sKey; } set { mp_oCollection.mp_SetKey(ref mp_sKey, value, SYS_ERRORS.MP_SET_KEY); } } public bool IsNull() { bool bReturn = true; if (mp_lUID != 0) { bReturn = false; } if (mp_lID != 0) { bReturn = false; } if (mp_sName != "") { bReturn = false; } if (mp_yType != E_TYPE_4.T_4_FIXED_UNITS) { bReturn = false; } if (mp_bIsNull != false) { bReturn = false; } if (mp_dtCreateDate.Ticks != 0) { bReturn = false; } if (mp_sContact != "") { bReturn = false; } if (mp_sWBS != "") { bReturn = false; } if (mp_sWBSLevel != "") { bReturn = false; } if (mp_sOutlineNumber != "") { bReturn = false; } if (mp_lOutlineLevel != 0) { bReturn = false; } if (mp_lPriority != 0) { bReturn = false; } if (mp_dtStart.Ticks != 0) { bReturn = false; } if (mp_dtFinish.Ticks != 0) { bReturn = false; } if (mp_oDuration.IsNull() == false) { bReturn = false; } if (mp_yDurationFormat != E_DURATIONFORMAT.DF_M) { bReturn = false; } if (mp_oWork.IsNull() == false) { bReturn = false; } if (mp_dtStop.Ticks != 0) { bReturn = false; } if (mp_dtResume.Ticks != 0) { bReturn = false; } if (mp_bResumeValid != false) { bReturn = false; } if (mp_bEffortDriven != false) { bReturn = false; } if (mp_bRecurring != false) { bReturn = false; } if (mp_bOverAllocated != false) { bReturn = false; } if (mp_bEstimated != false) { bReturn = false; } if (mp_bMilestone != false) { bReturn = false; } if (mp_bSummary != false) { bReturn = false; } if (mp_bCritical != false) { bReturn = false; } if (mp_bIsSubproject != false) { bReturn = false; } if (mp_bIsSubprojectReadOnly != false) { bReturn = false; } if (mp_sSubprojectName != "") { bReturn = false; } if (mp_bExternalTask != false) { bReturn = false; } if (mp_sExternalTaskProject != "") { bReturn = false; } if (mp_dtEarlyStart.Ticks != 0) { bReturn = false; } if (mp_dtEarlyFinish.Ticks != 0) { bReturn = false; } if (mp_dtLateStart.Ticks != 0) { bReturn = false; } if (mp_dtLateFinish.Ticks != 0) { bReturn = false; } if (mp_lStartVariance != 0) { bReturn = false; } if (mp_lFinishVariance != 0) { bReturn = false; } if (mp_fWorkVariance != 0) { bReturn = false; } if (mp_lFreeSlack != 0) { bReturn = false; } if (mp_lTotalSlack != 0) { bReturn = false; } if (mp_fFixedCost != 0) { bReturn = false; } if (mp_yFixedCostAccrual != E_FIXEDCOSTACCRUAL.FCA_START) { bReturn = false; } if (mp_lPercentComplete != 0) { bReturn = false; } if (mp_lPercentWorkComplete != 0) { bReturn = false; } if (mp_cCost != 0) { bReturn = false; } if (mp_cOvertimeCost != 0) { bReturn = false; } if (mp_oOvertimeWork.IsNull() == false) { bReturn = false; } if (mp_dtActualStart.Ticks != 0) { bReturn = false; } if (mp_dtActualFinish.Ticks != 0) { bReturn = false; } if (mp_oActualDuration.IsNull() == false) { bReturn = false; } if (mp_cActualCost != 0) { bReturn = false; } if (mp_cActualOvertimeCost != 0) { bReturn = false; } if (mp_oActualWork.IsNull() == false) { bReturn = false; } if (mp_oActualOvertimeWork.IsNull() == false) { bReturn = false; } if (mp_oRegularWork.IsNull() == false) { bReturn = false; } if (mp_oRemainingDuration.IsNull() == false) { bReturn = false; } if (mp_cRemainingCost != 0) { bReturn = false; } if (mp_oRemainingWork.IsNull() == false) { bReturn = false; } if (mp_cRemainingOvertimeCost != 0) { bReturn = false; } if (mp_oRemainingOvertimeWork.IsNull() == false) { bReturn = false; } if (mp_fACWP != 0) { bReturn = false; } if (mp_fCV != 0) { bReturn = false; } if (mp_yConstraintType != E_CONSTRAINTTYPE.CT_AS_SOON_AS_POSSIBLE) { bReturn = false; } if (mp_lCalendarUID != 0) { bReturn = false; } if (mp_dtConstraintDate.Ticks != 0) { bReturn = false; } if (mp_dtDeadline.Ticks != 0) { bReturn = false; } if (mp_bLevelAssignments != false) { bReturn = false; } if (mp_bLevelingCanSplit != false) { bReturn = false; } if (mp_lLevelingDelay != 0) { bReturn = false; } if (mp_yLevelingDelayFormat != E_LEVELINGDELAYFORMAT.LDF_M) { bReturn = false; } if (mp_dtPreLeveledStart.Ticks != 0) { bReturn = false; } if (mp_dtPreLeveledFinish.Ticks != 0) { bReturn = false; } if (mp_sHyperlink != "") { bReturn = false; } if (mp_sHyperlinkAddress != "") { bReturn = false; } if (mp_sHyperlinkSubAddress != "") { bReturn = false; } if (mp_bIgnoreResourceCalendar != false) { bReturn = false; } if (mp_sNotes != "") { bReturn = false; } if (mp_bHideBar != false) { bReturn = false; } if (mp_bRollup != false) { bReturn = false; } if (mp_fBCWS != 0) { bReturn = false; } if (mp_fBCWP != 0) { bReturn = false; } if (mp_lPhysicalPercentComplete != 0) { bReturn = false; } if (mp_yEarnedValueMethod != E_EARNEDVALUEMETHOD.EVM_PERCENT_COMPLETE) { bReturn = false; } if (mp_oPredecessorLink_C.IsNull() == false) { bReturn = false; } if (mp_oActualWorkProtected.IsNull() == false) { bReturn = false; } if (mp_oActualOvertimeWorkProtected.IsNull() == false) { bReturn = false; } if (mp_oExtendedAttribute_C.IsNull() == false) { bReturn = false; } if (mp_oBaseline_C.IsNull() == false) { bReturn = false; } if (mp_oOutlineCode_C.IsNull() == false) { bReturn = false; } if (mp_bIsPublished != false) { bReturn = false; } if (mp_sStatusManager != "") { bReturn = false; } if (mp_dtCommitmentStart.Ticks != 0) { bReturn = false; } if (mp_dtCommitmentFinish.Ticks != 0) { bReturn = false; } if (mp_yCommitmentType != E_COMMITMENTTYPE.CT_THE_TASK_HAS_NO_DELIVERABLE_OR_DEPENDENCY_ON_A_DELIVERABLE) { bReturn = false; } if (mp_oTimephasedData_C.IsNull() == false) { bReturn = false; } return bReturn; } public string GetXML() { if (IsNull() == true) { return "<Task/>"; } clsXML oXML = new clsXML("Task"); oXML.InitializeWriter(); oXML.SupportOptional = true; oXML.BoolsAreNumeric = true; oXML.WriteProperty("UID", mp_lUID); oXML.WriteProperty("ID", mp_lID); if (mp_sName != "") { oXML.WriteProperty("Name", mp_sName); } oXML.WriteProperty("Type", mp_yType); oXML.WriteProperty("IsNull", mp_bIsNull); if (mp_dtCreateDate.Ticks != 0) { oXML.WriteProperty("CreateDate", mp_dtCreateDate); } if (mp_sContact != "") { oXML.WriteProperty("Contact", mp_sContact); } if (mp_sWBS != "") { oXML.WriteProperty("WBS", mp_sWBS); } if (mp_sWBSLevel != "") { oXML.WriteProperty("WBSLevel", mp_sWBSLevel); } if (mp_sOutlineNumber != "") { oXML.WriteProperty("OutlineNumber", mp_sOutlineNumber); } oXML.WriteProperty("OutlineLevel", mp_lOutlineLevel); oXML.WriteProperty("Priority", mp_lPriority); if (mp_dtStart.Ticks != 0) { oXML.WriteProperty("Start", mp_dtStart); } if (mp_dtFinish.Ticks != 0) { oXML.WriteProperty("Finish", mp_dtFinish); } oXML.WriteProperty("Duration", mp_oDuration); oXML.WriteProperty("DurationFormat", mp_yDurationFormat); oXML.WriteProperty("Work", mp_oWork); if (mp_dtStop.Ticks != 0) { oXML.WriteProperty("Stop", mp_dtStop); } if (mp_dtResume.Ticks != 0) { oXML.WriteProperty("Resume", mp_dtResume); } oXML.WriteProperty("ResumeValid", mp_bResumeValid); oXML.WriteProperty("EffortDriven", mp_bEffortDriven); oXML.WriteProperty("Recurring", mp_bRecurring); oXML.WriteProperty("OverAllocated", mp_bOverAllocated); oXML.WriteProperty("Estimated", mp_bEstimated); oXML.WriteProperty("Milestone", mp_bMilestone); oXML.WriteProperty("Summary", mp_bSummary); oXML.WriteProperty("Critical", mp_bCritical); oXML.WriteProperty("IsSubproject", mp_bIsSubproject); oXML.WriteProperty("IsSubprojectReadOnly", mp_bIsSubprojectReadOnly); if (mp_sSubprojectName != "") { oXML.WriteProperty("SubprojectName", mp_sSubprojectName); } oXML.WriteProperty("ExternalTask", mp_bExternalTask); if (mp_sExternalTaskProject != "") { oXML.WriteProperty("ExternalTaskProject", mp_sExternalTaskProject); } if (mp_dtEarlyStart.Ticks != 0) { oXML.WriteProperty("EarlyStart", mp_dtEarlyStart); } if (mp_dtEarlyFinish.Ticks != 0) { oXML.WriteProperty("EarlyFinish", mp_dtEarlyFinish); } if (mp_dtLateStart.Ticks != 0) { oXML.WriteProperty("LateStart", mp_dtLateStart); } if (mp_dtLateFinish.Ticks != 0) { oXML.WriteProperty("LateFinish", mp_dtLateFinish); } oXML.WriteProperty("StartVariance", mp_lStartVariance); oXML.WriteProperty("FinishVariance", mp_lFinishVariance); oXML.WriteProperty("WorkVariance", mp_fWorkVariance); oXML.WriteProperty("FreeSlack", mp_lFreeSlack); oXML.WriteProperty("TotalSlack", mp_lTotalSlack); oXML.WriteProperty("FixedCost", mp_fFixedCost); oXML.WriteProperty("FixedCostAccrual", mp_yFixedCostAccrual); oXML.WriteProperty("PercentComplete", mp_lPercentComplete); oXML.WriteProperty("PercentWorkComplete", mp_lPercentWorkComplete); oXML.WriteProperty("Cost", mp_cCost); oXML.WriteProperty("OvertimeCost", mp_cOvertimeCost); oXML.WriteProperty("OvertimeWork", mp_oOvertimeWork); if (mp_dtActualStart.Ticks != 0) { oXML.WriteProperty("ActualStart", mp_dtActualStart); } if (mp_dtActualFinish.Ticks != 0) { oXML.WriteProperty("ActualFinish", mp_dtActualFinish); } oXML.WriteProperty("ActualDuration", mp_oActualDuration); oXML.WriteProperty("ActualCost", mp_cActualCost); oXML.WriteProperty("ActualOvertimeCost", mp_cActualOvertimeCost); oXML.WriteProperty("ActualWork", mp_oActualWork); oXML.WriteProperty("ActualOvertimeWork", mp_oActualOvertimeWork); oXML.WriteProperty("RegularWork", mp_oRegularWork); oXML.WriteProperty("RemainingDuration", mp_oRemainingDuration); oXML.WriteProperty("RemainingCost", mp_cRemainingCost); oXML.WriteProperty("RemainingWork", mp_oRemainingWork); oXML.WriteProperty("RemainingOvertimeCost", mp_cRemainingOvertimeCost); oXML.WriteProperty("RemainingOvertimeWork", mp_oRemainingOvertimeWork); oXML.WriteProperty("ACWP", mp_fACWP); oXML.WriteProperty("CV", mp_fCV); oXML.WriteProperty("ConstraintType", mp_yConstraintType); oXML.WriteProperty("CalendarUID", mp_lCalendarUID); if (mp_dtConstraintDate.Ticks != 0) { oXML.WriteProperty("ConstraintDate", mp_dtConstraintDate); } if (mp_dtDeadline.Ticks != 0) { oXML.WriteProperty("Deadline", mp_dtDeadline); } oXML.WriteProperty("LevelAssignments", mp_bLevelAssignments); oXML.WriteProperty("LevelingCanSplit", mp_bLevelingCanSplit); oXML.WriteProperty("LevelingDelay", mp_lLevelingDelay); oXML.WriteProperty("LevelingDelayFormat", mp_yLevelingDelayFormat); if (mp_dtPreLeveledStart.Ticks != 0) { oXML.WriteProperty("PreLeveledStart", mp_dtPreLeveledStart); } if (mp_dtPreLeveledFinish.Ticks != 0) { oXML.WriteProperty("PreLeveledFinish", mp_dtPreLeveledFinish); } if (mp_sHyperlink != "") { oXML.WriteProperty("Hyperlink", mp_sHyperlink); } if (mp_sHyperlinkAddress != "") { oXML.WriteProperty("HyperlinkAddress", mp_sHyperlinkAddress); } if (mp_sHyperlinkSubAddress != "") { oXML.WriteProperty("HyperlinkSubAddress", mp_sHyperlinkSubAddress); } oXML.WriteProperty("IgnoreResourceCalendar", mp_bIgnoreResourceCalendar); if (mp_sNotes != "") { oXML.WriteProperty("Notes", mp_sNotes); } oXML.WriteProperty("HideBar", mp_bHideBar); oXML.WriteProperty("Rollup", mp_bRollup); oXML.WriteProperty("BCWS", mp_fBCWS); oXML.WriteProperty("BCWP", mp_fBCWP); oXML.WriteProperty("PhysicalPercentComplete", mp_lPhysicalPercentComplete); oXML.WriteProperty("EarnedValueMethod", mp_yEarnedValueMethod); if (mp_oPredecessorLink_C.IsNull() == false) { mp_oPredecessorLink_C.WriteObjectProtected(ref oXML); } if (mp_oActualWorkProtected.IsNull() == false) { oXML.WriteProperty("ActualWorkProtected", mp_oActualWorkProtected); } if (mp_oActualOvertimeWorkProtected.IsNull() == false) { oXML.WriteProperty("ActualOvertimeWorkProtected", mp_oActualOvertimeWorkProtected); } if (mp_oExtendedAttribute_C.IsNull() == false) { mp_oExtendedAttribute_C.WriteObjectProtected(ref oXML); } if (mp_oBaseline_C.IsNull() == false) { mp_oBaseline_C.WriteObjectProtected(ref oXML); } if (mp_oOutlineCode_C.IsNull() == false) { mp_oOutlineCode_C.WriteObjectProtected(ref oXML); } oXML.WriteProperty("IsPublished", mp_bIsPublished); if (mp_sStatusManager != "") { oXML.WriteProperty("StatusManager", mp_sStatusManager); } if (mp_dtCommitmentStart.Ticks != 0) { oXML.WriteProperty("CommitmentStart", mp_dtCommitmentStart); } if (mp_dtCommitmentFinish.Ticks != 0) { oXML.WriteProperty("CommitmentFinish", mp_dtCommitmentFinish); } oXML.WriteProperty("CommitmentType", mp_yCommitmentType); if (mp_oTimephasedData_C.IsNull() == false) { mp_oTimephasedData_C.WriteObjectProtected(ref oXML); } return oXML.GetXML(); } public void SetXML(string sXML) { clsXML oXML = new clsXML("Task"); oXML.SupportOptional = true; oXML.SetXML(sXML); oXML.InitializeReader(); oXML.ReadProperty("UID", ref mp_lUID); oXML.ReadProperty("ID", ref mp_lID); oXML.ReadProperty("Name", ref mp_sName); if (mp_sName.Length > 512) { mp_sName = mp_sName.Substring(0, 512); } oXML.ReadProperty("Type", ref mp_yType); oXML.ReadProperty("IsNull", ref mp_bIsNull); oXML.ReadProperty("CreateDate", ref mp_dtCreateDate); oXML.ReadProperty("Contact", ref mp_sContact); if (mp_sContact.Length > 512) { mp_sContact = mp_sContact.Substring(0, 512); } oXML.ReadProperty("WBS", ref mp_sWBS); oXML.ReadProperty("WBSLevel", ref mp_sWBSLevel); oXML.ReadProperty("OutlineNumber", ref mp_sOutlineNumber); if (mp_sOutlineNumber.Length > 512) { mp_sOutlineNumber = mp_sOutlineNumber.Substring(0, 512); } oXML.ReadProperty("OutlineLevel", ref mp_lOutlineLevel); oXML.ReadProperty("Priority", ref mp_lPriority); oXML.ReadProperty("Start", ref mp_dtStart); oXML.ReadProperty("Finish", ref mp_dtFinish); oXML.ReadProperty("Duration", ref mp_oDuration); oXML.ReadProperty("DurationFormat", ref mp_yDurationFormat); oXML.ReadProperty("Work", ref mp_oWork); oXML.ReadProperty("Stop", ref mp_dtStop); oXML.ReadProperty("Resume", ref mp_dtResume); oXML.ReadProperty("ResumeValid", ref mp_bResumeValid); oXML.ReadProperty("EffortDriven", ref mp_bEffortDriven); oXML.ReadProperty("Recurring", ref mp_bRecurring); oXML.ReadProperty("OverAllocated", ref mp_bOverAllocated); oXML.ReadProperty("Estimated", ref mp_bEstimated); oXML.ReadProperty("Milestone", ref mp_bMilestone); oXML.ReadProperty("Summary", ref mp_bSummary); oXML.ReadProperty("Critical", ref mp_bCritical); oXML.ReadProperty("IsSubproject", ref mp_bIsSubproject); oXML.ReadProperty("IsSubprojectReadOnly", ref mp_bIsSubprojectReadOnly); oXML.ReadProperty("SubprojectName", ref mp_sSubprojectName); if (mp_sSubprojectName.Length > 512) { mp_sSubprojectName = mp_sSubprojectName.Substring(0, 512); } oXML.ReadProperty("ExternalTask", ref mp_bExternalTask); oXML.ReadProperty("ExternalTaskProject", ref mp_sExternalTaskProject); if (mp_sExternalTaskProject.Length > 512) { mp_sExternalTaskProject = mp_sExternalTaskProject.Substring(0, 512); } oXML.ReadProperty("EarlyStart", ref mp_dtEarlyStart); oXML.ReadProperty("EarlyFinish", ref mp_dtEarlyFinish); oXML.ReadProperty("LateStart", ref mp_dtLateStart); oXML.ReadProperty("LateFinish", ref mp_dtLateFinish); oXML.ReadProperty("StartVariance", ref mp_lStartVariance); oXML.ReadProperty("FinishVariance", ref mp_lFinishVariance); oXML.ReadProperty("WorkVariance", ref mp_fWorkVariance); oXML.ReadProperty("FreeSlack", ref mp_lFreeSlack); oXML.ReadProperty("TotalSlack", ref mp_lTotalSlack); oXML.ReadProperty("FixedCost", ref mp_fFixedCost); oXML.ReadProperty("FixedCostAccrual", ref mp_yFixedCostAccrual); oXML.ReadProperty("PercentComplete", ref mp_lPercentComplete); oXML.ReadProperty("PercentWorkComplete", ref mp_lPercentWorkComplete); oXML.ReadProperty("Cost", ref mp_cCost); oXML.ReadProperty("OvertimeCost", ref mp_cOvertimeCost); oXML.ReadProperty("OvertimeWork", ref mp_oOvertimeWork); oXML.ReadProperty("ActualStart", ref mp_dtActualStart); oXML.ReadProperty("ActualFinish", ref mp_dtActualFinish); oXML.ReadProperty("ActualDuration", ref mp_oActualDuration); oXML.ReadProperty("ActualCost", ref mp_cActualCost); oXML.ReadProperty("ActualOvertimeCost", ref mp_cActualOvertimeCost); oXML.ReadProperty("ActualWork", ref mp_oActualWork); oXML.ReadProperty("ActualOvertimeWork", ref mp_oActualOvertimeWork); oXML.ReadProperty("RegularWork", ref mp_oRegularWork); oXML.ReadProperty("RemainingDuration", ref mp_oRemainingDuration); oXML.ReadProperty("RemainingCost", ref mp_cRemainingCost); oXML.ReadProperty("RemainingWork", ref mp_oRemainingWork); oXML.ReadProperty("RemainingOvertimeCost", ref mp_cRemainingOvertimeCost); oXML.ReadProperty("RemainingOvertimeWork", ref mp_oRemainingOvertimeWork); oXML.ReadProperty("ACWP", ref mp_fACWP); oXML.ReadProperty("CV", ref mp_fCV); oXML.ReadProperty("ConstraintType", ref mp_yConstraintType); oXML.ReadProperty("CalendarUID", ref mp_lCalendarUID); oXML.ReadProperty("ConstraintDate", ref mp_dtConstraintDate); oXML.ReadProperty("Deadline", ref mp_dtDeadline); oXML.ReadProperty("LevelAssignments", ref mp_bLevelAssignments); oXML.ReadProperty("LevelingCanSplit", ref mp_bLevelingCanSplit); oXML.ReadProperty("LevelingDelay", ref mp_lLevelingDelay); oXML.ReadProperty("LevelingDelayFormat", ref mp_yLevelingDelayFormat); oXML.ReadProperty("PreLeveledStart", ref mp_dtPreLeveledStart); oXML.ReadProperty("PreLeveledFinish", ref mp_dtPreLeveledFinish); oXML.ReadProperty("Hyperlink", ref mp_sHyperlink); if (mp_sHyperlink.Length > 512) { mp_sHyperlink = mp_sHyperlink.Substring(0, 512); } oXML.ReadProperty("HyperlinkAddress", ref mp_sHyperlinkAddress); if (mp_sHyperlinkAddress.Length > 512) { mp_sHyperlinkAddress = mp_sHyperlinkAddress.Substring(0, 512); } oXML.ReadProperty("HyperlinkSubAddress", ref mp_sHyperlinkSubAddress); if (mp_sHyperlinkSubAddress.Length > 512) { mp_sHyperlinkSubAddress = mp_sHyperlinkSubAddress.Substring(0, 512); } oXML.ReadProperty("IgnoreResourceCalendar", ref mp_bIgnoreResourceCalendar); oXML.ReadProperty("Notes", ref mp_sNotes); oXML.ReadProperty("HideBar", ref mp_bHideBar); oXML.ReadProperty("Rollup", ref mp_bRollup); oXML.ReadProperty("BCWS", ref mp_fBCWS); oXML.ReadProperty("BCWP", ref mp_fBCWP); oXML.ReadProperty("PhysicalPercentComplete", ref mp_lPhysicalPercentComplete); oXML.ReadProperty("EarnedValueMethod", ref mp_yEarnedValueMethod); mp_oPredecessorLink_C.ReadObjectProtected(ref oXML); oXML.ReadProperty("ActualWorkProtected", ref mp_oActualWorkProtected); oXML.ReadProperty("ActualOvertimeWorkProtected", ref mp_oActualOvertimeWorkProtected); mp_oExtendedAttribute_C.ReadObjectProtected(ref oXML); mp_oBaseline_C.ReadObjectProtected(ref oXML); mp_oOutlineCode_C.ReadObjectProtected(ref oXML); oXML.ReadProperty("IsPublished", ref mp_bIsPublished); oXML.ReadProperty("StatusManager", ref mp_sStatusManager); oXML.ReadProperty("CommitmentStart", ref mp_dtCommitmentStart); oXML.ReadProperty("CommitmentFinish", ref mp_dtCommitmentFinish); oXML.ReadProperty("CommitmentType", ref mp_yCommitmentType); mp_oTimephasedData_C.ReadObjectProtected(ref oXML); } } }
19.743405
108
0.6558
[ "MIT" ]
jluzardo1971/ActiveGanttCSN
MSP2007/Task.cs
41,167
C#
using System; using Microsoft.Extensions.DependencyInjection; namespace DrawSequence.Infrastructure.Utility { public static class IServiceCollectionExtensions { public static IServiceCollection AddScopedLazy<TService, TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { services .AddScoped<TService, TImplementation>() .AddScoped(x => new Lazy<TService>(x.GetRequiredService<TService>)); return services; } } }
33.470588
178
0.692443
[ "MIT" ]
Wawrzyn321/Draw-Sequence
DrawSequence/Infrastructure/Utility/IServiceCollectionExtensions.cs
571
C#
using System; using Xamarin.Forms.Platform.iOS; using UIKit; using CoreGraphics; using Xamarin.Forms; using System.Linq; namespace SlideOverKit.iOS { public class SlideOverKitiOSHandler { PageRenderer _pageRenderer; ISlideOverKitPageRendereriOS _menuKit; IMenuContainerPage _basePage; IVisualElementRenderer _menuOverlayRenderer; UIPanGestureRecognizer _panGesture; IDragGesture _dragGesture; IPopupContainerPage _popupBasePage; UIView _popupNativeView; string _currentPopup = null; public SlideOverKitiOSHandler () { } public void Init (ISlideOverKitPageRendereriOS menuKit) { _menuKit = menuKit; _pageRenderer = menuKit as PageRenderer; _menuKit.ViewDidAppearEvent = ViewDidAppear; _menuKit.OnElementChangedEvent = OnElementChanged; _menuKit.ViewDidLayoutSubviewsEvent = ViewDidLayoutSubviews; _menuKit.ViewDidDisappearEvent = ViewDidDisappear; _menuKit.ViewWillTransitionToSizeEvent = ViewWillTransitionToSize; } bool CheckPageAndMenu () { if (_basePage != null && _basePage.SlideMenu != null) return true; else return false; } bool CheckPageAndPopup () { if (_popupBasePage != null && _popupBasePage.PopupViews != null && _popupBasePage.PopupViews.Count > 0) return true; else return false; } UIView _backgroundOverlay; void HideBackgroundOverlay () { if (_backgroundOverlay != null) { _backgroundOverlay.RemoveFromSuperview (); _backgroundOverlay.Dispose (); _backgroundOverlay = null; } _menuOverlayRenderer?.NativeView?.EndEditing (true); } void HideBackgroundForPopup () { _currentPopup = null; if (_popupNativeView != null) { _popupNativeView.RemoveFromSuperview (); _popupNativeView = null; } if (_backgroundOverlay != null) { _backgroundOverlay.RemoveFromSuperview (); _backgroundOverlay.Dispose (); _backgroundOverlay = null; } } void ShowBackgroundOverlay (double alpha) { if (!CheckPageAndMenu ()) return; nfloat value = (nfloat)(alpha * _basePage.SlideMenu.BackgroundViewColor.A); if (_backgroundOverlay != null) { _backgroundOverlay.BackgroundColor = _basePage.SlideMenu.BackgroundViewColor.ToUIColor ().ColorWithAlpha (value); return; } _backgroundOverlay = new UIView (); _backgroundOverlay.BackgroundColor = _basePage.SlideMenu.BackgroundViewColor.ToUIColor ().ColorWithAlpha (value); _backgroundOverlay.AddGestureRecognizer (new UITapGestureRecognizer (() => { this._basePage.HideMenuAction (); })); if (_basePage.SlideMenu.IsFullScreen) { _backgroundOverlay.Frame = new CGRect (UIApplication.SharedApplication.KeyWindow.Frame.Location, UIApplication.SharedApplication.KeyWindow.Frame.Size); UIApplication.SharedApplication.KeyWindow.InsertSubviewBelow (_backgroundOverlay, _menuOverlayRenderer.NativeView); } else { _backgroundOverlay.Frame = new CGRect (_pageRenderer.View.Frame.Location, _pageRenderer.View.Frame.Size); _pageRenderer.View.InsertSubviewBelow (_backgroundOverlay, _menuOverlayRenderer.NativeView); } } void ShowBackgroundForPopup (UIColor color) { if (!CheckPageAndPopup ()) return; if (_backgroundOverlay != null) { _backgroundOverlay.BackgroundColor = color; return; } _backgroundOverlay = new UIView (); _backgroundOverlay.BackgroundColor = color; _backgroundOverlay.AddGestureRecognizer (new UITapGestureRecognizer (() => { this._popupBasePage.HidePopupAction (); })); _backgroundOverlay.Frame = new CGRect (_pageRenderer.View.Frame.Location, _pageRenderer.View.Frame.Size); _pageRenderer.View.AddSubview (_popupNativeView); _pageRenderer.View.InsertSubviewBelow (_backgroundOverlay, _popupNativeView); } void LayoutMenu () { if (!CheckPageAndMenu ()) return; // areadly add gesture if (_dragGesture != null) return; var menu = _basePage.SlideMenu; _dragGesture = DragGestureFactory.GetGestureByView (menu); _dragGesture.RequestLayout = (l, t, r, b, density) => { _menuOverlayRenderer.NativeView.Frame = new CGRect (l, t, (r - l), (b - t)); _menuOverlayRenderer.NativeView.SetNeedsLayout (); }; _dragGesture.NeedShowBackgroundView = (open, alpha) => { UIView.CommitAnimations (); if (open) ShowBackgroundOverlay (alpha); else HideBackgroundOverlay (); }; _basePage.HideMenuAction = () => { UIView.BeginAnimations ("OpenAnimation"); UIView.SetAnimationDuration (((double)menu.AnimationDurationMillisecond) / 1000); _dragGesture.LayoutHideStatus (); _basePage.OnHideMenuAction?.Invoke (); }; _basePage.ShowMenuAction = () => { UIView.BeginAnimations ("OpenAnimation"); UIView.SetAnimationDuration (((double)menu.AnimationDurationMillisecond) / 1000); _dragGesture.LayoutShowStatus (); _basePage.OnShowMenuAction?.Invoke (); }; if (_menuOverlayRenderer == null) { _menuOverlayRenderer = Platform.CreateRenderer (menu); Platform.SetRenderer (menu, _menuOverlayRenderer); _panGesture = new UIPanGestureRecognizer (() => { var p0 = _panGesture.LocationInView (_pageRenderer.View); if (_panGesture.State == UIGestureRecognizerState.Began) { _dragGesture.DragBegin (p0.X, p0.Y); } else if (_panGesture.State == UIGestureRecognizerState.Changed && _panGesture.NumberOfTouches == 1) { _dragGesture.DragMoving (p0.X, p0.Y); } else if (_panGesture.State == UIGestureRecognizerState.Ended) { _dragGesture.DragFinished (); } }); _menuOverlayRenderer.NativeView.AddGestureRecognizer (_panGesture); } var rect = _dragGesture.GetHidePosition (); menu.Layout (new Rectangle ( rect.left, rect.top, (rect.right - rect.left), (rect.bottom - rect.top))); _menuOverlayRenderer.NativeView.Hidden = !menu.IsVisible; _menuOverlayRenderer.NativeView.Frame = new CGRect ( rect.left, rect.top, (rect.right - rect.left), (rect.bottom - rect.top)); _menuOverlayRenderer.NativeView.SetNeedsLayout (); } void LayoutPopup () { if (!CheckPageAndPopup ()) return; _popupBasePage.ShowPopupAction = (key) => { if (!string.IsNullOrEmpty (_currentPopup)) return; SlidePopupView popup = null; if (!_popupBasePage.PopupViews.ContainsKey (key)) { if (string.IsNullOrEmpty (key) && _popupBasePage.PopupViews.Count == 1) popup = _popupBasePage.PopupViews.Values.GetEnumerator ().Current; if (popup == null) return; } _currentPopup = key; popup = _popupBasePage.PopupViews [_currentPopup] as SlidePopupView; var renderer = Platform.CreateRenderer (popup); Platform.SetRenderer (popup, renderer); _popupNativeView = renderer.NativeView; CGRect pos = GetPopupPositionAndLayout (); if (pos.IsEmpty) return; _popupNativeView.Hidden = false; if (_popupNativeView != null) { ShowBackgroundForPopup (popup.BackgroundViewColor.ToUIColor ()); popup.IsShown = true; } popup.HideMySelf = () => { HideBackgroundForPopup (); popup.IsShown = false; }; }; _popupBasePage.HidePopupAction = () => { HideBackgroundForPopup (); var popup = _popupBasePage.PopupViews.Values.Where (o => o.IsShown).FirstOrDefault (); if (popup != null) popup.IsShown = false; }; } CGRect GetPopupPositionAndLayout () { if (string.IsNullOrEmpty (_currentPopup)) return CGRect.Empty; var popup = _popupBasePage.PopupViews [_currentPopup] as SlidePopupView; // This should layout with LeftMargin, TopMargin, WidthRequest and HeightRequest CGRect pos; popup.CalucatePosition (); nfloat y = (nfloat)popup.TopMargin; nfloat x = (nfloat)popup.LeftMargin; nfloat width = (nfloat)(popup.WidthRequest <= 0 ? ScreenSizeHelper.ScreenWidth - popup.LeftMargin * 2 : popup.WidthRequest); nfloat height = (nfloat)(popup.HeightRequest <= 0 ? ScreenSizeHelper.ScreenHeight - popup.TopMargin * 2 : popup.HeightRequest); pos = new CGRect (x, y, width, height); popup.Layout (pos.ToRectangle ()); _popupNativeView.Frame = pos; _popupNativeView.SetNeedsLayout (); return pos; } public void OnElementChanged (VisualElementChangedEventArgs e) { _basePage = e.NewElement as IMenuContainerPage; _popupBasePage = e.NewElement as IPopupContainerPage; ScreenSizeHelper.ScreenHeight = UIScreen.MainScreen.Bounds.Height; ScreenSizeHelper.ScreenWidth = UIScreen.MainScreen.Bounds.Width; LayoutMenu (); LayoutPopup (); } public void ViewDidLayoutSubviews () { GetPopupPositionAndLayout (); } public void ViewDidAppear (bool animated) { if (!CheckPageAndMenu ()) return; if (_basePage.SlideMenu.IsFullScreen) UIApplication.SharedApplication.KeyWindow.AddSubview (_menuOverlayRenderer.NativeView); else _pageRenderer.View.AddSubview (_menuOverlayRenderer.NativeView); } public void ViewDidDisappear (bool animated) { if (_menuOverlayRenderer != null) _menuOverlayRenderer.NativeView.RemoveFromSuperview (); HideBackgroundOverlay (); HideBackgroundForPopup (); } public void ViewWillTransitionToSize (CGSize toSize, IUIViewControllerTransitionCoordinator coordinator) { var menu = _basePage.SlideMenu; // this is used for rotation double bigValue = UIScreen.MainScreen.Bounds.Height > UIScreen.MainScreen.Bounds.Width ? UIScreen.MainScreen.Bounds.Height : UIScreen.MainScreen.Bounds.Width; double smallValue = UIScreen.MainScreen.Bounds.Height < UIScreen.MainScreen.Bounds.Width ? UIScreen.MainScreen.Bounds.Height : UIScreen.MainScreen.Bounds.Width; if (toSize.Width < toSize.Height) { ScreenSizeHelper.ScreenHeight = bigValue; // this is used for mutiltasking ScreenSizeHelper.ScreenWidth = toSize.Width < smallValue ? toSize.Width : smallValue; } else { ScreenSizeHelper.ScreenHeight = smallValue; ScreenSizeHelper.ScreenWidth = toSize.Width < bigValue ? toSize.Width : bigValue; } if (!string.IsNullOrEmpty (_currentPopup)) { GetPopupPositionAndLayout (); // Layout background _backgroundOverlay.Frame = new CGRect (0, 0, ScreenSizeHelper.ScreenWidth, ScreenSizeHelper.ScreenHeight); } if (_dragGesture == null) return; _dragGesture.UpdateLayoutSize (menu); var rect = _dragGesture.GetHidePosition (); menu.Layout (new Xamarin.Forms.Rectangle ( rect.left, rect.top, (rect.right - rect.left), (rect.bottom - rect.top))); _dragGesture.LayoutHideStatus (); } } }
38.12894
172
0.571955
[ "Apache-2.0" ]
raver99/SlideOverKit
SlideOverKit.iOS/SlideOverKitiOSHandler.cs
13,309
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WhiteLotusYoga { public partial class Pricing : Page { protected void Page_Load(object sender, EventArgs e) { } } }
17.823529
60
0.686469
[ "MIT" ]
bennjs/whitelotusyoga
WhiteLotusYoga/Pricing.aspx.cs
305
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Microsoft.CSharp.RuntimeBinder { /// <summary> /// Represents an error that occurs while processing a dynamic bind in the C# runtime binder. Exceptions of this type differ from <see cref="RuntimeBinderException"/> in that /// <see cref="RuntimeBinderException"/> represents a failure to bind in the sense of a usual compiler error, whereas <see cref="RuntimeBinderInternalCompilerException"/> /// represents a malfunctioning of the runtime binder itself. /// </summary> public class RuntimeBinderInternalCompilerException : Exception { /// <summary> /// Initializes a new instance of the <see cref="RuntimeBinderInternalCompilerException"/> class. /// </summary> public RuntimeBinderInternalCompilerException() : base() { } /// <summary> /// Initializes a new instance of the <see cref="RuntimeBinderInternalCompilerException"/> class with a specified error message. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> public RuntimeBinderInternalCompilerException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="RuntimeBinderInternalCompilerException"/> class with a specified error message /// and a reference to the inner exception that is the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param> public RuntimeBinderInternalCompilerException(string message, Exception innerException) : base(message, innerException) { } } }
48.837209
178
0.682857
[ "MIT" ]
690486439/corefx
src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/RuntimeBinderInternalCompilerException.cs
2,100
C#
namespace Snittlistan.Web.Areas.V2.Controllers { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using Snittlistan.Web.Areas.V2.Domain; using Snittlistan.Web.Areas.V2.Indexes; using Snittlistan.Web.Areas.V2.ViewModels; using Snittlistan.Web.Controllers; public class PlayerController : AbstractController { public ActionResult Index() { var players = DocumentSession.Query<Player, PlayerSearch>() .OrderBy(p => p.PlayerStatus) .ThenBy(p => p.Name) .ToList(); var vm = players.Where(x => x.Hidden == false) .Select(x => new PlayerViewModel(x, WebsiteRoles.UserGroup().ToDict())) .ToList(); return View(vm); } [Authorize(Roles = WebsiteRoles.Player.Admin)] public ActionResult Create() { return View(new CreatePlayerViewModel()); } [HttpPost] [Authorize(Roles = WebsiteRoles.Player.Admin)] public ActionResult Create(CreatePlayerViewModel vm) { // prevent duplicates bool isDuplicate = DocumentSession.Query<Player, PlayerSearch>().Any(x => x.Name == vm.Name); if (isDuplicate) { ModelState.AddModelError("namn", "Namnet är redan registrerat"); } if (!ModelState.IsValid) return View(vm); var player = new Player( vm.Name, vm.Email, vm.Status, vm.PersonalNumber.GetValueOrDefault(), vm.Nickname, vm.Roles); DocumentSession.Store(player); return RedirectToAction("Index"); } [Authorize(Roles = WebsiteRoles.Player.Admin)] public ActionResult Edit(int id) { Player player = DocumentSession.Load<Player>(id); if (player == null) throw new HttpException(404, "Player not found"); return View(new CreatePlayerViewModel(player)); } [Authorize(Roles = WebsiteRoles.Player.Admin)] [HttpPost] public ActionResult Edit(int id, CreatePlayerViewModel vm) { Player player = DocumentSession.Load<Player>(id); if (player == null) throw new HttpException(404, "Player not found"); // prevent duplicates Player[] duplicates = DocumentSession.Query<Player, PlayerSearch>().Where(x => x.Name == vm.Name).ToArray(); if (duplicates.Any(x => x.Id != player.Id)) { ModelState.AddModelError("namn", "Namnet är redan registrerat"); } if (!ModelState.IsValid) return View(vm); player.SetName(vm.Name); player.SetEmail(vm.Email); player.SetStatus(vm.Status); player.SetPersonalNumber(vm.PersonalNumber.GetValueOrDefault()); player.SetNickname(vm.Nickname); var allowedRoles = new HashSet<string>(WebsiteRoles.UserGroup().Except(WebsiteRoles.PlayerGroup()).Select(x => x.Name)); player.SetRoles(vm.Roles.Where(x => allowedRoles.Contains(x)).ToArray()); return RedirectToAction("Index"); } [Authorize(Roles = WebsiteRoles.Player.Admin)] public ActionResult Delete(int id) { Player player = DocumentSession.Load<Player>(id); if (player == null) throw new HttpException(404, "Player not found"); return View(new PlayerViewModel(player, WebsiteRoles.UserGroup().ToDictionary(x => x.Name))); } [HttpPost] [Authorize(Roles = WebsiteRoles.Player.Admin)] [ActionName("Delete")] public ActionResult DeleteConfirmed(int id) { Player player = DocumentSession.Load<Player>(id); if (player == null) throw new HttpException(404, "Player not found"); DocumentSession.Delete(player); return RedirectToAction("Index"); } public class CreatePlayerViewModel { public CreatePlayerViewModel() { Name = string.Empty; Nickname = string.Empty; Email = string.Empty; Status = Player.Status.Active; Roles = new string[0]; } public CreatePlayerViewModel(Player player) { Name = player.Name; Nickname = player.Nickname; Email = player.Email; Status = player.PlayerStatus; PersonalNumber = player.PersonalNumber; Roles = player.Roles; } [Required] public string Name { get; set; } public string Nickname { get; set; } [Required] public string Email { get; set; } [Required] public Player.Status Status { get; set; } public int? PersonalNumber { get; set; } public MultiSelectList RolesList { get { WebsiteRoles.WebsiteRole[] roles = WebsiteRoles.UserGroup() .Except(WebsiteRoles.PlayerGroup()) .OrderBy(x => x.Description) .ToArray(); var rolesList = new MultiSelectList( roles, "Name", "Description"); return rolesList; } } [Required] [Display(Name = "Funktioner:")] public string[] Roles { get; set; } } } }
36.28655
133
0.50701
[ "MIT" ]
dlidstrom/Snittlistan
Snittlistan.Web/Areas/V2/Controllers/PlayerController.cs
6,209
C#
// MonoGame - Copyright (C) The MonoGame Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using Microsoft.Xna.Framework.Utilities; namespace Microsoft.Xna.Framework.Content { internal class ReflectiveReader<T> : ContentTypeReader { delegate void ReadElement(ContentReader input, object parent); private List<ReadElement> _readers; private ConstructorInfo _constructor; private ContentTypeReader _baseTypeReader; public ReflectiveReader() : base(typeof(T)) { } public override bool CanDeserializeIntoExistingObject { get { return TargetType.IsClass(); } } protected internal override void Initialize(ContentTypeReaderManager manager) { base.Initialize(manager); var baseType = ReflectionHelpers.GetBaseType(TargetType); if (baseType != null && baseType != typeof(object)) _baseTypeReader = manager.GetTypeReader(baseType); _constructor = TargetType.GetDefaultConstructor(); var properties = TargetType.GetAllProperties(); var fields = TargetType.GetAllFields(); _readers = new List<ReadElement>(fields.Length + properties.Length); // Gather the properties. foreach (var property in properties) { var read = GetElementReader(manager, property); if (read != null) _readers.Add(read); } // Gather the fields. foreach (var field in fields) { var read = GetElementReader(manager, field); if (read != null) _readers.Add(read); } } private static ReadElement GetElementReader(ContentTypeReaderManager manager, MemberInfo member) { var property = member as PropertyInfo; var field = member as FieldInfo; Debug.Assert(field != null || property != null); if (property != null) { // Properties must have at least a getter. if (property.CanRead == false) return null; // Skip over indexer properties. if (property.GetIndexParameters().Any()) return null; } // Are we explicitly asked to ignore this item? if (ReflectionHelpers.GetCustomAttribute<ContentSerializerIgnoreAttribute>(member) != null) return null; var contentSerializerAttribute = ReflectionHelpers.GetCustomAttribute<ContentSerializerAttribute>(member); if (contentSerializerAttribute == null) { if (property != null) { // There is no ContentSerializerAttribute, so non-public // properties cannot be deserialized. if (!ReflectionHelpers.PropertyIsPublic(property)) return null; // If the read-only property has a type reader, // and CanDeserializeIntoExistingObject is true, // then it is safe to deserialize into the existing object. if (!property.CanWrite) { var typeReader = manager.GetTypeReader(property.PropertyType); if (typeReader == null || !typeReader.CanDeserializeIntoExistingObject) return null; } } else { // There is no ContentSerializerAttribute, so non-public // fields cannot be deserialized. if (!field.IsPublic) return null; // evolutional: Added check to skip initialise only fields if (field.IsInitOnly) return null; } } Action<object, object> setter; Type elementType; if (property != null) { elementType = property.PropertyType; if (property.CanWrite) setter = (o, v) => property.SetValue(o, v, null); else setter = (o, v) => { }; } else { elementType = field.FieldType; setter = field.SetValue; } // Shared resources get special treatment. if (contentSerializerAttribute != null && contentSerializerAttribute.SharedResource) { return (input, parent) => { Action<object> action = value => setter(parent, value); input.ReadSharedResource(action); }; } // We need to have a reader at this point. var reader = manager.GetTypeReader(elementType); if (reader == null) if (elementType == typeof(System.Array)) reader = new ArrayReader<Array>(); else throw new ContentLoadException(string.Format("Content reader could not be found for {0} type.", elementType.FullName)); // We use the construct delegate to pick the correct existing // object to be the target of deserialization. Func<object, object> construct = parent => null; if (property != null && !property.CanWrite) construct = parent => property.GetValue(parent, null); return (input, parent) => { var existing = construct(parent); var obj2 = input.ReadObject(reader, existing); setter(parent, obj2); }; } protected internal override object Read(ContentReader input, object existingInstance) { T obj; if (existingInstance != null) obj = (T)existingInstance; else obj = (_constructor == null ? (T)Activator.CreateInstance(typeof(T)) : (T)_constructor.Invoke(null)); if(_baseTypeReader != null) _baseTypeReader.Read(input, obj); // Box the type. var boxed = (object)obj; foreach (var reader in _readers) reader(input, boxed); // Unbox it... required for value types. obj = (T)boxed; return obj; } } }
35.510417
139
0.531534
[ "MIT" ]
MH15/monogame-web-scratch
MonoGame.Framework/Content/ContentReaders/ReflectiveReader.cs
6,818
C#
// Copyright (c) Valdis Iljuconoks. All rights reserved. // Licensed under Apache-2.0. See the LICENSE file in the project root for more information using System.Collections.Generic; using System.Linq; using DbLocalizationProvider.Abstractions; using DbLocalizationProvider.Queries; namespace DbLocalizationProvider.AspNet.Queries { public class GetAllTranslationsHandler : IQueryHandler<GetAllTranslations.Query, IEnumerable<ResourceItem>> { public IEnumerable<ResourceItem> Execute(GetAllTranslations.Query query) { var q = new GetAllResources.Query(); var allResources = q.Execute().Where(r => r.ResourceKey.StartsWith(query.Key) && r.Translations != null && r.Translations.Any(t => t.Language == query.Language.Name)).ToList(); if(!allResources.Any()) { return Enumerable.Empty<ResourceItem>(); } return allResources.Select(r => new ResourceItem(r.ResourceKey, r.Translations.First(t => t.Language == query.Language.Name).Value, query.Language)).ToList(); } } }
42.677419
148
0.57294
[ "Apache-2.0" ]
MattisOlsson/localization-provider-aspnet
src/DbLocalizationProvider.AspNet/Queries/GetAllTranslationsHandler.cs
1,325
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics.ContractsLight; using System.IO; using System.Linq; using System.Threading; using BuildXL.Utilities; namespace BuildXL.Processes.Sideband { /// <summary> /// A disposable reader for sideband files. /// /// Uses <see cref="FileEnvelope"/> to check the integrity of the given file. /// </summary> public sealed class SidebandReader : IDisposable { private readonly BuildXLReader m_bxlReader; private int m_readCounter = 0; private void IncrementAndAssertOrder(Func<int, bool> condition, string errorMessage) { var currentValue = Interlocked.Increment(ref m_readCounter); if (!condition(currentValue)) { throw Contract.AssertFailure($"{errorMessage}. Current counter: " + currentValue); } } /// <nodoc /> public SidebandReader(string sidebandFile) { m_bxlReader = new BuildXLReader( stream: new FileStream(sidebandFile, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete), debug: false, leaveOpen: false); } /// <summary> /// Returns all recorded paths inside the <paramref name="sidebandFile"/> sideband file. /// </summary> public static (IReadOnlyList<string> Paths, SidebandMetadata Metadata) ReadSidebandFile(string sidebandFile, bool ignoreChecksum) { using var sidebandReader = new SidebandReader(sidebandFile); sidebandReader.ReadHeader(ignoreChecksum: ignoreChecksum); var metadata = sidebandReader.ReadMetadata(); var paths = sidebandReader.ReadRecordedPaths().ToList(); return (paths, metadata); } /// <summary> /// Reads the header and returns if the sideband file has been compromised. /// /// Even when the sideband file is compromised, it is possible to call <see cref="ReadRecordedPaths"/> /// which will then try to recover as many recorded paths as possible. /// </summary> public bool ReadHeader(bool ignoreChecksum) { IncrementAndAssertOrder(cnt => cnt == 1, "Read header must be called first"); var result = SidebandWriter.FileEnvelope.TryReadHeader(m_bxlReader.BaseStream, ignoreChecksum); return result.Succeeded; } /// <summary> /// Reads and returns the metadata. /// /// Before calling this method, <see cref="ReadHeader(bool)"/> must be called first. /// </summary> public SidebandMetadata ReadMetadata() { IncrementAndAssertOrder(cnt => cnt == 2, "ReadMetadata must be called second, right after ReadHeader"); return SidebandMetadata.Deserialize(m_bxlReader); } /// <summary> /// Returns all paths recorded in this sideband file. /// /// Before calling this method, <see cref="ReadHeader(bool)"/> and <see cref="ReadMetadata"/> must be called first. /// </summary> /// <remarks> /// Those paths are expected to be absolute paths of files/directories that were written to by the previous build. /// /// NOTE: this method does not validate the recorded paths in any way. That means that each returned string may be /// - a path pointing to an absent file /// - a path pointing to a file /// - a path pointing to a directory. /// /// NOTE: if the sideband file was produced by an instance of this class (and wasn't corrupted in any way) /// - the strings in the returned enumerable are all legal paths /// - the returned collection does not contain any duplicates /// Whether or not this sideband file is corrupted is determined by the result of the <see cref="ReadHeader"/> method. /// </remarks> public IEnumerable<string> ReadRecordedPaths() { IncrementAndAssertOrder(cnt => cnt > 2, "ReadRecordedPaths must be called after ReadHeader and ReadMetadata"); string nextString = null; while ((nextString = ReadStringOrNull()) != null) { yield return nextString; } } private string ReadStringOrNull() { try { return m_bxlReader.ReadString(); } catch (IOException) { return null; } } /// <nodoc /> public void Dispose() { m_bxlReader.Dispose(); } } }
39.15873
138
0.58634
[ "MIT" ]
BearerPipelineTest/BuildXL
Public/Src/Engine/Processes/Sideband/SidebandReader.cs
4,936
C#
// // System.Globalization.CultureInfo Test Cases // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // (c) 2005 Novell, Inc. (http://www.novell.com) // using System; using System.Globalization; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using NUnit.Framework; namespace MonoTests.System.Globalization { [TestFixture] public class CultureInfoTest { CultureInfo old_culture; [SetUp] public void Setup () { old_culture = Thread.CurrentThread.CurrentCulture; } [TearDown] public void TearDown () { Thread.CurrentThread.CurrentCulture = old_culture; } [Test] public void Constructor0 () { CultureInfo ci = new CultureInfo (2067); Assert.IsFalse (ci.IsReadOnly, "#1"); Assert.AreEqual (2067, ci.LCID, "#2"); Assert.AreEqual ("nl-BE", ci.Name, "#3"); Assert.IsTrue (ci.UseUserOverride, "#4"); } [Test] public void Constructor0_Identifier_Negative () { try { new CultureInfo (-1); Assert.Fail ("#1"); } catch (ArgumentOutOfRangeException ex) { Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNotNull (ex.ParamName, "#5"); Assert.AreEqual ("culture", ex.ParamName, "#6"); } } [Test] public void Constructor1 () { CultureInfo ci = new CultureInfo ("nl-BE"); Assert.IsFalse (ci.IsReadOnly, "#1"); Assert.AreEqual (2067, ci.LCID, "#2"); Assert.AreEqual ("nl-BE", ci.Name, "#3"); Assert.IsTrue (ci.UseUserOverride, "#4"); } [Test] public void Constructor1_Name_Null () { try { new CultureInfo ((string) null); Assert.Fail ("#1"); } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNotNull (ex.ParamName, "#5"); Assert.AreEqual ("name", ex.ParamName, "#6"); } } [Test] public void Constructor2 () { CultureInfo ci = new CultureInfo (2067, false); Assert.IsFalse (ci.IsReadOnly, "#A1"); Assert.AreEqual (2067, ci.LCID, "#A2"); Assert.AreEqual ("nl-BE", ci.Name, "#A3"); Assert.IsFalse (ci.UseUserOverride, "#A4"); ci = new CultureInfo (2067, true); Assert.IsFalse (ci.IsReadOnly, "#B1"); Assert.AreEqual (2067, ci.LCID, "#B2"); Assert.AreEqual ("nl-BE", ci.Name, "#B3"); Assert.IsTrue (ci.UseUserOverride, "#B4"); } [Test] public void Constructor2_Identifier_Negative () { try { new CultureInfo (-1, false); Assert.Fail ("#1"); } catch (ArgumentOutOfRangeException ex) { Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNotNull (ex.ParamName, "#5"); Assert.AreEqual ("culture", ex.ParamName, "#6"); } } [Test] public void Constructor3 () { CultureInfo ci = new CultureInfo ("nl-BE", false); Assert.IsFalse (ci.IsReadOnly, "#A1"); Assert.AreEqual (2067, ci.LCID, "#A2"); Assert.AreEqual ("nl-BE", ci.Name, "#A3"); Assert.IsFalse (ci.UseUserOverride, "#A4"); ci = new CultureInfo ("nl-BE", true); Assert.IsFalse (ci.IsReadOnly, "#B1"); Assert.AreEqual (2067, ci.LCID, "#B2"); Assert.AreEqual ("nl-BE", ci.Name, "#B3"); Assert.IsTrue (ci.UseUserOverride, "#B4"); } [Test] public void Constructor3_Name_Null () { try { new CultureInfo ((string) null, false); Assert.Fail ("#1"); } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNotNull (ex.ParamName, "#5"); Assert.AreEqual ("name", ex.ParamName, "#6"); } } [Test] public void ClearCachedData () { var dt = DateTime.Now; old_culture.ClearCachedData (); // It can be any culture instance as the method should be static dt = DateTime.Now; } [Test] public void CreateSpecificCulture () { var ci = CultureInfo.CreateSpecificCulture ("en"); Assert.AreEqual ("en-US", ci.Name, "#1"); ci = CultureInfo.CreateSpecificCulture ("en-GB"); Assert.AreEqual ("en-GB", ci.Name, "#2"); ci = CultureInfo.CreateSpecificCulture ("en-----"); Assert.AreEqual ("en-US", ci.Name, "#3"); ci = CultureInfo.CreateSpecificCulture ("en-GB-"); Assert.AreEqual ("en-US", ci.Name, "#4"); ci = CultureInfo.CreateSpecificCulture (""); Assert.AreEqual (CultureInfo.InvariantCulture, ci, "#5"); } [Test] public void CreateSpecificCulture_Invalid () { try { CultureInfo.CreateSpecificCulture ("uy32"); Assert.Fail ("#1"); #if NET_4_0 } catch (CultureNotFoundException) { #else } catch (ArgumentException) { #endif } try { CultureInfo.CreateSpecificCulture (null); Assert.Fail ("#2"); } catch (ArgumentNullException) { // .NET throws NRE which is lame } } [Test] public void DateTimeFormat_Neutral_Culture () { CultureInfo ci = new CultureInfo ("nl"); try { DateTimeFormatInfo dfi = ci.DateTimeFormat; #if NET_4_0 Assert.IsNotNull (dfi, "#1"); #else Assert.Fail ("#1:" + (dfi != null)); #endif } catch (NotSupportedException ex) { Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); } } [Test] // bug #72081 public void GetAllCulturesInvariant () { CultureInfo invariant = CultureInfo.InvariantCulture; CultureInfo [] infos = CultureInfo.GetCultures (CultureTypes.AllCultures); foreach (CultureInfo culture in infos) { if (culture.Equals (invariant)) return; } Assert.Fail ("InvariantCulture not found in the array from GetCultures()"); } [Test] #if !NET_4_0 [ExpectedException (typeof (NotSupportedException))] #endif public void TrySetNeutralCultureNotInvariant () { Thread.CurrentThread.CurrentCulture = new CultureInfo ("ar"); } [Test] // make sure that all CultureInfo holds non-null calendars. public void OptionalCalendars () { #if MOBILE // ensure the linker does not remove them so we can test them Assert.IsNotNull (typeof (UmAlQuraCalendar), "UmAlQuraCalendar"); #endif foreach (CultureInfo ci in CultureInfo.GetCultures ( CultureTypes.AllCultures)) Assert.IsNotNull (ci.OptionalCalendars, String.Format ("{0} {1}", ci.LCID, ci.Name)); } [Test] // bug #77347 public void CloneNeutral () { CultureInfo culture = new CultureInfo ("en"); CultureInfo cultureClone = culture.Clone () as CultureInfo; Assert.IsTrue (culture.Equals (cultureClone)); } [Test] public void IsNeutral () { var ci = new CultureInfo (0x6C1A); Assert.IsTrue (ci.IsNeutralCulture, "#1"); Assert.AreEqual ("srp", ci.ThreeLetterISOLanguageName, "#2"); ci = new CultureInfo ("en-US"); Assert.IsFalse (ci.IsNeutralCulture, "#1a"); Assert.AreEqual ("eng", ci.ThreeLetterISOLanguageName, "#2a"); } [Test] // bug #81930 public void IsReadOnly () { CultureInfo ci; ci = new CultureInfo ("en-US"); Assert.IsFalse (ci.IsReadOnly, "#A1"); Assert.IsFalse (ci.NumberFormat.IsReadOnly, "#A2"); Assert.IsFalse (ci.DateTimeFormat.IsReadOnly, "#A3"); ci.NumberFormat.NumberGroupSeparator = ","; ci.NumberFormat = new NumberFormatInfo (); ci.DateTimeFormat.DateSeparator = "/"; ci.DateTimeFormat = new DateTimeFormatInfo (); Assert.IsFalse (ci.NumberFormat.IsReadOnly, "#A4"); Assert.IsFalse (ci.DateTimeFormat.IsReadOnly, "#A5"); ci = new CultureInfo (CultureInfo.InvariantCulture.LCID); Assert.IsFalse (ci.IsReadOnly, "#B1"); Assert.IsFalse (ci.NumberFormat.IsReadOnly, "#B2"); Assert.IsFalse (ci.DateTimeFormat.IsReadOnly, "#B3"); ci.NumberFormat.NumberGroupSeparator = ","; ci.NumberFormat = new NumberFormatInfo (); ci.DateTimeFormat.DateSeparator = "/"; ci.DateTimeFormat = new DateTimeFormatInfo (); Assert.IsFalse (ci.NumberFormat.IsReadOnly, "#B4"); Assert.IsFalse (ci.DateTimeFormat.IsReadOnly, "#B5"); ci = CultureInfo.CurrentCulture; Assert.IsTrue (ci.IsReadOnly, "#C1:" + ci.DisplayName); Assert.IsTrue (ci.NumberFormat.IsReadOnly, "#C2"); Assert.IsTrue (ci.DateTimeFormat.IsReadOnly, "#C3"); try { ci.NumberFormat.NumberGroupSeparator = ","; Assert.Fail ("#C4"); } catch (InvalidOperationException ex) { Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#C5"); Assert.IsNull (ex.InnerException, "#C6"); Assert.IsNotNull (ex.Message, "#C7"); } ci = CultureInfo.CurrentUICulture; Assert.IsTrue (ci.IsReadOnly, "#D1"); Assert.IsTrue (ci.NumberFormat.IsReadOnly, "#D2"); Assert.IsTrue (ci.DateTimeFormat.IsReadOnly, "#D3"); try { ci.NumberFormat.NumberGroupSeparator = ","; Assert.Fail ("#D4"); } catch (InvalidOperationException ex) { Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#D5"); Assert.IsNull (ex.InnerException, "#D6"); Assert.IsNotNull (ex.Message, "#D7"); } ci = CultureInfo.InvariantCulture; Assert.IsTrue (ci.IsReadOnly, "#F1"); Assert.IsTrue (ci.NumberFormat.IsReadOnly, "#F2"); Assert.IsTrue (ci.DateTimeFormat.IsReadOnly, "#F3"); try { ci.NumberFormat.NumberGroupSeparator = ","; Assert.Fail ("#F4"); } catch (InvalidOperationException ex) { Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#F5"); Assert.IsNull (ex.InnerException, "#F6"); Assert.IsNotNull (ex.Message, "#F7"); } ci = new CultureInfo (string.Empty); Assert.IsFalse (ci.IsReadOnly, "#G1"); Assert.IsFalse (ci.NumberFormat.IsReadOnly, "#G2"); Assert.IsFalse (ci.DateTimeFormat.IsReadOnly, "#G3"); ci.NumberFormat.NumberGroupSeparator = ","; ci.NumberFormat = new NumberFormatInfo (); ci.DateTimeFormat.DateSeparator = "/"; ci.DateTimeFormat = new DateTimeFormatInfo (); Assert.IsFalse (ci.NumberFormat.IsReadOnly, "#G4"); Assert.IsFalse (ci.DateTimeFormat.IsReadOnly, "#G5"); } [Test] public void IsReadOnly_GetCultures () { foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.AllCultures)) { string cultureMsg = String.Format ("{0} {1}", ci.LCID, ci.Name); Assert.IsFalse (ci.IsReadOnly, "#1:" + cultureMsg); if (ci.IsNeutralCulture) continue; Assert.IsFalse (ci.NumberFormat.IsReadOnly, "#2:" + cultureMsg); Assert.IsFalse (ci.DateTimeFormat.IsReadOnly, "#3:" + cultureMsg); } } [Test] [Category ("NotWorking")] public void IsReadOnly_InstalledUICulture () { CultureInfo ci = CultureInfo.InstalledUICulture; Assert.IsTrue (ci.IsReadOnly, "#1"); Assert.IsTrue (ci.NumberFormat.IsReadOnly, "#2"); Assert.IsTrue (ci.DateTimeFormat.IsReadOnly, "#3"); try { ci.NumberFormat.NumberGroupSeparator = ","; Assert.Fail ("#4"); } catch (InvalidOperationException ex) { Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#5"); Assert.IsNull (ex.InnerException, "#6"); Assert.IsNotNull (ex.Message, "#7"); } } [Test] // bug #69652 public void Norwegian () { new CultureInfo ("no"); new CultureInfo ("nb-NO"); new CultureInfo ("nn-NO"); } [Test] public void NumberFormat_Neutral_Culture () { CultureInfo ci = new CultureInfo ("nl"); try { NumberFormatInfo nfi = ci.NumberFormat; #if NET_4_0 Assert.IsNotNull (nfi, "#1"); #else Assert.Fail ("#1:" + (nfi != null)); #endif } catch (NotSupportedException ex) { Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); } } [Test] [Category ("NotDotNet")] // On MS, the NumberFormatInfo of the CultureInfo matching the current locale is not read-only public void GetCultureInfo_Identifier () { foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.AllCultures)) { string cultureMsg = String.Format ("{0} {1}", ci.LCID, ci.Name); CultureInfo culture = CultureInfo.GetCultureInfo (ci.LCID); Assert.IsTrue (culture.IsReadOnly, "#1:" + cultureMsg); if (culture.IsNeutralCulture) continue; Assert.IsTrue (culture.NumberFormat.IsReadOnly, "#2:" + cultureMsg); Assert.IsTrue (culture.DateTimeFormat.IsReadOnly, "#3:" + cultureMsg); } } [Test] public void GetCultureInfo_Identifier_Negative () { try { CultureInfo.GetCultureInfo (-1); Assert.Fail ("#1"); } catch (ArgumentOutOfRangeException ex) { Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNotNull (ex.ParamName, "#5"); Assert.AreEqual ("culture", ex.ParamName, "#6"); } } [Test] public void GetCultureInfo_Identifier_NotSupported () { try { CultureInfo.GetCultureInfo (666); Assert.Fail ("#1"); } catch (ArgumentException ex) { #if NET_4_0 Assert.AreEqual (typeof (CultureNotFoundException), ex.GetType (), "#2"); #else Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2"); #endif Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNotNull (ex.ParamName, "#5"); Assert.AreEqual ("culture", ex.ParamName, "#6"); } } [Test] [Category ("NotDotNet")] // On MS, the NumberFormatInfo of the CultureInfo matching the current locale is not read-only public void GetCultureInfo_Name () { foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.AllCultures)) { string cultureMsg = String.Format ("{0} {1}", ci.LCID, ci.Name); CultureInfo culture = CultureInfo.GetCultureInfo (ci.Name); Assert.IsTrue (culture.IsReadOnly, "#1:" + cultureMsg); if (culture.IsNeutralCulture) continue; Assert.IsTrue (culture.NumberFormat.IsReadOnly, "#2:" + cultureMsg); Assert.IsTrue (culture.DateTimeFormat.IsReadOnly, "#3:" + cultureMsg); } } [Test] public void GetCultureInfo_Name_NotSupported () { try { CultureInfo.GetCultureInfo ("666"); Assert.Fail ("#1"); } catch (ArgumentException ex) { #if NET_4_0 Assert.AreEqual (typeof (CultureNotFoundException), ex.GetType (), "#2"); #else Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2"); #endif Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNotNull (ex.ParamName, "#5"); Assert.AreEqual ("name", ex.ParamName, "#6"); } } [Test] public void GetCultureInfo_Name_Null () { try { CultureInfo.GetCultureInfo ((string) null); Assert.Fail ("#1"); } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNotNull (ex.ParamName, "#5"); Assert.AreEqual ("name", ex.ParamName, "#6"); } } [Test] public void UseUserOverride_CurrentCulture () { CultureInfo ci = CultureInfo.CurrentCulture; bool expected = (ci.LCID != CultureInfo.InvariantCulture.LCID); Assert.AreEqual (expected, ci.UseUserOverride, "#1"); ci = (CultureInfo) ci.Clone (); Assert.AreEqual (expected, ci.UseUserOverride, "#2"); } [Test] public void UseUserOverride_CurrentUICulture () { CultureInfo ci = CultureInfo.CurrentCulture; bool expected = (ci.LCID != CultureInfo.InvariantCulture.LCID); Assert.AreEqual (expected, ci.UseUserOverride, "#1"); ci = (CultureInfo) ci.Clone (); Assert.AreEqual (expected, ci.UseUserOverride, "#2"); } [Test] public void UseUserOverride_GetCultureInfo () { CultureInfo culture; foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.AllCultures)) { string cultureMsg = String.Format ("{0} {1}", ci.LCID, ci.Name); culture = CultureInfo.GetCultureInfo (ci.Name); Assert.IsFalse (culture.UseUserOverride, "#1: " + cultureMsg); culture = CultureInfo.GetCultureInfo (ci.LCID); Assert.IsFalse (culture.UseUserOverride, "#2: " + cultureMsg); } } [Test] public void UseUserOverride_GetCultures () { foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.AllCultures)) { string cultureMsg = String.Format ("{0} {1}", ci.LCID, ci.Name); if (ci.LCID == CultureInfo.InvariantCulture.LCID) Assert.IsFalse (ci.UseUserOverride, cultureMsg); else Assert.IsTrue (ci.UseUserOverride, cultureMsg); } } [Test] public void UseUserOverride_InvariantCulture () { CultureInfo ci = CultureInfo.InvariantCulture; Assert.IsFalse (ci.UseUserOverride, "#21"); ci = (CultureInfo) ci.Clone (); Assert.IsFalse (ci.UseUserOverride, "#2"); } [Test] public void Bug402128 () { var culture = new CultureInfo ("en-US"); var ms = new MemoryStream (); var formatter = new BinaryFormatter (); formatter.Serialize (ms, culture); ms.Seek (0, SeekOrigin.Begin); var deserializedCulture = (CultureInfo) formatter.Deserialize (ms); } [Test] public void ZhHant () { Assert.AreEqual (31748, new CultureInfo ("zh-Hant").LCID); Assert.AreEqual (31748, CultureInfo.GetCultureInfo ("zh-Hant").LCID); Assert.AreEqual (31748, new CultureInfo ("zh-CHT").LCID); Assert.AreEqual (31748, new CultureInfo ("zh-CHT").Parent.LCID); } [Test] [SetCulture ("zh-TW")] public void ParentOfZh () { Assert.AreEqual (31748, CultureInfo.CurrentCulture.Parent.LCID); Assert.AreEqual (31748, CultureInfo.CurrentCulture.Parent.Parent.LCID); } [Test] public void CurrentCulture () { Assert.IsNotNull (CultureInfo.CurrentCulture, "CurrentCulture"); } [Test] #if NET_4_0 [ExpectedException (typeof (CultureNotFoundException))] #else [ExpectedException (typeof (ArgumentException))] #endif public void CultureNotFound () { // that's how the 'locale' gets defined for a device with an English UI // and it's international settings set for Hong Kong // https://bugzilla.xamarin.com/show_bug.cgi?id=3471 new CultureInfo ("en-HK"); } #if NET_4_5 CountdownEvent barrier = new CountdownEvent (3); AutoResetEvent[] evt = new AutoResetEvent [] { new AutoResetEvent (false), new AutoResetEvent (false), new AutoResetEvent (false)}; CultureInfo[] initial_culture = new CultureInfo[4]; CultureInfo[] changed_culture = new CultureInfo[4]; CultureInfo[] changed_culture2 = new CultureInfo[4]; CultureInfo alternative_culture = new CultureInfo("pt-BR"); void StepAllPhases (int index) { initial_culture [index] = CultureInfo.CurrentCulture; /*Phase 1 - we witness the original value */ barrier.Signal (); /*Phase 2 - main thread changes culture */ evt [index].WaitOne (); /*Phase 3 - we witness the new value */ changed_culture [index] = CultureInfo.CurrentCulture; barrier.Signal (); /* Phase 4 - main thread changes culture back */ evt [index].WaitOne (); /*Phase 5 - we witness the new value */ changed_culture2 [index] = CultureInfo.CurrentCulture; barrier.Signal (); } void ThreadWithoutChange () { StepAllPhases (1); } void ThreadWithChange () { Thread.CurrentThread.CurrentCulture = alternative_culture; StepAllPhases (2); } void ThreadPoolWithoutChange () { StepAllPhases (3); } [Test] public void DefaultThreadCurrentCulture () { var orig_culture = CultureInfo.CurrentCulture; var new_culture = new CultureInfo("fr-FR"); // The test doesn't work if the current culture is already set if (orig_culture != CultureInfo.InvariantCulture) Assert.Ignore ("The test doesn't work if the current culture is already set."); /* Phase 0 - warm up */ new Thread (ThreadWithoutChange).Start (); new Thread (ThreadWithChange).Start (); Action x = ThreadPoolWithoutChange; x.BeginInvoke (null, null); /* Phase 1 - let everyone witness initial values */ initial_culture [0] = CultureInfo.CurrentCulture; barrier.Wait (); barrier.Reset (); /* Phase 2 - change the default culture*/ CultureInfo.DefaultThreadCurrentCulture = new_culture; evt [0].Set (); evt [1].Set (); evt [2].Set (); /* Phase 3 - let everyone witness the new value */ changed_culture [0] = CultureInfo.CurrentCulture; barrier.Wait (); barrier.Reset (); /* Phase 4 - revert the default culture back to null */ CultureInfo.DefaultThreadCurrentCulture = null; evt [0].Set (); evt [1].Set (); evt [2].Set (); /* Phase 5 - let everyone witness the new value */ changed_culture2 [0] = CultureInfo.CurrentCulture; barrier.Wait (); barrier.Reset (); CultureInfo.DefaultThreadCurrentCulture = null; Assert.AreEqual (orig_culture, initial_culture [0], "#1"); Assert.AreEqual (orig_culture, initial_culture [1], "#2"); Assert.AreEqual (alternative_culture, initial_culture [2], "#3"); Assert.AreEqual (orig_culture, initial_culture [3], "#4"); Assert.AreEqual (new_culture, changed_culture [0], "#5"); Assert.AreEqual (new_culture, changed_culture [1], "#6"); Assert.AreEqual (alternative_culture, changed_culture [2], "#7"); Assert.AreEqual (new_culture, changed_culture [3], "#8"); Assert.AreEqual (orig_culture, changed_culture [0], "#9"); Assert.AreEqual (orig_culture, changed_culture2 [1], "#10"); Assert.AreEqual (alternative_culture, changed_culture2 [2], "#11"); Assert.AreEqual (orig_culture, changed_culture2 [3], "#12"); } [Test] public void DefaultThreadCurrentCultureAndNumberFormaters () { string us_str = null; string br_str = null; var thread = new Thread (() => { CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US"); us_str = 100000.ToString ("C"); CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("pt-BR"); br_str = 100000.ToString ("C"); }); thread.Start (); thread.Join (); CultureInfo.DefaultThreadCurrentCulture = null; Assert.AreEqual ("$100,000.00", us_str, "#1"); Assert.AreEqual ("R$ 100.000,00", br_str, "#2"); } #endif } }
30.500684
133
0.670793
[ "Apache-2.0" ]
DLBob/mono
mcs/class/corlib/Test/System.Globalization/CultureInfoTest.cs
22,296
C#
using Mccole.Geodesy.Calculator; using Mccole.Geodesy.Extension; using Mccole.Geodesy.Formatter; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace Mccole.Geodesy.UnitTesting.Calculator { [TestClass] public class RhumbCalculator_Tests { private static double ConvertToBearing(string value) { DegreeMinuteSecond dms; if (DegreeMinuteSecond.TryParse(value, out dms)) { return dms.Bearing; } else { throw new InvalidCastException(string.Format("Could not convert '{0}' to a DegreeMinuteSecond.", value)); } } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Bearing_PointA_Null_ThrowsException() { ICoordinate pointA = default(ICoordinate); var pointB = new Coordinate("58 38 38N", "003 04 12W"); RhumbCalculator.Instance.Bearing(pointA, pointB); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Bearing_PointB_Null_ThrowsException() { var pointA = new Coordinate("50 03 59N", "005 42 53W"); ICoordinate pointB = default(ICoordinate); RhumbCalculator.Instance.Bearing(pointA, pointB); } [TestMethod] public void Bearing_Valid_Assert() { var pointA = new Coordinate("50 21 59N", "004 08 02W"); var pointB = new Coordinate("42 21 04N", "071 02 27W"); var result = RhumbCalculator.Instance.Bearing(pointA, pointB); System.Diagnostics.Debug.WriteLine(string.Format(new DegreeMinuteSecondFormatInfo(), "{0:DMS}", result)); Assert.AreEqual(260.1272, System.Math.Round(result, 4)); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Destination_Above_Range_Kilometres_ThrowsException() { var pointA = new Coordinate("53 19 14N", "001 43 47W"); double distance = 124.8 * 1000; double bearing = ConvertToBearing("096°01′18″"); double radius = 6000; RhumbCalculator.Instance.Destination(pointA, distance, bearing, radius); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Destination_Above_Range_Metres_ThrowsException() { var pointA = new Coordinate("53 19 14N", "001 43 47W"); double distance = 124.8 * 1000; double bearing = ConvertToBearing("096°01′18″"); double radius = 6000 * 1000; RhumbCalculator.Instance.Destination(pointA, distance, bearing, radius); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Destination_Bearing_GreaterThan_360_ThrowsException() { var pointA = new Coordinate("53 19 14N", "001 43 47W"); double distance = 124.8 * 1000; double bearing = 361; RhumbCalculator.Instance.Destination(pointA, distance, bearing); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Destination_Bearing_Negative_ThrowsException() { var pointA = new Coordinate("53 19 14N", "001 43 47W"); double distance = 124.8 * 1000; double bearing = -1; RhumbCalculator.Instance.Destination(pointA, distance, bearing); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Destination_Below_Range_Kilometres_ThrowsException() { var pointA = new Coordinate("53 19 14N", "001 43 47W"); double distance = 124.8 * 1000; double bearing = ConvertToBearing("096°01′18″"); double radius = 4000; RhumbCalculator.Instance.Destination(pointA, distance, bearing, radius); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Destination_Below_Range_Metres_ThrowsException() { var pointA = new Coordinate("53 19 14N", "001 43 47W"); double distance = 124.8 * 1000; double bearing = ConvertToBearing("096°01′18″"); double radius = 4000 * 1000; RhumbCalculator.Instance.Destination(pointA, distance, bearing, radius); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Destination_Distance_Negative_ThrowsException() { var pointA = new Coordinate("53 19 14N", "001 43 47W"); double distance = -1; double bearing = ConvertToBearing("096°01′18″"); RhumbCalculator.Instance.Destination(pointA, distance, bearing); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Destination_PointA_Null_ThrowsException() { ICoordinate pointA = default(ICoordinate); double distance = 124.8 * 1000; double bearing = ConvertToBearing("096°01′18″"); RhumbCalculator.Instance.Destination(pointA, distance, bearing); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Destination_Radius_Negative_ThrowsException() { var pointA = new Coordinate("53 19 14N", "001 43 47W"); double distance = 124.8 * 1000; double bearing = ConvertToBearing("096°01′18″"); double radius = -1; RhumbCalculator.Instance.Destination(pointA, distance, bearing, radius); } [TestMethod] public void Destination_Valid_Assert() { var pointA = new Coordinate("51 07 32N", "001 20 17E"); double distance = 40.23 * 1000; double bearing = ConvertToBearing("116°38′10"); var result = RhumbCalculator.Instance.Destination(pointA, distance, bearing); System.Diagnostics.Debug.WriteLine(result); Assert.AreEqual(50.96335, Math.Round(result.Latitude, 5)); Assert.AreEqual(1.85244, Math.Round(result.Longitude, 5)); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Distance_PointA_Null_ThrowsException() { ICoordinate pointA = default(ICoordinate); var pointB = new Coordinate("58 38 38N", "003 04 12W"); RhumbCalculator.Instance.Distance(pointA, pointB); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Distance_PointB_Null_ThrowsException() { var pointA = new Coordinate("58 38 38N", "003 04 12W"); ICoordinate pointB = default(ICoordinate); RhumbCalculator.Instance.Distance(pointA, pointB); } [TestMethod] public void Distance_Valid_Assert() { var pointA = new Coordinate("50 21 59N", "004 08 02W"); var pointB = new Coordinate("42 21 04N", "071 02 27W"); var result = RhumbCalculator.Instance.Distance(pointA, pointB); System.Diagnostics.Debug.WriteLine(result); Assert.AreEqual(5198001.8698, System.Math.Round(result, 4)); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Midpoint_PointA_Null_ThrowsException() { ICoordinate pointA = default(ICoordinate); var pointB = new Coordinate("58 38 38N", "003 04 12W"); RhumbCalculator.Instance.Midpoint(pointA, pointB); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Midpoint_PointB_Null_ThrowsException() { var pointA = new Coordinate("58 38 38N", "003 04 12W"); ICoordinate pointB = default(ICoordinate); RhumbCalculator.Instance.Midpoint(pointA, pointB); } [TestMethod] public void Midpoint_Valid_Assert() { var pointA = new Coordinate("50 21 59N", "004 08 02W"); var pointB = new Coordinate("42 21 04N", "071 02 27W"); var result = RhumbCalculator.Instance.Midpoint(pointA, pointB); System.Diagnostics.Debug.WriteLine(result); Assert.AreEqual(46.35875, Math.Round(result.Latitude, 5)); Assert.AreEqual(-37.58736, Math.Round(result.Longitude, 5)); } } }
36.316667
121
0.612322
[ "MIT" ]
dungeym/Mccole.Geodesy
Mccole.Geodesy.UnitTesting/Calculator/RhumCalculator_Tests.cs
8,756
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace FileManager.UserControls { /// <summary> /// UCfileListControl.xaml 的交互逻辑 /// </summary> public partial class UCfileListControl : UserControl { public UCfileListControl() { InitializeComponent(); } } }
22.62069
56
0.72561
[ "MIT" ]
toolandhelp/WPFStudyDemos
FileManager/UserControls/UCfileListControl.xaml.cs
668
C#
using Microsoft.CSharp; using NBi.Core.Injection; using NBi.Core.Scalar.Casting; using NBi.Core.Variable; using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Transformation.Transformer { class NCalcTransformer<T> : ITransformer { private ServiceLocator ServiceLocator { get; } protected Context Context { get; } private NCalc.Expression method; public NCalcTransformer() : this(null, null) { } public NCalcTransformer(ServiceLocator serviceLocator, Context context) => (ServiceLocator, Context) = (serviceLocator, context); public void Initialize(string code) { method = new NCalc.Expression(code); } public object Execute(object value) { if (method == null) throw new InvalidOperationException(); if (method.Parameters.ContainsKey("value")) method.Parameters["value"] = value; else method.Parameters.Add("value", value); var transformedValue = method.Evaluate(); return transformedValue; } } }
27.673913
79
0.641005
[ "Apache-2.0" ]
TheAutomatingMrLynch/NBi
NBi.Core/Transformation/Transformer/NCalcTransformer.cs
1,275
C#
// ----------------------------------------------------------------------- // <copyright file="TypeExtensions.cs" company="Hybrid开源团队"> // Copyright (c) 2014-2015 Hybrid. All rights reserved. // </copyright> // <site>https://www.lxking.cn</site> // <last-editor>ArcherTrister</last-editor> // <last-date>2015-10-20 13:37</last-date> // ----------------------------------------------------------------------- using Hybrid.Data; using Hybrid.Extensions; using JetBrains.Annotations; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Hybrid.Reflection { /// <summary> /// 类型<see cref="Type"/>辅助扩展方法类 /// </summary> public static class TypeExtensions { /// <summary> /// 判断当前类型是否可由指定类型派生 /// </summary> public static bool IsDeriveClassFrom<TBaseType>(this Type type, bool canAbstract = false) { return IsDeriveClassFrom(type, typeof(TBaseType), canAbstract); } /// <summary> /// 判断当前类型是否可由指定类型派生 /// </summary> public static bool IsDeriveClassFrom(this Type type, Type baseType, bool canAbstract = false) { Check.NotNull(type, nameof(type)); Check.NotNull(baseType, nameof(baseType)); return type.IsClass && (canAbstract || !type.IsAbstract) && type.IsBaseOn(baseType); } /// <summary> /// 判断类型是否为Nullable类型 /// </summary> /// <param name="type"> 要处理的类型 </param> /// <returns> 是返回True,不是返回False </returns> public static bool IsNullableType(this Type type) { return type != null && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } /// <summary> /// 由类型的Nullable类型返回实际类型 /// </summary> /// <param name="type"> 要处理的类型对象 </param> /// <returns> </returns> public static Type GetNonNullableType(this Type type) { return IsNullableType(type) ? type.GetGenericArguments()[0] : type; } /// <summary> /// 通过类型转换器获取Nullable类型的基础类型 /// </summary> /// <param name="type"> 要处理的类型对象 </param> /// <returns> </returns> public static Type GetUnNullableType(this Type type) { if (IsNullableType(type)) { NullableConverter nullableConverter = new NullableConverter(type); return nullableConverter.UnderlyingType; } return type; } /// <summary> /// 获取类型的Description特性描述信息 /// </summary> /// <param name="type">类型对象</param> /// <param name="inherit">是否搜索类型的继承链以查找描述特性</param> /// <returns>返回Description特性描述信息,如不存在则返回类型的全名</returns> public static string GetDescription(this Type type, bool inherit = true) { DescriptionAttribute desc = type.GetAttribute<DescriptionAttribute>(inherit); return desc == null ? type.FullName : desc.Description; } public static bool IsPrimitiveExtendedIncludingNullable(this Type type, bool includeEnums = false) { if (IsPrimitiveExtended(type, includeEnums)) { return true; } if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { return IsPrimitiveExtended(type.GenericTypeArguments[0], includeEnums); } return false; } private static bool IsPrimitiveExtended(Type type, bool includeEnums) { if (type.GetTypeInfo().IsPrimitive) { return true; } if (includeEnums && type.GetTypeInfo().IsEnum) { return true; } return type == typeof(string) || type == typeof(decimal) || type == typeof(DateTime) || type == typeof(DateTimeOffset) || type == typeof(TimeSpan) || type == typeof(Guid); } /// <summary> /// 获取成员元数据的Description特性描述信息 /// </summary> /// <param name="member">成员元数据对象</param> /// <param name="inherit">是否搜索成员的继承链以查找描述特性</param> /// <returns>返回Description特性描述信息,如不存在则返回成员的名称</returns> public static string GetDescription(this MemberInfo member, bool inherit = true) { DescriptionAttribute desc = member.GetAttribute<DescriptionAttribute>(inherit); if (desc != null) { return desc.Description; } DisplayNameAttribute displayName = member.GetAttribute<DisplayNameAttribute>(inherit); if (displayName != null) { return displayName.DisplayName; } DisplayAttribute display = member.GetAttribute<DisplayAttribute>(inherit); if (display != null) { return display.Name; } return member.Name; } /// <summary> /// 检查指定指定类型成员中是否存在指定的Attribute特性 /// </summary> /// <typeparam name="T">要检查的Attribute特性类型</typeparam> /// <param name="memberInfo">要检查的类型成员</param> /// <param name="inherit">是否从继承中查找</param> /// <returns>是否存在</returns> public static bool HasAttribute<T>(this MemberInfo memberInfo, bool inherit = true) where T : Attribute { return memberInfo.IsDefined(typeof(T), inherit); } /// <summary> /// 从类型成员获取指定Attribute特性 /// </summary> /// <typeparam name="T">Attribute特性类型</typeparam> /// <param name="memberInfo">类型类型成员</param> /// <param name="inherit">是否从继承中查找</param> /// <returns>存在返回第一个,不存在返回null</returns> public static T GetAttribute<T>(this MemberInfo memberInfo, bool inherit = true) where T : Attribute { var attributes = memberInfo.GetCustomAttributes(typeof(T), inherit); return attributes.FirstOrDefault() as T; } /// <summary> /// 从类型成员获取指定Attribute特性 /// </summary> /// <typeparam name="T">Attribute特性类型</typeparam> /// <param name="memberInfo">类型类型成员</param> /// <param name="inherit">是否从继承中查找</param> /// <returns>返回所有指定Attribute特性的数组</returns> public static T[] GetAttributes<T>(this MemberInfo memberInfo, bool inherit = true) where T : Attribute { return memberInfo.GetCustomAttributes(typeof(T), inherit).Cast<T>().ToArray(); } public static TAttribute GetSingleAttributeOrDefaultByFullSearch<TAttribute>(this TypeInfo info) where TAttribute : Attribute { var attributeType = typeof(TAttribute); if (info.IsDefined(attributeType, true)) { return info.GetCustomAttributes(attributeType, true).Cast<TAttribute>().First(); } else { foreach (var implInter in info.ImplementedInterfaces) { var res = implInter.GetTypeInfo().GetSingleAttributeOrDefaultByFullSearch<TAttribute>(); if (res != null) { return res; } } } return null; } public static TAttribute GetSingleAttributeOrDefault<TAttribute>(this MemberInfo memberInfo, TAttribute defaultValue = default(TAttribute), bool inherit = true) where TAttribute : Attribute { var attributeType = typeof(TAttribute); if (memberInfo.IsDefined(typeof(TAttribute), inherit)) { return memberInfo.GetCustomAttributes(attributeType, inherit).Cast<TAttribute>().First(); } return defaultValue; } /// <summary> /// Gets a single attribute for a member. /// </summary> /// <typeparam name="TAttribute">Type of the attribute</typeparam> /// <param name="memberInfo">The member that will be checked for the attribute</param> /// <param name="inherit">Include inherited attributes</param> /// <returns>Returns the attribute object if found. Returns null if not found.</returns> public static TAttribute GetSingleAttributeOrNull<TAttribute>(this MemberInfo memberInfo, bool inherit = true) where TAttribute : Attribute { if (memberInfo == null) { throw new ArgumentNullException(nameof(memberInfo)); } var attrs = memberInfo.GetCustomAttributes(typeof(TAttribute), inherit).ToArray(); if (attrs.Length > 0) { return (TAttribute)attrs[0]; } return default(TAttribute); } public static TAttribute GetSingleAttributeOfTypeOrBaseTypesOrNull<TAttribute>(this Type type, bool inherit = true) where TAttribute : Attribute { var attr = type.GetTypeInfo().GetSingleAttributeOrNull<TAttribute>(); if (attr != null) { return attr; } if (type.GetTypeInfo().BaseType == null) { return null; } return type.GetTypeInfo().BaseType.GetSingleAttributeOfTypeOrBaseTypesOrNull<TAttribute>(inherit); } /// <summary> /// 判断类型是否为集合类型 /// </summary> /// <param name="type">要处理的类型</param> /// <returns>是返回True,不是返回False</returns> public static bool IsEnumerable(this Type type) { if (type == typeof(string)) { return false; } return typeof(IEnumerable).IsAssignableFrom(type); } /// <summary> /// 判断当前泛型类型是否可由指定类型的实例填充 /// </summary> /// <param name="genericType">泛型类型</param> /// <param name="type">指定类型</param> /// <returns></returns> public static bool IsGenericAssignableFrom(this Type genericType, Type type) { genericType.CheckNotNull("genericType"); type.CheckNotNull("type"); if (!genericType.IsGenericType) { throw new ArgumentException("该功能只支持泛型类型的调用,非泛型类型可使用 IsAssignableFrom 方法。"); } List<Type> allOthers = new List<Type> { type }; if (genericType.IsInterface) { allOthers.AddRange(type.GetInterfaces()); } foreach (var other in allOthers) { Type cur = other; while (cur != null) { if (cur.IsGenericType) { cur = cur.GetGenericTypeDefinition(); } if (cur.IsSubclassOf(genericType) || cur == genericType) { return true; } cur = cur.BaseType; } } return false; } /// <summary> /// 方法是否是异步 /// </summary> public static bool IsAsync(this MethodInfo method) { return method.ReturnType == typeof(Task) || method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>); } /// <summary> /// 返回当前类型是否是指定基类的派生类 /// </summary> /// <param name="type">当前类型</param> /// <param name="baseType">要判断的基类型</param> /// <returns></returns> public static bool IsBaseOn(this Type type, Type baseType) { if (baseType.IsGenericTypeDefinition) { return baseType.IsGenericAssignableFrom(type); } return baseType.IsAssignableFrom(type); } /// <summary> /// 返回当前类型是否是指定基类的派生类 /// </summary> /// <typeparam name="TBaseType">要判断的基类型</typeparam> /// <param name="type">当前类型</param> /// <returns></returns> public static bool IsBaseOn<TBaseType>(this Type type) { Type baseType = typeof(TBaseType); return type.IsBaseOn(baseType); } /// <summary> /// 返回当前方法信息是否是重写方法 /// </summary> /// <param name="method">要判断的方法信息</param> /// <returns>是否是重写方法</returns> public static bool IsOverridden(this MethodInfo method) { return method.GetBaseDefinition().DeclaringType != method.DeclaringType; } /// <summary> /// 返回当前属性信息是否为virtual /// </summary> public static bool IsVirtual(this PropertyInfo property) { var accessor = property.GetAccessors().FirstOrDefault(); if (accessor == null) { return false; } return accessor.IsVirtual && !accessor.IsFinal; } /// <summary> /// 获取类型的全名,附带所在类库 /// </summary> public static string GetFullNameWithModule(this Type type) { return $"{type.FullName},{type.Module.Name.Replace(".dll", "").Replace(".exe", "")}"; } /// <summary> /// 获取类型的显示短名称 /// </summary> public static string ShortDisplayName(this Type type) { return type.DisplayName(false); } /// <summary> /// 获取类型的显示名称 /// </summary> public static string DisplayName([NotNull]this Type type, bool fullName = true) { StringBuilder sb = new StringBuilder(); ProcessType(sb, type, fullName); return sb.ToString(); } public static Assembly GetAssembly(this Type type) { return type.GetTypeInfo().Assembly; } #region 私有方法 private static readonly Dictionary<Type, string> _builtInTypeNames = new Dictionary<Type, string> { { typeof(bool), "bool" }, { typeof(byte), "byte" }, { typeof(char), "char" }, { typeof(decimal), "decimal" }, { typeof(double), "double" }, { typeof(float), "float" }, { typeof(int), "int" }, { typeof(long), "long" }, { typeof(object), "object" }, { typeof(sbyte), "sbyte" }, { typeof(short), "short" }, { typeof(string), "string" }, { typeof(uint), "uint" }, { typeof(ulong), "ulong" }, { typeof(ushort), "ushort" }, { typeof(void), "void" } }; private static void ProcessType(StringBuilder builder, Type type, bool fullName) { if (type.IsGenericType) { var genericArguments = type.GetGenericArguments(); ProcessGenericType(builder, type, genericArguments, genericArguments.Length, fullName); } else if (type.IsArray) { ProcessArrayType(builder, type, fullName); } else if (_builtInTypeNames.TryGetValue(type, out var builtInName)) { builder.Append(builtInName); } else if (!type.IsGenericParameter) { builder.Append(fullName ? type.FullName : type.Name); } } private static void ProcessArrayType(StringBuilder builder, Type type, bool fullName) { var innerType = type; while (innerType.IsArray) { innerType = innerType.GetElementType(); } ProcessType(builder, innerType, fullName); while (type.IsArray) { builder.Append('['); builder.Append(',', type.GetArrayRank() - 1); builder.Append(']'); type = type.GetElementType(); } } private static void ProcessGenericType(StringBuilder builder, Type type, Type[] genericArguments, int length, bool fullName) { var offset = type.IsNested ? type.DeclaringType.GetGenericArguments().Length : 0; if (fullName) { if (type.IsNested) { ProcessGenericType(builder, type.DeclaringType, genericArguments, offset, fullName); builder.Append('+'); } else { builder.Append(type.Namespace); builder.Append('.'); } } var genericPartIndex = type.Name.IndexOf('`'); if (genericPartIndex <= 0) { builder.Append(type.Name); return; } builder.Append(type.Name, 0, genericPartIndex); builder.Append('<'); for (var i = offset; i < length; i++) { ProcessType(builder, genericArguments[i], fullName); if (i + 1 == length) { continue; } builder.Append(','); if (!genericArguments[i + 1].IsGenericParameter) { builder.Append(' '); } } builder.Append('>'); } #endregion 私有方法 } }
33.598113
168
0.524681
[ "Apache-2.0" ]
ArcherTrister/ESoftor
src/Hybrid/Reflection/TypeExtensions.cs
18,963
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; namespace Microsoft.Extensions.FileSystemGlobbing.Internal { /// <summary> /// This API supports infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public interface ILinearPattern : IPattern { IList<IPathSegment> Segments { get; } } }
33.352941
111
0.716049
[ "Apache-2.0" ]
188867052/Extensions
src/FileSystemGlobbing/src/Internal/ILinearPattern.cs
567
C#
namespace State { /// <summary> /// State that indicates the Account is not accruing interest. /// /// Behaves as a ConcreteState in the State pattern. /// </summary> internal class ZeroInterestAccountState : AccountState { private new const double InterestRate = 0; private new const double LowerLimit = 0; private new const double UpperLimit = 1_000; public ZeroInterestAccountState(AccountState accountState) : this(accountState.Balance, accountState.Account) { } public ZeroInterestAccountState(double balance, Account account) { Balance = balance; Account = account; } public override bool Deposit(double amount) { Balance += amount; TryStateChange(); return true; } public override double? AccrueInterest() { var accruedInterest = InterestRate * Balance; Balance += accruedInterest; TryStateChange(); return accruedInterest; } public override void TryStateChange() { if (Balance < LowerLimit) { Account.AccountState = new OverdrawnAccountState(this); } else if (Balance > UpperLimit) { Account.AccountState = new InterestAccountState(this); } } public override bool Withdraw(double amount) { Balance -= amount; TryStateChange(); return true; } } }
27.474576
72
0.550895
[ "MIT" ]
GabeStah/Airbrake.io
Pitches/A Guide to Software Design Patterns/State/ZeroInterestAccountState.cs
1,623
C#
using Microsoft.AspNetCore.Components; using System; using System.Collections.Generic; using System.Text; namespace Blazorade.Bootstrap.Components { /// <summary> /// The <see cref="DropdownMenu"/> component is uses as child component in a <see cref="Dropdown"/> component. /// It is the parent to one or many <see cref="DropdownItem"/> components. /// </summary> public partial class DropdownMenu { /// <summary> /// </summary> protected override void OnParametersSet() { this.AddClasses(ClassNames.Dropdowns.Menu); base.OnParametersSet(); } } }
26.75
114
0.637072
[ "Apache-2.0", "MIT" ]
Blazorade/Blazorade-Bootstrap
Blazorade.Bootstrap.Components/DropdownMenu.razor.cs
644
C#
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Security.AccessControl; using static Kernel32; /// <content> /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// </content> public static partial class AdvApi32 { /// <summary> /// Enumerates services in the specified service control manager database. /// The name and status of each service are provided. /// </summary> /// <returns> /// An IEnumerable of <see cref="ENUM_SERVICE_STATUS"/> structures that receive the name and service status information for each service in the database. /// </returns> /// <exception cref="Win32Exception">If the method fails, returning the calling thread's last-error code value.</exception> public static unsafe IEnumerable<ENUM_SERVICE_STATUS> EnumServicesStatus() { using (var scmHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ENUMERATE_SERVICE)) { if (scmHandle.IsInvalid) { throw new Win32Exception(); } int bufferSizeNeeded = 0; int numServicesReturned = 0; int resumeIndex = 0; if (EnumServicesStatus( scmHandle, ServiceType.SERVICE_WIN32, ServiceStateQuery.SERVICE_STATE_ALL, null, 0, ref bufferSizeNeeded, ref numServicesReturned, ref resumeIndex)) { return Enumerable.Empty<ENUM_SERVICE_STATUS>(); } var lastError = GetLastError(); if (lastError != Win32ErrorCode.ERROR_MORE_DATA) { throw new Win32Exception(lastError); } fixed (byte* buffer = new byte[bufferSizeNeeded]) { if (!EnumServicesStatus( scmHandle, ServiceType.SERVICE_WIN32, ServiceStateQuery.SERVICE_STATE_ALL, buffer, bufferSizeNeeded, ref bufferSizeNeeded, ref numServicesReturned, ref resumeIndex)) { throw new Win32Exception(); } var result = new ENUM_SERVICE_STATUS[numServicesReturned]; byte* position = buffer; int structSize = Marshal.SizeOf(typeof(ENUM_SERVICE_STATUS)); for (int i = 0; i < numServicesReturned; i++) { result[i] = (ENUM_SERVICE_STATUS)Marshal.PtrToStructure(new IntPtr(position), typeof(ENUM_SERVICE_STATUS)); position += structSize; } return result; } } } /// <summary> /// Retrieves a copy of the security descriptor associated with a service object. You can also use the /// GetNamedSecurityInfo function to retrieve a security descriptor. /// </summary> /// <param name="hService"> /// A handle to the service control manager or the service. Handles to the service control manager /// are returned by the <see cref="OpenSCManager" /> function, and handles to a service are returned by either the /// <see cref="OpenService" /> or <see cref="CreateService(SafeServiceHandle,string,string,ServiceAccess,ServiceType,ServiceStartType,ServiceErrorControl,string,string,int, string,string,string)" /> function. The handle must have the READ_CONTROL access /// right. /// </param> /// <param name="dwSecurityInformation"> /// A set of bit flags that indicate the type of security information to retrieve. This /// parameter can be a combination of the <see cref="SECURITY_INFORMATION" /> flags, with the exception that this /// function does not support the <see cref="SECURITY_INFORMATION.LABEL_SECURITY_INFORMATION" /> value. /// </param> /// <returns> /// A copy of the security descriptor of the specified service object. The calling process must have the /// appropriate access to view the specified aspects of the security descriptor of the object. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="hService" /> is NULL.</exception> /// <exception cref="Win32Exception">If the call to the native method fails fails.</exception> public static RawSecurityDescriptor QueryServiceObjectSecurity(SafeServiceHandle hService, SECURITY_INFORMATION dwSecurityInformation) { if (hService == null) { throw new ArgumentNullException(nameof(hService)); } var securityDescriptor = new byte[0]; int bufSizeNeeded; QueryServiceObjectSecurity(hService, dwSecurityInformation, securityDescriptor, 0, out bufSizeNeeded); var lastError = GetLastError(); if (lastError != Win32ErrorCode.ERROR_INSUFFICIENT_BUFFER) { throw new Win32Exception(lastError); } securityDescriptor = new byte[bufSizeNeeded]; var success = QueryServiceObjectSecurity(hService, dwSecurityInformation, securityDescriptor, bufSizeNeeded, out bufSizeNeeded); if (!success) { throw new Win32Exception(); } return new RawSecurityDescriptor(securityDescriptor, 0); } /// <summary>The SetServiceObjectSecurity function sets the security descriptor of a service object.</summary> /// <param name="hService"> /// A handle to the service. This handle is returned by the <see cref="OpenService" /> or /// <see cref="CreateService(SafeServiceHandle,string,string,ServiceAccess,ServiceType,ServiceStartType,ServiceErrorControl,string,string,int, string,string,string)" /> function. The access required for this handle depends on the security information /// specified in the <paramref name="dwSecurityInformation" /> parameter. /// </param> /// <param name="dwSecurityInformation"> /// Specifies the components of the security descriptor to set. This parameter can be a /// combination of the following values : <see cref="SECURITY_INFORMATION.DACL_SECURITY_INFORMATION" />, /// <see cref="SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION" />, /// <see cref="SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION" />, /// <see cref="SECURITY_INFORMATION.SACL_SECURITY_INFORMATION" />. Note that flags not handled by /// SetServiceObjectSecurity will be silently ignored. /// </param> /// <param name="lpSecurityDescriptor">The new security information.</param> public static void SetServiceObjectSecurity( SafeServiceHandle hService, SECURITY_INFORMATION dwSecurityInformation, RawSecurityDescriptor lpSecurityDescriptor) { var binaryForm = new byte[lpSecurityDescriptor.BinaryLength]; lpSecurityDescriptor.GetBinaryForm(binaryForm, 0); if (!SetServiceObjectSecurity(hService, dwSecurityInformation, binaryForm)) { throw new Win32Exception(); } } } }
49.284848
265
0.602927
[ "MIT" ]
augustoproiete-forks/dotnet--pinvoke
src/AdvApi32.Desktop/AdvApi32.Helpers.cs
8,134
C#
/* * CAMERA LOOK DETECTOR * Detects what the camera is looking at * If it is looking at something that has a collider, it will attempt * to tell the MouseCursor script to change its cursor * If the Interact key is pressed while looking at an object * it will attempt to run the 'Interact Function' of the targets' Object Interaction script */ using UnityEngine; using System.Collections; public class CameraLookDetector : MonoBehaviour { Camera cam; public MouseCursor mouseCursor; public KeyCode interactKey = KeyCode.E; public float maxInteractionDistance = 2.0f; ObjectInteraction currentLookTarget; void Start() { cam = GetComponent<Camera>(); currentLookTarget = null; } void Update() { Ray ray = cam.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0)); RaycastHit hit; if (Physics.Raycast(ray, out hit, maxInteractionDistance)) LookAtInteractible(hit.transform.GetComponent<ObjectInteraction>() ?? null); else LookAtInteractible(null); if (Input.GetKeyDown(interactKey) && currentLookTarget != null) { currentLookTarget.OnInteract(); } } void LookAtInteractible(ObjectInteraction obj) { currentLookTarget = obj; if (obj != null && obj.cursor != null) mouseCursor.SetCursor(obj.cursor); else mouseCursor.SetCursor(); } }
26.054545
91
0.662945
[ "MIT" ]
CMD-Breda-Avans/CMD-First-Person-Controller
CameraLookDetector.cs
1,433
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudfront-2020-05-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.CloudFront.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using System.Xml; namespace Amazon.CloudFront.Model.Internal.MarshallTransformations { /// <summary> /// DeleteFunction Request Marshaller /// </summary> public class DeleteFunctionRequestMarshaller : IMarshaller<IRequest, DeleteFunctionRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DeleteFunctionRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DeleteFunctionRequest publicRequest) { var request = new DefaultRequest(publicRequest, "Amazon.CloudFront"); request.HttpMethod = "DELETE"; if(publicRequest.IsSetIfMatch()) request.Headers["If-Match"] = publicRequest.IfMatch; if (!publicRequest.IsSetName()) throw new AmazonCloudFrontException("Request object does not have required field Name set"); request.AddPathResource("{Name}", StringUtils.FromString(publicRequest.Name)); request.ResourcePath = "/2020-05-31/function/{Name}"; return request; } private static DeleteFunctionRequestMarshaller _instance = new DeleteFunctionRequestMarshaller(); internal static DeleteFunctionRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteFunctionRequestMarshaller Instance { get { return _instance; } } } }
33.865169
143
0.65063
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/Internal/MarshallTransformations/DeleteFunctionRequestMarshaller.cs
3,014
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Oscar.BL { public class Genres { // Data members. private Nullable<Guid> genreId; private string genreName = string.Empty; ///////////////////////////////////////// // Access to the data members. public Nullable<Guid> GenreId { get { return genreId; } set { if (genreId == null) { genreId = value; } } } public string GenreName { get { return genreName; } set { genreName = value; } } public void AddNewGenre(string InputGenreName) { genreName = InputGenreName; } public Genres() { } } }
20.021739
54
0.457112
[ "MIT" ]
IVIvk/Oscar
Syntra.Oscar/Oscar.BL/Genres.cs
923
C#
using System; using System.Collections.Generic; using System.Data.Entity.Design.PluralizationServices; using System.Globalization; using System.IO; using System.Linq; using Microsoft.VisualStudio.Modeling.Diagrams; using Microsoft.VisualStudio.Modeling.Validation; using Sawczyn.EFDesigner.EFModel.Annotations; using Sawczyn.EFDesigner.EFModel.Extensions; #pragma warning disable 1591 namespace Sawczyn.EFDesigner.EFModel { [ValidationState(ValidationState.Enabled)] public partial class ModelRoot : IHasStore { /// <summary> /// Provides pluralization for names (currently English only) /// </summary> public static readonly PluralizationService PluralizationService; internal static bool BatchUpdating = false; internal static string InstallationDirectory { get; set; } /// <summary> /// Current method that validates the model /// </summary> public static Action ExecuteValidator { get; set; } /// <summary> /// Method to finds the diagram that currently has focus, if any /// </summary> public static Func<Diagram> GetCurrentDiagram { get; set; } /// <summary> /// Method to output a diagram as a zip file /// </summary> public static Func<bool> WriteDiagramAsBinary { get; set; } = () => false; static ModelRoot() { try { PluralizationService = PluralizationService.CreateService(CultureInfo.CurrentCulture); InstallationDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(ModelRoot)).Location); } catch (NotImplementedException) { PluralizationService = null; } } /// <summary> /// FQN of the DbContext-derived class /// </summary> // ReSharper disable once UnusedMember.Global public string FullName => string.IsNullOrWhiteSpace(Namespace) ? $"global::{EntityContainerName}" : $"global::{Namespace}.{EntityContainerName}"; /// <summary> /// True if the model is EFCore and the Entity Framework version is >= 5 /// </summary> public bool IsEFCore5Plus => EntityFrameworkVersion == EFVersion.EFCore && (EntityFrameworkPackageVersion == "Latest" || GetEntityFrameworkPackageVersionNum() >= 5); /// <summary> /// Finds all diagrams associated to this model /// </summary> public EFModelDiagram[] GetDiagrams() { return Store .DefaultPartitionForClass(EFModelDiagram.DomainClassId) .ElementDirectory .AllElements .OfType<EFModelDiagram>() .ToArray(); } #region Filename private string filename; /// <summary> /// Sets the filename for saving this model /// </summary> public void SetFileName(string fileName) { filename = fileName; } /// <summary> /// Gets the filename of this model /// </summary> public string GetFileName() { return filename; } #endregion #region OutputLocations private OutputLocations outputLocationsStorage; private OutputLocations GetOutputLocationsValue() { return outputLocationsStorage ?? (outputLocationsStorage = new OutputLocations(this)); } private void SetOutputLocationsValue(OutputLocations value) { outputLocationsStorage = value; } #endregion OutputLocations #region Namespaces private Namespaces namespacesStorage; private Namespaces GetNamespacesValue() { return namespacesStorage ?? (namespacesStorage = new Namespaces(this)); } private void SetNamespacesValue(Namespaces value) { namespacesStorage = value; } #endregion Namespaces #region Valid types based on EF version /// <summary> /// List of spatial types, depending on EF version selected /// </summary> public string[] SpatialTypes { get { return EntityFrameworkVersion == EFVersion.EF6 ? new[] { "Geography" , "GeographyCollection" , "GeographyLineString" , "GeographyMultiLineString" , "GeographyMultiPoint" , "GeographyMultiPolygon" , "GeographyPoint" , "GeographyPolygon" , "Geometry" , "GeometryCollection" , "GeometryLineString" , "GeometryMultiLineString" , "GeometryMultiPoint" , "GeometryMultiPolygon" , "GeometryPoint" , "GeometryPolygon" } : new[] { "Geometry" , "GeometryCollection" , "LineString" , "MultiLineString" , "MultiPoint" , "MultiPolygon" , "Point" , "Polygon" }; } } /// <summary> /// Class types that can be used in the model /// </summary> public string[] ValidTypes { get { List<string> validTypes = new List<string>(new[] { "Binary" , "Boolean" , "Byte" , "byte" , "DateTime" , "DateTimeOffset" , "Decimal" , "Double" , "Guid" }); if (IsEFCore5Plus) { validTypes.Add("System.Net.IPAddress"); validTypes.Add("System.Net.NetworkInformation.PhysicalAddress"); } validTypes.AddRange(new[] { "Int16" , "Int32" , "Int64" , "Single" , "String" , "Time" }); return validTypes.Union(SpatialTypes).ToArray(); } } /// <summary> /// CLR Types that can be used in the model /// </summary> public string[] ValidCLRTypes { get { List<string> validClrTypes = new List<string>(new[] { "Binary", "Boolean", "Boolean?", "Nullable<Boolean>", "Byte", "Byte?", "Nullable<Byte>", "DateTime", "DateTime?", "Nullable<DateTime>", "DateTimeOffset", "DateTimeOffset?", "Nullable<DateTimeOffset>", "DbGeography", "DbGeometry", "Decimal", "Decimal?", "Nullable<Decimal>", "Double", "Double?", "Nullable<Double>", "Guid", "Guid?", "Nullable<Guid>" }); if (IsEFCore5Plus) validClrTypes.Add("System.Net.IPAddress"); validClrTypes.AddRange(new[] { "Int16", "Int16?", "Nullable<Int16>", "Int32", "Int32?", "Nullable<Int32>", "Int64", "Int64?", "Nullable<Int64>", "Single", "Single?", "Nullable<Single>", "String", "Time", "TimeSpan", "TimeSpan?", "Nullable<TimeSpan>", "bool", "bool?", "Nullable<bool>", "byte", "byte?", "Nullable<byte>", "byte[]", "decimal", "decimal?", "Nullable<decimal>", "double", "double?", "Nullable<double>", "int", "int?", "Nullable<int>", "long", "long?", "Nullable<long>", "short", "short?", "Nullable<short>", "string" }); return validClrTypes.Union(SpatialTypes).ToArray(); } } /// <summary> /// Validates that the type in question can be used as an identity. /// EF6 is constrained as to identity types, as is EFCore before v5. /// EFCore v5+ has no constraints, other than what's put on by the database type /// </summary> /// <param name="typename">Name of type to check for use as identity</param> /// <returns>True if valid, false otherwise</returns> public bool IsValidIdentityAttributeType(string typename) { return IsEFCore5Plus || ValidIdentityAttributeTypes.Contains(typename); } /// <summary> /// Collection of type names valid for identity attribute types /// </summary> public string[] ValidIdentityAttributeTypes { get { List<string> baseResult = ValidIdentityTypeAttributesBaseList; baseResult.AddRange(Store.ElementDirectory .AllElements .OfType<ModelEnum>() .Where(e => baseResult.Contains(e.ValueType.ToString())) .Select(e => e.Name) .OrderBy(n => n)); return baseResult.ToArray(); } } private static List<string> ValidIdentityTypeAttributesBaseList { get { return new List<string> { "Int16", "Int32", "Int64", "Byte", "String", "Guid" }; } } /// <summary> /// Determines if a type name string is a valid C# CLR type for model usage. /// </summary> public bool IsValidCLRType(string type) { return ValidCLRTypes.Contains(type); } #endregion #region Nuget /// <summary> /// Transforms the selected EntityFrameworkPackageVersion into a decimal number, only taking the first two segments into account. If a "Latest" version is chosen, looks up the appropriate real version. /// </summary> public double GetEntityFrameworkPackageVersionNum() { string packageVersion = EntityFrameworkPackageVersion; string[] parts = packageVersion.Split('.'); if (packageVersion.EndsWith("Latest")) { (int A, int B, int C) actualVersion; switch (parts.Length) { case 1: // just "Latest" actualVersion = NugetVersions.Last(); break; case 2: // x.Latest actualVersion = NugetVersions.Last(v => v.A == int.Parse(parts[0], CultureInfo.InvariantCulture)); break; default: // x.y.Latest actualVersion = NugetVersions.Last(v => v.A == int.Parse(parts[0], CultureInfo.InvariantCulture) && v.B == int.Parse(parts[1], CultureInfo.InvariantCulture)); break; } packageVersion = $"{actualVersion.A}.{actualVersion.B}"; } else packageVersion = $"{parts[0]}.{parts[1]}"; return double.Parse(packageVersion, CultureInfo.InvariantCulture); } private List<(int A, int B, int C)> nugetVersions; private List<(int A, int B, int C)> NugetVersions { get { return nugetVersions ?? (nugetVersions = NuGetHelper.EFPackageVersions[EntityFrameworkVersion] .Where(x => x.Count(c => c == '.') == 2) .Select(v => (int.TryParse(v.Substring(0, v.IndexOf('.')), out int x1) ? x1 : 0 , int.TryParse(v.Substring(v.IndexOf('.') + 1, v.IndexOf('.', v.IndexOf('.') + 1) - v.IndexOf('.') - 1), out int x2) ? x2 : 0 , int.TryParse(v.Substring(v.IndexOf('.', v.IndexOf('.') + 1) + 1), out int x3) ? x3 : 0)) .OrderBy<(int A, int B, int C), int>(v => v.A).ThenBy(v => v.B).ThenBy(v => v.C) .Distinct() .ToList()); } } #endregion Nuget #region Validation methods [ValidationMethod(/*ValidationCategories.Open | */ValidationCategories.Save | ValidationCategories.Menu)] [UsedImplicitly] [System.Diagnostics.CodeAnalysis.SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "Called by validation")] private void ConnectionStringMustExist(ValidationContext context) { if (!Classes.Any() && !Enums.Any()) return; if (string.IsNullOrEmpty(ConnectionString) && string.IsNullOrEmpty(ConnectionStringName)) context.LogWarning("Model: Default connection string missing", "MRWConnectionString", this); if (string.IsNullOrEmpty(EntityContainerName)) context.LogError("Model: Entity container needs a name", "MREContainerNameEmpty", this); } [ValidationMethod(ValidationCategories.Open | ValidationCategories.Save | ValidationCategories.Menu)] [UsedImplicitly] [System.Diagnostics.CodeAnalysis.SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "Called by validation")] private void SummaryDescriptionIsEmpty(ValidationContext context) { if (string.IsNullOrWhiteSpace(Summary) && WarnOnMissingDocumentation) context.LogWarning("Model: Summary documentation missing", "AWMissingSummary", this); } #endregion Validation methods #region DatabaseSchema tracking property protected virtual void OnDatabaseSchemaChanged(string oldValue, string newValue) { TrackingHelper.UpdateTrackingCollectionProperty(Store, Classes, ModelClass.DatabaseSchemaDomainPropertyId, ModelClass.IsDatabaseSchemaTrackingDomainPropertyId); } internal sealed partial class DatabaseSchemaPropertyHandler { protected override void OnValueChanged(ModelRoot element, string oldValue, string newValue) { base.OnValueChanged(element, oldValue, newValue); if (!element.Store.InUndoRedoOrRollback) element.OnDatabaseSchemaChanged(oldValue, newValue); } } #endregion DatabaseSchema tracking property #region DatabaseCollationDefault tracking property protected virtual void OnDatabaseCollationDefaultChanged(string oldValue, string newValue) { TrackingHelper.UpdateTrackingCollectionProperty(Store, Classes, ModelAttribute.DatabaseCollationDomainPropertyId, ModelAttribute.IsDatabaseCollationTrackingDomainPropertyId); } internal sealed partial class DatabaseCollationDefaultPropertyHandler { protected override void OnValueChanged(ModelRoot element, string oldValue, string newValue) { base.OnValueChanged(element, oldValue, newValue); if (!element.Store.InUndoRedoOrRollback) element.OnDatabaseCollationDefaultChanged(oldValue, newValue); } } #endregion DatabaseCollationDefault tracking property #region DefaultCollectionClass tracking property protected virtual void OnCollectionClassChanged(string oldValue, string newValue) { TrackingHelper.UpdateTrackingCollectionProperty(Store, Store.GetAll<Association>().ToList(), Association.CollectionClassDomainPropertyId, Association.IsCollectionClassTrackingDomainPropertyId); } internal sealed partial class DefaultCollectionClassPropertyHandler { protected override void OnValueChanged(ModelRoot element, string oldValue, string newValue) { base.OnValueChanged(element, oldValue, newValue); if (!element.Store.InUndoRedoOrRollback) element.OnCollectionClassChanged(oldValue, newValue); } } #endregion DefaultCollectionClass tracking property #region Entity Output Directory tracking property protected virtual void OnEntityOutputDirectoryChanged(string oldValue, string newValue) { TrackingHelper.UpdateTrackingCollectionProperty(Store, Classes, ModelClass.OutputDirectoryDomainPropertyId, ModelClass.IsOutputDirectoryTrackingDomainPropertyId); } internal sealed partial class EntityOutputDirectoryPropertyHandler { protected override void OnValueChanged(ModelRoot element, string oldValue, string newValue) { base.OnValueChanged(element, oldValue, newValue); if (!element.Store.InUndoRedoOrRollback) element.OnEntityOutputDirectoryChanged(oldValue, newValue); } } #endregion #region Enum Output Directory tracking property protected virtual void OnEnumOutputDirectoryChanged(string oldValue, string newValue) { TrackingHelper.UpdateTrackingCollectionProperty(Store, Classes, ModelEnum.OutputDirectoryDomainPropertyId, ModelEnum.IsOutputDirectoryTrackingDomainPropertyId); } internal sealed partial class EnumOutputDirectoryPropertyHandler { protected override void OnValueChanged(ModelRoot element, string oldValue, string newValue) { base.OnValueChanged(element, oldValue, newValue); if (!element.Store.InUndoRedoOrRollback) element.OnEnumOutputDirectoryChanged(oldValue, newValue); } } #endregion #region Namespace tracking property internal sealed partial class NamespacePropertyHandler { protected override void OnValueChanged(ModelRoot element, string oldValue, string newValue) { base.OnValueChanged(element, oldValue, newValue); if (!element.Store.InUndoRedoOrRollback) { if (string.IsNullOrWhiteSpace(element.EntityNamespace)) { TrackingHelper.UpdateTrackingCollectionProperty(element.Store , element.Classes.Where(c => !c.IsDependentType) , ModelClass.NamespaceDomainPropertyId , ModelClass.IsNamespaceTrackingDomainPropertyId); } if (string.IsNullOrWhiteSpace(element.StructNamespace)) { TrackingHelper.UpdateTrackingCollectionProperty(element.Store , element.Classes.Where(c => c.IsDependentType) , ModelClass.NamespaceDomainPropertyId , ModelClass.IsNamespaceTrackingDomainPropertyId); } if (string.IsNullOrWhiteSpace(element.EnumNamespace)) TrackingHelper.UpdateTrackingCollectionProperty(element.Store, element.Enums, ModelEnum.NamespaceDomainPropertyId, ModelEnum.IsNamespaceTrackingDomainPropertyId); } } } internal sealed partial class EntityNamespacePropertyHandler { protected override void OnValueChanged(ModelRoot element, string oldValue, string newValue) { base.OnValueChanged(element, oldValue, newValue); if (!element.Store.InUndoRedoOrRollback) { TrackingHelper.UpdateTrackingCollectionProperty(element.Store, element.Classes.Where(c => !c.IsDependentType), ModelClass.NamespaceDomainPropertyId, ModelClass.IsNamespaceTrackingDomainPropertyId); } } } internal sealed partial class EnumNamespacePropertyHandler { protected override void OnValueChanged(ModelRoot element, string oldValue, string newValue) { base.OnValueChanged(element, oldValue, newValue); if (!element.Store.InUndoRedoOrRollback) TrackingHelper.UpdateTrackingCollectionProperty(element.Store, element.Enums, ModelEnum.NamespaceDomainPropertyId, ModelEnum.IsNamespaceTrackingDomainPropertyId); } } internal sealed partial class StructNamespacePropertyHandler { protected override void OnValueChanged(ModelRoot element, string oldValue, string newValue) { base.OnValueChanged(element, oldValue, newValue); if (!element.Store.InUndoRedoOrRollback) { TrackingHelper.UpdateTrackingCollectionProperty(element.Store , element.Classes.Where(c => c.IsDependentType) , ModelClass.NamespaceDomainPropertyId , ModelClass.IsNamespaceTrackingDomainPropertyId); } } } #endregion Namespace tracking property #region AutoPropertyDefault tracking property /// <summary> /// Updates tracking properties when the IsImplementNotify value changes /// </summary> /// <param name="oldValue">Prior value</param> /// <param name="newValue">Current value</param> protected virtual void OnAutoPropertyDefaultChanged(bool oldValue, bool newValue) { TrackingHelper.UpdateTrackingCollectionProperty(Store, Classes, ModelClass.AutoPropertyDefaultDomainPropertyId, ModelClass.IsAutoPropertyDefaultTrackingDomainPropertyId); } internal sealed partial class AutoPropertyDefaultPropertyHandler { protected override void OnValueChanged(ModelRoot element, bool oldValue, bool newValue) { base.OnValueChanged(element, oldValue, newValue); if (!element.Store.InUndoRedoOrRollback) element.OnAutoPropertyDefaultChanged(oldValue, newValue); } } #endregion AutoPropertyDefault tracking property } }
41.582524
208
0.503113
[ "MIT" ]
MagicAndre1981/EFDesigner
src/Dsl/CustomCode/Partials/ModelRoot.cs
25,700
C#
using Upgrade; namespace Ship { namespace SecondEdition.M12LKimogilaFighter { public class CartelExecutioner : M12LKimogilaFighter { public CartelExecutioner() : base() { PilotInfo = new PilotCardInfo( "Cartel Executioner", 3, 44, extraUpgradeIcon: UpgradeType.Talent, seImageNumber: 209 ); ModelInfo.SkinName = "Cartel Executioner"; } } } }
24.521739
60
0.475177
[ "MIT" ]
GeneralVryth/FlyCasual
Assets/Scripts/Model/Content/SecondEdition/Pilots/M12LKimogilaFighter/CartelExecutioner.cs
566
C#
// <auto-generated /> namespace BellumGens.Api.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")] public sealed partial class ApplicationToTournament : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(ApplicationToTournament)); string IMigrationMetadata.Id { get { return "202001141324006_ApplicationToTournament"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
28.5
106
0.636257
[ "MIT" ]
BellumGens/bellum-gens-api
BellumGens.Api/Migrations/202001141324006_ApplicationToTournament.Designer.cs
855
C#
namespace Machete.X12Schema.V5010 { using X12; public interface LoopSAC_860 : X12Layout { Segment<SAC> ServicePromotionAllowanceOrChargeInformation { get; } Segment<CUR> Currency { get; } } }
18.615385
74
0.623967
[ "Apache-2.0" ]
ahives/Machete
src/Machete.X12Schema/V5010/Layouts/LoopSAC_860.cs
242
C#
///////////////////////////////////////////////////////////////////// // Copyright (c) Autodesk, Inc. All rights reserved // Written by Forge Partner Development // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. ///////////////////////////////////////////////////////////////////// using Autodesk.Forge; using Autodesk.Forge.OAuth; using Autodesk.Forge.OSS; using System.Collections.Generic; using System.Threading.Tasks; using System.Web.Http; namespace WebAPISample.Controllers { public class JSTreeController : ApiController { public class TreeNode { public TreeNode(string id, string text, string type, bool children) { this.id = id; this.text = text; this.type = type; this.children = children; } public string id { get; set; } public string text { get; set; } public string type { get; set; } public bool children { get; set; } } [HttpGet] [Route("api/forge/tree")] public async Task<IList<TreeNode>> GetTreeDataAsync([FromUri]string id) { IList<TreeNode> nodes = new List<TreeNode>(); OAuth oauth = await OAuth2LeggedToken.AuthenticateAsync(Config.FORGE_CLIENT_ID, Config.FORGE_CLIENT_SECRET, new Scope[] { Scope.BucketRead, Scope.DataRead }); if (id == "#") // root { // in this case, let's return all buckets AppBuckets appBuckets = new AppBuckets(oauth); IEnumerable<Bucket> buckets = await appBuckets.GetBucketsAsync(int.MaxValue); foreach (Bucket b in buckets) nodes.Add(new TreeNode(b.BucketKey, b.BucketKey, "bucket", true)); } else { // as we have the id (bucketKey), let's return all objects Bucket bucket = new Bucket(oauth, id/*bucketKey*/); IEnumerable<Autodesk.Forge.OSS.Object> objects = await bucket.GetObjectsAsync(int.MaxValue); foreach (Autodesk.Forge.OSS.Object obj in objects) nodes.Add(new TreeNode(obj.ObjectId.Base64Encode(), obj.ObjectKey, "object", false)); } return nodes; } } }
37.902778
165
0.630634
[ "MIT" ]
efrenabella/model.derivative-csharp.webapi-viewer.sample
ASPNET.webapi/Controllers/JSTreeController.cs
2,731
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api20180501Preview { using static Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Extensions; /// <summary>The collection of content validation properties</summary> public partial class WebTestPropertiesValidationRulesContentValidation { /// <summary> /// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonObject json); /// <summary> /// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonObject" /// /> before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonObject container); /// <summary> /// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of /// the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> /// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return /// instantly.</param> partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonObject json, ref bool returnNow); /// <summary> /// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the /// object before it is serialized. /// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonObject container, ref bool returnNow); /// <summary> /// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api20180501Preview.IWebTestPropertiesValidationRulesContentValidation. /// </summary> /// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonNode" /> to deserialize from.</param> /// <returns> /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api20180501Preview.IWebTestPropertiesValidationRulesContentValidation. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api20180501Preview.IWebTestPropertiesValidationRulesContentValidation FromJson(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonNode node) { return node is Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonObject json ? new WebTestPropertiesValidationRulesContentValidation(json) : null; } /// <summary> /// Serializes this instance of <see cref="WebTestPropertiesValidationRulesContentValidation" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonNode" /// />. /// </summary> /// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller /// passes in <c>null</c>, a new instance will be created and returned to the caller.</param> /// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="WebTestPropertiesValidationRulesContentValidation" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonNode" /// />. /// </returns> public Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.SerializationMode serializationMode) { container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return container; } AddIf( null != (((object)this._contentMatch)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonString(this._contentMatch.ToString()) : null, "ContentMatch" ,container.Add ); AddIf( null != this._ignoreCase ? (Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonBoolean((bool)this._ignoreCase) : null, "IgnoreCase" ,container.Add ); AddIf( null != this._passIfTextFound ? (Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonBoolean((bool)this._passIfTextFound) : null, "PassIfTextFound" ,container.Add ); AfterToJson(ref container); return container; } /// <summary> /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonObject into a new instance of <see cref="WebTestPropertiesValidationRulesContentValidation" /// />. /// </summary> /// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonObject instance to deserialize from.</param> internal WebTestPropertiesValidationRulesContentValidation(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonObject json) { bool returnNow = false; BeforeFromJson(json, ref returnNow); if (returnNow) { return; } {_contentMatch = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonString>("ContentMatch"), out var __jsonContentMatch) ? (string)__jsonContentMatch : (string)ContentMatch;} {_ignoreCase = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonBoolean>("IgnoreCase"), out var __jsonIgnoreCase) ? (bool?)__jsonIgnoreCase : IgnoreCase;} {_passIfTextFound = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonBoolean>("PassIfTextFound"), out var __jsonPassIfTextFound) ? (bool?)__jsonPassIfTextFound : PassIfTextFound;} AfterFromJson(json); } } }
77.017699
306
0.716879
[ "MIT" ]
Agazoth/azure-powershell
src/ApplicationInsights/ApplicationInsights.Autorest/generated/api/Models/Api20180501Preview/WebTestPropertiesValidationRulesContentValidation.json.cs
8,591
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Example.AdventureWorks2008ObjectContext_Dal.DbCtx { using System; using System.Collections.Generic; public partial class ErrorLog { public int ErrorLogID { get; set; } public System.DateTime ErrorTime { get; set; } public string UserName { get; set; } public int ErrorNumber { get; set; } public Nullable<int> ErrorSeverity { get; set; } public Nullable<int> ErrorState { get; set; } public string ErrorProcedure { get; set; } public Nullable<int> ErrorLine { get; set; } public string ErrorMessage { get; set; } } }
37.321429
84
0.558852
[ "MIT", "Unlicense" ]
vgribok/Aspectacular
NET 4.0/Example.AdventureWorks2008_Dal.40/DbCtx/ErrorLog.cs
1,045
C#
using RestWithASPNET5Udemy.Configurations; using RestWithASPNET5Udemy.Data.VO; using RestWithASPNET5Udemy.Repositories; using RestWithASPNET5Udemy.Services; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; namespace RestWithASPNET5Udemy.Business.Implementations { public class LoginBusinessImplementation : ILoginBusiness { private const string DATE_FORMAT = "yyy-MM-dd HH:mm:ss"; private TokenConfiguration _configuration; private IUserRepository _repository; private readonly ITokenService _tokenservice; public LoginBusinessImplementation(TokenConfiguration configuration, IUserRepository repository, ITokenService tokenservice) { _configuration = configuration; _repository = repository; _tokenservice = tokenservice; } public TokenVO ValidateCredentials(UserVO userCredentials) { var user = _repository.ValidateCredentials(userCredentials); if (user == null) return null; var claims = new List<Claim> { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName) }; var accessToken = _tokenservice.GenerateAccessToken(claims); var refreshToken = _tokenservice.GenerateRefresToken(); user.RefresToken = refreshToken; user.RefreshTokenExpiryTime = DateTime.Now.AddDays(_configuration.DaysToExpiry); _repository.RefreshUserInfo(user); DateTime createDate = DateTime.Now; DateTime expirationDate = createDate.AddMinutes(_configuration.Minutes); return new TokenVO( true, createDate.ToString(DATE_FORMAT), expirationDate.ToString(DATE_FORMAT), accessToken, refreshToken ); } } }
32.53125
132
0.653218
[ "Apache-2.0" ]
fulviomanfrin/RestWithASP-NET5Udemy
02_RestWithASPNET5Udemy_Calculator/RestWithASPNET5Udemy/RestWithASPNET5Udemy/Business/Implementations/LoginBusinessImplementation.cs
2,084
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BusinessLayer; using P2DbContext.Models; using Microsoft.EntityFrameworkCore; namespace P2Api { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors((options) => { options.AddPolicy(name: "dev", builder => { builder.WithOrigins("http://127.0.0.1:5500", "http://localhost:4200", "https://localhost:44307", "https://pokelootapi.azurewebsites.net", "https://pokeloot.azurewebsites.net/", "https://pokeloot.z19.web.core.windows.net/") // update thisssssssssss to proper ip / pathing .AllowAnyHeader() .AllowAnyMethod(); }); }); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "P2Api", Version = "v1" }); }); services.AddDbContext<P2DbClass>(options => { if (!options.IsConfigured) { options.UseSqlServer("Server=tcp:p2pokelootserver.database.windows.net,1433;Initial Catalog=PokeLoot;Persist Security Info=False;User ID=christian.romero@revature.net@p2pokelootserver;Password=P2PokeLoot;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"); } }); services.AddScoped<IBusinessModel, BusinessModel>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "P2Api v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseCors("dev"); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
35.588235
323
0.599008
[ "MIT" ]
06012021-dotnet-uta/P2_PokeLoot
P2Project/P2Main/P2Api/Startup.cs
3,025
C#
using System; using System.Linq; using ApexSharp.ApexParser.Parser; using ApexSharp.ApexParser.Syntax; using ApexSharp.ApexParser.Toolbox; using NUnit.Framework; using Sprache; using static ApexSharp.ApexParser.Tests.Properties.Resources; namespace ApexSharp.ApexParser.Tests.Toolbox { [TestFixture] public class ParseExtensionTests : ICommentParserProvider { [Test] public void ParseExProducesMoreDetailedExceptionMessage() { // append the error line to the valid demo file var errorLine = "--===-- oops! --===--"; var demo = Demo + Environment.NewLine + errorLine; try { new ApexGrammar().ClassDeclaration.End().ParseEx(demo); Assert.Fail("The code should have thrown ParseException."); } catch (ParseException ex) { // check that the error message contains the complete invalid code line var exc = ex as ParseExceptionCustom; Assert.NotNull(exc); Assert.True(exc.Apexcode.Contains(errorLine)); } } private readonly Parser<string> Identifier1 = from id in Parse.Identifier(Parse.Letter, Parse.LetterOrDigit).Token(null).End() select id; [Test] public void ForStaticParserTokenNullModifierWorksLikeOrdinaryToken() { var result = Identifier1.Parse(" \t hello123 \t\r\n "); Assert.AreEqual("hello123", result); } public IComment CommentParser { get; } = new CommentParser(); private Parser<string> Identifier2 => from id in Parse.Identifier(Parse.Letter, Parse.LetterOrDigit).Token(this).End() select id; [Test] public void ForParserOwnedByICommentParserProviderTokenThisStripsOutComments() { // whitespace only var result = Identifier2.Parse(" \t hello123 \t\r\n "); Assert.AreEqual("hello123", result); // trailing comments result = Identifier2.End().Parse(" \t hello123 // what's that? "); Assert.AreEqual("hello123", result); // leading and trailing comments result = Identifier2.Parse(@" // leading comments! helloWorld // trailing comments! "); Assert.AreEqual("helloWorld", result); // multiple leading and trailing comments result = Identifier2.Parse(@" // leading comments! /* multiline leading comments this is the second line */ test321 // trailing comments! /* --==-- */"); Assert.AreEqual("test321", result); } private Parser<BreakStatementSyntax> BreakStatement1 => from @break in Parse.IgnoreCase(ApexKeywords.Break).Token(this) from semicolon in Parse.Char(';').Token(this) select new BreakStatementSyntax(); [Test] public void TokenThisModifierDoesntSaveCommentsContentAutomatically() { // whitespace only var @break = BreakStatement1.Parse(" \t break; \t\r\n "); Assert.AreEqual(0, @break.LeadingComments.Count); Assert.AreEqual(0, @break.TrailingComments.Count); // leading comments @break = BreakStatement1.Parse(@" // this is a break statement break;"); Assert.AreEqual(0, @break.LeadingComments.Count); Assert.AreEqual(0, @break.TrailingComments.Count); // trailing comments @break = BreakStatement1.Parse(@" break /* a comment before the semicolon */; // this is ignored"); Assert.AreEqual(0, @break.LeadingComments.Count); Assert.AreEqual(0, @break.TrailingComments.Count); } private Parser<BreakStatementSyntax> BreakStatement2 => from @break in Parse.IgnoreCase(ApexKeywords.Break).Commented(this) from semicolon in Parse.Char(';').Commented(this) select new BreakStatementSyntax { LeadingComments = @break.LeadingComments.ToList(), TrailingComments = semicolon.TrailingComments.ToList(), }; [Test] public void CommentedThisModifierAllowsSavingCommentsAsNeeded() { // whitespace only var @break = BreakStatement2.Parse(" \t break; \t\r\n "); Assert.AreEqual(0, @break.LeadingComments.Count); Assert.AreEqual(0, @break.TrailingComments.Count); // leading comments @break = BreakStatement2.Parse(@" // this is a break statement break; "); Assert.AreEqual(1, @break.LeadingComments.Count); Assert.AreEqual("this is a break statement", @break.LeadingComments[0].Trim()); Assert.AreEqual(0, @break.TrailingComments.Count); // trailing comments @break = BreakStatement2.Parse(@" break /* this is ignored */; // a comment after the semicolon"); Assert.AreEqual(0, @break.LeadingComments.Count); Assert.AreEqual(1, @break.TrailingComments.Count); Assert.AreEqual("a comment after the semicolon", @break.TrailingComments[0].Trim()); // both leading trailing comments @break = BreakStatement2.Parse(@" // leading1 /* leading2 */ break /* this is ignored */; // a comment after the semicolon"); Assert.AreEqual(2, @break.LeadingComments.Count); Assert.AreEqual("leading1", @break.LeadingComments[0].Trim()); Assert.AreEqual("leading2", @break.LeadingComments[1].Trim()); Assert.AreEqual(1, @break.TrailingComments.Count); Assert.AreEqual("a comment after the semicolon", @break.TrailingComments[0].Trim()); } private Parser<ITextSpan<string>> IdentifierSpan => from id in Parse.Identifier(Parse.Letter, Parse.LetterOrDigit).Span().Token(this) select id; [Test] public void SourceSpanOfIdentifierReturnsProperValues() { var id = IdentifierSpan.Parse(" HelloThere "); Assert.AreEqual(1, id.Start.Line); Assert.AreEqual(3, id.Start.Column); Assert.AreEqual(2, id.Start.Pos); Assert.AreEqual(1, id.End.Line); Assert.AreEqual(13, id.End.Column); Assert.AreEqual(12, id.End.Pos); Assert.AreEqual(10, id.Length); Assert.AreEqual("HelloThere", id.Value); id = IdentifierSpan.Parse(@" // comment /* another comment */ MyIdentifier // test"); Assert.AreEqual(3, id.Start.Line); Assert.AreEqual(13, id.Start.Column); Assert.AreEqual(3, id.End.Line); Assert.AreEqual(25, id.End.Column); Assert.AreEqual(12, id.Length); Assert.AreEqual("MyIdentifier", id.Value); } private Parser<string> PreviewParserDemo => from test in Parse.String("test").Token().Preview() from testMethod in Parse.String("testMethod").Token().Text() select testMethod; [Test] public void PreviewVersionOfAParserDoesntConsumeAnyInput() { var testMethod = PreviewParserDemo.Parse(" testMethod "); Assert.AreEqual("testMethod", testMethod); } private Parser<ICommented<string>> Identifier4 => from id in Parse.Identifier(Parse.Letter, Parse.LetterOrDigit).Commented(this) select id; [Test] public void CommentedParserStripsOutLeadingCommentsAndSingleTrailingCommentThatStartsOnTheSameLine() { // whitespace only var result = Identifier4.Parse(" \t hello123 \t\r\n "); Assert.AreEqual("hello123", result.Value); Assert.False(result.LeadingComments.Any()); Assert.False(result.TrailingComments.Any()); // trailing comments result = Identifier4.End().Parse(" \t hello123 // what's that? "); Assert.AreEqual("hello123", result.Value); Assert.False(result.LeadingComments.Any()); Assert.True(result.TrailingComments.Any()); Assert.AreEqual("what's that?", result.TrailingComments.First().Trim()); // leading and trailing comments result = Identifier4.Parse(@" // leading comments! /* more leading comments! */ helloWorld // trailing comments! // more trailing comments! (that don't belong to the parsed value)"); Assert.AreEqual("helloWorld", result.Value); Assert.AreEqual(2, result.LeadingComments.Count()); Assert.AreEqual("leading comments!", result.LeadingComments.First().Trim()); Assert.AreEqual("more leading comments!", result.LeadingComments.Last().Trim()); Assert.AreEqual(1, result.TrailingComments.Count()); Assert.AreEqual("trailing comments!", result.TrailingComments.First().Trim()); // multiple leading and trailing comments result = Identifier4.Parse(@" // leading comments! /* multiline leading comments this is the second line */ test321 // trailing comments! /* --==-- */"); Assert.AreEqual("test321", result.Value); Assert.AreEqual(2, result.LeadingComments.Count()); Assert.AreEqual("leading comments!", result.LeadingComments.First().Trim()); Assert.True(result.LeadingComments.Last().Trim().StartsWith("multiline leading comments")); Assert.True(result.LeadingComments.Last().Trim().EndsWith("this is the second line")); Assert.False(result.TrailingComments.Any()); } [Test] public void CommentedParserAcceptsMultipleTrailingCommentsAsLongAsTheyStartOnTheSameLine() { // trailing comments var result = Identifier4.Parse(" \t hello123 /* one */ /* two */ /* " + @" three */ // this is not a trailing comment // neither this"); Assert.AreEqual("hello123", result.Value); Assert.False(result.LeadingComments.Any()); Assert.True(result.TrailingComments.Any()); var trailing = result.TrailingComments.ToArray(); Assert.AreEqual(3, trailing.Length); Assert.AreEqual("one", trailing[0].Trim()); Assert.AreEqual("two", trailing[1].Trim()); Assert.AreEqual("three", trailing[2].Trim()); // leading and trailing comments result = Identifier4.Parse(@" // leading comments! /* more leading comments! */ helloWorld /* one*/ // two! // more trailing comments! (that don't belong to the parsed value)"); Assert.AreEqual("helloWorld", result.Value); Assert.AreEqual(2, result.LeadingComments.Count()); Assert.AreEqual("leading comments!", result.LeadingComments.First().Trim()); Assert.AreEqual("more leading comments!", result.LeadingComments.Last().Trim()); trailing = result.TrailingComments.ToArray(); Assert.AreEqual(2, trailing.Length); Assert.AreEqual("one", trailing[0].Trim()); Assert.AreEqual("two!", trailing[1].Trim()); } private Parser<string> OptionalTestParser => from test in Parse.String("test").Text().Optional() from t in Parse.String("t").Text().Optional() from method in Parse.String("method").Text() select test.GetOrElse(string.Empty) + t.GetOrElse(string.Empty) + method; private Parser<string> XOptionalTestParser => from test in Parse.String("test").Text().XOptional() from t in Parse.String("t").Text().Optional() // this part never succeeds from method in Parse.String("method").Text() select test.GetOrElse(string.Empty) + t.GetOrElse(string.Empty) + method; [Test] public void XOptionalParserFailsIfSomeInputIsConsumed() { var result = OptionalTestParser.Parse("testmethod"); Assert.AreEqual("testmethod", result); XOptionalTestParser.Parse("testmethod"); Assert.AreEqual("testmethod", result); result = OptionalTestParser.Parse("method"); Assert.AreEqual("method", result); result = XOptionalTestParser.Parse("method"); Assert.AreEqual("method", result); result = OptionalTestParser.Parse("tmethod"); Assert.AreEqual("tmethod", result); Assert.Throws<ParseException>(() => XOptionalTestParser.Parse("tmethod")); } private Parser<string> DummyNewExpressionTestParser(bool failByDefault) => from z in ApexParser.Toolbox.ParserExtensions.PrevChar(c => !char.IsLetterOrDigit(c), "non-alphanumeric", failByDefault) from n in Parse.String("new").Token().Text() from c in Parse.LetterOrDigit.Many().Token().Text() select $"{n} {c}"; private Parser<string> DummyNewExpressionTestParserWithLeadingChar => from x in Parse.AnyChar from n in DummyNewExpressionTestParser(true) select n; [Test] public void PrevCharParserTests() { var result = DummyNewExpressionTestParserWithLeadingChar.Parse(".new Ex"); Assert.AreEqual("new Ex", result); result = DummyNewExpressionTestParserWithLeadingChar.Parse("?new Ex "); Assert.AreEqual("new Ex", result); Assert.Throws<ParseException>(() => DummyNewExpressionTestParserWithLeadingChar.Parse("xnew Ex")); Assert.Throws<ParseException>(() => DummyNewExpressionTestParserWithLeadingChar.Parse("1new Ex")); Assert.Throws<ParseException>(() => DummyNewExpressionTestParser(true).Parse("new Ex")); Assert.DoesNotThrow(() => DummyNewExpressionTestParser(false).Parse("new Ex")); } } }
42.463127
132
0.59479
[ "MIT" ]
apexsharp/apexparser
ApexSharp.ApexParser.Tests/Toolbox/ParseExtensionTests.cs
14,397
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace Webinar.TranslationDemo.Infrastructure.Common { public class DefinitionCulture { protected DefinitionCulture() { } private static List<CultureInfo> supportedCultures = new List<CultureInfo> { new CultureInfo("es-CO"), new CultureInfo("en-US"), new CultureInfo("fr-FR") }; public static CultureInfo GetCulture(string culture) { var supportCulture = supportedCultures.Find(c => c.Name.Equals(culture)); return supportCulture ?? supportedCultures.First(); } public static List<CultureInfo> DefineCulture() { foreach (var culture in supportedCultures) { culture.NumberFormat.CurrencyDecimalSeparator = ","; culture.NumberFormat.CurrencyGroupSeparator = "."; culture.NumberFormat.NumberDecimalSeparator = ","; culture.NumberFormat.NumberGroupSeparator = "."; culture.NumberFormat.PercentDecimalSeparator = ","; culture.NumberFormat.PercentGroupSeparator = "."; } return supportedCultures; } } }
30.857143
85
0.621914
[ "MIT" ]
EstebanVallejoMorales/TranslationDemo
Webinar.TranslationDemo.Infrastructure.Common/DefinitionCulture.cs
1,298
C#
using System; class Program { static void Main(string[] args) { string personName = Console.ReadLine(); Ferrari ferrari = new Ferrari(personName); Console.WriteLine(ferrari); } }
19.636364
50
0.625
[ "MIT" ]
SimeonShterev/2018.01.22-2018.04.22-CSharpFundamentals
2018.02.12-OOPBasics/2018.02.27-InterfacesAbstrH5/Ferrari/Program.cs
218
C#
using IAttendanceWebAPI.Core.Entities; namespace IAttendanceWebAPI.Core.Repositories { public interface ICourseRepository : IRepository<Course> { } }
20.375
60
0.766871
[ "MIT" ]
ducmeit1/IAttendance-API
IAttendanceWebAPI/Core/Repositories/ICourseRepository.cs
165
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.Events; namespace PokemonBattele { public abstract class UseBagItem { public readonly bool canUseInBattle; public readonly bool canUseOutBattle; public readonly bool NotNeedUseButEffect; public readonly bool UseWhilePokemonCarry; public readonly bool UseForPlay; public readonly string BagItemName = ""; public UseBagItem( bool canUseInBattle, bool canUseOutBattle, bool NotNeedUseButEffect, bool UseWhilePokemonCarry, bool UseForPlay, string ItemName) { this.canUseInBattle = canUseInBattle; this.canUseOutBattle = canUseOutBattle; this.NotNeedUseButEffect = NotNeedUseButEffect; this.UseWhilePokemonCarry = UseWhilePokemonCarry; this.UseForPlay = UseForPlay; BagItemName = ItemName; } public abstract void Effect(BattlePokemonData pokemon); } }
30.108108
63
0.655296
[ "MIT" ]
Avatarchik/Pokemon_Unity3D_Entitas
Assets/Scripts/Data/Bag/UseBagIten/UseBagItem.cs
1,116
C#
// // SelectColorDialog.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2012 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Drawing; using Xwt.Backends; namespace Xwt { public sealed class SelectColorDialog { Color color = Colors.Transparent; string title = ""; bool supportsAlpha; public SelectColorDialog () { } /// <summary> /// Initializes a new instance of the <see cref="Xwt.SelectColorDialog"/> class. /// </summary> /// <param name='title'> /// Title of the dialog /// </param> public SelectColorDialog (string title) { this.title = title; } /// <summary> /// Gets or sets the title of the dialog /// </summary> public string Title { get { return title ?? ""; } set { title = value ?? ""; } } /// <summary> /// Gets or sets the selected color /// </summary> public Color Color { get { return color; } set { color = value; } } public bool SupportsAlpha { get { return supportsAlpha; } set { supportsAlpha = value; } } /// <summary> /// Shows the dialog. /// </summary> public bool Run () { return Run (null); } /// <summary> /// Shows the dialog. /// </summary> public bool Run (WindowFrame parentWindow) { var backend = Toolkit.CurrentEngine.Backend.CreateBackend<ISelectColorDialogBackend> (); try { if (color != Colors.Transparent) backend.Color = color; return backend.Run ((IWindowFrameBackend)Toolkit.CurrentEngine.GetSafeBackend (parentWindow), title, supportsAlpha); } finally { color = backend.Color; backend.Dispose (); } } } }
26.752475
120
0.679127
[ "MIT" ]
DavidKarlas/xwt
Xwt/Xwt/SelectColorDialog.cs
2,702
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("Example.Initialization.MultiAction")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Example.Initialization.MultiAction")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("97d52af1-0ccb-45d6-bcd0-5ed14b784b79")] // 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.945946
84
0.750173
[ "MIT" ]
juniorgasparotto/SysCommand
examples/Example.Initialization.MultiAction/Properties/AssemblyInfo.cs
1,444
C#
using System; using System.Collections; using System.IO; using MbUnit.Core.Framework; using MbUnit.Framework; using System.Reflection; using MbUnit.Core.Invokers; using MbUnit.Core; namespace MbUnit.Tests.Core.Invokers { /// <summary> /// <see cref="TestFixture"/> for the <see cref="MethodRunInvoker"/> class. /// </summary> [TestFixture] public class MethodRunInvokerTest { [Test] [ExpectedArgumentNullException] public void MethodNull() { MethodRunInvoker invoker = new MethodRunInvoker(new MockRun(), null); } [Test] public void NoArgumentMethod() { MethodInfo mi = typeof(HelloWorld).GetMethod("NoArgument"); MethodRunInvoker invoker = new MethodRunInvoker(new MockRun(), mi); HelloWorld hw = new HelloWorld(); invoker.Execute(hw,new ArrayList()); Assert.IsTrue(hw.Executed); } [Test] public void OneArgumentMethod() { MethodInfo mi = typeof(HelloWorld).GetMethod("OneArgument"); MethodRunInvoker invoker = new MethodRunInvoker(new MockRun(), mi); HelloWorld hw = new HelloWorld(); ArrayList args = new ArrayList(); args.Add("Hello"); invoker.Execute(hw,args); Assert.IsTrue(hw.Executed); Assert.AreEqual(args[0], hw.Arg); } internal class HelloWorld { private bool executed = false; private string arg=null; public bool Executed { get { return executed; } } public string Arg { get { return this.arg; } } public void NoArgument() { Console.WriteLine("NoArgument executed"); this.executed = true; } public void OneArgument(string arg) { Console.WriteLine("OneArgument executed with {0}",arg); this.executed = true; this.arg = arg; } } } }
27.011494
82
0.496596
[ "ECL-2.0", "Apache-2.0" ]
Gallio/mbunit-v2
src/mbunit/MbUnit.Tests/Core/Invokers/MethodRunInvokerTest.cs
2,352
C#