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 |
|---|---|---|---|---|---|---|---|---|
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("Silence.Macro")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Silence.Macro")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("63b186aa-962c-4a5f-90ee-268bbb5377f2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.810811 | 84 | 0.744103 | [
"MIT"
] | MisterDr/silence | Silence.Macro/Properties/AssemblyInfo.cs | 1,402 | 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("SQ06. Sequence N-M")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SQ06. Sequence N-M")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1a6e07b4-4a69-481e-9619-56ec681e1435")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.945946 | 84 | 0.744302 | [
"MIT"
] | spzvtbg/Data-Structures-January-2018 | 01. Linear DS/SQ06. Sequence N-M/Properties/AssemblyInfo.cs | 1,407 | C# |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// The class FacPadronController was not generated because FAC_Padron does not have a primary key.
| 28 | 98 | 0.816667 | [
"MIT"
] | saludnqn/prosane | RIS_Publico/RIS_Publico/generated/FacPadronController.cs | 420 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
public class Node<T>
{
T data;
Node<T> link;
public Node(T data, Node<T> link)
{
this.data = data;
this.link = link;
}
}
}
| 16.222222 | 41 | 0.523973 | [
"MIT"
] | jonjelliott1/Data-Structures-and-Algorithms | ConsoleApp1/ConsoleApp1/Node.cs | 294 | C# |
using LaplacianHDR.Helpers;
using System;
using System.Drawing;
using System.Windows.Forms;
using UMapx.Imaging;
namespace LaplacianHDR
{
public partial class Form5 : Form
{
#region Private data
ExposureFusion fusion;
Bitmap[] images;
#endregion
#region Form voids
public Form5()
{
InitializeComponent();
trackBar1.MouseUp += new MouseEventHandler(trackBar1_MouseUp);
trackBar1.MouseWheel += (sender, e) => ((HandledMouseEventArgs)e).Handled = true;
trackBar1.KeyDown += (sender, e) => ((KeyEventArgs)e).Handled = true;
}
private void Form5_Load(object sender, EventArgs e)
{
pictureBox1.Image = Apply(images);
}
public Bitmap Apply(params Bitmap[] images)
{
this.fusion = new ExposureFusion(int.MaxValue, float.Parse(textBox2.Text));
return this.fusion.Apply(images);
}
public Bitmap[] Images
{
set
{
int length = value.Length;
images = new Bitmap[length];
for (int i = 0; i < length; i++)
{
images[i] = ImageHelper.Crop(value[i], pictureBox1.Width);
}
}
get
{
return images;
}
}
private void button1_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
#endregion
#region TrackBars
private void trackBar1_Scroll(object sender, EventArgs e)
{
textBox2.Text = (trackBar1.Value / 100.0 + 0.1).ToString();
}
void trackBar1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
trackBar1.Value = 45;
trackBar1_Scroll(sender, e);
}
pictureBox1.Image = Apply(images);
}
#endregion
}
}
| 26.935897 | 93 | 0.526416 | [
"MIT"
] | UMapx/Local-Laplacian-filters | sources/forms/Form5.cs | 2,103 | C# |
using System;
using System.Data;
using System.Reflection;
using Autofac.Extras.IocManager;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Stove.Data;
using Stove.Extensions;
namespace Stove.EntityFrameworkCore
{
public class EfCoreActiveTransactionProvider : IActiveTransactionProvider, ITransientDependency
{
private static readonly MethodInfo getDbContextMethod = typeof(IDbContextProvider<StoveDbContext>)
.GetMethod(nameof(IDbContextProvider<StoveDbContext>.GetDbContext));
private readonly IScopeResolver _scopeResolver;
public EfCoreActiveTransactionProvider(IScopeResolver scopeResolver)
{
_scopeResolver = scopeResolver;
}
public IDbTransaction GetActiveTransaction(ActiveTransactionProviderArgs args)
{
return GetDbContext(args).Database.CurrentTransaction?.GetDbTransaction();
}
public IDbConnection GetActiveConnection(ActiveTransactionProviderArgs args)
{
return GetDbContext(args).Database.GetDbConnection();
}
private DbContext GetDbContext(ActiveTransactionProviderArgs args)
{
var dbContextType = (Type)args["ContextType"];
Type dbContextProviderType = typeof(IDbContextProvider<>).MakeGenericType(dbContextType);
object dbContextProvider = _scopeResolver.Resolve(dbContextProviderType);
var dbContext = getDbContextMethod.Invoke(dbContextProvider, null).As<DbContext>();
return dbContext;
}
}
}
| 33.93617 | 106 | 0.725392 | [
"MIT"
] | eraydin/Stove | src/Stove.EntityFrameworkCore/EntityFrameworkCore/EfCoreActiveTransactionProvider.cs | 1,597 | C# |
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace Rich.HaoDanKu.Response
{
/// <summary>
/// 定时拉取API返回参数
/// </summary>
public class TimingItemsResponse: HaoDanKuResponse
{
[JsonPropertyName("data")]
public List<TimingItemsData > Data { get; set; }
}
public class TimingItemsData
{
/// <summary>
/// 自增ID
/// </summary>
[JsonPropertyName("product_id")]
public int ProductId { get; set; }
/// <summary>
/// 宝贝ID
/// </summary>
[JsonPropertyName("itemid")]
public long ItemId { get; set; }
/// <summary>
/// 宝贝标题
/// </summary>
[JsonPropertyName("itemtitle")]
public string Itemtitle { get; set; }
/// <summary>
/// 宝贝短标题
/// </summary>
[JsonPropertyName("itemshorttitle")]
public string ItemShortTitle { get; set; }
/// <summary>
/// 宝贝推荐语
/// </summary>
[JsonPropertyName("itemdesc")]
public string Itemdesc { get; set; }
/// <summary>
/// 在售价
/// </summary>
[JsonPropertyName("itemprice")]
public float ItemPrice { get; set; }
/// <summary>
/// 宝贝月销量
/// </summary>
[JsonPropertyName("itemsale")]
public int ItemSale { get; set; }
/// <summary>
/// 宝贝近2小时跑单
/// </summary>
[JsonPropertyName("itemsale2")]
public int Itemsale2 { get; set; }
/// <summary>
/// 当天销量
/// </summary>
[JsonPropertyName("todaysale")]
public int Todaysale { get; set; }
/// <summary>
/// 宝贝主图原始图像(由于图片原图过大影响加载速度,建议加上后缀_310x310.jpg,如https://img.alicdn.com/imgextra/i2/3412518427/TB26gs7bb7U5uJjSZFFXXaYHpXa_!!3412518427.jpg_310x310.jpg)
/// </summary>
[JsonPropertyName("itempic")]
public string ItemPic { get; set; }
/// <summary>
/// 推广长图(带http://img-haodanku-com.cdn.fudaiapp.com/0_553757100845_1509175123.jpg-600进行访问)
/// </summary>
[JsonPropertyName("itempic_copy")]
public string ItempicCopy { get; set; }
/// <summary>
/// 商品类目:1女装,2男装,3内衣,4美妆,5配饰,6鞋品,7箱包,8儿童,9母婴,10居家,11美食,12数码,13家电,14其他,15车品,16文体,17宠物
/// </summary>
[JsonPropertyName("fqcat")]
public int Fqcat { get; set; }
/// <summary>
/// 宝贝券后价
/// </summary>
[JsonPropertyName("itemendprice")]
public float ItemEndPrice { get; set; }
/// <summary>
/// 店铺类型:天猫(B)淘宝店(C)
/// </summary>
[JsonPropertyName("shoptype")]
public string Shoptype { get; set; }
/// <summary>
/// 优惠券链接
/// </summary>
[JsonPropertyName("couponurl")]
public string Couponurl { get; set; }
/// <summary>
/// 优惠券金额
/// </summary>
[JsonPropertyName("couponmoney")]
public float CouponMoney { get; set; }
/// <summary>
/// 是否为品牌产品(1是)
/// </summary>
[JsonPropertyName("is_brand")]
public int IsBrand { get; set; }
/// <summary>
/// 是否为直播(1是)
/// </summary>
[JsonPropertyName("is_live")]
public int IsLive { get; set; }
/// <summary>
/// 推广导购文案
/// </summary>
[JsonPropertyName("guide_article")]
public string GuideArticle { get; set; }
/// <summary>
/// 商品视频ID(id大于0的为有视频单,视频拼接地址http://cloud.video.taobao.com/play/u/1/p/1/e/6/t/1/+videoid+.mp4)
/// </summary>
[JsonPropertyName("videoid")]
public long VideoId { get; set; }
/// <summary>
/// 活动类型:普通活动聚划算淘抢购
/// </summary>
[JsonPropertyName("activity_type")]
public string ActivityType { get; set; }
/// <summary>
/// 营销计划链接
/// </summary>
[JsonPropertyName("planlink")]
public string Planlink { get; set; }
/// <summary>
/// 店主的userid
/// </summary>
[JsonPropertyName("userid")]
public long UserId { get; set; }
/// <summary>
/// 店铺掌柜名
/// </summary>
[JsonPropertyName("sellernick")]
public string Sellernick { get; set; }
/// <summary>
/// 店铺名
/// </summary>
[JsonPropertyName("shopname")]
public string ShopName { get; set; }
/// <summary>
/// 佣金计划:隐藏营销
/// </summary>
[JsonPropertyName("tktype")]
public string Tktype { get; set; }
/// <summary>
/// 佣金比例
/// </summary>
[JsonPropertyName("tkrates")]
public float Tkrates { get; set; }
/// <summary>
/// 是否村淘(1是)
/// </summary>
[JsonPropertyName("cuntao")]
public int Cuntao { get; set; }
/// <summary>
/// 预计可得(宝贝价格 * 佣金比例 / 100)
/// </summary>
[JsonPropertyName("tkmoney")]
public float Tkmoney { get; set; }
/// <summary>
/// 当天优惠券领取量
/// </summary>
[JsonPropertyName("couponreceive2")]
public int Couponreceive2 { get; set; }
/// <summary>
/// 优惠券总数量
/// </summary>
[JsonPropertyName("couponnum")]
public int CouponNum { get; set; }
/// <summary>
/// 优惠券使用条件
/// </summary>
[JsonPropertyName("couponexplain")]
public string Couponexplain { get; set; }
/// <summary>
/// 优惠券开始时间
/// </summary>
[JsonPropertyName("couponstarttime")]
public int CouponStartTime { get; set; }
/// <summary>
/// 优惠券结束时间
/// </summary>
[JsonPropertyName("couponendtime")]
public int CouponendTime { get; set; }
/// <summary>
/// 活动开始时间
/// </summary>
[JsonPropertyName("start_time")]
public int StartTime { get; set; }
/// <summary>
/// 活动结束时间
/// </summary>
[JsonPropertyName("end_time")]
public int EndTime { get; set; }
/// <summary>
/// 发布时间
/// </summary>
[JsonPropertyName("starttime")]
public int Starttime { get; set; }
/// <summary>
/// 举报处理条件0未举报1为待处理2为忽略3为下架
/// </summary>
[JsonPropertyName("report_status")]
public int ReportStatus { get; set; }
/// <summary>
/// 好单指数
/// </summary>
[JsonPropertyName("general_index")]
public int GeneralIndex { get; set; }
/// <summary>
/// 放单人名号
/// </summary>
[JsonPropertyName("seller_name")]
public string SellerName { get; set; }
/// <summary>
/// 折扣力度
/// </summary>
[JsonPropertyName("discount")]
public float Discount { get; set; }
}
}
| 26.139098 | 159 | 0.502085 | [
"MIT"
] | Jesn/Rich.HaoDanKu | Rich.HaoDanKu/Response/Storage/TimingItemsResponse.cs | 7,689 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.ComponentModel;
namespace Azure.ResourceManager.NetworkFunction.Models
{
/// <summary> Emission destination type. </summary>
public readonly partial struct EmissionDestinationType : IEquatable<EmissionDestinationType>
{
private readonly string _value;
/// <summary> Initializes a new instance of <see cref="EmissionDestinationType"/>. </summary>
/// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
public EmissionDestinationType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
private const string AzureMonitorValue = "AzureMonitor";
/// <summary> AzureMonitor. </summary>
public static EmissionDestinationType AzureMonitor { get; } = new EmissionDestinationType(AzureMonitorValue);
/// <summary> Determines if two <see cref="EmissionDestinationType"/> values are the same. </summary>
public static bool operator ==(EmissionDestinationType left, EmissionDestinationType right) => left.Equals(right);
/// <summary> Determines if two <see cref="EmissionDestinationType"/> values are not the same. </summary>
public static bool operator !=(EmissionDestinationType left, EmissionDestinationType right) => !left.Equals(right);
/// <summary> Converts a string to a <see cref="EmissionDestinationType"/>. </summary>
public static implicit operator EmissionDestinationType(string value) => new EmissionDestinationType(value);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => obj is EmissionDestinationType other && Equals(other);
/// <inheritdoc />
public bool Equals(EmissionDestinationType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
/// <inheritdoc />
public override string ToString() => _value;
}
}
| 47.102041 | 142 | 0.699307 | [
"MIT"
] | v-kaifazhang/azure-sdk-for-net | sdk/networkfunction/Azure.ResourceManager.NetworkFunction/src/Generated/Models/EmissionDestinationType.cs | 2,308 | C# |
using Alabo.Cloud.Cms.BookDonae.Domain.Entities;
using Alabo.Domains.Repositories;
using MongoDB.Bson;
namespace Alabo.Cloud.Cms.BookDonae.Domain.Repositories
{
public interface IBookDonaeInfoRepository : IRepository<BookDonaeInfo, ObjectId>
{
}
} | 26 | 84 | 0.792308 | [
"MIT"
] | tongxin3267/alabo | src/05.cloud/09-Alabo.Cloud.Cms/BookDonae/Domain/Repositories/IBookDonaeInfoRepository.cs | 260 | C# |
using System.Collections.Generic;
using System.Text;
namespace Automated.Arca.Libraries
{
public static class StringExtensions
{
public static string JoinWithFormat( this IEnumerable<string> texts, string format, string separator )
{
StringBuilder sb = new StringBuilder();
var enumerator = texts.GetEnumerator();
bool hasMore = enumerator.MoveNext();
while( hasMore )
{
if( enumerator.Current != null )
sb.AppendFormat( format, enumerator.Current );
hasMore = enumerator.MoveNext();
if( hasMore )
sb.Append( separator );
}
return sb.ToString();
}
}
}
| 20.366667 | 104 | 0.692308 | [
"MIT"
] | georgehara/Arca | Automated.Arca.Libraries/StringExtensions.cs | 613 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// </auto-generated>
namespace Microsoft.Azure.Management.Network.Fluent.Models
{
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Virtual Router Peering resource.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class VirtualRouterPeeringInner : Management.ResourceManager.Fluent.SubResource
{
/// <summary>
/// Initializes a new instance of the VirtualRouterPeeringInner class.
/// </summary>
public VirtualRouterPeeringInner()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the VirtualRouterPeeringInner class.
/// </summary>
/// <param name="peerAsn">Peer ASN.</param>
/// <param name="peerIp">Peer IP.</param>
/// <param name="provisioningState">The provisioning state of the
/// resource. Possible values include: 'Succeeded', 'Updating',
/// 'Deleting', 'Failed'</param>
/// <param name="name">Name of the virtual router peering that is
/// unique within a virtual router.</param>
/// <param name="etag">A unique read-only string that changes whenever
/// the resource is updated.</param>
/// <param name="type">Peering type.</param>
public VirtualRouterPeeringInner(string id = default(string), long? peerAsn = default(long?), string peerIp = default(string), ProvisioningState provisioningState = default(ProvisioningState), string name = default(string), string etag = default(string), string type = default(string))
: base(id)
{
PeerAsn = peerAsn;
PeerIp = peerIp;
ProvisioningState = provisioningState;
Name = name;
Etag = etag;
Type = type;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets peer ASN.
/// </summary>
[JsonProperty(PropertyName = "properties.peerAsn")]
public long? PeerAsn { get; set; }
/// <summary>
/// Gets or sets peer IP.
/// </summary>
[JsonProperty(PropertyName = "properties.peerIp")]
public string PeerIp { get; set; }
/// <summary>
/// Gets the provisioning state of the resource. Possible values
/// include: 'Succeeded', 'Updating', 'Deleting', 'Failed'
/// </summary>
[JsonProperty(PropertyName = "properties.provisioningState")]
public ProvisioningState ProvisioningState { get; private set; }
/// <summary>
/// Gets or sets name of the virtual router peering that is unique
/// within a virtual router.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Gets a unique read-only string that changes whenever the resource
/// is updated.
/// </summary>
[JsonProperty(PropertyName = "etag")]
public string Etag { get; private set; }
/// <summary>
/// Gets peering type.
/// </summary>
[JsonProperty(PropertyName = "type")]
public string Type { get; private set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (PeerAsn > 4294967295)
{
throw new ValidationException(ValidationRules.InclusiveMaximum, "PeerAsn", 4294967295);
}
if (PeerAsn < 0)
{
throw new ValidationException(ValidationRules.InclusiveMinimum, "PeerAsn", 0);
}
}
}
}
| 36.45 | 293 | 0.594193 | [
"MIT"
] | Azure/azure-libraries-for-net | src/ResourceManagement/Network/Generated/Models/VirtualRouterPeeringInner.cs | 4,374 | C# |
/* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using OpenSearch.OpenSearch.Xunit.XunitPlumbing;
using Osc;
namespace Tests.Mapping.Types.Shape
{
public class ShapeTest
{
[Shape(
Orientation = ShapeOrientation.ClockWise,
Coerce = true)]
public object Full { get; set; }
[Shape]
public object Minimal { get; set; }
}
public class ShapeAttributeTests : AttributeTestsBase<ShapeTest>
{
protected override object ExpectJson => new
{
properties = new
{
full = new
{
type = "shape",
orientation = "clockwise",
coerce = true
},
minimal = new
{
type = "shape"
}
}
};
}
}
| 26.09375 | 65 | 0.717365 | [
"Apache-2.0"
] | MaxKsyunz/opensearch-net | tests/Tests/Mapping/Types/Specialized/Shape/ShapeAttributeTests.cs | 1,670 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using LVK.Configuration;
using LVK.Core.Services;
using LVK.Logging;
namespace WinFormsSandbox
{
internal class MyBackgroundService : IBackgroundService
{
[NotNull]
private readonly ILogger _Logger;
[NotNull]
private readonly IConfigurationElementWithDefault<ConfigurationElement> _Configuration;
public MyBackgroundService([NotNull] ILogger logger, [NotNull] IConfiguration configuration)
{
if (configuration is null)
throw new ArgumentNullException(nameof(configuration));
_Logger = logger ?? throw new ArgumentNullException(nameof(logger));
_Configuration = configuration.Element<ConfigurationElement>("Test").WithDefault(new ConfigurationElement());
}
public async Task Execute(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
_Logger.LogInformation(_Configuration.Value().Value);
await Task.Delay(1000, cancellationToken);
}
}
}
} | 30.615385 | 121 | 0.678392 | [
"MIT"
] | FeatureToggleStudy/LVK | WinFormsSandbox/MyBackgroundService.cs | 1,194 | C# |
/*
* Copyright (c) 2007 by Michael L. Taylor
* All rights reserved.
*/
#region Imports
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using FluentAssertions;
using P3Net.Kraken.ComponentModel;
using P3Net.Kraken.UnitTesting;
#endregion
namespace Tests.P3Net.Kraken.ComponentModel
{
[TestClass]
public class NotifyPropertyChangeTests : UnitTest
{
#region Tests
#region PropertyChanged
[TestMethod]
public void PropertyChanged_RaisedWithNoHandler ()
{
var target = new TestNotifyPropertyChange();
//Act
target.Value = 4;
//Assert
target.PropertyChangedWasRaised("Value").Should().BeTrue();
}
[TestMethod]
public void PropertyChanged_CallsHandler ()
{
var target = new TestNotifyPropertyChange();
//Act
bool actual = false;
target.PropertyChanged += ( o, e ) =>
{
if (e.PropertyName == "Value")
actual = true;
};
target.Value = 4;
//Assert
actual.Should().BeTrue();
}
#endregion
#region PropertyChanging
[TestMethod]
public void PropertyChanging_RaisedWithNoHandler ()
{
var target = new TestNotifyPropertyChange();
//Act
target.Value = 4;
//Assert
target.PropertyChangingWasRaised("Value").Should().BeTrue();
}
[TestMethod]
public void PropertyChanging_CallsHandler ()
{
var target = new TestNotifyPropertyChange();
//Act
bool actual = false;
target.PropertyChanging += ( o, e ) =>
{
if (e.PropertyName == "Value")
actual = true;
};
target.Value = 4;
//Assert
actual.Should().BeTrue();
}
#endregion
#endregion
#region Private Members
private class TestNotifyPropertyChange : NotifyPropertyChange
{
public int Value
{
get { return m_value; }
set
{
this.OnPropertyChanging("Value");
m_value = value;
this.OnPropertyChanged("Value");
}
}
public bool PropertyChangingWasRaised ( string propertyName )
{
return m_propertyChanging.Contains(propertyName);
}
public bool PropertyChangedWasRaised ( string propertyName )
{
return m_propertyChanged.Contains(propertyName);
}
protected override void OnPropertyChanged ( string propertyName )
{
base.OnPropertyChanged(propertyName);
m_propertyChanged.Add(propertyName);
}
protected override void OnPropertyChanging ( string propertyName )
{
base.OnPropertyChanging(propertyName);
m_propertyChanging.Add(propertyName);
}
private int m_value;
private List<string> m_propertyChanged = new List<string>();
private List<string> m_propertyChanging = new List<string>();
}
#endregion
}
} | 25.482014 | 78 | 0.527103 | [
"MIT"
] | CoolDadTx/Kraken | Tests/Tests.P3Net.Kraken/ComponentModel/NotifyPropertyChangeTests.cs | 3,542 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
public class BasicStackOperations
{
public static void Main()
{
string[] commands = Console.ReadLine()
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var n = double.Parse(commands[0]);
var s = double.Parse(commands[1]);
var x = double.Parse(commands[2]);
Stack<double> numbers = new Stack<double>();
List<double> input = Console.ReadLine()
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(double.Parse).ToList();
for (int i = 0; i < n; i++)
{
numbers.Push(input[i]);
}
for (int i = 0; i < s; i++)
{
numbers.Pop();
}
if (numbers.Contains(x))
{
Console.WriteLine("true");
}
else if(numbers.Count == 0)
{
Console.WriteLine("0");
}
else
{
Console.WriteLine(numbers.Min());
}
}
} | 24.348837 | 104 | 0.509074 | [
"MIT"
] | ChrisPam/CSharpAdvanced | 02.StacksAndQueuesExcercise/02.BasicStackOperations/Program.cs | 1,049 | C# |
//
// Copyright (C) 2017 Trinidad Sibajas Bodoque
//
// 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 UnityEngine;
using UnityEditor;
using System;
namespace Trisibo
{
[CustomPropertyDrawer(typeof(DelayedAsset))]
public class DelayedAssetDrawer : PropertyDrawer
{
bool isDraggingValidProxy;
/// <summary>
/// <see cref="PropertyDrawer.OnGUI(Rect, SerializedProperty, GUIContent)"/> implementation.
/// </summary>
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
// Check if the field has a type attribute, and get the type:
DelayedAssetTypeAttribute typeAttribute = (DelayedAssetTypeAttribute)Attribute.GetCustomAttribute(fieldInfo, typeof(DelayedAssetTypeAttribute));
Type desiredType = typeAttribute != null ? typeAttribute.Type : typeof(UnityEngine.Object);
// If a DelayedAssetProxy is being dragged into the slot, and the type of the referenced asset matches the desired type, allow to set it:
if (Event.current.type == EventType.DragUpdated)
{
UnityEngine.Object draggedObject = DragAndDrop.objectReferences.Length == 0 ? null : DragAndDrop.objectReferences[0];
isDraggingValidProxy = draggedObject is DelayedAssetProxy && ((DelayedAssetProxy)draggedObject).Asset != null && desiredType.IsAssignableFrom(((DelayedAssetProxy)draggedObject).Asset.GetType()) && position.Contains(Event.current.mousePosition);
}
else if (Event.current.type == EventType.DragExited)
{
isDraggingValidProxy = false;
}
if (isDraggingValidProxy)
desiredType = typeof(DelayedAssetProxy);
// Begin the property:
EditorGUI.BeginProperty(position, label, property);
EditorGUI.BeginDisabledGroup(EditorApplication.isPlayingOrWillChangePlaymode);
// Draw the property:
SerializedProperty assetProperty = property.FindPropertyRelative("asset");
label.text = GetFormattedLabel(label.text);
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = property.hasMultipleDifferentValues;
UnityEngine.Object newAsset = EditorGUI.ObjectField(position, label, assetProperty.objectReferenceValue, desiredType, false);
EditorGUI.showMixedValue = false;
bool hasChanged = EditorGUI.EndChangeCheck();
if (hasChanged)
assetProperty.objectReferenceValue = newAsset;
// If an object has been assigned, check if there is some problem with it:
if (hasChanged && newAsset != null)
{
string error = DelayedAsset.CheckForErrors(newAsset, DelayedAsset.GetResourcesRelativeAssetPath(AssetDatabase.GetAssetPath(newAsset)));
if (error != null)
{
assetProperty.objectReferenceValue = null;
EditorUtility.DisplayDialog("Delayed asset error", error, "OK");
Debug.LogError("<b>Delayed asset error:</b> " + error);
}
}
// End of the property:
EditorGUI.EndDisabledGroup();
EditorGUI.EndProperty();
}
/// <summary>
/// Gets a formatted label for the field.
/// </summary>
/// <param name="originalLabel">The original label.</param>
/// <returns>The formatted label.</returns>
static string GetFormattedLabel(string originalLabel)
{
return "{" + originalLabel + "}";
}
}
}
| 38.918699 | 266 | 0.654481 | [
"MIT"
] | Trisibo/Unity-delayed-asset | Assets/Trisibo/Delayed asset/Editor/DelayedAssetDrawer.cs | 4,789 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.ServiceFabric.Client.Http
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ServiceFabric.Client;
using Microsoft.ServiceFabric.Client.Http.Serialization;
using Microsoft.ServiceFabric.Common;
using Newtonsoft.Json;
/// <summary>
/// Class containing methods for performing PropertyManagementClient operataions.
/// </summary>
internal partial class PropertyManagementClient : IPropertyManagementClient
{
private readonly ServiceFabricHttpClient httpClient;
/// <summary>
/// Initializes a new instance of the PropertyManagementClient class.
/// </summary>
/// <param name="httpClient">ServiceFabricHttpClient instance.</param>
public PropertyManagementClient(ServiceFabricHttpClient httpClient)
{
this.httpClient = httpClient;
}
/// <inheritdoc />
public Task CreateNameAsync(
FabricName fabricName,
long? serverTimeout = 60,
CancellationToken cancellationToken = default(CancellationToken))
{
fabricName.ThrowIfNull(nameof(fabricName));
serverTimeout?.ThrowIfOutOfInclusiveRange("serverTimeout", 1, 4294967295);
var requestId = Guid.NewGuid().ToString();
var url = "Names/$/Create";
var queryParams = new List<string>();
// Append to queryParams if not null.
serverTimeout?.AddToQueryParameters(queryParams, $"timeout={serverTimeout}");
queryParams.Add("api-version=6.0");
url += "?" + string.Join("&", queryParams);
string content;
using (var sw = new StringWriter())
{
NameDescriptionConverter.Serialize(new JsonTextWriter(sw), fabricName);
content = sw.ToString();
}
HttpRequestMessage RequestFunc()
{
var request = new HttpRequestMessage()
{
Method = HttpMethod.Post,
Content = new StringContent(content, Encoding.UTF8)
};
request.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
return request;
}
return this.httpClient.SendAsync(RequestFunc, url, requestId, cancellationToken);
}
/// <inheritdoc />
public Task GetNameExistsInfoAsync(
string nameId,
long? serverTimeout = 60,
CancellationToken cancellationToken = default(CancellationToken))
{
nameId.ThrowIfNull(nameof(nameId));
serverTimeout?.ThrowIfOutOfInclusiveRange("serverTimeout", 1, 4294967295);
var requestId = Guid.NewGuid().ToString();
var url = "Names/{nameId}";
url = url.Replace("{nameId}", nameId);
var queryParams = new List<string>();
// Append to queryParams if not null.
serverTimeout?.AddToQueryParameters(queryParams, $"timeout={serverTimeout}");
queryParams.Add("api-version=6.0");
url += "?" + string.Join("&", queryParams);
HttpRequestMessage RequestFunc()
{
var request = new HttpRequestMessage()
{
Method = HttpMethod.Get,
};
return request;
}
return this.httpClient.SendAsync(RequestFunc, url, requestId, cancellationToken);
}
/// <inheritdoc />
public Task DeleteNameAsync(
string nameId,
long? serverTimeout = 60,
CancellationToken cancellationToken = default(CancellationToken))
{
nameId.ThrowIfNull(nameof(nameId));
serverTimeout?.ThrowIfOutOfInclusiveRange("serverTimeout", 1, 4294967295);
var requestId = Guid.NewGuid().ToString();
var url = "Names/{nameId}";
url = url.Replace("{nameId}", nameId);
var queryParams = new List<string>();
// Append to queryParams if not null.
serverTimeout?.AddToQueryParameters(queryParams, $"timeout={serverTimeout}");
queryParams.Add("api-version=6.0");
url += "?" + string.Join("&", queryParams);
HttpRequestMessage RequestFunc()
{
var request = new HttpRequestMessage()
{
Method = HttpMethod.Delete,
};
return request;
}
return this.httpClient.SendAsync(RequestFunc, url, requestId, cancellationToken);
}
/// <inheritdoc />
public Task<PagedData<string>> GetSubNameInfoListAsync(
string nameId,
bool? recursive = false,
ContinuationToken continuationToken = default(ContinuationToken),
long? serverTimeout = 60,
CancellationToken cancellationToken = default(CancellationToken))
{
nameId.ThrowIfNull(nameof(nameId));
serverTimeout?.ThrowIfOutOfInclusiveRange("serverTimeout", 1, 4294967295);
var requestId = Guid.NewGuid().ToString();
var url = "Names/{nameId}/$/GetSubNames";
url = url.Replace("{nameId}", nameId);
var queryParams = new List<string>();
// Append to queryParams if not null.
recursive?.AddToQueryParameters(queryParams, $"Recursive={recursive}");
continuationToken?.AddToQueryParameters(queryParams, $"ContinuationToken={continuationToken.ToString()}");
serverTimeout?.AddToQueryParameters(queryParams, $"timeout={serverTimeout}");
queryParams.Add("api-version=6.0");
url += "?" + string.Join("&", queryParams);
HttpRequestMessage RequestFunc()
{
var request = new HttpRequestMessage()
{
Method = HttpMethod.Get,
};
return request;
}
return this.httpClient.SendAsyncGetResponseAsPagedData(RequestFunc, url, JsonReaderExtensions.ReadValueAsString, requestId, cancellationToken);
}
/// <inheritdoc />
public Task<PagedData<PropertyInfo>> GetPropertyInfoListAsync(
string nameId,
bool? includeValues = false,
ContinuationToken continuationToken = default(ContinuationToken),
long? serverTimeout = 60,
CancellationToken cancellationToken = default(CancellationToken))
{
nameId.ThrowIfNull(nameof(nameId));
serverTimeout?.ThrowIfOutOfInclusiveRange("serverTimeout", 1, 4294967295);
var requestId = Guid.NewGuid().ToString();
var url = "Names/{nameId}/$/GetProperties";
url = url.Replace("{nameId}", nameId);
var queryParams = new List<string>();
// Append to queryParams if not null.
includeValues?.AddToQueryParameters(queryParams, $"IncludeValues={includeValues}");
continuationToken?.AddToQueryParameters(queryParams, $"ContinuationToken={continuationToken.ToString()}");
serverTimeout?.AddToQueryParameters(queryParams, $"timeout={serverTimeout}");
queryParams.Add("api-version=6.0");
url += "?" + string.Join("&", queryParams);
HttpRequestMessage RequestFunc()
{
var request = new HttpRequestMessage()
{
Method = HttpMethod.Get,
};
return request;
}
return this.httpClient.SendAsyncGetResponseAsPagedData(RequestFunc, url, PropertyInfoConverter.Deserialize, requestId, cancellationToken);
}
/// <inheritdoc />
public Task PutPropertyAsync(
string nameId,
PropertyDescription propertyDescription,
long? serverTimeout = 60,
CancellationToken cancellationToken = default(CancellationToken))
{
nameId.ThrowIfNull(nameof(nameId));
propertyDescription.ThrowIfNull(nameof(propertyDescription));
serverTimeout?.ThrowIfOutOfInclusiveRange("serverTimeout", 1, 4294967295);
var requestId = Guid.NewGuid().ToString();
var url = "Names/{nameId}/$/GetProperty";
url = url.Replace("{nameId}", nameId);
var queryParams = new List<string>();
// Append to queryParams if not null.
serverTimeout?.AddToQueryParameters(queryParams, $"timeout={serverTimeout}");
queryParams.Add("api-version=6.0");
url += "?" + string.Join("&", queryParams);
string content;
using (var sw = new StringWriter())
{
PropertyDescriptionConverter.Serialize(new JsonTextWriter(sw), propertyDescription);
content = sw.ToString();
}
HttpRequestMessage RequestFunc()
{
var request = new HttpRequestMessage()
{
Method = HttpMethod.Put,
Content = new StringContent(content, Encoding.UTF8)
};
request.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
return request;
}
return this.httpClient.SendAsync(RequestFunc, url, requestId, cancellationToken);
}
/// <inheritdoc />
public Task<PropertyInfo> GetPropertyInfoAsync(
string nameId,
string propertyName,
long? serverTimeout = 60,
CancellationToken cancellationToken = default(CancellationToken))
{
nameId.ThrowIfNull(nameof(nameId));
propertyName.ThrowIfNull(nameof(propertyName));
serverTimeout?.ThrowIfOutOfInclusiveRange("serverTimeout", 1, 4294967295);
var requestId = Guid.NewGuid().ToString();
var url = "Names/{nameId}/$/GetProperty";
url = url.Replace("{nameId}", nameId);
var queryParams = new List<string>();
// Append to queryParams if not null.
propertyName?.AddToQueryParameters(queryParams, $"PropertyName={propertyName}");
serverTimeout?.AddToQueryParameters(queryParams, $"timeout={serverTimeout}");
queryParams.Add("api-version=6.0");
url += "?" + string.Join("&", queryParams);
HttpRequestMessage RequestFunc()
{
var request = new HttpRequestMessage()
{
Method = HttpMethod.Get,
};
return request;
}
return this.httpClient.SendAsyncGetResponse(RequestFunc, url, PropertyInfoConverter.Deserialize, requestId, cancellationToken);
}
/// <inheritdoc />
public Task DeletePropertyAsync(
string nameId,
string propertyName,
long? serverTimeout = 60,
CancellationToken cancellationToken = default(CancellationToken))
{
nameId.ThrowIfNull(nameof(nameId));
propertyName.ThrowIfNull(nameof(propertyName));
serverTimeout?.ThrowIfOutOfInclusiveRange("serverTimeout", 1, 4294967295);
var requestId = Guid.NewGuid().ToString();
var url = "Names/{nameId}/$/GetProperty";
url = url.Replace("{nameId}", nameId);
var queryParams = new List<string>();
// Append to queryParams if not null.
propertyName?.AddToQueryParameters(queryParams, $"PropertyName={propertyName}");
serverTimeout?.AddToQueryParameters(queryParams, $"timeout={serverTimeout}");
queryParams.Add("api-version=6.0");
url += "?" + string.Join("&", queryParams);
HttpRequestMessage RequestFunc()
{
var request = new HttpRequestMessage()
{
Method = HttpMethod.Delete,
};
return request;
}
return this.httpClient.SendAsync(RequestFunc, url, requestId, cancellationToken);
}
/// <inheritdoc />
public Task<PropertyBatchInfo> SubmitPropertyBatchAsync(
string nameId,
PropertyBatchDescriptionList propertyBatchDescriptionList,
long? serverTimeout = 60,
CancellationToken cancellationToken = default(CancellationToken))
{
nameId.ThrowIfNull(nameof(nameId));
propertyBatchDescriptionList.ThrowIfNull(nameof(propertyBatchDescriptionList));
serverTimeout?.ThrowIfOutOfInclusiveRange("serverTimeout", 1, 4294967295);
var requestId = Guid.NewGuid().ToString();
var url = "Names/{nameId}/$/GetProperties/$/SubmitBatch";
url = url.Replace("{nameId}", nameId);
var queryParams = new List<string>();
// Append to queryParams if not null.
serverTimeout?.AddToQueryParameters(queryParams, $"timeout={serverTimeout}");
queryParams.Add("api-version=6.0");
url += "?" + string.Join("&", queryParams);
string content;
using (var sw = new StringWriter())
{
PropertyBatchDescriptionListConverter.Serialize(new JsonTextWriter(sw), propertyBatchDescriptionList);
content = sw.ToString();
}
HttpRequestMessage RequestFunc()
{
var request = new HttpRequestMessage()
{
Method = HttpMethod.Post,
Content = new StringContent(content, Encoding.UTF8)
};
request.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
return request;
}
return this.httpClient.SendAsyncGetResponse(RequestFunc, url, PropertyBatchInfoConverter.Deserialize, requestId, cancellationToken);
}
}
}
| 42.51567 | 155 | 0.574616 | [
"MIT"
] | aL3891/service-fabric-client-dotnet | src/Microsoft.ServiceFabric.Client.Http/PropertyManagementClient.cs | 14,923 | C# |
//Write a program that finds all prime numbers in the range [1...10 000 000]. Use the Sieve of Eratosthenes algorithm.
using System;
using System.IO;
class PrimeNumbers
{
static void Main()
{
int[] nums = new int[10000001];
int[] primeNumbers = new int[664579];
for (int i = 1; i <= 10000000; i++)
{
nums[i] = i;
}
int k = 0;
for (int i = 2; i <= 10000000; i++)
{
if (nums[i] != 0)
{
// Console.Write(nums[i] + " ");
primeNumbers[k] = i;
k++;
for (int j = i + i; j <= 10000000; j += i)
{
nums[j] = 0;
}
}
}
string fileName = "Prime Numbers.txt";
string strPath = Path.Combine(Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory),fileName);
FileStream fs = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
for (int i = 0; i < primeNumbers.Length; i++)
{
sw.Write("{0},\n", primeNumbers[i]);
Console.Write(primeNumbers[i] + ",");
}
}
}
| 27.0625 | 125 | 0.492687 | [
"MIT"
] | NikolaiMishev/Telerik-Academy | Module-1/02.CSharp Part 2/Arrays/15.Prime numbers/PrimeNumbers.cs | 1,301 | C# |
namespace PowerRunner.Settings
{
using System.ComponentModel;
using System.Xml.Serialization;
/// <summary>
/// User settings
/// </summary>
[XmlRootAttribute(ElementName = "PowerRunner", IsNullable = false)]
public class GlobalSettings
{
#region Fields
internal static event PropertyChangedEventHandler PropertyChanged;
private static GlobalSettings main;
#endregion
#region Enumerations
#endregion
#region Properties
[XmlIgnore]
internal static GlobalSettings Main
{
get
{
if (main == null)
{
main = new GlobalSettings();
}
return main;
}
}
#endregion
#region Methods
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
| 20.163636 | 89 | 0.532011 | [
"Apache-2.0"
] | mechgt/power-runner | PowerRunner/Settings/GlobalSettings.cs | 1,111 | C# |
using System;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
namespace RockLib.Messaging
{
/// <summary>
/// Defines extension methods for implementations of the <see cref="IReceiverMessage"/>
/// interface.
/// </summary>
public static class ReceiverMessageExtensions
{
/// <summary>
/// Indicates that the message was successfully processed and should not
/// be redelivered.
/// </summary>
/// <param name="receiverMessage">The message to acknowledge.</param>
[Obsolete("Use AcknowledgeAsync method instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Acknowledge(this IReceiverMessage receiverMessage) =>
Sync(() => receiverMessage.AcknowledgeAsync());
/// <summary>
/// Indicates that the message was not successfully processed but should be
/// (or should be allowed to be) redelivered.
/// </summary>
/// <param name="receiverMessage">The message to roll back.</param>
[Obsolete("Use RollbackAsync method instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Rollback(this IReceiverMessage receiverMessage) =>
Sync(() => receiverMessage.RollbackAsync());
/// <summary>
/// Indicates that the message could not be successfully processed and should
/// not be redelivered.
/// </summary>
/// <param name="receiverMessage">The message to reject.</param>
[Obsolete("Use RejectAsync method instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Reject(this IReceiverMessage receiverMessage) =>
Sync(() => receiverMessage.RejectAsync());
/// <summary>
/// Indicates that the message was successfully processed and should not
/// be redelivered.
/// </summary>
/// <param name="receiverMessage">The message to acknowledge.</param>
public static Task AcknowledgeAsync(this IReceiverMessage receiverMessage) =>
receiverMessage.AcknowledgeAsync(CancellationToken.None);
/// <summary>
/// Indicates that the message was not successfully processed but should be
/// (or should be allowed to be) redelivered.
/// </summary>
/// <param name="receiverMessage">The message to roll back.</param>
public static Task RollbackAsync(this IReceiverMessage receiverMessage) =>
receiverMessage.RollbackAsync(CancellationToken.None);
/// <summary>
/// Indicates that the message could not be successfully processed and should
/// not be redelivered.
/// </summary>
/// <param name="receiverMessage">The message to reject.</param>
public static Task RejectAsync(this IReceiverMessage receiverMessage) =>
receiverMessage.RejectAsync(CancellationToken.None);
private static void Sync(Func<Task> getTaskOfTResult)
{
SynchronizationContext old = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(null);
getTaskOfTResult().GetAwaiter().GetResult();
}
finally
{
SynchronizationContext.SetSynchronizationContext(old);
}
}
/// <summary>
/// Gets the ID of the message, or null if not found in the message's headers.
/// </summary>
/// <param name="receiverMessage">The source <see cref="IReceiverMessage"/> object.</param>
/// <returns>The ID of the message.</returns>
public static string GetMessageId(this IReceiverMessage receiverMessage) =>
receiverMessage.GetHeaders()
.TryGetValue(HeaderNames.MessageId, out string messageId)
? messageId
: null;
/// <summary>
/// Gets a value indicating whether the message's payload was sent compressed,
/// as indicated in the message's headers.
/// </summary>
/// <param name="receiverMessage">The source <see cref="IReceiverMessage"/> object.</param>
/// <returns>Whether the message's payload was sent compressed.</returns>
public static bool IsCompressed(this IReceiverMessage receiverMessage) =>
receiverMessage.GetHeaders()
.TryGetValue(HeaderNames.IsCompressedPayload, out bool isCompressed)
&& isCompressed;
/// <summary>
/// Gets a value indicating whether the original message was constructed with
/// a byte array, as indicated in the message's headers. A value of false
/// means that the original message was constructed with a string.
/// </summary>
/// <param name="receiverMessage">The source <see cref="IReceiverMessage"/> object.</param>
/// <returns>Whether the original message was constructed with a byte array.</returns>
public static bool IsBinary(this IReceiverMessage receiverMessage) =>
receiverMessage.GetHeaders()
.TryGetValue(HeaderNames.IsBinaryPayload, out bool isBinary)
&& isBinary;
/// <summary>
/// Gets the originating system of the message, or null if not found in the
/// message's headers.
/// </summary>
/// <param name="receiverMessage">The source <see cref="IReceiverMessage"/> object.</param>
/// <returns>The originating system of the message.</returns>
public static string GetOriginatingSystem(this IReceiverMessage receiverMessage) =>
receiverMessage.GetHeaders()
.TryGetValue(HeaderNames.OriginatingSystem, out string originatingSystem)
? originatingSystem
: null;
private static HeaderDictionary GetHeaders(this IReceiverMessage receiverMessage) =>
(receiverMessage ?? throw new ArgumentNullException(nameof(receiverMessage))).Headers;
/// <summary>
/// Creates an instance of <see cref="SenderMessage"/> that is equivalent to the
/// specified <see cref="IReceiverMessage"/>.
/// </summary>
/// <param name="receiverMessage">The source <see cref="IReceiverMessage"/> object.</param>
/// <param name="validateHeaderValue">
/// A function that validates header values, returning either the value passed to it
/// or an equivalent value. If a value is invalid, the function should attempt to
/// convert it to another type that is valid. If a value cannot be converted, the
/// function should throw an exception.
/// </param>
/// <returns>
/// A new <see cref="SenderMessage"/> instance that is equivalent to the specified
/// <paramref name="receiverMessage"/> parameter.
/// </returns>
public static SenderMessage ToSenderMessage(this IReceiverMessage receiverMessage, Func<object, object> validateHeaderValue = null) =>
new SenderMessage(receiverMessage, validateHeaderValue);
}
} | 48.33557 | 142 | 0.639267 | [
"MIT"
] | Finity/RockLib.Messaging | RockLib.Messaging/ReceiverMessageExtensions.cs | 7,204 | C# |
namespace TestSetControlLibrary
{
partial class MasterDataDisplay
{
/// <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()
{
this.tabPageAOStatus = new System.Windows.Forms.TabPage();
this.tabPageBOStatus = new System.Windows.Forms.TabPage();
this.tabPageCounter = new System.Windows.Forms.TabPage();
this.tabPageAnalog = new System.Windows.Forms.TabPage();
this.tabPageBinary = new System.Windows.Forms.TabPage();
this.tabControlMeas = new System.Windows.Forms.TabControl();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.issueToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.analogOutputToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.binaryOutputToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.flickerFreeListViewBinary = new TestSetControlLibrary.FlickerFreeListView();
this.columnHeaderIndex = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeaderValue = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.flickerFreeListViewAnalog = new TestSetControlLibrary.FlickerFreeListView();
this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.flickerFreeListViewCounter = new TestSetControlLibrary.FlickerFreeListView();
this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader4 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.flickerFreeListViewBOStatus = new TestSetControlLibrary.FlickerFreeListView();
this.columnHeader5 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader6 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.flickerFreeListViewAOStatus = new TestSetControlLibrary.FlickerFreeListView();
this.columnHeader7 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader8 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.tabPageAOStatus.SuspendLayout();
this.tabPageBOStatus.SuspendLayout();
this.tabPageCounter.SuspendLayout();
this.tabPageAnalog.SuspendLayout();
this.tabPageBinary.SuspendLayout();
this.tabControlMeas.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// tabPageAOStatus
//
this.tabPageAOStatus.Controls.Add(this.flickerFreeListViewAOStatus);
this.tabPageAOStatus.Location = new System.Drawing.Point(4, 22);
this.tabPageAOStatus.Name = "tabPageAOStatus";
this.tabPageAOStatus.Padding = new System.Windows.Forms.Padding(3);
this.tabPageAOStatus.Size = new System.Drawing.Size(830, 475);
this.tabPageAOStatus.TabIndex = 4;
this.tabPageAOStatus.Text = "Analog Output Status";
this.tabPageAOStatus.UseVisualStyleBackColor = true;
//
// tabPageBOStatus
//
this.tabPageBOStatus.Controls.Add(this.flickerFreeListViewBOStatus);
this.tabPageBOStatus.Location = new System.Drawing.Point(4, 22);
this.tabPageBOStatus.Name = "tabPageBOStatus";
this.tabPageBOStatus.Padding = new System.Windows.Forms.Padding(3);
this.tabPageBOStatus.Size = new System.Drawing.Size(830, 475);
this.tabPageBOStatus.TabIndex = 3;
this.tabPageBOStatus.Text = "Binary Output Status";
this.tabPageBOStatus.UseVisualStyleBackColor = true;
//
// tabPageCounter
//
this.tabPageCounter.Controls.Add(this.flickerFreeListViewCounter);
this.tabPageCounter.Location = new System.Drawing.Point(4, 22);
this.tabPageCounter.Name = "tabPageCounter";
this.tabPageCounter.Padding = new System.Windows.Forms.Padding(3);
this.tabPageCounter.Size = new System.Drawing.Size(830, 475);
this.tabPageCounter.TabIndex = 2;
this.tabPageCounter.Text = "Counter";
this.tabPageCounter.UseVisualStyleBackColor = true;
//
// tabPageAnalog
//
this.tabPageAnalog.Controls.Add(this.flickerFreeListViewAnalog);
this.tabPageAnalog.Location = new System.Drawing.Point(4, 22);
this.tabPageAnalog.Name = "tabPageAnalog";
this.tabPageAnalog.Padding = new System.Windows.Forms.Padding(3);
this.tabPageAnalog.Size = new System.Drawing.Size(830, 475);
this.tabPageAnalog.TabIndex = 1;
this.tabPageAnalog.Text = "Analog Input";
this.tabPageAnalog.UseVisualStyleBackColor = true;
//
// tabPageBinary
//
this.tabPageBinary.Controls.Add(this.flickerFreeListViewBinary);
this.tabPageBinary.Location = new System.Drawing.Point(4, 22);
this.tabPageBinary.Name = "tabPageBinary";
this.tabPageBinary.Padding = new System.Windows.Forms.Padding(3);
this.tabPageBinary.Size = new System.Drawing.Size(830, 475);
this.tabPageBinary.TabIndex = 0;
this.tabPageBinary.Text = "Binary Input";
this.tabPageBinary.UseVisualStyleBackColor = true;
//
// tabControlMeas
//
this.tabControlMeas.Controls.Add(this.tabPageBinary);
this.tabControlMeas.Controls.Add(this.tabPageAnalog);
this.tabControlMeas.Controls.Add(this.tabPageCounter);
this.tabControlMeas.Controls.Add(this.tabPageBOStatus);
this.tabControlMeas.Controls.Add(this.tabPageAOStatus);
this.tabControlMeas.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControlMeas.Location = new System.Drawing.Point(0, 24);
this.tabControlMeas.Name = "tabControlMeas";
this.tabControlMeas.SelectedIndex = 0;
this.tabControlMeas.Size = new System.Drawing.Size(838, 501);
this.tabControlMeas.TabIndex = 0;
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.issueToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.menuStrip1.Size = new System.Drawing.Size(838, 24);
this.menuStrip1.TabIndex = 1;
this.menuStrip1.Text = "menuStrip1";
//
// issueToolStripMenuItem
//
this.issueToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.analogOutputToolStripMenuItem,
this.binaryOutputToolStripMenuItem});
this.issueToolStripMenuItem.Name = "issueToolStripMenuItem";
this.issueToolStripMenuItem.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.issueToolStripMenuItem.Size = new System.Drawing.Size(45, 20);
this.issueToolStripMenuItem.Text = "Issue";
//
// analogOutputToolStripMenuItem
//
this.analogOutputToolStripMenuItem.Name = "analogOutputToolStripMenuItem";
this.analogOutputToolStripMenuItem.Size = new System.Drawing.Size(155, 22);
this.analogOutputToolStripMenuItem.Text = "Analog Output";
this.analogOutputToolStripMenuItem.Click += new System.EventHandler(this.analogOutputToolStripMenuItem_Click);
//
// binaryOutputToolStripMenuItem
//
this.binaryOutputToolStripMenuItem.Name = "binaryOutputToolStripMenuItem";
this.binaryOutputToolStripMenuItem.Size = new System.Drawing.Size(155, 22);
this.binaryOutputToolStripMenuItem.Text = "Binary Output";
//
// flickerFreeListViewBinary
//
this.flickerFreeListViewBinary.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.flickerFreeListViewBinary.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeaderIndex,
this.columnHeaderValue});
this.flickerFreeListViewBinary.Dock = System.Windows.Forms.DockStyle.Fill;
this.flickerFreeListViewBinary.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.flickerFreeListViewBinary.Location = new System.Drawing.Point(3, 3);
this.flickerFreeListViewBinary.MultiSelect = false;
this.flickerFreeListViewBinary.Name = "flickerFreeListViewBinary";
this.flickerFreeListViewBinary.Size = new System.Drawing.Size(824, 469);
this.flickerFreeListViewBinary.TabIndex = 0;
this.flickerFreeListViewBinary.UseCompatibleStateImageBehavior = false;
this.flickerFreeListViewBinary.View = System.Windows.Forms.View.Details;
//
// columnHeaderIndex
//
this.columnHeaderIndex.Text = "Index";
//
// columnHeaderValue
//
this.columnHeaderValue.Text = "Value";
//
// flickerFreeListViewAnalog
//
this.flickerFreeListViewAnalog.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.flickerFreeListViewAnalog.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2});
this.flickerFreeListViewAnalog.Dock = System.Windows.Forms.DockStyle.Fill;
this.flickerFreeListViewAnalog.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.flickerFreeListViewAnalog.Location = new System.Drawing.Point(3, 3);
this.flickerFreeListViewAnalog.MultiSelect = false;
this.flickerFreeListViewAnalog.Name = "flickerFreeListViewAnalog";
this.flickerFreeListViewAnalog.Size = new System.Drawing.Size(824, 469);
this.flickerFreeListViewAnalog.TabIndex = 1;
this.flickerFreeListViewAnalog.UseCompatibleStateImageBehavior = false;
this.flickerFreeListViewAnalog.View = System.Windows.Forms.View.Details;
//
// columnHeader1
//
this.columnHeader1.Text = "Index";
//
// columnHeader2
//
this.columnHeader2.Text = "Value";
//
// flickerFreeListViewCounter
//
this.flickerFreeListViewCounter.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.flickerFreeListViewCounter.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader3,
this.columnHeader4});
this.flickerFreeListViewCounter.Dock = System.Windows.Forms.DockStyle.Fill;
this.flickerFreeListViewCounter.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.flickerFreeListViewCounter.Location = new System.Drawing.Point(3, 3);
this.flickerFreeListViewCounter.MultiSelect = false;
this.flickerFreeListViewCounter.Name = "flickerFreeListViewCounter";
this.flickerFreeListViewCounter.Size = new System.Drawing.Size(824, 469);
this.flickerFreeListViewCounter.TabIndex = 2;
this.flickerFreeListViewCounter.UseCompatibleStateImageBehavior = false;
this.flickerFreeListViewCounter.View = System.Windows.Forms.View.Details;
//
// columnHeader3
//
this.columnHeader3.Text = "Index";
//
// columnHeader4
//
this.columnHeader4.Text = "Value";
//
// flickerFreeListViewBOStatus
//
this.flickerFreeListViewBOStatus.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.flickerFreeListViewBOStatus.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader5,
this.columnHeader6});
this.flickerFreeListViewBOStatus.Dock = System.Windows.Forms.DockStyle.Fill;
this.flickerFreeListViewBOStatus.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.flickerFreeListViewBOStatus.Location = new System.Drawing.Point(3, 3);
this.flickerFreeListViewBOStatus.MultiSelect = false;
this.flickerFreeListViewBOStatus.Name = "flickerFreeListViewBOStatus";
this.flickerFreeListViewBOStatus.Size = new System.Drawing.Size(824, 469);
this.flickerFreeListViewBOStatus.TabIndex = 3;
this.flickerFreeListViewBOStatus.UseCompatibleStateImageBehavior = false;
this.flickerFreeListViewBOStatus.View = System.Windows.Forms.View.Details;
//
// columnHeader5
//
this.columnHeader5.Text = "Index";
//
// columnHeader6
//
this.columnHeader6.Text = "Value";
//
// flickerFreeListViewAOStatus
//
this.flickerFreeListViewAOStatus.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.flickerFreeListViewAOStatus.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader7,
this.columnHeader8});
this.flickerFreeListViewAOStatus.Dock = System.Windows.Forms.DockStyle.Fill;
this.flickerFreeListViewAOStatus.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.flickerFreeListViewAOStatus.Location = new System.Drawing.Point(3, 3);
this.flickerFreeListViewAOStatus.MultiSelect = false;
this.flickerFreeListViewAOStatus.Name = "flickerFreeListViewAOStatus";
this.flickerFreeListViewAOStatus.Size = new System.Drawing.Size(824, 469);
this.flickerFreeListViewAOStatus.TabIndex = 4;
this.flickerFreeListViewAOStatus.UseCompatibleStateImageBehavior = false;
this.flickerFreeListViewAOStatus.View = System.Windows.Forms.View.Details;
//
// columnHeader7
//
this.columnHeader7.Text = "Index";
//
// columnHeader8
//
this.columnHeader8.Text = "Value";
//
// MasterDataDisplay
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tabControlMeas);
this.Controls.Add(this.menuStrip1);
this.Name = "MasterDataDisplay";
this.Size = new System.Drawing.Size(838, 525);
this.tabPageAOStatus.ResumeLayout(false);
this.tabPageBOStatus.ResumeLayout(false);
this.tabPageCounter.ResumeLayout(false);
this.tabPageAnalog.ResumeLayout(false);
this.tabPageBinary.ResumeLayout(false);
this.tabControlMeas.ResumeLayout(false);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TabPage tabPageAOStatus;
private FlickerFreeListView flickerFreeListViewAOStatus;
private System.Windows.Forms.ColumnHeader columnHeader7;
private System.Windows.Forms.ColumnHeader columnHeader8;
private System.Windows.Forms.TabPage tabPageBOStatus;
private FlickerFreeListView flickerFreeListViewBOStatus;
private System.Windows.Forms.ColumnHeader columnHeader5;
private System.Windows.Forms.ColumnHeader columnHeader6;
private System.Windows.Forms.TabPage tabPageCounter;
private FlickerFreeListView flickerFreeListViewCounter;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.ColumnHeader columnHeader4;
private System.Windows.Forms.TabPage tabPageAnalog;
private FlickerFreeListView flickerFreeListViewAnalog;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.TabPage tabPageBinary;
private FlickerFreeListView flickerFreeListViewBinary;
private System.Windows.Forms.ColumnHeader columnHeaderIndex;
private System.Windows.Forms.ColumnHeader columnHeaderValue;
private System.Windows.Forms.TabControl tabControlMeas;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem issueToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem analogOutputToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem binaryOutputToolStripMenuItem;
}
}
| 54.435294 | 122 | 0.654096 | [
"ECL-2.0",
"Apache-2.0"
] | demirelcan/dnp3 | windows/TestSetControlLibrary/MasterDataDisplay.Designer.cs | 18,510 | C# |
using System;
using UnityEngine;
namespace Mirror
{
// message packing all in one place, instead of constructing headers in all
// kinds of different places
//
// MsgType (2 bytes)
// Content (ContentSize bytes)
public static class MessagePacking
{
// message header size
internal const int HeaderSize = sizeof(ushort);
public static ushort GetId<T>() where T : struct, NetworkMessage
{
// paul: 16 bits is enough to avoid collisions
// - keeps the message size small
// - in case of collisions, Mirror will display an error
return (ushort)(typeof(T).FullName.GetStableHashCode() & 0xFFFF);
}
// pack message before sending
// -> NetworkWriter passed as arg so that we can use .ToArraySegment
// and do an allocation free send before recycling it.
public static void Pack<T>(T message, NetworkWriter writer)
where T : struct, NetworkMessage
{
ushort msgType = GetId<T>();
writer.WriteUShort(msgType);
// serialize message into writer
writer.Write(message);
}
// unpack message after receiving
// -> pass NetworkReader so it's less strange if we create it in here
// and pass it upwards.
// -> NetworkReader will point at content afterwards!
public static bool Unpack(NetworkReader messageReader, out ushort msgType)
{
// read message type
try
{
msgType = messageReader.ReadUShort();
return true;
}
catch (System.IO.EndOfStreamException)
{
msgType = 0;
return false;
}
}
internal static NetworkMessageDelegate WrapHandler<T, C>(Action<C, T> handler, bool requireAuthentication)
where T : struct, NetworkMessage
where C : NetworkConnection
=> (conn, reader, channelId) =>
{
// protect against DOS attacks if attackers try to send invalid
// data packets to crash the server/client. there are a thousand
// ways to cause an exception in data handling:
// - invalid headers
// - invalid message ids
// - invalid data causing exceptions
// - negative ReadBytesAndSize prefixes
// - invalid utf8 strings
// - etc.
//
// let's catch them all and then disconnect that connection to avoid
// further attacks.
T message = default;
// record start position for NetworkDiagnostics because reader might contain multiple messages if using batching
int startPos = reader.Position;
try
{
if (requireAuthentication && !conn.isAuthenticated)
{
// message requires authentication, but the connection was not authenticated
Debug.LogWarning($"Closing connection: {conn}. Received message {typeof(T)} that required authentication, but the user has not authenticated yet");
conn.Disconnect();
return;
}
//Debug.Log($"ConnectionRecv {conn} msgType:{typeof(T)} content:{BitConverter.ToString(reader.buffer.Array, reader.buffer.Offset, reader.buffer.Count)}");
// if it is a value type, just use default(T)
// otherwise allocate a new instance
message = reader.Read<T>();
}
catch (Exception exception)
{
Debug.LogError($"Closed connection: {conn}. This can happen if the other side accidentally (or an attacker intentionally) sent invalid data. Reason: {exception}");
conn.Disconnect();
return;
}
finally
{
int endPos = reader.Position;
// TODO: Figure out the correct channel
NetworkDiagnostics.OnReceive(message, channelId, endPos - startPos);
}
// user handler exception should not stop the whole server
try
{
// user implemented handler
handler((C)conn, message);
}
catch (Exception e)
{
Debug.LogError($"Exception in MessageHandler: {e.GetType().Name} {e.Message}\n{e.StackTrace}");
conn.Disconnect();
}
};
}
}
| 38.957983 | 179 | 0.553063 | [
"MIT"
] | jacktoka/Mirror | Assets/Mirror/Runtime/MessagePacking.cs | 4,636 | C# |
using System.IO;
namespace DioDocs.FastReportBuilder
{
public class ReportBuilderFactory : IReportBuilderFactory
{
public IReportBuilder<TReportRow> Create<TReportRow>(Stream template)
{
return new ReportBuilder<TReportRow>(template);
}
}
} | 24.166667 | 77 | 0.682759 | [
"MIT"
] | nuitsjp/DioDocs.FastReportBuilder | Source/DioDocs.FastReportBuilder/ReportBuilderFactory.cs | 292 | C# |
using System;
using System.Reflection;
namespace BLToolkit.Common
{
using Reflection;
/// <summary>
/// Converts a base data type to another base data type.
/// </summary>
/// <typeparam name="T">Destination data type.</typeparam>
/// <typeparam name="P">Source data type.</typeparam>
public static class Convert<T,P>
{
/// <summary>
/// Represents a method that converts an object from one type to another type.
/// </summary>
/// <param name="p">A value to convert to the target type.</param>
/// <returns>The <typeparamref name="T"/> that represents the converted <paramref name="p"/>.</returns>
public delegate T ConvertMethod(P p);
/// <summary>Converts an array of one type to an array of another type.</summary>
/// <returns>An array of the target type containing the converted elements from the source array.</returns>
/// <param name="src">The one-dimensional, zero-based <see cref="T:System.Array"></see> to convert to a target type.</param>
/// <exception cref="T:System.ArgumentNullException">array is null.-or-converter is null.</exception>
public static T[] FromArray(P[] src)
{
// Note that type parameters are in reverse order.
//
return Array.ConvertAll<P,T>(src, (Converter<P,T>)((object)From));
}
///<summary>
/// Converter instance.
///</summary>
public static ConvertMethod From = GetConverter();
///<summary>
/// Initializes converter instance.
///</summary>
///<returns>Converter instance.</returns>
public static ConvertMethod GetConverter()
{
Type from = typeof(P);
Type to = typeof(T);
// Convert to the same type.
//
if (to == from)
return (ConvertMethod)(object)(Convert<P,P>.ConvertMethod)SameType;
if (from.IsEnum)
from = Enum.GetUnderlyingType(from);
if (to.IsEnum)
to = Enum.GetUnderlyingType(to);
if (TypeHelper.IsSameOrParent(to, from))
return Assignable;
string methodName;
if (TypeHelper.IsNullable(to))
methodName = "ToNullable" + to.GetGenericArguments()[0].Name;
else if (to.IsArray)
methodName = "To" + to.GetElementType().Name + "Array";
else
methodName = "To" + to.Name;
MethodInfo mi = typeof(Convert).GetMethod(methodName,
BindingFlags.Public | BindingFlags.Static | BindingFlags.ExactBinding,
null, new Type[] {from}, null) ?? FindTypeCastOperator(to) ?? FindTypeCastOperator(from);
if (mi == null && TypeHelper.IsNullable(to))
{
// To-nullable conversion.
// We have to use reflection to enforce some constraints.
//
Type toType = to.GetGenericArguments()[0];
Type fromType = TypeHelper.IsNullable(from)? from.GetGenericArguments()[0]: from;
methodName = TypeHelper.IsNullable(from) ? "FromNullable" : "From";
mi = typeof(NullableConvert<,>)
.MakeGenericType(toType, fromType)
.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static);
}
if (mi != null)
return (ConvertMethod)Delegate.CreateDelegate(typeof(ConvertMethod), mi);
return Default;
}
private static MethodInfo FindTypeCastOperator(Type t)
{
foreach (MethodInfo mi in t.GetMethods(BindingFlags.Public | BindingFlags.Static))
{
if (mi.IsSpecialName && mi.ReturnType == typeof(T) && (mi.Name == "op_Implicit" || mi.Name == "op_Explicit"))
{
ParameterInfo[] parameters = mi.GetParameters();
if (1 == parameters.Length && parameters[0].ParameterType == typeof(P))
return mi;
}
}
return null;
}
private static P SameType (P p) { return p; }
private static T Assignable(P p) { return (T)(object)p; }
private static T Default (P p) { return (T)System.Convert.ChangeType(p, typeof(T)); }
}
/// <summary>
/// Converts a base data type to another base data type.
/// </summary>
/// <typeparam name="T">Destination data type.</typeparam>
public static class ConvertTo<T>
{
/// <summary>Returns an <typeparamref name="T"/> whose value is equivalent to the specified value.</summary>
/// <returns>The <typeparamref name="T"/> that represents the converted <paramref name="p"/>.</returns>
/// <param name="p">A value to convert to the target type.</param>
public static T From<P>(P p)
{
return Convert<T,P>.From(p);
}
}
internal static class NullableConvert<T,P>
where T: struct
where P: struct
{
public static T? FromNullable(P? p)
{
return p.HasValue? From(p.Value): null;
}
public static T? From(P p)
{
return Convert<T,P>.From(p);
}
}
}
| 31.813793 | 127 | 0.649469 | [
"BSD-2-Clause"
] | EIDSS/EIDSS-Legacy | EIDSS v5/bltoolkit.3.2.dev/Common/ConvertT.cs | 4,613 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Typeracer.Core.Data
{
public struct QuoteData
{
public static string Quote { get; }
= "Hello, my name is Rek'Sai";
public static string Written { get; set; }
= string.Empty;
public static int CurrentIndex;
}
}
| 17.85 | 45 | 0.717087 | [
"Apache-2.0"
] | VectorArtGames/Typeracer | src/Typeracer/Typeracer/Core/Data/QuoteData.cs | 359 | C# |
namespace RatioMaster.Core
{
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
internal class ProcessMemoryReader
{
[DllImport("kernel32.dll")]
internal static extern int CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll")]
internal static extern IntPtr OpenProcess(uint dwDesiredAccess, int bInheritHandle, uint dwProcessId);
[DllImport("kernel32.dll")]
internal static extern int ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [In, Out] byte[] buffer, uint size, out IntPtr lpNumberOfBytesRead);
internal const uint PROCESS_VM_READ = 0x10;
private IntPtr m_hProcess;
private Process m_ReadProcess;
internal ProcessMemoryReader()
{
this.m_hProcess = IntPtr.Zero;
}
internal Process ReadProcess
{
get
{
return this.m_ReadProcess;
}
set
{
this.m_ReadProcess = value;
}
}
internal static void SaveArrayToFile(byte[] arr, string filename)
{
FileStream stream1 = File.OpenWrite(filename);
stream1.Write(arr, 0, arr.Length);
stream1.Close();
}
internal void CloseHandle()
{
if (CloseHandle(this.m_hProcess) == 0)
{
throw new Exception("CloseHandle failed");
}
}
internal void OpenProcess()
{
this.m_hProcess = OpenProcess(0x10, 1, (uint)this.m_ReadProcess.Id);
}
internal byte[] ReadProcessMemory(IntPtr memoryAddress, uint bytesToRead, out int bytesRead)
{
IntPtr pointer;
var buffer = new byte[bytesToRead];
ReadProcessMemory(this.m_hProcess, memoryAddress, buffer, bytesToRead, out pointer);
bytesRead = pointer.ToInt32();
return buffer;
}
}
} | 28.236111 | 160 | 0.581407 | [
"MIT"
] | xas/RatioMaster.NET | Source/RatioMaster.Core.WinApp/ProcessMemoryReader.cs | 2,033 | C# |
using FluentAssertions;
using Moq;
using RestSharp;
using System;
using System.Net.Http;
using WeatherTest.Services;
using Xunit;
namespace WeatherTest.ServicesTests
{
public class BbcWeatherSourceTests
{
[Fact]
public void GivenNullLocationThenThrowArgumentNullException()
{
var client = new Mock<IRestClient>();
var source = new BbcWeatherSource(client.Object);
Action act = () => source.Get(null).Wait();
act.ShouldThrow<ArgumentNullException>();
}
[Fact]
public async void GivenInvocationThenReturnWeatherSourceResult()
{
var location = "bmouth";
var json = JsonBuilder(new TestJsonModel
{
Location = location,
TemperatureCelsius = 100,
TemperatureFahrenheit = 200,
WindSpeedKph = 10,
WindSpeedMph = 5
});
var client = new Mock<IRestClient>();
client.Setup(c => c.ExecuteGetTaskAsync(It.IsAny<IRestRequest>())).ReturnsAsync(new RestResponse
{
Content = json
});
var source = new BbcWeatherSource(client.Object);
var result = await source.Get(location);
result.TemperatureCelsius.Should().Be(100);
result.TemperatureFahrenheit.Should().Be(200);
result.WindSpeedKph.Should().Be(10);
result.WindSpeedMph.Should().Be(5);
}
[Fact]
public void GivenInvocationWhenThereIsHttpRequestExceptionThenThrowException()
{
var location = "bmouth";
var client = new Mock<IRestClient>();
client.Setup(c => c.ExecuteGetTaskAsync(It.IsAny<IRestRequest>()))
.ThrowsAsync(new HttpRequestException());
var source = new BbcWeatherSource(client.Object);
Action act = () => source.Get(location).Wait(); ;
act.ShouldThrow<Exception>();
}
private string JsonBuilder(TestJsonModel model)
{
return "{" + $"\"Location\": \"{model.Location}\"," + $"\"TemperatureFahrenheit\": {model.TemperatureFahrenheit}," +
$"\"WindSpeedKph\": {model.WindSpeedKph}," + $"\"WindSpeedMph\": {model.WindSpeedMph},"
+ $"\"TemperatureCelsius\": {model.TemperatureCelsius}" + "}";
}
}
public class TestJsonModel
{
public string Location { get; set; }
public double TemperatureFahrenheit { get; set; }
public double WindSpeedKph { get; set; }
public double WindSpeedMph { get; set; }
public double TemperatureCelsius { get; set; }
}
}
| 32.761905 | 128 | 0.573038 | [
"Apache-2.0"
] | MooneyHussain/WeatherTest | tests/WeatherTest.ServicesTests/BbcWeatherSourceTests.cs | 2,754 | C# |
using UnityEngine;
using UnityEditor;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
using Chisel;
using Chisel.Core;
using UnityEditor.SceneManagement;
namespace FoundationTests
{
public sealed class TestUtility
{
public static Material GenerateDebugColorMaterial(Color color)
{
var name = "Color: " + color;
var shader = Shader.Find("Unlit/Color");
if (!shader)
return null;
var material = new Material(shader)
{
name = name.Replace(':', '_'),
hideFlags = HideFlags.HideAndDontSave
};
material.SetColor("_Color", color);
return material;
}
public static void CreateBox(Vector3 size, ChiselBrushMaterial brushMaterial, out BrushMesh box)
{
var chiselSurface = new ChiselSurface();
chiselSurface.brushMaterial = brushMaterial;
BrushMeshFactory.CreateBox(Vector3.one, in chiselSurface, out box);
}
public static void ExpectValidBrushWithUserID(ref CSGTreeBrush brush, int userID)
{
CSGNodeType type = CSGTreeNode.Encapsulate(brush.NodeID).Type;
Assert.AreEqual(true, brush.Valid);
Assert.AreNotEqual(0, brush.NodeID);
Assert.AreEqual(userID, brush.UserID);
Assert.AreEqual(CSGNodeType.Brush, type);
}
public static void ExpectInvalidBrush(ref CSGTreeBrush brush)
{
CSGNodeType type = CSGTreeNode.Encapsulate(brush.NodeID).Type;
Assert.AreEqual(false, brush.Valid);
Assert.AreEqual(0, brush.UserID);
Assert.AreEqual(CSGNodeType.None, type);
}
public static void ExpectValidBranchWithUserID(ref CSGTreeBranch branch, int userID)
{
CSGNodeType type = CSGTreeNode.Encapsulate(branch.NodeID).Type;
Assert.AreEqual(true, branch.Valid);
Assert.AreNotEqual(0, branch.NodeID);
Assert.AreEqual(userID, branch.UserID);
Assert.AreEqual(CSGNodeType.Branch, type);
}
public static void ExpectInvalidBranch(ref CSGTreeBranch branch)
{
CSGNodeType type = CSGTreeNode.Encapsulate(branch.NodeID).Type;
Assert.AreEqual(false, branch.Valid);
Assert.AreEqual(0, branch.UserID);
Assert.AreEqual(CSGNodeType.None, type);
}
public static void ExpectValidTreeWithUserID(ref CSGTree model, int userID)
{
CSGNodeType type = CSGTreeNode.Encapsulate(model.NodeID).Type;
Assert.AreEqual(true, model.Valid);
Assert.AreNotEqual(0, model.NodeID);
Assert.AreEqual(userID, model.UserID);
Assert.AreEqual(CSGNodeType.Tree, type);
}
public static void ExpectInvalidTree(ref CSGTree model)
{
CSGNodeType type = CSGTreeNode.Encapsulate(model.NodeID).Type;
Assert.AreEqual(false, model.Valid);
Assert.AreEqual(0, model.UserID);
Assert.AreEqual(CSGNodeType.None, type);
}
}
} | 33.914894 | 104 | 0.618883 | [
"MIT"
] | cr4yz/Chisel.Prototype | Packages/com.chisel.core.tests/Chisel/Core/Tests/CoreTests/TestUtility.cs | 3,190 | C# |
#if !DISABLE_DHT
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using System.Net.BitTorrent.Dht.Messages;
using System.Net.BitTorrent.BEncoding;
using System.Net;
using System.Threading;
using System.Net.BitTorrent.Dht.Tasks;
namespace System.Net.BitTorrent.Dht
{
[TestFixture]
public class MessageHandlingTests
{
//static void Main(string[] args)
//{
// TaskTests t = new TaskTests();
// t.Setup();
// t.BucketRefreshTest();
//}
BEncodedString transactionId = "cc";
DhtEngine engine;
Node node;
TestListener listener;
[SetUp]
public void Setup()
{
listener = new TestListener();
node = new Node(NodeId.Create(), new IPEndPoint(IPAddress.Any, 0));
engine = new DhtEngine(listener);
//engine.Add(node);
}
[TearDown]
public void Teardown()
{
engine.Dispose();
}
[Test]
public void SendPing()
{
engine.Add(node);
engine.TimeOut = TimeSpan.FromMilliseconds(75);
ManualResetEvent handle = new ManualResetEvent(false);
engine.MessageLoop.QuerySent += delegate(object o, SendQueryEventArgs e) {
if (!e.TimedOut && e.Query is Ping)
handle.Set();
if (!e.TimedOut || !(e.Query is Ping))
return;
PingResponse response = new PingResponse(node.Id, e.Query.TransactionId);
listener.RaiseMessageReceived(response, e.EndPoint);
};
Assert.AreEqual(NodeState.Unknown, node.State, "#1");
DateTime lastSeen = node.LastSeen;
Assert.IsTrue(handle.WaitOne(1000, false), "#1a");
Node nnnn = node;
node = engine.RoutingTable.FindNode(nnnn.Id);
Assert.IsTrue (lastSeen < node.LastSeen, "#2");
Assert.AreEqual(NodeState.Good, node.State, "#3");
}
[Test]
public void PingTimeout()
{
engine.TimeOut = TimeSpan.FromHours(1);
// Send ping
Ping ping = new Ping(node.Id);
ping.TransactionId = transactionId;
ManualResetEvent handle = new ManualResetEvent(false);
SendQueryTask task = new SendQueryTask(engine, ping, node);
task.Completed += delegate {
handle.Set();
};
task.Execute();
// Receive response
PingResponse response = new PingResponse(node.Id, transactionId);
listener.RaiseMessageReceived(response, node.EndPoint);
Assert.IsTrue(handle.WaitOne(1000, true), "#0");
engine.TimeOut = TimeSpan.FromMilliseconds(75);
DateTime lastSeen = node.LastSeen;
// Time out a ping
ping = new Ping(node.Id);
ping.TransactionId = (BEncodedString)"ab";
task = new SendQueryTask(engine, ping, node, 4);
task.Completed += delegate { handle.Set(); };
handle.Reset();
task.Execute();
handle.WaitOne();
Assert.AreEqual(4, node.FailedCount, "#1");
Assert.AreEqual(NodeState.Bad, node.State, "#2");
Assert.AreEqual(lastSeen, node.LastSeen, "#3");
}
// void FakePingResponse(object sender, SendQueryEventArgs e)
// {
// if (!e.TimedOut || !(e.Query is Ping))
// return;
//
// SendQueryTask task = (SendQueryTask)e.Task;
// PingResponse response = new PingResponse(task.Target.Id);
// listener.RaiseMessageReceived(response, task.Target.EndPoint);
// }
}
}
#endif | 31.61157 | 89 | 0.555817 | [
"MIT"
] | kanggaogang/BitTorrent | test/BitTorrent.Tests/Dht/MessageHandlingTests.cs | 3,825 | C# |
namespace Sparkle.NetworksStatus.Data.Repositories
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The base of all repository.
/// </summary>
public interface IRepository
{
}
/// <summary>
/// Entity-centric repository
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public interface IRepository<TEntity> : IRepository
{
/// <summary>
/// Begins a query.
/// </summary>
/// <returns></returns>
IList<TEntity> GetAll();
/// <summary>
/// Inserts immediately a new entity in an isolated context.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
TEntity Insert(TEntity item);
/// <summary>
/// Inserts immediately many entities in an isolated context.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
void InsertMany(IList<TEntity> items);
}
/// <summary>
/// Entity-centric abstract repository class with SCUD operations for entities with one primary key (generic).
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <typeparam name="TPrimaryKey"></typeparam>
public interface IRepository<TEntity, TPrimaryKey> : IRepository<TEntity>
{
/// <summary>
/// Gets an entity by its ID.
/// </summary>
/// <param name="id"></param>
/// <returns>the desired entity or null</returns>
TEntity GetById(TPrimaryKey id);
/// <summary>
/// Updates immediately an existing entity in a isolated context.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
TEntity Update(TEntity item);
/// <summary>
/// Deletes immediately an existing entity in a isolated context.
/// </summary>
/// <param name="item"></param>
void Delete(TEntity item);
/// <summary>
/// Deletes immediately an existing entity in a isolated context.
/// </summary>
/// <param name="item"></param>
void Delete(TPrimaryKey id);
}
}
| 30.236842 | 115 | 0.542646 | [
"MPL-2.0"
] | SparkleNetworks/SparkleNetworks | src/Sparkle.NetworksStatus/Data/Repositories/IRepository.cs | 2,300 | C# |
/*
* Copyright (c) Contributors, http://virtual-planets.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
* For an explanation of the license of each contributor and the content it
* covers please see the Licenses directory.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Virtual Universe Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using OpenMetaverse;
using Universe.Framework.Services;
namespace Universe.Modules.Ban
{
public class PresenceInfo
{
public UUID AgentID;
public string LastKnownIP = "";
public string LastKnownViewer = "";
public string LastKnownID0 = "";
public string LastKnownMac = "";
public string Platform = "";
public List<string> KnownIPs = new List<string>();
public List<string> KnownViewers = new List<string>();
public List<string> KnownMacs = new List<string>();
public List<string> KnownID0s = new List<string>();
public List<string> KnownAlts = new List<string>();
public PresenceInfoFlags Flags;
[Flags]
public enum PresenceInfoFlags
{
Clean = 1 << 1,
Suspected = 1 << 2,
Known = 1 << 3,
SuspectedAltAccount = 1 << 4,
SuspectedAltAccountOfKnown = 1 << 5,
SuspectedAltAccountOfSuspected = 1 << 6,
KnownAltAccountOfKnown = 1 << 7,
KnownAltAccountOfSuspected = 1 << 8,
Banned = 1 << 9
}
}
public interface IPresenceInfo : IUniverseDataPlugin
{
PresenceInfo GetPresenceInfo(UUID agentID);
void UpdatePresenceInfo(PresenceInfo agent);
void Check(PresenceInfo info, List<string> viewers, bool includeList);
void Check(List<string> viewers, bool includeList);
}
}
| 42.628205 | 81 | 0.67218 | [
"MIT"
] | johnfelipe/Virtual-Universe | Universe/Modules/World/BannedViewersModule/PresenceInfo.cs | 3,325 | C# |
using System.ComponentModel.DataAnnotations;
namespace dotnetHelloWorld.Models
{
public class Visitor
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
} | 19.272727 | 45 | 0.617925 | [
"Apache-2.0"
] | Appdynamics/cloudfoundry-apps | cf-net-linux/src/dotnetHelloWorld/Models/Visitor.cs | 214 | C# |
/* ##HEADER##
namespace GameCreator.Core
{
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
[AddComponentMenu("")]
public class __CLASS_NAME__ : ICondition
{
public bool satisfied = true;
public override bool Check(GameObject target)
{
return this.satisfied;
}
#if UNITY_EDITOR
public static new string NAME = "Custom/__CLASS_NAME__";
#endif
}
}
##FOOTER## */
| 18.36 | 64 | 0.699346 | [
"MIT"
] | SK0P3iN/Rapid-Prototyping-Unity-Game | Assets/Plugins/GameCreator/Extra/ScriptTemplates/SimpleConditionTemplate.cs | 461 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("PaintTool")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PaintTool")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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")]
| 40.142857 | 93 | 0.745996 | [
"MIT"
] | mawasi/WPFSample | PaintTool/Properties/AssemblyInfo.cs | 2,251 | 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;
using Pulumi.Utilities;
namespace Pulumi.GoogleNative.Datastream.V1
{
public static class GetPrivateConnection
{
/// <summary>
/// Use this method to get details about a private connectivity configuration.
/// </summary>
public static Task<GetPrivateConnectionResult> InvokeAsync(GetPrivateConnectionArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetPrivateConnectionResult>("google-native:datastream/v1:getPrivateConnection", args ?? new GetPrivateConnectionArgs(), options.WithVersion());
/// <summary>
/// Use this method to get details about a private connectivity configuration.
/// </summary>
public static Output<GetPrivateConnectionResult> Invoke(GetPrivateConnectionInvokeArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.Invoke<GetPrivateConnectionResult>("google-native:datastream/v1:getPrivateConnection", args ?? new GetPrivateConnectionInvokeArgs(), options.WithVersion());
}
public sealed class GetPrivateConnectionArgs : Pulumi.InvokeArgs
{
[Input("location", required: true)]
public string Location { get; set; } = null!;
[Input("privateConnectionId", required: true)]
public string PrivateConnectionId { get; set; } = null!;
[Input("project")]
public string? Project { get; set; }
public GetPrivateConnectionArgs()
{
}
}
public sealed class GetPrivateConnectionInvokeArgs : Pulumi.InvokeArgs
{
[Input("location", required: true)]
public Input<string> Location { get; set; } = null!;
[Input("privateConnectionId", required: true)]
public Input<string> PrivateConnectionId { get; set; } = null!;
[Input("project")]
public Input<string>? Project { get; set; }
public GetPrivateConnectionInvokeArgs()
{
}
}
[OutputType]
public sealed class GetPrivateConnectionResult
{
/// <summary>
/// The create time of the resource.
/// </summary>
public readonly string CreateTime;
/// <summary>
/// Display name.
/// </summary>
public readonly string DisplayName;
/// <summary>
/// In case of error, the details of the error in a user-friendly format.
/// </summary>
public readonly Outputs.ErrorResponse Error;
/// <summary>
/// Labels.
/// </summary>
public readonly ImmutableDictionary<string, string> Labels;
/// <summary>
/// The resource's name.
/// </summary>
public readonly string Name;
/// <summary>
/// The state of the Private Connection.
/// </summary>
public readonly string State;
/// <summary>
/// The update time of the resource.
/// </summary>
public readonly string UpdateTime;
/// <summary>
/// VPC Peering Config.
/// </summary>
public readonly Outputs.VpcPeeringConfigResponse VpcPeeringConfig;
[OutputConstructor]
private GetPrivateConnectionResult(
string createTime,
string displayName,
Outputs.ErrorResponse error,
ImmutableDictionary<string, string> labels,
string name,
string state,
string updateTime,
Outputs.VpcPeeringConfigResponse vpcPeeringConfig)
{
CreateTime = createTime;
DisplayName = displayName;
Error = error;
Labels = labels;
Name = name;
State = state;
UpdateTime = updateTime;
VpcPeeringConfig = vpcPeeringConfig;
}
}
}
| 32.354331 | 198 | 0.618155 | [
"Apache-2.0"
] | AaronFriel/pulumi-google-native | sdk/dotnet/Datastream/V1/GetPrivateConnection.cs | 4,109 | C# |
using System;
namespace CRial.xbmcgui
{
public class Window : WindowBase
{
public Window(string name) : base(name)
{
}
public Window(int existingWindowId = -1) : base()
{
Utils.Call(_name + " = Window(" + existingWindowId + ")");
Utils.Call(_name + ".winname = '" + _name + "'");
KSharp.Windows.Add(_name, this);
}
}
} | 24.111111 | 71 | 0.488479 | [
"MIT"
] | CRialDev/KSHarp | KSharp/xbmcgui/Window.cs | 436 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Dapper;
namespace Dommel
{
public static partial class DommelMapper
{
/// <summary>
/// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="id">The id of the entity in the database.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="cancellationToken">Optional cancellation token for the command.</param>
/// <returns>The entity with the corresponding id joined with the specified types.</returns>
public static TReturn Get<T1, T2, TReturn>(this IDbConnection connection, object id, Func<T1, T2, TReturn> map, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where TReturn : class
=> MultiMap<T1, T2, DontMap, DontMap, DontMap, DontMap, DontMap, TReturn>(connection, map, id, transaction).FirstOrDefault();
/// <summary>
/// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="id">The id of the entity in the database.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="cancellationToken">Optional cancellation token for the command.</param>
/// <returns>The entity with the corresponding id joined with the specified types.</returns>
public static async Task<TReturn> GetAsync<T1, T2, TReturn>(this IDbConnection connection, object id, Func<T1, T2, TReturn> map, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where TReturn : class
=> (await MultiMapAsync<T1, T2, DontMap, DontMap, DontMap, DontMap, DontMap, TReturn>(connection, map, id, transaction, cancellationToken: cancellationToken)).FirstOrDefault();
/// <summary>
/// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="id">The id of the entity in the database.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <returns>The entity with the corresponding id joined with the specified types.</returns>
public static TReturn Get<T1, T2, T3, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, TReturn> map, IDbTransaction? transaction = null) where TReturn : class
=> MultiMap<T1, T2, T3, DontMap, DontMap, DontMap, DontMap, TReturn>(connection, map, id, transaction).FirstOrDefault();
/// <summary>
/// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="id">The id of the entity in the database.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="cancellationToken">Optional cancellation token for the command.</param>
/// <returns>The entity with the corresponding id joined with the specified types.</returns>
public static async Task<TReturn> GetAsync<T1, T2, T3, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, TReturn> map, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where TReturn : class
=> (await MultiMapAsync<T1, T2, T3, DontMap, DontMap, DontMap, DontMap, TReturn>(connection, map, id, transaction, cancellationToken: cancellationToken)).FirstOrDefault();
/// <summary>
/// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="T4">The fourth type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="id">The id of the entity in the database.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <returns>The entity with the corresponding id joined with the specified types.</returns>
public static TReturn Get<T1, T2, T3, T4, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, T4, TReturn> map, IDbTransaction? transaction = null) where TReturn : class
=> MultiMap<T1, T2, T3, T4, DontMap, DontMap, DontMap, TReturn>(connection, map, id, transaction).FirstOrDefault();
/// <summary>
/// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="T4">The fourth type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="id">The id of the entity in the database.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="cancellationToken">Optional cancellation token for the command.</param>
/// <returns>The entity with the corresponding id joined with the specified types.</returns>
public static async Task<TReturn> GetAsync<T1, T2, T3, T4, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, T4, TReturn> map, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where TReturn : class
=> (await MultiMapAsync<T1, T2, T3, T4, DontMap, DontMap, DontMap, TReturn>(connection, map, id, transaction, cancellationToken: cancellationToken)).FirstOrDefault();
/// <summary>
/// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="T4">The fourth type parameter.</typeparam>
/// <typeparam name="T5">The fifth type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="id">The id of the entity in the database.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <returns>The entity with the corresponding id joined with the specified types.</returns>
public static TReturn Get<T1, T2, T3, T4, T5, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, T4, T5, TReturn> map,
IDbTransaction? transaction = null) where TReturn : class
=> MultiMap<T1, T2, T3, T4, T5, DontMap, DontMap, TReturn>(connection, map, id, transaction).FirstOrDefault();
/// <summary>
/// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="T4">The fourth type parameter.</typeparam>
/// <typeparam name="T5">The fifth type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="id">The id of the entity in the database.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="cancellationToken">Optional cancellation token for the command.</param>
/// <returns>The entity with the corresponding id joined with the specified types.</returns>
public static async Task<TReturn> GetAsync<T1, T2, T3, T4, T5, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, T4, T5, TReturn> map, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where TReturn : class
=> (await MultiMapAsync<T1, T2, T3, T4, T5, DontMap, DontMap, TReturn>(connection, map, id, transaction, cancellationToken: cancellationToken)).FirstOrDefault();
/// <summary>
/// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="T4">The fourth type parameter.</typeparam>
/// <typeparam name="T5">The fifth type parameter.</typeparam>
/// <typeparam name="T6">The sixth type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="id">The id of the entity in the database.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <returns>The entity with the corresponding id joined with the specified types.</returns>
public static TReturn Get<T1, T2, T3, T4, T5, T6, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, T4, T5, T6, TReturn> map, IDbTransaction? transaction = null) where TReturn : class
=> MultiMap<T1, T2, T3, T4, T5, T6, DontMap, TReturn>(connection, map, id, transaction).FirstOrDefault();
/// <summary>
/// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="T4">The fourth type parameter.</typeparam>
/// <typeparam name="T5">The fifth type parameter.</typeparam>
/// <typeparam name="T6">The sixth type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="id">The id of the entity in the database.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="cancellationToken">Optional cancellation token for the command.</param>
/// <returns>The entity with the corresponding id joined with the specified types.</returns>
public static async Task<TReturn> GetAsync<T1, T2, T3, T4, T5, T6, TReturn>(
this IDbConnection connection,
object id,
Func<T1, T2, T3, T4, T5, T6, TReturn> map,
IDbTransaction? transaction = null,
CancellationToken cancellationToken = default) => (await MultiMapAsync<T1, T2, T3, T4, T5, T6, DontMap, TReturn>(connection, map, id, transaction, cancellationToken: cancellationToken)).FirstOrDefault();
/// <summary>
/// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="T4">The fourth type parameter.</typeparam>
/// <typeparam name="T5">The fifth type parameter.</typeparam>
/// <typeparam name="T6">The sixth type parameter.</typeparam>
/// <typeparam name="T7">The seventh type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="id">The id of the entity in the database.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <returns>The entity with the corresponding id joined with the specified types.</returns>
public static TReturn Get<T1, T2, T3, T4, T5, T6, T7, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, T4, T5, T6, T7, TReturn> map, IDbTransaction? transaction = null) where TReturn : class
=> MultiMap<T1, T2, T3, T4, T5, T6, T7, TReturn>(connection, map, id, transaction).FirstOrDefault();
/// <summary>
/// Retrieves the entity of type <typeparamref name="TReturn"/> with the specified id
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="T4">The fourth type parameter.</typeparam>
/// <typeparam name="T5">The fifth type parameter.</typeparam>
/// <typeparam name="T6">The sixth type parameter.</typeparam>
/// <typeparam name="T7">The seventh type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="id">The id of the entity in the database.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="cancellationToken">Optional cancellation token for the command.</param>
/// <returns>The entity with the corresponding id joined with the specified types.</returns>
public static async Task<TReturn> GetAsync<T1, T2, T3, T4, T5, T6, T7, TReturn>(this IDbConnection connection, object id, Func<T1, T2, T3, T4, T5, T6, T7, TReturn> map, IDbTransaction? transaction = null, CancellationToken cancellationToken = default) where TReturn : class
=> (await MultiMapAsync<T1, T2, T3, T4, T5, T6, T7, TReturn>(connection, map, id, transaction, cancellationToken: cancellationToken)).FirstOrDefault();
/// <summary>
/// Retrieves all the entities of type <typeparamref name="TReturn"/>
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="buffered">
/// A value indicating whether the result of the query should be executed directly,
/// or when the query is materialized (using <c>ToList()</c> for example).
/// </param>
/// <returns>
/// A collection of entities of type <typeparamref name="TReturn"/>
/// joined with the specified type types.
/// </returns>
public static IEnumerable<TReturn> GetAll<T1, T2, TReturn>(
this IDbConnection connection,
Func<T1, T2, TReturn> map,
IDbTransaction? transaction = null,
bool buffered = true) => MultiMap<T1, T2, DontMap, DontMap, DontMap, DontMap, DontMap, TReturn>(connection, map, id: null, transaction, buffered);
/// <summary>
/// Retrieves all the entities of type <typeparamref name="TReturn"/>
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="buffered">
/// A value indicating whether the result of the query should be executed directly,
/// or when the query is materialized (using <c>ToList()</c> for example).
/// </param>
/// <param name="cancellationToken">Optional cancellation token for the command.</param>
/// <returns>
/// A collection of entities of type <typeparamref name="TReturn"/>
/// joined with the specified type types.
/// </returns>
public static Task<IEnumerable<TReturn>> GetAllAsync<T1, T2, TReturn>(
this IDbConnection connection,
Func<T1, T2, TReturn> map,
IDbTransaction? transaction = null,
bool buffered = true,
CancellationToken cancellationToken = default) => MultiMapAsync<T1, T2, DontMap, DontMap, DontMap, DontMap, DontMap, TReturn>(connection, map, id: null, transaction, buffered, cancellationToken: cancellationToken);
/// <summary>
/// Retrieves all the entities of type <typeparamref name="TReturn"/>
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="buffered">
/// A value indicating whether the result of the query should be executed directly,
/// or when the query is materialized (using <c>ToList()</c> for example).
/// </param>
/// <returns>
/// A collection of entities of type <typeparamref name="TReturn"/>
/// joined with the specified type types.
/// </returns>
public static IEnumerable<TReturn> GetAll<T1, T2, T3, TReturn>(
this IDbConnection connection,
Func<T1, T2, T3, TReturn> map,
IDbTransaction? transaction = null,
bool buffered = true) => MultiMap<T1, T2, T3, DontMap, DontMap, DontMap, DontMap, TReturn>(connection, map, id: null, transaction, buffered);
/// <summary>
/// Retrieves all the entities of type <typeparamref name="TReturn"/>
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="buffered">
/// A value indicating whether the result of the query should be executed directly,
/// or when the query is materialized (using <c>ToList()</c> for example).
/// </param>
/// <param name="cancellationToken">Optional cancellation token for the command.</param>
/// <returns>
/// A collection of entities of type <typeparamref name="TReturn"/>
/// joined with the specified type types.
/// </returns>
public static Task<IEnumerable<TReturn>> GetAllAsync<T1, T2, T3, TReturn>(
this IDbConnection connection,
Func<T1, T2, T3, TReturn> map,
IDbTransaction? transaction = null,
bool buffered = true,
CancellationToken cancellationToken = default) => MultiMapAsync<T1, T2, T3, DontMap, DontMap, DontMap, DontMap, TReturn>(connection, map, id: null, transaction, buffered, cancellationToken: cancellationToken);
/// <summary>
/// Retrieves all the entities of type <typeparamref name="TReturn"/>
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="T4">The fourth type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="buffered">
/// A value indicating whether the result of the query should be executed directly,
/// or when the query is materialized (using <c>ToList()</c> for example).
/// </param>
/// <returns>
/// A collection of entities of type <typeparamref name="TReturn"/>
/// joined with the specified type types.
/// </returns>
public static IEnumerable<TReturn> GetAll<T1, T2, T3, T4, TReturn>(
this IDbConnection connection,
Func<T1, T2, T3, T4, TReturn> map,
IDbTransaction? transaction = null,
bool buffered = true) => MultiMap<T1, T2, T3, T4, DontMap, DontMap, DontMap, TReturn>(connection, map, id: null, transaction, buffered);
/// <summary>
/// Retrieves all the entities of type <typeparamref name="TReturn"/>
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="T4">The fourth type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="buffered">
/// A value indicating whether the result of the query should be executed directly,
/// or when the query is materialized (using <c>ToList()</c> for example).
/// </param>
/// <param name="cancellationToken">Optional cancellation token for the command.</param>
/// <returns>
/// A collection of entities of type <typeparamref name="TReturn"/>
/// joined with the specified type types.
/// </returns>
public static Task<IEnumerable<TReturn>> GetAllAsync<T1, T2, T3, T4, TReturn>(
this IDbConnection connection,
Func<T1, T2, T3, T4, TReturn> map,
IDbTransaction? transaction = null,
bool buffered = true,
CancellationToken cancellationToken = default) => MultiMapAsync<T1, T2, T3, T4, DontMap, DontMap, DontMap, TReturn>(connection, map, id: null, transaction, buffered, cancellationToken: cancellationToken);
/// <summary>
/// Retrieves all the entities of type <typeparamref name="TReturn"/>
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="T4">The fourth type parameter.</typeparam>
/// <typeparam name="T5">The fifth type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="buffered">
/// A value indicating whether the result of the query should be executed directly,
/// or when the query is materialized (using <c>ToList()</c> for example).
/// </param>
/// <returns>
/// A collection of entities of type <typeparamref name="TReturn"/>
/// joined with the specified type types.
/// </returns>
public static IEnumerable<TReturn> GetAll<T1, T2, T3, T4, T5, TReturn>(
this IDbConnection connection,
Func<T1, T2, T3, T4, T5, TReturn> map,
IDbTransaction? transaction = null,
bool buffered = true) => MultiMap<T1, T2, T3, T4, T5, DontMap, DontMap, TReturn>(connection, map, id: null, transaction, buffered);
/// <summary>
/// Retrieves all the entities of type <typeparamref name="TReturn"/>
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="T4">The fourth type parameter.</typeparam>
/// <typeparam name="T5">The fifth type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="buffered">
/// A value indicating whether the result of the query should be executed directly,
/// or when the query is materialized (using <c>ToList()</c> for example).
/// </param>
/// <param name="cancellationToken">Optional cancellation token for the command.</param>
/// <returns>
/// A collection of entities of type <typeparamref name="TReturn"/>
/// joined with the specified type types.
/// </returns>
public static Task<IEnumerable<TReturn>> GetAllAsync<T1, T2, T3, T4, T5, TReturn>(
this IDbConnection connection,
Func<T1, T2, T3, T4, T5, TReturn> map,
IDbTransaction? transaction = null,
bool buffered = true,
CancellationToken cancellationToken = default) => MultiMapAsync<T1, T2, T3, T4, T5, DontMap, DontMap, TReturn>(connection, map, id: null, transaction, buffered, cancellationToken: cancellationToken);
/// <summary>
/// Retrieves all the entities of type <typeparamref name="TReturn"/>
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="T4">The fourth type parameter.</typeparam>
/// <typeparam name="T5">The fifth type parameter.</typeparam>
/// <typeparam name="T6">The sixth type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="buffered">
/// A value indicating whether the result of the query should be executed directly,
/// or when the query is materialized (using <c>ToList()</c> for example).
/// </param>
/// <returns>
/// A collection of entities of type <typeparamref name="TReturn"/>
/// joined with the specified type types.
/// </returns>
public static IEnumerable<TReturn> GetAll<T1, T2, T3, T4, T5, T6, TReturn>(
this IDbConnection connection,
Func<T1, T2, T3, T4, T5, T6, TReturn> map,
IDbTransaction? transaction = null,
bool buffered = true) => MultiMap<T1, T2, T3, T4, T5, T6, DontMap, TReturn>(connection, map, id: null, transaction, buffered);
/// <summary>
/// Retrieves all the entities of type <typeparamref name="TReturn"/>
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="T4">The fourth type parameter.</typeparam>
/// <typeparam name="T5">The fifth type parameter.</typeparam>
/// <typeparam name="T6">The sixth type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="buffered">
/// A value indicating whether the result of the query should be executed directly,
/// or when the query is materialized (using <c>ToList()</c> for example).
/// </param>
/// <param name="cancellationToken">Optional cancellation token for the command.</param>
/// <returns>
/// A collection of entities of type <typeparamref name="TReturn"/>
/// joined with the specified type types.
/// </returns>
public static Task<IEnumerable<TReturn>> GetAllAsync<T1, T2, T3, T4, T5, T6, TReturn>(
this IDbConnection connection,
Func<T1, T2, T3, T4, T5, T6, TReturn> map,
IDbTransaction? transaction = null,
bool buffered = true,
CancellationToken cancellationToken = default) => MultiMapAsync<T1, T2, T3, T4, T5, T6, DontMap, TReturn>(connection, map, id: null, transaction, buffered, cancellationToken: cancellationToken);
/// <summary>
/// Retrieves all the entities of type <typeparamref name="TReturn"/>
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="T4">The fourth type parameter.</typeparam>
/// <typeparam name="T5">The fifth type parameter.</typeparam>
/// <typeparam name="T6">The sixth type parameter.</typeparam>
/// <typeparam name="T7">The seventh type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="buffered">
/// A value indicating whether the result of the query should be executed directly,
/// or when the query is materialized (using <c>ToList()</c> for example).
/// </param>
/// <returns>
/// A collection of entities of type <typeparamref name="TReturn"/>
/// joined with the specified type types.
/// </returns>
public static IEnumerable<TReturn> GetAll<T1, T2, T3, T4, T5, T6, T7, TReturn>(
this IDbConnection connection,
Func<T1, T2, T3, T4, T5, T6, T7, TReturn> map,
IDbTransaction? transaction = null,
bool buffered = true) => MultiMap<T1, T2, T3, T4, T5, T6, T7, TReturn>(connection, map, id: null, transaction, buffered);
/// <summary>
/// Retrieves all the entities of type <typeparamref name="TReturn"/>
/// joined with the types specified as type parameters.
/// </summary>
/// <typeparam name="T1">The first type parameter. This is the source entity.</typeparam>
/// <typeparam name="T2">The second type parameter.</typeparam>
/// <typeparam name="T3">The third type parameter.</typeparam>
/// <typeparam name="T4">The fourth type parameter.</typeparam>
/// <typeparam name="T5">The fifth type parameter.</typeparam>
/// <typeparam name="T6">The sixth type parameter.</typeparam>
/// <typeparam name="T7">The seventh type parameter.</typeparam>
/// <typeparam name="TReturn">The return type parameter.</typeparam>
/// <param name="connection">The connection to the database. This can either be open or closed.</param>
/// <param name="map">The mapping to perform on the entities in the result set.</param>
/// <param name="transaction">Optional transaction for the command.</param>
/// <param name="buffered">
/// A value indicating whether the result of the query should be executed directly,
/// or when the query is materialized (using <c>ToList()</c> for example).
/// </param>
/// <param name="cancellationToken">Optional cancellation token for the command.</param>
/// <returns>
/// A collection of entities of type <typeparamref name="TReturn"/>
/// joined with the specified type types.
/// </returns>
public static Task<IEnumerable<TReturn>> GetAllAsync<T1, T2, T3, T4, T5, T6, T7, TReturn>(
this IDbConnection connection,
Func<T1, T2, T3, T4, T5, T6, T7, TReturn> map,
IDbTransaction? transaction = null,
bool buffered = true,
CancellationToken cancellationToken = default) => MultiMapAsync<T1, T2, T3, T4, T5, T6, T7, TReturn>(connection, map, id: null, transaction, buffered, cancellationToken: cancellationToken);
private static IEnumerable<TReturn> MultiMap<T1, T2, T3, T4, T5, T6, T7, TReturn>(IDbConnection connection, Delegate map, object? id, IDbTransaction? transaction = null, bool buffered = true)
{
var resultType = typeof(TReturn);
var includeTypes = new[]
{
typeof(T1),
typeof(T2),
typeof(T3),
typeof(T4),
typeof(T5),
typeof(T6),
typeof(T7)
}
.Where(t => t != typeof(DontMap))
.ToArray();
var sql = BuildMultiMapQuery(GetSqlBuilder(connection), resultType, includeTypes, id, out var parameters);
LogQuery<TReturn>(sql);
var splitOn = CreateSplitOn(includeTypes);
return includeTypes.Length switch
{
2 => connection.Query(sql, (Func<T1, T2, TReturn>)map, parameters, transaction, buffered, splitOn),
3 => connection.Query(sql, (Func<T1, T2, T3, TReturn>)map, parameters, transaction, buffered, splitOn),
4 => connection.Query(sql, (Func<T1, T2, T3, T4, TReturn>)map, parameters, transaction, buffered, splitOn),
5 => connection.Query(sql, (Func<T1, T2, T3, T4, T5, TReturn>)map, parameters, transaction, buffered, splitOn),
6 => connection.Query(sql, (Func<T1, T2, T3, T4, T5, T6, TReturn>)map, parameters, transaction, buffered, splitOn),
7 => connection.Query(sql, (Func<T1, T2, T3, T4, T5, T6, T7, TReturn>)map, parameters, transaction, buffered, splitOn),
_ => throw new InvalidOperationException($"Invalid amount of include types: {includeTypes.Length}."),
};
}
private static Task<IEnumerable<TReturn>> MultiMapAsync<T1, T2, T3, T4, T5, T6, T7, TReturn>(IDbConnection connection, Delegate map, object? id, IDbTransaction? transaction = null, bool buffered = true, CancellationToken cancellationToken = default)
{
var resultType = typeof(TReturn);
var includeTypes = new[]
{
typeof(T1),
typeof(T2),
typeof(T3),
typeof(T4),
typeof(T5),
typeof(T6),
typeof(T7)
}
.Where(t => t != typeof(DontMap))
.ToArray();
var sql = BuildMultiMapQuery(GetSqlBuilder(connection), resultType, includeTypes, id, out var parameters);
LogQuery<TReturn>(sql);
var splitOn = CreateSplitOn(includeTypes);
CommandDefinition commandDefinition = new CommandDefinition(sql, parameters, transaction, flags: buffered ? CommandFlags.Buffered : CommandFlags.None, cancellationToken: cancellationToken);
return includeTypes.Length switch
{
2 => connection.QueryAsync(commandDefinition, (Func<T1, T2, TReturn>)map, splitOn),
3 => connection.QueryAsync(commandDefinition, (Func<T1, T2, T3, TReturn>)map, splitOn),
4 => connection.QueryAsync(commandDefinition, (Func<T1, T2, T3, T4, TReturn>)map, splitOn),
5 => connection.QueryAsync(commandDefinition, (Func<T1, T2, T3, T4, T5, TReturn>)map, splitOn),
6 => connection.QueryAsync(commandDefinition, (Func<T1, T2, T3, T4, T5, T6, TReturn>)map, splitOn),
7 => connection.QueryAsync(commandDefinition, (Func<T1, T2, T3, T4, T5, T6, T7, TReturn>)map, splitOn),
_ => throw new InvalidOperationException($"Invalid amount of include types: {includeTypes.Length}."),
};
}
internal static string CreateSplitOn(Type[] includeTypes)
{
// Create a splitOn parameter from the key properties of the included types
// We use the column name resolver directly rather than via the Resolvers class
// because Dapper needs an un-quoted column identifier.
// E.g. FooId rather than [FooId] for SQL server, etc.
return string.Join(",", includeTypes
.Select(t => Resolvers.KeyProperties(t).First())
.Select(p => ColumnNameResolver.ResolveColumnName(p.Property)));
}
internal static string BuildMultiMapQuery(ISqlBuilder sqlBuilder, Type resultType, Type[] includeTypes, object? id, out DynamicParameters? parameters)
{
var resultTableName = Resolvers.Table(resultType, sqlBuilder);
var resultTableKeyColumnName = Resolvers.Column(Resolvers.KeyProperties(resultType).Single().Property, sqlBuilder);
var sql = $"select * from {resultTableName}";
// Determine the table to join with.
var sourceType = includeTypes[0];
var sourceTableName = Resolvers.Table(sourceType, sqlBuilder);
for (var i = 1; i < includeTypes.Length; i++)
{
// Determine the table name of the joined table.
var includeType = includeTypes[i];
var foreignKeyTableName = Resolvers.Table(includeType, sqlBuilder);
// Determine the foreign key and the relationship type.
var foreignKeyProperty = Resolvers.ForeignKeyProperty(sourceType, includeType, out var relation);
var foreignKeyPropertyName = Resolvers.Column(foreignKeyProperty, sqlBuilder);
if (relation == ForeignKeyRelation.OneToOne)
{
// Determine the primary key of the foreign key table.
var foreignKeyTableKeyColumName = Resolvers.Column(Resolvers.KeyProperties(includeType).Single().Property, sqlBuilder);
sql += $" left join {foreignKeyTableName} on {sourceTableName}.{foreignKeyPropertyName} = {foreignKeyTableName}.{foreignKeyTableKeyColumName}";
}
else if (relation == ForeignKeyRelation.OneToMany)
{
// Determine the primary key of the source table.
var sourceKeyColumnName = Resolvers.Column(Resolvers.KeyProperties(sourceType).Single().Property, sqlBuilder);
sql += $" left join {foreignKeyTableName} on {sourceTableName}.{sourceKeyColumnName} = {foreignKeyTableName}.{foreignKeyPropertyName}";
}
}
parameters = null;
if (id != null)
{
sql += $" where {resultTableName}.{resultTableKeyColumnName} = {sqlBuilder.PrefixParameter("Id")}";
parameters = new DynamicParameters();
parameters.Add("Id", id);
}
return sql;
}
internal class DontMap
{
}
}
}
| 67.709538 | 281 | 0.639825 | [
"MIT"
] | bornlogic/bornlogic-dapper-dommel | src/Bornlogic.Dapper.Dommel/MultiMap.cs | 46,855 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由T4模板自动生成
// 生成时间 2020-02-04 21:25:26
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失
// 作者:Harbour CTS
// </auto-generated>
//------------------------------------------------------------------------------
using LQExtension.Model;
using LQExtension.DAL;
namespace LQExtension.BLL
{
public partial class Sys_WarehouseBLL:BaseServiceDapperContrib<Model.Sys_Warehouse>
{
}
}
| 21.541667 | 84 | 0.470019 | [
"MIT"
] | haitongxuan/LQExtesion | LQExtension.BLL/T4.DapperExt/Sys_WarehouseBLL.cs | 627 | C# |
/*
MIT License
Copyright(c) 2020 Evgeny Pereguda
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 CaptureManagerToCSharpProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 WPFDeviceInfoViewer
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
CaptureManager lCaptureManager = null;
try
{
lCaptureManager = new CaptureManager("CaptureManager.dll");
}
catch (System.Exception exc)
{
try
{
lCaptureManager = new CaptureManager();
}
catch (System.Exception exc1)
{
}
}
if (lCaptureManager == null)
return;
XmlDataProvider lXmlDataProvider = (XmlDataProvider)this.Resources["XmlLogProvider"];
if (lXmlDataProvider == null)
return;
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
string lxmldoc = "";
lCaptureManager.getCollectionOfSources(ref lxmldoc);
doc.LoadXml(lxmldoc);
var lDeviceLinkNodeList = doc.SelectNodes("Sources/Source/Source.Attributes/Attribute[@Name='CM_DEVICE_LINK']/SingleValue/@Value");
List<string> lDeviceLinkList = new List<string>();
for (int i = 0; i < lDeviceLinkNodeList.Count; i++)
{
if (!lDeviceLinkList.Contains(lDeviceLinkNodeList.Item(i).Value))
{
lDeviceLinkList.Add(lDeviceLinkNodeList.Item(i).Value);
}
}
System.Xml.XmlDocument groupDoc = new System.Xml.XmlDocument();
var lroot = groupDoc.CreateElement("Sources");
groupDoc.AppendChild(lroot);
foreach (var item in lDeviceLinkList)
{
var ldevices = doc.SelectNodes("Sources/Source[Source.Attributes/Attribute[@Name='CM_DEVICE_LINK']/SingleValue[@Value='" + item + "']]");
if (ldevices != null)
{
var lgroup = groupDoc.CreateElement("DeviceGroup");
var lTitle = groupDoc.CreateAttribute("Title");
lTitle.Value = item;
lgroup.Attributes.Append(lTitle);
foreach (var node in ldevices)
{
var lSourceNode = groupDoc.ImportNode((node as System.Xml.XmlNode), true);
lgroup.AppendChild(lSourceNode);
}
lroot.AppendChild(lgroup);
}
}
lXmlDataProvider.XPath = "Sources/DeviceGroup";
lXmlDataProvider.Document = groupDoc;
}
}
}
| 31.57037 | 153 | 0.612623 | [
"MIT"
] | AreebaAroosh/CaptureManagerSDK | Demo/CSDemo/WPFDemo/WPFDeviceInfoViewer/MainWindow.xaml.cs | 4,264 | C# |
using System;
using System.IO;
using System.Threading.Tasks;
namespace LogJoint.Persistence
{
public class ContentCacheManager: IContentCache, IDisposable
{
public ContentCacheManager(ITraceSourceFactory traceSourceFactory, Implementation.IStorageManagerImplementation impl)
{
this.trace = traceSourceFactory.CreateTraceSource("ContentCache", "cache");
this.impl = impl;
this.impl.SetTrace(trace);
}
void IDisposable.Dispose()
{
impl.Dispose();
}
async Task<Stream> IContentCache.GetValue(string key)
{
var entry = await GetEntry(key);
var section = await entry.OpenRawStreamSection(dataSectionName, StorageSectionOpenFlag.ReadOnly);
if (!await ((Implementation.IStorageSectionInternal)section).ExistsInFileSystem())
{
await section.DisposeAsync();
return null;
}
return new CachedStream(section);
}
async Task IContentCache.SetValue(string key, Stream data)
{
var entry = await GetEntry(key);
await using var section = await entry.OpenRawStreamSection(dataSectionName, StorageSectionOpenFlag.ReadWrite);
await data.CopyToAsync(section.Data);
}
private async Task<IStorageEntry> GetEntry(string key)
{
var entry = await impl.GetEntry(key, 0);
await entry.AllowCleanup();
return entry;
}
#region Members
readonly LJTraceSource trace;
readonly Implementation.IStorageManagerImplementation impl;
readonly string dataSectionName = "data";
#endregion
public class ConfigAccess : Implementation.IStorageConfigAccess
{
readonly Settings.IGlobalSettingsAccessor settings;
public ConfigAccess(Settings.IGlobalSettingsAccessor settings)
{
this.settings = settings;
}
long Implementation.IStorageConfigAccess.SizeLimit
{
get { return settings.ContentStorageSizes.StoreSizeLimit; }
}
int Implementation.IStorageConfigAccess.CleanupPeriod
{
get { return settings.ContentStorageSizes.CleanupPeriod; }
}
};
class CachedStream : DelegatingStream
{
readonly IRawStreamStorageSection section;
public CachedStream(IRawStreamStorageSection section)
: base(section.Data)
{
this.section = section;
}
protected override void Dispose(bool disposing)
{
if (disposing)
section.DisposeAsync();
base.Dispose(disposing);
}
};
};
}
| 24.851064 | 122 | 0.735445 | [
"MIT"
] | sergey-su/logjoint | trunk/model/persistence/ContentCacheManager.cs | 2,336 | C# |
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Microsoft.Recognizers.Definitions.French;
namespace Microsoft.Recognizers.Text.Choice.French
{
class FrenchBooleanExtractorConfiguration : IBooleanExtractorConfiguration
{
public static readonly Regex TrueRegex =
new Regex(ChoiceDefinitions.TrueRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
public static readonly Regex FalseRegex =
new Regex(ChoiceDefinitions.FalseRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
public static readonly Regex TokenRegex =
new Regex(ChoiceDefinitions.TokenizerRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
public static readonly IDictionary<Regex, string> MapRegexes = new Dictionary<Regex, string>()
{
{TrueRegex, Constants.SYS_BOOLEAN_TRUE },
{FalseRegex, Constants.SYS_BOOLEAN_FALSE }
};
public FrenchBooleanExtractorConfiguration(bool onlyTopMatch = true)
{
this.OnlyTopMatch = onlyTopMatch;
}
Regex IBooleanExtractorConfiguration.TrueRegex => TrueRegex;
Regex IBooleanExtractorConfiguration.FalseRegex => FalseRegex;
IDictionary<Regex, string> IChoiceExtractorConfiguration.MapRegexes => MapRegexes;
Regex IChoiceExtractorConfiguration.TokenRegex => TokenRegex;
public bool AllowPartialMatch => false;
public int MaxDistance => 2;
public bool OnlyTopMatch { get; }
}
}
| 33.673913 | 107 | 0.715946 | [
"MIT"
] | Josverl/Recognizers-Text | .NET/Microsoft.Recognizers.Text.Choice/French/Extractors/FrenchBooleanExtractorConfiguration.cs | 1,551 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace RandomSchool {
public partial class SiteMaster {
/// <summary>
/// ulNavbar control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl ulNavbar;
/// <summary>
/// MainContent control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder MainContent;
}
}
| 32.529412 | 84 | 0.500904 | [
"Apache-2.0"
] | jbwilliamson/MaximiseWFScaffolding | RandomSchool/RandomSchool/Site.Master.designer.cs | 1,108 | C# |
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using SqlParser.Analysis;
using SqlParser.Ast;
using SqlParser.SqlServer.Parsing;
namespace SqlParser.SqlServer.Tests.Examples
{
[TestFixture]
public class EFQuery1Tests
{
// sample query generated by EF, with some details removed/anonymized
private const string Query = @"
SELECT
[Project1].[Id] AS [Id],
[Project1].[C2] AS [C1],
[Project1].[Id1] AS [Id1],
[Project1].[C1] AS [C2],
[Project1].[Id2] AS [Id2],
[Project1].[Table2_Id] AS [Table2_Id],
[Project1].[CreateDateUTC] AS [CreateDateUTC],
[Project1].[CreatedBy] AS [CreatedBy],
[Project1].[UpdateDateUTC] AS [UpdateDateUTC],
[Project1].[UpdatedBy] AS [UpdatedBy],
[Project1].[AuditId] AS [AuditId],
[Project1].[IpAddress] AS [IpAddress],
[Project1].[Signon_Id] AS [Signon_Id]
FROM ( SELECT
[Extent1].[Id] AS [Id],
[Join1].[Id1] AS [Id1],
[Join1].[Id2] AS [Id2],
[Join1].[Table2_Id] AS [Table2_Id],
[Join1].[CreateDateUTC1] AS [CreateDateUTC],
[Join1].[CreatedBy1] AS [CreatedBy],
[Join1].[UpdateDateUTC1] AS [UpdateDateUTC],
[Join1].[UpdatedBy1] AS [UpdatedBy],
[Join1].[AuditId1] AS [AuditId],
[Join1].[IpAddress1] AS [IpAddress],
[Join1].[Signon_Id1] AS [Signon_Id],
CASE WHEN ([Join1].[Id1] IS NULL) THEN CAST(NULL AS int) WHEN ([Join1].[Id2] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1],
CASE WHEN ([Join1].[Id1] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2]
FROM [dbo].[Table3] AS [Extent1]
LEFT OUTER JOIN (SELECT [Extent2].[Id] AS [Id1], [Extent2].[Table3Id] AS [Table3Id], [Extent3].[Id] AS [Id2], [Extent3].[Table2_Id] AS [Table2_Id], [Extent3].[CreateDateUTC] AS [CreateDateUTC1], [Extent3].[CreatedBy] AS [CreatedBy1], [Extent3].[UpdateDateUTC] AS [UpdateDateUTC1], [Extent3].[UpdatedBy] AS [UpdatedBy1], [Extent3].[AuditId] AS [AuditId1], [Extent3].[IpAddress] AS [IpAddress1], [Extent3].[Signon_Id] AS [Signon_Id1]
FROM [dbo].[Table2] AS [Extent2]
LEFT OUTER JOIN [dbo].[Table1] AS [Extent3] ON [Extent2].[Id] = [Extent3].[Table2_Id] ) AS [Join1] ON [Extent1].[Id] = [Join1].[Table3Id]
WHERE [Extent1].[Id] = @Z_7_p__linq__0
) AS [Project1]
ORDER BY [Project1].[Id] DESC, [Project1].[C2] ASC, [Project1].[Id1] ASC, [Project1].[C1] ASC
";
[Test]
public void Query_Parse()
{
var target = new Parser();
var result = target.Parse(Query);
SqlParser.SqlServer.Tests.Utility.SqlNodeExtensions.Should(result).NotBeNull();
}
[Test]
public void GetDataSources_Test()
{
var ast = new Parser().Parse(Query);
var result = ast.GetDataSources().ToList();
result.Count.Should().Be(3);
result.Should().Contain("dbo.Table1");
result.Should().Contain("dbo.Table2");
result.Should().Contain("dbo.Table3");
}
[Test]
public void GetVariableNames_Test()
{
var ast = new Parser().Parse(Query);
var result = ast.GetVariableNames();
result.Count.Should().Be(1);
result.First().Should().Be("@Z_7_p__linq__0");
}
}
}
| 41.617284 | 440 | 0.595966 | [
"Apache-2.0"
] | Whiteknight/SqlParser | Src/SqlParser.SqlServer.Tests/Examples/EFQuery1Tests.cs | 3,373 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using Newtonsoft.Json;
namespace BungieNet.Destiny.Entities.Inventory
{
/// <summary>
/// A list of minimal information for items in an inventory: be it a character's inventory, or a Profile's inventory. (Note that the Vault is a collection of inventory buckets in the Profile's inventory)
/// Inventory Items returned here are in a flat list, but importantly they have a bucketHash property that indicates the specific inventory bucket that is holding them. These buckets constitute things like the separate sections of the Vault, the user's inventory slots, etc. See DestinyInventoryBucketDefinition for more info.
/// </summary>
public partial class DestinyInventoryComponent
{
[JsonProperty("items")]
public Destiny.Entities.Items.DestinyItemComponent[] Items { get; set; }
}
}
| 46.68 | 327 | 0.652099 | [
"BSD-3-Clause"
] | KiaArmani/XurSuite | Libraries/MadReflection.BungieApi/MadReflection.BungieNetApi.Entities/Generated_/Destiny/Entities/Inventory/DestinyInventoryComponent.cs | 1,169 | C# |
namespace System
{
/// <summary>
/// Provides an extensible interface for generic configuration.
/// </summary>
public interface IConfiguration<out T>
{
/// <summary>
/// Provides an instance of the specified <typeparamref name="T"/>.
/// </summary>
T Configure();
}
} | 25.923077 | 76 | 0.554896 | [
"MIT"
] | TylerKendrick/Sugar.Core | Sugar/IConfiguration.cs | 339 | C# |
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Polly;
using FhirImporter.Extensions;
using Flurl.Http;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using FhirImporter.Models;
namespace Microsoft.Health
{
public static class FhirImport
{
public static async Task ImportBundle(string fhirString, ILogger log)
{
await ProcessItems(fhirString, log, "upsert");
}
public static async Task DeleteBundle(string fhirString, ILogger log)
{
await ProcessItems(fhirString, log, "delete");
}
public static async Task<IList<string>> GetEndpointsAsync(ILogger log)
{
string fhirServerUrl = Environment.GetEnvironmentVariable("FhirServerUrl");
string fhirResult = await $"{fhirServerUrl}/metadata".GetStringAsync();
try
{
JObject capabilityStatement = JObject.Parse(fhirResult);
JArray resources = (JArray)((JArray)capabilityStatement["rest"].FirstOrDefault()["resource"]);
return resources.Select(i => (string)i["type"]).ToList();
}
catch (Exception ex)
{
log.LogError("Error fetching metadata", ex);
throw ex;
}
}
public static async Task<IList<string>> GetEntriesJsonAsync(string resource, ILogger log)
{
var result = new List<string>();
try
{
string fhirServerUrl = Environment.GetEnvironmentVariable("FhirServerUrl");
string authToken = (await GetAuthTokenAsync()).AccessToken;
string nextLink = resource;
do
{
var bundleJson = await $"{fhirServerUrl}/{nextLink}"
.WithOAuthBearerToken(authToken)
.GetStringAsync();
result.Add(bundleJson);
var response = JsonConvert.DeserializeObject<FhirResponse>(bundleJson);
nextLink = response.Link.FirstOrDefault(l => l.Relation == "next")?.Url.PathAndQuery;
}
while (!string.IsNullOrEmpty(nextLink));
return result;
}
catch (Exception ex)
{
log.LogError($"Error fetching {resource}");
throw ex;
}
}
private static async Task<AuthenticationResult> GetAuthTokenAsync()
{
string authority = Environment.GetEnvironmentVariable("Authority");
string audience = Environment.GetEnvironmentVariable("Audience");
string clientId = Environment.GetEnvironmentVariable("ClientId");
string clientSecret = Environment.GetEnvironmentVariable("ClientSecret");
AuthenticationContext authContext;
ClientCredential clientCredential;
AuthenticationResult authResult;
try
{
authContext = new AuthenticationContext(authority);
clientCredential = new ClientCredential(clientId, clientSecret);
authResult = await authContext.AcquireTokenAsync(audience, clientCredential);
return authResult;
}
catch (Exception ee)
{
throw new Exception($"Unable to obtain token to access FHIR server in FhirImportService {ee}", ee);
}
}
private static async Task ProcessItems(string fhirString, ILogger log, string operation = "upsert")
{
JObject bundle;
JArray entries;
try
{
bundle = JObject.Parse(fhirString);
}
catch (JsonReaderException ex)
{
var msg = "Input file is not a valid JSON document";
throw new Exception(msg, ex);
}
entries = (JArray)bundle["entry"];
if (entries == null)
{
log.LogWarning("No entries found in bundle");
return;
}
try
{
FhirImportReferenceConverter.ConvertUUIDs(bundle);
}
catch (Exception ex)
{
var msg = "Failed to resolve references in doc";
throw new Exception(msg, ex);
}
int maxDegreeOfParallelism;
if (!int.TryParse(Environment.GetEnvironmentVariable("MaxDegreeOfParallelism"), out maxDegreeOfParallelism))
{
maxDegreeOfParallelism = 16;
}
string fhirServerUrl = Environment.GetEnvironmentVariable("FhirServerUrl");
var authToken = (await GetAuthTokenAsync()).AccessToken;
await entries.AsyncParallelForEach(async entry => {
var entry_json = ((JObject)entry)["resource"].ToString();
string resource_type = (string)((JObject)entry)["resource"]["resourceType"];
string id = (string)((JObject)entry)["resource"]["id"];
var randomGenerator = new Random();
Thread.Sleep(TimeSpan.FromMilliseconds(randomGenerator.Next(50)));
if (string.IsNullOrEmpty(entry_json))
{
log.LogError("No 'resource' section found in JSON document");
throw new FhirImportException("'resource' not found or empty");
}
if (string.IsNullOrEmpty(resource_type))
{
throw new FhirImportException("No resource_type in resource.");
}
var pollyDelays =
new[]
{
TimeSpan.FromMilliseconds(2000 + randomGenerator.Next(50)),
TimeSpan.FromMilliseconds(3000 + randomGenerator.Next(50)),
TimeSpan.FromMilliseconds(5000 + randomGenerator.Next(50)),
TimeSpan.FromMilliseconds(8000 + randomGenerator.Next(50)),
};
IFlurlResponse uploadResult = await Policy
.Handle<FlurlHttpException>()
//.Handle<FlurlHttpException>(flurlEx => null == flurlEx.Call || !flurlEx.Call.Succeeded)
.WaitAndRetryAsync(pollyDelays, (result, timeSpan, retryCount, context) =>
{
log.LogWarning($"Request failed with {result.Message}. Waiting {timeSpan} before next retry. Retry attempt {retryCount}");
})
.ExecuteAsync(() =>
{
switch (operation)
{
case "delete":
return $"{fhirServerUrl}/{resource_type}/{id}"
.WithOAuthBearerToken(authToken)
.DeleteAsync();
case "upsert":
default:
StringContent content = new StringContent(entry_json, Encoding.UTF8, "application/json");
return string.IsNullOrEmpty(id)
? $"{fhirServerUrl}/{resource_type}".WithOAuthBearerToken(authToken).PostAsync(content)
: $"{fhirServerUrl}/{resource_type}/{id}".WithOAuthBearerToken(authToken).PutAsync(content);
}
});
if (!uploadResult.ResponseMessage.IsSuccessStatusCode)
{
string resultContent = await uploadResult.GetStringAsync();
log.LogError(resultContent);
// Throwing a generic exception here. This will leave the blob in storage and retry.
throw new Exception($"Unable to {operation}. Error code {uploadResult.StatusCode}");
}
else
{
log.LogInformation($"{operation}ed /{resource_type}/{id}");
}
}, maxDegreeOfParallelism);
}
}
}
| 39.430556 | 146 | 0.534226 | [
"MIT"
] | pjirsa/fhir-server-samples | src/FhirImporter/FhirImport.cs | 8,517 | C# |
namespace Ripple.WebSocketClient.Model.Transaction.Interfaces
{
public interface ISetRegularKeyTransaction : ITransactionCommon
{
string RegularKey { get; set; }
}
} | 26.571429 | 67 | 0.731183 | [
"Apache-2.0"
] | MaintenanceExperts/Ripple.NET.WebSocketClient | src/RippleDotNet/Model/Transaction/Interfaces/ISetRegularKeyTransaction.cs | 188 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.Membership.OpenAuth;
namespace WebAppHola.Account
{
public partial class Register : Page
{
protected void Page_Load(object sender, EventArgs e)
{
RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"];
}
protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
FormsAuthentication.SetAuthCookie(RegisterUser.UserName, createPersistentCookie: false);
string continueUrl = RegisterUser.ContinueDestinationPageUrl;
if (!OpenAuth.IsLocalUrl(continueUrl))
{
continueUrl = "~/";
}
Response.Redirect(continueUrl);
}
}
} | 28.967742 | 100 | 0.667038 | [
"MIT"
] | mglezh/visual-studio-2012 | WebAppHola/WebAppHola/Account/Register.aspx.cs | 900 | C# |
using System;
using Microsoft.Maui.Controls;
namespace Maui.Controls.Sample.Pages.SwipeViewGalleries
{
public partial class SwipeItemPositionGallery
{
public SwipeItemPositionGallery()
{
InitializeComponent();
ModePicker.SelectedIndex = 0;
}
void OnModePickerSelectedIndexChanged(object sender, EventArgs e)
{
LeftSwipeItems.Mode = TopSwipeItems.Mode = RightSwipeItems.Mode = BottomSwipeItems.Mode = ModePicker.SelectedIndex == 0 ? SwipeMode.Reveal : SwipeMode.Execute;
}
}
} | 25.15 | 162 | 0.77336 | [
"MIT"
] | Mu-L/maui | src/Controls/samples/Controls.Sample/Pages/Controls/SwipeViewGalleries/SwipeItemPositionGallery.xaml.cs | 505 | C# |
/*
Copyright 2013 Vistaprint
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.
CommandMode.cs
*/
namespace Automobile.Mobile.Framework.Commands
{
/// <summary>
/// Type of action a command is doings
/// </summary>
public enum CommandMode
{
Get,
Set,
Invoke
}
} | 26.965517 | 72 | 0.727621 | [
"Apache-2.0"
] | vistaprint/automobile | Mobile/Framework/Commands/CommandMode.cs | 784 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace Compilator
{
public class ParameterList : Types
{
public List<Types> parameters = new List<Types>();
public bool declare = false;
public bool cantdefault = false;
public Token token;
public bool allowMultipel = false;
public Token allowMultipelName = null;
public bool cantDefaultThenNormal = false;
Dictionary<string, Types> genericTusage = new Dictionary<string, Types>();
public Dictionary<string, Types> defaultCustom = new Dictionary<string, Types>();
/*Serialization to JSON object for export*/
[JsonParam] public List<Types> Parameters => parameters;
[JsonParam] public bool AllowMultipel => allowMultipel;
[JsonParam] public Token AllowMultipelName => allowMultipelName;
[JsonParam] public Dictionary<string, JObject> DefaulCustom => defaultCustom.ToDictionary(x => x.Key, x => JsonParam.ToJson(x.Value));
public override void FromJson(JObject o)
{
parameters = JsonParam.FromJsonArray<Types>((JArray)o["Parameters"]);
allowMultipel = (bool) o["AllowMultipel"];
allowMultipelName = Token.FromJson(o["AllowMultipelName"]);
var dfcstm = JsonParam.FromJsonDictionaryKeyBase<string, Types>(o["DefaulCustom"]);
if (dfcstm.Count > 0)
{
Debugger.Break();
}
}
public ParameterList() { }
public ParameterList(bool declare)
{
this.declare = declare;
}
public ParameterList(ParameterList plist)
{
parameters = new List<Types>(plist.Parameters);
allowMultipel = plist.allowMultipel;
allowMultipelName = plist.allowMultipelName;
defaultCustom = plist.defaultCustom;
}
public bool IsAllPrimitive
{
get
{
foreach (var param in parameters)
{
if (param is Variable pv && !pv.IsPrimitive)
return false;
else if (param is Assign pa && pa.Right is Variable pav && !pav.IsPrimitive)
return false;
}
return true;
}
}
public Dictionary<string, Types> GenericTUsage
{
get { return genericTusage; }
set { genericTusage = value; }
}
public override Token getToken() { return token; }
public Variable Find(string name)
{
foreach(Types par in parameters)
{
Variable va = null;
if (par is Assign)
va = (Variable)(((Assign)par).Left);
else if (par is Variable)
va = (Variable)par;
else if (par is Lambda)
va = ((Lambda)par).TryVariable();
if (va.Value == name)
return va;
}
return null;
}
public string List()
{
string ret = "";
foreach (Types par in parameters)
{
if (ret != "") ret += ", ";
if (par is Variable parv)
{
ret += parv.Type + (parv.GenericList.Count > 0 ? "<" + string.Join(", ", parv.GenericList) + ">" : "") + " " + parv.Value;
}
else if (par is Assign ap)
ret += ap.GetType() + " " + ap.Left.TryVariable().Value + " = " + ap.Right.TryVariable().Value;
else if (par is Function af)
ret += af.RealName + (af.GenericArguments.Count > 0 ? "<" + string.Join(", ", af.GenericArguments) + ">" : "") + "(" + af.ParameterList.List() +") -> " + af.Return();
else if(par is UnaryOp au)
{
if(au.Op == "call")
{
if(au.usingFunction != null)
{
ret += au.usingFunction.RealName + (au.usingFunction.GenericArguments.Count > 0 ? "<" + string.Join(", ", au.usingFunction.GenericArguments) + ">" : "") + "(" + au.usingFunction.ParameterList.List() +") -> " + au.usingFunction.Return();
}
}
}
else if(par is Lambda al)
{
ret += "lambda ("+ al.ParameterList.List()+")";
}
else
{
Variable v = par.TryVariable();
ret += v.Type + (v.GenericList.Count > 0 ? "<" + string.Join(", ", v.GenericList) + ">" : "") + " " + v.Value;
}
}
return ret;
}
public List<string> ToList()
{
List<string> list = new List<string>();
foreach (var p in parameters)
{
if(p is Assign pa)
{
list.Add(pa.Left.TryVariable().Value);
}
else if(p is Variable pv)
{
list.Add(pv.Value);
}
else if(p is Lambda pl)
{
list.Add(pl.RealName);
}
}
return list;
}
public override string Compile(int tabs = 0)
{
return Compile(tabs, null);
}
public string Compile(int tabs = 0, ParameterList plist = null, ParameterList myList = null)
{
var ret = new StringBuilder();
Dictionary<string, bool> argDefined = new Dictionary<string, bool>();
List<string> argNamed = plist?.ToList();
int i = 0;
bool startne = false;
if(allowMultipel && plist == null && assingBlock != null && !assingBlock.variables.ContainsKey(allowMultipelName.Value))
{
new Assign(
new Variable(new Token(Token.Type.ID, allowMultipelName.Value), assingBlock) { isArray = true },
new Token(Token.Type.ASIGN, '='),
new Null(),
isVal: (assingBlock != null && assingBlock.assingToType is Function asif && asif.isInline));
}
foreach (Types par in parameters)
{
if(argNamed != null && i >= argNamed.Count && !startne)
{
ret.Append(ret.ToString() == "" ? "" : ", " + "[");
startne = true;
}
if(argNamed != null && argNamed.Count > i)
argDefined[argNamed[i]] = true;
par.endit = false;
if (assingBlock != null && par is Variable && assingBlock.SymbolTable.Get(((Variable)par).Value) is Error)
{
par.assingBlock = assingBlock;
var assign = new Assign(
((Variable) par),
new Token(Token.Type.ASIGN, '='),
new Null(),
assingBlock,
isVal: (assingBlock != null && assingBlock.assingToType is Function asif && asif.isInline));
}
else if(par is Assign && assingBlock != null && !assingBlock.variables.ContainsKey(((Assign)par).Left.TryVariable().Value))
{
assingBlock.variables.Add(((Assign)par).Left.TryVariable().Value, (Assign)par);
if (((Assign) par).Left is Variable parl)
{
parl.IsVal = (assingBlock != null && assingBlock.assingToType is Function asif && asif.isInline);
}
}
if (ret.ToString() != "" && ret[ret.Length-1] != '[') ret.Append(", ");
if (declare)
{
if (par is Variable parv)
{
parv.IsVal = (assingBlock != null && assingBlock.assingToType is Function asif && asif.isInline);
}
if (par is Assign)
ret.Append(((Assign)par).Left.Compile());
else if (par is Variable && ((Variable)par).Block?.SymbolTable.Get(((Variable)par).Type) is Delegate)
{
string rrr = par.Compile(0);
if (rrr.Split('$')[0] != "delegate")
ret.Append("delegate$" + rrr);
else
ret.Append(rrr);
}
else
ret.Append(par.Compile(0));
}
else
{
if (plist != null && i < plist.parameters.Count && plist.parameters[i].TryVariable().Type == "Predicate" && par is Lambda lambda)
{
lambda.predicate = plist.parameters[i];
lambda.assingBlock = assingBlock ?? plist.assingBlock;
lambda.assingToToken = assingToToken;
ret.Append(lambda.Compile());
}
else if (assingToType != null && assingToType is Variable varia && varia.Type == assingToType.TryVariable().Type && par is Variable variable && variable.Type == "auto")
{
var split = assingToToken.Value.Split('.');
var foundvar = assingBlock.SymbolTable.Get((split.Length > 1 ? split[split.Length-2]: split[0]));
if (foundvar is Assign foundAssign)
{
var mydelegate = assingBlock.SymbolTable.Get(varia.Type);
if (foundAssign.Left.TryVariable().genericArgs.Any() && mydelegate is Delegate jdelegate)
{
var leftvar = foundAssign.Left.TryVariable().genericArgs;
Dictionary<string, string> delegateAssign = new Dictionary<string, string>();
int x = 0;
foreach (var argument in jdelegate.GenericArguments)
{
delegateAssign[argument] = leftvar[x++];
}
var funct = assingBlock.SymbolTable.Get(assingToToken.Value);
if (funct is Function f)
{
var genericT = f.ParameterList.parameters[i].TryVariable().GenericList[i];
if (delegateAssign.ContainsKey(genericT))
{
variable.setType(new Token(Token.Type.CLASS, delegateAssign[genericT]));
}
}
}
}
var assignpredic = varia.Block.SymbolTable.Get(varia.Type);
ret.Append(variable.CompileHard(0, par));
}
else
ret.Append(par.Compile(0));
}
i++;
}
if (startne)
{
ret.Append("]");
}
if (myList != null)
{
foreach (Types par in plist.Parameters)
{
if (par is Assign para)
{
if (!argDefined.ContainsKey(para.Left.TryVariable().Value))
{
ret.Append((ret.ToString() != "" ? ", " : "") + "undefined");
}
}
else if(par is Variable parv)
{
if (!argDefined.ContainsKey(parv.Value))
{
ret.Append((ret.ToString() != "" ? ", " : "") + "undefined");
}
}
}
}
if(defaultCustom.Count != 0 && plist != null)
{
i = 0;
foreach(var p in plist.parameters)
{
i++;
bool found = false;
if (i-1 < parameters.Count)
continue;
if (p is Assign pa)
{
foreach (var q in defaultCustom)
{
if (pa.Left.TryVariable().Value == q.Key)
{
ret.Append(", " + q.Value.Compile());
found = true;
}
}
}
if (!found)
{
ret.Append((ret.ToString() != "" ? ", " : "") + "undefined");
}
}
}
if (plist != null && plist.allowMultipel && parameters.Count == argNamed.Count)
{
ret.Append((ret.ToString() != "" ? ", " : "") + "undefined");
}
if(allowMultipel && myList == null)
{
ret.Append((ret.ToString() != "" ? ", " : "") + allowMultipelName.Value);
}
assingBlock = null;
return ret.ToString();
}
public bool Compare(ParameterList p)
{
if (p == null && !allowMultipel) return false;
int i = 0;
bool haveDefault = false;
foreach(Types t in parameters)
{
bool def = false;
bool isGeneric = false;
bool isDelegate = false;
string dtype = null;
if (t is Variable)
{
dtype = ((Variable)t).Type;
if (((Variable)t).Block.SymbolTable.Get(dtype) is Generic || ((Variable)t).assingBlock?.SymbolTable.Get(dtype) is Generic)
{
isGeneric = true;
if (p.genericTusage.ContainsKey(dtype) && p.genericTusage[dtype] is Class __c)
{
dtype = __c.Name.Value;
isGeneric = false;
}
}
else if (assingBlock?.SymbolTable.Get(dtype) is Generic)
{
isGeneric = true;
if (p.genericTusage.ContainsKey(dtype) && p.genericTusage[dtype] is Class __c)
{
dtype = __c.Name.Value;
isGeneric = false;
}
}
else if (assingBlock?.SymbolTable.Get(dtype, genericArgs: ((Variable)t).GenericList.Count) is Delegate delegat)
{
if(p.parameters[i] is UnaryOp)
{
if(((UnaryOp)p.parameters[i]).usingFunction != null)
{
isDelegate = true;
if (delegat.CompareTo((Variable)t, ((UnaryOp)p.parameters[i]).usingFunction, p) != 0)
return false;
}
}
else if(p.parameters[i] is Lambda lambda)
{
isDelegate = true;
if (delegat.CompareTo((Variable)t, null, lambda.ParameterList) != 0)
return false;
}
else if(p.parameters[i] is Variable variab)
{
Types q = assingBlock.SymbolTable.Get(variab.Value);
if(q is Function func)
{
isDelegate = true;
if (delegat.CompareTo((Variable)t, func, func.ParameterList) != 0)
return false;
}
}
}
if (i < p.parameters.Count && p.parameters[i] is Variable && ((Variable)p.parameters[i]).Block.SymbolTable.Get(p.parameters[i].TryVariable().Type) is Generic)
isGeneric = true;
if (i < p.parameters.Count && p.parameters[i] is Variable && p.parameters[i].TryVariable().Type == "object")
isGeneric = true; //TODO Actualy is a object xD
}
if(t is Assign)
{
dtype = ((Variable)((Assign)t).Left).Type;
def = true;
}
if (t is Lambda)
dtype = "lambda";
if (i >= p.parameters.Count && !allowMultipel && !def)
return false;
if (i >= p.parameters.Count && def)
{
haveDefault = true;
break;
}
if (p.parameters[i] is Variable)
{
((Variable)p.parameters[i]).Check();
}
var rtype = p.parameters[i].TryVariable().Type;
if (!def && (dtype != rtype) && dtype != "object" && !isGeneric && !isDelegate)
{
bool bad = true;
var qq = assingBlock.SymbolTable.Get(p.parameters[i].TryVariable().Type);
if (assingBlock != null && !(qq is Error))
{
if(qq is Class qqc)
{
if (qqc.haveParent(dtype))
bad = false;
}
}
if(bad)
return false;
}
else if (def)
{
//haveDefault = true;
if (i < p.parameters.Count)
{
if (dtype != p.parameters[i].TryVariable().Type)
return false;
}
else
{
break;
}
}
i++;
}
if(parameters.Count != p.Parameters.Count)
{
if (!allowMultipel && !haveDefault)
return false;
}
return true;
}
public bool Equal(ParameterList b)
{
if (this is null && b is null) return true;
if (b is null) return false;
if (this.parameters.Count != b.parameters.Count)
return false;
int index = 0;
foreach (Types t in this.parameters)
{
Variable v1 = (Variable)t;
Variable v2 = (Variable)b.parameters[index];
if (v1.GetDateType().Value != v2.GetDateType().Value)
return false;
index++;
}
return true;
}
static public bool operator ==(ParameterList a, ParameterList b)
{
if (a is null && b is null) return true;
if (a is null) return false;
return a.Equal(b);
}
static public bool operator !=(ParameterList a, ParameterList b)
{
if (a is null && !(b is null)) return true;
if (a is null) return false;
return !a.Equal(b);
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return List().GetHashCode();
}
public override void Semantic()
{
Semantic(null, "");
}
public void Semantic(ParameterList plist = null, string fname = "")
{
if(defaultCustom.Count != 0 && plist != null)
{
foreach (var q in defaultCustom)
{
bool found = false;
foreach (var p in plist.parameters)
{
if (p is Assign pa)
if(pa.Left.TryVariable().Value == q.Key)
found = true;
}
if(!found)
{
Interpreter.semanticError.Add(new Error("#1xx Parameter "+q.Key+" not found in function "+fname, Interpreter.ErrorType.ERROR, token));
}
}
}
if(cantDefaultThenNormal)
Interpreter.semanticError.Add(new Error("#1xx When you define default you can't put normal", Interpreter.ErrorType.ERROR, token));
if (cantdefault)
Interpreter.semanticError.Add(new Error("#113 Optional parameters must follow all required parameters", Interpreter.ErrorType.ERROR, token));
foreach (Types par in parameters)
{
par.parent = this;
if (par.assingBlock == null)
par.assingBlock = assingBlock;
if(par is Assign para)
para.Semantic(true);
else
par.Semantic();
}
}
public override int Visit()
{
return 0;
}
public override string InterpetSelf()
{
throw new NotImplementedException();
}
}
}
| 41.972426 | 265 | 0.407743 | [
"Unlicense"
] | Natsu13/Pyr2 | Types/ParameterList.cs | 22,835 | C# |
using System;
using System.IO;
using CoreADT.ADT.MCALData;
namespace CoreADT.ADT.Chunks.Subchunks
{
public class MCAL : Chunk
{
public override uint ChunkSize { get; }
public MCALAlphaMap[] AlphaMaps { get; set; }
public MCAL(byte[] chunkBytes, MCNK parentChunk, WDT.WDT wdt) : base(chunkBytes)
{
AlphaMaps = new MCALAlphaMap[parentChunk.MCLY.Layers.Length];
for (int i = 0; i < parentChunk.MCLY.Layers.Length; i++)
AlphaMaps[i] = new MCALAlphaMap(this, parentChunk, wdt, i);
Close();
}
public override byte[] GetChunkBytes()
{
throw new NotImplementedException();
}
public byte[] GetChunkBytes(MCNK parentChunk, WDT.WDT wdt)
{
using (var stream = new MemoryStream())
{
using (var writer = new BinaryWriter(stream))
{
for (int i = 0; i < AlphaMaps.Length; i++)
AlphaMaps[i].Write(writer, parentChunk, wdt, i);
}
return stream.ToArray();
}
}
public override byte[] GetChunkHeaderBytes()
{
using (var stream = new MemoryStream())
{
using (var writer = new BinaryWriter(stream))
{
writer.Write(new char[] { 'L', 'A', 'C', 'M' });
writer.Write(ChunkSize);
}
return stream.ToArray();
}
}
}
}
| 28.509091 | 88 | 0.496173 | [
"MIT"
] | Kaev/CoreADT | CoreADT/ADT/Chunks/Subchunks/MCAL.cs | 1,570 | C# |
/*
Copyright (c) 2014 <a href="http://www.gutgames.com">James Craig</a>
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 UnitTests.Fixtures;
using Utilities.DataTypes;
using Utilities.IO.Logging.Enums;
using Utilities.IO.Logging.Interfaces;
using Xunit;
namespace UnitTests.IO.Logging
{
public class Manager : TestingDirectoryFixture
{
[Fact]
public void Creation()
{
using (Utilities.IO.Logging.Manager Temp = new Utilities.IO.Logging.Manager(AppDomain.CurrentDomain.GetAssemblies().Objects<ILogger>()))
{
Assert.NotNull(Temp);
}
new Utilities.IO.DirectoryInfo("~/Logs/").Delete();
}
[Fact]
public void Log()
{
using (Utilities.IO.Logging.Manager Temp = new Utilities.IO.Logging.Manager(AppDomain.CurrentDomain.GetAssemblies().Objects<ILogger>()))
{
var File = (Utilities.IO.Logging.Default.DefaultLog)Temp.GetLog();
Assert.Equal("Default", File.Name);
foreach (MessageType Type in Enum.GetValues(typeof(MessageType)))
File.LogMessage("TestMessage", Type);
Assert.Contains("\r\nGeneral: TestMessage\r\nDebug: TestMessage\r\nTrace: TestMessage\r\nInfo: TestMessage\r\nWarn: TestMessage\r\nError: TestMessage\r\n", new Utilities.IO.FileInfo(File.FileName).Read());
}
new Utilities.IO.DirectoryInfo("~/Logs/").Delete();
}
}
} | 43.789474 | 221 | 0.698718 | [
"MIT"
] | JaCraig/Craig-s-Utility-Library | UnitTests/IO/Logging/Manager.cs | 2,498 | 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 ecr-2015-09-21.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.ECR.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ECR.Model.Internal.MarshallTransformations
{
/// <summary>
/// SetRepositoryPolicy Request Marshaller
/// </summary>
public class SetRepositoryPolicyRequestMarshaller : IMarshaller<IRequest, SetRepositoryPolicyRequest> , 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((SetRepositoryPolicyRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(SetRepositoryPolicyRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.ECR");
string target = "AmazonEC2ContainerRegistry_V20150921.SetRepositoryPolicy";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-09-21";
request.HttpMethod = "POST";
request.ResourcePath = "/";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetForce())
{
context.Writer.WritePropertyName("force");
context.Writer.Write(publicRequest.Force);
}
if(publicRequest.IsSetPolicyText())
{
context.Writer.WritePropertyName("policyText");
context.Writer.Write(publicRequest.PolicyText);
}
if(publicRequest.IsSetRegistryId())
{
context.Writer.WritePropertyName("registryId");
context.Writer.Write(publicRequest.RegistryId);
}
if(publicRequest.IsSetRepositoryName())
{
context.Writer.WritePropertyName("repositoryName");
context.Writer.Write(publicRequest.RepositoryName);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static SetRepositoryPolicyRequestMarshaller _instance = new SetRepositoryPolicyRequestMarshaller();
internal static SetRepositoryPolicyRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static SetRepositoryPolicyRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.739837 | 154 | 0.595264 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/ECR/Generated/Model/Internal/MarshallTransformations/SetRepositoryPolicyRequestMarshaller.cs | 4,519 | C# |
/* ------------------------------------------------------------------------------
Copyright (c) 2020 Christopher Whitley
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------ */
namespace MonoGame.Aseprite.ContentPipeline.Processors
{
/// <summary>
/// Defines the values for the type of spritesheet to
/// create when processing an Aseprite file.
/// </summary>
public enum ProcessorSheetType
{
/// <summary>
/// Describes a horizontal spritesheet with only 1 column
/// and as many rows as there are frames.
/// </summary>
HorizontalStrip = 0,
/// <summary>
/// Describes a vertical spritesheet with only 1 row and
/// as many columns as there are frames.
/// </summary>
VerticalStrip = 1,
/// <summary>
/// Descrbies a packed spritesheet.
/// </summary>
Packed = 2
}
}
| 41.38 | 82 | 0.618173 | [
"MIT"
] | 10Drenth/monogame-aseprite | source/MonoGame.Aseprite.ContentPipeline/Processors/ProcessorSheetType.cs | 2,071 | C# |
using LCU.NET.API_Models;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using static LCU.NET.LeagueClient;
namespace LCU.NET.Plugins.LoL
{
public interface IPerks
{
Task<LolPerksPerkPageResource> GetCurrentPageAsync();
Task PutCurrentPageAsync(int id);
Task<LolPerksPerkPageResource[]> GetPagesAsync();
Task DeletePageAsync(int id);
Task<LolPerksPerkPageResource> GetPageAsync(int id);
Task<LolPerksPerkPageResource> PutPageAsync(int id, LolPerksPerkPageResource page);
Task<LolPerksPerkPageResource> PostPageAsync(LolPerksPerkPageResource page);
Task<LolPerksPerkUIPerk[]> GetPerksAsync();
Task<LolPerksPlayerInventory> GetInventoryAsync();
Task<Image> GetPerkImageAsync(LolPerksPerkUIPerk perk);
}
public class Perks : IPerks
{
private readonly ILeagueClient Client;
private readonly IPluginManager PluginManager;
public Perks(ILeagueClient client, IPluginManager pluginManager)
{
this.Client = client;
this.PluginManager = pluginManager;
}
/// <summary>
/// Returns the current runes page.
/// </summary>
public Task<LolPerksPerkPageResource> GetCurrentPageAsync()
=> Client.MakeRequestAsync<LolPerksPerkPageResource>("/lol-perks/v1/currentpage", Method.GET);
/// <summary>
/// Sets the current rune page.
/// </summary>
/// <param name="id">The new page's ID.</param>
public Task PutCurrentPageAsync(int id)
=> Client.MakeRequestAsync("/lol-perks/v1/currentpage", Method.PUT, id);
/// <summary>
/// Gets all the user's rune pages, including default ones.
/// </summary>
public async Task<LolPerksPerkPageResource[]> GetPagesAsync()
=> (await Client.MakeRequestAsync<List<LolPerksPerkPageResource>>("/lol-perks/v1/pages", Method.GET).ConfigureAwait(false)).ToArray();
/// <summary>
/// Deletes a rune page by ID.
/// </summary>
/// <param name="id">The page's ID.</param>
public Task DeletePageAsync(int id)
=> Client.MakeRequestAsync($"/lol-perks/v1/pages/{id}", Method.DELETE);
/// <summary>
/// Gets a rune page by ID.
/// </summary>
/// <param name="id">The page's ID.</param>
public Task<LolPerksPerkPageResource> GetPageAsync(int id)
=> Client.MakeRequestAsync<LolPerksPerkPageResource>($"/lol-perks/v1/pages/{id}", Method.GET);
/// <summary>
/// Updates a rune page.
/// </summary>
/// <param name="id">The page's ID.</param>
/// <param name="page">The new page.</param>
public Task<LolPerksPerkPageResource> PutPageAsync(int id, LolPerksPerkPageResource page)
=> Client.MakeRequestAsync<LolPerksPerkPageResource>($"/lol-perks/v1/pages/{id}", Method.PUT, page);
/// <summary>
/// Creates a new rune page.
/// </summary>
/// <param name="page">The new page.</param>
public Task<LolPerksPerkPageResource> PostPageAsync(LolPerksPerkPageResource page)
=> Client.MakeRequestAsync<LolPerksPerkPageResource>("/lol-perks/v1/pages", Method.POST, page);
/// <summary>
/// Gets a list of all the runes in LoL.
/// </summary>
public async Task<LolPerksPerkUIPerk[]> GetPerksAsync()
=> (await Client.MakeRequestAsync<List<LolPerksPerkUIPerk>>("/lol-perks/v1/perks", Method.GET)).ToArray();
public Task<LolPerksPlayerInventory> GetInventoryAsync()
=> Client.MakeRequestAsync<LolPerksPlayerInventory>("/lol-perks/v1/inventory", Method.GET);
/// <summary>
/// Gets a rune's icon.
/// </summary>
/// <param name="perk">The rune. See <see cref="GetPerks"/>.</param>
public Task<Image> GetPerkImageAsync(LolPerksPerkUIPerk perk) => Cache(async () =>
{
string[] split = perk.iconPath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string plugin = split[0];
string path = string.Join("/", split.Skip(2));
byte[] b = await PluginManager.GetAssetAsync(plugin, path).ConfigureAwait(false);
using (var mem = new MemoryStream(b))
{
return Image.FromStream(mem);
}
});
}
}
| 39.859649 | 146 | 0.625 | [
"MIT"
] | pipe01/LCU.NET | Plugins/LoL/Perks.cs | 4,544 | C# |
using System;
namespace c_sharp_fundamentals
{
/// <summary>
/// Program.cs is a static class that contains only one static method - Main() method which is required to start an app
/// </summary>
class Program
{
/// <summary>
/// The Main() method is required in every C# app. It specifies where the execution point starts.
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
// This {} and the codes inside are called a code block
{
//string name = SayHi();
//Age();
// When we call Console here, we are actually calling it from .NET Framework library.
// The dot after it is called a member accesser to allow us to access a member of the class. WriteLine is a member of the Console class.
//Console.Write("Enter your birthday MM/DD: ");
//Birthday(Console.ReadLine());
//GuessANumber();
//CanYouReadTheSentence();
//ArraySize();
//Console.WriteLine("Enter two numbers. One at a time.");
//Console.WriteLine("Enter the first number:");
//int num1 = Convert.ToInt32(Console.ReadLine());
//Console.WriteLine("Enter the second number:");
//int num2 = Convert.ToInt32(Console.ReadLine());
//int sum = AddNumbers(num1, num2);
//Console.WriteLine("Enter a last number.");
//int num3 = Convert.ToInt32(Console.ReadLine());
//int multiplication = MultiplyNumbers(sum, num3);
}
#region SayHi()
/// <summary>
/// This method takes in no parameter and returns a boolean
/// The method takes in the user's response and lowercases the answer. Therefore, whether the user types a Y or y, they can both be processed as a yes
/// If the user types in Y/y, print to the console "Let's play a game" and invoke the PlayGame() method
/// If the user types in any character other than Y or y, print to the console "Alright. Maybe next time." and exit the method
/// </summary>
static string SayHi()
{
Console.Write("What is your name? ");
string name = Console.ReadLine();
Console.WriteLine($"It's very nice to meet you {name}!\n");
Console.Write("Would you like to know your unique number based on your name (Y/N)? ");
string game = Console.ReadLine().ToLower();
string message = game == "y" ? $"Your name is {name}, therefore your unique number is {UniqueNumber(name)}" : "Alright! Maybe next time.";
Console.WriteLine(message);
Console.ReadLine();
return name;
}
#endregion
#region UniqueNumber()
/// <summary>
/// This method takes in a string returns an integer
/// The method gets the ASCII numbers of each character in name and add all the numbers together as the unique number
/// </summary>
static int UniqueNumber(string name)
{
char[] nameCharacters = name.ToCharArray();
int uniqueNumber = 0;
foreach (char character in nameCharacters)
{
uniqueNumber += char.ToUpper(character); // Use char.ToUpper to get each character's ASCII code
}
return uniqueNumber;
}
#endregion
#region Age()
/// <summary>
/// This method takes in no parameter and returns nothing
/// It asks the user to enter his/her age and print to the console how many months and how many days they have lived.
/// To prevent the user enters an incorrect data type, use try and catch clause to avoid the program from breaking
/// </summary>
static void Age()
{
Console.Write("Enter your age: ");
try
{
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"You have lived {age * 12} months or {age * 365} days!");
}
catch
{
Console.WriteLine("You did not enter a valid answer.");
};
Console.ReadLine();
}
#endregion
#region Birthday()
/// <summary>
/// This method takes in a string format of the user's birthday MM/DD
/// Concatenate the user's birthday with the current year in a string format
/// Convert the complete birthday date to a DateTime data type then deduct today's date to determine how many days are left until the user's next birthday
/// The result above is converted and stored as a string. Then use IndexOf() pre-determined method to get the days only from the result
/// When the result is 0 days away from the next birthday, the result does not have a . and therefore it will be set to -1 by default but this will crash the program
/// To avoid crashing the program, set the index to be 1
/// Convert the days in the string data type to an int data type
/// Based on how many days to the next birthday, print different message to the console window
/// If the birthday has already passed for this year, concatenate the user's birthday with the next year's string
/// Calculate how many days are there until the next birthday using the next year's birthday date
/// Print the result to the console window
/// </summary>
/// <param name="birthday"></param>
/// <returns></returns>
static bool Birthday(string birthday)
{
try
{
string thisYear = "/2020";
string nextYear = "/2021";
string daysUntilNextBirthday = (Convert.ToDateTime(birthday + thisYear) - DateTime.Today).ToString();
// When there's more than 0 days until the next birthday, the calculation result would be in this format: {3.00:00:00}
// If there's 0 day until the next birthday, the calculation result would be {00:00:00}
// Therefore, a default index 1 is set to prevent the program from breaking
int index = (daysUntilNextBirthday.IndexOf(".") >= 0) ? daysUntilNextBirthday.IndexOf(".") : 1 ;
int days = Convert.ToInt32(daysUntilNextBirthday.Substring(0, index));
if (days >= 0)
{
string message = $"Your next birthday is {daysUntilNextBirthday.Substring(0, index)}";
if (days >= 2)
{
Console.WriteLine(message + " days away.");
return true;
}
if (days > 0)
{
Console.WriteLine(message + " day away.");
return true;
}
if (days == 0)
{
Console.WriteLine($"Your next birthday is today!");
return true;
}
}
else
{
daysUntilNextBirthday = (Convert.ToDateTime(birthday + nextYear) - DateTime.Today).ToString();
int index2 = daysUntilNextBirthday.IndexOf(".");
Console.WriteLine($"Your next birthday is {daysUntilNextBirthday.Substring(0, index2)} days away");
return true;
}
return false;
}
catch
{
Console.WriteLine("You did not enter a valid answer.");
return false;
};
}
#endregion
#region GuessANumber()
/// <summary>
/// Practice for loop. This method takes in no parameter and does not return anything
/// Use Random class and .Next() method to generate a number between 1 to 10 and store the answer in the answer variable
/// Iterate a for loop three times and check if the user's guess matches with the answer
/// If yes, print the message to the console and break out from the for loop
/// If no, let the user know how many times they have left to guess the right answer
/// If the user guess a number that is out of the range of 1 to 10, notify them and let them guess again
/// Once the user uses up three chances, break out from the for loop and tell the the correct answer
/// If the user enters an invalid character, let them know and terminate the program
/// </summary>
static void GuessANumber()
{
bool play = true;
while (play)
{
try
{
Console.WriteLine("Guess a number between 1 to 10. You have 3 chances. ");
Random random = new Random();
int answer = random.Next(11);
for (int i = 0; i < 3; i++)
{
Console.Write("Enter a number: ");
int guess = Convert.ToInt32(Console.ReadLine());
if (guess == answer)
{
Console.WriteLine($"\nYou guess it right!");
break;
}
else if (guess < 1 || guess > 10)
{
Console.WriteLine("\nPlease enter a number between 1 and 10.");
Console.WriteLine($"You have {2 - i} more chance.\n");
}
else
{
Console.WriteLine($"\nWrong answer. You have {2 - i} more chance.");
}
}
Console.WriteLine($"The correct answer is {answer}.");
play = false;
}
catch
{
Console.WriteLine("You did not enter a valid number.\n");
}
}
}
#endregion
#region CanYouReadTheSentence()
/// <summary>
/// Print to the console the three sentences for the user to choose which one to revserse
/// Store the user's selection. If the user does not select one of the valid options, let them know and restart the game
/// Based on the user's selection, convert the sentence to a char array
/// Store the user's attempt answer in a char array and reverse the array
/// Compare the answer char array to the user's attempt char array character by character
/// If find a different character, let the user know that they did not get it right and ask if they want to try again
/// If the user wants to try again, break out the for loop and restart the game
/// If the user does not want to try again, terminate the program
/// If comparing both arrays to the last character and no differences are found, let the user know that they win and do not restart the game again
/// </summary>
static void CanYouReadTheSentence()
{
bool play = true;
while (play)
{
Console.WriteLine("Can you reverse one of the sentences below and type out the right sentence?");
Console.WriteLine("Example: ?siht daer uoy naC\nAnswer: Can you read this?\n");
string sentence1 = ".saedi ssucsid sdnim taerG";
string sentence2 = ".deeccus ot deirt evah ot reven esrow si ti tub ,liaf ot drah si tI";
string sentence3 = ".era ylurt ew tahw wohs taht seciohc ruo si tI";
Console.WriteLine($"1) {sentence1}");
Console.WriteLine($"2) {sentence2}");
Console.WriteLine($"3) {sentence3}");
Console.Write("\nPlease select one of the sentences to reverse: ");
string selection = Console.ReadLine();
char[] answerChar = new char[] {};
// The logic here is if selection is not "1" and not "2" and not "3", run the code
// Conditional logical operator || cannot be used here because if selection is not "1" or not "2" or not "3", run the code
// This does not work because if the user selects "1", it satisfy the two other conditions selection is not "2" or not "3", the code will run
// You want to run the code only when the selection is not "1" and not "2" and not "3"
if (selection != "1" && selection != "2" && selection != "3")
{
Console.WriteLine("You did not enter a valid number.\n");
}
else
{
Console.WriteLine("Please type your answer here: ");
char[] attemptChar = Console.ReadLine().ToCharArray();
switch (selection)
{
case "1":
answerChar = sentence1.ToCharArray();
break;
case "2":
answerChar = sentence2.ToCharArray();
break;
case "3":
answerChar = sentence3.ToCharArray();
break;
default:
break;
}
Array.Reverse(attemptChar);
for (int i = 0; i < attemptChar.Length; i++)
{
if (attemptChar[i] != answerChar[i])
{
Console.Write("You did not get it right.\nWould you like to try again(Y/N)? ");
string tryAgain = Console.ReadLine().ToLower();
Console.WriteLine();
play = (tryAgain == "y") ? true : false;
break;
}
if (i == attemptChar.Length - 1 && attemptChar[attemptChar.Length-1] == answerChar[attemptChar.Length - 1])
{
Console.WriteLine("\nAwesome! You got it right!");
play = false;
}
}
}
}
}
#endregion
#region ArraySize()
//Array with size specified and without size specified
/// <summary>
/// Pracitce pre-defined array methods including .Length, Array.Reverse(), and Array.Sort()
/// </summary>
static void ArraySize()
{
int[] array1 = new int[5];
int[] array2 = new int[] { 0, 5, 10, 15, 20, 25 };
int[] array3 = { 13, 11, 9, 7, 5, 3, 1 };
string[] array4 = { "Jeff", "Cindy", "Mark", "Eva", "Andy", "Lily", "Jason", "Anderson", "Nicole" };
// assign array1 index position 0 to be value of integer 1
array1[0] = 1;
// assign array1 index position 1 to be value of integer 2
array1[1] = 2;
Console.WriteLine($"Array1's length: {array1.Length}");
PrintIntArray(array1);
Console.WriteLine($"Array2's length: {array2.Length}");
PrintIntArray(array2);
Console.WriteLine($"Array3's length: {array3.Length}");
PrintIntArray(array3);
Array.Sort(array3);
PrintIntArray(array3);
Console.WriteLine($"Array4's length: {array4.Length}");
PrintStringArray(array4);
Array.Sort(array4);
PrintStringArray(array4);
}
// Use foreach to print out values from an int array
static void PrintIntArray(int[] intArray)
{
Console.WriteLine("Array values:");
foreach (int value in intArray)
{
Console.Write($"{value} -> ");
}
Console.WriteLine("x");
Console.WriteLine();
}
// Use foreach to print out values from an string array
static void PrintStringArray(string[] stringArray)
{
foreach (string value in stringArray)
{
Console.Write($"{value} -> ");
}
Console.WriteLine("x");
Console.WriteLine();
}
#endregion
#region AddNumbers()
/// <summary>
/// This method takes in two numbers (int) and returns the sum (int) of the two numbers
/// </summary>
/// <param name="num1">The first number you want to add together</param>
/// <param name="num2">The second number you want to add together</param>
/// <returns>The sum of the two numbers</returns>
static int AddNumbers(int num1, int num2)
{
int sum = num1 + num2;
Console.WriteLine($"The sum of {num1} and {num2} is {sum}");
return sum;
}
#endregion
#region MultiplyNumbers()
/// <summary>
/// This method takes in two numbers (int) and returns the multiplication (int) of the two numbers
/// </summary>
/// <param name="num1">The first number you want to multiply together</param>
/// <param name="num2">The second number you want to multiply together</param>
/// <returns>The multiplication of the two numbers</returns>
static int MultiplyNumbers(int num1, int num2)
{
int sum = num1 * num2;
Console.WriteLine($"The multiplication of {num1} and {num2} is {sum}");
return sum;
}
#endregion
}
}
| 45.482234 | 173 | 0.52606 | [
"MIT"
] | karina6188/C_Sharp_Fundamentals | c_sharp_fundamentals/c_sharp_fundamentals/Program.cs | 17,922 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Xunit;
namespace Microsoft.Azure.SignalR.Common.Tests
{
public class ClaimsUtilityTests
{
private static readonly Claim[] JwtAuthenticatedClaims = new Claim[] { new Claim("dummy", "dummy"), new Claim("name", "name"), new Claim("role", "admin"), new Claim("aud", "aud") };
private static readonly (ClaimsIdentity identity, string userId, Func<IEnumerable<Claim>> provider, string expectedAuthenticationType, int expectedClaimsCount)[] _claimsParameters =
{
(new ClaimsIdentity(), null, null, null, 0),
(new ClaimsIdentity(null, null, null, null), null, null, null, 0),
(new ClaimsIdentity("", "", ""), "", () => JwtAuthenticatedClaims, "", 4),
(new ClaimsIdentity(), "user1", () => JwtAuthenticatedClaims, "Bearer", 4),
(new ClaimsIdentity(JwtAuthenticatedClaims, "Bearer"), null, null, "Bearer", 4),
(new ClaimsIdentity(JwtAuthenticatedClaims, "Bearer", "name", "role"), null, null, "Bearer", 4),
(new ClaimsIdentity("jwt", "name", "role"), "user", () => JwtAuthenticatedClaims, "jwt", 4),
};
public static IEnumerable<object[]> ClaimsParameters =>
_claimsParameters.Select(provider => new object[] { provider.identity, provider.userId, provider.provider, provider.expectedAuthenticationType, provider.expectedClaimsCount });
[Fact]
public void TestGetSystemClaimsWithDefaultValue()
{
var claims = ClaimsUtility.BuildJwtClaims(null, null, null).ToList();
Assert.Empty(claims);
}
[Theory]
[MemberData(nameof(ClaimsParameters))]
public void TestGetSystemClaims(ClaimsIdentity identity, string userId, Func<IEnumerable<Claim>> provider, string expectedAuthenticationType, int expectedClaimsCount)
{
var claims = ClaimsUtility.BuildJwtClaims(new ClaimsPrincipal(identity), userId, provider).ToArray();
var resultIdentity = ClaimsUtility.GetUserPrincipal(claims).Identity;
var ci = resultIdentity as ClaimsIdentity;
Assert.NotNull(ci);
Assert.Equal(expectedAuthenticationType, ci.AuthenticationType);
Assert.Equal(identity.RoleClaimType, ci.RoleClaimType);
Assert.Equal(identity.NameClaimType, ci.NameClaimType);
Assert.Equal(expectedClaimsCount, ci.Claims.Count());
}
}
}
| 48.563636 | 189 | 0.669038 | [
"MIT"
] | Andy9FromSpace/azure-signalr | test/Microsoft.Azure.SignalR.Common.Tests/ClaimsUtilityTests.cs | 2,671 | C# |
namespace DevTeam.Patterns.IoC
{
using System;
internal class ContainerDescription
{
public ContainerDescription(IContainer parentContainer, object key)
{
if (parentContainer == null) throw new ArgumentNullException(nameof(parentContainer));
ParentContainer = parentContainer;
Key = key;
}
public IContainer ParentContainer { get; private set; }
public object Key { get; private set; }
public override string ToString()
{
return $"{nameof(ContainerDescription)} [ParentContainer: {ParentContainer}, Key: {Key?.ToString() ?? "null"}]";
}
}
}
| 27 | 124 | 0.619259 | [
"MIT"
] | DevTeam/patterns | DevTeam.Patterns.IoC/ContainerDescription.cs | 677 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using Microsoft.Azure.PowerShell.Cmdlets.Synapse.Runtime.Json;
using System;
namespace Microsoft.Azure.PowerShell.Cmdlets.Synapse.Runtime
{
public interface IJsonSerializable
{
JsonNode ToJson(JsonObject container = null, SerializationMode serializationMode = SerializationMode.None);
}
internal static class JsonSerializable
{
/// <summary>
/// Serializes an enumerable and returns a JsonNode.
/// </summary>
/// <param name="enumerable">an IEnumerable collection of items</param>
/// <returns>A JsonNode that contains the collection of items serialized.</returns>
private static JsonNode ToJsonValue(System.Collections.IEnumerable enumerable)
{
if (enumerable != null)
{
// is it a byte array of some kind?
if (enumerable is System.Collections.Generic.IEnumerable<byte> byteEnumerable)
{
return new XBinary(System.Linq.Enumerable.ToArray(byteEnumerable));
}
var hasValues = false;
// just create an array of value nodes.
var result = new XNodeArray();
foreach (var each in enumerable)
{
// we had at least one value.
hasValues = true;
// try to serialize it.
var node = ToJsonValue(each);
if (null != node)
{
result.Add(node);
}
}
// if we were able to add values, (or it was just empty), return it.
if (result.Count > 0 || !hasValues)
{
return result;
}
}
// we couldn't serialize the values. Sorry.
return null;
}
/// <summary>
/// Serializes a valuetype to a JsonNode.
/// </summary>
/// <param name="vValue">a <c>ValueType</c> (ie, a primitive, enum or struct) to be serialized </param>
/// <returns>a JsonNode with the serialized value</returns>
private static JsonNode ToJsonValue(ValueType vValue)
{
// numeric type
if (vValue is SByte || vValue is Int16 || vValue is Int32 || vValue is Int64 || vValue is Byte || vValue is UInt16 || vValue is UInt32 || vValue is UInt64 || vValue is decimal || vValue is float || vValue is double)
{
return new JsonNumber(vValue.ToString());
}
// boolean type
if (vValue is bool bValue)
{
return new JsonBoolean(bValue);
}
// dates
if (vValue is DateTime dtValue)
{
return new JsonDate(dtValue);
}
// sorry, no idea.
return null;
}
/// <summary>
/// Attempts to serialize an object by using ToJson() or ToJsonString() if they exist.
/// </summary>
/// <param name="oValue">the object to be serialized.</param>
/// <returns>the serialized JsonNode (if successful), otherwise, <c>null</c></returns>
private static JsonNode TryToJsonValue(dynamic oValue)
{
object jsonValue = null;
dynamic v = oValue;
try
{
jsonValue = v.ToJson().ToString();
}
catch
{
// no harm...
try
{
jsonValue = v.ToJsonString().ToString();
}
catch
{
// no worries here either.
}
}
// if we got something out, let's use it.
if (null != jsonValue)
{
// JsonNumber is really a literal json value. Just don't try to cast that back to an actual number, ok?
return new JsonNumber(jsonValue.ToString());
}
return null;
}
/// <summary>
/// Serialize an object by using a variety of methods.
/// </summary>
/// <param name="oValue">the object to be serialized.</param>
/// <returns>the serialized JsonNode (if successful), otherwise, <c>null</c></returns>
internal static JsonNode ToJsonValue(object value)
{
// things that implement our interface are preferred.
if (value is Microsoft.Azure.PowerShell.Cmdlets.Synapse.Runtime.IJsonSerializable jsonSerializable)
{
return jsonSerializable.ToJson();
}
// strings are easy.
if (value is string || value is char)
{
return new JsonString(value.ToString());
}
// value types are fairly straightforward (fallback to ToJson()/ToJsonString() or literal JsonString )
if (value is System.ValueType vValue)
{
return ToJsonValue(vValue) ?? TryToJsonValue(vValue) ?? new JsonString(vValue.ToString());
}
// dictionaries are objects that should be able to serialize
if (value is System.Collections.Generic.IDictionary<string, object> dictionary)
{
return Microsoft.Azure.PowerShell.Cmdlets.Synapse.Runtime.JsonSerializable.ToJson(dictionary, null);
}
// enumerable collections are handled like arrays (again, fallback to ToJson()/ToJsonString() or literal JsonString)
if (value is System.Collections.IEnumerable enumerableValue)
{
// some kind of enumerable value
return ToJsonValue(enumerableValue) ?? TryToJsonValue(value) ?? new JsonString(value.ToString());
}
// at this point, we're going to fallback to a string literal here, since we really have no idea what it is.
return new JsonString(value.ToString());
}
internal static JsonObject ToJson<T>(System.Collections.Generic.Dictionary<string, T> dictionary, JsonObject container) => ToJson((System.Collections.Generic.IDictionary<string, T>)dictionary, container);
/// <summary>
/// Serializes a dictionary into a JsonObject container.
/// </summary>
/// <param name="dictionary">The dictionary to serailize</param>
/// <param name="container">the container to serialize the dictionary into</param>
/// <returns>the container</returns>
internal static JsonObject ToJson<T>(System.Collections.Generic.IDictionary<string, T> dictionary, JsonObject container)
{
container = container ?? new JsonObject();
if (dictionary != null && dictionary.Count > 0)
{
foreach (var key in dictionary)
{
// currently, we don't serialize null values.
if (null != key.Value)
{
container.Add(key.Key, ToJsonValue(key.Value));
continue;
}
}
}
return container;
}
internal static Func<JsonObject, System.Collections.Generic.IDictionary<string, V>> DeserializeDictionary<V>(Func<System.Collections.Generic.IDictionary<string, V>> dictionaryFactory)
{
return (node) => FromJson<V>(node, dictionaryFactory(), (object)(DeserializeDictionary(dictionaryFactory)) as Func<JsonObject, V>);
}
internal static System.Collections.Generic.IDictionary<string, V> FromJson<V>(JsonObject json, System.Collections.Generic.Dictionary<string, V> container, System.Func<JsonObject, V> objectFactory, System.Collections.Generic.HashSet<string> excludes = null) => FromJson(json, (System.Collections.Generic.IDictionary<string, V>)container, objectFactory, excludes);
internal static System.Collections.Generic.IDictionary<string, V> FromJson<V>(JsonObject json, System.Collections.Generic.IDictionary<string, V> container, System.Func<JsonObject, V> objectFactory, System.Collections.Generic.HashSet<string> excludes = null)
{
if (null == json)
{
return container;
}
foreach (var key in json.Keys)
{
if (true == excludes?.Contains(key))
{
continue;
}
var value = json[key];
try
{
switch (value.Type)
{
case JsonType.Null:
// skip null values.
continue;
case JsonType.Array:
case JsonType.Boolean:
case JsonType.Date:
case JsonType.Binary:
case JsonType.Number:
case JsonType.String:
container.Add(key, (V)value.ToValue());
break;
case JsonType.Object:
if (objectFactory != null)
{
var v = objectFactory(value as JsonObject);
if (null != v)
{
container.Add(key, v);
}
}
break;
}
}
catch
{
}
}
return container;
}
}
} | 41.823293 | 371 | 0.498848 | [
"MIT"
] | Amrinder-Singh29/azure-powershell | src/Synapse/Synapse.Autorest/generated/runtime/Customizations/IJsonSerializable.cs | 10,166 | C# |
using System;
using System.Linq;
using System.Text;
using MinionSuite.Tool.Extensions;
using MinionSuite.Tool.Helpers;
namespace MinionSuite.Tool.Generators
{
/// <summary>
/// Generates an API controller with CRUD operations for a model
/// </summary>
public class ApiControllerGenerator : IGenerator
{
/// <summary>
/// Generates an API controller with CRUD operations for a model
/// </summary>
/// <param name="argReader">Information fetched from the command line arguments</param>
public void Generate(ArgReader argReader)
{
var metadata = new ModelMetadata(argReader.ModelPath);
var builder = new StringBuilder();
var filledProperties = metadata.Properties
.Where(w => w.Key != metadata.KeyName && w.Key != "CreatedAt" && w.Key != "UpdatedAt");
builder
.AppendNestedLine(0, "using System;")
.AppendNestedLine(0, "using System.Threading.Tasks;")
.AppendNestedLine(0, "using Microsoft.AspNetCore.Mvc;")
.AppendNestedLine(0, $"using {metadata.Namespace};")
.AppendLine()
.AppendNestedLine(0, $"namespace {argReader.Namespace}")
.AppendNestedLine(0, "{")
.AppendNestedLine(1, "[Route(\"api/[controller]\")]")
.AppendNestedLine(1, "[ApiController]")
.AppendNestedLine(1, $"public class {metadata.PluralName}Controller : ControllerBase")
.AppendNestedLine(1, "{")
.AppendNestedLine(2, "private const int PAGE_SIZE = 20;")
.AppendLine()
.AppendNestedLine(2, $"private readonly I{metadata.Name}Service _service;")
.AppendLine()
.AppendNestedLine(2, $"public {metadata.PluralName}Controller(I{metadata.Name}Service service)")
.AppendNestedLine(2, "{")
.AppendNestedLine(3, "_service = service;")
.AppendNestedLine(2, "}")
.AppendLine()
.AppendNestedLine(2, "[HttpGet]")
.AppendNestedLine(2, "public async Task<IActionResult> GetAll(string term, int page = 1, string sortField = \"\", bool asc = true)")
.AppendNestedLine(2, "{")
.AppendNestedLine(3, "var entities = string.IsNullOrWhiteSpace(term)")
.AppendNestedLine(4, "? await _service.GetAllAsync(page, PAGE_SIZE, sortField, asc)")
.AppendNestedLine(4, ": await _service.SearchAsync(term, page, PAGE_SIZE, sortField, asc);")
.AppendLine()
.AppendNestedLine(3, "return Ok(entities);")
.AppendNestedLine(2, "}")
.AppendLine()
.AppendNestedLine(2, "[HttpGet(\"{id}\")]")
.AppendNestedLine(2, $"public async Task<IActionResult> Get({metadata.KeyProperty.TypeName} id)")
.AppendNestedLine(2, "{")
.AppendNestedLine(3, "var entity = await _service.GetAsync(id);")
.AppendNestedLine(3, "if (entity == null)")
.AppendNestedLine(3, "{")
.AppendNestedLine(4, "return NotFound();")
.AppendNestedLine(3, "}")
.AppendLine()
.AppendNestedLine(3, "return Ok(entity);")
.AppendNestedLine(2, "}")
.AppendLine()
.AppendNestedLine(2, "[HttpPost]")
.AppendNestedLine(2, $"public async Task<IActionResult> Create({metadata.Name} entity)")
.AppendNestedLine(2, "{")
.AppendNestedLine(3, "var result = await _service.CreateAsync(entity);")
.AppendLine()
.AppendNestedLine(3, "return Ok(result);")
.AppendNestedLine(2, "}")
.AppendLine()
.AppendNestedLine(2, "[HttpPut(\"{id}\")]")
.AppendNestedLine(2, $"public async Task<IActionResult> Update({metadata.Name} entity)")
.AppendNestedLine(2, "{")
.AppendNestedLine(3, "var result = await _service.UpdateAsync(entity);")
.AppendNestedLine(3, "if (result == null)")
.AppendNestedLine(3, "{")
.AppendNestedLine(4, "return NotFound();")
.AppendNestedLine(3, "}")
.AppendLine()
.AppendNestedLine(3, "return Ok(result);")
.AppendNestedLine(2, "}")
.AppendLine()
.AppendNestedLine(2, "[HttpDelete(\"{id}\")]")
.AppendNestedLine(2, $"public async Task<IActionResult> Delete({metadata.KeyProperty.TypeName} id)")
.AppendNestedLine(2, "{")
.AppendNestedLine(3, "var result = await _service.DeleteAsync(id);")
.AppendNestedLine(3, "if (result)")
.AppendNestedLine(3, "{")
.AppendNestedLine(4, "return Ok();")
.AppendNestedLine(3, "}")
.AppendLine()
.AppendNestedLine(3, "return NotFound();")
.AppendNestedLine(2, "}")
.AppendNestedLine(1, "}")
.AppendNestedLine(0, "}");
FileHelper.SaveToOutput(argReader.OutputFolder, $"{metadata.PluralName}Controller.cs", builder.ToString());
}
/// <summary>
/// Displays a help message
/// </summary>
public void ShowHelpMessage()
{
var builder = new StringBuilder();
builder
.AppendLine("Usage: minionsuite apicontroller [parameters]")
.AppendLine()
.AppendLine("Generates an API controller with CRUD operations on a model class.")
.AppendLine()
.AppendLine("Parameters:")
.AppendLine(" -m|--model-path <path>:\tThe path to the model class.")
.AppendLine(" -ns|--namespace <name>:\tThe namespace of the generated class.")
.AppendLine(" -o|--output <path>:\t\tThe path to the output folder (default: .).");
Console.WriteLine(builder.ToString());
}
}
}
| 49.468254 | 148 | 0.545323 | [
"MIT"
] | printezisn/minionsuite | MinionSuite/MinionSuite.Tool/Generators/ApiControllerGenerator.cs | 6,235 | C# |
using System;
using GestionaleFitstic.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
[assembly: HostingStartup(typeof(GestionaleFitstic.Areas.Identity.IdentityHostingStartup))]
namespace GestionaleFitstic.Areas.Identity
{
public class IdentityHostingStartup : IHostingStartup
{
public void Configure(IWebHostBuilder builder)
{
builder.ConfigureServices((context, services) => {
});
}
}
} | 30.857143 | 91 | 0.762346 | [
"MIT"
] | FITSTIC/Hackathon_Team2_19_21 | GestionaleFitstic/GestionaleFitstic/Areas/Identity/IdentityHostingStartup.cs | 650 | C# |
using System;
using BEPUphysics.Entities;
using BEPUphysics.Entities.Prefabs;
using BEPUphysics.UpdateableSystems.ForceFields;
using BEPUphysicsDemos.SampleCode;
using BEPUphysics.NarrowPhaseSystems;
using BEPUutilities;
using FixMath.NET;
namespace BEPUphysicsDemos.Demos
{
/// <summary>
/// Boxes fall on a planetoid.
/// </summary>
public class PlanetDemo : StandardDemo
{
private Vector3 planetPosition;
/// <summary>
/// Constructs a new demo.
/// </summary>
/// <param name="game">Game owning this demo.</param>
public PlanetDemo(DemosGame game)
: base(game)
{
Space.ForceUpdater.Gravity = Vector3.Zero;
//By pre-allocating a bunch of box-box pair handlers, the simulation will avoid having to allocate new ones at runtime.
NarrowPhaseHelper.Factories.BoxBox.EnsureCount(1000);
planetPosition = new Vector3(0, 0, 0);
var planet = new Sphere(planetPosition, 30);
Space.Add(planet);
var field = new GravitationalField(new InfiniteForceFieldShape(), planet.Position, 66730 / 2, 100);
Space.Add(field);
//Drop the "meteorites" on the planet.
Entity toAdd;
int numColumns = 10;
int numRows = 10;
int numHigh = 10;
Fix64 separation = 5;
for (int i = 0; i < numRows; i++)
for (int j = 0; j < numColumns; j++)
for (int k = 0; k < numHigh; k++)
{
toAdd = new Box(new Vector3(separation * i - numRows * separation / 2, 40 + k * separation, separation * j - numColumns * separation / 2), 1, 1, 1, 5);
toAdd.LinearVelocity = new Vector3(30, 0, 0);
toAdd.LinearDamping = 0;
toAdd.AngularDamping = 0;
Space.Add(toAdd);
}
game.Camera.Position = new Vector3(0, 0, 150);
}
/// <summary>
/// Gets the name of the simulation.
/// </summary>
public override string Name
{
get { return "Planet"; }
}
public override void Update(Fix64 dt)
{
//Orient the character and camera as needed.
if (character.IsActive)
{
var down = planetPosition - character.CharacterController.Body.Position;
character.CharacterController.Down = down;
Game.Camera.LockedUp = -down;
}
else if (vehicle.IsActive)
{
Game.Camera.LockedUp = vehicle.Vehicle.Body.Position - planetPosition;
}
else
{
Game.Camera.LockedUp = Vector3.Up;
}
base.Update(dt);
}
}
} | 33.322222 | 176 | 0.517506 | [
"MIT"
] | RossNordby/bepuphysics1int | BEPUphysicsDemos/Demos/PlanetDemo.cs | 3,001 | C# |
using FluentPOS.Shared.Core.Domain;
using FluentPOS.Shared.Core.EventLogging;
using FluentPOS.Shared.Core.Settings;
using FluentPOS.Shared.Infrastructure.Extensions;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System.Threading;
using System.Threading.Tasks;
using FluentPOS.Shared.Core.Interfaces;
namespace FluentPOS.Shared.Infrastructure.Persistence
{
public abstract class ModuleDbContext : DbContext, IModuleDbContext
{
private readonly IMediator _mediator;
private readonly IEventLogger _eventLogger;
private readonly PersistenceSettings _persistenceOptions;
protected abstract string Schema { get; }
protected ModuleDbContext(
DbContextOptions options,
IMediator mediator,
IEventLogger eventLogger,
IOptions<PersistenceSettings> persistenceOptions) : base(options)
{
_mediator = mediator;
_eventLogger = eventLogger;
_persistenceOptions = persistenceOptions.Value;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
if (!string.IsNullOrWhiteSpace(Schema))
{
modelBuilder.HasDefaultSchema(Schema);
}
modelBuilder.Ignore<Event>();
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly);
modelBuilder.ApplyModuleConfiguration(_persistenceOptions);
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
return await this.SaveChangeWithPublishEventsAsync(_eventLogger, _mediator, cancellationToken);
}
public override int SaveChanges()
{
return this.SaveChangeWithPublishEvents(_eventLogger, _mediator);
}
public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
return SaveChanges();
}
}
} | 34.233333 | 107 | 0.685492 | [
"MIT"
] | abdul-qadirdeveloper/fluentpos | src/server/Shared/Shared.Infrastructure/Persistence/ModuleDbContext.cs | 2,056 | C# |
namespace TokanPages.Backend.Shared.Dto.Content
{
using Base;
public class NotFoundDto : BaseClass
{
public string Code { get; set; }
public string Header { get; set; }
public string Description { get; set; }
public string Button { get; set; }
}
} | 19.933333 | 47 | 0.605351 | [
"MIT"
] | TomaszKandula/TokanPages | TokanPages.Backend/TokanPages.Backend.Shared/Dto/Content/NotFoundDto.cs | 299 | C# |
using Liru3D.Models.Data;
using Microsoft.Xna.Framework.Graphics;
namespace Liru3D.Models
{
/// <summary> A single mesh of a <see cref="SkinnedModel"/>. </summary>
public class SkinnedMesh
{
#region Dependencies
private readonly GraphicsDevice graphicsDevice;
#endregion
#region Properties
/// <summary> The name of the mesh. </summary>
public string Name { get; }
/// <summary> The vertex buffer object that contains the vertex data of this mesh. </summary>
public VertexBuffer VertexBuffer { get; }
/// <summary> The index buffer object that contains the index data of this mesh. </summary>
public IndexBuffer IndexBuffer { get; }
#endregion
#region Constructors
private SkinnedMesh(GraphicsDevice graphicsDevice, VertexBuffer vertexBuffer, IndexBuffer indexBuffer, string name)
{
this.graphicsDevice = graphicsDevice ?? throw new System.ArgumentNullException(nameof(graphicsDevice));
VertexBuffer = vertexBuffer ?? throw new System.ArgumentNullException(nameof(vertexBuffer));
IndexBuffer = indexBuffer ?? throw new System.ArgumentNullException(nameof(indexBuffer));
Name = name;
}
#endregion
#region Creation Functions
/// <summary> Creates and returns a new skinned mesh from the given <paramref name="data"/>, uploaded onto the given <paramref name="graphicsDevice"/>. </summary>
/// <param name="graphicsDevice"> The graphics device onto which the mesh will be uploaded. </param>
/// <param name="data"> The mesh data. </param>
/// <returns> The created skinned mesh. </returns>
public static SkinnedMesh CreateFrom(GraphicsDevice graphicsDevice, SkinnedMeshData data)
{
// Create a vertex buffer.
VertexBuffer vertexBuffer = new VertexBuffer(graphicsDevice, SkinnedVertex.VertexDeclaration, data.Vertices.Length * SkinnedVertex.VertexDeclaration.VertexStride, BufferUsage.WriteOnly);
vertexBuffer.SetData(0, data.Vertices, 0, data.Vertices.Length, SkinnedVertex.VertexDeclaration.VertexStride);
// Create an index buffer.
IndexBuffer indexBuffer = new IndexBuffer(graphicsDevice, IndexElementSize.ThirtyTwoBits, data.Indices.Length, BufferUsage.WriteOnly);
indexBuffer.SetData(data.Indices);
// Create the skinned mesh using the created data.
SkinnedMesh skinnedMesh = new SkinnedMesh(graphicsDevice, vertexBuffer, indexBuffer, data.Name);
// Return the created mesh.
return skinnedMesh;
}
#endregion
#region Draw Functions
/// <summary> Draws this mesh. </summary>
public void Draw()
{
graphicsDevice.SetVertexBuffer(VertexBuffer);
graphicsDevice.Indices = IndexBuffer;
graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, VertexBuffer.VertexCount);
}
#endregion
}
} | 45.850746 | 198 | 0.670573 | [
"MIT"
] | LiruJ/MonoGame-Skinned-Mesh-Importer | Liru3D/Models/SkinnedMesh.cs | 3,074 | C# |
using System;
using System.Diagnostics;
using System.Resources;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using GymBooster.WindowsSilverPhone.Resources;
using GymBooster.WindowsSilverPhone.ViewModels;
namespace GymBooster.WindowsSilverPhone
{
public partial class App : Application
{
private static MainViewModel viewModel = null;
/// <summary>
/// A static ViewModel used by the views to bind against.
/// </summary>
/// <returns>The MainViewModel object.</returns>
public static MainViewModel ViewModel
{
get
{
// Delay creation of the view model until necessary
if (viewModel == null)
viewModel = new MainViewModel();
return viewModel;
}
}
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public static PhoneApplicationFrame RootFrame { get; private set; }
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Standard XAML initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
// Language display initialization
InitializeLanguage();
// Show graphics profiling information while debugging.
if (Debugger.IsAttached)
{
// Display the current frame rate counters
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are handed off to GPU with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// Prevent the screen from turning off while under the debugger by disabling
// the application's idle detection.
// Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
// and consume battery power when the user is not using the phone.
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
}
// Code to execute when a contract activation such as a file open or save picker returns
// with the picked file or other return values
private void Application_ContractActivated(object sender, Windows.ApplicationModel.Activation.IActivatedEventArgs e)
{
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
// Ensure that application state is restored appropriately
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
// Ensure that required application state is persisted here.
}
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
Debugger.Break();
}
}
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Handle reset requests for clearing the backstack
RootFrame.Navigated += CheckForResetNavigation;
// Handle contract activation such as a file open or save picker
PhoneApplicationService.Current.ContractActivated += Application_ContractActivated;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
private void CheckForResetNavigation(object sender, NavigationEventArgs e)
{
// If the app has received a 'reset' navigation, then we need to check
// on the next navigation to see if the page stack should be reset
if (e.NavigationMode == NavigationMode.Reset)
RootFrame.Navigated += ClearBackStackAfterReset;
}
private void ClearBackStackAfterReset(object sender, NavigationEventArgs e)
{
// Unregister the event so it doesn't get called again
RootFrame.Navigated -= ClearBackStackAfterReset;
// Only clear the stack for 'new' (forward) and 'refresh' navigations
if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh)
return;
// For UI consistency, clear the entire page stack
while (RootFrame.RemoveBackEntry() != null)
{
; // do nothing
}
}
#endregion
// Initialize the app's font and flow direction as defined in its localized resource strings.
//
// To ensure that the font of your application is aligned with its supported languages and that the
// FlowDirection for each of those languages follows its traditional direction, ResourceLanguage
// and ResourceFlowDirection should be initialized in each resx file to match these values with that
// file's culture. For example:
//
// AppResources.es-ES.resx
// ResourceLanguage's value should be "es-ES"
// ResourceFlowDirection's value should be "LeftToRight"
//
// AppResources.ar-SA.resx
// ResourceLanguage's value should be "ar-SA"
// ResourceFlowDirection's value should be "RightToLeft"
//
// For more info on localizing Windows Phone apps see http://go.microsoft.com/fwlink/?LinkId=262072.
//
private void InitializeLanguage()
{
try
{
// Set the font to match the display language defined by the
// ResourceLanguage resource string for each supported language.
//
// Fall back to the font of the neutral language if the Display
// language of the phone is not supported.
//
// If a compiler error is hit then ResourceLanguage is missing from
// the resource file.
RootFrame.Language = XmlLanguage.GetLanguage(AppResources.ResourceLanguage);
// Set the FlowDirection of all elements under the root frame based
// on the ResourceFlowDirection resource string for each
// supported language.
//
// If a compiler error is hit then ResourceFlowDirection is missing from
// the resource file.
FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), AppResources.ResourceFlowDirection);
RootFrame.FlowDirection = flow;
}
catch
{
// If an exception is caught here it is most likely due to either
// ResourceLangauge not being correctly set to a supported language
// code or ResourceFlowDirection is set to a value other than LeftToRight
// or RightToLeft.
if (Debugger.IsAttached)
{
Debugger.Break();
}
throw;
}
}
}
} | 40.527344 | 127 | 0.613976 | [
"MIT"
] | PawelSzczygielski/DajSiePoznac | src/GymBooster.WindowsSilverPhone/App.xaml.cs | 10,377 | C# |
using System;
using FluentAssertions;
using Xunit;
namespace Light.GuardClauses.Tests.ComparableAssertions;
public static class MustBeLessThanOrEqualToTests
{
[Theory]
[InlineData(10, 9)]
[InlineData(-42, -1888)]
public static void ParameterGreater(int first, int second)
{
Action act = () => first.MustBeLessThanOrEqualTo(second, nameof(first));
var exceptionAssertion = act.Should().Throw<ArgumentOutOfRangeException>().Which;
exceptionAssertion.Message.Should().Contain($"{nameof(first)} must be less than or equal to {second}, but it actually is {first}.");
exceptionAssertion.ParamName.Should().BeSameAs(nameof(first));
}
[Theory]
[InlineData(13, 13)]
[InlineData(12, 13)]
public static void ParameterLessOrEqual(int first, int second) => first.MustBeLessThanOrEqualTo(second).Should().Be(first);
[Fact]
public static void CustomException() =>
Test.CustomException(20, 19, (x, y, exceptionFactory) => x.MustBeLessThanOrEqualTo(y, exceptionFactory));
[Fact]
public static void CustomExceptionParameterNull() =>
Test.CustomException((string) null,
"Foo",
(x, y, exceptionFactory) => x.MustBeLessThanOrEqualTo(y, exceptionFactory));
[Fact]
public static void NoCustomExceptionThrown() => 5m.MustBeLessThanOrEqualTo(5.1m, (_, _) => null).Should().Be(5m);
[Fact]
public static void CustomMessage() =>
Test.CustomMessage<ArgumentOutOfRangeException>(message => 'c'.MustBeLessThanOrEqualTo('a', message: message));
[Fact]
public static void CustomMessageParameterNull() =>
Test.CustomMessage<ArgumentNullException>(message => ((string) null).MustBeLessThanOrEqualTo("Bar", message: message));
[Fact]
public static void CallerArgumentExpression()
{
var six = 6;
Action act = () => six.MustBeLessThanOrEqualTo(5);
act.Should().Throw<ArgumentOutOfRangeException>()
.And.ParamName.Should().Be(nameof(six));
}
} | 36.315789 | 140 | 0.671981 | [
"MIT"
] | feO2x/Light.GuardClauses | Code/Light.GuardClauses.Tests/ComparableAssertions/MustBeLessThanOrEqualToTests.cs | 2,072 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace Riganti.Selenium.Coordinator.Service
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
| 22.92 | 64 | 0.586387 | [
"Apache-2.0"
] | JTOne123/selenium-utils | src/Coordinator/Riganti.Selenium.Coordinator.Service/Program.cs | 575 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IBufferInternal.cs" company="Hukano">
// Copyright (c) Hukano. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Sundew.Base.Memory.Internal;
internal interface IBufferInternal<TItem> : IBuffer<TItem>
{
void EnsureAdditionalCapacity(int requiredAdditionalCapacity);
void WriteInternal(TItem item);
} | 44.666667 | 120 | 0.49403 | [
"MIT"
] | hugener/Sundew.Base | Source/Sundew.Base.Memory/Internal/IBufferInternal.cs | 672 | C# |
using System;
using System.Diagnostics;
using System.Threading;
namespace Hudl.FFmpeg.Extensions
{
public static class ProcessExtensions
{
public static bool WaitForProcessStart(this Process process)
{
return process.WaitForProcessStart(null);
}
public static bool WaitForProcessStart(this Process process, int? timeoutMilliseconds)
{
var processTimeout = TimeSpan.FromMilliseconds(timeoutMilliseconds ?? 10000);
return process.WaitForProcessStart(processTimeout);
}
public static bool WaitForProcessStart(this Process process, TimeSpan processTimeout)
{
var processStopwatch = Stopwatch.StartNew();
var isProcessRunning = false;
while (processStopwatch.ElapsedMilliseconds <= processTimeout.TotalMilliseconds && !isProcessRunning)
{
//give a little bit of breathing room here....
Thread.Sleep(20.Milliseconds());
try
{
isProcessRunning = (process != null && process.HasExited && process.Id != 0);
}
catch
{
isProcessRunning = false;
}
}
return isProcessRunning;
}
public static bool WaitForProcessStop(this Process process)
{
return process.WaitForProcessStop(null);
}
public static bool WaitForProcessStop(this Process process, int? timeoutMilliseconds)
{
var processTimeout = TimeSpan.FromMilliseconds(timeoutMilliseconds ?? 0);
return process.WaitForProcessStop(processTimeout);
}
public static bool WaitForProcessStop(this Process process, TimeSpan processTimeout)
{
var processStopwatch = Stopwatch.StartNew();
while (!process.HasExited)
{
Thread.Sleep(1.Seconds());
if (processTimeout.TotalMilliseconds > 0 && processStopwatch.ElapsedMilliseconds > processTimeout.TotalMilliseconds)
{
process.Kill();
process.WaitForExit((int)5.Seconds().TotalMilliseconds);
return false;
}
}
return true;
}
}
}
| 32.847222 | 132 | 0.579281 | [
"Apache-2.0"
] | alex6dj/HudlFfmpeg | Hudl.FFmpeg.Core/Extensions/ProcessExtensions.cs | 2,367 | 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: Templates\CSharp\Model\MethodRequestBody.cs.tt
namespace Microsoft.Graph
{
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
/// <summary>
/// The type WorkbookFunctionsIsLogicalRequestBody.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class WorkbookFunctionsIsLogicalRequestBody
{
/// <summary>
/// Gets or sets Value.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "value", Required = Newtonsoft.Json.Required.Default)]
public Newtonsoft.Json.Linq.JToken Value { get; set; }
}
}
| 36.030303 | 153 | 0.603028 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Models/Generated/WorkbookFunctionsIsLogicalRequestBody.cs | 1,189 | 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.RegularExpressions;
using Xunit;
public class GroupNamesAndNumber
{
/*
Tested Methods:
public string[] GetGroupNames();
public int[] GetGroupNumbers();
public string GroupNameFromNumber(int i);
public int GroupNumberFromName(string name);
*/
[Fact]
public static void GroupNamesAndNumberTestCase()
{
//////////// Global Variables used for all tests
String strLoc = "Loc_000oo";
String strValue = String.Empty;
int iCountErrors = 0;
int iCountTestcases = 0;
Regex r;
String s;
String[] expectedNames;
String[] expectedGroups;
int[] expectedNumbers;
try
{
///////////////////////// START TESTS ////////////////////////////
///////////////////////////////////////////////////////////////////
//[]Vanilla
s = "Ryan Byington";
r = new Regex("(?<first_name>\\S+)\\s(?<last_name>\\S+)");
strLoc = "Loc_498yg";
iCountTestcases++;
expectedNames = new String[]
{
"0", "first_name", "last_name"
}
;
expectedNumbers = new int[]
{
0, 1, 2
}
;
expectedGroups = new String[]
{
"Ryan Byington", "Ryan", "Byington"
}
;
if (!VerifyGroupNames(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_79793asdwk! Unexpected GroupNames");
}
if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_12087ahas! Unexpected GroupNumbers");
}
if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_08712saopz! Unexpected Groups");
}
//[]RegEx from SDK
s = "abc208923xyzanqnakl";
r = new Regex(@"((?<One>abc)\d+)?(?<Two>xyz)(.*)");
strLoc = "Loc_0822aws";
iCountTestcases++;
expectedNames = new String[]
{
"0", "1", "2", "One", "Two"
}
;
expectedNumbers = new int[]
{
0, 1, 2, 3, 4
}
;
expectedGroups = new String[]
{
"abc208923xyzanqnakl", "abc208923", "anqnakl", "abc", "xyz"
}
;
if (!VerifyGroupNames(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_79793asdwk! Unexpected GroupNames");
}
if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_12087ahas! Unexpected GroupNumbers");
}
if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_0822klas! Unexpected Groups");
}
//[]RegEx with numeric names
s = "0272saasdabc8978xyz][]12_+-";
r = new Regex(@"((?<256>abc)\d+)?(?<16>xyz)(.*)");
strLoc = "Loc_0982asd";
iCountTestcases++;
expectedNames = new String[]
{
"0", "1", "2", "16", "256"
}
;
expectedNumbers = new int[]
{
0, 1, 2, 16, 256
}
;
expectedGroups = new String[]
{
"abc8978xyz][]12_+-", "abc8978", "][]12_+-", "xyz", "abc"
}
;
if (!VerifyGroupNames(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_79793asdwk! Unexpected GroupNames");
}
if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_12087ahas! Unexpected GroupNumbers");
}
if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_7072ankla! Unexpected Groups");
}
//[]RegEx with numeric names and string names
s = "0272saasdabc8978xyz][]12_+-";
r = new Regex(@"((?<4>abc)(?<digits>\d+))?(?<2>xyz)(?<everything_else>.*)");
strLoc = "Loc_98968asdf";
iCountTestcases++;
expectedNames = new String[]
{
"0", "1", "2", "digits", "4", "everything_else"
}
;
expectedNumbers = new int[]
{
0, 1, 2, 3, 4, 5
}
;
expectedGroups = new String[]
{
"abc8978xyz][]12_+-", "abc8978", "xyz", "8978", "abc", "][]12_+-"
}
;
if (!VerifyGroupNames(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_9496sad! Unexpected GroupNames");
}
if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_6984awsd! Unexpected GroupNumbers");
}
if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_7072ankla! Unexpected Groups");
}
//[]RegEx with 0 numeric names
try
{
r = new Regex(@"foo(?<0>bar)");
iCountErrors++;
Console.WriteLine("Err_16891 Expected Regex to throw ArgumentException and nothing was thrown");
}
catch (ArgumentException)
{
}
catch (Exception e)
{
iCountErrors++;
Console.WriteLine("Err_9877sawa Expected Regex to throw ArgumentException and the following exception was thrown:\n {0}", e);
}
//[]RegEx without closing >
try
{
r = new Regex(@"foo(?<1bar)");
iCountErrors++;
Console.WriteLine("Err_2389uop Expected Regex to throw ArgumentException and nothing was thrown");
}
catch (ArgumentException)
{
}
catch (Exception e)
{
iCountErrors++;
Console.WriteLine("Err_3298asoia Expected Regex to throw ArgumentException and the following exception was thrown:\n {0}", e);
}
//[] Duplicate string names
s = "Ryan Byington";
r = new Regex("(?<first_name>\\S+)\\s(?<first_name>\\S+)");
strLoc = "Loc_sdfa9849";
iCountTestcases++;
expectedNames = new String[]
{
"0", "first_name"
}
;
expectedNumbers = new int[]
{
0, 1
}
;
expectedGroups = new String[]
{
"Ryan Byington", "Byington"
}
;
if (!VerifyGroupNames(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_32189asdd! Unexpected GroupNames");
}
if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_7978assd! Unexpected GroupNumbers");
}
if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_98732soiya! Unexpected Groups");
}
//[] Duplicate numeric names
s = "Ryan Byington";
r = new Regex("(?<15>\\S+)\\s(?<15>\\S+)");
strLoc = "Loc_89198asda";
iCountTestcases++;
expectedNames = new String[]
{
"0", "15"
}
;
expectedNumbers = new int[]
{
0, 15
}
;
expectedGroups = new String[]
{
"Ryan Byington", "Byington"
}
;
if (!VerifyGroupNames(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_97654awwa! Unexpected GroupNames");
}
if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_6498asde! Unexpected GroupNumbers");
}
if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_316jkkl! Unexpected Groups");
}
/******************************************************************
Repeat the same steps from above but using (?'foo') instead
******************************************************************/
//[]Vanilla
s = "Ryan Byington";
r = new Regex("(?'first_name'\\S+)\\s(?'last_name'\\S+)");
strLoc = "Loc_0982aklpas";
iCountTestcases++;
expectedNames = new String[]
{
"0", "first_name", "last_name"
}
;
expectedNumbers = new int[]
{
0, 1, 2
}
;
expectedGroups = new String[]
{
"Ryan Byington", "Ryan", "Byington"
}
;
if (!VerifyGroupNames(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_464658safsd! Unexpected GroupNames");
}
if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_15689asda! Unexpected GroupNumbers");
}
if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_31568kjkj! Unexpected Groups");
}
//[]RegEx from SDK
s = "abc208923xyzanqnakl";
r = new Regex(@"((?'One'abc)\d+)?(?'Two'xyz)(.*)");
strLoc = "Loc_98977uouy";
iCountTestcases++;
expectedNames = new String[]
{
"0", "1", "2", "One", "Two"
}
;
expectedNumbers = new int[]
{
0, 1, 2, 3, 4
}
;
expectedGroups = new String[]
{
"abc208923xyzanqnakl", "abc208923", "anqnakl", "abc", "xyz"
}
;
if (!VerifyGroupNames(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_65498yuiy! Unexpected GroupNames");
}
if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_5698yuiyh! Unexpected GroupNumbers");
}
if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_2168hkjh! Unexpected Groups");
}
//[]RegEx with numeric names
s = "0272saasdabc8978xyz][]12_+-";
r = new Regex(@"((?'256'abc)\d+)?(?'16'xyz)(.*)");
strLoc = "Loc_9879hjly";
iCountTestcases++;
expectedNames = new String[]
{
"0", "1", "2", "16", "256"
}
;
expectedNumbers = new int[]
{
0, 1, 2, 16, 256
}
;
expectedGroups = new String[]
{
"abc8978xyz][]12_+-", "abc8978", "][]12_+-", "xyz", "abc"
}
;
if (!VerifyGroupNames(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_21689hjkh! Unexpected GroupNames");
}
if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_2689juj! Unexpected GroupNumbers");
}
if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_2358adea! Unexpected Groups");
}
//[]RegEx with numeric names and string names
s = "0272saasdabc8978xyz][]12_+-";
r = new Regex(@"((?'4'abc)(?'digits'\d+))?(?'2'xyz)(?'everything_else'.*)");
strLoc = "Loc_23189uioyp";
iCountTestcases++;
expectedNames = new String[]
{
"0", "1", "2", "digits", "4", "everything_else"
}
;
expectedNumbers = new int[]
{
0, 1, 2, 3, 4, 5
}
;
expectedGroups = new String[]
{
"abc8978xyz][]12_+-", "abc8978", "xyz", "8978", "abc", "][]12_+-"
}
;
if (!VerifyGroupNames(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_3219hjkj! Unexpected GroupNames");
}
if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_23189aseq! Unexpected GroupNumbers");
}
if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_2318adew! Unexpected Groups");
}
//[]RegEx with 0 numeric names
try
{
r = new Regex(@"foo(?'0'bar)");
iCountErrors++;
Console.WriteLine("Err_16891 Expected Regex to throw ArgumentException and nothing was thrown");
}
catch (ArgumentException)
{
}
catch (Exception e)
{
iCountErrors++;
Console.WriteLine("Err_9877sawa Expected Regex to throw ArgumentException and the following exception was thrown:\n {0}", e);
}
//[]RegEx without closing >
try
{
r = new Regex(@"foo(?'1bar)");
iCountErrors++;
Console.WriteLine("Err_979asja Expected Regex to throw ArgumentException and nothing was thrown");
}
catch (ArgumentException)
{
}
catch (Exception e)
{
iCountErrors++;
Console.WriteLine("Err_16889asdfw Expected Regex to throw ArgumentException and the following exception was thrown:\n {0}", e);
}
//[] Duplicate string names
s = "Ryan Byington";
r = new Regex("(?'first_name'\\S+)\\s(?'first_name'\\S+)");
strLoc = "Loc_2318opa";
iCountTestcases++;
expectedNames = new String[]
{
"0", "first_name"
}
;
expectedNumbers = new int[]
{
0, 1
}
;
expectedGroups = new String[]
{
"Ryan Byington", "Byington"
}
;
if (!VerifyGroupNames(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_28978adfe! Unexpected GroupNames");
}
if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_3258adsw! Unexpected GroupNumbers");
}
if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_2198asd! Unexpected Groups");
}
//[] Duplicate numeric names
s = "Ryan Byington";
r = new Regex("(?'15'\\S+)\\s(?'15'\\S+)");
strLoc = "Loc_3289hjaa";
iCountTestcases++;
expectedNames = new String[]
{
"0", "15"
}
;
expectedNumbers = new int[]
{
0, 15
}
;
expectedGroups = new String[]
{
"Ryan Byington", "Byington"
}
;
if (!VerifyGroupNames(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_13289asd! Unexpected GroupNames");
}
if (!VerifyGroupNumbers(r, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_23198asdf! Unexpected GroupNumbers");
}
if (!VerifyGroups(r, s, expectedGroups, expectedNames, expectedNumbers))
{
iCountErrors++;
Console.WriteLine("Err_15689teraku! Unexpected Groups");
}
///////////////////////////////////////////////////////////////////
/////////////////////////// END TESTS /////////////////////////////
}
catch (Exception exc_general)
{
++iCountErrors;
Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString());
}
//// Finish Diagnostics
Assert.Equal(0, iCountErrors);
}
public static bool VerifyGroupNames(Regex r, String[] expectedNames, int[] expectedNumbers)
{
string[] names = r.GetGroupNames();
if (names.Length != expectedNames.Length)
{
Console.WriteLine("Err_08722aswa! Expect {0} names actual={1}", expectedNames.Length, names.Length);
return false;
}
for (int i = 0; i < expectedNames.Length; i++)
{
if (!names[i].Equals(expectedNames[i]))
{
Console.WriteLine("Err_09878asfas! Expected GroupNames[{0}]={1} actual={2}", i, expectedNames[i], names[i]);
return false;
}
if (expectedNames[i] != r.GroupNameFromNumber(expectedNumbers[i]))
{
Console.WriteLine("Err_6589sdafn!GroupNameFromNumber({0})={1} actual={2}", expectedNumbers[i], expectedNames[i], r.GroupNameFromNumber(expectedNumbers[i]));
return false;
}
}
return true;
}
public static bool VerifyGroupNumbers(Regex r, String[] expectedNames, int[] expectedNumbers)
{
int[] numbers = r.GetGroupNumbers();
if (numbers.Length != expectedNumbers.Length)
{
Console.WriteLine("Err_7978awoyp! Expect {0} numbers actual={1}", expectedNumbers.Length, numbers.Length);
return false;
}
for (int i = 0; i < expectedNumbers.Length; i++)
{
if (numbers[i] != expectedNumbers[i])
{
Console.WriteLine("Err_4342asnmc! Expected GroupNumbers[{0}]={1} actual={2}", i, expectedNumbers[i], numbers[i]);
return false;
}
if (expectedNumbers[i] != r.GroupNumberFromName(expectedNames[i]))
{
Console.WriteLine("Err_98795ajkas!GroupNumberFromName({0})={1} actual={2}", expectedNames[i], expectedNumbers[i], r.GroupNumberFromName(expectedNames[i]));
return false;
}
}
return true;
}
public static bool VerifyGroups(Regex r, String s, String[] expectedGroups, String[] expectedNames, int[] expectedNumbers)
{
Match m = r.Match(s);
Group g;
if (!m.Success)
{
Console.WriteLine("Err_08220kha Match not a success");
return false;
}
if (m.Groups.Count != expectedGroups.Length)
{
Console.WriteLine("Err_9722asqa! Expect {0} groups actual={1}", expectedGroups.Length, m.Groups.Count);
return false;
}
for (int i = 0; i < expectedNumbers.Length; i++)
{
if (null == (g = m.Groups[expectedNames[i]]) || expectedGroups[i] != g.Value)
{
Console.WriteLine("Err_3327nkoo! Expected Groups[{0}]={1} actual={2}", expectedNames[i], expectedGroups[i], g == null ? "<null>" : g.Value);
return false;
}
if (null == (g = m.Groups[expectedNumbers[i]]) || expectedGroups[i] != g.Value)
{
Console.WriteLine("Err_9465sdjh! Expected Groups[{0}]={1} actual={2}", expectedNumbers[i], expectedGroups[i], g == null ? "<null>" : g.Value);
return false;
}
}
return true;
}
}
| 31.478571 | 172 | 0.465941 | [
"MIT"
] | benjamin-bader/corefx | src/System.Text.RegularExpressions/tests/GroupNamesAndNumbers.cs | 22,035 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Analyzer.Utilities.Extensions;
using Analyzer.Utilities.FlowAnalysis.Analysis.TaintedDataAnalysis;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.NetCore.Analyzers.Security
{
/// <summary>
/// Base class to aid in implementing tainted data analyzers.
/// </summary>
public abstract class SourceTriggeredTaintedDataAnalyzerBase : DiagnosticAnalyzer
{
/// <summary>
/// <see cref="DiagnosticDescriptor"/> for when tainted data enters a sink.
/// </summary>
/// <remarks>Format string arguments are:
/// 0. Sink symbol.
/// 1. Method name containing the code where the tainted data enters the sink.
/// 2. Source symbol.
/// 3. Method name containing the code where the tainted data came from the source.
/// </remarks>
protected abstract DiagnosticDescriptor TaintedDataEnteringSinkDescriptor { get; }
/// <summary>
/// Kind of tainted data sink.
/// </summary>
protected abstract SinkKind SinkKind { get; }
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(TaintedDataEnteringSinkDescriptor);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.RegisterCompilationStartAction(
(CompilationStartAnalysisContext compilationContext) =>
{
TaintedDataConfig taintedDataConfig = TaintedDataConfig.GetOrCreate(compilationContext.Compilation);
TaintedDataSymbolMap<SourceInfo> sourceInfoSymbolMap = taintedDataConfig.GetSourceSymbolMap(this.SinkKind);
if (sourceInfoSymbolMap.IsEmpty)
{
return;
}
TaintedDataSymbolMap<SinkInfo> sinkInfoSymbolMap = taintedDataConfig.GetSinkSymbolMap(this.SinkKind);
if (sinkInfoSymbolMap.IsEmpty)
{
return;
}
compilationContext.RegisterOperationBlockStartAction(
operationBlockStartContext =>
{
ISymbol owningSymbol = operationBlockStartContext.OwningSymbol;
HashSet<IOperation> rootOperationsNeedingAnalysis = new HashSet<IOperation>();
operationBlockStartContext.RegisterOperationAction(
operationAnalysisContext =>
{
IPropertyReferenceOperation propertyReferenceOperation = (IPropertyReferenceOperation)operationAnalysisContext.Operation;
if (sourceInfoSymbolMap.IsSourceProperty(propertyReferenceOperation.Property))
{
rootOperationsNeedingAnalysis.Add(operationAnalysisContext.Operation.GetRoot());
}
},
OperationKind.PropertyReference);
operationBlockStartContext.RegisterOperationAction(
operationAnalysisContext =>
{
IInvocationOperation invocationOperation = (IInvocationOperation)operationAnalysisContext.Operation;
if (sourceInfoSymbolMap.IsSourceMethod(invocationOperation.TargetMethod))
{
rootOperationsNeedingAnalysis.Add(operationAnalysisContext.Operation.GetRoot());
}
},
OperationKind.Invocation);
operationBlockStartContext.RegisterOperationBlockEndAction(
operationBlockAnalysisContext =>
{
if (!rootOperationsNeedingAnalysis.Any())
{
return;
}
foreach (IOperation rootOperation in rootOperationsNeedingAnalysis)
{
TaintedDataAnalysisResult taintedDataAnalysisResult = TaintedDataAnalysis.TryGetOrComputeResult(
rootOperation.GetEnclosingControlFlowGraph(),
operationBlockAnalysisContext.Compilation,
operationBlockAnalysisContext.OwningSymbol,
operationBlockAnalysisContext.Options,
TaintedDataEnteringSinkDescriptor,
sourceInfoSymbolMap,
taintedDataConfig.GetSanitizerSymbolMap(this.SinkKind),
sinkInfoSymbolMap,
operationBlockAnalysisContext.CancellationToken);
if (taintedDataAnalysisResult == null)
{
return;
}
foreach (TaintedDataSourceSink sourceSink in taintedDataAnalysisResult.TaintedDataSourceSinks)
{
if (!sourceSink.SinkKinds.Contains(this.SinkKind))
{
continue;
}
foreach (SymbolAccess sourceOrigin in sourceSink.SourceOrigins)
{
// Something like:
// CA3001: Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'.
Diagnostic diagnostic = Diagnostic.Create(
this.TaintedDataEnteringSinkDescriptor,
sourceSink.Sink.Location,
additionalLocations: new Location[] { sourceOrigin.Location },
messageArgs: new object[] {
sourceSink.Sink.Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
sourceSink.Sink.AccessingMethod.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
sourceOrigin.Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
sourceOrigin.AccessingMethod.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)});
operationBlockAnalysisContext.ReportDiagnostic(diagnostic);
}
}
}
});
});
});
}
}
} | 58.347518 | 201 | 0.497994 | [
"Apache-2.0"
] | dkalbertson/roslyn-analyzers | src/Microsoft.NetCore.Analyzers/Core/Security/SourceTriggeredTaintedDataAnalyzerBase.cs | 8,229 | C# |
// Copyright (c) IxMilia. 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 IxMilia.Iges.Entities;
namespace IxMilia.Iges
{
internal class IgesReaderBinder
{
private List<Tuple<int, Action<IgesEntity>>> _unboundEntities;
public Dictionary<int, IgesEntity> EntityMap { get; }
public IgesReaderBinder()
{
EntityMap = new Dictionary<int, IgesEntity>();
_unboundEntities = new List<Tuple<int, Action<IgesEntity>>>();
}
public void BindEntity(int entityIndex, Action<IgesEntity> bindAction)
{
if (EntityMap.ContainsKey(entityIndex))
{
bindAction(EntityMap[entityIndex]);
}
else
{
_unboundEntities.Add(Tuple.Create(entityIndex, bindAction));
}
}
public void BindRemainingEntities()
{
foreach (var pair in _unboundEntities)
{
var index = pair.Item1;
var bindAction = pair.Item2;
var entity = EntityMap.ContainsKey(index)
? EntityMap[index]
: null;
bindAction(entity);
}
}
}
}
| 29.382979 | 159 | 0.564084 | [
"Apache-2.0"
] | RSchwarzwald-Hexagon/iges | src/IxMilia.Iges/IgesReaderBinder.cs | 1,383 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Password Hasher")]
[assembly:
AssemblyDescription(
"Lets you hash a string through a variety of algorithms and see how long each method takes and the length of the resulting hashes."
)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Austin S.")]
[assembly: AssemblyProduct("Password Hasher")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("Austin S.")]
[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("1146a36c-4303-4059-a6b6-bb5ab5580c56")]
// 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.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")] | 36.547619 | 139 | 0.736156 | [
"Apache-2.0"
] | austins/PasswordHasher | PasswordHasher/Properties/AssemblyInfo.cs | 1,538 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
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;
namespace ExampleServer
{
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.AddControllers();
}
// 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.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
} | 28.604167 | 106 | 0.672251 | [
"MIT"
] | shumantt/ClusterClient.Chaos | ExampleServer/Startup.cs | 1,373 | C# |
using System.Collections.Generic;
namespace Sitecore.CH.Base.Features.SDK.Services.Config
{
public class MClientOptions
{
public string Host { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public List<string> KnownSSoRedirects { get; set; } = new List<string>();
}
}
| 29.8 | 81 | 0.635347 | [
"Apache-2.0"
] | Sitecore/-ContentHub-VS-Solution-Example | src/Sitecore.CH.Base/Features/SDK/Services/Config/MClientOptions.cs | 449 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
namespace Microsoft.Azure.PowerShell.Cmdlets.ADDomainServices.Runtime.Json
{
internal class ParserException : Exception
{
internal ParserException(string message)
: base(message)
{ }
internal ParserException(string message, SourceLocation location)
: base(message)
{
Location = location;
}
internal SourceLocation Location { get; }
}
} | 34.375 | 97 | 0.488485 | [
"MIT"
] | 3quanfeng/azure-powershell | src/ADDomainServices/generated/runtime/Parser/Exceptions/ParseException.cs | 804 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace MaxProfitJobsInTime
{
class Job
{
public string Name { get; private set; }
public int Deadline { get; private set; }
public int Profit { get; private set; }
public Job(string name, int deadline, int profit)
{
this.Name = name;
this.Deadline = deadline;
this.Profit = profit;
}
}
class Program
{
static void Main(string[] args)
{
//Input
int n = 5;
var jobs = new List<Job>()
{
new Job("j1", 2, 60),
new Job("j2", 1, 100),
new Job("j3", 3, 20),
new Job("j4", 2, 40),
new Job("j5", 1, 20)
};
int maxProfit = 0;
int maxDeadlie = jobs.Max(x => x.Deadline);
int i = 1;
while(i < n && i <= maxDeadlie)
{
var job = jobs.Where(j => j.Deadline >= i).OrderByDescending(j => j.Profit).ThenBy(j => j.Deadline).First();
jobs.Remove(job);
Console.Write(job.Name + " ");
maxProfit += job.Profit;
i++;
}
Console.WriteLine();
Console.WriteLine("Max profit: " + maxProfit);
}
}
}
| 27.490196 | 124 | 0.444365 | [
"MIT"
] | CaptainUltra/IT-Career-Course | Year 3/Module 10 - Algorithms and Data Structures/Greedy Algorithms/MaxProfitJobsInTime/Program.cs | 1,404 | C# |
using Microsoft.AspNet.Identity.EntityFramework;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace GuiltyPleasures.Models
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<UserWithGoal> UsersWithGoals { get; set; }
public DbSet<Fruit> Fruits { get; set; }
//public DbSet<FoodTypes> FoodTypes { get; set; }
public DbSet<UsersFruits> UsersFruits { get; set; }
public DbSet<UsersBurns> UsersBurns { get; set; }
public DbSet<Burn> Burns { get; set; }
//public DbSet<Money> Money { get; set; }
public DbSet<Package> Packages { get; set; }
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Fruit>().ToTable("Food");
modelBuilder.Entity<UsersBurns>().ToTable("UsersExercise");
modelBuilder.Entity<Burn>().ToTable("Exercise");
modelBuilder.Entity<Money>().ToTable("UsersBalance");
modelBuilder.Entity<UserWithGoal>().ToTable("UsersGoals");
base.OnModelCreating(modelBuilder);
}
}
} | 32.860465 | 76 | 0.640481 | [
"MIT"
] | VangelisSaranteas/Plan_Eat | GuiltyPleasures/Models/ApplicationDbContext.cs | 1,415 | C# |
namespace OlympicGames.Olympics.Enums
{
public enum BoxingCategory
{
Flyweight,
Featherweight,
Lightweight,
Middleweight,
Heavyweight
}
}
| 15.916667 | 38 | 0.596859 | [
"MIT"
] | AlxxlA/OOPWorkshops | 04. Dependency Inversion/Olympics-Task/OlympicGames/OlympicGames/Olympics/Enums/BoxingCategory.cs | 193 | C# |
using OriinDic.Models;
namespace OriinDic.Store.Users
{
public record UsersPasswordChangeAction
{
public string Token { get; } = string.Empty;
public UserPwdUpdate User { get; } = new();
public string UserPasswordChangeMessage { get; } = string.Empty;
public UsersPasswordChangeAction(UserPwdUpdate user, string token, string userPasswordChangeMessage)
{
Token = token;
UserPasswordChangeMessage = userPasswordChangeMessage;
User = user;
}
}
} | 30.555556 | 108 | 0.64 | [
"MIT"
] | kierepka/OriinDictionary | Store/Users/UsersPasswordChangeAction.cs | 552 | C# |
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("UnitTest.Rollbar")]
namespace Rollbar
{
using Rollbar.Diagnostics;
using Rollbar.DTOs;
using System;
using System.Collections.Generic;
internal class PayloadQueue
{
private readonly object _syncLock = null;
private readonly Queue<Payload> _queue = null;
private readonly RollbarLogger _logger = null;
private PayloadQueue()
{
}
public PayloadQueue(RollbarLogger logger)
{
Assumption.AssertNotNull(logger, nameof(logger));
this._logger = logger;
this._syncLock = new object();
this._queue = new Queue<Payload>();
}
public DateTimeOffset NextDequeueTime { get; internal set; }
public RollbarLogger Logger
{
get { return this._logger; }
}
public void Enqueue(Payload payload)
{
Assumption.AssertNotNull(payload, nameof(payload));
lock (this._syncLock)
{
this._queue.Enqueue(payload);
}
}
public Payload Peek()
{
lock(this._syncLock)
{
Payload result = null;
if (this._queue.Count > 0)
{
result = this._queue.Peek();
}
return result;
}
}
public Payload Dequeue()
{
lock (this._syncLock)
{
Payload result = null;
if (this._queue.Count > 0)
{
result = this._queue.Dequeue();
TimeSpan delta = TimeSpan.FromTicks(
TimeSpan.FromMinutes(1).Ticks / this.Logger.Config.MaxReportsPerMinute
);
this.NextDequeueTime = DateTimeOffset.Now.Add(delta);
}
return result;
}
}
public int GetPayloadCount()
{
lock (this._syncLock)
{
return this._queue.Count;
}
}
public void Flush()
{
lock (this._syncLock)
{
this._queue.Clear();
}
}
}
}
| 23.846939 | 94 | 0.479675 | [
"MIT"
] | PancakeTeam/Rollbar.NET | Rollbar/PayloadQueue.cs | 2,339 | C# |
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ZR.Admin.WebApi.Extensions;
using ZR.Admin.WebApi.Filters;
using ZR.Admin.WebApi.Framework;
using Infrastructure.Model;
using Infrastructure;
using Infrastructure.Attribute;
using ZR.Model.System;
using ZR.Model.System.Dto;
using ZR.Service.System.IService;
using Hei.Captcha;
using ZR.Common;
using ZR.Service.System;
namespace ZR.Admin.WebApi.Controllers.System
{
/// <summary>
/// 登录
/// </summary>
public class SysLoginController : BaseController
{
static readonly NLog.Logger logger = NLog.LogManager.GetLogger("LoginController");
private readonly IHttpContextAccessor httpContextAccessor;
private readonly ISysUserService sysUserService;
private readonly ISysMenuService sysMenuService;
private readonly ISysLoginService sysLoginService;
private readonly ISysPermissionService permissionService;
private readonly SecurityCodeHelper SecurityCodeHelper;
private readonly ISysConfigService sysConfigService;
private readonly ISysRoleService roleService;
public SysLoginController(
IHttpContextAccessor contextAccessor,
ISysMenuService sysMenuService,
ISysUserService sysUserService,
ISysLoginService sysLoginService,
ISysPermissionService permissionService,
ISysConfigService configService,
ISysRoleService sysRoleService,
SecurityCodeHelper captcha)
{
httpContextAccessor = contextAccessor;
SecurityCodeHelper = captcha;
this.sysMenuService = sysMenuService;
this.sysUserService = sysUserService;
this.sysLoginService = sysLoginService;
this.permissionService = permissionService;
this.sysConfigService = configService;
roleService = sysRoleService;
}
/// <summary>
/// 登录
/// </summary>
/// <param name="loginBody">登录对象</param>
/// <returns></returns>
[Route("login")]
[HttpPost]
[Log(Title = "登录")]
public IActionResult Login([FromBody] LoginBodyDto loginBody)
{
if (loginBody == null) { throw new CustomException("请求参数错误"); }
loginBody.LoginIP = HttpContextExtension.GetClientUserIp(HttpContext);
SysConfig sysConfig = sysConfigService.GetSysConfigByKey("sys.account.captchaOnOff");
if (sysConfig?.ConfigValue != "off" && CacheHelper.Get(loginBody.Uuid) is string str && !str.ToLower().Equals(loginBody.Code.ToLower()))
{
return CustomError(ResultCode.CAPTCHA_ERROR, "验证码错误");
}
var user = sysLoginService.Login(loginBody, AsyncFactory.RecordLogInfo(httpContextAccessor.HttpContext, "0", "login"));
#region 存入cookie Action校验权限使用
//角色集合 eg: admin,yunying,common
//List<string> roles = permissionService.GetRolePermission(user);
List<SysRole> roles = roleService.SelectRolePermissionByUserId(user.UserId);
//权限集合 eg *:*:*,system:user:list
List<string> permissions = permissionService.GetMenuPermission(user);
#endregion
LoginUser loginUser = new LoginUser(user, roles, permissions);
return SUCCESS(JwtUtil.GenerateJwtToken(HttpContext.AddClaims(loginUser)));
}
/// <summary>
/// 注销
/// </summary>
/// <returns></returns>
[Log(Title = "注销")]
[HttpPost("logout")]
public IActionResult LogOut()
{
//Task.Run(async () =>
//{
// //注销登录的用户,相当于ASP.NET中的FormsAuthentication.SignOut
// await HttpContext.SignOutAsync();
//}).Wait();
return SUCCESS(1);
}
/// <summary>
/// 获取用户信息
/// </summary>
/// <returns></returns>
[Verify]
[HttpGet("getInfo")]
public IActionResult GetUserInfo()
{
long userid = HttpContext.GetUId();
var user = sysUserService.SelectUserById(userid);
//前端校验按钮权限使用
//角色集合 eg: admin,yunying,common
List<string> roles = permissionService.GetRolePermission(user);
//权限集合 eg *:*:*,system:user:list
List<string> permissions = permissionService.GetMenuPermission(user);
return SUCCESS(new { user, roles, permissions });
}
/// <summary>
/// 获取路由信息
/// </summary>
/// <returns></returns>
[Verify]
[HttpGet("getRouters")]
public IActionResult GetRouters()
{
long uid = HttpContext.GetUId();
var menus = sysMenuService.SelectMenuTreeByUserId(uid);
return ToResponse(ToJson(1, sysMenuService.BuildMenus(menus)));
}
/// <summary>
/// 生成图片验证码
/// </summary>
/// <returns></returns>
[HttpGet("captchaImage")]
public ApiResult CaptchaImage()
{
string uuid = Guid.NewGuid().ToString().Replace("-", "");
SysConfig sysConfig = sysConfigService.GetSysConfigByKey("sys.account.captchaOnOff");
var captchaOff = sysConfig?.ConfigValue ?? "0";
var code = SecurityCodeHelper.GetRandomEnDigitalText(4);
byte[] imgByte;
if (captchaOff == "1")
{
imgByte = SecurityCodeHelper.GetGifEnDigitalCodeByte(code);//动态gif数字字母
}
else if (captchaOff == "2")
{
imgByte = SecurityCodeHelper.GetGifBubbleCodeByte(code);//动态gif泡泡
}
else if (captchaOff == "3")
{
imgByte = SecurityCodeHelper.GetBubbleCodeByte(code);//泡泡
}
else
{
imgByte = SecurityCodeHelper.GetEnDigitalCodeByte(code);//英文字母加数字
}
string base64Str = Convert.ToBase64String(imgByte);
CacheHelper.SetCache(uuid, code);
var obj = new { uuid, img = base64Str };// File(stream, "image/png")
return ToJson(1, obj);
}
}
}
| 36.039548 | 148 | 0.6037 | [
"MIT"
] | samisgod/ZrAdmin.NET | ZR.Admin.WebApi/Controllers/System/SysLoginController.cs | 6,601 | C# |
namespace Buildit.Web.TestMethodsMsTets.SearchControllerTestMethods
{
internal interface IPublicationsService
{
}
} | 21.333333 | 68 | 0.78125 | [
"MIT"
] | Aimanan/BuildItRepo | Buildit/Buildit.Web.TestsMsTets/SearchControllerTests/IPublicationsService.cs | 130 | C# |
using System;
namespace MarkdownToGist.Configs
{
public class GithubConfig
{
public string GistApi { get; set; }
}
}
| 15.333333 | 43 | 0.644928 | [
"MIT"
] | superwalnut/markdown-gist-transform | Configs/GithubConfig.cs | 140 | C# |
namespace ResXManager.VSIX
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.Win32;
using ResXManager.Infrastructure;
using ResXManager.Model;
using ResXManager.VSIX.Visuals;
using TomsToolbox.Composition;
using TomsToolbox.Essentials;
using TomsToolbox.Wpf;
using TomsToolbox.Wpf.Composition.XamlExtensions;
/// <summary>
/// This class implements the tool window exposed by this package and hosts a user control.
/// </summary>
[Guid("79664857-03bf-4bca-aa54-ec998b3328f8")]
public sealed class MyToolWindow : ToolWindowPane
{
private readonly ITracer _tracer;
private readonly Configuration _configuration;
private readonly IExportProvider _exportProvider;
private readonly ContentControl _contentWrapper = new ContentControl
{
Focusable = false,
Content = new Border { Background = Brushes.Red }
};
/// <summary>
/// Standard constructor for the tool window.
/// </summary>
public MyToolWindow()
: base(null)
{
// Set the window title reading it from the resources.
Caption = Resources.ToolWindowTitle;
// Set the image that will appear on the tab of the window frame when docked with an other window.
// The resource ID correspond to the one defined in the resx file while the Index is the offset in the bitmap strip.
// Each image in the strip being 16x16.
BitmapResourceID = 301;
BitmapIndex = 0;
var exportProvider = VsPackage.Instance.ExportProvider;
_tracer = exportProvider.GetExportedValue<ITracer>();
_configuration = exportProvider.GetExportedValue<Configuration>();
exportProvider.GetExportedValue<ResourceManager>().BeginEditing += ResourceManager_BeginEditing;
_exportProvider = exportProvider;
VisualComposition.Error += VisualComposition_Error;
_contentWrapper.Loaded += ContentWrapper_Loaded;
_contentWrapper.Unloaded += ContentWrapper_Unloaded;
}
protected override void OnCreate()
{
base.OnCreate();
try
{
_tracer.WriteLine(Resources.IntroMessage);
var executingAssembly = Assembly.GetExecutingAssembly();
var folder = Path.GetDirectoryName(executingAssembly.Location);
// ReSharper disable once AssignNullToNotNullAttribute
_tracer.WriteLine(Resources.AssemblyLocation, folder);
_tracer.WriteLine(Resources.Version, new AssemblyName(executingAssembly.FullName).Version);
_tracer.WriteLine(".NET Framework Version: {0} (https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed)", FrameworkVersion());
const string switchName = @"Switch.System.Windows.Baml2006.AppendLocalAssemblyVersionForSourceUri";
AppContext.TryGetSwitch(switchName, out var isEnabled);
_tracer.WriteLine("{0}={1} (https://github.com/Microsoft/dotnet/blob/master/releases/net472/dotnet472-changes.md#wpf)", switchName, isEnabled);
EventManager.RegisterClassHandler(typeof(VsixShellView), ButtonBase.ClickEvent, new RoutedEventHandler(Navigate_Click));
// This is the user control hosted by the tool window; Note that, even if this class implements IDisposable,
// we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on
// the object returned by the Content property.
Content = _contentWrapper;
}
catch (Exception ex)
{
_tracer.TraceError("MyToolWindow OnCreate failed: " + ex);
MessageBox.Show(string.Format(CultureInfo.CurrentCulture, Resources.ExtensionLoadingError, ex.Message));
}
}
private void ContentWrapper_Loaded(object? sender, RoutedEventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
try
{
VsPackage.Instance.ToolWindowLoaded();
var view = _exportProvider.GetExportedValue<VsixShellView>();
_contentWrapper.Content = view;
Dte.SetFontSize(view);
}
catch (Exception ex)
{
_tracer.TraceError("ContentWrapper_Loaded failed: " + ex);
MessageBox.Show(string.Format(CultureInfo.CurrentCulture, Resources.ExtensionLoadingError, ex.Message));
}
}
private void ContentWrapper_Unloaded(object? sender, RoutedEventArgs e)
{
VsPackage.Instance.ToolWindowUnloaded();
_contentWrapper.Content = null;
}
private EnvDTE.DTE Dte
{
get
{
ThreadHelper.ThrowIfNotOnUIThread();
var dte = (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE));
return dte;
}
}
private static void Navigate_Click(object? sender, RoutedEventArgs e)
{
string? url;
if (e.OriginalSource is FrameworkElement source)
{
var button = source.TryFindAncestorOrSelf<ButtonBase>();
if (button == null)
return;
url = source.Tag as string;
if (url?.StartsWith(@"http", StringComparison.OrdinalIgnoreCase) != true)
return;
}
else
{
var link = e.OriginalSource as Hyperlink;
var navigateUri = link?.NavigateUri;
if (navigateUri == null)
return;
url = navigateUri.ToString();
}
CreateWebBrowser(url);
}
[Localizable(false)]
private static void CreateWebBrowser(string url)
{
Process.Start(url);
}
private void ResourceManager_BeginEditing(object? sender, ResourceBeginEditingEventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (!CanEdit(e.Entity, e.CultureKey))
{
e.Cancel = true;
}
}
private bool CanEdit(ResourceEntity entity, CultureKey? cultureKey)
{
ThreadHelper.ThrowIfNotOnUIThread();
var languages = entity.Languages.Where(lang => (cultureKey == null) || cultureKey.Equals(lang.CultureKey)).ToArray();
if (!languages.Any())
{
try
{
var culture = cultureKey?.Culture;
if (culture == null)
return false; // no neutral culture => this should never happen.
return AddLanguage(entity, culture);
}
catch (Exception ex)
{
MessageBox.Show(string.Format(CultureInfo.CurrentCulture, View.Properties.Resources.ErrorAddingNewResourceFile, ex), Resources.ToolWindowTitle);
}
}
var alreadyOpenItems = GetLanguagesOpenedInAnotherEditor(languages);
string message;
if (alreadyOpenItems.Any())
{
message = string.Format(CultureInfo.CurrentCulture, Resources.ErrorOpenFilesInEditor, FormatFileNames(alreadyOpenItems.Select(item => item.Item1)));
MessageBox.Show(message, Resources.ToolWindowTitle);
ActivateWindow(alreadyOpenItems.Select(item => item.Item2).FirstOrDefault());
return false;
}
// if file is not read only, assume file is either
// - already checked out
// - not under source control
// - or does not need special SCM handling (e.g. TFS local workspace)
var lockedFiles = GetLockedFiles(languages);
if (!lockedFiles.Any())
return true;
if (!QueryEditFiles(lockedFiles))
return false;
// if file is not under source control, we get an OK from QueryEditFiles even if the file is read only, so we have to test again:
lockedFiles = GetLockedFiles(languages);
if (!lockedFiles.Any())
return true;
message = string.Format(CultureInfo.CurrentCulture, Resources.ProjectHasReadOnlyFiles, FormatFileNames(lockedFiles));
MessageBox.Show(message, Resources.ToolWindowTitle);
return false;
}
private static void ActivateWindow(EnvDTE.Window? window)
{
try
{
ThreadHelper.ThrowIfNotOnUIThread();
window?.Activate();
}
catch
{
// Something is wrong with the window, we can't do anything about this...
}
}
private Tuple<string, EnvDTE.Window>[] GetLanguagesOpenedInAnotherEditor(IEnumerable<ResourceLanguage> languages)
{
try
{
ThreadHelper.ThrowIfNotOnUIThread();
#pragma warning disable VSTHRD010 // Accessing ... should only be done on the main thread.
var openDocuments = Dte.Windows?
.OfType<EnvDTE.Window>()
.Where(window => window.Visible && (window.Document != null))
.ToDictionary(window => window.Document);
var items = from l in languages
let file = l.FileName
let projectFile = l.ProjectFile as DteProjectFile
let documents = projectFile?.ProjectItems.Select(item => item.TryGetDocument()).Where(doc => doc != null)
let window = documents?.Select(doc => openDocuments?.GetValueOrDefault(doc)).FirstOrDefault(win => win != null)
where window != null
select Tuple.Create(file, window);
#pragma warning restore VSTHRD010 // Accessing ... should only be done on the main thread.
return items.ToArray();
}
catch
{
return Array.Empty<Tuple<string, EnvDTE.Window>>();
}
}
private bool QueryEditFiles(string[] lockedFiles)
{
ThreadHelper.ThrowIfNotOnUIThread();
var service = (IVsQueryEditQuerySave2)GetService(typeof(SVsQueryEditQuerySave));
if (service != null)
{
if ((0 != service.QueryEditFiles(0, lockedFiles.Length, lockedFiles, null, null, out var editVerdict, out _))
|| (editVerdict != (uint)tagVSQueryEditResult.QER_EditOK))
{
return false;
}
}
return true;
}
private static string[] GetLockedFiles(IEnumerable<ResourceLanguage> languages)
{
return languages.Where(l => !l.ProjectFile.IsWritable)
.Select(l => l.FileName)
.ToArray();
}
private bool AddLanguage(ResourceEntity entity, CultureInfo culture)
{
ThreadHelper.ThrowIfNotOnUIThread();
var resourceLanguages = entity.Languages;
if (!resourceLanguages.Any())
return false;
if (_configuration.ConfirmAddLanguageFile)
{
var message = string.Format(CultureInfo.CurrentCulture, Resources.ProjectHasNoResourceFile, culture.DisplayName);
if (MessageBox.Show(message, Resources.ToolWindowTitle, MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
return false;
}
var neutralLanguage = resourceLanguages.First();
var languageFileName = neutralLanguage.ProjectFile.GetLanguageFileName(culture);
if (!File.Exists(languageFileName))
{
var directoryName = Path.GetDirectoryName(languageFileName);
if (!directoryName.IsNullOrEmpty())
Directory.CreateDirectory(directoryName);
File.WriteAllText(languageFileName, Model.Properties.Resources.EmptyResxTemplate);
}
AddProjectItems(entity, neutralLanguage, languageFileName);
return true;
}
private void AddProjectItems(ResourceEntity entity, ResourceLanguage neutralLanguage, string languageFileName)
{
ThreadHelper.ThrowIfNotOnUIThread();
DteProjectFile? projectFile = null;
var projectItems = (neutralLanguage.ProjectFile as DteProjectFile)?.ProjectItems;
if (projectItems == null)
{
entity.AddLanguage(new ProjectFile(languageFileName, entity.Container.SolutionFolder ?? string.Empty, entity.ProjectName, null));
return;
}
foreach (var neutralLanguageProjectItem in projectItems)
{
var collection = neutralLanguageProjectItem.Collection;
var projectItem = collection.AddFromFile(languageFileName);
var containingProject = projectItem.ContainingProject;
var projectName = containingProject.Name;
if (projectFile == null)
{
var solution = _exportProvider.GetExportedValue<DteSolution>();
projectFile = new DteProjectFile(solution, solution.SolutionFolder, languageFileName, projectName, containingProject.UniqueName, projectItem);
}
else
{
projectFile.AddProject(projectName, projectItem);
}
}
if (projectFile != null)
{
entity.AddLanguage(projectFile);
}
}
[Localizable(false)]
private static string FormatFileNames(IEnumerable<string> lockedFiles)
{
return string.Join("\n", lockedFiles.Select(x => "\xA0-\xA0" + x));
}
private void VisualComposition_Error(object? sender, TextEventArgs e)
{
_tracer.TraceError(e.Text);
}
private const string Subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
private static int FrameworkVersion()
{
using var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
using var ndpKey = baseKey.OpenSubKey(Subkey);
return (int?)ndpKey?.GetValue("Release") ?? 0;
}
protected override bool PreProcessMessage(ref System.Windows.Forms.Message m)
{
if ((m.Msg != 0x0100) || (m.WParam != (IntPtr)27))
{
return base.PreProcessMessage(ref m);
}
// https://github.com/dotnet/ResXResourceManager/issues/397
// must process ESC key here, else window will loose focus without notification.
var keyboardDevice = Keyboard.PrimaryDevice;
var e = new KeyEventArgs(keyboardDevice, keyboardDevice.ActiveSource, 0, Key.Escape)
{
RoutedEvent = Keyboard.KeyDownEvent
};
InputManager.Current.ProcessInput(e);
return true;
}
}
}
| 38.101382 | 200 | 0.572811 | [
"MIT"
] | amse2000/ResXResourceManager | src/ResXManager.VSIX/MyToolWindow.cs | 16,538 | C# |
using OnlineShop.Common.Constants;
using OnlineShop.Models.Products.Components;
using OnlineShop.Models.Products.Peripherals;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OnlineShop.Models.Products.Computers
{
abstract class Computer : Product, IComputer
{
private readonly List<IComponent> components;
private readonly List<IPeripheral> peripherals;
public Computer(int id, string manufacturer, string model, decimal price, double overallPerformance)
: base(id, manufacturer, model, price, overallPerformance)
{
this.components = new List<IComponent>();
this.peripherals = new List<IPeripheral>();
}
public override double OverallPerformance
{
get
{
if (!this.components.Any())
{
return base.OverallPerformance;
}
var totalPerformanceComponents = this.components.Sum(x => x.OverallPerformance) / this.components.Count();
return base.OverallPerformance + totalPerformanceComponents;
}
set => base.OverallPerformance = value;
}
public override decimal Price
{
get
{
var totalPrice = base.Price + this.components.Sum(x => x.Price) + this.peripherals.Sum(x => x.Price);
return totalPrice;
}
set => base.Price = value;
}
public IReadOnlyCollection<IComponent> Components => this.components.AsReadOnly();
public IReadOnlyCollection<IPeripheral> Peripherals => this.peripherals.AsReadOnly();
public void AddComponent(IComponent component)
{
IComponent existingComponent = this.components.FirstOrDefault(x => x.GetType().Name == component.GetType().Name);
if (existingComponent != null)
{
var message = string.Format(ExceptionMessages.ExistingComponent, existingComponent.GetType().Name, existingComponent.Model, existingComponent.Id);
throw new ArgumentException(message);
}
this.components.Add(component);
}
public void AddPeripheral(IPeripheral peripheral)
{
IPeripheral existingPeripheral = this.peripherals.FirstOrDefault(x => x.GetType().Name == peripheral.GetType().Name);
if (existingPeripheral != null)
{
var message = string.Format(ExceptionMessages.ExistingPeripheral, existingPeripheral.GetType().Name, existingPeripheral.Id);
throw new ArgumentException(message);
}
this.peripherals.Add(peripheral);
}
public IComponent RemoveComponent(string componentType)
{
IComponent component = this.components.FirstOrDefault(x => x.GetType().Name == componentType);
if (!this.components.Any() || component == null)
{
string message = string.Format(ExceptionMessages.NotExistingComponent, componentType, this.GetType().Name, this.Id);
throw new ArgumentException(message);
}
this.components.Remove(component);
return component;
}
public IPeripheral RemovePeripheral(string peripheralType)
{
IPeripheral peripheral = this.peripherals.FirstOrDefault(x => x.GetType().Name == peripheralType);
if (!this.peripherals.Any() || peripheral == null)
{
string message = string.Format(ExceptionMessages.NotExistingPeripheral, peripheralType, this.GetType().Name, this.Id);
throw new ArgumentException(message);
}
this.peripherals.Remove(peripheral);
return peripheral;
}
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine($"Overall Performance: {this.OverallPerformance:f2}. Price: {this.Price:f2} - {this.GetType().Name}: {this.Manufacturer} {this.Model} (Id: {this.Id})");
sb.AppendLine($" Components ({this.Components.Count}):");
if (components.Any())
{
this.components.ForEach(component =>
{
sb.AppendLine($" {component}");
});
}
double averageOverallPerformance = peripherals.Any() ? this.peripherals.Average(x => x.OverallPerformance) : 0d;
sb.AppendLine($" Peripherals ({this.peripherals.Count}); Average Overall Performance ({averageOverallPerformance:f2}):");
this.peripherals.ForEach(peripheral =>
{
sb.AppendLine($" {peripheral}");
});
return sb.ToString().Trim();
}
}
}
| 30.059259 | 169 | 0.720552 | [
"MIT"
] | kristiyanivanovx/SoftUni-Programming-Basics-March-2020 | 04 - CSharp-OOP/10 - CSharp OOP Exams/06 - Exam 16 August 2020/OnlineShop/OnlineShop/Models/Products/Computers/Computer.cs | 4,060 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Query.Internal
{
/// <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 class QueryOptimizingExpressionVisitor : ExpressionVisitor
{
private static readonly MethodInfo _stringCompareWithComparisonMethod =
typeof(string).GetRequiredRuntimeMethod(nameof(string.Compare), new[] { typeof(string), typeof(string), typeof(StringComparison) });
private static readonly MethodInfo _stringCompareWithoutComparisonMethod =
typeof(string).GetRequiredRuntimeMethod(nameof(string.Compare), new[] { typeof(string), typeof(string) });
private static readonly MethodInfo _startsWithMethodInfo =
typeof(string).GetRequiredRuntimeMethod(nameof(string.StartsWith), new[] { typeof(string) });
private static readonly MethodInfo _endsWithMethodInfo =
typeof(string).GetRequiredRuntimeMethod(nameof(string.EndsWith), new[] { typeof(string) });
private static readonly Expression _constantNullString = Expression.Constant(null, typeof(string));
/// <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>
protected override Expression VisitMember(MemberExpression memberExpression)
{
var expression = memberExpression.Expression != null
? MatchExpressionType(
Visit(memberExpression.Expression),
memberExpression.Expression.Type)
: null;
var visitedExpression = memberExpression.Update(expression);
return TryOptimizeMemberAccessOverConditional(visitedExpression) ?? visitedExpression;
}
/// <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>
protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
{
Check.NotNull(methodCallExpression, nameof(methodCallExpression));
if (Equals(_startsWithMethodInfo, methodCallExpression.Method)
|| Equals(_endsWithMethodInfo, methodCallExpression.Method))
{
if (methodCallExpression.Arguments[0] is ConstantExpression constantArgument
&& constantArgument.Value is string stringValue
&& stringValue == string.Empty)
{
// every string starts/ends with empty string.
return Expression.Constant(true);
}
var newObject = Visit(methodCallExpression.Object)!;
var newArgument = Visit(methodCallExpression.Arguments[0]);
var result = Expression.AndAlso(
Expression.NotEqual(newObject, _constantNullString),
Expression.AndAlso(
Expression.NotEqual(newArgument, _constantNullString),
methodCallExpression.Update(newObject, new[] { newArgument })));
return newArgument is ConstantExpression
? result
: Expression.OrElse(
Expression.Equal(
newArgument,
Expression.Constant(string.Empty)),
result);
}
if (methodCallExpression.Method.IsGenericMethod
&& methodCallExpression.Method.GetGenericMethodDefinition() is MethodInfo methodInfo
&& (methodInfo.Equals(EnumerableMethods.AnyWithPredicate) || methodInfo.Equals(EnumerableMethods.All))
&& methodCallExpression.Arguments[0].NodeType is ExpressionType nodeType
&& (nodeType == ExpressionType.Parameter || nodeType == ExpressionType.Constant)
&& methodCallExpression.Arguments[1] is LambdaExpression lambda
&& TryExtractEqualityOperands(lambda.Body, out var left, out var right, out var negated)
&& (left is ParameterExpression || right is ParameterExpression))
{
var nonParameterExpression = left is ParameterExpression ? right : left;
if (methodInfo.Equals(EnumerableMethods.AnyWithPredicate)
&& !negated)
{
var containsMethod = EnumerableMethods.Contains.MakeGenericMethod(methodCallExpression.Method.GetGenericArguments()[0]);
return Expression.Call(null, containsMethod, methodCallExpression.Arguments[0], nonParameterExpression);
}
if (methodInfo.Equals(EnumerableMethods.All) && negated)
{
var containsMethod = EnumerableMethods.Contains.MakeGenericMethod(methodCallExpression.Method.GetGenericArguments()[0]);
return Expression.Not(Expression.Call(null, containsMethod, methodCallExpression.Arguments[0], nonParameterExpression));
}
}
if (methodCallExpression.Method.IsGenericMethod
&& methodCallExpression.Method.GetGenericMethodDefinition() is MethodInfo containsMethodInfo
&& containsMethodInfo.Equals(QueryableMethods.Contains))
{
var typeArgument = methodCallExpression.Method.GetGenericArguments()[0];
var anyMethod = QueryableMethods.AnyWithPredicate.MakeGenericMethod(typeArgument);
var anyLambdaParameter = Expression.Parameter(typeArgument, "p");
var anyLambda = Expression.Lambda(
Expression.Equal(
anyLambdaParameter,
methodCallExpression.Arguments[1]),
anyLambdaParameter);
return Expression.Call(null, anyMethod, new[] { methodCallExpression.Arguments[0], anyLambda });
}
var @object = default(Expression);
if (methodCallExpression.Object != null)
{
@object = MatchExpressionType(
Visit(methodCallExpression.Object),
methodCallExpression.Object.Type);
}
var arguments = new Expression[methodCallExpression.Arguments.Count];
for (var i = 0; i < arguments.Length; i++)
{
arguments[i] = MatchExpressionType(
Visit(methodCallExpression.Arguments[i]),
methodCallExpression.Arguments[i].Type);
}
var visited = methodCallExpression.Update(@object!, arguments);
// In VB.NET, comparison operators between strings (equality, greater-than, less-than) yield
// calls to a VB-specific CompareString method. Normalize that to string.Compare.
if (visited.Method.Name == "CompareString"
&& visited.Method.DeclaringType?.Name == "Operators"
&& visited.Method.DeclaringType?.Namespace == "Microsoft.VisualBasic.CompilerServices"
&& visited.Object == null
&& visited.Arguments.Count == 3
&& visited.Arguments[2] is ConstantExpression textCompareConstantExpression
&& _stringCompareWithComparisonMethod != null
&& _stringCompareWithoutComparisonMethod != null)
{
return textCompareConstantExpression.Value is bool boolValue
&& boolValue
? Expression.Call(
_stringCompareWithComparisonMethod,
visited.Arguments[0],
visited.Arguments[1],
Expression.Constant(StringComparison.OrdinalIgnoreCase))
: Expression.Call(
_stringCompareWithoutComparisonMethod,
visited.Arguments[0],
visited.Arguments[1]);
}
return visited;
}
private Expression MatchExpressionType(Expression expression, Type typeToMatch)
=> expression.Type != typeToMatch
? Expression.Convert(expression, typeToMatch)
: expression;
/// <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>
protected override Expression VisitUnary(UnaryExpression unaryExpression)
{
Check.NotNull(unaryExpression, nameof(unaryExpression));
if (unaryExpression.NodeType == ExpressionType.Not
&& unaryExpression.Operand is MethodCallExpression innerMethodCall
&& (Equals(_startsWithMethodInfo, innerMethodCall.Method)
|| Equals(_endsWithMethodInfo, innerMethodCall.Method)))
{
if (innerMethodCall.Arguments[0] is ConstantExpression constantArgument
&& constantArgument.Value is string stringValue
&& stringValue == string.Empty)
{
// every string starts/ends with empty string.
return Expression.Constant(false);
}
var newObject = Visit(innerMethodCall.Object)!;
var newArgument = Visit(innerMethodCall.Arguments[0]);
var result = Expression.AndAlso(
Expression.NotEqual(newObject, _constantNullString),
Expression.AndAlso(
Expression.NotEqual(newArgument, _constantNullString),
Expression.Not(innerMethodCall.Update(newObject, new[] { newArgument }))));
return newArgument is ConstantExpression
? result
: Expression.AndAlso(
Expression.NotEqual(
newArgument,
Expression.Constant(string.Empty)),
result);
}
return unaryExpression.Update(
Visit(unaryExpression.Operand));
}
/// <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>
protected override Expression VisitBinary(BinaryExpression binaryExpression)
{
var left = Visit(binaryExpression.Left);
var right = Visit(binaryExpression.Right);
if (binaryExpression.NodeType != ExpressionType.Coalesce
&& left.Type != right.Type
&& left.Type.UnwrapNullableType() == right.Type.UnwrapNullableType())
{
if (left.Type.IsNullableValueType())
{
right = Expression.Convert(right, left.Type);
}
else
{
left = Expression.Convert(left, right.Type);
}
}
return binaryExpression.Update(left, binaryExpression.Conversion, right);
}
/// <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>
protected override Expression VisitConditional(ConditionalExpression conditionalExpression)
{
var test = Visit(conditionalExpression.Test);
var ifTrue = Visit(conditionalExpression.IfTrue);
var ifFalse = Visit(conditionalExpression.IfFalse);
if (ifTrue.Type != ifFalse.Type
&& ifTrue.Type.UnwrapNullableType() == ifFalse.Type.UnwrapNullableType())
{
if (ifTrue.Type.IsNullableValueType())
{
ifFalse = Expression.Convert(ifFalse, ifTrue.Type);
}
else
{
ifTrue = Expression.Convert(ifTrue, ifFalse.Type);
}
return Expression.Condition(test, ifTrue, ifFalse);
}
return conditionalExpression.Update(test, ifTrue, ifFalse);
}
/// <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>
protected override Expression VisitLambda<T>(Expression<T> lambdaExpression)
{
Check.NotNull(lambdaExpression, nameof(lambdaExpression));
var body = Visit(lambdaExpression.Body);
return body.Type != lambdaExpression.Body.Type
? Expression.Lambda(Expression.Convert(body, lambdaExpression.Body.Type), lambdaExpression.Parameters)
: lambdaExpression.Update(body, lambdaExpression.Parameters)!;
}
/// <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>
protected override Expression VisitNew(NewExpression newExpression)
{
if (newExpression.Arguments.Count == 0)
{
return newExpression;
}
var arguments = new Expression[newExpression.Arguments.Count];
for (var i = 0; i < arguments.Length; i++)
{
arguments[i] = MatchExpressionType(
Visit(newExpression.Arguments[i]),
newExpression.Arguments[i].Type);
}
return newExpression.Update(arguments);
}
/// <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>
protected override ElementInit VisitElementInit(ElementInit elementInit)
{
var arguments = new Expression[elementInit.Arguments.Count];
for (var i = 0; i < arguments.Length; i++)
{
arguments[i] = MatchExpressionType(
Visit(elementInit.Arguments[i]),
elementInit.Arguments[i].Type);
}
return elementInit.Update(arguments);
}
/// <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>
protected override MemberAssignment VisitMemberAssignment(MemberAssignment memberAssignment)
{
var expression = MatchExpressionType(
Visit(memberAssignment.Expression),
memberAssignment.Expression.Type);
return memberAssignment.Update(expression);
}
/// <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>
protected override Expression VisitNewArray(NewArrayExpression newArrayExpression)
{
var expressions = new Expression[newArrayExpression.Expressions.Count];
for (var i = 0; i < expressions.Length; i++)
{
expressions[i] = MatchExpressionType(
Visit(newArrayExpression.Expressions[i]),
newArrayExpression.Expressions[i].Type);
}
return newArrayExpression.Update(expressions);
}
private bool TryExtractEqualityOperands(
Expression expression,
[NotNullWhen(true)] out Expression? left,
[NotNullWhen(true)] out Expression? right,
out bool negated)
{
(left, right, negated) = (default, default, default);
switch (expression)
{
case BinaryExpression binaryExpression:
switch (binaryExpression.NodeType)
{
case ExpressionType.Equal:
negated = false;
break;
case ExpressionType.NotEqual:
negated = true;
break;
default:
return false;
}
(left, right) = (binaryExpression.Left, binaryExpression.Right);
return true;
case MethodCallExpression methodCallExpression
when methodCallExpression.Method.Name == nameof(object.Equals):
{
negated = false;
if (methodCallExpression.Arguments.Count == 1
&& methodCallExpression.Object?.Type == methodCallExpression.Arguments[0].Type)
{
(left, right) = (methodCallExpression.Object, methodCallExpression.Arguments[0]);
return true;
}
else if (methodCallExpression.Arguments.Count == 2
&& methodCallExpression.Arguments[0].Type == methodCallExpression.Arguments[1].Type)
{
(left, right) = (methodCallExpression.Arguments[0], methodCallExpression.Arguments[1]);
return true;
}
return false;
}
case UnaryExpression unaryExpression
when unaryExpression.IsLogicalNot():
{
var result = TryExtractEqualityOperands(unaryExpression.Operand, out left, out right, out negated);
negated = !negated;
return result;
}
}
return false;
}
private Expression? TryOptimizeMemberAccessOverConditional(Expression expression)
{
// Simplify (a != null ? new { Member = b, ... } : null).Member
// to a != null ? b : null
// Later null check removal will simplify it further
if (expression is MemberExpression visitedMemberExpression
&& visitedMemberExpression.Expression is ConditionalExpression conditionalExpression
&& conditionalExpression.Test is BinaryExpression binaryTest
&& (binaryTest.NodeType == ExpressionType.Equal
|| binaryTest.NodeType == ExpressionType.NotEqual)
// Exclude HasValue/Value over Nullable<> as they return non-null type and we don't have equivalent for it for null part
&& !(conditionalExpression.Type.IsNullableValueType()
&& (visitedMemberExpression.Member.Name == nameof(Nullable<int>.HasValue)
|| visitedMemberExpression.Member.Name == nameof(Nullable<int>.Value))))
{
var isLeftNullConstant = IsNullConstant(binaryTest.Left);
var isRightNullConstant = IsNullConstant(binaryTest.Right);
if (isLeftNullConstant != isRightNullConstant
&& ((binaryTest.NodeType == ExpressionType.Equal
&& IsNullConstant(conditionalExpression.IfTrue))
|| (binaryTest.NodeType == ExpressionType.NotEqual
&& IsNullConstant(conditionalExpression.IfFalse))))
{
var nonNullExpression = binaryTest.NodeType == ExpressionType.Equal
? conditionalExpression.IfFalse
: conditionalExpression.IfTrue;
// Use ReplacingExpressionVisitor rather than creating MemberExpression
// So that member access chain on NewExpression/MemberInitExpression condenses
nonNullExpression = ReplacingExpressionVisitor.Replace(
visitedMemberExpression.Expression, nonNullExpression, visitedMemberExpression);
nonNullExpression = TryOptimizeMemberAccessOverConditional(nonNullExpression) ?? nonNullExpression;
if (!nonNullExpression.Type.IsNullableType())
{
nonNullExpression = Expression.Convert(nonNullExpression, nonNullExpression.Type.MakeNullable());
}
var nullExpression = Expression.Constant(null, nonNullExpression.Type);
return Expression.Condition(
conditionalExpression.Test,
binaryTest.NodeType == ExpressionType.Equal ? nullExpression : nonNullExpression,
binaryTest.NodeType == ExpressionType.Equal ? nonNullExpression : nullExpression);
}
}
return null;
}
private bool IsNullConstant(Expression expression)
=> expression is ConstantExpression constantExpression
&& constantExpression.Value == null;
}
}
| 50.462777 | 144 | 0.599801 | [
"MIT"
] | FelicePollano/efcore | src/EFCore/Query/Internal/QueryOptimizingExpressionVisitor.cs | 25,080 | C# |
//==============================================================
// Copyright (C) 2020 Inc. All rights reserved.
//
//==============================================================
// Create by 种道洋 at 2020/8/26 13:23:02.
// Version 1.0
// 种道洋
//==============================================================
using Cdy.Spider;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace Cdy.Api.SpiderMqtt.Develop
{
/// <summary>
///
/// </summary>
public class ApiConfigViewModel:Cdy.Spider.DevelopCommon.ViewModelBase
{
#region ... Variables ...
private MqttApiData mModel;
private List<string> mTransTypes;
#endregion ...Variables...
#region ... Events ...
#endregion ...Events...
#region ... Constructor...
public ApiConfigViewModel()
{
mTransTypes = Enum.GetNames(typeof(ApiData.TransType)).ToList();
}
#endregion ...Constructor...
#region ... Properties ...
/// <summary>
///
/// </summary>
public MqttApiData Model
{
get
{
return mModel;
}
set
{
if (mModel != value)
{
mModel = value;
OnPropertyChanged("Model");
}
}
}
/// <summary>
///
/// </summary>
public string ServerIp
{
get
{
return mModel.ServerIp;
}
set
{
if (mModel.ServerIp != value)
{
mModel.ServerIp = value;
OnPropertyChanged("ServerIp");
}
}
}
/// <summary>
///
/// </summary>
public int Port
{
get
{
return mModel.Port;
}
set
{
if (mModel.Port != value)
{
mModel.Port = value;
OnPropertyChanged("Port");
}
}
}
/// <summary>
///
/// </summary>
public string UserName
{
get
{
return mModel.UserName;
}
set
{
if (mModel.UserName != value)
{
mModel.UserName = value;
OnPropertyChanged("UserName");
}
}
}
/// <summary>
///
/// </summary>
public string Password
{
get
{
return mModel.Password;
}
set
{
if (mModel.Password != value)
{
mModel.Password = value;
OnPropertyChanged("Password");
}
}
}
/// <summary>
///
/// </summary>
public int Circle
{
get
{
return mModel.Circle;
}
set
{
if (mModel.Circle != value)
{
mModel.Circle = value;
OnPropertyChanged("Circle");
}
}
}
/// <summary>
///
/// </summary>
public int TransType
{
get
{
return (int)mModel.Type;
}
set
{
if ((int)Model.Type != value)
{
Model.Type = (ApiData.TransType)value;
OnPropertyChanged("TransType");
OnPropertyChanged("CircleVisiable");
}
}
}
/// <summary>
///
/// </summary>
public List<string> TransTypes
{
get
{
return mTransTypes;
}
set
{
if (mTransTypes != value)
{
mTransTypes = value;
OnPropertyChanged("TransTypes");
}
}
}
/// <summary>
///
/// </summary>
public Visibility CircleVisiable
{
get
{
return Model.Type == ApiData.TransType.Timer ? Visibility.Visible : Visibility.Collapsed;
}
}
/// <summary>
///
/// </summary>
public string RemoteTopic
{
get
{
return mModel.RemoteTopic;
}
set
{
if (mModel.RemoteTopic != value)
{
mModel.RemoteTopic = value;
RemoteResponseTopic = value+ "_response";
OnPropertyChanged("RemoteTopic");
}
}
}
/// <summary>
///
/// </summary>
public string RemoteResponseTopic
{
get
{
return mModel.RemoteResponseTopic;
}
set
{
if (mModel.RemoteResponseTopic != value)
{
mModel.RemoteResponseTopic = value;
OnPropertyChanged("RemoteResponseTopic");
}
}
}
/// <summary>
///
/// </summary>
public string LocalTopic
{
get
{
return mModel.LocalTopic;
}
set
{
if (mModel.LocalTopic != value)
{
mModel.LocalTopic = value;
LocalResponseTopic = value + "_response";
OnPropertyChanged("LocalTopic");
}
}
}
/// <summary>
///
/// </summary>
public string LocalResponseTopic
{
get
{
return mModel.LocalResponseTopic;
}
set
{
if (mModel.LocalResponseTopic != value)
{
mModel.LocalResponseTopic = value;
OnPropertyChanged("LocalResponseTopic");
}
}
}
#endregion ...Properties...
#region ... Methods ...
#endregion ...Methods...
#region ... Interfaces ...
#endregion ...Interfaces...
}
}
| 22.744186 | 105 | 0.350131 | [
"Apache-2.0"
] | bingwang12/Spider | Develop/Api/Cdy.Api.SpiderMqtt.Develop/ApiConfigViewModel.cs | 6,860 | C# |
/* Copyright 2010-2014 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using NUnit.Framework;
namespace MongoDB.BsonUnitTests.Jira.CSharp147
{
[TestFixture]
public class CSharp146Tests
{
public class Parent
{
public Child Child { get; set; }
}
public class Child
{
public Guid Id { get; set; }
public int A { get; set; }
}
[Test]
public void Test()
{
var p = new Parent { Child = new Child() };
p.Child.A = 1;
var json = p.ToJson();
BsonSerializer.Deserialize<Parent>(json); // throws Unexpected element exception
}
}
}
| 27.297872 | 92 | 0.637568 | [
"Apache-2.0"
] | EvilMindz/mongo-csharp-driver | MongoDB.BsonUnitTests/Jira/CSharp147Tests.cs | 1,285 | C# |
// Copyright 2018 Esri.
//
// 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 Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;
using Esri.ArcGISRuntime.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using Windows.UI.Popups;
namespace ArcGISRuntime.UWP.Samples.ClosestFacility
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Find closest facility to an incident (interactive)",
category: "Network analysis",
description: "Find a route to the closest facility from a location.",
instructions: "Click near any of the hospitals and a route will be displayed from that clicked location to the nearest hospital.",
tags: new[] { "incident", "network analysis", "route", "search" })]
public partial class ClosestFacility
{
// Holds locations of hospitals around San Diego.
private List<Facility> _facilities;
// Graphics overlays for facilities and incidents.
private GraphicsOverlay _facilityGraphicsOverlay;
// Symbol for facilities.
private PictureMarkerSymbol _facilitySymbol;
// Overlay for the incident.
private GraphicsOverlay _incidentGraphicsOverlay;
// Black cross where user clicked.
private MapPoint _incidentPoint;
// Symbol for the incident.
private SimpleMarkerSymbol _incidentSymbol;
// Used to display route between incident and facility to mapview.
private SimpleLineSymbol _routeSymbol;
// Solves task to find closest route between an incident and a facility.
private ClosestFacilityTask _task;
public ClosestFacility()
{
InitializeComponent();
// Create the map and graphics overlays.
Initialize();
}
private async void Initialize()
{
// Hook up the DrawStatusChanged event.
MyMapView.DrawStatusChanged += OnDrawStatusChanged;
// Construct the map and set the MapView.Map property.
Map map = new Map(BasemapStyle.ArcGISLightGray);
MyMapView.Map = map;
try
{
// Create a ClosestFacilityTask using the San Diego Uri.
_task = await ClosestFacilityTask.CreateAsync(new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ClosestFacility"));
// List of facilities to be placed around San Diego area.
_facilities = new List<Facility> {
new Facility(new MapPoint(-1.3042129900625112E7, 3860127.9479775648, SpatialReferences.WebMercator)),
new Facility(new MapPoint(-1.3042193400557665E7, 3862448.873041752, SpatialReferences.WebMercator)),
new Facility(new MapPoint(-1.3046882875518233E7, 3862704.9896770366, SpatialReferences.WebMercator)),
new Facility(new MapPoint(-1.3040539754780494E7, 3862924.5938606677, SpatialReferences.WebMercator)),
new Facility(new MapPoint(-1.3042571225655518E7, 3858981.773018156, SpatialReferences.WebMercator)),
new Facility(new MapPoint(-1.3039784633928463E7, 3856692.5980474586, SpatialReferences.WebMercator)),
new Facility(new MapPoint(-1.3049023883956768E7, 3861993.789732541, SpatialReferences.WebMercator))
};
// Center the map on the San Diego facilities.
Envelope fullExtent = GeometryEngine.CombineExtents(_facilities.Select(facility => facility.Geometry));
await MyMapView.SetViewpointGeometryAsync(fullExtent, 50);
// Create a symbol for displaying facilities.
_facilitySymbol = new PictureMarkerSymbol(new Uri("https://static.arcgis.com/images/Symbols/SafetyHealth/Hospital.png"))
{
Height = 30,
Width = 30
};
// Incident symbol.
_incidentSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Cross, Color.FromArgb(255, 0, 0, 0), 30);
// Route to hospital symbol.
_routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.FromArgb(255, 0, 0, 255), 5.0f);
// Create Graphics Overlays for incidents and facilities.
_incidentGraphicsOverlay = new GraphicsOverlay();
_facilityGraphicsOverlay = new GraphicsOverlay();
// Create a graphic and add to graphics overlay for each facility.
foreach (Facility facility in _facilities)
{
_facilityGraphicsOverlay.Graphics.Add(new Graphic(facility.Geometry, _facilitySymbol));
}
// Add each graphics overlay to MyMapView.
MyMapView.GraphicsOverlays.Add(_incidentGraphicsOverlay);
MyMapView.GraphicsOverlays.Add(_facilityGraphicsOverlay);
}
catch (Exception e)
{
await new MessageDialog(e.ToString(), "Error").ShowAsync();
}
}
private void OnDrawStatusChanged(object sender, DrawStatusChangedEventArgs e)
{
if (e.Status == DrawStatus.Completed)
{
// Link the action of tapping on the map with the MyMapView_GeoViewTapped method.
MyMapView.GeoViewTapped += MyMapView_GeoViewTapped;
// Remove this method from DrawStatusChanged events.
MyMapView.DrawStatusChanged -= OnDrawStatusChanged;
}
}
private void MyMapView_GeoViewTapped(object sender, Esri.ArcGISRuntime.UI.Controls.GeoViewInputEventArgs e)
{
// Clear any prior incident and routes from the graphics.
_incidentGraphicsOverlay.Graphics.Clear();
// Get the tapped point.
_incidentPoint = e.Location;
// Populate the facility parameters than solve using the task.
PopulateParametersAndSolveRouteAsync();
}
private async void PopulateParametersAndSolveRouteAsync()
{
try
{
// Set facilities and incident in parameters.
ClosestFacilityParameters closestFacilityParameters = await _task.CreateDefaultParametersAsync();
closestFacilityParameters.SetFacilities(_facilities);
closestFacilityParameters.SetIncidents(new List<Incident> { new Incident(_incidentPoint) });
// Use the task to solve for the closest facility.
ClosestFacilityResult result = await _task.SolveClosestFacilityAsync(closestFacilityParameters);
// Get the index of the closest facility to incident. (0) is the index of the incident, [0] is the index of the closest facility.
int closestFacility = result.GetRankedFacilityIndexes(0)[0];
// Get route from closest facility to the incident and display to mapview.
ClosestFacilityRoute route = result.GetRoute(closestFacility, 0);
// Add graphics for the incident and route.
_incidentGraphicsOverlay.Graphics.Add(new Graphic(_incidentPoint, _incidentSymbol));
_incidentGraphicsOverlay.Graphics.Add(new Graphic(route.RouteGeometry, _routeSymbol));
}
catch (Esri.ArcGISRuntime.Http.ArcGISWebException exception)
{
if (exception.Message.Equals("Unable to complete operation."))
{
await new MessageDialog("Incident not within San Diego area!", "Sample error").ShowAsync();
}
else
{
await new MessageDialog("An ArcGIS web exception occurred. \n" + exception.Message, "Sample error").ShowAsync();
}
}
}
}
} | 46.652174 | 184 | 0.644688 | [
"Apache-2.0"
] | Esri/arcgis-runtime-samples-dotne | src/UWP/ArcGISRuntime.UWP.Viewer/Samples/Network analysis/ClosestFacility/ClosestFacility.xaml.cs | 8,584 | C# |
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace PierresBakery.Models
{
public class Order
{
public string Title { get; set; }
public string Description { get; set; }
public double Price { get; set; }
public string Date { get; set; }
public int Id { get; }
private static List<Order> _instances = new List<Order> {};
public Order(string title, string description, double price, string date)
{
Title = title;
Description = description;
Price = price;
Date = date;
Id = _instances.Count;
_instances.Add(this);
}
public static List<Order> GetAll()
{
return _instances;
}
public static void ClearAll()
{
_instances.Clear();
}
public static Order Find(int searchId)
{
return _instances[searchId];
}
}
} | 22.384615 | 77 | 0.61512 | [
"MIT"
] | AnthonyGolovin/C-MVCBakery | C-MVCBakery/Models/Order.cs | 873 | C# |
/*
dotNetRDF is free and open source software licensed under the MIT License
-----------------------------------------------------------------------------
Copyright (c) 2009-2012 dotNetRDF Project (dotnetrdf-developer@lists.sf.net)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.IO;
using VDS.RDF.Query;
namespace VDS.RDF.Parsing.Tokens
{
/// <summary>
/// Tokeniser for tokenising TSV inputs
/// </summary>
public class TsvTokeniser
: BaseTokeniser
{
private ParsingTextReader _in;
/// <summary>
/// Creates a new TSV Tokeniser
/// </summary>
/// <param name="reader">Text Reader</param>
public TsvTokeniser(ParsingTextReader reader)
: base(reader)
{
this._in = reader;
}
/// <summary>
/// Creates a new TSV Tokeniser
/// </summary>
/// <param name="reader">Stream Reader</param>
public TsvTokeniser(StreamReader reader)
: this(ParsingTextReader.Create(reader)) { }
/// <summary>
/// Gets the next available token from the input
/// </summary>
/// <returns></returns>
public override IToken GetNextToken()
{
//Have we read anything yet?
if (this.LastTokenType == -1)
{
//Nothing read yet so produce a BOF Token
this.LastTokenType = Token.BOF;
return new BOFToken();
}
else
{
try
{
//Reading has started
this.StartNewToken();
//Check for EOF
if (this._in.EndOfStream)
{
if (this.Length == 0)
{
//We're at the End of the Stream and not part-way through reading a Token
return new EOFToken(this.CurrentLine, this.CurrentPosition);
}
else
{
//We're at the End of the Stream and part-way through reading a Token
//Raise an error
throw UnexpectedEndOfInput("Token");
}
}
char next = this.Peek();
//Always need to do a check for End of Stream after Peeking to handle empty files OK
if (next == Char.MaxValue && this._in.EndOfStream)
{
if (this.Length == 0)
{
//We're at the End of the Stream and not part-way through reading a Token
return new EOFToken(this.CurrentLine, this.CurrentPosition);
}
else
{
//We're at the End of the Stream and part-way through reading a Token
//Raise an error
throw UnexpectedEndOfInput("Token");
}
}
if (Char.IsDigit(next) || next == '+' || next == '-')
{
return this.TryGetNumericLiteral();
}
switch (next)
{
case '\t':
//Tab
this.ConsumeCharacter();
this.LastTokenType = Token.TAB;
return new TabToken(this.StartLine, this.StartPosition);
case '\r':
case '\n':
//New Line
this.ConsumeNewLine(true);
this.LastTokenType = Token.EOL;
return new EOLToken(this.StartLine, this.StartPosition);
case '.':
//Dot
this.ConsumeCharacter();
return this.TryGetNumericLiteral();
case '@':
//Start of a Keyword or Language Specifier
return this.TryGetLangSpec();
case '?':
//Start of a Variable
return this.TryGetVariable();
case '<':
//Start of a Uri
return this.TryGetUri();
case '_':
//Start of a QName
return this.TryGetQName();
case '"':
//Start of a Literal
return this.TryGetLiteral();
case '^':
//Data Type Specifier
this.ConsumeCharacter();
next = this.Peek();
if (next == '^')
{
this.ConsumeCharacter();
//Try and get the Datatype
this.StartNewToken();
return this.TryGetDataType();
}
else
{
throw UnexpectedCharacter(next, "the second ^ as part of a ^^ Data Type Specifier");
}
case 't':
case 'f':
//Plain Literal?
return this.TryGetPlainLiteral();
default:
//Unexpected Character
throw this.UnexpectedCharacter(next, String.Empty);
}
}
catch (IOException)
{
//End Of Stream Check
if (this._in.EndOfStream)
{
//At End of Stream so produce the EOFToken
return new EOFToken(this.CurrentLine, this.CurrentPosition);
}
else
{
//Some other Error so throw
throw;
}
}
}
}
private IToken TryGetVariable()
{
//Consume first Character which must be a ?/$
this.ConsumeCharacter();
//Consume other valid Characters
char next = this.Peek();
while (Char.IsLetterOrDigit(next) || UnicodeSpecsHelper.IsLetterOrDigit(next) || next == '-' || next == '_' || next == '\\')
{
if (next == '\\')
{
//Check its a valid Escape
this.HandleEscapes(TokeniserEscapeMode.QName);
}
else
{
this.ConsumeCharacter();
}
next = this.Peek();
}
//Validate
String value = this.Value;
if (value.EndsWith("."))
{
this.Backtrack();
value = value.Substring(0, value.Length - 1);
}
if (SparqlSpecsHelper.IsValidVarName(value))
{
return new VariableToken(value, this.CurrentLine, this.StartPosition, this.EndPosition);
}
else
{
throw Error("The value '" + value + "' is not valid a Variable Name");
}
}
private IToken TryGetLangSpec()
{
//Skip the first Character which must have been an @
this.SkipCharacter();
//Consume characters which can be in the keyword or Language Specifier
char next = this.Peek();
while (Char.IsLetterOrDigit(next) || next == '-')
{
this.ConsumeCharacter();
next = this.Peek();
}
//Check the output to see if it's valid
String output = this.Value;
if (RdfSpecsHelper.IsValidLangSpecifier(output))
{
this.LastTokenType = Token.LANGSPEC;
return new LanguageSpecifierToken(output, this.CurrentLine, this.StartPosition, this.EndPosition);
}
else
{
throw Error("Unexpected Content '" + output + "' encountered, expected a valid Language Specifier");
}
}
private IToken TryGetUri()
{
//Consume the first Character which must have been a <
this.ConsumeCharacter();
//Consume subsequent characters
char next;
do
{
next = this.Peek();
//Watch out for escapes
if (next == '\\')
{
this.HandleEscapes(TokeniserEscapeMode.Uri);
}
else
{
this.ConsumeCharacter();
}
} while (next != '>');
//Return the Token
this.LastTokenType = Token.URI;
return new UriToken(this.Value, this.CurrentLine, this.StartPosition, this.EndPosition);
}
private IToken TryGetQName()
{
bool colonoccurred = false;
char next = this.Peek();
while (Char.IsLetterOrDigit(next) || next == '-' || next == '_' || next == ':')
{
this.ConsumeCharacter();
if (next == ':')
{
if (colonoccurred)
{
throw Error("Unexpected Colon encountered in input '" + this.Value + "', a Colon may only occur once in a QName");
}
colonoccurred = true;
}
next = this.Peek();
}
//Validate the QName
if (this.Value.StartsWith("_:"))
{
//Blank Node ID
this.LastTokenType = Token.BLANKNODEWITHID;
return new BlankNodeWithIDToken(this.Value, this.CurrentLine, this.StartPosition, this.EndPosition);
}
else
{
throw Error("The input '" + this.Value + "' is not a valid Blank Node Name in {0}");
}
}
private IToken TryGetLiteral()
{
bool longliteral = false;
//Consume first character which must have been a "
this.ConsumeCharacter();
//Check if this is a long literal
char next = this.Peek();
if (next == '"')
{
this.ConsumeCharacter();
next = this.Peek();
if (next == '"')
{
//Long Literal
longliteral = true;
}
else
{
//Empty Literal
this.LastTokenType = Token.LITERAL;
return new LiteralToken(this.Value, this.CurrentLine, this.StartPosition, this.EndPosition);
}
}
while (true)
{
//Handle Escapes
if (next == '\\')
{
this.HandleEscapes(TokeniserEscapeMode.QuotedLiterals);
next = this.Peek();
continue;
}
//Add character to output buffer
this.ConsumeCharacter();
//Check for end of Literal
if (next == '"')
{
if (longliteral)
{
next = this.Peek();
if (next == '"')
{
//Got two quotes so far
this.ConsumeCharacter();
next = this.Peek();
if (next == '"')
{
//Triple quote - end of literal
this.LastTokenType = Token.LONGLITERAL;
return new LongLiteralToken(this.Value, this.StartLine, this.EndLine, this.StartPosition, this.EndPosition);
}
else
{
//Not a triple quote so continue
continue;
}
}
else
{
//Not a Triple quote so continue
continue;
}
}
else
{
//End of Literal
this.LastTokenType = Token.LITERAL;
return new LiteralToken(this.Value, this.CurrentLine, this.StartPosition, this.EndPosition);
}
}
//Continue Reading
next = this.Peek();
}
}
private IToken TryGetNumericLiteral()
{
bool dotoccurred = false;
bool expoccurred = false;
bool negoccurred = false;
if (this.Length == 1) dotoccurred = true;
char next = this.Peek();
while (Char.IsDigit(next) || next == '-' || next == '+' || next == 'e' || (next == '.' && !dotoccurred))
{
//Consume the Character
this.ConsumeCharacter();
if (next == '+')
{
//Can only be first character in the numeric literal or come immediately after the 'e'
if (this.Length > 1 && !this.Value.EndsWith("e+"))
{
throw Error("Unexpected Character (Code " + (int)next + ") +\nThe plus sign can only occur once at the Start of a Numeric Literal and once immediately after the 'e' exponent specifier, if this was intended as an additive operator please insert space to disambiguate this");
}
}
if (next == '-')
{
if (negoccurred && !this.Value.EndsWith("e-"))
{
//Negative sign already seen
throw Error("Unexpected Character (Code " + (int)next + ") -\nThe minus sign can only occur once at the Start of a Numeric Literal, if this was intended as a subtractive operator please insert space to disambiguate this");
}
else
{
negoccurred = true;
//Check this is at the start of the string or immediately after the 'e'
if (this.Length > 1 && !this.Value.EndsWith("e-"))
{
throw Error("Unexpected Character (Code " + (int)next + ") -\nThe minus sign can only occur at the Start of a Numeric Literal and once immediately after the 'e' exponent specifier, if this was intended as a subtractive operator please insert space to disambiguate this");
}
}
}
else if (next == 'e')
{
if (expoccurred)
{
//Exponent already seen
throw Error("Unexpected Character (Code " + (int)next + " e\nThe Exponent specifier can only occur once in a Numeric Literal");
}
else
{
expoccurred = true;
//Check that it isn't the start of the string
if (this.Length == 1)
{
throw Error("Unexpected Character (Code " + (int)next + " e\nThe Exponent specifier cannot occur at the start of a Numeric Literal");
}
}
}
else if (next == '.')
{
dotoccurred = true;
}
next = this.Peek();
}
//Decimals can't end with a . so backtrack
if (this.Value.EndsWith(".")) this.Backtrack();
String value = this.Value;
if (!SparqlSpecsHelper.IsValidNumericLiteral(value))
{
//Invalid Numeric Literal
throw Error("The format of the Numeric Literal '" + this.Value + "' is not valid!");
}
//Return the Token
this.LastTokenType = Token.PLAINLITERAL;
return new PlainLiteralToken(this.Value, this.CurrentLine, this.StartPosition, this.EndPosition);
}
private IToken TryGetPlainLiteral()
{
this.ConsumeCharacter();
char next = this.Peek();
while (Char.IsLetter(next))
{
this.ConsumeCharacter();
next = this.Peek();
}
if (TurtleSpecsHelper.IsValidPlainLiteral(this.Value, TurtleSyntax.Original))
{
this.LastTokenType = Token.PLAINLITERAL;
return new PlainLiteralToken(this.Value, this.StartLine, this.StartPosition, this.EndPosition);
}
else
{
throw new RdfParseException("'" + this.Value + "' is not a valid Plain Literal!");
}
}
private IToken TryGetDataType()
{
char next = this.Peek();
if (next == '<')
{
//Uri for Data Type
IToken temp = this.TryGetUri();
return new DataTypeToken("<" + temp.Value + ">", temp.StartLine, temp.StartPosition - 3, temp.EndPosition + 1);
}
else
{
throw UnexpectedCharacter(next, "expected a < to start a URI to specify a Data Type for a Typed Literal");
}
}
}
}
| 36.952741 | 299 | 0.434981 | [
"MIT"
] | mungojam/dotnetrdf-fork | Libraries/core/net40/Parsing/Tokens/TsvTokeniser.cs | 19,548 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using AdaptiveExpressions.Properties;
using Newtonsoft.Json;
namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
{
/// <summary>
/// Goto an action by Id.
/// </summary>
public class GotoAction : Dialog
{
/// <summary>
/// Class identifier.
/// </summary>
[JsonProperty("$kind")]
public const string Kind = "Microsoft.GotoAction";
/// <summary>
/// Initializes a new instance of the <see cref="GotoAction"/> class.
/// </summary>
/// <param name="actionId">Optional, action's unique identifier.</param>
/// <param name="callerPath">Optional, source file full path.</param>
/// <param name="callerLine">Optional, line number in source file.</param>
public GotoAction(string actionId = null, [CallerFilePath] string callerPath = "", [CallerLineNumber] int callerLine = 0)
{
this.RegisterSourceLocation(callerPath, callerLine);
this.ActionId = actionId;
}
/// <summary>
/// Gets or sets the action Id to goto.
/// </summary>
/// <value>The action Id.</value>
public StringExpression ActionId { get; set; }
/// <summary>
/// Gets or sets an optional expression which if is true will disable this action.
/// </summary>
/// <example>
/// "user.age > 18".
/// </example>
/// <value>
/// A boolean expression.
/// </value>
[JsonProperty("disabled")]
public BoolExpression Disabled { get; set; }
/// <summary>
/// Called when the dialog is started and pushed onto the dialog stack.
/// </summary>
/// <param name="dc">The <see cref="DialogContext"/> for the current turn of conversation.</param>
/// <param name="options">Optional, initial information to pass to the dialog.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects
/// or threads to receive notice of cancellation.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public override async Task<DialogTurnResult> BeginDialogAsync(DialogContext dc, object options = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (options is CancellationToken)
{
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
// Continue is simply returning an ActionScopeResult with GotoAction and actionId command in it.
var actionScopeResult = new ActionScopeResult()
{
ActionScopeCommand = ActionScopeCommands.GotoAction,
ActionId = this.ActionId?.GetValue(dc.State) ?? throw new InvalidOperationException($"Unable to get a {nameof(ActionId)} from state.")
};
return await dc.EndDialogAsync(result: actionScopeResult, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
}
| 41.423529 | 176 | 0.621414 | [
"MIT"
] | BetaLixT/botbuilder-dotnet | libraries/Microsoft.Bot.Builder.Dialogs.Adaptive/Actions/GotoAction.cs | 3,523 | C# |
/*
* The MIT License (MIT)
*
* Copyright (c) 2012-2013 Brno University of Technology - Faculty of Information Technology (http://www.fit.vutbr.cz)
* Author(s):
* Vladimir Vesely (mailto:ivesely@fit.vutbr.cz)
* Martin Mares (mailto:xmares04@stud.fit.vutbr.cz)
* Jan Plusal (mailto:xplusk03@stud.fit.vutbr.cz)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Net;
using Netfox.Framework.Models.PmLib.SupportedTypes;
using PacketDotNet;
namespace Netfox.Framework.Models.PmLib
{
/// <summary> Gets a IP flags.</summary>
public enum PmPacketIPv4FlagsEnum
{
/// <summary> An enum constant representing the not i pv 4 option.</summary>
NotIPv4 = -1,
/// <summary> An enum constant representing the no flags option.</summary>
NoFlags = 0,
/// <summary> An enum constant representing the mf option.</summary>
Mf = 1, //more fragments
/// <summary> An enum constant representing the df option.</summary>
Df = 2, //do not fragment
/// <summary> An enum constant representing the reserved option.</summary>
Reserved = 4 //must be zero
}
/// <summary>
/// Represents a basic structure containing all relevant packet information.
/// </summary>
public class PmPacket
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="linkLayer"></param>
/// <param name="packetData"></param>
public PmPacket(PmLinkType linkLayer, Byte[] packetData)
{
this.PacketInfo = Packet.ParsePacket(PmSupportedTypes.ConvertLinkTypeToPacketdotNet(linkLayer), packetData);
this.UpdateCalculatedOffsets();
}
/// <summary>
/// Gets or sets an application name.
/// </summary>
public String ApplicationName { get; set; }
#region L2
/// <summary>
/// Gets a protocol type carried in the Ethernet frame.
/// If current packet is not Ethernet frame it yields to EthernetPacketType.NONE
/// </summary>
public EthernetPacketType EthernetType
{
get
{
var eth = (EthernetPacket) this.PacketInfo.Extract(typeof(EthernetPacket));
return eth?.Type ?? EthernetPacketType.None;
}
}
public EthernetPacket Ethernet
{
get
{
return (EthernetPacket)this.PacketInfo.Extract(typeof(EthernetPacket));
}
}
#endregion
/// <summary>
/// Gets or sets the lenght of the frame.
/// </summary>
public Int32 FrameLength { get; set; }
/// <summary>
/// Gets or sets the unique frame locator.
/// </summary>
public Object FrameLocator { get; set; }
/// <summary>
/// Represents an offset of this frame in the source file.
/// Using this offset it is possible to directly access the frame
/// within source pcap file.
/// </summary>
public Int64 FramePcapOffset { get; set; }
/// <summary>
/// Gets or sets time offset of the frame.
/// </summary>
public DateTime FrameTimeStamp { get; set; }
/// <summary>
/// Gets or sets IP protocol number
/// </summary>
public IPProtocolType IPProtocol { get; set; }
/// <summary>
/// Gets an underlaying packet info object.
/// </summary>
public Packet PacketInfo { get; }
public DateTime TimeStamp
{
get { return this.FrameTimeStamp; }
set { this.FrameTimeStamp = value; }
}
#region Various offsets in the packet
/// <summary>
/// Gets an offset of a network protocol header.
/// </summary>
public Int16 PacketHeaderOffset { get; private set; }
/// <summary>
/// Gets an offset of a transport protocol header.
/// </summary>
public Int16 SegmentHeaderOffset { get; private set; }
/// <summary>
/// Gets an offset of a application payload data.
/// </summary>
public Int16 SegmentPayloadOffset { get; private set; }
/// <summary>
/// Gets a length of application payload data.
/// </summary>
public Int32 SegmentPayloadLength { get; private set; }
/// <summary>
/// Method calculates offsets of L2, L3 and L4 headers so that they could be easily accessed and parsed afterwards
/// </summary>
private void UpdateCalculatedOffsets()
{
var packet = this.PacketInfo;
while(packet != null)
{
if(packet is EthernetPacket)
{
var tpacket = packet as EthernetPacket;
this.PacketHeaderOffset = (Int16) tpacket.Header.Length;
}
if(packet is IPv4Packet)
{
var tpacket = packet as IPv4Packet;
this.SegmentHeaderOffset = (Int16) (this.PacketHeaderOffset + tpacket.Header.Length);
}
if(packet is IPv6Packet)
{
var tpacket = packet as IPv6Packet;
this.SegmentHeaderOffset = (Int16) (this.PacketHeaderOffset + (tpacket.TotalLength - tpacket.PayloadLength));
}
if(packet is TcpPacket)
{
var tpacket = packet as TcpPacket;
this.SegmentPayloadOffset = (Int16) (this.SegmentHeaderOffset + (tpacket.DataOffset*4));
this.SegmentPayloadLength = tpacket.PayloadData?.Length ?? 0;
}
if(packet is UdpPacket)
{
var tpacket = packet as UdpPacket;
this.SegmentPayloadOffset = (Int16) (this.SegmentHeaderOffset + tpacket.Header.Length);
this.SegmentPayloadLength = tpacket.PayloadData?.Length ?? 0;
}
packet = packet.PayloadPacket;
}
}
#endregion
#region L3
#region IPv4/IPv6 common informations
/// <summary>
/// Gets the IP packet enbcapulated in the current CapPacket object.
/// </summary>
/// <value>The IPPacket instance if current CapPacket contains this pacekt; otherwise null.</value>
public IpPacket IP
{
get
{
var p = (IpPacket) this.PacketInfo.Extract(typeof(IpPacket));
return p;
}
}
/// <summary>
/// Gets an IP version, i.e. IPv4 or IPv6.
/// </summary>
public IpVersion IpVersion
{
get
{
var ip = (IpPacket) this.PacketInfo.Extract(typeof(IpPacket));
return ip?.Version ?? IpVersion.IPv4;
}
}
/// <summary>
/// Gets a protocol type carried in the IP packet.
/// </summary>
public IPProtocolType ProtocolIdentifier
{
get
{
var ip = (IpPacket) this.PacketInfo.Extract(typeof(IpPacket));
return ip?.Protocol ?? IPProtocolType.NONE;
}
}
/// <summary>
/// Gets a source address.
/// </summary>
public IPAddress SourceAddress
{
get
{
var ip = (IpPacket) this.PacketInfo.Extract(typeof(IpPacket));
return ip?.SourceAddress ?? IPAddress.None;
}
}
/// <summary>
/// Gets a destination address.
/// </summary>
public IPAddress DestinationAddress
{
get
{
var ip = (IpPacket) this.PacketInfo.Extract(typeof(IpPacket));
return ip?.DestinationAddress ?? IPAddress.None;
}
}
/// <summary>
/// Gets the source end point of the encapsulated pacekt.
/// </summary>
/// <value>The source end point.</value>
public IPEndPoint SourceEndPoint => new IPEndPoint(this.IP.SourceAddress, this.SourceTransportPort);
/// <summary>
/// Gets the target end point of the encapsulated packet.
/// </summary>
/// <value>The target end point.</value>
public IPEndPoint DestinationEndPoint => new IPEndPoint(this.IP.DestinationAddress, this.DestinationTransportPort);
public PmPacketIPv4FlagsEnum PmPacketIPv4Flags
{
get
{
var ipv4 = this.PacketInfo.Extract(typeof(IpPacket)) as IPv4Packet;
return (ipv4 != null)? (PmPacketIPv4FlagsEnum) ipv4.FragmentFlags : PmPacketIPv4FlagsEnum.NotIPv4;
}
}
public Int32 Pv4FragmentOffset
{
get
{
var ipv4 = this.PacketInfo.Extract(typeof(IpPacket)) as IPv4Packet;
return ipv4?.FragmentOffset ?? -1;
}
}
#endregion
#region IPv4 related information
/// <summary>
/// Gets the IPv4 packet enbcapulated in the current CapPacket object.
/// </summary>
/// <value>The IPV4Packet instance if current CapPacket contains this pacekt; otherwise null.</value>
public IPv4Packet Pv4 => (IPv4Packet) this.PacketInfo.Extract(typeof(IPv4Packet));
/// <summary>
/// In case of IPv4 packet it returns FragmentOffset field from IPv4 header
/// </summary>
public Int32 Ipv4FragmentOffset
{
get
{
var ipv4 = this.PacketInfo.Extract(typeof(IpPacket)) as IPv4Packet;
return ipv4?.FragmentOffset ?? -1;
}
}
/// <summary>
/// Retrieves IPv4 identification
/// </summary>
public Int32 Ipv4Identification
{
get
{
var ipv4 = this.PacketInfo.Extract(typeof(IpPacket)) as IPv4Packet;
return ipv4?.Id ?? -1;
}
}
//TODO: Vesely - Return also unspecified value
/// <summary>
/// Retrieves IPv4 fragmentation DF bit
/// </summary>
public Boolean Ipv4DFbit => this.Ipv4FragmentFlags != -1 && (this.Pv4FragmentOffset&1) != 0;
//TODO: Vesely - Return also unspecified value
/// <summary>
/// Retrieves IPv4 fragmentation MF bit
/// </summary>
public Boolean Ipv4MFbit => this.Ipv4FragmentFlags != -1 && (this.Ipv4FragmentFlags&1) != 0;
/// <summary>
/// In case of IPv4 packet it returns FragmentFlags field from IPv4 header
/// </summary>
public Int16 Ipv4FragmentFlags
{
get
{
//It is non-IPv4 for packet, hence fragmentation information are obsolete
var tpacket = this.PacketInfo.Extract(typeof(IpPacket)) as IPv4Packet;
return tpacket?.FragmentFlags ?? -1;
}
}
#endregion
#region IPv6 related information
/// <summary>
/// Gets the IPv6 packet enbcapulated in the current CapPacket object.
/// </summary>
/// <value>The IPV6 Packet instance if current CapPacket contains this pacekt; otherwise null.</value>
public IPv6Packet Pv6 => (IPv6Packet) this.PacketInfo.Extract(typeof(IPv6Packet));
#endregion
#endregion
#region L4
#region TCP/UDP common informations
/// <summary>
/// Gets a source transport port if applicable.
/// </summary>
public UInt16 SourceTransportPort
{
get
{
switch(this.ProtocolIdentifier)
{
case IPProtocolType.TCP:
var tcp = (TcpPacket) this.PacketInfo.Extract(typeof(TcpPacket));
return tcp?.SourcePort ?? 0;
case IPProtocolType.UDP:
var udp = (UdpPacket) this.PacketInfo.Extract(typeof(UdpPacket));
return udp?.SourcePort ?? 0;
}
return 0;
}
}
/// <summary>
/// Gets a destination transport port if applicable.
/// </summary>
public UInt16 DestinationTransportPort
{
get
{
switch(this.ProtocolIdentifier)
{
case IPProtocolType.TCP:
var tcp = (TcpPacket) this.PacketInfo.Extract(typeof(TcpPacket));
return tcp?.DestinationPort ?? 0;
case IPProtocolType.UDP:
var udp = (UdpPacket) this.PacketInfo.Extract(typeof(UdpPacket));
return udp?.DestinationPort ?? 0;
default:
return 0;
}
}
}
#endregion
#region TCP related information
/// <summary>
/// Gets the TCP packet enbcapulated in the current CapPacket object.
/// </summary>
/// <value>The TCPPacket instance if current CapPacket contains this pacekt; otherwise null.</value>
public TcpPacket TCP => (TcpPacket) this.PacketInfo.Extract(typeof(TcpPacket));
#region TCPFlags
/// <summary>
/// Gets a TCP flags.
/// </summary>
public Byte TcpFlags
{
get
{
var tcp = (TcpPacket) this.PacketInfo.Extract(typeof(TcpPacket));
return tcp?.AllFlags ?? 0;
}
}
//TODO: Vesely - For all TCP flags return also unspecified value
/// <summary>
/// Gets TCP ACK flag
/// </summary>
public Boolean TcpFAck
{
get
{
var tcp = (TcpPacket) this.PacketInfo.Extract(typeof(TcpPacket));
return (tcp != null) && tcp.Ack;
}
}
/// <summary>
/// Gets TCP ACK flag
/// </summary>
public Boolean TcpFCwr
{
get
{
var tcp = (TcpPacket) this.PacketInfo.Extract(typeof(TcpPacket));
return (tcp != null) && tcp.CWR;
}
}
/// <summary>
/// Gets TCP ACK flag
/// </summary>
public Boolean TcpFEce
{
get
{
var tcp = (TcpPacket) this.PacketInfo.Extract(typeof(TcpPacket));
return (tcp != null) && tcp.ECN;
}
}
/// <summary>
/// Gets TCP ACK flag
/// </summary>
public Boolean TcpFFin
{
get
{
var tcp = (TcpPacket) this.PacketInfo.Extract(typeof(TcpPacket));
return (tcp != null) && tcp.Fin;
}
}
/// <summary>
/// Gets TCP NS flag
/// </summary>
/// <summary>
/// Gets TCP ACK flag
/// </summary>
public Boolean TcpFPsh
{
get
{
var tcp = (TcpPacket) this.PacketInfo.Extract(typeof(TcpPacket));
return (tcp != null) && tcp.Psh;
}
}
/// <summary>
/// Gets TCP ACK flag
/// </summary>
public Boolean TcpFRst
{
get
{
var tcp = (TcpPacket) this.PacketInfo.Extract(typeof(TcpPacket));
return (tcp != null) && tcp.Rst;
}
}
/// <summary>
/// Gets TCP ACK flag
/// </summary>
public Boolean TcpFSyn
{
get
{
var tcp = (TcpPacket) this.PacketInfo.Extract(typeof(TcpPacket));
return (tcp != null) && tcp.Syn;
}
}
/// <summary>
/// Gets TCP ACK flag
/// </summary>
public Boolean TcpFUrg
{
get
{
var tcp = (TcpPacket) this.PacketInfo.Extract(typeof(TcpPacket));
return (tcp != null) && tcp.Urg;
}
}
#endregion
/// <summary>
/// Gets a TCP sequence number field.
/// </summary>
public UInt32 TcpSequenceNumber
{
get
{
var tcp = (TcpPacket) this.PacketInfo.Extract(typeof(TcpPacket));
return tcp?.SequenceNumber ?? 0;
}
}
/// <summary>
/// Gets a TCP acknowledgment number field.
/// </summary>
public UInt32 TcpAcknowledgmentNumber
{
get
{
var tcp = (TcpPacket) this.PacketInfo.Extract(typeof(TcpPacket));
return tcp?.AcknowledgmentNumber ?? 0;
}
}
/// <summary>
/// Gets a TCP sequence number field.
/// </summary>
public UInt32 SequenceNumber
{
get
{
var tcp = (TcpPacket) this.PacketInfo.Extract(typeof(TcpPacket));
return tcp?.SequenceNumber ?? 0;
}
}
/// <summary>
/// Gets a TCP acknowledgment number field.
/// </summary>
public UInt32 AcknowledgmentNumber
{
get
{
var tcp = (TcpPacket) this.PacketInfo.Extract(typeof(TcpPacket));
return tcp?.AcknowledgmentNumber ?? 0;
}
}
/// <summary>
/// Gets a TCP checksum
/// </summary>
public Boolean IsValidChecksum
{
get
{
var tcp = (TcpPacket) this.PacketInfo.Extract(typeof(TcpPacket));
return (tcp != null) && tcp.CalculateTCPChecksum() == tcp.Checksum;
}
}
#endregion
#region UDP related information
/// <summary>
/// Gets the UDP packet enbcapulated in the current CapPacket object.
/// </summary>
/// <value>The UDPPacket instance if current CapPacket contains this pacekt; otherwise null.</value>
public UdpPacket Udp => (UdpPacket) this.PacketInfo.Extract(typeof(UdpPacket));
#endregion
#endregion
}
} | 33.427119 | 129 | 0.523679 | [
"Apache-2.0"
] | mvondracek/NetfoxDetective | Framework/CModels/PmLib/PmPacket.cs | 19,724 | C# |
#nullable disable
using System;
using System.Linq;
using PasPasPas.Globals.Options.DataTypes;
using PasPasPas.Globals.Types;
using PasPasPasTests.Common;
namespace PasPasPasTests.Types {
/// <summary>
/// test for structural properties
/// </summary>
public class StructuralTests : TypeTest {
private void AssertExprTypeInProc(string proc, string expression, string typeName = "", string decls = "", ITypeDefinition typeId = default, string proc2 = "") {
var file = "SimpleExpr";
var program = $"program {file};{decls} {proc} begin writeln({expression}); end; {proc2} begin end. ";
AssertExprType(file, program, typeId, false, typeName);
}
private enum AccessModifierTestMode {
InType, InDerivedType, InExternalType
}
private ISystemUnit KnownTypeIds
=> CreateEnvironment().TypeRegistry.SystemUnit;
private void AssertTypeForAccessModifier(string modifier, string decl, string expression, AccessModifierTestMode mode, ITypeDefinition typeId, bool classFunction = false) {
var file = "SimpleExpr";
var decl1 = string.Empty;
var decl2 = string.Empty;
var cf = classFunction ? " class " : string.Empty;
switch (mode) {
case AccessModifierTestMode.InType: {
decl1 = cf + "function x: Integer;";
decl2 = cf + "function ta.x: Integer; begin ";
break;
}
case AccessModifierTestMode.InDerivedType: {
decl1 = cf + "function x: Integer; virtual; end; tb = class(ta) " + cf + " function x: Integer; override;";
decl2 = cf + "function ta.x: integer; begin Result := 5; end; " + cf + " function tb.x: Integer; begin ";
break;
}
case AccessModifierTestMode.InExternalType: {
decl2 = " procedure x; var a: ta; begin ";
expression = "a." + expression;
break;
}
}
var decls = $"type ta = class {modifier} {decl} {decl1} end; {decl2} writeln({expression}); end; ";
var program = $"program {file}; {decls} begin end. ";
AssertExprType(file, program, typeId, false, string.Empty);
}
/// <summary>
/// test result definitions
/// </summary>
[TestMethod]
public void TestResultDef() {
AssertExprTypeInProc("function a: Integer;", "a", typeId: KnownTypeIds.IntegerType);
AssertExprTypeInProc("type x = class function a: string; end; function x.a: string;", "Result", typeId: KnownTypeIds.StringType);
AssertExprTypeInProc("function a: string;", "4", typeId: KnownTypeIds.ShortIntType);
AssertExprTypeInProc("function a: string;", "Result", typeId: KnownTypeIds.StringType);
AssertExprTypeInProc("function a: string;", "a", typeId: KnownTypeIds.StringType);
AssertExprTypeInProc("function a: Integer; function b: string; ", "Result", "", "", KnownTypeIds.StringType, " begin end; ");
AssertExprTypeInProc("function a: Integer; function b: string; ", "b", "", "", KnownTypeIds.StringType, " begin end; ");
AssertExprTypeInProc("function a: Integer; function b: string; ", "a", "", "", KnownTypeIds.IntegerType, " begin end; ");
}
/// <summary>
/// test method parameters
/// </summary>
[TestMethod]
public void TestMethodParams() {
AssertExprTypeInProc("procedure b(a: Integer);", "a", typeId: KnownTypeIds.IntegerType);
AssertExprTypeInProc("procedure b(a, c: Integer);", "a", typeId: KnownTypeIds.IntegerType);
AssertExprTypeInProc("procedure b(a, c: Integer);", "c", typeId: KnownTypeIds.IntegerType);
AssertExprTypeInProc("function b(a: Integer): string;", "a", typeId: KnownTypeIds.IntegerType);
AssertExprTypeInProc("type x = class function a(b: Integer): string; end; function x.a(b: Integer): string;", "b", typeId: KnownTypeIds.IntegerType);
AssertExprTypeInProc("type x = class procedure a(b: Integer); end; procedure x.a;", "b", typeId: KnownTypeIds.IntegerType);
AssertExprTypeInProc("type x = class function a(b: Integer): string; end; function x.a;", "b", typeId: KnownTypeIds.IntegerType);
}
/// <summary>
/// test self pointer
/// </summary>
[TestMethod]
public void TestSelfPointer() {
var e = CreateEnvironment();
var ct = e.TypeRegistry.CreateTypeFactory(e.TypeRegistry.SystemUnit);
var c = ct.CreateStructuredType("x", StructuredTypeKind.Class);
AssertExprTypeInProc("type x = class var z: string; procedure b; end; procedure x.b;", "Self", typeId: c);
AssertExprTypeInProc("type x = class var z: string; procedure b; end; procedure x.b;", "Self.z", typeId: KnownTypeIds.StringType);
AssertExprTypeInProc("type x = class var z: string; procedure b; end; procedure x.b;", "z", typeId: KnownTypeIds.StringType);
AssertExprTypeInProc("type x = class class var z: string; procedure b; end; procedure x.b;", "Self.z", typeId: KnownTypeIds.StringType);
AssertExprTypeInProc("type x = class class var z: string; procedure b; end; procedure x.b;", "z", typeId: KnownTypeIds.StringType);
AssertExprTypeInProc("type x = class var z: string; class procedure b; end; class procedure x.b;", "Self.z", typeId: KnownTypeIds.ErrorType);
AssertExprTypeInProc("type x = class var z: string; class procedure b; end; class procedure x.b;", "z", typeId: KnownTypeIds.ErrorType);
AssertExprTypeInProc("type x = class class var z: string; class procedure b; end; class procedure x.b;", "Self.z", typeId: KnownTypeIds.StringType);
AssertExprTypeInProc("type x = class class var z: string; class procedure b; end; class procedure x.b;", "z", typeId: KnownTypeIds.StringType);
}
/// <summary>
/// test visibility for private members
/// </summary>
[TestMethod]
public void TestVisibilityPrivate() {
var i = AccessModifierTestMode.InType;
var o = AccessModifierTestMode.InDerivedType;
var u = AccessModifierTestMode.InExternalType;
AssertTypeForAccessModifier("private", "f: integer;", "f", i, KnownTypeIds.IntegerType);
AssertTypeForAccessModifier("private", "f: integer;", "f", o, KnownTypeIds.IntegerType);
AssertTypeForAccessModifier("private", "f: integer;", "f", u, KnownTypeIds.IntegerType);
AssertTypeForAccessModifier("strict private", "f: integer;", "f", i, KnownTypeIds.IntegerType);
AssertTypeForAccessModifier("strict private", "f: integer;", "f", o, KnownTypeIds.ErrorType);
AssertTypeForAccessModifier("strict private", "f: integer;", "f", u, KnownTypeIds.ErrorType);
}
/// <summary>
/// test calls to inherited methods
/// </summary>
[TestMethod]
public void TestInherited() {
var o = AccessModifierTestMode.InDerivedType;
AssertTypeForAccessModifier(string.Empty, "function f: integer;", "inherited", o, KnownTypeIds.IntegerType);
AssertTypeForAccessModifier(string.Empty, "function f: integer;", "inherited", o, KnownTypeIds.IntegerType, true);
}
/// <summary>
/// test protected visibility of members
/// </summary>
[TestMethod]
public void TestVisibilityProtected() {
var i = AccessModifierTestMode.InType;
var o = AccessModifierTestMode.InDerivedType;
var u = AccessModifierTestMode.InExternalType;
AssertTypeForAccessModifier("protected", "f: integer;", "f", o, KnownTypeIds.IntegerType);
AssertTypeForAccessModifier("protected", "f: integer;", "f", i, KnownTypeIds.IntegerType);
AssertTypeForAccessModifier("protected", "f: integer", "f", u, KnownTypeIds.IntegerType);
AssertTypeForAccessModifier("strict protected", "f: integer;", "f", o, KnownTypeIds.IntegerType);
AssertTypeForAccessModifier("strict protected", "f: integer;", "f", i, KnownTypeIds.IntegerType);
AssertTypeForAccessModifier("strict protected", "f: integer", "f", u, KnownTypeIds.ErrorType);
}
/*
[TestMethod]
public void TestForwardDeclarations() {
AssertExprTypeInProc("function a: Integer; begin Result := 5; end; procedure b; ", "a", typeId: KnownTypeIds.IntegerType);
AssertExprTypeInProc("function a: integer; forward; function a: Integer; begin Result := 5; end; procedure b; ", "a", typeId: KnownTypeIds.IntegerType);
AssertExprTypeInProc("function a: integer; forward; function a: integer; forward; function a: Integer; begin Result := 5; end; procedure b; ", "a", typeId: KnownTypeIds.IntegerType);
}
*/
/// <summary>
/// test global methods
/// </summary>
[TestMethod]
public void TestGlobalMethod() {
var f = "SimpleExpr";
var p = $"unit {f}; interface procedure a; implementation procedure a; begin WriteLn(x); end; end.";
bool v(IErrorType e) => (e.DefiningUnit.TypeRegistry.Units.Where(t => string.Equals(f, t.Name, StringComparison.OrdinalIgnoreCase)) as IUnitType)?.Symbols.Any(t => t.Name == "a") ?? false;
AssertDeclTypeDef<IErrorType>(program: p, f, NativeIntSize.Undefined, v);
}
/// <summary>
/// test global method invocation
/// </summary>
[TestMethod]
public void TestGlobalMethodInvocation() {
var p = "WriteLn('a')";
AssertStatementType(p, default, kind: SymbolTypeKind.IntrinsicRoutineResult);
}
}
}
| 55.435484 | 201 | 0.602657 | [
"Apache-2.0"
] | prjm/paspaspas | PasPasPasTests/src/Types/StructuralTests.cs | 10,313 | C# |
#pragma checksum "..\..\..\..\..\VideoInfoPanel\View\VideoInfoPanel.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "2B247A235EB67C0857E448ABA8C306D51C44366F"
//------------------------------------------------------------------------------
// <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 MaterialDesignThemes.Wpf;
using MaterialDesignThemes.Wpf.Converters;
using MaterialDesignThemes.Wpf.Transitions;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Controls.Ribbon;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace YoutubeDownloader.VideoInfoPanel.View {
/// <summary>
/// VideoInfoPanel
/// </summary>
public partial class VideoInfoPanel : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector {
#line 18 "..\..\..\..\..\VideoInfoPanel\View\VideoInfoPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label VideoTitle;
#line default
#line hidden
#line 22 "..\..\..\..\..\VideoInfoPanel\View\VideoInfoPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Image VideoThumbnail;
#line default
#line hidden
#line 39 "..\..\..\..\..\VideoInfoPanel\View\VideoInfoPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label LikesCount;
#line default
#line hidden
#line 59 "..\..\..\..\..\VideoInfoPanel\View\VideoInfoPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label DislikesCount;
#line default
#line hidden
#line 69 "..\..\..\..\..\VideoInfoPanel\View\VideoInfoPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label ViewCount;
#line default
#line hidden
#line 78 "..\..\..\..\..\VideoInfoPanel\View\VideoInfoPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label VideoAuthor;
#line default
#line hidden
#line 79 "..\..\..\..\..\VideoInfoPanel\View\VideoInfoPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label VideoPublishedDate;
#line default
#line hidden
#line 80 "..\..\..\..\..\VideoInfoPanel\View\VideoInfoPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label VideoDesciption;
#line default
#line hidden
#line 86 "..\..\..\..\..\VideoInfoPanel\View\VideoInfoPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label VideoDuration;
#line default
#line hidden
#line 87 "..\..\..\..\..\VideoInfoPanel\View\VideoInfoPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label VideoUrl;
#line default
#line hidden
#line 88 "..\..\..\..\..\VideoInfoPanel\View\VideoInfoPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label VideoExtension;
#line default
#line hidden
#line 93 "..\..\..\..\..\VideoInfoPanel\View\VideoInfoPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label VideoAvailable;
#line default
#line hidden
#line 94 "..\..\..\..\..\VideoInfoPanel\View\VideoInfoPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label SoundAvailable;
#line default
#line hidden
#line 95 "..\..\..\..\..\VideoInfoPanel\View\VideoInfoPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label MixedAvailable;
#line default
#line hidden
#line 106 "..\..\..\..\..\VideoInfoPanel\View\VideoInfoPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button DownloadButton;
#line default
#line hidden
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "5.0.4.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/YoutubeDownloader.Wpf.App;component/videoinfopanel/view/videoinfopanel.xaml", System.UriKind.Relative);
#line 1 "..\..\..\..\..\VideoInfoPanel\View\VideoInfoPanel.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "5.0.4.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
switch (connectionId)
{
case 1:
this.VideoTitle = ((System.Windows.Controls.Label)(target));
return;
case 2:
this.VideoThumbnail = ((System.Windows.Controls.Image)(target));
return;
case 3:
this.LikesCount = ((System.Windows.Controls.Label)(target));
return;
case 4:
this.DislikesCount = ((System.Windows.Controls.Label)(target));
return;
case 5:
this.ViewCount = ((System.Windows.Controls.Label)(target));
return;
case 6:
this.VideoAuthor = ((System.Windows.Controls.Label)(target));
return;
case 7:
this.VideoPublishedDate = ((System.Windows.Controls.Label)(target));
return;
case 8:
this.VideoDesciption = ((System.Windows.Controls.Label)(target));
return;
case 9:
this.VideoDuration = ((System.Windows.Controls.Label)(target));
return;
case 10:
this.VideoUrl = ((System.Windows.Controls.Label)(target));
return;
case 11:
this.VideoExtension = ((System.Windows.Controls.Label)(target));
return;
case 12:
this.VideoAvailable = ((System.Windows.Controls.Label)(target));
return;
case 13:
this.SoundAvailable = ((System.Windows.Controls.Label)(target));
return;
case 14:
this.MixedAvailable = ((System.Windows.Controls.Label)(target));
return;
case 15:
this.DownloadButton = ((System.Windows.Controls.Button)(target));
return;
}
this._contentLoaded = true;
}
}
}
| 40.639676 | 161 | 0.630504 | [
"MIT"
] | sste9512/YoutubeDownloader | YoutubeDownloader.Wpf.App/obj/Debug/net5.0-windows/VideoInfoPanel/View/VideoInfoPanel.g.cs | 10,040 | C# |
#define G_LOG
using System;
using System.Collections.Generic;
using ShipDock.Testers;
using ShipDock.Tools;
namespace ShipDock.FSM
{
/// <summary>
///
/// 有限状态机类
///
/// add by Minghua.ji
///
/// </summary>
public class StateMachine : IStateMachine
{
#region 静态属性
public const int DEFAULT_STATE = -1;
#endregion
#region 私有属性
/// <summary>当前状态的索引</summary>
private int mStateIndex;
/// <summary>状态机名</summary>
private int mFSMName;
/// <summary>下一个状态,以状态列表的顺序为依据</summary>
private IState mNext;
/// <summary>上一个状态</summary>
private IState mPrevious;
/// <summary>转换中的状态</summary>
private IState mChangingState;
/// <summary>状态切换使用的参数</summary>
private IStateParam mStateParam;
/// <summary>所有状态对象的映射</summary>
private KeyValueList<int, IState> mStates;
/// <summary>所有状态对象的列表</summary>
private List<IState> mStateList;
#endregion
#region 构造函数
public StateMachine(int name, Action<IStateMachine> fsmRegister = default)
{
FSMRegister = fsmRegister;
Init(name);
}
private void Init(int name)
{
mFSMName = name;
FSMRegister?.Invoke(this);
InitStates(ref name);
}
#endregion
#region 销毁
/// <summary>销毁</summary>
public virtual void Dispose()
{
StopStateMachine();
if (mStateList != null)
{
int max = mStateList.Count;
for (var i = 0; i < max; i++)
{
Utils.Reclaim(mStateList[i]);
}
}
Utils.Reclaim(ref mStates, true);
Utils.Reclaim(ref mStateList, true);
mNext = default;
Current = default;
mPrevious = default;
mStateParam = default;
mChangingState = default;
FSMFrameUpdater = default;
FSMRegister = default;
OnFSMChanged = default;
}
#endregion
#region 初始化
/// <summary>初始化各状态</summary>
protected virtual void InitStates(ref int name)
{
IsRun = false;
mStateIndex = 0;
mStates = new KeyValueList<int, IState>();
SubStateWillChange = int.MaxValue;
IState state;
int max = StateInfos.Length;
mStateList = new List<IState>(max);
for (int i = 0; i < max; i++)
{
state = StateInfos[i];
if(state.IsValid)
{
state.SetFSMName(name);
state.SetFSM(this);
state.StateFrameUpdater = StateFrameUpdater;
AddState(i, ref state);
AfterStateInited(ref state);
}
else
{
state.Dispose();
}
}
Array.Clear(StateInfos, 0, StateInfos.Length);
}
/// <summary>子状态初始化之后</summary>
protected virtual void AfterStateInited(ref IState state)
{
}
#endregion
#region 状态管理
/// <summary>添加状态</summary>
public void AddState(int index, ref IState info)
{
if (mStates == null)
{
return;
}
CreateStatesMap(info.StateName, info, index);
}
protected virtual IState CreateStatesMap(int name, IState state, int index = -1)
{
if (!mStates.IsContainsKey(name))
{
mStates.Put(name, state);
}
else
{
Tester.Instance.Log(TesterBaseApp.Instance, TesterBaseApp.LOG5, mFSMName.ToString());
return null;
}
if ((index == -1) || (mStateList.Count <= index))
{
mStateList.Add(state);
}
else
{
if(mStateList[index] == null)
{
mStateList[index] = state;
}
else
{
mStateList.Insert(index, state);
}
}
return state;
}
/// <summary>移除状态</summary>
public void RemoveState(int name)
{
if (mStates == default)
{
return;
}
IState state = mStates.Remove(name);
int index = mStateList.IndexOf(state);
mStateList.RemoveAt(index);
if (state == Current)
{
ChangeToDefaultState();
}
Utils.Reclaim(state);
}
protected IState GetState(int name)
{
return mStates.GetValue(name);
}
protected IState GetStateByIndex(int index)
{
return mStates.GetValueByIndex(index);
}
#endregion
#region 状态修改
/// <summary>更改至下一个状态</summary>
public void ChangeToNextState(IStateParam param = null)
{
if (Current != null)
{
if (Current.NextState == int.MaxValue)
{
mNext = mStates.GetValue(Current.NextState);
}
if ((mNext == null) && Current.IsApplyAutoNext)
{
int n = mStateIndex + 1;
mNext = (n <= (mStateList.Count - 1)) ? mStateList[n] : null;
}
if (mNext == null)
{
return;
}
}
else
{
return;
}
SetCurrentState(ref mNext, param);
}
/// <summary>更改至上一个状态</summary>
public void ChangeToPreviousState(IStateParam param = null)
{
if (mPrevious == null)
{
if ((Current != null) && (Current.PreviousState == int.MaxValue))
{
mPrevious = mStates.GetValue(Current.PreviousState);
}
else
{
mPrevious = (mStateIndex - 1 >= 0) ? mStateList[mStateIndex - 1] : null;
}
}
if (mPrevious == null)
{
return;
}
SetCurrentState(ref mPrevious, param);
}
/// <summary>更改至指定状态</summary>
public virtual void ChangeState(int name, IStateParam param = null)
{
IState state = mStates.IsContainsKey(name) ? mStates[name] : null;
SetCurrentState(ref state, param);
}
public virtual void ChangeStateByIndex(int index, IStateParam param = null)
{
IState state = GetState(index);
SetCurrentState(ref state, param);
}
/// <summary>更改至默认状态</summary>
public virtual void ChangeToDefaultState(IStateParam param = null)
{
IState defaultState = mStates.GetValue(DefaultState);
if (defaultState != null)
{
SetCurrentState(ref defaultState, param);
}
}
/// <summary>设置当前状态</summary>
private void SetCurrentState(ref IState state, IStateParam param = null)
{
if (state == default)
{
ChangeToDefaultState(param);
return;
}
if (mChangingState != state)
{
IsStateChanging = true;
mStateParam = param;
mChangingState = state;
if (IsApplyFastChange)
{
ChangedStateFinish();
}
}
else
{
if (Current != null)
{
Current.SetStateParam(param);
}
}
}
#endregion
#region 启动、停止和更新
/// <summary>运行状态机</summary>
public virtual void Run(IStateParam param = null, int initState = int.MaxValue)
{
IsRun = true;
FSMFrameUpdater?.Invoke(this, true);
if (initState != int.MaxValue)
{
ChangeState(initState, param);
}
else if (DefaultState != int.MaxValue)
{
ChangeToDefaultState(param);
}
}
/// <summary>停止状态机</summary>
public virtual void StopStateMachine()
{
IsRun = false;
FSMFrameUpdater?.Invoke(this, false);
}
/// <summary>更新当前状态</summary>
public virtual void UpdateState(int dTime)
{
#region 完成状态修改
if (!IsApplyFastChange)
{
ChangedStateFinish();
}
#endregion
//if (Current != null)
//{
// Current.UpdateState(dTime);
//}
}
private void ChangedStateFinish()
{
if (IsStateChanging)
{
IsStateChanging = false;
BeforeStateChange();
if (IsStateChanging)
{
return;//防止 DeinitState 的逻辑中存在跳转状态操作引起的参数错误
}
StateChanging();
if (IsStateChanging)
{
return;//防止多次跳转状态操作同时发生引起的参数错误
}
Tester.Instance.Log(TesterBaseApp.Instance,
TesterBaseApp.LOG4,
GetType().Name,
(mPrevious != null) ? mPrevious.StateName.ToString() : DefaultState.ToString(),
CurrentStateName.ToString());
AfterStateChanged();
}
}
private void BeforeStateChange()
{
IState state = Current;
bool isDeinitLater = IsStateDeinitLater(ref state);
if (!isDeinitLater)
{
if (Current != null)
{
Current.DeinitState();
}
}
}
private void StateChanging()
{
mPrevious = Current;
Current = mChangingState;
CurrentStateName = Current.StateName;
mStateIndex = mStateList.IndexOf(Current);
Current.InitState(mStateParam);
if (IsStateDeinitLater(ref mPrevious))
{
mPrevious.DeinitState();
}
}
private void AfterStateChanged()
{
if ((Current.SubStateCount > 0) && (SubStateWillChange != int.MaxValue))
{
Current.ChangeSubState(SubStateWillChange, SubStateParam);
}
if (OnFSMChanged != null)
{
OnFSMChanged.Invoke(this, CurrentStateName);
}
mNext = null;
mStateParam = null;
SubStateParam = null;
SubStateWillChange = int.MaxValue;
}
private bool IsStateDeinitLater(ref IState state)
{
return (state != null) && state.IsDeinitLater;
}
#endregion
#region 属性
/// <summary>状态机名</summary>
public virtual int Name
{
get
{
return mFSMName;
}
}
/// <summary>覆盖此方法,定义状态列表</summary>
public virtual IState[] StateInfos
{
get
{
return new IState[0];
}
}
/// <summary>覆盖此方法,定义默认状态名</summary>
public virtual int DefaultState
{
get
{
return DEFAULT_STATE;
}
}
public IState Previous
{
get
{
return mPrevious;
}
}
public IState Next
{
get
{
return mNext;
}
}
public int StateCount
{
get
{
return (mStates != null) ? mStates.Size : 0;
}
}
public int SubStateWillChange { get; set; }
public int CurrentStateName { get; private set; }
public bool IsRun { get; private set; }
public bool IsApplyFastChange { get; set; }
public bool IsStateChanging { get; private set; }
public Action<IStateMachine, bool> FSMFrameUpdater { get; set; }
public Action<IStateMachine> FSMRegister { get; set; }
public Action<IStateMachine, int> OnFSMChanged { get; set; }
public Action<IState, bool> StateFrameUpdater { get; set; }
public IStateParam SubStateParam { get; set; }
public IState Current { get; private set; }
#endregion
}
} | 27.505219 | 115 | 0.457154 | [
"MIT"
] | firefishes/FWGame | Assets/Scripts/ShipDock/StateMachine/StateMachine.cs | 13,697 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.